rem
stringlengths 0
477k
| add
stringlengths 0
313k
| context
stringlengths 6
599k
|
---|---|---|
window.readPedGenotypes(inputArray, 3); | window.readGenotypes(inputArray, PED); | public static void main(String[] args) { boolean nogui = false; //HaploView window; for(int i = 0;i<args.length;i++) { if(args[i].equals("-n") || args[i].equals("-h") || args[i].equals("-help")) { nogui = true; } } if(nogui) { HaploText textOnly = new HaploText(args); } else { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { } //System.setProperty("swing.disableFileChooserSpeedFix", "true"); window = new HaploView(); //setup view object window.setTitle(TITLE_STRING); window.setSize(800,600); //center the window on the screen Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); window.setLocation((screen.width - window.getWidth()) / 2, (screen.height - window.getHeight()) / 2); window.setVisible(true); //parse command line stuff for input files or prompt data dialog HaploText argParser = new HaploText(args); String[] inputArray = new String[3]; if (argParser.getHapsFileName() != ""){ inputArray[0] = argParser.getHapsFileName(); inputArray[1] = argParser.getInfoFileName(); inputArray[2] = String.valueOf(argParser.getMaxDistance()); window.readPhasedGenotypes(inputArray); }else if (argParser.getPedFileName() != ""){ inputArray[0] = argParser.getPedFileName(); inputArray[1] = argParser.getInfoFileName(); inputArray[2] = String.valueOf(argParser.getMaxDistance()); window.readPedGenotypes(inputArray, 3); }else if (argParser.getHapmapFileName() != ""){ inputArray[0] = argParser.getHapmapFileName(); inputArray[1] = ""; inputArray[2] = String.valueOf(argParser.getMaxDistance()); window.readPedGenotypes(inputArray, 4); }else{ ReadDataDialog readDialog = new ReadDataDialog("Welcome to HaploView", window); readDialog.pack(); readDialog.setVisible(true); } } } |
window.readPedGenotypes(inputArray, 4); | window.readGenotypes(inputArray, DCC); | public static void main(String[] args) { boolean nogui = false; //HaploView window; for(int i = 0;i<args.length;i++) { if(args[i].equals("-n") || args[i].equals("-h") || args[i].equals("-help")) { nogui = true; } } if(nogui) { HaploText textOnly = new HaploText(args); } else { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { } //System.setProperty("swing.disableFileChooserSpeedFix", "true"); window = new HaploView(); //setup view object window.setTitle(TITLE_STRING); window.setSize(800,600); //center the window on the screen Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); window.setLocation((screen.width - window.getWidth()) / 2, (screen.height - window.getHeight()) / 2); window.setVisible(true); //parse command line stuff for input files or prompt data dialog HaploText argParser = new HaploText(args); String[] inputArray = new String[3]; if (argParser.getHapsFileName() != ""){ inputArray[0] = argParser.getHapsFileName(); inputArray[1] = argParser.getInfoFileName(); inputArray[2] = String.valueOf(argParser.getMaxDistance()); window.readPhasedGenotypes(inputArray); }else if (argParser.getPedFileName() != ""){ inputArray[0] = argParser.getPedFileName(); inputArray[1] = argParser.getInfoFileName(); inputArray[2] = String.valueOf(argParser.getMaxDistance()); window.readPedGenotypes(inputArray, 3); }else if (argParser.getHapmapFileName() != ""){ inputArray[0] = argParser.getHapmapFileName(); inputArray[1] = ""; inputArray[2] = String.valueOf(argParser.getMaxDistance()); window.readPedGenotypes(inputArray, 4); }else{ ReadDataDialog readDialog = new ReadDataDialog("Welcome to HaploView", window); readDialog.pack(); readDialog.setVisible(true); } } } |
theData.infoKnown = false; File markerFile; if (inputOptions[1].equals("")){ markerFile = null; }else{ markerFile = new File(inputOptions[1]); } readMarkers(markerFile, hminfo); | public Object construct(){ dPrimeDisplay=null; theData.infoKnown = false; File markerFile; if (inputOptions[1].equals("")){ markerFile = null; }else{ markerFile = new File(inputOptions[1]); } readMarkers(markerFile, hminfo); changeKey(1); theData.generateDPrimeTable(); //theData.guessBlocks(BLOX_GABRIEL); theData.guessBlocks(BLOX_NONE); //for debugging, doesn't call blocks at first colorMenuItems[0].setSelected(true); blockMenuItems[0].setSelected(true); zoomMenuItems[0].setSelected(true); theData.blocksChanged = false; Container contents = getContentPane(); contents.removeAll(); int currentTab = VIEW_D_NUM; /*if (!(tabs == null)){ currentTab = tabs.getSelectedIndex(); } */ tabs = new JTabbedPane(); tabs.addChangeListener(new TabChangeListener()); //first, draw the D' picture JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); dPrimeDisplay = new DPrimeDisplay(window); JScrollPane dPrimeScroller = new JScrollPane(dPrimeDisplay); dPrimeScroller.getViewport().setScrollMode(JViewport.BLIT_SCROLL_MODE); dPrimeScroller.getVerticalScrollBar().setUnitIncrement(60); dPrimeScroller.getHorizontalScrollBar().setUnitIncrement(60); panel.add(dPrimeScroller); tabs.addTab(viewItems[VIEW_D_NUM], panel); viewMenuItems[VIEW_D_NUM].setEnabled(true); //compute and show haps on next tab panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); try { hapDisplay = new HaplotypeDisplay(theData); } catch(HaploViewException e) { JOptionPane.showMessageDialog(window, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } HaplotypeDisplayController hdc = new HaplotypeDisplayController(hapDisplay); hapScroller = new JScrollPane(hapDisplay); hapScroller.getVerticalScrollBar().setUnitIncrement(60); hapScroller.getHorizontalScrollBar().setUnitIncrement(60); panel.add(hapScroller); panel.add(hdc); tabs.addTab(viewItems[VIEW_HAP_NUM], panel); viewMenuItems[VIEW_HAP_NUM].setEnabled(true); //LOD panel /*panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); LODDisplay ld = new LODDisplay(theData); JScrollPane lodScroller = new JScrollPane(ld); panel.add(lodScroller); tabs.addTab(viewItems[VIEW_LOD_NUM], panel); viewMenuItems[VIEW_LOD_NUM].setEnabled(true);*/ //int optionalTabCount = 1; //check data panel if (checkPanel != null){ //optionalTabCount++; //VIEW_CHECK_NUM = optionalTabCount; //viewItems[VIEW_CHECK_NUM] = VIEW_CHECK_PANEL; JPanel metaCheckPanel = new JPanel(); metaCheckPanel.setLayout(new BoxLayout(metaCheckPanel, BoxLayout.Y_AXIS)); JLabel countsLabel = new JLabel("Using " + theData.numSingletons + " singletons and " + theData.numTrios + " trios from " + theData.numPeds + " families."); if (theData.numTrios + theData.numSingletons == 0){ countsLabel.setForeground(Color.red); } countsLabel.setAlignmentX(Component.CENTER_ALIGNMENT); metaCheckPanel.add(countsLabel); metaCheckPanel.add(checkPanel); cdc = new CheckDataController(window); metaCheckPanel.add(cdc); tabs.addTab(viewItems[VIEW_CHECK_NUM], metaCheckPanel); viewMenuItems[VIEW_CHECK_NUM].setEnabled(true); currentTab=VIEW_CHECK_NUM; } //TDT panel if(assocTest > 0) { //optionalTabCount++; //VIEW_TDT_NUM = optionalTabCount; //viewItems[VIEW_TDT_NUM] = VIEW_TDT; tdtPanel = new TDTPanel(theData.chromosomes, assocTest); tabs.addTab(viewItems[VIEW_TDT_NUM], tdtPanel); viewMenuItems[VIEW_TDT_NUM].setEnabled(true); } tabs.setSelectedIndex(currentTab); contents.add(tabs); repaint(); setVisible(true); theData.finished = true; setTitle(TITLE_STRING + " -- " + inputOptions[0]); return null; } |
|
setTitle(TITLE_STRING + " -- " + inputOptions[0]); | setTitle(TITLE_STRING + " -- " + inFile.getName()); | public Object construct(){ dPrimeDisplay=null; theData.infoKnown = false; File markerFile; if (inputOptions[1].equals("")){ markerFile = null; }else{ markerFile = new File(inputOptions[1]); } readMarkers(markerFile, hminfo); changeKey(1); theData.generateDPrimeTable(); //theData.guessBlocks(BLOX_GABRIEL); theData.guessBlocks(BLOX_NONE); //for debugging, doesn't call blocks at first colorMenuItems[0].setSelected(true); blockMenuItems[0].setSelected(true); zoomMenuItems[0].setSelected(true); theData.blocksChanged = false; Container contents = getContentPane(); contents.removeAll(); int currentTab = VIEW_D_NUM; /*if (!(tabs == null)){ currentTab = tabs.getSelectedIndex(); } */ tabs = new JTabbedPane(); tabs.addChangeListener(new TabChangeListener()); //first, draw the D' picture JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); dPrimeDisplay = new DPrimeDisplay(window); JScrollPane dPrimeScroller = new JScrollPane(dPrimeDisplay); dPrimeScroller.getViewport().setScrollMode(JViewport.BLIT_SCROLL_MODE); dPrimeScroller.getVerticalScrollBar().setUnitIncrement(60); dPrimeScroller.getHorizontalScrollBar().setUnitIncrement(60); panel.add(dPrimeScroller); tabs.addTab(viewItems[VIEW_D_NUM], panel); viewMenuItems[VIEW_D_NUM].setEnabled(true); //compute and show haps on next tab panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); try { hapDisplay = new HaplotypeDisplay(theData); } catch(HaploViewException e) { JOptionPane.showMessageDialog(window, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } HaplotypeDisplayController hdc = new HaplotypeDisplayController(hapDisplay); hapScroller = new JScrollPane(hapDisplay); hapScroller.getVerticalScrollBar().setUnitIncrement(60); hapScroller.getHorizontalScrollBar().setUnitIncrement(60); panel.add(hapScroller); panel.add(hdc); tabs.addTab(viewItems[VIEW_HAP_NUM], panel); viewMenuItems[VIEW_HAP_NUM].setEnabled(true); //LOD panel /*panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); LODDisplay ld = new LODDisplay(theData); JScrollPane lodScroller = new JScrollPane(ld); panel.add(lodScroller); tabs.addTab(viewItems[VIEW_LOD_NUM], panel); viewMenuItems[VIEW_LOD_NUM].setEnabled(true);*/ //int optionalTabCount = 1; //check data panel if (checkPanel != null){ //optionalTabCount++; //VIEW_CHECK_NUM = optionalTabCount; //viewItems[VIEW_CHECK_NUM] = VIEW_CHECK_PANEL; JPanel metaCheckPanel = new JPanel(); metaCheckPanel.setLayout(new BoxLayout(metaCheckPanel, BoxLayout.Y_AXIS)); JLabel countsLabel = new JLabel("Using " + theData.numSingletons + " singletons and " + theData.numTrios + " trios from " + theData.numPeds + " families."); if (theData.numTrios + theData.numSingletons == 0){ countsLabel.setForeground(Color.red); } countsLabel.setAlignmentX(Component.CENTER_ALIGNMENT); metaCheckPanel.add(countsLabel); metaCheckPanel.add(checkPanel); cdc = new CheckDataController(window); metaCheckPanel.add(cdc); tabs.addTab(viewItems[VIEW_CHECK_NUM], metaCheckPanel); viewMenuItems[VIEW_CHECK_NUM].setEnabled(true); currentTab=VIEW_CHECK_NUM; } //TDT panel if(assocTest > 0) { //optionalTabCount++; //VIEW_TDT_NUM = optionalTabCount; //viewItems[VIEW_TDT_NUM] = VIEW_TDT; tdtPanel = new TDTPanel(theData.chromosomes, assocTest); tabs.addTab(viewItems[VIEW_TDT_NUM], tdtPanel); viewMenuItems[VIEW_TDT_NUM].setEnabled(true); } tabs.setSelectedIndex(currentTab); contents.add(tabs); repaint(); setVisible(true); theData.finished = true; setTitle(TITLE_STRING + " -- " + inputOptions[0]); return null; } |
checkPanel.refreshNames(); | checkPanel = new CheckDataPanel(theData); Container checkTab = (Container)tabs.getComponentAt(VIEW_CHECK_NUM); checkTab.removeAll(); JPanel metaCheckPanel = new JPanel(); metaCheckPanel.setLayout(new BoxLayout(metaCheckPanel, BoxLayout.Y_AXIS)); JLabel countsLabel = new JLabel("Using " + theData.numSingletons + " singletons and " + theData.numTrios + " trios from " + theData.numPeds + " families."); if (theData.numTrios + theData.numSingletons == 0){ countsLabel.setForeground(Color.red); } countsLabel.setAlignmentX(Component.CENTER_ALIGNMENT); metaCheckPanel.add(countsLabel); metaCheckPanel.add(checkPanel); cdc = new CheckDataController(window); metaCheckPanel.add(cdc); checkTab.add(metaCheckPanel); repaint(); | void readMarkers(File inputFile, String[][] hminfo){ try { theData.prepareMarkerInput(inputFile,maxCompDist,hminfo); if (checkPanel != null){ checkPanel.refreshNames(); } if (tdtPanel != null){ tdtPanel.refreshNames(); } }catch (HaploViewException e){ JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); }catch (IOException ioexec){ JOptionPane.showMessageDialog(this, ioexec.getMessage(), "File Error", JOptionPane.ERROR_MESSAGE); } if (dPrimeDisplay != null && tabs.getSelectedIndex() == VIEW_D_NUM){ dPrimeDisplay.refresh(); } } |
}catch (PedFileException pfe){ | void readMarkers(File inputFile, String[][] hminfo){ try { theData.prepareMarkerInput(inputFile,maxCompDist,hminfo); if (checkPanel != null){ checkPanel.refreshNames(); } if (tdtPanel != null){ tdtPanel.refreshNames(); } }catch (HaploViewException e){ JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); }catch (IOException ioexec){ JOptionPane.showMessageDialog(this, ioexec.getMessage(), "File Error", JOptionPane.ERROR_MESSAGE); } if (dPrimeDisplay != null && tabs.getSelectedIndex() == VIEW_D_NUM){ dPrimeDisplay.refresh(); } } |
|
if(haps == null) { return ; } | public void makeTable(Haplotype[][] haps) { this.removeAll(); initialHaplotypeDisplayThreshold = Options.getHaplotypeDisplayThreshold(); Vector colNames = new Vector(); colNames.add("Haplotype"); colNames.add("Freq."); if (Options.getAssocTest() == ASSOC_TRIO){ colNames.add("T:U"); }else{ colNames.add("Case, Control Ratios"); } colNames.add("Chi Square"); colNames.add("p value"); HaplotypeAssociationNode root = new HaplotypeAssociationNode("Haplotype Associations"); String[] alleleCodes = new String[5]; alleleCodes[0] = "X"; alleleCodes[1] = "A"; alleleCodes[2] = "C"; alleleCodes[3] = "G"; alleleCodes[4] = "T"; for(int i=0;i< haps.length;i++){ Haplotype[] curBlock = haps[i]; HaplotypeAssociationNode han = new HaplotypeAssociationNode("Block " + (i+1)); double chisq; for(int j=0;j< curBlock.length; j++) { if (curBlock[j].getPercentage()*100 >= Options.getHaplotypeDisplayThreshold()){ int[] genotypes = curBlock[j].getGeno(); StringBuffer curHap = new StringBuffer(genotypes.length); for(int k=0;k<genotypes.length;k++) { curHap.append(alleleCodes[genotypes[k]]); } double[][] counts; if(Options.getAssocTest() == ASSOC_TRIO) { counts = new double[1][2]; counts[0][0] = curBlock[j].getTransCount(); counts[0][1] = curBlock[j].getUntransCount(); } else { counts = new double[2][2]; counts[0][0] = curBlock[j].getCaseFreq(); counts[1][0] = curBlock[j].getControlFreq(); double caseSum=0; double controlSum=0; for (int k=0; k < curBlock.length; k++){ if (j!=k){ caseSum += curBlock[k].getCaseFreq(); controlSum += curBlock[k].getControlFreq(); } } counts[0][1] = caseSum; counts[1][1] = controlSum; } chisq = getChiSq(counts); han.add(new HaplotypeAssociationNode(curHap.toString(),curBlock[j].getPercentage(),counts,chisq,getPValue(chisq))); } } root.add(han); } int countsOrRatios = SHOW_HAP_COUNTS; if(jtt != null) { //if were just updating the table, then we want to retain the current status of countsOrRatios HaplotypeAssociationModel ham = (HaplotypeAssociationModel) jtt.getTree().getModel(); countsOrRatios = ham.getCountsOrRatios(); } jtt = new JTreeTable(new HaplotypeAssociationModel(colNames, root)); ((HaplotypeAssociationModel)(jtt.getTree().getModel())).setCountsOrRatios(countsOrRatios); jtt.getColumnModel().getColumn(0).setPreferredWidth(200); jtt.getColumnModel().getColumn(1).setPreferredWidth(50); //we need more space for the CC counts in the third column if(Options.getAssocTest() == ASSOC_CC) { jtt.getColumnModel().getColumn(2).setPreferredWidth(200); jtt.getColumnModel().getColumn(3).setPreferredWidth(75); jtt.getColumnModel().getColumn(4).setPreferredWidth(75); } else { jtt.getColumnModel().getColumn(2).setPreferredWidth(150); jtt.getColumnModel().getColumn(3).setPreferredWidth(100); jtt.getColumnModel().getColumn(4).setPreferredWidth(100); } jtt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); Font monoFont = new Font("Monospaced",Font.PLAIN,12); jtt.setFont(monoFont); JTree theTree = jtt.getTree(); theTree.setFont(monoFont); DefaultTreeCellRenderer r = new DefaultTreeCellRenderer(); r.setLeafIcon(null); r.setOpenIcon(null); r.setClosedIcon(null); theTree.setCellRenderer(r); jtt.setPreferredScrollableViewportSize(new Dimension(600,jtt.getPreferredScrollableViewportSize().height)); JScrollPane treeScroller = new JScrollPane(jtt); treeScroller.setMaximumSize(treeScroller.getPreferredSize()); add(treeScroller); if(Options.getAssocTest() == ASSOC_CC) { JRadioButton countsButton = new JRadioButton("Show CC counts"); JRadioButton ratiosButton = new JRadioButton("Show CC frequencies"); ButtonGroup bg = new ButtonGroup(); bg.add(countsButton); bg.add(ratiosButton); countsButton.addActionListener(this); ratiosButton.addActionListener(this); JPanel butPan = new JPanel(); butPan.add(countsButton); butPan.add(ratiosButton); add(butPan); if(countsOrRatios == SHOW_HAP_RATIOS) { ratiosButton.setSelected(true); }else{ countsButton.setSelected(true); } } } |
|
public static double gammq (double a, double x) throws CheckDataException { | public static double gammq (double a, double x) { | public static double gammq (double a, double x) throws CheckDataException { double gamser, gammcf; //, gln; if ((x < 0.0 )|| (a <= 0.0 )) throw new CheckDataException("Invalid arguments in routine gammq" ); if (x < (a + 1.0) ) { gamser = gser(a , x); return (1.0 - gamser) ; } else { gammcf = gcf (a , x); return gammcf ; } } |
if ((x < 0.0 )|| (a <= 0.0 )) throw new CheckDataException("Invalid arguments in routine gammq" ); | try{ | public static double gammq (double a, double x) throws CheckDataException { double gamser, gammcf; //, gln; if ((x < 0.0 )|| (a <= 0.0 )) throw new CheckDataException("Invalid arguments in routine gammq" ); if (x < (a + 1.0) ) { gamser = gser(a , x); return (1.0 - gamser) ; } else { gammcf = gcf (a , x); return gammcf ; } } |
}catch (CheckDataException e){ return 0; } | public static double gammq (double a, double x) throws CheckDataException { double gamser, gammcf; //, gln; if ((x < 0.0 )|| (a <= 0.0 )) throw new CheckDataException("Invalid arguments in routine gammq" ); if (x < (a + 1.0) ) { gamser = gser(a , x); return (1.0 - gamser) ; } else { gammcf = gcf (a , x); return gammcf ; } } |
|
this.pval = ""; | this.pval = new Double(0); | public HaplotypeAssociationNode(String name) { this.name = name; this.freq = ""; this.chisq = -1; this.pval = ""; } |
if (c.isNullable()) { | if (c.isDefinitelyNullable()) { | public void writeTable(SQLTable t) throws SQLException, ArchitectException { Map colNameMap = new HashMap(); // for detecting duplicate column names String origTableName = t.getName(); if (topLevelNames.get(t.getName()) != null) { int i = 1; String newName = origTableName+"_"+i; while (topLevelNames.get(newName) != null) { i++; newName = origTableName+"_"+i; } t.setTableName(newName); warnings.add(new NameChangeWarning(t, "Duplicate Table Name", origTableName)); } topLevelNames.put(t.getName(), t); print("\nCREATE TABLE "); printIdentifier(t.getName()); println(" ("); boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn c = (SQLColumn) it.next(); String origName = c.getName(); if (colNameMap.get(origName) != null) { int i = 1; String newName = origName+"_"+i; while (colNameMap.get(newName) != null) { i++; newName = origName+"_"+i; } c.setColumnName(newName); warnings.add(new NameChangeWarning(c, "Duplicate Col Name", origName)); } colNameMap.put(c.getName(), c); GenericTypeDescriptor td = (GenericTypeDescriptor) typeMap.get(new Integer(c.getType())); if (td == null) { td = (GenericTypeDescriptor) typeMap.get(new Integer(Types.VARCHAR)); //better be non-null! GenericTypeDescriptor oldType = new GenericTypeDescriptor (c.getSourceDBTypeName(), c.getType(), c.getPrecision(), null, null, c.getNullable(), false, false); oldType.determineScaleAndPrecision(); warnings.add(new TypeMapWarning(c, "Unknown Target Type", oldType, td)); } if (!firstCol) println(","); print(" "); printIdentifier(c.getName()); print(" "); print(td.getName()); if (td.getHasScale()) { print("("+c.getScale()); if (td.getHasPrecision()) { print(","+c.getPrecision()); } print(")"); } if (c.isNullable()) { if (! td.isNullable()) { throw new UnsupportedOperationException ("The data type "+td.getName()+" is not nullable on the target database platform."); } print(" NULL"); } else { print(" NOT NULL"); } // XXX: default values handled only in ETL? firstCol = false; } println(""); print(")"); endStatement(); println(""); } |
if ( ! ( parentObject instanceof Task ) && project.getTaskDefinitions().containsKey( tagName ) ) { | if (findParentTaskSource() == null && project.getTaskDefinitions().containsKey( tagName )) { | public void doTag(XMLOutput output) throws Exception { Project project = getAntProject(); String tagName = getTagName(); Object parentObject = findBeanAncestor(); // lets assume that Task instances are not nested inside other Task instances // for example <manifest> inside a <jar> should be a nested object, where as // if the parent is not a Task the <manifest> should create a ManifestTask if ( ! ( parentObject instanceof Task ) && project.getTaskDefinitions().containsKey( tagName ) ) { if ( log.isDebugEnabled() ) { log.debug( "Creating an ant Task for name: " + tagName ); } // the following algorithm follows the lifetime of a tag // http://jakarta.apache.org/ant/manual/develop.html#writingowntask // kindly recommended by Stefan Bodewig // create and set its project reference task = createTask( tagName ); if ( task instanceof TaskAdapter ) { setObject( ((TaskAdapter)task).getProxy() ); } else { setObject( task ); } // set the task ID if one is given Object id = getAttributes().remove( "id" ); if ( id != null ) { project.addReference( (String) id, task ); } // ### we might want to spoof a Target setting here // now lets initialize task.init(); // now lets invoke the body to call all the createXXX() or addXXX() methods String body = getBodyText(); // now lets set any attributes of this tag... setBeanProperties(); // now lets set the addText() of the body content, if its applicaable Method method = MethodUtils.getAccessibleMethod( task.getClass(), "addText", addTaskParamTypes ); if (method != null) { Object[] args = { body }; method.invoke(this.task, args); } // now lets set all the attributes of the child elements // XXXX: to do! // now we're ready to invoke the task // XXX: should we call execute() or perform()? task.perform(); } else { if ( log.isDebugEnabled() ) { log.debug( "Creating a nested object name: " + tagName ); } Object nested = createNestedObject( parentObject, tagName ); if ( nested == null ) { nested = createDataType( tagName ); } if ( nested != null ) { setObject( nested ); // set the task ID if one is given Object id = getAttributes().remove( "id" ); if ( id != null ) { project.addReference( (String) id, nested ); } try{ PropertyUtils.setProperty( nested, "name", tagName ); } catch (Exception e) { } // now lets invoke the body String body = getBodyText(); // now lets set any attributes of this tag... setBeanProperties(); // now lets add it to its parent if ( parentObject != null ) { IntrospectionHelper ih = IntrospectionHelper.getHelper( parentObject.getClass() ); try { if (log.isDebugEnabled()) { log.debug("About to set the: " + tagName + " property on: " + parentObject + " to value: " + nested + " with type: " + nested.getClass() ); } ih.storeElement( project, parentObject, nested, tagName ); } catch (Exception e) { log.warn( "Caught exception setting nested: " + tagName, e ); } // now try to set the property for good measure // as the storeElement() method does not // seem to call any setter methods of non-String types try { BeanUtils.setProperty( parentObject, tagName, nested ); } catch (Exception e) { log.debug("Caught exception trying to set property: " + tagName + " on: " + parentObject); } } } else { // lets treat this tag as static XML... StaticTag tag = new StaticTag("", tagName, tagName); tag.setParent( getParent() ); tag.setBody( getBody() ); tag.setContext(context); for (Iterator iter = getAttributes().entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String name = (String) entry.getKey(); Object value = entry.getValue(); tag.setAttribute(name, value); } tag.doTag(output); } } } |
hasIDAttribute = true; | public void doTag(XMLOutput output) throws Exception { Project project = getAntProject(); String tagName = getTagName(); Object parentObject = findBeanAncestor(); // lets assume that Task instances are not nested inside other Task instances // for example <manifest> inside a <jar> should be a nested object, where as // if the parent is not a Task the <manifest> should create a ManifestTask if ( ! ( parentObject instanceof Task ) && project.getTaskDefinitions().containsKey( tagName ) ) { if ( log.isDebugEnabled() ) { log.debug( "Creating an ant Task for name: " + tagName ); } // the following algorithm follows the lifetime of a tag // http://jakarta.apache.org/ant/manual/develop.html#writingowntask // kindly recommended by Stefan Bodewig // create and set its project reference task = createTask( tagName ); if ( task instanceof TaskAdapter ) { setObject( ((TaskAdapter)task).getProxy() ); } else { setObject( task ); } // set the task ID if one is given Object id = getAttributes().remove( "id" ); if ( id != null ) { project.addReference( (String) id, task ); } // ### we might want to spoof a Target setting here // now lets initialize task.init(); // now lets invoke the body to call all the createXXX() or addXXX() methods String body = getBodyText(); // now lets set any attributes of this tag... setBeanProperties(); // now lets set the addText() of the body content, if its applicaable Method method = MethodUtils.getAccessibleMethod( task.getClass(), "addText", addTaskParamTypes ); if (method != null) { Object[] args = { body }; method.invoke(this.task, args); } // now lets set all the attributes of the child elements // XXXX: to do! // now we're ready to invoke the task // XXX: should we call execute() or perform()? task.perform(); } else { if ( log.isDebugEnabled() ) { log.debug( "Creating a nested object name: " + tagName ); } Object nested = createNestedObject( parentObject, tagName ); if ( nested == null ) { nested = createDataType( tagName ); } if ( nested != null ) { setObject( nested ); // set the task ID if one is given Object id = getAttributes().remove( "id" ); if ( id != null ) { project.addReference( (String) id, nested ); } try{ PropertyUtils.setProperty( nested, "name", tagName ); } catch (Exception e) { } // now lets invoke the body String body = getBodyText(); // now lets set any attributes of this tag... setBeanProperties(); // now lets add it to its parent if ( parentObject != null ) { IntrospectionHelper ih = IntrospectionHelper.getHelper( parentObject.getClass() ); try { if (log.isDebugEnabled()) { log.debug("About to set the: " + tagName + " property on: " + parentObject + " to value: " + nested + " with type: " + nested.getClass() ); } ih.storeElement( project, parentObject, nested, tagName ); } catch (Exception e) { log.warn( "Caught exception setting nested: " + tagName, e ); } // now try to set the property for good measure // as the storeElement() method does not // seem to call any setter methods of non-String types try { BeanUtils.setProperty( parentObject, tagName, nested ); } catch (Exception e) { log.debug("Caught exception trying to set property: " + tagName + " on: " + parentObject); } } } else { // lets treat this tag as static XML... StaticTag tag = new StaticTag("", tagName, tagName); tag.setParent( getParent() ); tag.setBody( getBody() ); tag.setContext(context); for (Iterator iter = getAttributes().entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String name = (String) entry.getKey(); Object value = entry.getValue(); tag.setAttribute(name, value); } tag.doTag(output); } } } |
|
window.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); | public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command.equals(READ_GENOTYPES)){ ReadDataDialog readDialog = new ReadDataDialog("Open new data", this); readDialog.pack(); readDialog.setVisible(true); } else if (command.equals(READ_MARKERS)){ //JFileChooser fc = new JFileChooser(System.getProperty("user.dir")); fc.setSelectedFile(new File("")); int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { readMarkers(fc.getSelectedFile(),null); } }else if (command.equals(READ_ANALYSIS_TRACK)){ fc.setSelectedFile(new File("")); int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION){ readAnalysisFile(fc.getSelectedFile()); } }else if (command.equals(DOWNLOAD_GBROWSE)){ GBrowseDialog gbd = new GBrowseDialog(this, "Connect to HapMap Info Server"); gbd.pack(); gbd.setVisible(true); }else if (command.equals(READ_BLOCKS_FILE)){ fc.setSelectedFile(new File("")); if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION){ readBlocksFile(fc.getSelectedFile()); } }else if (command.equals(CUST_BLOCKS)){ TweakBlockDefsDialog tweakDialog = new TweakBlockDefsDialog("Customize Blocks", this); tweakDialog.pack(); tweakDialog.setVisible(true); }else if (command.equals(CLEAR_BLOCKS)){ changeBlocks(BLOX_NONE); //blockdef clauses }else if (command.startsWith("block")){ int method = Integer.valueOf(command.substring(5)).intValue(); changeBlocks(method); /*for (int i = 1; i < colorMenuItems.length; i++){ if (method+1 == i){ colorMenuItems[i].setEnabled(true); }else{ colorMenuItems[i].setEnabled(false); } } colorMenuItems[0].setSelected(true);*/ //zooming clauses }else if (command.startsWith("zoom")){ dPrimeDisplay.zoom(Integer.valueOf(command.substring(4)).intValue()); //coloring clauses }else if (command.startsWith("color")){ Options.setLDColorScheme(Integer.valueOf(command.substring(5)).intValue()); dPrimeDisplay.colorDPrime(); changeKey(); //exporting clauses }else if (command.equals(EXPORT_PNG)){ export(tabs.getSelectedIndex(), PNG_MODE, 0, Chromosome.getSize()); }else if (command.equals(EXPORT_TEXT)){ export(tabs.getSelectedIndex(), TXT_MODE, 0, Chromosome.getSize()); }else if (command.equals(EXPORT_OPTIONS)){ ExportDialog exDialog = new ExportDialog(this); exDialog.pack(); exDialog.setVisible(true); }else if (command.equals("Select All")){ checkPanel.selectAll(); }else if (command.equals("Rescore Markers")){ String cut = cdc.hwcut.getText(); if (cut.equals("")){ cut = "0"; } CheckData.hwCut = Double.parseDouble(cut); cut = cdc.genocut.getText(); if (cut.equals("")){ cut="0"; } CheckData.failedGenoCut = Integer.parseInt(cut); cut = cdc.mendcut.getText(); if (cut.equals("")){ cut="0"; } CheckData.numMendErrCut = Integer.parseInt(cut); cut = cdc.mafcut.getText(); if (cut.equals("")){ cut="0"; } CheckData.mafCut = Double.parseDouble(cut); checkPanel.redoRatings(); JTable jt = checkPanel.getTable(); jt.repaint(); }else if (command.equals("LD Display Spacing")){ ProportionalSpacingDialog spaceDialog = new ProportionalSpacingDialog(this, "Adjust LD Spacing"); spaceDialog.pack(); spaceDialog.setVisible(true); }else if (command.equals("Tutorial")){ showHelp(); } else if(command.equals("Check for update")) { final SwingWorker worker = new SwingWorker(){ UpdateChecker uc; public Object construct() { uc = new UpdateChecker(); uc.checkForUpdate(); return null; } public void finished() { if(uc != null) { if(uc.isNewVersionAvailable()) { UpdateDisplayDialog udp = new UpdateDisplayDialog(window,"Update Check",uc); udp.pack(); udp.setVisible(true); } else { JOptionPane.showMessageDialog(window, "Your version of Haploview is up to date.", "Update Check", JOptionPane.INFORMATION_MESSAGE); } } window.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } }; setCursor(new Cursor(Cursor.WAIT_CURSOR)); worker.start(); }else if (command.equals("Quit")){ quit(); } else { for (int i = 0; i < viewItems.length; i++) { if (command.equals(viewItems[i])) tabs.setSelectedIndex(i); } } } |
|
window.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); | public void finished() { if(uc != null) { if(uc.isNewVersionAvailable()) { UpdateDisplayDialog udp = new UpdateDisplayDialog(window,"Update Check",uc); udp.pack(); udp.setVisible(true); } else { JOptionPane.showMessageDialog(window, "Your version of Haploview is up to date.", "Update Check", JOptionPane.INFORMATION_MESSAGE); } } window.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } |
|
dbcs = new DBConnectionSpec(); dbcsPanel.applyChanges(dbcs); historyBox.addItem(ASUtils.lvb(dbcs.getDisplayName(), dbcs)); | dbcsPanel.applyChanges(); DBConnectionSpec dbcs = dbcsPanel.getDbcs(); connectionsBox.addItem(ASUtils.lvb(dbcs.getDisplayName(), dbcs)); ArchitectFrame.getMainInstance().getUserSettings().getConnections().add(dbcs); | public void actionPerformed(ActionEvent e) { final JDialog d = new JDialog(ArchitectFrame.getMainInstance(), "New PL Repository Connection"); JPanel plr = new JPanel(new BorderLayout(12,12)); plr.setBorder(BorderFactory.createEmptyBorder(12,12,12,12)); final DBCSPanel dbcsPanel = new DBCSPanel(); plr.add(dbcsPanel, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JButton okButton = new JButton("Ok"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { dbcs = new DBConnectionSpec(); dbcsPanel.applyChanges(dbcs); historyBox.addItem(ASUtils.lvb(dbcs.getDisplayName(), dbcs)); d.setVisible(false); } }); buttonPanel.add(okButton); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { dbcsPanel.discardChanges(); d.setVisible(false); } }); buttonPanel.add(cancelButton); plr.add(buttonPanel, BorderLayout.SOUTH); d.setContentPane(plr); d.pack(); d.setVisible(true); } |
dbcs = new DBConnectionSpec(); dbcsPanel.applyChanges(dbcs); historyBox.addItem(ASUtils.lvb(dbcs.getDisplayName(), dbcs)); | dbcsPanel.applyChanges(); DBConnectionSpec dbcs = dbcsPanel.getDbcs(); connectionsBox.addItem(ASUtils.lvb(dbcs.getDisplayName(), dbcs)); ArchitectFrame.getMainInstance().getUserSettings().getConnections().add(dbcs); | public void actionPerformed(ActionEvent evt) { dbcs = new DBConnectionSpec(); dbcsPanel.applyChanges(dbcs); historyBox.addItem(ASUtils.lvb(dbcs.getDisplayName(), dbcs)); d.setVisible(false); } |
public Tag getTag() { | public Tag getTag() throws Exception { Tag tag = (Tag) tagHolder.get(); if ( tag == null ) { tag = createTag(); if ( tag != null ) { configureTag(tag); tagHolder.set(tag); } } | public Tag getTag() { return tag; } |
public static TagScript newInstance(Tag tag) { if (tag instanceof DynaTag) { return new DynaTagScript((DynaTag) tag); | public static TagScript newInstance(Class tagClass) { TagFactory factory = new DefaultTagFactory(tagClass); if ( DynaTag.class.isAssignableFrom(tagClass) ) { return new DynaTagScript(factory); | public static TagScript newInstance(Tag tag) { if (tag instanceof DynaTag) { return new DynaTagScript((DynaTag) tag); } return new BeanTagScript(tag); } |
return new BeanTagScript(tag); | return new BeanTagScript(factory); | public static TagScript newInstance(Tag tag) { if (tag instanceof DynaTag) { return new DynaTagScript((DynaTag) tag); } return new BeanTagScript(tag); } |
if ( ! (namespacesMap instanceof Hashtable) ) { namespacesMap = new Hashtable( namespacesMap ); } | public void setNamespacesMap(Map namespacesMap) { this.namespacesMap = namespacesMap; } |
|
return super.toString() + "[tag=" + tag + "]"; | return super.toString() + "[tag=" + elementName + ";at=" + lineNumber + ":" + columnNumber + "]"; | public String toString() { return super.toString() + "[tag=" + tag + "]"; } |
public BeanTagScript(Tag tag) { super(tag); | public BeanTagScript() { | public BeanTagScript(Tag tag) { super(tag); } |
getBody().run( context, output); | invokeBody( output); | public void doTag(final XMLOutput output) throws Exception { getGoal(getName()).addPreGoalCallback( new PreGoalCallback() { public void firePreGoal(Goal goal) throws Exception { // lets run the body log.debug( "Running pre goal: " + getName() ); getBody().run( context, output); } } ); } |
getBody().run( context, output); | invokeBody( output); | public void firePreGoal(Goal goal) throws Exception { // lets run the body log.debug( "Running pre goal: " + getName() ); getBody().run( context, output); } |
} Vector unsortedRes = pedFile.getResults(); Vector sortedRes = new Vector(); for (int i = 0; i < realPos.length; i++){ sortedRes.add(unsortedRes.elementAt(realPos[i])); } pedFile.setResults(sortedRes); Vector o = pedFile.getOrder(); for (int i = 0; i < o.size(); i++){ Individual ind = (Individual) o.get(i); Vector unsortedMarkers = ind.getMarkers(); Vector sortedMarkers = new Vector(); for (int j = 0; j < unsortedMarkers.size(); j++){ sortedMarkers.add(unsortedMarkers.elementAt(realPos[j])); } ind.setMarkers(sortedMarkers); | void prepareMarkerInput(File infile, String[][] hapmapGoodies) throws IOException, HaploViewException{ //this method is called to gather data about the markers used. //It is assumed that the input file is two columns, the first being //the name and the second the absolute position. the maxdist is //used to determine beyond what distance comparisons will not be //made. if the infile param is null, loads up "dummy info" for //situation where no info file exists //An optional third column is supported which is designed to hold //association study data. If there is a third column there will be //a visual indicator in the D' display that there is additional data //and the detailed data can be viewed with a mouse press. Vector names = new Vector(); Vector positions = new Vector(); Vector extras = new Vector(); dupsToBeFlagged = false; try{ if (infile != null){ if (infile.length() < 1){ throw new HaploViewException("Info file is empty or does not exist: " + infile.getName()); } String currentLine; long prevloc = -1000000000; //read the input file: BufferedReader in = new BufferedReader(new FileReader(infile)); int lineCount = 0; while ((currentLine = in.readLine()) != null){ StringTokenizer st = new StringTokenizer(currentLine); if (st.countTokens() > 1){ lineCount++; }else if (st.countTokens() == 1){ //complain if only one field found throw new HaploViewException("Info file format error on line "+lineCount+ ":\n Info file must be of format: <markername> <markerposition>"); }else{ //skip blank lines continue; } String name = st.nextToken(); String l = st.nextToken(); String extra = null; if (st.hasMoreTokens()) extra = st.nextToken(); long loc; try{ loc = Long.parseLong(l); }catch (NumberFormatException nfe){ throw new HaploViewException("Info file format error on line "+lineCount+ ":\n\"" + l + "\" should be of type long." + "\n Info file must be of format: <markername> <markerposition>"); } //basically if anyone is crazy enough to load a dataset, then go back and load //an out-of-order info file we tell them to bugger off and start over. if (loc < prevloc && Chromosome.markers != null){ throw new HaploViewException("Info file out of order with preloaded dataset:\n"+ name + "\nPlease reload data file and info file together."); } prevloc = loc; names.add(name); positions.add(l); extras.add(extra); } if (lineCount > Chromosome.getUnfilteredSize()){ throw(new HaploViewException("Info file error:\nMarker number mismatch: too many\nmarkers in info file compared to data file.")); } if (lineCount < Chromosome.getUnfilteredSize()){ throw(new HaploViewException("Info file error:\nMarker number mismatch: too few\nmarkers in info file compared to data file.")); } infoKnown=true; } if (hapmapGoodies != null){ //we know some stuff from the hapmap so we'll add it here for (int x=0; x < hapmapGoodies.length; x++){ names.add(hapmapGoodies[x][0]); positions.add(hapmapGoodies[x][1]); extras.add(null); } infoKnown = true; } else if (infile != null){ //we only sort if we read the info from an info file. if //it is from a hapmap file, then the markers were already sorted //when they were read in (in class Pedfile). int numLines = names.size(); Hashtable sortHelp = new Hashtable(numLines-1,1.0f); long[] pos = new long[numLines]; boolean needSort = false; //this loop stores the positions of each marker in an array (pos[]) in the order they appear in the file. //it also creates a hashtable with the positions as keys and their index in the pos[] array as the value for (int k = 0; k < (numLines); k++){ pos[k] = new Long((String)(positions.get(k))).longValue(); sortHelp.put(new Long(pos[k]),new Integer(k)); } //loop through and check if any markers are out of order for (int k = 1; k < (numLines); k++){ if(pos[k] < pos[k-1]) { needSort = true; break; } } //if any were out of order, then we need to put them in order if(needSort) { //sort the positions Arrays.sort(pos); Vector newNames = new Vector(); Vector newExtras = new Vector(); Vector newPositions = new Vector(); int[] realPos = new int[numLines]; //reorder the vectors names and extras so that they have the same order as the sorted markers for (int i = 0; i < pos.length; i++){ realPos[i] = ((Integer)(sortHelp.get(new Long(pos[i])))).intValue(); newNames.add(names.get(realPos[i])); newPositions.add(positions.get(realPos[i])); newExtras.add(extras.get(realPos[i])); } names = newNames; extras = newExtras; positions = newPositions; byte[] tempGenotype = new byte[pos.length]; //now we reorder all the individuals genotypes according to the sorted marker order for(int j=0;j<chromosomes.size();j++){ Chromosome tempChrom = (Chromosome)chromosomes.elementAt(j); for(int i =0;i<pos.length;i++){ tempGenotype[i] = tempChrom.getUnfilteredGenotype(realPos[i]); } for(int i=0;i<pos.length;i++) { tempChrom.setGenotype(tempGenotype[i],i); } } } } }catch (HaploViewException e){ throw(e); }finally{ double numChroms = chromosomes.size(); Vector markerInfo = new Vector(); double[] numBadGenotypes = new double[Chromosome.getUnfilteredSize()]; percentBadGenotypes = new double[Chromosome.getUnfilteredSize()]; Vector results = null; if (pedFile != null){ results = pedFile.getResults(); } long prevPosition = Long.MIN_VALUE; SNP prevMarker = null; for (int i = 0; i < Chromosome.getUnfilteredSize(); i++){ MarkerResult mr = null; if (results != null){ mr = (MarkerResult)results.elementAt(i); } //to compute minor/major alleles, browse chrom list and count instances of each allele byte a1 = 0; byte a2 = 0; double numa1 = 0; double numa2 = 0; for (int j = 0; j < chromosomes.size(); j++){ //if there is a data point for this marker on this chromosome byte thisAllele = ((Chromosome)chromosomes.elementAt(j)).getUnfilteredGenotype(i); if (!(thisAllele == 0)){ if (thisAllele >= 5){ numa1+=0.5; numa2+=0.5; if (thisAllele < 9){ if (a1==0){ a1 = (byte)(thisAllele-4); }else if (a2 == 0){ if (!(thisAllele-4 == a1)){ a2 = (byte)(thisAllele-4); } } } }else if (a1 == 0){ a1 = thisAllele; numa1++; }else if (thisAllele == a1){ numa1++; }else{ numa2++; a2 = thisAllele; } } else { numBadGenotypes[i]++; } } if (numa2 > numa1){ byte temp = a1; double tempnum = numa1; numa1 = numa2; a1 = a2; numa2 = tempnum; a2 = temp; } double maf; if (mr != null){ maf = Math.rint(mr.getMAF()*100.0)/100.0; }else{ maf = Math.rint(100.0*(numa2/(numa1+numa2)))/100.0; } if (infoKnown){ long pos = Long.parseLong((String)positions.elementAt(i)); SNP thisMarker = (new SNP((String)names.elementAt(i), pos, maf, a1, a2, (String)extras.elementAt(i))); markerInfo.add(thisMarker); if (mr != null){ double genoPC = mr.getGenoPercent(); //check to make sure adjacent SNPs do not have identical positions if (prevPosition != Long.MIN_VALUE){ //only do this for markers 2..N, since we're comparing to the previous location if (pos == prevPosition){ dupsToBeFlagged = true; if (genoPC >= mr.getGenoPercent()){ //use this one because it has more genotypes thisMarker.setDup(1); prevMarker.setDup(2); }else{ //use the other one because it has more genotypes thisMarker.setDup(2); prevMarker.setDup(1); } } } prevPosition = pos; prevMarker = thisMarker; } }else{ markerInfo.add(new SNP("Marker " + String.valueOf(i+1), (i*4000), maf,a1,a2)); } percentBadGenotypes[i] = numBadGenotypes[i]/numChroms; } Chromosome.markers = markerInfo.toArray(); } } |
|
sample = new PairwiseLinkage[1]; | public DPrimeTable(int numMarkers){ theTable = new PairwiseLinkage[numMarkers][]; sample = new PairwiseLinkage[1]; } |
|
theTable[pos] = (PairwiseLinkage[]) marker.toArray(sample); | theTable[pos] = (PairwiseLinkage[]) marker.toArray(new PairwiseLinkage[0]); | public void addMarker(Vector marker, int pos){ theTable[pos] = (PairwiseLinkage[]) marker.toArray(sample); } |
SNP(String n, long p, double m, byte a1, byte a2, String e){ | SNP(String n, long p, double m, byte a1, byte a2){ | SNP(String n, long p, double m, byte a1, byte a2, String e){ name = n; position = p; MAF = m; major = a1; minor = a2; extra = e; } |
extra = e; | SNP(String n, long p, double m, byte a1, byte a2, String e){ name = n; position = p; MAF = m; major = a1; minor = a2; extra = e; } |
|
df = new DecimalFormat("0.0000E0"); | df = new DecimalFormat("0.0000E0", new DecimalFormatSymbols(Locale.US)); | public String getPValue() { double pval = 0; pval= MathUtil.gammq(.5,.5*this.chiSqVal); DecimalFormat df; //java truly sucks for simply restricting the number of sigfigs but still //using scientific notation when appropriate if (pval < 0.0001){ df = new DecimalFormat("0.0000E0"); }else{ df = new DecimalFormat(); df.setMaximumFractionDigits(4); } String formattedNumber = df.format(pval, new StringBuffer(), new FieldPosition(NumberFormat.INTEGER_FIELD)).toString(); return formattedNumber; } |
df = new DecimalFormat(); df.setMaximumFractionDigits(4); | df = new DecimalFormat("0.0000", new DecimalFormatSymbols(Locale.US)); | public String getPValue() { double pval = 0; pval= MathUtil.gammq(.5,.5*this.chiSqVal); DecimalFormat df; //java truly sucks for simply restricting the number of sigfigs but still //using scientific notation when appropriate if (pval < 0.0001){ df = new DecimalFormat("0.0000E0"); }else{ df = new DecimalFormat(); df.setMaximumFractionDigits(4); } String formattedNumber = df.format(pval, new StringBuffer(), new FieldPosition(NumberFormat.INTEGER_FIELD)).toString(); return formattedNumber; } |
Iterator readers = ImageIO.getImageReadersByFormatName( "jpg" ); | File imageFile = original.getImageFile(); String fname = imageFile.getName(); int lastDotPos = fname.lastIndexOf( "." ); if ( lastDotPos <= 0 || lastDotPos >= fname.length()-1 ) { throw new IOException( "Cannot determine file type extension of " + imageFile.getAbsolutePath() ); } String suffix = fname.substring( lastDotPos+1 ); Iterator readers = ImageIO.getImageReadersBySuffix( suffix ); if ( !readers.hasNext() ) { throw new IOException( "Unknown image file extension " + suffix + "\nwhile reading " + imageFile.getAbsolutePath() ); } | protected void createThumbnail( VolumeBase volume ) { log.debug( "Creating thumbnail for " + uid ); ODMGXAWrapper txw = new ODMGXAWrapper(); txw.lock( this, Transaction.WRITE ); // Maximum size of the thumbnail int maxThumbWidth = 100; int maxThumbHeight = 100; checkCropBounds(); /* Determine the minimum size for the instance used for thumbnail creation to get decent image quality. The cropped portion of the image must be roughly the same resolution as the intended thumbnail. */ double cropWidth = cropMaxX - cropMinX; cropWidth = ( cropWidth > 0.000001 ) ? cropWidth : 1.0; double cropHeight = cropMaxY - cropMinY; cropHeight = ( cropHeight > 0.000001 ) ? cropHeight : 1.0; int minInstanceWidth = (int)(((double)maxThumbWidth)/cropWidth); int minInstanceHeight = (int)(((double)maxThumbHeight)/cropHeight); int minInstanceSide = Math.max( minInstanceWidth, minInstanceHeight ); // Find the original image to use as a staring point ImageInstance original = null; for ( int n = 0; n < instances.size(); n++ ) { ImageInstance instance = (ImageInstance) instances.get( n ); if ( instance.getInstanceType() == ImageInstance.INSTANCE_TYPE_ORIGINAL ) { original = instance; txw.lock( original, Transaction.READ ); break; } } if ( original == null || original.getImageFile() == null || !original.getImageFile().exists() ) { // If there are uncorrupted instances, no thumbnail can be created log.warn( "Error - no original image was found!!!" ); txw.commit(); return; } log.debug( "Found original, reading it..." ); /* We try to ensure that the thumbnail is actually from the original image by comparing aspect ratio of it to original. This is not a perfect check but it will usually catch the most typical errors (like having a the original rotated by RAW conversion SW but still the original EXIF thumbnail. */ double origAspect = this.getAspect( original.getWidth(), original.getHeight(), 1.0 ); double aspectAccuracy = 0.01; // First, check if there is a thumbnail in image header BufferedImage origImage = readExifThumbnail( original.getImageFile() ); if ( origImage == null || !isOkForThumbCreation( origImage.getWidth(), origImage.getHeight(), minInstanceWidth, minInstanceHeight, origAspect, aspectAccuracy ) ) { // Read the image try { Iterator readers = ImageIO.getImageReadersByFormatName( "jpg" ); if ( readers.hasNext() ) { ImageReader reader = (ImageReader)readers.next(); log.debug( "Creating stream" ); ImageInputStream iis = ImageIO.createImageInputStream( original.getImageFile() ); reader.setInput( iis, false, false ); int numThumbs = 0; try { int numImages = reader.getNumImages( true ); numThumbs = reader.getNumThumbnails(0); } catch (IOException ex) { ex.printStackTrace(); } if ( numThumbs > 0 && isOkForThumbCreation( reader.getThumbnailWidth( 0, 0 ), reader.getThumbnailHeight( 0, 0 ) , minInstanceWidth, minInstanceHeight, origAspect, aspectAccuracy ) ) { // There is a thumbanil that is big enough - use it log.debug( "Original has thumbnail, size " + reader.getThumbnailWidth( 0, 0 ) + " x " + reader.getThumbnailHeight( 0, 0 ) ); origImage = reader.readThumbnail( 0, 0 ); log.debug( "Read thumbnail" ); } else { log.debug( "No thumbnail in original" ); ImageReadParam param = reader.getDefaultReadParam(); // Find the maximum subsampling rate we can still use for creating // a quality thumbnail int subsampling = 1; int minDim = Math.min( reader.getWidth( 0 ),reader.getHeight( 0 ) ); while ( 2 * minInstanceSide * subsampling < minDim ) { subsampling *= 2; } param.setSourceSubsampling( subsampling, subsampling, 0, 0 ); origImage = reader.read( 0, param ); log.debug( "Read original" ); } iis.close(); } } catch ( IOException e ) { log.warn( "Error reading image: " + e.getMessage() ); txw.abort(); return; } } log.debug( "Done, finding name" ); // Find where to store the file in the target volume File thumbnailFile = volume.getInstanceName( this, "jpg" ); log.debug( "name = " + thumbnailFile.getName() ); // Shrink the image to desired state and save it // Find first the correct transformation for doing this int origWidth = origImage.getWidth(); int origHeight = origImage.getHeight(); AffineTransform xform = org.photovault.image.ImageXform.getRotateXform( prefRotation -original.getRotated(), origWidth, origHeight ); ParameterBlockJAI rotParams = new ParameterBlockJAI( "affine" ); rotParams.addSource( origImage ); rotParams.setParameter( "transform", xform ); rotParams.setParameter( "interpolation", Interpolation.getInstance( Interpolation.INTERP_NEAREST ) ); RenderedOp rotatedImage = JAI.create( "affine", rotParams ); ParameterBlockJAI cropParams = new ParameterBlockJAI( "crop" ); cropParams.addSource( rotatedImage ); float cropX = (float)( Math.rint( rotatedImage.getMinX() + cropMinX * rotatedImage.getWidth() ) ); float cropY = (float)( Math.rint( rotatedImage.getMinY() + cropMinY * rotatedImage.getHeight())); float cropW = (float)( Math.rint((cropWidth) * rotatedImage.getWidth() ) ); float cropH = (float) ( Math.rint((cropHeight) * rotatedImage.getHeight() )); cropParams.setParameter( "x", cropX ); cropParams.setParameter( "y", cropY ); cropParams.setParameter( "width", cropW ); cropParams.setParameter( "height", cropH ); RenderedOp cropped = JAI.create("crop", cropParams, null); // Translate the image so that it begins in origo ParameterBlockJAI pbXlate = new ParameterBlockJAI( "translate" ); pbXlate.addSource( cropped ); pbXlate.setParameter( "xTrans", (float) (-cropped.getMinX() ) ); pbXlate.setParameter( "yTrans", (float) (-cropped.getMinY() ) ); RenderedOp xformImage = JAI.create( "translate", pbXlate ); // Finally, scale this to thumbnail AffineTransform thumbScale = org.photovault.image.ImageXform.getFittingXform( maxThumbWidth, maxThumbHeight, 0, xformImage.getWidth(), xformImage.getHeight() ); ParameterBlockJAI thumbScaleParams = new ParameterBlockJAI( "affine" ); thumbScaleParams.addSource( xformImage ); thumbScaleParams.setParameter( "transform", thumbScale ); thumbScaleParams.setParameter( "interpolation", Interpolation.getInstance( Interpolation.INTERP_NEAREST ) ); PlanarImage thumbImage = JAI.create( "affine", thumbScaleParams ); // Save it FileOutputStream out = null; try { out = new FileOutputStream(thumbnailFile.getAbsolutePath()); } catch(IOException e) { log.error( "Error writing thumbnail: " + e.getMessage() ); txw.abort(); return; } JPEGEncodeParam encodeParam = new JPEGEncodeParam(); ImageEncoder encoder = ImageCodec.createImageEncoder("JPEG", out, encodeParam); try { encoder.encode( thumbImage ); out.close(); // origImage.dispose(); thumbImage.dispose(); } catch (IOException e) { log.error( "Error writing thumbnail: " + e.getMessage() ); txw.abort(); return; } // add the created instance to this persistent object ImageInstance thumbInstance = addInstance( volume, thumbnailFile, ImageInstance.INSTANCE_TYPE_THUMBNAIL ); thumbInstance.setRotated( prefRotation -original.getRotated() ); thumbInstance.setCropBounds( getCropBounds() ); log.debug( "Loading thumbnail..." ); thumbnail = Thumbnail.createThumbnail( this, thumbnailFile ); oldThumbnail = null; log.debug( "Thumbnail loaded" ); txw.commit(); } |
int minDim = Math.min( reader.getWidth( 0 ),reader.getHeight( 0 ) ); while ( 2 * minInstanceSide * subsampling < minDim ) { subsampling *= 2; | if ( suffix.toLowerCase().equals( "jpg" ) ) { int minDim = Math.min( reader.getWidth( 0 ),reader.getHeight( 0 ) ); while ( 2 * minInstanceSide * subsampling < minDim ) { subsampling *= 2; } | protected void createThumbnail( VolumeBase volume ) { log.debug( "Creating thumbnail for " + uid ); ODMGXAWrapper txw = new ODMGXAWrapper(); txw.lock( this, Transaction.WRITE ); // Maximum size of the thumbnail int maxThumbWidth = 100; int maxThumbHeight = 100; checkCropBounds(); /* Determine the minimum size for the instance used for thumbnail creation to get decent image quality. The cropped portion of the image must be roughly the same resolution as the intended thumbnail. */ double cropWidth = cropMaxX - cropMinX; cropWidth = ( cropWidth > 0.000001 ) ? cropWidth : 1.0; double cropHeight = cropMaxY - cropMinY; cropHeight = ( cropHeight > 0.000001 ) ? cropHeight : 1.0; int minInstanceWidth = (int)(((double)maxThumbWidth)/cropWidth); int minInstanceHeight = (int)(((double)maxThumbHeight)/cropHeight); int minInstanceSide = Math.max( minInstanceWidth, minInstanceHeight ); // Find the original image to use as a staring point ImageInstance original = null; for ( int n = 0; n < instances.size(); n++ ) { ImageInstance instance = (ImageInstance) instances.get( n ); if ( instance.getInstanceType() == ImageInstance.INSTANCE_TYPE_ORIGINAL ) { original = instance; txw.lock( original, Transaction.READ ); break; } } if ( original == null || original.getImageFile() == null || !original.getImageFile().exists() ) { // If there are uncorrupted instances, no thumbnail can be created log.warn( "Error - no original image was found!!!" ); txw.commit(); return; } log.debug( "Found original, reading it..." ); /* We try to ensure that the thumbnail is actually from the original image by comparing aspect ratio of it to original. This is not a perfect check but it will usually catch the most typical errors (like having a the original rotated by RAW conversion SW but still the original EXIF thumbnail. */ double origAspect = this.getAspect( original.getWidth(), original.getHeight(), 1.0 ); double aspectAccuracy = 0.01; // First, check if there is a thumbnail in image header BufferedImage origImage = readExifThumbnail( original.getImageFile() ); if ( origImage == null || !isOkForThumbCreation( origImage.getWidth(), origImage.getHeight(), minInstanceWidth, minInstanceHeight, origAspect, aspectAccuracy ) ) { // Read the image try { Iterator readers = ImageIO.getImageReadersByFormatName( "jpg" ); if ( readers.hasNext() ) { ImageReader reader = (ImageReader)readers.next(); log.debug( "Creating stream" ); ImageInputStream iis = ImageIO.createImageInputStream( original.getImageFile() ); reader.setInput( iis, false, false ); int numThumbs = 0; try { int numImages = reader.getNumImages( true ); numThumbs = reader.getNumThumbnails(0); } catch (IOException ex) { ex.printStackTrace(); } if ( numThumbs > 0 && isOkForThumbCreation( reader.getThumbnailWidth( 0, 0 ), reader.getThumbnailHeight( 0, 0 ) , minInstanceWidth, minInstanceHeight, origAspect, aspectAccuracy ) ) { // There is a thumbanil that is big enough - use it log.debug( "Original has thumbnail, size " + reader.getThumbnailWidth( 0, 0 ) + " x " + reader.getThumbnailHeight( 0, 0 ) ); origImage = reader.readThumbnail( 0, 0 ); log.debug( "Read thumbnail" ); } else { log.debug( "No thumbnail in original" ); ImageReadParam param = reader.getDefaultReadParam(); // Find the maximum subsampling rate we can still use for creating // a quality thumbnail int subsampling = 1; int minDim = Math.min( reader.getWidth( 0 ),reader.getHeight( 0 ) ); while ( 2 * minInstanceSide * subsampling < minDim ) { subsampling *= 2; } param.setSourceSubsampling( subsampling, subsampling, 0, 0 ); origImage = reader.read( 0, param ); log.debug( "Read original" ); } iis.close(); } } catch ( IOException e ) { log.warn( "Error reading image: " + e.getMessage() ); txw.abort(); return; } } log.debug( "Done, finding name" ); // Find where to store the file in the target volume File thumbnailFile = volume.getInstanceName( this, "jpg" ); log.debug( "name = " + thumbnailFile.getName() ); // Shrink the image to desired state and save it // Find first the correct transformation for doing this int origWidth = origImage.getWidth(); int origHeight = origImage.getHeight(); AffineTransform xform = org.photovault.image.ImageXform.getRotateXform( prefRotation -original.getRotated(), origWidth, origHeight ); ParameterBlockJAI rotParams = new ParameterBlockJAI( "affine" ); rotParams.addSource( origImage ); rotParams.setParameter( "transform", xform ); rotParams.setParameter( "interpolation", Interpolation.getInstance( Interpolation.INTERP_NEAREST ) ); RenderedOp rotatedImage = JAI.create( "affine", rotParams ); ParameterBlockJAI cropParams = new ParameterBlockJAI( "crop" ); cropParams.addSource( rotatedImage ); float cropX = (float)( Math.rint( rotatedImage.getMinX() + cropMinX * rotatedImage.getWidth() ) ); float cropY = (float)( Math.rint( rotatedImage.getMinY() + cropMinY * rotatedImage.getHeight())); float cropW = (float)( Math.rint((cropWidth) * rotatedImage.getWidth() ) ); float cropH = (float) ( Math.rint((cropHeight) * rotatedImage.getHeight() )); cropParams.setParameter( "x", cropX ); cropParams.setParameter( "y", cropY ); cropParams.setParameter( "width", cropW ); cropParams.setParameter( "height", cropH ); RenderedOp cropped = JAI.create("crop", cropParams, null); // Translate the image so that it begins in origo ParameterBlockJAI pbXlate = new ParameterBlockJAI( "translate" ); pbXlate.addSource( cropped ); pbXlate.setParameter( "xTrans", (float) (-cropped.getMinX() ) ); pbXlate.setParameter( "yTrans", (float) (-cropped.getMinY() ) ); RenderedOp xformImage = JAI.create( "translate", pbXlate ); // Finally, scale this to thumbnail AffineTransform thumbScale = org.photovault.image.ImageXform.getFittingXform( maxThumbWidth, maxThumbHeight, 0, xformImage.getWidth(), xformImage.getHeight() ); ParameterBlockJAI thumbScaleParams = new ParameterBlockJAI( "affine" ); thumbScaleParams.addSource( xformImage ); thumbScaleParams.setParameter( "transform", thumbScale ); thumbScaleParams.setParameter( "interpolation", Interpolation.getInstance( Interpolation.INTERP_NEAREST ) ); PlanarImage thumbImage = JAI.create( "affine", thumbScaleParams ); // Save it FileOutputStream out = null; try { out = new FileOutputStream(thumbnailFile.getAbsolutePath()); } catch(IOException e) { log.error( "Error writing thumbnail: " + e.getMessage() ); txw.abort(); return; } JPEGEncodeParam encodeParam = new JPEGEncodeParam(); ImageEncoder encoder = ImageCodec.createImageEncoder("JPEG", out, encodeParam); try { encoder.encode( thumbImage ); out.close(); // origImage.dispose(); thumbImage.dispose(); } catch (IOException e) { log.error( "Error writing thumbnail: " + e.getMessage() ); txw.abort(); return; } // add the created instance to this persistent object ImageInstance thumbInstance = addInstance( volume, thumbnailFile, ImageInstance.INSTANCE_TYPE_THUMBNAIL ); thumbInstance.setRotated( prefRotation -original.getRotated() ); thumbInstance.setCropBounds( getCropBounds() ); log.debug( "Loading thumbnail..." ); thumbnail = Thumbnail.createThumbnail( this, thumbnailFile ); oldThumbnail = null; log.debug( "Thumbnail loaded" ); txw.commit(); } |
} catch (IOException e) { log.error( "Error writing thumbnail: " + e.getMessage() ); | } catch (Exception e) { log.error( "Error writing thumbnail for " + original.getImageFile().getAbsolutePath()+ ": " + e.getMessage() ); | protected void createThumbnail( VolumeBase volume ) { log.debug( "Creating thumbnail for " + uid ); ODMGXAWrapper txw = new ODMGXAWrapper(); txw.lock( this, Transaction.WRITE ); // Maximum size of the thumbnail int maxThumbWidth = 100; int maxThumbHeight = 100; checkCropBounds(); /* Determine the minimum size for the instance used for thumbnail creation to get decent image quality. The cropped portion of the image must be roughly the same resolution as the intended thumbnail. */ double cropWidth = cropMaxX - cropMinX; cropWidth = ( cropWidth > 0.000001 ) ? cropWidth : 1.0; double cropHeight = cropMaxY - cropMinY; cropHeight = ( cropHeight > 0.000001 ) ? cropHeight : 1.0; int minInstanceWidth = (int)(((double)maxThumbWidth)/cropWidth); int minInstanceHeight = (int)(((double)maxThumbHeight)/cropHeight); int minInstanceSide = Math.max( minInstanceWidth, minInstanceHeight ); // Find the original image to use as a staring point ImageInstance original = null; for ( int n = 0; n < instances.size(); n++ ) { ImageInstance instance = (ImageInstance) instances.get( n ); if ( instance.getInstanceType() == ImageInstance.INSTANCE_TYPE_ORIGINAL ) { original = instance; txw.lock( original, Transaction.READ ); break; } } if ( original == null || original.getImageFile() == null || !original.getImageFile().exists() ) { // If there are uncorrupted instances, no thumbnail can be created log.warn( "Error - no original image was found!!!" ); txw.commit(); return; } log.debug( "Found original, reading it..." ); /* We try to ensure that the thumbnail is actually from the original image by comparing aspect ratio of it to original. This is not a perfect check but it will usually catch the most typical errors (like having a the original rotated by RAW conversion SW but still the original EXIF thumbnail. */ double origAspect = this.getAspect( original.getWidth(), original.getHeight(), 1.0 ); double aspectAccuracy = 0.01; // First, check if there is a thumbnail in image header BufferedImage origImage = readExifThumbnail( original.getImageFile() ); if ( origImage == null || !isOkForThumbCreation( origImage.getWidth(), origImage.getHeight(), minInstanceWidth, minInstanceHeight, origAspect, aspectAccuracy ) ) { // Read the image try { Iterator readers = ImageIO.getImageReadersByFormatName( "jpg" ); if ( readers.hasNext() ) { ImageReader reader = (ImageReader)readers.next(); log.debug( "Creating stream" ); ImageInputStream iis = ImageIO.createImageInputStream( original.getImageFile() ); reader.setInput( iis, false, false ); int numThumbs = 0; try { int numImages = reader.getNumImages( true ); numThumbs = reader.getNumThumbnails(0); } catch (IOException ex) { ex.printStackTrace(); } if ( numThumbs > 0 && isOkForThumbCreation( reader.getThumbnailWidth( 0, 0 ), reader.getThumbnailHeight( 0, 0 ) , minInstanceWidth, minInstanceHeight, origAspect, aspectAccuracy ) ) { // There is a thumbanil that is big enough - use it log.debug( "Original has thumbnail, size " + reader.getThumbnailWidth( 0, 0 ) + " x " + reader.getThumbnailHeight( 0, 0 ) ); origImage = reader.readThumbnail( 0, 0 ); log.debug( "Read thumbnail" ); } else { log.debug( "No thumbnail in original" ); ImageReadParam param = reader.getDefaultReadParam(); // Find the maximum subsampling rate we can still use for creating // a quality thumbnail int subsampling = 1; int minDim = Math.min( reader.getWidth( 0 ),reader.getHeight( 0 ) ); while ( 2 * minInstanceSide * subsampling < minDim ) { subsampling *= 2; } param.setSourceSubsampling( subsampling, subsampling, 0, 0 ); origImage = reader.read( 0, param ); log.debug( "Read original" ); } iis.close(); } } catch ( IOException e ) { log.warn( "Error reading image: " + e.getMessage() ); txw.abort(); return; } } log.debug( "Done, finding name" ); // Find where to store the file in the target volume File thumbnailFile = volume.getInstanceName( this, "jpg" ); log.debug( "name = " + thumbnailFile.getName() ); // Shrink the image to desired state and save it // Find first the correct transformation for doing this int origWidth = origImage.getWidth(); int origHeight = origImage.getHeight(); AffineTransform xform = org.photovault.image.ImageXform.getRotateXform( prefRotation -original.getRotated(), origWidth, origHeight ); ParameterBlockJAI rotParams = new ParameterBlockJAI( "affine" ); rotParams.addSource( origImage ); rotParams.setParameter( "transform", xform ); rotParams.setParameter( "interpolation", Interpolation.getInstance( Interpolation.INTERP_NEAREST ) ); RenderedOp rotatedImage = JAI.create( "affine", rotParams ); ParameterBlockJAI cropParams = new ParameterBlockJAI( "crop" ); cropParams.addSource( rotatedImage ); float cropX = (float)( Math.rint( rotatedImage.getMinX() + cropMinX * rotatedImage.getWidth() ) ); float cropY = (float)( Math.rint( rotatedImage.getMinY() + cropMinY * rotatedImage.getHeight())); float cropW = (float)( Math.rint((cropWidth) * rotatedImage.getWidth() ) ); float cropH = (float) ( Math.rint((cropHeight) * rotatedImage.getHeight() )); cropParams.setParameter( "x", cropX ); cropParams.setParameter( "y", cropY ); cropParams.setParameter( "width", cropW ); cropParams.setParameter( "height", cropH ); RenderedOp cropped = JAI.create("crop", cropParams, null); // Translate the image so that it begins in origo ParameterBlockJAI pbXlate = new ParameterBlockJAI( "translate" ); pbXlate.addSource( cropped ); pbXlate.setParameter( "xTrans", (float) (-cropped.getMinX() ) ); pbXlate.setParameter( "yTrans", (float) (-cropped.getMinY() ) ); RenderedOp xformImage = JAI.create( "translate", pbXlate ); // Finally, scale this to thumbnail AffineTransform thumbScale = org.photovault.image.ImageXform.getFittingXform( maxThumbWidth, maxThumbHeight, 0, xformImage.getWidth(), xformImage.getHeight() ); ParameterBlockJAI thumbScaleParams = new ParameterBlockJAI( "affine" ); thumbScaleParams.addSource( xformImage ); thumbScaleParams.setParameter( "transform", thumbScale ); thumbScaleParams.setParameter( "interpolation", Interpolation.getInstance( Interpolation.INTERP_NEAREST ) ); PlanarImage thumbImage = JAI.create( "affine", thumbScaleParams ); // Save it FileOutputStream out = null; try { out = new FileOutputStream(thumbnailFile.getAbsolutePath()); } catch(IOException e) { log.error( "Error writing thumbnail: " + e.getMessage() ); txw.abort(); return; } JPEGEncodeParam encodeParam = new JPEGEncodeParam(); ImageEncoder encoder = ImageCodec.createImageEncoder("JPEG", out, encodeParam); try { encoder.encode( thumbImage ); out.close(); // origImage.dispose(); thumbImage.dispose(); } catch (IOException e) { log.error( "Error writing thumbnail: " + e.getMessage() ); txw.abort(); return; } // add the created instance to this persistent object ImageInstance thumbInstance = addInstance( volume, thumbnailFile, ImageInstance.INSTANCE_TYPE_THUMBNAIL ); thumbInstance.setRotated( prefRotation -original.getRotated() ); thumbInstance.setCropBounds( getCropBounds() ); log.debug( "Loading thumbnail..." ); thumbnail = Thumbnail.createThumbnail( this, thumbnailFile ); oldThumbnail = null; log.debug( "Thumbnail loaded" ); txw.commit(); } |
StringBuffer cameraBuf = new StringBuffer( maker ); cameraBuf.append( " "). append( model ); | StringBuffer cameraBuf = new StringBuffer( maker != null ? maker : "" ); if ( model != null ) { cameraBuf.append( " "). append( model ); } | void updateFromFileMetadata( File f ) { ExifDirectory exif = null; try { Metadata metadata = JpegMetadataReader.readMetadata(f); if ( metadata.containsDirectory( ExifDirectory.class ) ) { try { exif = (ExifDirectory) metadata.getDirectory( ExifDirectory.class ); } catch ( MetadataException e ) { } } else { // No known directory was found no reason to continue return; } } catch (FileNotFoundException e) { // If error, just return - this is just an additional 'nice-if-succesful' operation. // If there is no metadata this will happen... return; } // Shooting date try { java.util.Date origDate = exif.getDate( exif.TAG_DATETIME_ORIGINAL ); setShootTime( origDate ); log.debug( "TAG_DATETIME_ORIGINAL: " + origDate.toString() ); } catch ( MetadataException e ) { log.info( "Error reading origDate: " + e.getMessage() ); } // Exposure try { double fstop = exif.getDouble( exif.TAG_FNUMBER ); log.debug( "TAG_FNUMBER: " + fstop ); setFStop( fstop ); } catch ( MetadataException e ) { log.info( "Error reading origDate: " + e.getMessage() ); } try { double sspeed = exif.getDouble( exif.TAG_EXPOSURE_TIME ); setShutterSpeed( sspeed ); log.debug( "TAG_EXPOSURE_TIME: " + sspeed ); } catch ( MetadataException e ) { log.info( "Error reading origDate: " + e.getMessage() ); } try { double flen = exif.getDouble( exif.TAG_FOCAL_LENGTH ); setFocalLength( flen ); } catch ( MetadataException e ) { log.info( "Error reading origDate: " + e.getMessage() ); } try { int filmSpeed = exif.getInt( exif.TAG_ISO_EQUIVALENT ); setFilmSpeed( filmSpeed ); } catch ( MetadataException e ) { log.info( "Error reading origDate: " + e.getMessage() ); } // Camera name. Put here both camera manufacturer and model String maker = exif.getString( exif.TAG_MAKE ); String model = exif.getString( exif.TAG_MODEL ); StringBuffer cameraBuf = new StringBuffer( maker ); cameraBuf.append( " "). append( model ); String camera = cameraBuf.toString(); if ( cameraBuf.length() > CAMERA_LENGTH ) { camera = cameraBuf.substring( 0, CAMERA_LENGTH ); } setCamera( camera ); } |
fkCol.addReference(); | public synchronized TablePane importTableCopy(SQLTable source, Point preferredLocation) throws ArchitectException { SQLTable newTable = SQLTable.getDerivedInstance(source, db); // adds newTable to db String key = source.getName().toLowerCase(); // ensure tablename is unique if (logger.isDebugEnabled()) logger.debug("before add: " + tableNames); if (!tableNames.add(key)) { boolean done = false; int newSuffix = 0; while (!done) { newSuffix++; done = tableNames.add(key+"_"+newSuffix); } newTable.setName(source.getName()+"_"+newSuffix); } if (logger.isDebugEnabled()) logger.debug("after add: " + tableNames); TablePane tp = new TablePane(newTable, this); logger.info("adding table "+newTable); addImpl(tp, preferredLocation,getPPComponentCount()); tp.revalidate(); // create exported relationships if the importing tables exist in pp Iterator sourceKeys = source.getExportedKeys().iterator(); while (sourceKeys.hasNext()) { Object next = sourceKeys.next(); if ( !(next instanceof SQLRelationship) ) continue; // there could be SQLExceptionNodes here SQLRelationship r = (SQLRelationship) next; if (logger.isInfoEnabled()) { logger.info("Looking for fk table "+r.getFkTable().getName()+" in playpen"); } TablePane fkTablePane = findTablePaneByName(r.getFkTable().getName()); if (fkTablePane != null) { logger.info("FOUND IT!"); SQLTable fkTable = fkTablePane.getModel(); SQLRelationship newRel = new SQLRelationship(); newRel.setName(r.getName()); newRel.setIdentifying(true); newRel.attachRelationship(newTable,fkTable,false); addImpl(new Relationship(this, newRel),null,getPPComponentCount()); Iterator mappings = r.getChildren().iterator(); while (mappings.hasNext()) { SQLRelationship.ColumnMapping m = (SQLRelationship.ColumnMapping) mappings.next(); SQLColumn pkCol = newTable.getColumnByName(m.getPkColumn().getName()); SQLColumn fkCol = fkTable.getColumnByName(m.getFkColumn().getName()); if (pkCol == null) { // this shouldn't happen throw new IllegalStateException("Couldn't fink pkCol "+m.getPkColumn().getName()+" in new table"); } if (fkCol == null) { // this might reasonably happen (user deleted the column) continue; } SQLRelationship.ColumnMapping newMapping = new SQLRelationship.ColumnMapping(); newMapping.setPkColumn(pkCol); newMapping.setFkColumn(fkCol); newRel.addChild(newMapping); } } else { logger.info("NOT FOUND"); } } // create imported relationships if the exporting tables exist in pp sourceKeys = source.getImportedKeys().iterator(); while (sourceKeys.hasNext()) { SQLRelationship r = (SQLRelationship) sourceKeys.next(); if (logger.isDebugEnabled()) { logger.info("Looking for pk table "+r.getPkTable().getName()+" in playpen"); } TablePane pkTablePane = findTablePaneByName(r.getPkTable().getName()); if (pkTablePane != null) { logger.info("FOUND IT!"); SQLTable pkTable = pkTablePane.getModel(); SQLRelationship newRel = new SQLRelationship(); newRel.setName(r.getName()); newRel.setIdentifying(true); newRel.attachRelationship(pkTable,newTable,false); addImpl(new Relationship(this, newRel),null,getPPComponentCount()); Iterator mappings = r.getChildren().iterator(); while (mappings.hasNext()) { SQLRelationship.ColumnMapping m = (SQLRelationship.ColumnMapping) mappings.next(); SQLColumn pkCol = pkTable.getColumnByName(m.getPkColumn().getName()); SQLColumn fkCol = newTable.getColumnByName(m.getFkColumn().getName()); if (fkCol == null) { // this shouldn't happen throw new IllegalStateException("Couldn't fink fkCol "+m.getPkColumn().getName()+" in new table"); } if (pkCol == null) { // this might reasonably happen (user deleted the column) continue; } SQLRelationship.ColumnMapping newMapping = new SQLRelationship.ColumnMapping(); newMapping.setPkColumn(pkCol); newMapping.setFkColumn(fkCol); newRel.addChild(newMapping); } } else { logger.info("NOT FOUND"); } } return tp; } |
|
public void remove(PlayPenComponent c) { int j = children.indexOf(c); if ( j >= 0 ) remove(j); | public void remove(int j) { PlayPenComponent c = children.get(j); Rectangle r = c.getBounds(); c.removePlayPenComponentListener(playPenComponentEventPassthrough); c.removeSelectionListener(getOwner()); children.remove(j); getOwner().repaint(r); | public void remove(PlayPenComponent c) { int j = children.indexOf(c); if ( j >= 0 ) remove(j); } |
List selection = pp.getSelectedItems(); if (selection.size() < 1) { JOptionPane.showMessageDialog(pp, "Select a relationship (by clicking on it) and try again."); } else if (selection.size() > 1) { JOptionPane.showMessageDialog(pp, "You have selected multiple items, but you can only edit one at a time."); } else if (selection.get(0) instanceof Relationship) { Relationship r = (Relationship) selection.get(0); final JDialog d = new JDialog(ArchitectFrame.getMainInstance(), "Relationship Properties"); JPanel cp = new JPanel(new BorderLayout(12,12)); cp.setBorder(BorderFactory.createEmptyBorder(12,12,12,12)); final RelationshipEditPanel editPanel = new RelationshipEditPanel(); editPanel.setRelationship(r.getModel()); cp.add(editPanel, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JButton okButton = new JButton("Ok"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { editPanel.applyChanges(); d.setVisible(false); } }); buttonPanel.add(okButton); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { editPanel.discardChanges(); d.setVisible(false); } }); buttonPanel.add(cancelButton); cp.add(buttonPanel, BorderLayout.SOUTH); d.setContentPane(cp); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); | if (evt.getActionCommand().equals(ArchitectSwingConstants.ACTION_COMMAND_SRC_PLAYPEN)) { List selection = pp.getSelectedItems(); if (selection.size() < 1) { JOptionPane.showMessageDialog(pp, "Select a relationship (by clicking on it) and try again."); } else if (selection.size() > 1) { JOptionPane.showMessageDialog(pp, "You have selected multiple items, but you can only edit one at a time."); } else if (selection.get(0) instanceof Relationship) { Relationship r = (Relationship) selection.get(0); makeDialog(r.getModel()); } else { JOptionPane.showMessageDialog(pp, "The selected item type is not recognised"); } } else if (evt.getActionCommand().equals(ArchitectSwingConstants.ACTION_COMMAND_SRC_DBTREE)) { TreePath [] selections = dbt.getSelectionPaths(); if (selections.length != 1) { JOptionPane.showMessageDialog(dbt, "Please select the relationship you would like to edit."); } else { TreePath tp = selections[0]; SQLObject so = (SQLObject) tp.getLastPathComponent(); if (so instanceof SQLRelationship) { SQLRelationship sr = (SQLRelationship) so; makeDialog(sr); } else { JOptionPane.showMessageDialog(dbt, "Please select the relationship you would like to edit."); } } | public void actionPerformed(ActionEvent evt) { List selection = pp.getSelectedItems(); if (selection.size() < 1) { JOptionPane.showMessageDialog(pp, "Select a relationship (by clicking on it) and try again."); } else if (selection.size() > 1) { JOptionPane.showMessageDialog(pp, "You have selected multiple items, but you can only edit one at a time."); } else if (selection.get(0) instanceof Relationship) { Relationship r = (Relationship) selection.get(0); final JDialog d = new JDialog(ArchitectFrame.getMainInstance(), "Relationship Properties"); JPanel cp = new JPanel(new BorderLayout(12,12)); cp.setBorder(BorderFactory.createEmptyBorder(12,12,12,12)); final RelationshipEditPanel editPanel = new RelationshipEditPanel(); editPanel.setRelationship(r.getModel()); cp.add(editPanel, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JButton okButton = new JButton("Ok"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { editPanel.applyChanges(); d.setVisible(false); } }); buttonPanel.add(okButton); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { editPanel.discardChanges(); d.setVisible(false); } }); buttonPanel.add(cancelButton); cp.add(buttonPanel, BorderLayout.SOUTH); d.setContentPane(cp); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } else { JOptionPane.showMessageDialog(pp, "The selected item type is not recognised"); } } |
JOptionPane.showMessageDialog(pp, "The selected item type is not recognised"); } | } | public void actionPerformed(ActionEvent evt) { List selection = pp.getSelectedItems(); if (selection.size() < 1) { JOptionPane.showMessageDialog(pp, "Select a relationship (by clicking on it) and try again."); } else if (selection.size() > 1) { JOptionPane.showMessageDialog(pp, "You have selected multiple items, but you can only edit one at a time."); } else if (selection.get(0) instanceof Relationship) { Relationship r = (Relationship) selection.get(0); final JDialog d = new JDialog(ArchitectFrame.getMainInstance(), "Relationship Properties"); JPanel cp = new JPanel(new BorderLayout(12,12)); cp.setBorder(BorderFactory.createEmptyBorder(12,12,12,12)); final RelationshipEditPanel editPanel = new RelationshipEditPanel(); editPanel.setRelationship(r.getModel()); cp.add(editPanel, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JButton okButton = new JButton("Ok"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { editPanel.applyChanges(); d.setVisible(false); } }); buttonPanel.add(okButton); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { editPanel.discardChanges(); d.setVisible(false); } }); buttonPanel.add(cancelButton); cp.add(buttonPanel, BorderLayout.SOUTH); d.setContentPane(cp); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } else { JOptionPane.showMessageDialog(pp, "The selected item type is not recognised"); } } |
Point ep = e.getPoint(); Point sp = owner.unzoomPoint(ep); PlayPenComponent c = getComponentAt(sp); | PlayPenComponent c = getComponentAt(e.getPoint()); | public String getToolTipText(MouseEvent e) { String text = null; Point ep = e.getPoint(); // event's point in playpen in screen coords Point sp = owner.unzoomPoint(ep); PlayPenComponent c = getComponentAt(sp); if (c != null) { text = c.getToolTipText(); } logger.debug("Checking for tooltip component at "+e.getPoint()+" is "+c+". tooltipText is "+text); return text; } |
put(PL_LOGICAL, argName); | putImpl(PL_LOGICAL, argName, "name"); | public void setName(String argName){ put(PL_LOGICAL, argName); } |
if (getPreferredSize().getWidth() < getVisibleRect().width){ | if (getPreferredSize().getWidth() < getVisibleRect().width && theData.infoKnown){ | public void mousePressed (MouseEvent e) { Rectangle blockselector = new Rectangle(clickXShift-boxRadius,clickYShift - boxRadius, (Chromosome.getFilteredSize()*boxSize), boxSize); //if users right clicks & holds, pop up the info if ((e.getModifiers() & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK){ Graphics g = getGraphics(); g.setFont(boxFont); FontMetrics metrics = g.getFontMetrics(); PairwiseLinkage[][] dPrimeTable = theData.filteredDPrimeTable; final int clickX = e.getX(); final int clickY = e.getY(); double dboxX = (double)(clickX - clickXShift - (clickY-clickYShift))/boxSize; double dboxY = (double)(clickX - clickXShift + (clickY-clickYShift))/boxSize; final int boxX, boxY; if (dboxX < 0){ boxX = (int)(dboxX - 0.5); } else{ boxX = (int)(dboxX + 0.5); } if (dboxY < 0){ boxY = (int)(dboxY - 0.5); }else{ boxY = (int)(dboxY + 0.5); } if ((boxX >= lowX && boxX <= highX) && (boxY > boxX && boxY < highY) && !(worldmapRect.contains(clickX,clickY))){ if (dPrimeTable[boxX][boxY] != null){ displayStrings = new String[5]; if (theData.infoKnown){ displayStrings[0] = new String ("(" +Chromosome.getFilteredMarker(boxX).getName() + ", " + Chromosome.getFilteredMarker(boxY).getName() + ")"); }else{ displayStrings[0] = new String("(" + (Chromosome.realIndex[boxX]+1) + ", " + (Chromosome.realIndex[boxY]+1) + ")"); } displayStrings[1] = new String ("D': " + dPrimeTable[boxX][boxY].getDPrime()); displayStrings[2] = new String ("LOD: " + dPrimeTable[boxX][boxY].getLOD()); displayStrings[3] = new String ("r^2: " + dPrimeTable[boxX][boxY].getRSquared()); displayStrings[4] = new String ("D' conf. bounds: " + dPrimeTable[boxX][boxY].getConfidenceLow() + "-" + dPrimeTable[boxX][boxY].getConfidenceHigh()); popupExists = true; } } else if (blockselector.contains(clickX, clickY)){ int marker = (int)(0.5 + (double)((clickX - clickXShift))/boxSize); displayStrings = new String[2]; if (theData.infoKnown){ displayStrings[0] = new String (Chromosome.getFilteredMarker(marker).getName()); }else{ displayStrings[0] = new String("Marker " + (Chromosome.realIndex[marker]+1)); } displayStrings[1] = new String ("MAF: " + Chromosome.getFilteredMarker(marker).getMAF()); popupExists = true; } if (popupExists){ int strlen = 0; for (int x = 0; x < displayStrings.length; x++){ if (strlen < metrics.stringWidth(displayStrings[x])){ strlen = metrics.stringWidth(displayStrings[x]); } } //edge shifts prevent window from popping up partially offscreen int visRightBound = (int)(getVisibleRect().getWidth() + getVisibleRect().getX()); int visBotBound = (int)(getVisibleRect().getHeight() + getVisibleRect().getY()); int rightEdgeShift = 0; if (clickX + strlen + popupLeftMargin +5 > visRightBound){ rightEdgeShift = clickX + strlen + popupLeftMargin + 10 - visRightBound; } int botEdgeShift = 0; if (clickY + 5*metrics.getHeight()+10 > visBotBound){ botEdgeShift = clickY + 5*metrics.getHeight()+15 - visBotBound; } int smallDataVertSlop = 0; if (getPreferredSize().getWidth() < getVisibleRect().width){ smallDataVertSlop = (int)(getVisibleRect().height - getPreferredSize().getHeight())/2; } popupDrawRect = new Rectangle(clickX-rightEdgeShift, clickY-botEdgeShift+smallDataVertSlop, strlen+popupLeftMargin+5, displayStrings.length*metrics.getHeight()+10); repaint(); } }else if ((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK){ int x = e.getX(); int y = e.getY(); if (blockselector.contains(x,y)){ setCursor(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR)); blockStartX = x; } } } |
ApplicationConfigManager.deleteApplication(appForm.getApplicationId()); | ApplicationConfig config=ApplicationConfigManager.deleteApplication (appForm.getApplicationId()); | public ActionForward execute(WebContext context, ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { ApplicationForm appForm = (ApplicationForm)actionForm; ApplicationConfigManager.deleteApplication(appForm.getApplicationId()); UserActivityLogger.getInstance().logActivity( context.getUser().getUsername(), "Deleted application with ID "+appForm.getApplicationId()); return mapping.findForward(Forwards.SUCCESS); } |
"Deleted application with ID "+appForm.getApplicationId()); | "Deleted application "+"\""+config.getName()+"\""); | public ActionForward execute(WebContext context, ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { ApplicationForm appForm = (ApplicationForm)actionForm; ApplicationConfigManager.deleteApplication(appForm.getApplicationId()); UserActivityLogger.getInstance().logActivity( context.getUser().getUsername(), "Deleted application with ID "+appForm.getApplicationId()); return mapping.findForward(Forwards.SUCCESS); } |
roles.add(new Role(userForm.getRole())); | String[] rolesString = userForm.getRole(); for(int ctr=0; ctr < rolesString.length; ctr++){ roles.add(new Role(rolesString[ctr])); } | private User buildUser(ActionForm form){ UserForm userForm = (UserForm)form; List<Role> roles = new ArrayList<Role>(1); roles.add(new Role(userForm.getRole())); User user = new User(userForm.getUsername(), Crypto.hash(userForm.getPassword()), roles, userForm.getStatus(), 0); return user; } |
String aclName) | String aclName, String targetName) | public static void checkAccess(ServiceContext context, String aclName) throws UnAuthorizedAccessException { checkAccess(context, aclName, null); } |
checkAccess(context, aclName, null); | if(!canAccess(context, aclName, targetName)){ throw new UnAuthorizedAccessException("Insufficient Privileges"); } | public static void checkAccess(ServiceContext context, String aclName) throws UnAuthorizedAccessException { checkAccess(context, aclName, null); } |
if(metaAppConfig.isDisplayPassword() && config.getPassword() != null) | if(metaAppConfig.isDisplayPassword() && config.getPassword() != null && config.getPassword().length()>0) | public ActionForward execute(WebContext context, ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) { ApplicationConfig config = context.getApplicationConfig(); ApplicationForm appForm = (ApplicationForm)actionForm; ModuleConfig moduleConfig = ModuleRegistry.getModule(config.getType()); MetaApplicationConfig metaAppConfig = moduleConfig.getMetaApplicationConfig(); /* populate the form */ appForm.setApplicationId(config.getApplicationId()); appForm.setName(config.getName()); appForm.setType(config.getType()); if(metaAppConfig.isDisplayHost()) appForm.setHost(config.getHost()); if(metaAppConfig.isDisplayPort()) appForm.setPort(String.valueOf(config.getPort())); if(metaAppConfig.isDisplayUsername()) appForm.setUsername(config.getUsername()); if(metaAppConfig.isDisplayPassword() && config.getPassword() != null) appForm.setPassword(ApplicationForm.FORM_PASSWORD); request.setAttribute(RequestAttributes.META_APP_CONFIG, metaAppConfig); return mapping.findForward(Forwards.SUCCESS); } |
owner.addPropertyChangeListener("zoom", new ZoomFixer()); | public PlayPenContentPane(PlayPen owner) { this.owner = owner; playPenComponentEventPassthrough = new PlayPenComponentEventPassthrough(); } |
|
else { throw new JellyException( "The " + getTagName() + " tag must be nested within a tag which maps to a bean property" ); } return null; | throw new JellyException("The " + getTagName() + " tag must be nested within a tag which maps to a BeanSource implementor"); | protected Object newInstance(Class theClass, Map attributes, XMLOutput output) throws Exception { Object parentObject = getParentObject(); if (parentObject != null) { // now lets try call the create method... Class parentClass = parentObject.getClass(); Method method = findCreateMethod(parentClass); if (method != null) { try { return method.invoke(parentObject, EMPTY_ARGS); } catch (Exception e) { throw new JellyException( "failed to invoke method: " + method + " on bean: " + parentObject + " reason: " + e, e ); } } } else { throw new JellyException( "The " + getTagName() + " tag must be nested within a tag which maps to a bean property" ); } return null; } |
curDb.addVolume( extVol ); | try { curDb.addVolume( extVol ); } catch (PhotovaultException ex) { ex.printStackTrace(); } | public void setUp() { try { volumeRoot = File.createTempFile( "photovaultVolumeTest", "" ); volumeRoot.delete(); volumeRoot.mkdir(); extvolRoot = File.createTempFile( "photovaultVolumeTestExt", "" ); extvolRoot.delete(); extvolRoot.mkdir(); } catch (IOException ex) { ex.printStackTrace(); } volume = new Volume( "testVolume", volumeRoot.getAbsolutePath() ); extVol = new ExternalVolume( "extVolume", extvolRoot.getAbsolutePath() ); PhotovaultSettings settings = PhotovaultSettings.getSettings(); PVDatabase curDb = settings.getCurrentDatabase(); curDb.addVolume( extVol ); } |
getBody().run(context, output); | invokeBody(output); | public void doTag(XMLOutput output) throws Exception { // evaluate body as it may contain a <destination> or message tag getBody().run(context, output); Message message = getMessage(); if ( message == null ) { throw new JellyException( "No message specified. Either specify a 'message' attribute or use a nested <jms:message> tag" ); } Destination destination = getDestination(); if ( destination == null ) { throw new JellyException( "No destination specified. Either specify a 'destination' attribute or use a nested <jms:destination> tag" ); } getConnection().send( destination, message ); } |
return n.getRatios(); | if(this.countsOrRatios == SHOW_COUNTS) { return n.getCounts(); } else if(this.countsOrRatios == SHOW_RATIOS) { return n.getRatios(); } | public Object getValueAt(Object node, int column) { HaplotypeAssociationNode n = (HaplotypeAssociationNode) node; switch (column){ case 0: return n.getName(); case 1: return n.getFreq(); case 2: return n.getRatios(); case 3: return n.getChiSq(); case 4: return n.getPVal(); } return null; } |
int mid = rare * (2 * diplotypes - rare) / (2 * diplotypes); | int mid = (int)((double)rare * (double)(2 * diplotypes - rare) / (double)(2 * diplotypes)); | private double hwCalculate(int obsAA, int obsAB, int obsBB) throws PedFileException{ //Calculates exact two-sided hardy-weinberg p-value. Parameters //are number of genotypes, number of rare alleles observed and //number of heterozygotes observed. // // (c) 2003 Jan Wigginton, Goncalo Abecasis int diplotypes = obsAA + obsAB + obsBB; int rare = (obsAA*2) + obsAB; int hets = obsAB; //make sure "rare" allele is really the rare allele if (rare > diplotypes){ rare = 2*diplotypes-rare; } //make sure numbers aren't screwy if (hets > rare){ throw new PedFileException("HW test: " + hets + "heterozygotes but only " + rare + "rare alleles."); } double[] tailProbs = new double[rare+1]; for (int z = 0; z < tailProbs.length; z++){ tailProbs[z] = 0; } //start at midpoint int mid = rare * (2 * diplotypes - rare) / (2 * diplotypes); //check to ensure that midpoint and rare alleles have same parity if (((rare & 1) ^ (mid & 1)) != 0){ mid++; } int het = mid; int hom_r = (rare - mid) / 2; int hom_c = diplotypes - het - hom_r; //Calculate probability for each possible observed heterozygote //count up to a scaling constant, to avoid underflow and overflow tailProbs[mid] = 1.0; double sum = tailProbs[mid]; for (het = mid; het > 1; het -=2){ tailProbs[het-2] = (tailProbs[het] * het * (het-1.0))/(4.0*(hom_r + 1.0) * (hom_c + 1.0)); sum += tailProbs[het-2]; //2 fewer hets for next iteration -> add one rare and one common homozygote hom_r++; hom_c++; } het = mid; hom_r = (rare - mid) / 2; hom_c = diplotypes - het - hom_r; for (het = mid; het <= rare - 2; het += 2){ tailProbs[het+2] = (tailProbs[het] * 4.0 * hom_r * hom_c) / ((het+2.0)*(het+1.0)); sum += tailProbs[het+2]; //2 more hets for next iteration -> subtract one rare and one common homozygote hom_r--; hom_c--; } for (int z = 0; z < tailProbs.length; z++){ tailProbs[z] /= sum; } double top = tailProbs[hets]; for (int i = hets+1; i <= rare; i++){ top += tailProbs[i]; } double otherSide = tailProbs[hets]; for (int i = hets-1; i >= 0; i--){ otherSide += tailProbs[i]; } if (top > 0.5 && otherSide > 0.5){ return 1.0; }else{ if (top < otherSide){ return top * 2; }else{ return otherSide * 2; } } } |
return answer; } }; | return answer; } public String toString() { return super.toString() + "[expression:" + text + "]"; } }; | public Expression createExpression(final String text) throws Exception {/* org.apache.commons.jexl.Expression expr = org.apache.commons.jexl.ExpressionFactory.createExpression(text); if ( isSupportAntVariables() ) { expr.addPostResolver(new FlatResolver()); } return new JexlExpression( expr );*/ final Expression jexlExpression = new JexlExpression( org.apache.commons.jexl.ExpressionFactory.createExpression(text) ); if ( isSupportAntVariables() && isValidAntVariableName(text) ) { ExpressionSupport expr = new ExpressionSupport() { public Object evaluate(JellyContext context) { Object answer = jexlExpression.evaluate(context); if ( answer == null ) { answer = context.getVariable(text); } return answer; } }; return expr; } return jexlExpression; } |
public static void fitColumnWidth(JTable table, int colIndex) { fitColumnWidth(table, colIndex, -1); | public static void fitColumnWidth(JTable table, int colIndex, int padding) { fitColumnWidth(table, colIndex, -1, padding); | public static void fitColumnWidth(JTable table, int colIndex) { fitColumnWidth(table, colIndex, -1); } |
public static void fitColumnWidths(JTable table, int maxColumnWidth) { | public static void fitColumnWidths(JTable table, int maxColumnWidth, int padding) { | public static void fitColumnWidths(JTable table, int maxColumnWidth) { table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); for (int colIndex = 0; colIndex < table.getColumnCount(); colIndex++) { fitColumnWidth(table, colIndex, maxColumnWidth); } } |
fitColumnWidth(table, colIndex, maxColumnWidth); | fitColumnWidth(table, colIndex, maxColumnWidth, padding); | public static void fitColumnWidths(JTable table, int maxColumnWidth) { table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); for (int colIndex = 0; colIndex < table.getColumnCount(); colIndex++) { fitColumnWidth(table, colIndex, maxColumnWidth); } } |
tag.setContext(context); | try { tag.setContext(context); DynaTag dynaTag = (DynaTag) tag; for (Iterator iter = attributes.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String name = (String) entry.getKey(); Expression expression = (Expression) entry.getValue(); Object value = expression.evaluate(context); dynaTag.setAttribute(name, value); } | public void run(JellyContext context, XMLOutput output) throws Exception { if ( firstRun ) { firstRun = false; // lets see if we have a dynamic tag tag = findDynamicTag(context, (StaticTag) tag); } tag.setContext(context); DynaTag dynaTag = (DynaTag) tag; // ### probably compiling this to 2 arrays might be quicker and smaller for (Iterator iter = attributes.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String name = (String) entry.getKey(); Expression expression = (Expression) entry.getValue(); Object value = expression.evaluate(context); dynaTag.setAttribute(name, value); } runTag(output); } |
DynaTag dynaTag = (DynaTag) tag; for (Iterator iter = attributes.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String name = (String) entry.getKey(); Expression expression = (Expression) entry.getValue(); Object value = expression.evaluate(context); dynaTag.setAttribute(name, value); | tag.doTag(output); } catch (JellyException e) { handleException(e); | public void run(JellyContext context, XMLOutput output) throws Exception { if ( firstRun ) { firstRun = false; // lets see if we have a dynamic tag tag = findDynamicTag(context, (StaticTag) tag); } tag.setContext(context); DynaTag dynaTag = (DynaTag) tag; // ### probably compiling this to 2 arrays might be quicker and smaller for (Iterator iter = attributes.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String name = (String) entry.getKey(); Expression expression = (Expression) entry.getValue(); Object value = expression.evaluate(context); dynaTag.setAttribute(name, value); } runTag(output); } |
runTag(output); | catch (Exception e) { handleException(e); } | public void run(JellyContext context, XMLOutput output) throws Exception { if ( firstRun ) { firstRun = false; // lets see if we have a dynamic tag tag = findDynamicTag(context, (StaticTag) tag); } tag.setContext(context); DynaTag dynaTag = (DynaTag) tag; // ### probably compiling this to 2 arrays might be quicker and smaller for (Iterator iter = attributes.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String name = (String) entry.getKey(); Expression expression = (Expression) entry.getValue(); Object value = expression.evaluate(context); dynaTag.setAttribute(name, value); } runTag(output); } |
else if ( value instanceof DynaTag ) { return (DynaTag) value; | else if ( value instanceof TagFactory ) { TagFactory factory = (TagFactory) value; return factory.createTag(); | public Tag createTag(String name) throws Exception { Object value = templates.get(name); if ( value instanceof Script ) { Script template = (Script) value; return new DynamicTag(template); } else if ( value instanceof DynaTag ) { return (DynaTag) value; } return null; } |
finally { if ( ! context.isCacheTags() ) { clearTag(); } } | public void run(JellyContext context, XMLOutput output) throws Exception { try { Tag tag = getTag(); if ( tag == null ) { return; } tag.setContext(context); if ( tag instanceof DynaTag ) { DynaTag dynaTag = (DynaTag) tag; // ### probably compiling this to 2 arrays might be quicker and smaller for (Iterator iter = attributes.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String name = (String) entry.getKey(); Expression expression = (Expression) entry.getValue(); Object value = expression.evaluate(context); dynaTag.setAttribute(name, value); } } else { // treat the tag as a bean DynaBean dynaBean = new ConvertingWrapDynaBean( tag ); for (Iterator iter = attributes.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String name = (String) entry.getKey(); Expression expression = (Expression) entry.getValue(); Object value = expression.evaluate(context); dynaBean.set(name, value); } } tag.doTag(output); } catch (JellyException e) { handleException(e); } catch (Exception e) { handleException(e); } finally { if ( ! context.isCacheTags() ) { clearTag(); } } } |
|
TablePane tp = new TablePane((SQLTable) objects[i]); c.add(tp, dtde.getLocation()); tp.revalidate(); | c.addTable((SQLTable) objects[i], dtde.getLocation()); } else if (objects[i] instanceof SQLSchema) { c.addSchema((SQLSchema) objects[i], dtde.getLocation()); } else { logger.warn("Unsupported object in multi-item drop: " +objects[i]); | public void drop(DropTargetDropEvent dtde) { Transferable t = dtde.getTransferable(); PlayPen c = (PlayPen) dtde.getDropTargetContext().getComponent(); DataFlavor importFlavor = bestImportFlavor(c, t.getTransferDataFlavors()); if (importFlavor == null) { dtde.rejectDrop(); } else { try { Object someData = t.getTransferData(importFlavor); logger.debug("MyJTreeTransferHandler.importData: got object of type "+someData.getClass().getName()); if (someData instanceof SQLTable) { dtde.acceptDrop(DnDConstants.ACTION_COPY); c.addTable((SQLTable) someData, dtde.getLocation()); dtde.dropComplete(true); return; } else if (someData instanceof SQLSchema) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLSchema sourceSchema = (SQLSchema) someData; c.addSchema(sourceSchema, dtde.getLocation()); dtde.dropComplete(true); return; } else if (someData instanceof SQLCatalog) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLCatalog sourceCatalog = (SQLCatalog) someData; Iterator cit = sourceCatalog.getChildren().iterator(); if (sourceCatalog.isSchemaContainer()) { while (cit.hasNext()) { SQLSchema sourceSchema = (SQLSchema) cit.next(); c.addSchema(sourceSchema, dtde.getLocation()); } } else { while (cit.hasNext()) { SQLTable sourceTable = (SQLTable) cit.next(); c.addTable(sourceTable, dtde.getLocation()); } } dtde.dropComplete(true); return; } else if (someData instanceof SQLColumn) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLColumn column = (SQLColumn) someData; JLabel colName = new JLabel(column.getColumnName()); colName.setSize(colName.getPreferredSize()); c.add(colName, dtde.getLocation()); logger.debug("Added "+column.getColumnName()+" to playpen (temporary, only for testing)"); colName.revalidate(); dtde.dropComplete(true); return; } else if (someData instanceof SQLObject[]) { // needs work (should use addSchema()) dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLObject[] objects = (SQLObject[]) someData; for (int i = 0; i < objects.length; i++) { if (objects[i] instanceof SQLTable) { TablePane tp = new TablePane((SQLTable) objects[i]); c.add(tp, dtde.getLocation()); tp.revalidate(); } } dtde.dropComplete(true); return; } else { dtde.rejectDrop(); } } catch (UnsupportedFlavorException ufe) { ufe.printStackTrace(); dtde.rejectDrop(); } catch (IOException ioe) { ioe.printStackTrace(); dtde.rejectDrop(); } catch (InvalidDnDOperationException ex) { ex.printStackTrace(); dtde.rejectDrop(); } catch (ArchitectException ex) { ex.printStackTrace(); dtde.rejectDrop(); } } } |
public void setContext(JellyContext context) { | public void setContext(JellyContext context) throws Exception { | public void setContext(JellyContext context) { this.context = context; } |
if (Options.getAssocTest() == 1){ | if (Options.getAssocTest() == ASSOC_TRIO){ | public TDTPanel(PedFile pf) throws PedFileException{ if (Options.getAssocTest() == 1){ result = TDT.calcTrioTDT(pf); }else{ result = TDT.calcCCTDT(pf); } tableColumnNames.add("#"); tableColumnNames.add("Name"); if (Options.getAssocTest() == 1){ tableColumnNames.add("Overtransmitted"); tableColumnNames.add("T:U"); }else{ tableColumnNames.add("Major Alleles"); tableColumnNames.add("Case, Control Ratios"); } tableColumnNames.add("Chi Squared"); tableColumnNames.add("p value"); refreshTable(); } |
if (Options.getAssocTest() != 1){ | if (Options.getAssocTest() != ASSOC_TRIO){ | public void refreshTable(){ this.removeAll(); Vector tableData = new Vector(); int numRes = Chromosome.getSize(); for (int i = 0; i < numRes; i++){ Vector tempVect = new Vector(); TDTResult currentResult = (TDTResult)result.get(Chromosome.realIndex[i]); tempVect.add(new Integer(Chromosome.realIndex[i]+1)); tempVect.add(currentResult.getName()); tempVect.add(currentResult.getOverTransmittedAllele(Options.getAssocTest())); tempVect.add(currentResult.getTURatio(Options.getAssocTest())); tempVect.add(new Double(currentResult.getChiSq(Options.getAssocTest()))); tempVect.add(currentResult.getPValue()); tableData.add(tempVect.clone()); } TDTTableModel tm = new TDTTableModel(tableColumnNames, tableData); table = new JTable(tm); table.getColumnModel().getColumn(0).setPreferredWidth(50); table.getColumnModel().getColumn(1).setPreferredWidth(100); if (Options.getAssocTest() != 1){ table.getColumnModel().getColumn(3).setPreferredWidth(160); } table.getColumnModel().getColumn(2).setPreferredWidth(100); JScrollPane tableScroller = new JScrollPane(table); add(tableScroller); } |
if (subResults.size() < 1) { | if (subResults.size() <= 1) { | public Result analyze(Filter<S> filter, List<OrderedProperty<S>> orderings) { if (!filter.isBound()) { // Strictly speaking, this is not required, but it detects the // mistake of not properly calling initialFilterValues. throw new IllegalArgumentException("Filter must be bound"); } List<IndexedQueryAnalyzer<S>.Result> subResults = splitIntoSubResults(filter, orderings); if (subResults.size() < 1) { // Total ordering not required. return new Result(subResults); } boolean canMutateOrderings = false; // If any orderings have an unspecified direction, switch to ASCENDING // or DESCENDING, depending on which is more popular. Then build new // sub-results. for (int pos = 0; pos < orderings.size(); pos++) { OrderedProperty<S> ordering = orderings.get(pos); if (ordering.getDirection() != Direction.UNSPECIFIED) { continue; } // Find out which direction is most popular for this property. Tally tally = new Tally(ordering.getChainedProperty()); for (IndexedQueryAnalyzer<S>.Result result : subResults) { tally.increment(findHandledDirection(result, ordering)); } if (!canMutateOrderings) { orderings = new ArrayList<OrderedProperty<S>>(orderings); canMutateOrderings = true; } orderings.set(pos, ordering.direction(tally.getBestDirection())); // Re-calc with specified direction. Only do one property at a time // since one simple change might alter the query plan. subResults = splitIntoSubResults(filter, orderings); if (subResults.size() < 1) { // Total ordering no longer required. return new Result(subResults); } } // Gather all the keys available. As ordering properties touch key // properties, they are removed from all key sets. When a key set size // reaches zero, total ordering has been achieved. List<Set<ChainedProperty<S>>> keys = getKeys(); // Check if current ordering is total. for (OrderedProperty<S> ordering : orderings) { ChainedProperty<S> property = ordering.getChainedProperty(); if (pruneKeys(keys, property)) { // Found a key which is fully covered, indicating total ordering. return new Result(subResults); } } // Create a super key which contains all the properties required for // total ordering. The goal here is to append these properties to the // ordering in a fashion that takes advantage of each index's natural // ordering. This in turn should cause any sort operation to operate // over smaller groups. Smaller groups means smaller sort buffers. // Smaller sort buffers makes a merge sort happy. // Super key could be stored simply in a set, but a map makes it // convenient for tracking tallies. Map<ChainedProperty<S>, Tally> superKey = new LinkedHashMap<ChainedProperty<S>, Tally>(); for (Set<ChainedProperty<S>> key : keys) { for (ChainedProperty<S> property : key) { superKey.put(property, new Tally(property)); } } // Prepare to augment orderings to ensure a total ordering. if (!canMutateOrderings) { orderings = new ArrayList<OrderedProperty<S>>(orderings); canMutateOrderings = true; } // Keep looping until total ordering achieved. while (true) { // For each ordering score, find the next free property. If // property is in the super key increment a tally associated with // property direction. Choose the property with the best tally and // augment the orderings with it and create new sub-results. // Remove the property from the super key and the key set. If any // key is now fully covered, a total ordering has been achieved. for (IndexedQueryAnalyzer<S>.Result result : subResults) { OrderingScore<S> score = result.getCompositeScore().getOrderingScore(); List<OrderedProperty<S>> free = score.getFreeOrderings(); if (free.size() > 0) { OrderedProperty<S> prop = free.get(0); ChainedProperty<S> chainedProp = prop.getChainedProperty(); Tally tally = superKey.get(chainedProp); if (tally != null) { tally.increment(prop.getDirection()); } } } Tally best = bestTally(superKey.values()); ChainedProperty<S> bestProperty = best.getProperty(); // Now augment the orderings and create new sub-results. orderings.add(OrderedProperty.get(bestProperty, best.getBestDirection())); subResults = splitIntoSubResults(filter, orderings); if (subResults.size() < 1) { // Total ordering no longer required. break; } // Remove property from super key and key set... superKey.remove(bestProperty); if (superKey.size() == 0) { break; } if (pruneKeys(keys, bestProperty)) { break; } // Clear the tallies for the next run. for (Tally tally : superKey.values()) { tally.clear(); } } return new Result(subResults); } |
if (decision == JOptionPane.NO_OPTION) { | if (decision != JOptionPane.YES_OPTION ) { | public void actionPerformed(ActionEvent evt) { logger.debug("delete action detected!"); logger.debug("ACTION COMMAND: " + evt.getActionCommand()); if (evt.getActionCommand().equals(ArchitectSwingConstants.ACTION_COMMAND_SRC_PLAYPEN)) { logger.debug("delete action came from playpen"); List items = pp.getSelectedItems(); if (items.size() < 1) { JOptionPane.showMessageDialog(pp, "No items to delete!"); } if (items.size() > 1) { // count how many relationships and tables there are int tCount = pp.getSelectedTables().size(); int rCount = pp.getSelectedRelationShips().size(); int decision = JOptionPane.showConfirmDialog(pp, "Are you sure you want to delete these " +tCount+" tables and "+rCount+" relationships?", "Multiple Delete", JOptionPane.YES_NO_OPTION); if (decision == JOptionPane.NO_OPTION) { return; } } else { // single selection, so we might be deleting columns boolean deletingColumns = false; Selectable item = (Selectable) items.get(0); if (item instanceof TablePane) { // make a list of columns to delete TablePane tp = (TablePane) item; List<SQLColumn> selectedColumns = null; try { selectedColumns = tp.getSelectedColumns(); if (selectedColumns.size() > 0) { // don't fall through into Table/Relationship delete logic deletingColumns = true; } } catch (ArchitectException ae) { JOptionPane.showMessageDialog(pp, ae.getMessage()); return; } try { pp.startCompoundEdit("Starting multi-select"); // now, delete the columns Iterator it2 = selectedColumns.iterator(); while (it2.hasNext()) { SQLColumn sc = (SQLColumn) it2.next(); try { tp.getModel().removeColumn(sc); } catch (LockedColumnException ex) { int decision = JOptionPane.showConfirmDialog(pp, "Could not delete the column " + sc.getName() + " because it is part of\n" + "the relationship \""+ex.getLockingRelationship()+"\".\n\n" + "Continue deleting remaining selected columns?", "Column is Locked", JOptionPane.YES_NO_OPTION); if (decision == JOptionPane.NO_OPTION) { return; } } catch (ArchitectException e) { logger.error("Unexpected exception encountered when attempting to delete column '"+ sc+"' of table '"+sc.getParentTable()+"'"); ASUtils.showExceptionDialog(pp, "Encountered a Problem Deleting the column", e); } } } finally { pp.endCompoundEdit("Ending multi-select"); } } if (deletingColumns) { // we tried to delete 1 or more columns, so don't try to delete the table return; } } pp.startCompoundEdit("Starting multi-select"); try { // items.size() > 0, user has OK'ed the delete Iterator it = items.iterator(); while (it.hasNext()) { Selectable item = (Selectable) it.next(); logger.debug("next item for delete is: " + item.getClass().getName()); if (item instanceof TablePane) { TablePane tp = (TablePane) item; tp.setSelected(false); pp.getDatabase().removeChild(tp.getModel()); if (logger.isDebugEnabled()) { logger.debug("removing element from tableNames set: " + tp.getModel().getName()); logger.debug("before delete: " + pp.getTablePanes().toArray()); } pp.getTablePanes().remove(tp.getModel().getName().toLowerCase()); if (logger.isDebugEnabled()) { logger.debug("after delete: " + pp.getTablePanes().toArray()); } } else if (item instanceof Relationship) { Relationship r = (Relationship) item; logger.debug("trying to delete relationship " + r); r.setSelected(false); SQLRelationship sr = r.getModel(); sr.getPkTable().removeExportedKey(sr); } else { JOptionPane.showMessageDialog((JComponent) item, "The selected item type is not recognised"); } } } finally { pp.endCompoundEdit("Ending multi-select"); } } else if (evt.getActionCommand().equals(ArchitectSwingConstants.ACTION_COMMAND_SRC_DBTREE)) { logger.debug("delete action came from dbtree"); TreePath [] selections = dbt.getSelectionPaths(); if (selections.length > 1) { int decision = JOptionPane.showConfirmDialog(dbt, "Are you sure you want to delete the " +selections.length+" selected items?", "Multiple Delete", JOptionPane.YES_NO_OPTION); if (decision == JOptionPane.NO_OPTION) { return; } } pp.startCompoundEdit("Starting multi-select"); try { // FIXME: parts of the following code look like they were cut'n'pasted from above... PURE EVIL! Iterator it = Arrays.asList(selections).iterator(); while (it.hasNext()) { TreePath tp = (TreePath) it.next(); SQLObject so = (SQLObject) tp.getLastPathComponent(); if (so instanceof SQLTable) { SQLTable st = (SQLTable) so; pp.getDatabase().removeChild(st); pp.getTablePanes().remove(st.getName().toLowerCase()); } else if (so instanceof SQLColumn) { SQLColumn sc = (SQLColumn)so; SQLTable st = sc.getParentTable(); try { st.removeColumn(sc); } catch (LockedColumnException ex) { int decision = JOptionPane.showConfirmDialog(dbt, "Could not delete the column " + sc.getName() + " because it is part of a relationship key. Continue" + " deleting of other selected items?", "Column is Locked", JOptionPane.YES_NO_OPTION); if (decision == JOptionPane.NO_OPTION) { return; } } catch (ArchitectException e) { logger.error("Unexpected exception encountered when attempting to delete column '"+ sc+"' of table '"+sc.getParentTable()+"'"); ASUtils.showExceptionDialog(pp, "Encountered a Problem Deleting the column", e); } } else if (so instanceof SQLRelationship) { SQLRelationship sr = (SQLRelationship) so; sr.getPkTable().removeExportedKey(sr); sr.getFkTable().removeImportedKey(sr); } else { JOptionPane.showMessageDialog(dbt, "The selected SQLObject type is not recognised: " + so.getClass().getName()); } } } finally { pp.endCompoundEdit("Ending multi-select"); } } else { logger.debug("delete action came from unknown source, so we do nothing."); // unknown action command source, do nothing } } |
registerWidgetTag(name, widgetClass, SWT.DEFAULT); | registerWidgetTag(name, widgetClass, SWT.NULL); | protected void registerWidgetTag(String name, Class widgetClass) { registerWidgetTag(name, widgetClass, SWT.DEFAULT); } |
final String userName = context.getUser().getName(); | public ActionForward execute(WebContext context, ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { Subject subject = context.getSubject(); final String userName = context.getUser().getName(); if(subject != null){ LoginContext loginContext = new LoginContext(AuthConstants.AUTH_CONFIG_INDEX, subject, new LoginCallbackHandler()); loginContext.logout(); context.removeSubject(); } UserActivityLogger.getInstance().logActivity(userName, userName+" logged out successfully"); return mapping.findForward(Forwards.SUCCESS); } |
|
UserActivityLogger.getInstance().logActivity(userName, userName+" logged out successfully"); | public ActionForward execute(WebContext context, ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { Subject subject = context.getSubject(); final String userName = context.getUser().getName(); if(subject != null){ LoginContext loginContext = new LoginContext(AuthConstants.AUTH_CONFIG_INDEX, subject, new LoginCallbackHandler()); loginContext.logout(); context.removeSubject(); } UserActivityLogger.getInstance().logActivity(userName, userName+" logged out successfully"); return mapping.findForward(Forwards.SUCCESS); } |
|
fileScanner.setProject(AntTagLibrary.getProject(context)); | public void doTag(XMLOutput output) throws Exception { fileScanner.clear(); // run the body first to configure the task via nested invokeBody(output); // output the fileScanner if ( var == null ) { throw new MissingAttributeException( "var" ); } context.setVariable( var, fileScanner ); } |
|
}else if (!(populationArg.equalsIgnoreCase("CEU") || populationArg.equalsIgnoreCase("YRI") || populationArg.equalsIgnoreCase("HCB") || populationArg.equalsIgnoreCase("JPT"))){ die("-phasedhapmapdl requires a population specification of CEU, YRI, HCB, or JPT"); | }else if (!(populationArg.equalsIgnoreCase("CEU") || populationArg.equalsIgnoreCase("YRI") || populationArg.equalsIgnoreCase("CHB+JPT"))){ die("-phasedhapmapdl requires a population specification of CEU, YRI, or CHB+JPT"); | private void argHandler(String[] args){ argHandlerMessages = new Vector(); int maxDistance = -1; //this means that user didn't specify any output type if it doesn't get changed below blockOutputType = -1; double hapThresh = -1; double minimumMAF=-1; double spacingThresh = -1; double minimumGenoPercent = -1; double hwCutoff = -1; double missingCutoff = -1; int maxMendel = -1; boolean assocTDT = false; boolean assocCC = false; permutationCount = 0; tagging = Tagger.NONE; maxNumTags = Tagger.DEFAULT_MAXNUMTAGS; findTags = true; double cutHighCI = -1; double cutLowCI = -1; double mafThresh = -1; double recHighCI = -1; double informFrac = -1; double fourGameteCutoff = -1; double spineDP = -1; for(int i =0; i < args.length; i++) { if(args[i].equalsIgnoreCase("-help") || args[i].equalsIgnoreCase("-h")) { System.out.println(HELP_OUTPUT); System.exit(0); } else if(args[i].equalsIgnoreCase("-n") || args[i].equalsIgnoreCase("-nogui")) { nogui = true; } else if(args[i].equalsIgnoreCase("-p") || args[i].equalsIgnoreCase("-pedfile")) { i++; if( i>=args.length || (args[i].charAt(0) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(pedFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last pedfile listed will be used"); } pedFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-pcloadletter")){ die("PC LOADLETTER?! What the fuck does that mean?!"); } else if (args[i].equalsIgnoreCase("-skipcheck") || args[i].equalsIgnoreCase("--skipcheck")){ skipCheck = true; } else if (args[i].equalsIgnoreCase("-excludeMarkers")){ i++; if(i>=args.length || (args[i].charAt(0) == '-')){ die("-excludeMarkers requires a list of markers"); } else { StringTokenizer str = new StringTokenizer(args[i],","); try { StringBuffer sb = new StringBuffer(); if (!quietMode) sb.append("Excluding markers: "); while(str.hasMoreTokens()) { String token = str.nextToken(); if(token.indexOf("..") != -1) { int lastIndex = token.indexOf(".."); int rangeStart = Integer.parseInt(token.substring(0,lastIndex)); int rangeEnd = Integer.parseInt(token.substring(lastIndex+2,token.length())); for(int j=rangeStart;j<=rangeEnd;j++) { if (!quietMode) sb.append(j+" "); excludedMarkers.add(new Integer(j)); } } else { if (!quietMode) sb.append(token+" "); excludedMarkers.add(new Integer(token)); } } if (!quietMode) argHandlerMessages.add(sb.toString()); } catch(NumberFormatException nfe) { die("-excludeMarkers argument should be of the format: 1,3,5..8,12"); } } } else if(args[i].equalsIgnoreCase("-ha") || args[i].equalsIgnoreCase("-l") || args[i].equalsIgnoreCase("-haps")) { i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(hapsFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last haps file listed will be used"); } hapsFileName = args[i]; } } else if(args[i].equalsIgnoreCase("-i") || args[i].equalsIgnoreCase("-info")) { i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(infoFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last info file listed will be used"); } infoFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-a") || args[i].equalsIgnoreCase("-hapmap")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(hapmapFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last hapmap file listed will be used"); } hapmapFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-phasedhmpdata")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(phasedhmpdataFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last phased hapmap data file listed will be used"); } phasedhmpdataFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-phasedhmpsample")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(phasedhmpsampleFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last phased hapmap sample file listed will be used"); } phasedhmpsampleFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-phasedhmplegend")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(phasedhmplegendFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last phased hapmap legend file listed will be used"); } phasedhmplegendFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-phasedhapmapdl")){ phasedhapmapDownload = true; } else if (args[i].equalsIgnoreCase("-plink")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(plinkFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last PLINK file listed will be used"); } plinkFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-map")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(plinkFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last map file listed will be used"); } mapFileName = args[i]; } } else if(args[i].equalsIgnoreCase("-k") || args[i].equalsIgnoreCase("-blocks")) { i++; if (!(i>=args.length) && !((args[i].charAt(0)) == '-')){ blockFileName = args[i]; blockOutputType = BLOX_CUSTOM; }else{ die(args[i-1] + " requires a filename"); } } else if (args[i].equalsIgnoreCase("-png")){ outputPNG = true; } else if (args[i].equalsIgnoreCase("-smallpng") || args[i].equalsIgnoreCase("-compressedPNG")){ outputCompressedPNG = true; } else if (args[i].equalsIgnoreCase("-track")){ i++; if (!(i>=args.length) && !((args[i].charAt(0)) == '-')){ trackFileName = args[i]; }else{ die("-track requires a filename"); } } else if(args[i].equalsIgnoreCase("-o") || args[i].equalsIgnoreCase("-output") || args[i].equalsIgnoreCase("-blockoutput")) { i++; if(!(i>=args.length) && !((args[i].charAt(0)) == '-')){ if(blockOutputType != -1){ die("Only one block output type argument is allowed."); } if(args[i].equalsIgnoreCase("SFS") || args[i].equalsIgnoreCase("GAB")){ blockOutputType = BLOX_GABRIEL; } else if(args[i].equalsIgnoreCase("GAM")){ blockOutputType = BLOX_4GAM; } else if(args[i].equalsIgnoreCase("MJD") || args[i].equalsIgnoreCase("SPI")){ blockOutputType = BLOX_SPINE; } else if(args[i].equalsIgnoreCase("ALL")) { blockOutputType = BLOX_ALL; } } else { //defaults to SFS output blockOutputType = BLOX_GABRIEL; i--; } } else if(args[i].equalsIgnoreCase("-d") || args[i].equalsIgnoreCase("--dprime") || args[i].equalsIgnoreCase("-dprime")) { outputDprime = true; } else if (args[i].equalsIgnoreCase("-c") || args[i].equalsIgnoreCase("-check")){ outputCheck = true; } else if (args[i].equalsIgnoreCase("-indcheck")){ individualCheck = true; } else if (args[i].equalsIgnoreCase("-mendel")){ mendel = true; } else if (args[i].equalsIgnoreCase("-malehets")){ malehets = true; } else if(args[i].equalsIgnoreCase("-m") || args[i].equalsIgnoreCase("-maxdistance")) { i++; maxDistance = getIntegerArg(args,i); } else if(args[i].equalsIgnoreCase("-b") || args[i].equalsIgnoreCase("-batch")) { //batch mode i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(batchFileName != null){ argHandlerMessages.add("multiple " + args[i-1] + " arguments found. only last batch file listed will be used"); } batchFileName = args[i]; } } else if(args[i].equalsIgnoreCase("-hapthresh")) { i++; hapThresh = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-spacing")) { i++; spacingThresh = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-minMAF")) { i++; minimumMAF = getDoubleArg(args,i,0,0.5); } else if(args[i].equalsIgnoreCase("-minGeno") || args[i].equalsIgnoreCase("-minGenoPercent")) { i++; minimumGenoPercent = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-hwcutoff")) { i++; hwCutoff = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-maxMendel") ) { i++; maxMendel = getIntegerArg(args,i); } else if(args[i].equalsIgnoreCase("-missingcutoff")) { i++; missingCutoff = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-assoctdt")) { assocTDT = true; } else if(args[i].equalsIgnoreCase("-assoccc")) { assocCC = true; } else if(args[i].equalsIgnoreCase("-randomcc")){ assocCC = true; randomizeAffection = true; } else if(args[i].equalsIgnoreCase("-ldcolorscheme")) { i++; if(!(i>=args.length) && !((args[i].charAt(0)) == '-')){ if(args[i].equalsIgnoreCase("default")){ Options.setLDColorScheme(STD_SCHEME); } else if(args[i].equalsIgnoreCase("RSQ")){ Options.setLDColorScheme(RSQ_SCHEME); } else if(args[i].equalsIgnoreCase("DPALT") ){ Options.setLDColorScheme(WMF_SCHEME); } else if(args[i].equalsIgnoreCase("GAB")) { Options.setLDColorScheme(GAB_SCHEME); } else if(args[i].equalsIgnoreCase("GAM")) { Options.setLDColorScheme(GAM_SCHEME); } else if(args[i].equalsIgnoreCase("GOLD")) { Options.setLDColorScheme(GOLD_SCHEME); } } else { //defaults to STD color scheme Options.setLDColorScheme(STD_SCHEME); i--; } } else if(args[i].equalsIgnoreCase("-blockCutHighCI")) { i++; cutHighCI = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-blockCutLowCI")) { i++; cutLowCI = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-blockMafThresh")) { i++; mafThresh = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-blockRecHighCI")) { i++; recHighCI = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-blockInformFrac")) { i++; informFrac = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-block4GamCut")) { i++; fourGameteCutoff = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-blockSpineDP")) { i++; spineDP = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-permtests")) { i++; doPermutationTest = true; permutationCount = getIntegerArg(args,i); } else if(args[i].equalsIgnoreCase("-customassoc")) { i++; if (!(i>=args.length) && !((args[i].charAt(0)) == '-')){ customAssocTestsFileName = args[i]; }else{ die(args[i-1] + " requires a filename"); } } else if(args[i].equalsIgnoreCase("-aggressiveTagging")) { tagging = Tagger.AGGRESSIVE_TRIPLE; } else if (args[i].equalsIgnoreCase("-pairwiseTagging")){ tagging = Tagger.PAIRWISE_ONLY; } else if (args[i].equalsIgnoreCase("-printalltags")){ Options.setPrintAllTags(true); } else if(args[i].equalsIgnoreCase("-maxNumTags")){ i++; maxNumTags = getIntegerArg(args,i); } else if(args[i].equalsIgnoreCase("-tagrSqCutoff")) { i++; tagRSquaredCutOff = getDoubleArg(args,i,0,1); } else if (args[i].equalsIgnoreCase("-dontaddtags")){ findTags = false; } else if(args[i].equalsIgnoreCase("-tagLODCutoff")) { i++; Options.setTaggerLODCutoff(getDoubleArg(args,i,0,100000)); } else if(args[i].equalsIgnoreCase("-includeTags")) { i++; if(i>=args.length || args[i].charAt(0) == '-') { die(args[i-1] + " requires a list of marker names."); } StringTokenizer str = new StringTokenizer(args[i],","); forceIncludeTags = new Vector(); while(str.hasMoreTokens()) { forceIncludeTags.add(str.nextToken()); } } else if (args[i].equalsIgnoreCase("-includeTagsFile")) { i++; if(!(i>=args.length) && !(args[i].charAt(0) == '-')) { forceIncludeFileName =args[i]; }else { die(args[i-1] + " requires a filename"); } } else if(args[i].equalsIgnoreCase("-excludeTags")) { i++; if(i>=args.length || args[i].charAt(0) == '-') { die("-excludeTags requires a list of marker names."); } StringTokenizer str = new StringTokenizer(args[i],","); forceExcludeTags = new Vector(); while(str.hasMoreTokens()) { forceExcludeTags.add(str.nextToken()); } } else if (args[i].equalsIgnoreCase("-excludeTagsFile")) { i++; if(!(i>=args.length) && !(args[i].charAt(0) == '-')) { forceExcludeFileName =args[i]; }else { die(args[i-1] + " requires a filename"); } } else if (args[i].equalsIgnoreCase("-captureAlleles")){ i++; if(!(i>=args.length) && !(args[i].charAt(0) == '-')) { captureAllelesFileName =args[i]; }else { die(args[i-1] + " requires a filename"); } } else if (args[i].equalsIgnoreCase("-designScores")){ i++; if(!(i>=args.length) && !(args[i].charAt(0) == '-')) { designScoresFileName =args[i]; }else { die(args[i-1] + " requires a filename"); } } else if (args[i].equalsIgnoreCase("-mintagdistance")){ i++; minTagDistance = args[i]; } else if(args[i].equalsIgnoreCase("-chromosome") || args[i].equalsIgnoreCase("-chr")) { i++; if(!(i>=args.length) && !(args[i].charAt(0) == '-')) { chromosomeArg =args[i]; }else { die(args[i-1] + " requires a chromosome name"); } if(!(chromosomeArg.equalsIgnoreCase("x"))){ try{ if (Integer.parseInt(chromosomeArg) > 22){ die("-chromosome requires a chromsome name of 1-22 or X"); } }catch(NumberFormatException nfe){ die("-chromosome requires a chromsome name of 1-22 or X"); } } } else if(args[i].equalsIgnoreCase("-population")){ i++; if(!(i>=args.length) && !(args[i].charAt(0)== '-')) { populationArg = args[i]; }else { die(args[i-1] + "requires a population name"); } } else if(args[i].equalsIgnoreCase("-startpos")){ i++; startPos = args[i]; } else if(args[i].equalsIgnoreCase("-endPos")){ i++; endPos = args[i]; } else if(args[i].equalsIgnoreCase("-q") || args[i].equalsIgnoreCase("-quiet")) { quietMode = true; } else if(args[i].equalsIgnoreCase("-gzip")){ Options.setGzip(true); } else { die("invalid parameter specified: " + args[i]); } } int countOptions = 0; if(pedFileName != null) { countOptions++; } if(hapsFileName != null) { countOptions++; } if(hapmapFileName != null) { countOptions++; } if(phasedhmpdataFileName != null) { countOptions++; if(phasedhmpsampleFileName == null){ die("You must specify a sample file for phased hapmap input."); }else if(phasedhmplegendFileName == null){ die("You must specify a legend file for phased hapmap input."); } } if(phasedhapmapDownload) { countOptions++; } if(plinkFileName != null){ countOptions++; if(mapFileName == null){ die("You must specify a map file for plink format input."); } } if(batchFileName != null) { countOptions++; } if(countOptions > 1) { die("Only one genotype input file may be specified on the command line."); } else if(countOptions == 0 && nogui) { die("You must specify a genotype input file."); } //mess with vars, set defaults, etc if(skipCheck && !quietMode) { argHandlerMessages.add("Skipping genotype file check"); } if(maxDistance == -1){ maxDistance = MAXDIST_DEFAULT; }else{ if (!quietMode) argHandlerMessages.add("Max LD comparison distance = " +maxDistance + "kb"); } Options.setMaxDistance(maxDistance); if(hapThresh != -1) { Options.setHaplotypeDisplayThreshold(hapThresh); if (!quietMode) argHandlerMessages.add("Haplotype display threshold = " + hapThresh); } if(minimumMAF != -1) { CheckData.mafCut = minimumMAF; if (!quietMode) argHandlerMessages.add("Minimum MAF = " + minimumMAF); } if(minimumGenoPercent != -1) { CheckData.failedGenoCut = (int)(minimumGenoPercent*100); if (!quietMode) argHandlerMessages.add("Minimum SNP genotype % = " + minimumGenoPercent); } if(hwCutoff != -1) { CheckData.hwCut = hwCutoff; if (!quietMode) argHandlerMessages.add("Hardy Weinberg equilibrium p-value cutoff = " + hwCutoff); } if(maxMendel != -1) { CheckData.numMendErrCut = maxMendel; if (!quietMode) argHandlerMessages.add("Maximum number of Mendel errors = "+maxMendel); } if(spacingThresh != -1) { Options.setSpacingThreshold(spacingThresh); if (!quietMode) argHandlerMessages.add("LD display spacing value = "+spacingThresh); } if(missingCutoff != -1) { Options.setMissingThreshold(missingCutoff); if (!quietMode) argHandlerMessages.add("Maximum amount of missing data allowed per individual = "+missingCutoff); } if(cutHighCI != -1) { FindBlocks.cutHighCI = cutHighCI; } if(cutLowCI != -1) { FindBlocks.cutLowCI = cutLowCI; } if(mafThresh != -1) { FindBlocks.mafThresh = mafThresh; } if(recHighCI != -1) { FindBlocks.recHighCI = recHighCI; } if(informFrac != -1) { FindBlocks.informFrac = informFrac; } if(fourGameteCutoff != -1) { FindBlocks.fourGameteCutoff = fourGameteCutoff; } if(spineDP != -1) { FindBlocks.spineDP = spineDP; } if(assocTDT) { Options.setAssocTest(ASSOC_TRIO); }else if(assocCC) { Options.setAssocTest(ASSOC_CC); } if (Options.getAssocTest() != ASSOC_NONE && infoFileName == null && hapmapFileName == null) { die("A marker info file must be specified when performing association tests."); } if(doPermutationTest) { if(!assocCC && !assocTDT) { die("An association test type must be specified for permutation tests to be performed."); } } if(customAssocTestsFileName != null) { if(!assocCC && !assocTDT) { die("An association test type must be specified when using a custom association test file."); } if(infoFileName == null) { die("A marker info file must be specified when using a custom association test file."); } } if(tagging != Tagger.NONE) { if(infoFileName == null && hapmapFileName == null && batchFileName == null && phasedhmpdataFileName == null && !phasedhapmapDownload) { die("A marker info file must be specified when tagging."); } if(forceExcludeTags == null) { forceExcludeTags = new Vector(); } else if (forceExcludeFileName != null) { die("-excludeTags and -excludeTagsFile cannot both be used"); } if(forceExcludeFileName != null) { File excludeFile = new File(forceExcludeFileName); forceExcludeTags = new Vector(); try { BufferedReader br = new BufferedReader(new FileReader(excludeFile)); String line; while((line = br.readLine()) != null) { if(line.length() > 0 && line.charAt(0) != '#'){ forceExcludeTags.add(line); } } }catch(IOException ioe) { die("An error occured while reading the file specified by -excludeTagsFile."); } } if(forceIncludeTags == null ) { forceIncludeTags = new Vector(); } else if (forceIncludeFileName != null) { die("-includeTags and -includeTagsFile cannot both be used"); } if(forceIncludeFileName != null) { File includeFile = new File(forceIncludeFileName); forceIncludeTags = new Vector(); try { BufferedReader br = new BufferedReader(new FileReader(includeFile)); String line; while((line = br.readLine()) != null) { if(line.length() > 0 && line.charAt(0) != '#'){ forceIncludeTags.add(line); } } }catch(IOException ioe) { die("An error occured while reading the file specified by -includeTagsFile."); } } if (captureAllelesFileName != null) { File captureFile = new File(captureAllelesFileName); captureAlleleTags = new Vector(); try { BufferedReader br = new BufferedReader(new FileReader(captureFile)); String line; while((line = br.readLine()) != null) { if(line.length() > 0 && line.charAt(0) != '#'){ line = line.trim(); captureAlleleTags.add(line); } } }catch(IOException ioe) { die("An error occured while reading the file specified by -captureAlleles."); } } if (designScoresFileName != null) { File designFile = new File(designScoresFileName); designScores = new Hashtable(1,1); try { BufferedReader br = new BufferedReader(new FileReader(designFile)); String line; while((line = br.readLine()) != null) { if(line.length() > 0 && line.charAt(0) != '#'){ StringTokenizer st = new StringTokenizer(line); String marker = st.nextToken(); Double score = new Double(st.nextToken()); designScores.put(marker,score); } } }catch(IOException ioe) { die("An error occured while reading the file specified by -captureAlleles."); } } if (minTagDistance != null) { try{ if (Integer.parseInt(minTagDistance) < 0){ die("minimum tag distance cannot be negative"); } }catch(NumberFormatException nfe){ die("minimum tag distance must be a positive integer"); } Options.setTaggerMinDistance(Integer.parseInt(minTagDistance)); } //check that there isn't any overlap between include/exclude lists Vector tempInclude = (Vector) forceIncludeTags.clone(); tempInclude.retainAll(forceExcludeTags); if(tempInclude.size() > 0) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < tempInclude.size(); i++) { String s = (String) tempInclude.elementAt(i); sb.append(s).append(","); } die("The following markers appear in both the include and exclude lists: " + sb.toString()); } if(tagRSquaredCutOff != -1) { Options.setTaggerRsqCutoff(tagRSquaredCutOff); } } else if(forceExcludeTags != null || forceIncludeTags != null || tagRSquaredCutOff != -1) { die("-tagrSqCutoff, -excludeTags, -excludeTagsFile, -includeTags and -includeTagsFile cannot be used without a tagging option"); } if(chromosomeArg != null && hapmapFileName != null) { argHandlerMessages.add("-chromosome flag ignored when loading hapmap file"); chromosomeArg = null; } if(chromosomeArg != null) { Chromosome.setDataChrom("chr" + chromosomeArg); } if (phasedhapmapDownload){ if (chromosomeArg == null){ die("-phasedhapmapdl requires a chromosome specification"); }else if (!(populationArg.equalsIgnoreCase("CEU") || populationArg.equalsIgnoreCase("YRI") || populationArg.equalsIgnoreCase("HCB") || populationArg.equalsIgnoreCase("JPT"))){ die("-phasedhapmapdl requires a population specification of CEU, YRI, HCB, or JPT"); } if (Integer.parseInt(chromosomeArg) < 1 && Integer.parseInt(chromosomeArg) > 22){ if (!(chromosomeArg.equalsIgnoreCase("x"))){ die("chromsome specification must be betweeen 1 and 22 or X"); } } try{ if (Integer.parseInt(startPos) > Integer.parseInt(endPos)){ die("end position must be greater then start position"); } }catch(NumberFormatException nfe){ die("start and end positions must be integer values"); } } } |
check = new JCheckBox(); | check = new ThreeStateCheckBox(); | public FolderNodeEditor( FolderTreePane treePane ) { super(); this.treePane = treePane; setLayout( new BoxLayout(this, BoxLayout.X_AXIS) ); check = new JCheckBox(); check.setBackground( Color.WHITE ); check.addActionListener( this ); name = new JLabel(); icon = new JLabel(); add( icon ); add( check ); add( name ); this.setBackground( Color.WHITE ); closedIcon = getIcon( "folder_icon.png"); expandedIcon = getIcon( "folder_expanded_icon.png" ); DefaultTreeCellRenderer dr = new DefaultTreeCellRenderer(); name.setFont( dr.getFont() ); selectedBkg = dr.getBackgroundSelectionColor(); nonSelectedBkg = dr.getBackgroundNonSelectionColor(); } |
setupFolder( treePane.getSelectedFolder() ); | public void actionPerformed(ActionEvent actionEvent) { if ( actionEvent.getSource() == check ) { // Add or remove photos from current node depending on checkbox state if ( check.isSelected() ) { treePane.addAllToSelectedFolder(); } else { treePane.removeAllFromSelectedFolder(); } } } |
|
boolean isSelected, boolean isExpanded, boolean isLeaf, int i) { | boolean isSelected, boolean isExpanded, boolean isLeaf, int row ) { | public Component getTreeCellEditorComponent(JTree jTree, Object object, boolean isSelected, boolean isExpanded, boolean isLeaf, int i) { node = (FolderNode) object; icon.setIcon( isExpanded ? expandedIcon : closedIcon ); PhotoFolder f = node.getFolder(); name.setText( f.getName() ); name.setBackground( isSelected ? selectedBkg : nonSelectedBkg ); check.setSelected( node.containsPhotos() ); return this; } |
icon.setIcon( isExpanded ? expandedIcon : closedIcon ); PhotoFolder f = node.getFolder(); name.setText( f.getName() ); name.setBackground( isSelected ? selectedBkg : nonSelectedBkg ); check.setSelected( node.containsPhotos() ); | setupComponent( jTree, node, isSelected, isExpanded, isLeaf, row, true ); | public Component getTreeCellEditorComponent(JTree jTree, Object object, boolean isSelected, boolean isExpanded, boolean isLeaf, int i) { node = (FolderNode) object; icon.setIcon( isExpanded ? expandedIcon : closedIcon ); PhotoFolder f = node.getFolder(); name.setText( f.getName() ); name.setBackground( isSelected ? selectedBkg : nonSelectedBkg ); check.setSelected( node.containsPhotos() ); return this; } |
icon.setIcon( isExpanded ? expandedIcon : closedIcon ); PhotoFolder f = node.getFolder(); name.setText( f.getName() ); name.setBackground( isSelected ? selectedBkg : nonSelectedBkg ); check.setSelected( node.containsPhotos() ); | setupComponent( jTree, node, isSelected, isExpanded, isLeaf, row, hasFocus ); | public Component getTreeCellRendererComponent(JTree jTree, Object object, boolean isSelected, boolean isExpanded, boolean isLeaf, int row, boolean hasFocus) { if (object instanceof FolderNode) { node = (FolderNode) object; icon.setIcon( isExpanded ? expandedIcon : closedIcon ); PhotoFolder f = node.getFolder(); name.setText( f.getName() ); name.setBackground( isSelected ? selectedBkg : nonSelectedBkg ); check.setSelected( node.containsPhotos() ); } return this; } |
log.debug( "createThumbnail for " + photo.getUid() ); | synchronized public void createThumbnail( PhotoInfo photo ) { this.photo = photo; notify(); } |
|
System.out.println( "Waiting..." ); | log.debug( "Waiting..." ); | public void run() { synchronized ( this ) { while ( true ) { try { System.out.println( "Waiting..." ); wait(); System.out.println( "Waited..." ); if ( photo != null ) { System.out.println( "Creating thumbnail..." ); Thumbnail thumb = photo.getThumbnail(); System.out.println( "Done!" ); final PhotoInfo lastPhoto = photo; photo = null; SwingUtilities.invokeLater( new Runnable() { public void run() { view.thumbnailCreated( lastPhoto ); } }); } } catch ( InterruptedException e ) {} } } } |
System.out.println( "Waited..." ); | log.debug( "Waited..." ); | public void run() { synchronized ( this ) { while ( true ) { try { System.out.println( "Waiting..." ); wait(); System.out.println( "Waited..." ); if ( photo != null ) { System.out.println( "Creating thumbnail..." ); Thumbnail thumb = photo.getThumbnail(); System.out.println( "Done!" ); final PhotoInfo lastPhoto = photo; photo = null; SwingUtilities.invokeLater( new Runnable() { public void run() { view.thumbnailCreated( lastPhoto ); } }); } } catch ( InterruptedException e ) {} } } } |
System.out.println( "Creating thumbnail..." ); | log.debug( "Creating thumbnail for " + photo.getUid() ); | public void run() { synchronized ( this ) { while ( true ) { try { System.out.println( "Waiting..." ); wait(); System.out.println( "Waited..." ); if ( photo != null ) { System.out.println( "Creating thumbnail..." ); Thumbnail thumb = photo.getThumbnail(); System.out.println( "Done!" ); final PhotoInfo lastPhoto = photo; photo = null; SwingUtilities.invokeLater( new Runnable() { public void run() { view.thumbnailCreated( lastPhoto ); } }); } } catch ( InterruptedException e ) {} } } } |
System.out.println( "Done!" ); | log.debug( "Done!" ); | public void run() { synchronized ( this ) { while ( true ) { try { System.out.println( "Waiting..." ); wait(); System.out.println( "Waited..." ); if ( photo != null ) { System.out.println( "Creating thumbnail..." ); Thumbnail thumb = photo.getThumbnail(); System.out.println( "Done!" ); final PhotoInfo lastPhoto = photo; photo = null; SwingUtilities.invokeLater( new Runnable() { public void run() { view.thumbnailCreated( lastPhoto ); } }); } } catch ( InterruptedException e ) {} } } } |
log.debug( "drawing new thumbnail for " + lastPhoto.getUid() ); | public void run() { synchronized ( this ) { while ( true ) { try { System.out.println( "Waiting..." ); wait(); System.out.println( "Waited..." ); if ( photo != null ) { System.out.println( "Creating thumbnail..." ); Thumbnail thumb = photo.getThumbnail(); System.out.println( "Done!" ); final PhotoInfo lastPhoto = photo; photo = null; SwingUtilities.invokeLater( new Runnable() { public void run() { view.thumbnailCreated( lastPhoto ); } }); } } catch ( InterruptedException e ) {} } } } |
|
log.debug( "drawing new thumbnail for " + lastPhoto.getUid() ); | public void run() { view.thumbnailCreated( lastPhoto ); } |
|
setupContents(); | setLayout(new BorderLayout()); dbDriverField = new JComboBox(getDriverClasses()); dbDriverField.insertItemAt("", 0); dbNameField = new JTextField(); JComponent[] fields = new JComponent[] {dbNameField, dbDriverField, dbUrlField = new JTextField(), dbUserField = new JTextField(), dbPassField = new JPasswordField()}; String[] labels = new String[] {"Connection Name", "JDBC Driver", "JDBC URL", "Username", "Password"}; char[] mnemonics = new char[] {'n', 'd', 'u', 'r', 'p'}; int[] widths = new int[] {30, 30, 40, 20, 20}; String[] tips = new String[] {"The name of this database", "The class name of the JDBC Driver", "Vendor-specific JDBC URL", "Username for this database", "Password for this database"}; dbDriverField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String t = getTemplateForDriver(dbDriverField.getSelectedItem().toString()); if (t == null) t = "jdbc:"; dbUrlField.setText(t); } }); form = new TextPanel(fields, labels, mnemonics, widths, tips); add(form, BorderLayout.CENTER); | public DBCSPanel() { setupContents(); } |
int i = dbNameField.getSelectedIndex(); if (!itemChanging && i >= 0) { logger.debug("Changing to index "+i+" of "+dbcsHistory); applyChanges(); setDbcs((DBConnectionSpec) dbcsHistory.get(i)); } else if (i == -1) { String newName = (String) dbNameField.getEditor().getItem(); i = dbcsHistory.indexOf(dbcs); dbNameHistory.set(i, newName); logger.debug("Set name at index "+i+" to "+newName); } | String t = getTemplateForDriver(dbDriverField.getSelectedItem().toString()); if (t == null) t = "jdbc:"; dbUrlField.setText(t); | public void actionPerformed(ActionEvent e) { int i = dbNameField.getSelectedIndex(); if (!itemChanging && i >= 0) { logger.debug("Changing to index "+i+" of "+dbcsHistory); applyChanges(); setDbcs((DBConnectionSpec) dbcsHistory.get(i)); } else if (i == -1) { String newName = (String) dbNameField.getEditor().getItem(); i = dbcsHistory.indexOf(dbcs); dbNameHistory.set(i, newName); logger.debug("Set name at index "+i+" to "+newName); } } |
int oldIndex = dbcsHistory.indexOf(dbcs); String name = (String) dbNameField.getItemAt(oldIndex); logger.debug("Changing name of DBCS at index "+oldIndex+" to "+name); | String name = dbNameField.getText(); | public void applyChanges() { int oldIndex = dbcsHistory.indexOf(dbcs); String name = (String) dbNameField.getItemAt(oldIndex); logger.debug("Changing name of DBCS at index "+oldIndex+" to "+name); dbcs.setName(name); dbcs.setDisplayName(name); dbcs.setDriverClass(dbDriverField.getSelectedItem().toString()); dbcs.setUrl(dbUrlField.getText()); dbcs.setUser(dbUserField.getText()); dbcs.setPass(new String(dbPassField.getPassword())); // completely defeats the purpose for JPasswordField.getText() being deprecated, but we're saving passwords to the config file so it hardly matters. } |
try { itemChanging = true; int index = dbcsHistory.indexOf(dbcs); if (index < 0) { logger.debug("Adding NEW dbcs to history list: "+dbcs); dbcsHistory.add(dbcs); dbNameField.addItem(dbcs.getDisplayName()); index = dbcsHistory.size() - 1; } dbNameField.setSelectedIndex(index); dbDriverField.removeItemAt(0); if (dbcs.getDriverClass() != null) { dbDriverField.insertItemAt(dbcs.getDriverClass(), 0); } else { dbDriverField.insertItemAt("", 0); } dbDriverField.setSelectedIndex(0); dbUrlField.setText(dbcs.getUrl()); dbUserField.setText(dbcs.getUser()); dbPassField.setText(dbcs.getPass()); this.dbcs = dbcs; } finally { itemChanging = false; | dbNameField.setText(dbcs.getName()); dbDriverField.removeItemAt(0); if (dbcs.getDriverClass() != null) { dbDriverField.insertItemAt(dbcs.getDriverClass(), 0); } else { dbDriverField.insertItemAt("", 0); | public void setDbcs(DBConnectionSpec dbcs) { try { itemChanging = true; int index = dbcsHistory.indexOf(dbcs); if (index < 0) { logger.debug("Adding NEW dbcs to history list: "+dbcs); dbcsHistory.add(dbcs); dbNameField.addItem(dbcs.getDisplayName()); index = dbcsHistory.size() - 1; } dbNameField.setSelectedIndex(index); dbDriverField.removeItemAt(0); if (dbcs.getDriverClass() != null) { dbDriverField.insertItemAt(dbcs.getDriverClass(), 0); } else { dbDriverField.insertItemAt("", 0); } dbDriverField.setSelectedIndex(0); dbUrlField.setText(dbcs.getUrl()); dbUserField.setText(dbcs.getUser()); dbPassField.setText(dbcs.getPass()); this.dbcs = dbcs; } finally { itemChanging = false; } } |
dbDriverField.setSelectedIndex(0); dbUrlField.setText(dbcs.getUrl()); dbUserField.setText(dbcs.getUser()); dbPassField.setText(dbcs.getPass()); this.dbcs = dbcs; | public void setDbcs(DBConnectionSpec dbcs) { try { itemChanging = true; int index = dbcsHistory.indexOf(dbcs); if (index < 0) { logger.debug("Adding NEW dbcs to history list: "+dbcs); dbcsHistory.add(dbcs); dbNameField.addItem(dbcs.getDisplayName()); index = dbcsHistory.size() - 1; } dbNameField.setSelectedIndex(index); dbDriverField.removeItemAt(0); if (dbcs.getDriverClass() != null) { dbDriverField.insertItemAt(dbcs.getDriverClass(), 0); } else { dbDriverField.insertItemAt("", 0); } dbDriverField.setSelectedIndex(0); dbUrlField.setText(dbcs.getUrl()); dbUserField.setText(dbcs.getUser()); dbPassField.setText(dbcs.getPass()); this.dbcs = dbcs; } finally { itemChanging = false; } } |
|
public Vector<Transaction> getTransactions(Date startDate, Date endDate){ Vector<Transaction> transactions = getTransactions(); Vector<Transaction> v = new Vector<Transaction>(); for (Transaction t : transactions) { if (t.getDate().after(startDate) && t.getDate().before(endDate)){ v.add(t); } } | public Vector<Transaction> getTransactions(){ Vector<Transaction> v = new Vector<Transaction>(getDataModel().getAllTransactions().getTransactions()); Collections.sort(v); | public Vector<Transaction> getTransactions(Date startDate, Date endDate){ Vector<Transaction> transactions = getTransactions(); Vector<Transaction> v = new Vector<Transaction>(); for (Transaction t : transactions) { if (t.getDate().after(startDate) && t.getDate().before(endDate)){ v.add(t); } } return v; } |
if(missingCutoff != -1) { Options.setMissingThreshold(missingCutoff); } | private void argHandler(String[] args){ int maxDistance = -1; //this means that user didn't specify any output type if it doesn't get changed below outputType = -1; double hapThresh = -1; double minimumMAF=-1; double spacingThresh = -1; double minimumGenoPercent = -1; double hwCutoff = -1; int maxMendel = -1; boolean assocTDT = false; boolean assocCC = false; for(int i =0; i < args.length; i++) { if(args[i].equalsIgnoreCase("-help") || args[i].equalsIgnoreCase("-h")) { System.out.println(HELP_OUTPUT); System.exit(0); } else if(args[i].equals("-n") || args[i].equals("-nogui")) { nogui = true; } else if(args[i].equals("-p") || args[i].equals("-pedfile")) { i++; if( i>=args.length || (args[i].charAt(0) == '-')){ System.out.println(args[i-1] + " requires a filename"); System.exit(1); } else{ if(pedFileName != null){ System.out.println("multiple "+args[i-1] + " arguments found. only last pedfile listed will be used"); } pedFileName = args[i]; } } else if (args[i].equals("-skipcheck") || args[i].equals("--skipcheck")){ skipCheck = true; } //todo: fix ignoremarkers /* else if (args[i].equals("--ignoremarkers")){ i++; if(i>=args.length || (args[i].charAt(0) == '-')){ System.out.println("--ignoremarkers requires a list of markers"); System.exit(1); } else { StringTokenizer str = new StringTokenizer(args[i],","); while(str.hasMoreTokens()) { ignoreMarkers.add(str.nextToken()); } } } */ else if(args[i].equals("-ha") || args[i].equals("-l") || args[i].equals("-haps")) { i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ System.out.println(args[i-1] + " requires a filename"); System.exit(1); } else{ if(hapsFileName != null){ System.out.println("multiple "+args[i-1] + " arguments found. only last haps file listed will be used"); } hapsFileName = args[i]; } } else if(args[i].equals("-i") || args[i].equals("-info")) { i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ System.out.println(args[i-1] + " requires a filename"); System.exit(1); } else{ if(infoFileName != null){ System.out.println("multiple "+args[i-1] + " arguments found. only last info file listed will be used"); } infoFileName = args[i]; } } else if (args[i].equals("-a") || args[i].equals("-hapmap")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ System.out.println(args[i-1] + " requires a filename"); System.exit(1); } else{ if(hapmapFileName != null){ System.out.println("multiple "+args[i-1] + " arguments found. only last hapmap file listed will be used"); } hapmapFileName = args[i]; } } else if(args[i].equals("-k") || args[i].equals("-blocks")) { i++; if (!(i>=args.length) && !((args[i].charAt(0)) == '-')){ blockFileName = args[i]; outputType = BLOX_CUSTOM; }else{ System.out.println(args[i-1] + " requires a filename"); System.exit(1); } } else if (args[i].equalsIgnoreCase("-png")){ outputPNG = true; } else if (args[i].equalsIgnoreCase("-smallpng") || args[i].equalsIgnoreCase("-compressedPNG")){ outputCompressedPNG = true; } else if (args[i].equals("-track")){ i++; if (!(i>=args.length) && !((args[i].charAt(0)) == '-')){ trackFileName = args[i]; }else{ System.out.println("-track requires a filename"); System.exit(1); } } else if(args[i].equals("-o") || args[i].equals("-output") || args[i].equalsIgnoreCase("-blockoutput")) { i++; if(!(i>=args.length) && !((args[i].charAt(0)) == '-')){ if(outputType != -1){ System.out.println("only one output argument is allowed"); System.exit(1); } if(args[i].equalsIgnoreCase("SFS") || args[i].equalsIgnoreCase("GAB")){ outputType = BLOX_GABRIEL; } else if(args[i].equalsIgnoreCase("GAM")){ outputType = BLOX_4GAM; } else if(args[i].equalsIgnoreCase("MJD") || args[i].equalsIgnoreCase("SPI")){ outputType = BLOX_SPINE; } else if(args[i].equalsIgnoreCase("ALL")) { outputType = BLOX_ALL; } } else { //defaults to SFS output outputType = BLOX_GABRIEL; i--; } } else if(args[i].equals("-d") || args[i].equals("--dprime") || args[i].equals("-dprime")) { outputDprime = true; } else if (args[i].equals("-c") || args[i].equals("-check")){ outputCheck = true; } else if(args[i].equals("-m") || args[i].equals("-maxdistance")) { i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ System.out.println(args[i-1] + " requires an integer argument"); System.exit(1); } else { if(maxDistance != -1){ System.out.println("only one "+args[i-1] + " argument allowed"); System.exit(1); } try { maxDistance = Integer.parseInt(args[i]); if(maxDistance<0){ System.out.println(args[i-1] + " argument must be a positive integer"); System.exit(1); } } catch(NumberFormatException nfe) { System.out.println(args[i-1] + " argument must be a positive integer"); System.exit(1); } } } else if(args[i].equals("-b") || args[i].equals("-batch")) { //batch mode i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ System.out.println(args[i-1] + " requires a filename"); System.exit(1); } else{ if(batchFileName != null){ System.out.println("multiple " + args[i-1] + " arguments found. only last batch file listed will be used"); } batchFileName = args[i]; } } else if(args[i].equals("-hapthresh")) { i++; hapThresh = getDoubleArg(args,i,"-hapthresh",0,1); } else if(args[i].equals("-spacing")) { i++; spacingThresh = getDoubleArg(args,i,"-spacing",0,1); } else if(args[i].equalsIgnoreCase("-minMAF")) { i++; minimumMAF = getDoubleArg(args,i,"-minMAF",0,1); } else if(args[i].equalsIgnoreCase("-minGenoPercent")) { i++; minimumGenoPercent = getDoubleArg(args,i,"-minGenoPercent",0,1); } else if(args[i].equalsIgnoreCase("-hwcutoff")) { i++; hwCutoff = getDoubleArg(args,i,"-hwcutoff",0,1); } else if(args[i].equals("-maxMendel") ) { i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ System.out.println("-maxMendel requires an integer argument"); System.exit(1); } else { try { maxMendel = Integer.parseInt(args[i]); if(maxMendel<0){ System.out.println("-maxMendel argument must be a positive integer"); System.exit(1); } } catch(NumberFormatException nfe) { System.out.println("-maxMendel argument must be a positive integer"); System.exit(1); } } } else if(args[i].equalsIgnoreCase("-assoctdt")) { assocTDT = true; } else if(args[i].equalsIgnoreCase("-assoccc")) { assocCC = true; } else if(args[i].equalsIgnoreCase("-ldcolorscheme")) { i++; if(!(i>=args.length) && !((args[i].charAt(0)) == '-')){ if(args[i].equalsIgnoreCase("default")){ Options.setLDColorScheme(STD_SCHEME); } else if(args[i].equalsIgnoreCase("RSQ")){ Options.setLDColorScheme(RSQ_SCHEME); } else if(args[i].equalsIgnoreCase("DPALT") ){ Options.setLDColorScheme(WMF_SCHEME); } else if(args[i].equalsIgnoreCase("GAB")) { Options.setLDColorScheme(GAB_SCHEME); } else if(args[i].equalsIgnoreCase("GAM")) { Options.setLDColorScheme(GAM_SCHEME); } } else { //defaults to STD color scheme Options.setLDColorScheme(STD_SCHEME); i--; } } else if(args[i].equals("-q") || args[i].equals("-quiet")) { quietMode = true; } else { System.out.println("invalid parameter specified: " + args[i]); } } int countOptions = 0; if(pedFileName != null) { countOptions++; } if(hapsFileName != null) { countOptions++; } if(hapmapFileName != null) { countOptions++; } if(batchFileName != null) { countOptions++; } if(countOptions > 1) { System.out.println("Only one genotype input file may be specified on the command line."); System.exit(1); } else if(countOptions == 0 && nogui) { System.out.println("You must specify a genotype input file."); System.exit(1); } //mess with vars, set defaults, etc if( outputType == -1 && ( pedFileName != null || hapsFileName != null || batchFileName != null || hapmapFileName != null) && !outputDprime && !outputCheck && !outputPNG && !outputCompressedPNG) { outputType = BLOX_GABRIEL; if(nogui && !quietMode) { System.out.println("No output type specified. Default of Gabriel will be used"); } } if(skipCheck && !quietMode) { System.out.println("Skipping genotype file check"); } if(maxDistance == -1){ maxDistance = 500; } Options.setMaxDistance(maxDistance); if(hapThresh != -1) { Options.setHaplotypeDisplayThreshold((int)(hapThresh*100)); } if(minimumMAF != -1) { CheckData.mafCut = minimumMAF; } if(minimumGenoPercent != -1) { CheckData.failedGenoCut = (int)(minimumGenoPercent*100); } if(hwCutoff != -1) { CheckData.hwCut = hwCutoff; } if(maxMendel != -1) { CheckData.numMendErrCut = maxMendel; } if(spacingThresh != -1) { Options.setSpacingThreshold(spacingThresh); } if(assocTDT) { Options.setAssocTest(ASSOC_TRIO); } else if(assocCC) { Options.setAssocTest(ASSOC_CC); } } |
|
String encoding = "UTF-8"; | public void save(ProgressMonitor pm) throws IOException, ArchitectException { // write to temp file and then rename (this preserves old project file // when there's problems) if (file.exists() && !file.canWrite()) { // write problems with architect file will muck up the save process throw new ArchitectException("problem saving project -- " + "cannot write to architect file: " + file.getAbsolutePath()); } File backupFile = new File (file.getParent(), file.getName()+"~"); // Several places we would check dir perms, but MS-Windows stupidly doesn't let use the // "directory write" attribute for directory writing (but instead overloads // it to mean 'this is a special directory'. File tempFile = null; tempFile = new File (file.getParent(),"tmp___" + file.getName()); try { // If creating this temp file fails, feed the user back a more explanatory message out = new PrintWriter(new BufferedWriter(new FileWriter(tempFile))); } catch (IOException e) { throw new ArchitectException("Unable to create output file for save operation, data NOT saved.\n" + e, e); } objectIdMap = new HashMap(); dbcsIdMap = new HashMap(); indent = 0; progress = 0; boolean saveOk = false; // use this to determine if save process worked this.pm = pm; if (pm != null) { int pmMax = 0; pm.setMinimum(0); if (savingEntireSource) { pmMax = ArchitectUtils.countTablesSnapshot((SQLObject) sourceDatabases.getModel().getRoot()); } else { pmMax = ArchitectUtils.countTables((SQLObject) sourceDatabases.getModel().getRoot()); } logger.error("Setting progress monitor maximum to "+pmMax); pm.setMaximum(pmMax); pm.setProgress(progress); pm.setMillisToDecideToPopup(0); } saveOk = save(out); // Does ALL the actual I/O out = null; if (pm != null) pm.close(); pm = null; // Do the rename dance. // This is a REALLY bad place for failure (especially if we've made the user wait several hours to save // a large project), so we MUST check failures from renameto (both places!) if (saveOk) { boolean fstatus = false; fstatus = backupFile.delete(); logger.debug("deleting backup~ file: " + fstatus); // If this is a brand new project, the old file does not yet exist, no point trying to rename it. // But if it already existed, renaming current to backup must succeed, or we give up. if (file.exists()) { fstatus = file.renameTo(backupFile); logger.debug("rename current file to backupFile: " + fstatus); if (!fstatus) { throw new ArchitectException(( "Could not rename current file to backup\nProject saved in " + tempFile + ": " + file + " still contains old project")); } } fstatus = tempFile.renameTo(file); if (!fstatus) { throw new ArchitectException(( "Could not rename temp file to current\nProject saved in " + tempFile + ": " + file + " still contains old project")); } logger.debug("rename tempFile to current file: " + fstatus); } } |
|
out = new PrintWriter(new BufferedWriter(new FileWriter(tempFile))); | out = new PrintWriter(tempFile,encoding); | public void save(ProgressMonitor pm) throws IOException, ArchitectException { // write to temp file and then rename (this preserves old project file // when there's problems) if (file.exists() && !file.canWrite()) { // write problems with architect file will muck up the save process throw new ArchitectException("problem saving project -- " + "cannot write to architect file: " + file.getAbsolutePath()); } File backupFile = new File (file.getParent(), file.getName()+"~"); // Several places we would check dir perms, but MS-Windows stupidly doesn't let use the // "directory write" attribute for directory writing (but instead overloads // it to mean 'this is a special directory'. File tempFile = null; tempFile = new File (file.getParent(),"tmp___" + file.getName()); try { // If creating this temp file fails, feed the user back a more explanatory message out = new PrintWriter(new BufferedWriter(new FileWriter(tempFile))); } catch (IOException e) { throw new ArchitectException("Unable to create output file for save operation, data NOT saved.\n" + e, e); } objectIdMap = new HashMap(); dbcsIdMap = new HashMap(); indent = 0; progress = 0; boolean saveOk = false; // use this to determine if save process worked this.pm = pm; if (pm != null) { int pmMax = 0; pm.setMinimum(0); if (savingEntireSource) { pmMax = ArchitectUtils.countTablesSnapshot((SQLObject) sourceDatabases.getModel().getRoot()); } else { pmMax = ArchitectUtils.countTables((SQLObject) sourceDatabases.getModel().getRoot()); } logger.error("Setting progress monitor maximum to "+pmMax); pm.setMaximum(pmMax); pm.setProgress(progress); pm.setMillisToDecideToPopup(0); } saveOk = save(out); // Does ALL the actual I/O out = null; if (pm != null) pm.close(); pm = null; // Do the rename dance. // This is a REALLY bad place for failure (especially if we've made the user wait several hours to save // a large project), so we MUST check failures from renameto (both places!) if (saveOk) { boolean fstatus = false; fstatus = backupFile.delete(); logger.debug("deleting backup~ file: " + fstatus); // If this is a brand new project, the old file does not yet exist, no point trying to rename it. // But if it already existed, renaming current to backup must succeed, or we give up. if (file.exists()) { fstatus = file.renameTo(backupFile); logger.debug("rename current file to backupFile: " + fstatus); if (!fstatus) { throw new ArchitectException(( "Could not rename current file to backup\nProject saved in " + tempFile + ": " + file + " still contains old project")); } } fstatus = tempFile.renameTo(file); if (!fstatus) { throw new ArchitectException(( "Could not rename temp file to current\nProject saved in " + tempFile + ": " + file + " still contains old project")); } logger.debug("rename tempFile to current file: " + fstatus); } } |
saveOk = save(out); | saveOk = save(out,encoding); | public void save(ProgressMonitor pm) throws IOException, ArchitectException { // write to temp file and then rename (this preserves old project file // when there's problems) if (file.exists() && !file.canWrite()) { // write problems with architect file will muck up the save process throw new ArchitectException("problem saving project -- " + "cannot write to architect file: " + file.getAbsolutePath()); } File backupFile = new File (file.getParent(), file.getName()+"~"); // Several places we would check dir perms, but MS-Windows stupidly doesn't let use the // "directory write" attribute for directory writing (but instead overloads // it to mean 'this is a special directory'. File tempFile = null; tempFile = new File (file.getParent(),"tmp___" + file.getName()); try { // If creating this temp file fails, feed the user back a more explanatory message out = new PrintWriter(new BufferedWriter(new FileWriter(tempFile))); } catch (IOException e) { throw new ArchitectException("Unable to create output file for save operation, data NOT saved.\n" + e, e); } objectIdMap = new HashMap(); dbcsIdMap = new HashMap(); indent = 0; progress = 0; boolean saveOk = false; // use this to determine if save process worked this.pm = pm; if (pm != null) { int pmMax = 0; pm.setMinimum(0); if (savingEntireSource) { pmMax = ArchitectUtils.countTablesSnapshot((SQLObject) sourceDatabases.getModel().getRoot()); } else { pmMax = ArchitectUtils.countTables((SQLObject) sourceDatabases.getModel().getRoot()); } logger.error("Setting progress monitor maximum to "+pmMax); pm.setMaximum(pmMax); pm.setProgress(progress); pm.setMillisToDecideToPopup(0); } saveOk = save(out); // Does ALL the actual I/O out = null; if (pm != null) pm.close(); pm = null; // Do the rename dance. // This is a REALLY bad place for failure (especially if we've made the user wait several hours to save // a large project), so we MUST check failures from renameto (both places!) if (saveOk) { boolean fstatus = false; fstatus = backupFile.delete(); logger.debug("deleting backup~ file: " + fstatus); // If this is a brand new project, the old file does not yet exist, no point trying to rename it. // But if it already existed, renaming current to backup must succeed, or we give up. if (file.exists()) { fstatus = file.renameTo(backupFile); logger.debug("rename current file to backupFile: " + fstatus); if (!fstatus) { throw new ArchitectException(( "Could not rename current file to backup\nProject saved in " + tempFile + ": " + file + " still contains old project")); } } fstatus = tempFile.renameTo(file); if (!fstatus) { throw new ArchitectException(( "Could not rename temp file to current\nProject saved in " + tempFile + ": " + file + " still contains old project")); } logger.debug("rename tempFile to current file: " + fstatus); } } |
JOptionPane.showMessageDialog( this, "Database " + nameFld.getText() + " created succesfully", | JOptionPane.showMessageDialog( this, "Database " + nameFld.getText() + " created successfully", | private void createDatabase() { // Ask for the admin password PVDatabase db = new PVDatabase(); String user = ""; String passwd = ""; if ( dbServerBtn.isSelected() ) { AdminLoginDlg loginDlg = new AdminLoginDlg( this, true ); if ( loginDlg.showDialog() == AdminLoginDlg.LOGIN_DLG_OK ) { user = loginDlg.getUsername(); passwd = loginDlg.getPasswd(); } db.setDbName( dbNameFld.getText() ); db.setDbHost( dbHostFld.getText() ); db.setName( nameFld.getText() ); Volume vol = new Volume( "defaultVolume", volumeDirFld.getText() ); db.addVolume( vol ); } else { // Creating an embedded database db.setName( nameFld.getText() ); db.setInstanceType( PVDatabase.TYPE_EMBEDDED ); db.setEmbeddedDirectory( new File( volumeDirFld.getText() ) ); } db.createDatabase( user, passwd ); PhotovaultSettings settings = PhotovaultSettings.getSettings(); settings.addDatabase( db ); settings.saveConfig(); JOptionPane.showMessageDialog( this, "Database " + nameFld.getText() + " created succesfully", "Database created", JOptionPane.INFORMATION_MESSAGE ); } |
setTitle("Create Photovault database"); | private void initComponents() { dirChooser = new javax.swing.JFileChooser(); instanceTypeBtnGroup = new javax.swing.ButtonGroup(); jLabel1 = new javax.swing.JLabel(); volumeDirFld = new javax.swing.JTextField(); okBtn = new javax.swing.JButton(); CancelBtn = new javax.swing.JButton(); dirSelectBtn = new javax.swing.JButton(); jLabel4 = new javax.swing.JLabel(); nameFld = new javax.swing.JTextField(); sqlDbPane = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); dbHostFld = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); dbNameFld = new javax.swing.JTextField(); derbyBtn = new javax.swing.JRadioButton(); dbServerBtn = new javax.swing.JRadioButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setName("Database settings"); jLabel1.setText("Photo directory"); okBtn.setText("OK"); okBtn.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { okBtnMouseClicked(evt); } }); CancelBtn.setText("Cancel"); CancelBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CancelBtnActionPerformed(evt); } }); dirSelectBtn.setText("..."); dirSelectBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { dirSelectBtnActionPerformed(evt); } }); jLabel4.setText("Database name"); nameFld.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { nameFldActionPerformed(evt); } }); nameFld.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { nameFldFocusLost(evt); } }); sqlDbPane.setBorder(javax.swing.BorderFactory.createTitledBorder("MySQL settings")); jLabel2.setText("MySQL host"); dbHostFld.setEnabled(false); jLabel3.setText("Database name"); dbNameFld.setEnabled(false); org.jdesktop.layout.GroupLayout sqlDbPaneLayout = new org.jdesktop.layout.GroupLayout(sqlDbPane); sqlDbPane.setLayout(sqlDbPaneLayout); sqlDbPaneLayout.setHorizontalGroup( sqlDbPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, sqlDbPaneLayout.createSequentialGroup() .add(sqlDbPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jLabel2) .add(jLabel3)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 37, Short.MAX_VALUE) .add(sqlDbPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false) .add(dbNameFld) .add(org.jdesktop.layout.GroupLayout.TRAILING, dbHostFld, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 238, Short.MAX_VALUE))) ); sqlDbPaneLayout.setVerticalGroup( sqlDbPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(sqlDbPaneLayout.createSequentialGroup() .add(sqlDbPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(dbHostFld, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 19, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(sqlDbPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel3) .add(dbNameFld, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); sqlDbPane.getAccessibleContext().setAccessibleName("Database server"); instanceTypeBtnGroup.add(derbyBtn); derbyBtn.setSelected(true); derbyBtn.setText("Internal database engine"); derbyBtn.setActionCommand("useDerby"); derbyBtn.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); derbyBtn.setMargin(new java.awt.Insets(0, 0, 0, 0)); derbyBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { derbyBtnActionPerformed(evt); } }); instanceTypeBtnGroup.add(dbServerBtn); dbServerBtn.setText("MySQL server"); dbServerBtn.setActionCommand("useMySQL"); dbServerBtn.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); dbServerBtn.setMargin(new java.awt.Insets(0, 0, 0, 0)); dbServerBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { dbServerBtnActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(31, 31, 31) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jLabel4) .add(jLabel1)) .add(23, 23, 23) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(dbServerBtn) .add(derbyBtn) .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup() .add(volumeDirFld, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(dirSelectBtn, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 26, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(nameFld, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 247, Short.MAX_VALUE))) .add(layout.createSequentialGroup() .addContainerGap() .add(sqlDbPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup() .addContainerGap(246, Short.MAX_VALUE) .add(okBtn, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 59, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(CancelBtn))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup() .addContainerGap() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel4) .add(nameFld, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel1) .add(dirSelectBtn) .add(volumeDirFld, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 19, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(derbyBtn) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(dbServerBtn) .add(16, 16, 16) .add(sqlDbPane, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(CancelBtn) .add(okBtn)) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.