List of usage examples for java.util ArrayList set
public E set(int index, E element)
From source file:com.crushpaper.DbLogic.java
/** Helper method. Does all the real work for restoreMsWordListFormatForUser(). */ public boolean reallyRestoreMsWordListFormatForUser(String userId, InputStreamReader streamReader, boolean isAdmin, Errors errors) { if (userId == null) { Errors.add(errors, errorMessages.errorsUserIdIsNull()); return false; }/*from w w w. j a v a2s . c om*/ if (streamReader == null) { Errors.add(errors, errorMessages.errorsTheInputStreamReaderIsNull()); return false; } BufferedReader bf = new BufferedReader(streamReader); final User user = getUserById(userId); if (user == null) { return false; } boolean createdAnyChildren = false; try { final long now = System.currentTimeMillis(); Entry notebook = createEntryNoteBook(user, "Restored Notebook", now, null, null, false, false, false, isAdmin, false, errors); if (notebook == null) { return false; } Entry root = getEntryById(notebook.getRootId()); ArrayList<Entry> parents = new ArrayList<Entry>(); HashMap<String, Integer> bulletToDepth = new HashMap<String, Integer>(); String line = null; Integer previousDepth = 0; parents.add(root); while ((line = bf.readLine()) != null) { line = line.trim(); if (line.isEmpty()) { continue; } String note = line; Integer depth = 1; if (line.length() > 1 && line.charAt(1) == '\t') { String bullet = line.substring(0, 1); note = line.substring(2); depth = bulletToDepth.get(bullet); if (depth == null) { depth = new Integer(bulletToDepth.size() + 1); bulletToDepth.put(bullet, depth); } for (int i = parents.size(); i > depth.intValue(); --i) { parents.remove(i - 1); } depth = new Integer(parents.size() + 1); } else { previousDepth = 0; while (parents.size() > 1) { parents.remove(parents.size() - 1); } } if (parents.isEmpty()) { return false; } Entry parent = parents.get(parents.size() - 1); Entry entry = createSimpleEntry(user, note, now, parent.getId(), TreeRelType.Parent, false, false, false, isAdmin, Constants.note, errors, null); if (entry == null) { return false; } if (previousDepth.intValue() != depth.intValue()) { parents.add(entry); } else { parents.set(parents.size() - 1, entry); } createdAnyChildren = true; } } catch (IOException e) { Errors.add(errors, errorMessages.errorProblemReadingInput()); } return createdAnyChildren; }
From source file:org.LexGrid.LexBIG.Impl.dataAccess.SQLImplementedMethods.java
public static GHolder resolveRelationships(ConceptReference graphFocus, boolean resolveForward, boolean resolveBackward, int resolveAssociationDepth, int maxToReturn, ArrayList<Operation> operations, String internalCodingSchemeName, String internalVersionString, String relationName, boolean keepLastAssociationLevelUnResolved) throws Exception { SQLInterface si = ResourceManager.instance().getSQLInterface(internalCodingSchemeName, internalVersionString);/*from ww w . ja v a 2 s .c om*/ try { GHolder resultsToReturn = new GHolder(internalCodingSchemeName, internalVersionString, graphFocus, resolveForward, resolveBackward); boolean noFocus = false; if (graphFocus == null || graphFocus.getConceptCode() == null || graphFocus.getConceptCode().length() == 0 || graphFocus.getConceptCode().equals("@") || graphFocus.getConceptCode().equals("@@")) { // start from root. if (resolveForward && resolveBackward) { throw new LBParameterException( "If you do not provide a focus node, you must choose resolve forward or resolve reverse, not both." + " Choose resolve forward to start at root nodes. Choose resolve reverse to start at tail nodes."); } else { noFocus = true; } } boolean hasCodeRestriction = false; for (int i = 0; i < operations.size(); i++) { if (operations.get(i) instanceof CodeRestriction) { hasCodeRestriction = true; break; } } if (resolveForward) { ArrayList<Operation> localOps = new ArrayList<Operation>(); int currentDepth = 0; // if they have not provided a focus code (and no other code // restrictions) // I need to add a restriction to the special top node. // If they have not provided a focus code, but they have // provided other code // restrictions, I'm going to return the top or bottom of what // ever tree results from their // restrictions. // if they provided a real focus node, add a restriction for // that. boolean roots = false; if (noFocus && !hasCodeRestriction) { ConceptReference cr = new ConceptReference(); cr.setCode("@"); cr.setCodingSchemeName( getURNForInternalCodingSchemeName(internalCodingSchemeName, internalVersionString)); RestrictToSourceCodes r = new RestrictToSourceCodes(cr); localOps.add(r); roots = true; } else if (!noFocus) { RestrictToSourceCodes r = new RestrictToSourceCodes(graphFocus); localOps.add(r); } localOps.addAll(operations); ConceptReferenceList crl = relationshipHandler(si, resultsToReturn, localOps, true, internalCodingSchemeName, internalVersionString, maxToReturn, relationName, resolveAssociationDepth, currentDepth, keepLastAssociationLevelUnResolved); if (resultsToReturn.getNodeCount() == 0 && roots) { // they wanted top nodes, but we didn't find any for // whatever association restriction // they provided. Must not be calculated yet. throw new LBParameterException( "No top nodes could be located for the supplied restriction set in the requested direction. "); } if (!noFocus || hasCodeRestriction) { // If they provide a focus node, the first query already // returned that node plus the nodes it points to. currentDepth = 1; } // here is the loop to continue walking down the graph. while (crl.getConceptReferenceCount() > 0 && (currentDepth < resolveAssociationDepth || resolveAssociationDepth < 0)) { localOps.set(0, new RestrictToSourceCodes(crl)); crl = relationshipHandler(si, resultsToReturn, localOps, true, internalCodingSchemeName, internalVersionString, maxToReturn, relationName, resolveAssociationDepth, currentDepth, keepLastAssociationLevelUnResolved); currentDepth++; } } if (resolveBackward) { // If they provide a focus node, the first query will return // that node plus the nodes it points to. int currentDepth = 0; ArrayList<Operation> localOps = new ArrayList<Operation>(); boolean leafs = false; if (noFocus && !hasCodeRestriction) { ConceptReference cr = new ConceptReference(); cr.setCode("@@"); cr.setCodingSchemeName( getURNForInternalCodingSchemeName(internalCodingSchemeName, internalVersionString)); RestrictToTargetCodes r = new RestrictToTargetCodes(cr); localOps.add(r); leafs = true; } else if (!noFocus) { RestrictToTargetCodes r = new RestrictToTargetCodes(graphFocus); localOps.add(r); } localOps.addAll(operations); ConceptReferenceList crl = relationshipHandler(si, resultsToReturn, localOps, false, internalCodingSchemeName, internalVersionString, maxToReturn, relationName, resolveAssociationDepth, currentDepth, keepLastAssociationLevelUnResolved); if (resultsToReturn.getNodeCount() == 0 && leafs) { // they wanted leaf nodes, but we didn't find any for // whatever association restriction // they provided. Must not be calculated yet. throw new LBParameterException( "No leaf nodes could be located for the supplied restriction set in the requested direction. "); } if (!noFocus || hasCodeRestriction) { // If they provide a focus node, the first query already // returned that node plus the nodes it points to. currentDepth = 1; } // here is the loop to continue walking up the graph. while (crl.getConceptReferenceCount() > 0 && (currentDepth < resolveAssociationDepth || resolveAssociationDepth < 0)) { localOps.set(0, new RestrictToTargetCodes(crl)); crl = relationshipHandler(si, resultsToReturn, localOps, false, internalCodingSchemeName, internalVersionString, maxToReturn, relationName, resolveAssociationDepth, currentDepth, keepLastAssociationLevelUnResolved); currentDepth++; } } // TODO [performance] what about making faster by "unrolling" some // of these recursive queries on the DB? return resultsToReturn; } catch (MissingResourceException e) { throw new LBParameterException("Either the source or the target code could not be properly resolved"); } catch (Exception e) { throw e; } }
From source file:com.ebay.erl.mobius.core.mapred.MobiusInputSampler.java
@Override public Object[] getSample(InputFormat inf, JobConf job) throws IOException { // the following codes are copied from {@link InputSampler#RandomSampler}, // but require some modifications. InputSplit[] splits = inf.getSplits(job, job.getNumMapTasks()); ArrayList<DataJoinKey> samples = new ArrayList<DataJoinKey>(this.numSamples); int splitsToSample = Math.min(this.maxSplitsSampled, splits.length); Random r = new Random(); long seed = r.nextLong(); r.setSeed(seed);/* www. j ava2 s.c om*/ // get Sorters Sorter[] sorters = null; if (job.get(ConfigureConstants.SORTERS, null) != null) { // total sort job sorters = (Sorter[]) SerializableUtil.deserializeFromBase64(job.get(ConfigureConstants.SORTERS), job); } else { // there is no sorter, should be reducer/join job Column[] keys = (Column[]) SerializableUtil .deserializeFromBase64(job.get(ConfigureConstants.ALL_GROUP_KEY_COLUMNS), job); sorters = new Sorter[keys.length]; for (int i = 0; i < keys.length; i++) { sorters[i] = new Sorter(keys[i].getInputColumnName(), Ordering.ASC); } } long proportion = 10L; while ((int) (this.freq * proportion) == 0) { proportion = proportion * 10; } proportion = 5L * proportion; // shuffle splits for (int i = 0; i < splits.length; ++i) { InputSplit tmp = splits[i]; int j = r.nextInt(splits.length); splits[i] = splits[j]; splits[j] = tmp; } SamplingOutputCollector collector = new SamplingOutputCollector(); for (int i = 0; i < splitsToSample || (i < splits.length && samples.size() < numSamples); i++) { LOGGER.info("Sampling from split #" + (i + 1) + ", collected samples:" + samples.size()); RecordReader<WritableComparable, WritableComparable> reader = inf.getRecordReader(splits[i], job, Reporter.NULL); WritableComparable key = reader.createKey(); WritableComparable value = reader.createValue(); if (!(inf instanceof MobiusDelegatingInputFormat)) { // not mobius delegating input format, so the CURRENT_DATASET_ID // will not be set by inf#getRecordReader, we set them here. // // set the current dataset id, as the AbstractMobiusMapper#configure // method needs this property. job.set(ConfigureConstants.CURRENT_DATASET_ID, job.get(ConfigureConstants.ALL_DATASET_IDS)); } Byte datasetID = Byte.valueOf(job.get(ConfigureConstants.CURRENT_DATASET_ID)); LOGGER.info("Samples coming from dataset: " + datasetID.toString()); AbstractMobiusMapper mapper = this.getMapper(inf, splits[i], job); mapper.configure(job); // reading elements from one split long readElement = 0; while (reader.next(key, value)) { collector.clear(); Tuple tuple = mapper.parse(key, value); readElement++; if (readElement > (((long) numSamples) * ((long) proportion))) { // a split might be very big (ex: a large gz file), // so we just need to read the break; } if (r.nextDouble() <= freq) { if (samples.size() < numSamples) { mapper.joinmap(key, value, collector, Reporter.NULL); // joinmap function might generate more than one output key // per <code>key</code> input. for (Tuple t : collector.getOutKey()) { Tuple mt = Tuple.merge(tuple, t); DataJoinKey nkey = this.getKey(mt, sorters, datasetID, mapper, job); samples.add(nkey); } } else { // When exceeding the maximum number of samples, replace // a random element with this one, then adjust the // frequency to reflect the possibility of existing // elements being pushed out mapper.joinmap(key, value, collector, Reporter.NULL); for (Tuple t : collector.getOutKey()) { int ind = r.nextInt(numSamples); if (ind != numSamples) { Tuple mt = Tuple.merge(tuple, t); DataJoinKey nkey = this.getKey(mt, sorters, datasetID, mapper, job); samples.set(ind, nkey); } } freq *= (numSamples - collector.getOutKey().size()) / (double) numSamples; } key = reader.createKey(); value = reader.createValue(); } } reader.close(); } LOGGER.info("Samples have been collected, return."); return samples.toArray(); }
From source file:com.amalto.workbench.dialogs.AnnotationOrderedListsDialog.java
@Override protected Control createDialogArea(Composite parent) { // Should not really be here but well,.... parent.getShell().setText(this.title); Composite composite = (Composite) super.createDialogArea(parent); GridLayout layout = (GridLayout) composite.getLayout(); layout.numColumns = 3;// w w w . j ava2 s . c om layout.makeColumnsEqualWidth = false; // layout.verticalSpacing = 10; if (actionType == AnnotationWrite_ActionType || actionType == AnnotationHidden_ActionType) { textControl = new CCombo(composite, SWT.BORDER | SWT.READ_ONLY); // roles=Util.getCachedXObjectsNameSet(this.xObject, TreeObject.ROLE); roles = getAllRolesStr(); ((CCombo) textControl).setItems(roles.toArray(new String[roles.size()])); } else if (actionType == AnnotationLookupField_ActionType || actionType == AnnotationPrimaKeyInfo_ActionType) { textControl = new CCombo(composite, SWT.BORDER | SWT.READ_ONLY); // roles=Util.getCachedXObjectsNameSet(this.xObject, TreeObject.ROLE); roles = getConceptElements(); ((CCombo) textControl).setItems(roles.toArray(new String[roles.size()])); } else { if (actionType == AnnotationOrderedListsDialog.AnnotationSchematron_ActionType) { textControl = new Text(composite, SWT.BORDER | SWT.WRAP | SWT.V_SCROLL); } else { textControl = new Text(composite, SWT.BORDER | SWT.SINGLE); } } if (actionType == AnnotationOrderedListsDialog.AnnotationForeignKeyInfo_ActionType) { textControl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); } else { if (actionType == AnnotationOrderedListsDialog.AnnotationSchematron_ActionType) { textControl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 7)); } else { textControl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1)); } } ((GridData) textControl.getLayoutData()).minimumWidth = 400; textControl.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { if ((e.stateMask == 0) && (e.character == SWT.CR)) { xPaths.add(AnnotationOrderedListsDialog.getControlText(textControl)); viewer.refresh(); fireXPathsChanges(); } } }); if (actionType == AnnotationOrderedListsDialog.AnnotationForeignKeyInfo_ActionType) { Button xpathButton = new Button(composite, SWT.PUSH | SWT.CENTER); xpathButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1)); xpathButton.setText("...");//$NON-NLS-1$ xpathButton.setToolTipText(Messages.AnnotationOrderedListsDialog_SelectXpath); xpathButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { } public void widgetSelected(SelectionEvent e) { XpathSelectDialog dlg = getNewXpathSelectDialog(parentPage, dataModelName); dlg.setLock(lock); dlg.setBlockOnOpen(true); dlg.open(); if (dlg.getReturnCode() == Window.OK) { ((Text) textControl).setText(dlg.getXpath()); dlg.close(); } } }); } Button addLabelButton = new Button(composite, SWT.PUSH); addLabelButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); // addLabelButton.setText("Set"); addLabelButton.setImage(ImageCache.getCreatedImage(EImage.ADD_OBJ.getPath())); addLabelButton.setToolTipText(Messages.AnnotationOrderedListsDialog_Add); addLabelButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent e) { }; public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { boolean exist = false; for (String string : xPaths) { if (string.equals(getControlText(textControl))) { exist = true; } } if (!exist && getControlText(textControl) != null && getControlText(textControl) != "") { xPaths.add(getControlText(textControl)); } viewer.refresh(); fireXPathsChanges(); }; }); final String COLUMN = columnName; viewer = new TableViewer(composite, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER | SWT.FULL_SELECTION); viewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1)); ((GridData) viewer.getControl().getLayoutData()).heightHint = 100; // Set up the underlying table Table table = viewer.getTable(); // table.setLayoutData(new GridData(GridData.FILL_BOTH)); new TableColumn(table, SWT.CENTER).setText(COLUMN); table.getColumn(0).setWidth(500); for (int i = 1, n = table.getColumnCount(); i < n; i++) { table.getColumn(i).pack(); } table.setHeaderVisible(true); table.setLinesVisible(true); // Create the cell editors --> We actually discard those later: not natural for an user CellEditor[] editors = new CellEditor[1]; if (actionType == AnnotationOrderedListsDialog.AnnotationWrite_ActionType || actionType == AnnotationOrderedListsDialog.AnnotationHidden_ActionType || actionType == AnnotationLookupField_ActionType || actionType == AnnotationPrimaKeyInfo_ActionType) { editors[0] = new ComboBoxCellEditor(table, roles.toArray(new String[] {}), SWT.READ_ONLY); } else { editors[0] = new TextCellEditor(table); } viewer.setCellEditors(editors); // set the content provider viewer.setContentProvider(new IStructuredContentProvider() { public void dispose() { } public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } public Object[] getElements(Object inputElement) { @SuppressWarnings("unchecked") ArrayList<String> xPaths = (ArrayList<String>) inputElement; ArrayList<DescriptionLine> lines = new ArrayList<DescriptionLine>(); for (String xPath : xPaths) { DescriptionLine line = new DescriptionLine(xPath); lines.add(line); } // we return an instance line made of a Sring and a boolean return lines.toArray(new DescriptionLine[lines.size()]); } }); // set the label provider viewer.setLabelProvider(new ITableLabelProvider() { public boolean isLabelProperty(Object element, String property) { return false; } public void dispose() { } public void addListener(ILabelProviderListener listener) { } public void removeListener(ILabelProviderListener listener) { } public String getColumnText(Object element, int columnIndex) { // System.out.println("getColumnText() "+columnIndex); DescriptionLine line = (DescriptionLine) element; switch (columnIndex) { case 0: return line.getLabel(); } return "";//$NON-NLS-1$ } public Image getColumnImage(Object element, int columnIndex) { return null; } }); // Set the column properties viewer.setColumnProperties(new String[] { COLUMN }); // set the Cell Modifier viewer.setCellModifier(new ICellModifier() { public boolean canModify(Object element, String property) { // if (INSTANCE_ACCESS.equals(property)) return true; Deactivated return true; // return false; } public void modify(Object element, String property, Object value) { TableItem item = (TableItem) element; DescriptionLine line = (DescriptionLine) item.getData(); String orgValue = line.getLabel(); if (actionType != AnnotationWrite_ActionType && actionType != AnnotationHidden_ActionType && actionType != AnnotationLookupField_ActionType && actionType != AnnotationPrimaKeyInfo_ActionType) { int targetPos = xPaths.indexOf(value.toString()); if (targetPos < 0) { line.setLabel(value.toString()); int index = xPaths.indexOf(orgValue); xPaths.remove(index); xPaths.add(index, value.toString()); viewer.update(line, null); } else if (targetPos >= 0 && !value.toString().equals(orgValue)) { MessageDialog.openInformation(null, Messages.Warning, Messages.AnnotationOrderedListsDialog_ValueAlreadyExists); } } else { String[] attrs = roles.toArray(new String[] {}); int index = Integer.parseInt(value.toString()); if (index == -1) { return; } value = attrs[index]; int pos = xPaths.indexOf(value.toString()); if (pos >= 0 && !(orgValue.equals(value))) { MessageDialog.openInformation(null, Messages.Warning, Messages.AnnotationOrderedListsDialog_); return; } else if (pos < 0) { line.setLabel(value.toString()); xPaths.set(index, value.toString()); viewer.update(line, null); } } fireXPathsChanges(); } public Object getValue(Object element, String property) { DescriptionLine line = (DescriptionLine) element; String value = line.getLabel(); if (actionType == AnnotationWrite_ActionType || actionType == AnnotationHidden_ActionType || actionType == AnnotationLookupField_ActionType || actionType == AnnotationPrimaKeyInfo_ActionType) { String[] attrs = roles.toArray(new String[] {}); return Arrays.asList(attrs).indexOf(value); } else { return value; } } }); // Listen for changes in the selection of the viewer to display additional parameters viewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { DescriptionLine line = (DescriptionLine) ((IStructuredSelection) viewer.getSelection()) .getFirstElement(); if (line != null) { if (textControl instanceof CCombo) { ((CCombo) textControl).setText(line.getLabel()); } if (textControl instanceof Text) { ((Text) textControl).setText(line.getLabel()); } } } }); // display for Delete Key events to delete an instance viewer.getTable().addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { // System.out.println("Table keyReleased() "); if ((e.stateMask == 0) && (e.character == SWT.DEL) && (viewer.getSelection() != null)) { DescriptionLine line = (DescriptionLine) ((IStructuredSelection) viewer.getSelection()) .getFirstElement(); @SuppressWarnings("unchecked") ArrayList<String> xPaths = (ArrayList<String>) viewer.getInput(); xPaths.remove(line.getLabel()); viewer.refresh(); } } }); viewer.setInput(xPaths); viewer.refresh(); Composite rightButtonsComposite = new Composite(composite, SWT.NULL); rightButtonsComposite.setLayout(new GridLayout(1, true)); rightButtonsComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1)); Button upButton = new Button(rightButtonsComposite, SWT.PUSH | SWT.CENTER); upButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1)); upButton.setImage(ImageCache.getCreatedImage(EImage.PREV_NAV.getPath())); upButton.setToolTipText(Messages.AnnotationOrderedListsDialog_MoveUpTheItem); upButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent e) { }; public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { DescriptionLine line = (DescriptionLine) ((IStructuredSelection) viewer.getSelection()) .getFirstElement(); if (line == null) { return; } int i = 0; for (String xPath : xPaths) { if (xPath.equals(line.getLabel())) { if (i > 0) { xPaths.remove(i); xPaths.add(i - 1, xPath); viewer.refresh(); viewer.getTable().setSelection(i - 1); viewer.getTable().showSelection(); fireXPathsChanges(); } return; } i++; } }; }); Button downButton = new Button(rightButtonsComposite, SWT.PUSH | SWT.CENTER); downButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1)); downButton.setImage(ImageCache.getCreatedImage(EImage.NEXT_NAV.getPath())); downButton.setToolTipText(Messages.AnnotationOrderedListsDialog_MoveDownTheItem); downButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent e) { }; public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { DescriptionLine line = (DescriptionLine) ((IStructuredSelection) viewer.getSelection()) .getFirstElement(); if (line == null) { return; } int i = 0; for (String xPath : xPaths) { if (xPath.equals(line.getLabel())) { if (i < xPaths.size() - 1) { xPaths.remove(i); xPaths.add(i + 1, xPath); viewer.refresh(); viewer.getTable().setSelection(i + 1); viewer.getTable().showSelection(); fireXPathsChanges(); } return; } i++; } }; }); Button delButton = new Button(rightButtonsComposite, SWT.PUSH | SWT.CENTER); delButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1)); delButton.setImage(ImageCache.getCreatedImage(EImage.DELETE_OBJ.getPath())); delButton.setToolTipText(Messages.AnnotationOrderedListsDialog_DelTheItem); delButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent e) { }; public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { DescriptionLine line = (DescriptionLine) ((IStructuredSelection) viewer.getSelection()) .getFirstElement(); if (line != null) { @SuppressWarnings("unchecked") ArrayList<String> xPaths = (ArrayList<String>) viewer.getInput(); xPaths.remove(line.getLabel()); viewer.refresh(); fireXPathsChanges(); } }; }); textControl.setFocus(); if (actionType != AnnotationOrderedListsDialog.AnnotationForeignKeyInfo_ActionType && actionType != AnnotationOrderedListsDialog.AnnotationTargetSystems_ActionType && actionType != AnnotationOrderedListsDialog.AnnotationSchematron_ActionType && actionType != AnnotationOrderedListsDialog.AnnotationLookupField_ActionType && actionType != AnnotationOrderedListsDialog.AnnotationPrimaKeyInfo_ActionType) { checkBox = new Button(composite, SWT.CHECK); checkBox.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, false, true, 2, 1)); checkBox.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent e) { }; public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { recursive = checkBox.getSelection(); }; }); checkBox.setSelection(recursive); checkBox.setText(Messages.AnnotationOrderedListsDialog_SetRoleRecursively); // Label label = new Label(composite, SWT.LEFT); // label.setText("set role recursively"); // label.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, false, true, // 1, 1)); } if (actionType == AnnotationForeignKeyInfo_ActionType) { createFKInfoFormatComp(composite); addDoubleClickListener(); } return composite; }
From source file:com.vgi.mafscaling.ClosedLoop.java
private void calculateCorrectedGS() { double time;// www . j a v a2s. c o m double load; double rpm; double dvdt; double afr; double mafv; double stft; double ltft; double iat; double corr; double val1; double val2; String timeStr; String loadStr; String rpmStr; String mafvStr; String afrStr; String stftStr; String ltftStr; String dvdtStr; String iatStr; int closestMafIdx; int closestRmpIdx; int closestLoadIdx; int i; String tableName = "Log Data"; ArrayList<Integer> temp = new ArrayList<Integer>(gsArray.size()); correctionMeanArray = new ArrayList<Double>(gsArray.size()); correctionModeArray = new ArrayList<Double>(gsArray.size()); ArrayList<HashMap<Double, Integer>> modeCalcArray = new ArrayList<HashMap<Double, Integer>>(); for (i = 0; i < gsArray.size(); ++i) { temp.add(0); correctionMeanArray.add(0.0); correctionModeArray.add(0.0); modeCalcArray.add(new HashMap<Double, Integer>()); } ArrayList<Double> afrRpmArray = new ArrayList<Double>(); for (i = 1; i < polfTable.getRowCount(); ++i) { afrRpmArray.add(Double.valueOf(polfTable.getValueAt(i, 0).toString())); Utils.ensureRowCount(i + 1, afr1Table); Utils.ensureRowCount(i + 1, afr2Table); afr1Table.setValueAt(polfTable.getValueAt(i, 0), i, 0); afr2Table.setValueAt(polfTable.getValueAt(i, 0), i, 0); } ArrayList<Double> afrLoadArray = new ArrayList<Double>(); for (i = 1; i < polfTable.getColumnCount(); ++i) { afrLoadArray.add(Double.valueOf(polfTable.getValueAt(0, i).toString())); Utils.ensureColumnCount(i + 1, afr1Table); Utils.ensureColumnCount(i + 1, afr2Table); afr1Table.setValueAt(polfTable.getValueAt(0, i), 0, i); afr2Table.setValueAt(polfTable.getValueAt(0, i), 0, i); } Integer val; HashMap<Double, Integer> modeCountMap; for (i = 0; i < logDataTable.getRowCount(); ++i) { timeStr = logDataTable.getValueAt(i, 0).toString(); loadStr = logDataTable.getValueAt(i, 1).toString(); rpmStr = logDataTable.getValueAt(i, 2).toString(); mafvStr = logDataTable.getValueAt(i, 3).toString(); afrStr = logDataTable.getValueAt(i, 4).toString(); stftStr = logDataTable.getValueAt(i, 5).toString(); ltftStr = logDataTable.getValueAt(i, 6).toString(); dvdtStr = logDataTable.getValueAt(i, 7).toString(); iatStr = logDataTable.getValueAt(i, 8).toString(); if (timeStr.isEmpty() || loadStr.isEmpty() || rpmStr.isEmpty() || mafvStr.isEmpty() || afrStr.isEmpty() || stftStr.isEmpty() || ltftStr.isEmpty() || dvdtStr.isEmpty() || iatStr.isEmpty()) break; if (!Utils.validateDouble(timeStr, i, 0, tableName) || !Utils.validateDouble(loadStr, i, 1, tableName) || !Utils.validateDouble(rpmStr, i, 2, tableName) || !Utils.validateDouble(mafvStr, i, 3, tableName) || !Utils.validateDouble(afrStr, i, 4, tableName) || !Utils.validateDouble(stftStr, i, 5, tableName) || !Utils.validateDouble(ltftStr, i, 6, tableName) || !Utils.validateDouble(dvdtStr, i, 7, tableName) || !Utils.validateDouble(iatStr, i, 8, tableName)) return; time = Double.valueOf(timeStr); load = Double.valueOf(loadStr); rpm = Double.valueOf(rpmStr); mafv = Double.valueOf(mafvStr); afr = Double.valueOf(afrStr); stft = Double.valueOf(stftStr); ltft = Double.valueOf(ltftStr); dvdt = Double.valueOf(dvdtStr); iat = Double.valueOf(iatStr); corr = ltft + stft; trimArray.add(corr); rpmArray.add(rpm); timeArray.add(time); iatArray.add(iat); mafvArray.add(mafv); dvdtArray.add(dvdt); closestMafIdx = Utils.closestValueIndex(load * rpm / 60.0, gsArray); correctionMeanArray.set(closestMafIdx, (correctionMeanArray.get(closestMafIdx) * temp.get(closestMafIdx) + corr) / (temp.get(closestMafIdx) + 1)); temp.set(closestMafIdx, temp.get(closestMafIdx) + 1); modeCountMap = modeCalcArray.get(closestMafIdx); double roundedCorr = ((double) Math.round(corr * 10.0)) / 10.0; val = modeCountMap.get(roundedCorr); if (val == null) modeCountMap.put(roundedCorr, 1); else modeCountMap.put(roundedCorr, val + 1); closestRmpIdx = Utils.closestValueIndex(rpm, afrRpmArray) + 1; closestLoadIdx = Utils.closestValueIndex(load, afrLoadArray) + 1; val1 = (afr1Table.getValueAt(closestRmpIdx, closestLoadIdx).toString().isEmpty()) ? 0 : Double.valueOf(afr1Table.getValueAt(closestRmpIdx, closestLoadIdx).toString()); val2 = (afr2Table.getValueAt(closestRmpIdx, closestLoadIdx).toString().isEmpty()) ? 0 : Double.valueOf(afr2Table.getValueAt(closestRmpIdx, closestLoadIdx).toString()); afr1Table.setValueAt((val1 * val2 + afr) / (val2 + 1.0), closestRmpIdx, closestLoadIdx); afr2Table.setValueAt(val2 + 1.0, closestRmpIdx, closestLoadIdx); } for (i = 0; i < modeCalcArray.size(); ++i) { modeCountMap = modeCalcArray.get(i); if (modeCountMap.size() > 0) { int maxValueInMap = (Collections.max(modeCountMap.values())); double sum = 0; int count = 0; for (Entry<Double, Integer> entry : modeCountMap.entrySet()) { if (entry.getValue() == maxValueInMap) { sum += entry.getKey(); count += 1; } } correctionModeArray.set(i, sum / count); } } int size = afrRpmArray.size() + 1; while (size < afr1Table.getRowCount()) Utils.removeRow(size, afr1Table); while (size < afr2Table.getRowCount()) Utils.removeRow(size, afr2Table); Utils.colorTable(afr1Table); Utils.colorTable(afr2Table); int firstCorrIndex = 0; double firstCorr = 1; for (i = 0; i < correctionMeanArray.size(); ++i) { corr = 1; if (temp.get(i) > minCellHitCount) { corr = 1.0 + (correctionMeanArray.get(i) + correctionModeArray.get(i)) / 200.00; if (firstCorrIndex == 0) { firstCorrIndex = i; firstCorr = corr; } } gsCorrected.add(i, gsArray.get(i) * corr); } for (i = firstCorrIndex - 1; i > 0; --i) gsCorrected.set(i, gsArray.get(i) * firstCorr); }
From source file:Opm_Package.New_CommitsInterval.java
public Object[] getCommitsNow(String projectName, String date1, String date2, int i, String[] toks) throws org.json.simple.parser.ParseException { System.out.println(i + "\t\t\t : " + date1 + "\t\t - " + date2); ///.......................................... String location = "location"; long public_repos = 0; long public_gists = 0; long followers = 0; long following = 0; String createdAt = "#######"; String updatedAt = "#######"; String login = "login######"; String loginURL = ""; JSONObject loginObj = null;// w w w .ja v a 2 s . c o m long changed = 0, added = 0, deleted = 0; ArrayList<String> shaLists = new ArrayList<>(); ArrayList<String> logList = new ArrayList<>(); Set<String> loginSet = new LinkedHashSet<String>(); Set<String> locationSet = new LinkedHashSet<String>(); Set<String> nameSet = new LinkedHashSet<String>(); Set<String> emailSet = new LinkedHashSet<String>(); Set<String> createdSet = new LinkedHashSet<String>(); Set<String> updatedSet = new LinkedHashSet<String>(); List<Long> cList = new ArrayList<>(); List<Long> aList = new ArrayList<>(); List<Long> dList = new ArrayList<>(); ArrayList<List<String>> list = new ArrayList<List<String>>(); JSONParser parser = new JSONParser(); int p = 1; // Page number parameter //int i = 0; // Commit Counter int ct = 0; int count = 0; while (true) {////loop thru the pagess.... if (ct == (toks.length - 1)) {/// the the index for the tokens array... ct = 0; //// go back to the first index...... } String jsonString = callURL("https://api.github.com/repos/" + projectName + "/commits?page=" + p + "&per_page=100&since=" + date1 + "&until=" + date2 + "&access_token=" + toks[ct++]); JSONArray jsonArray = (JSONArray) parser.parse(jsonString); if (jsonArray.toString().equals("[]")) { /// Break out of the loop, when empty array is found! break; } for (Object jsonObj : jsonArray) { count++; JSONObject jsonObject = (JSONObject) jsonObj; String shaa = (String) jsonObject.get("sha"); shaLists.add(shaa);/// Add to the List JSONObject commitsObj = (JSONObject) jsonObject.get("commit"); JSONObject authorObj = (JSONObject) commitsObj.get("author"); ///.......................................... String name = (String) authorObj.get("name"); String email = (String) authorObj.get("email"); String date = (String) authorObj.get("date"); //...................................... if (ct == (toks.length - 1)) {/// the the index for the tokens array... ct = 0; //// go back to the first index...... } String commitsShaURL = callURL("https://api.github.com/repos/" + projectName + "/commits/" + shaa + "?access_token=" + toks[ct++]); JSONObject allObj = (JSONObject) parser.parse(commitsShaURL); //// JSONObject logObj = (JSONObject) allObj.get("author"); JSONArray fileArray = (JSONArray) allObj.get("files"); long chh = 0, add = 0, del = 0; if (!fileArray.toString().equals("[]")) { /// Now we also need to get the Login Details,,the corresponding followes and following List<String> comList = new ArrayList<>(); // String lgg = "###########"; for (int a = 0; a < fileArray.size(); a++) { JSONObject fileObj = (JSONObject) fileArray.get(a); chh += (long) fileObj.get("changes"); add += (long) fileObj.get("additions"); del += (long) fileObj.get("deletions"); } } cList.add(chh); aList.add(add); dList.add(del); nameSet.add(name); emailSet.add(email); if (ct == (toks.length - 1)) {/// the the index for the tokens array... ct = 0; //// go back to the first index...... } /// Now we also need to get the Login Details,,the corresponding followes and following JSONObject loginAuthorObj = (JSONObject) jsonObject.get("author"); /// Checking for null objects... if (logObj != null) { login = (String) loginAuthorObj.get("login"); loginSet.add(login); logList.add(login); /// Preventing dublicates using see............ //********************************************** } //...................................... if (logObj == null) { loginSet.add("login######"); logList.add("login######"); } //logList.add(login); if (ct == (toks.length - 1)) {/// the the index for the tokens array... ct = 0; //// go back to the first index...... } //############################################################### *********** } /// *** End of for loop for JSon Object..... p++;//// Goto the next Page....... } // ******* End of while loop.... // create an iterator Iterator iterator = loginSet.iterator(); Iterator name = nameSet.iterator(); Iterator email = emailSet.iterator(); /// List<String> lList = new ArrayList<>(); //// We ArrayList<String> nList = new ArrayList<>(); ArrayList<String> eList = new ArrayList<>(); ArrayList<String> locList = new ArrayList<>(); // while (iterator.hasNext()) { String l = (String) iterator.next(); //if(!l.equals("")){ lList.add(l); //} } while (name.hasNext()) { nList.add((String) name.next()); } while (email.hasNext()) { eList.add((String) email.next()); } /// This is where we shall store the list of all the comits with other details ArrayList<Long> commList = new ArrayList<>(); ArrayList<Long> chaList = new ArrayList<>(); ArrayList<Long> addList = new ArrayList<>(); ArrayList<Long> delList = new ArrayList<>(); ArrayList<Long> pubList = new ArrayList<>(); ArrayList<Long> gisList = new ArrayList<>(); ArrayList<Long> folList = new ArrayList<>(); ArrayList<Long> fowList = new ArrayList<>(); ///First initials all with 0 depending on number of users... for (int a = 0; a < lList.size(); a++) { long com = 0; commList.add(com); chaList.add(com); addList.add(com); delList.add(com); pubList.add(com); gisList.add(com); folList.add(com); fowList.add(com); } for (int cc = 0; cc < shaLists.size(); cc++) { for (int b = 0; b < lList.size(); b++) { if (logList.get(cc).equals(lList.get(b))) { long get_com = commList.get(b) + 1; long get_cha = chaList.get(b) + cList.get(cc); long get_add = addList.get(b) + aList.get(cc); long get_del = delList.get(b) + dList.get(cc); ///To update specific element in the List we have to first remove that element commList.remove(b); chaList.remove(b); addList.remove(b); delList.remove(b); /// Now we have to put it back to there position commList.add(b, get_com); chaList.add(b, get_cha); addList.add(b, get_add); delList.add(b, get_del); } } } if (ct == (toks.length - 1)) {/// the the index for the tokens array... ct = 0; //// go back to the first index...... } // Getting the PR Open, PR Clossed IS Openned, Is Clossed, Forks, Stars String pulsURL = callURL("https://api.github.com/repos/" + projectName + "/pulls?since=" + date1 + "&until=" + date2 + "&access_token=" + toks[ct++]); if (ct == (toks.length - 1)) {/// the the index for the tokens array... ct = 0; //// go back to the first index...... } String issuesURL = callURL("https://api.github.com/repos/" + projectName + "/issues?since=" + date1 + "&until=" + date2 + "&access_token=" + toks[ct++]); JSONArray pullsArray = (JSONArray) parser.parse(pulsURL); JSONArray issuesArray = (JSONArray) parser.parse(issuesURL); long pl = 0, pc = 0, f = 0, is = 0, ic = 0, s = 0, w = 0; for (Object jsonObj : pullsArray) { JSONObject pullsObj = (JSONObject) jsonObj; JSONObject headObj = (JSONObject) pullsObj.get("head"); JSONObject reposObj = (JSONObject) headObj.get("repo"); if (reposObj != null) { // System.out.println(reposObj); pl += (long) reposObj.get("open_issues"); f += (long) reposObj.get("forks"); w += (long) reposObj.get("watchers"); } } for (Object jsonObj2 : issuesArray) { JSONObject issuesObj = (JSONObject) jsonObj2; String is_open = (String) issuesObj.get("state"); String is_close = (String) issuesObj.get("closed_at"); if (is_open.equals("open")) { is += 1; } else { is += 0; } } for (int b = 0; b < lList.size(); b++) {/// Looping thru all the Shaa ...... //System.out.println(lList.get(b)); long get_up = 0; long get_gis = 0; long get_fol = 0; long get_fow = 0; if (!lList.get(b).equals("login######")) { if (ct == (toks.length - 1)) {/// the the index for the tokens array... ct = 0; //// go back to the first index...... } loginURL = callURL("https://api.github.com/users/" + lList.get(b) + "?access_token=" + toks[ct++]); loginObj = (JSONObject) parser.parse(loginURL); get_up = pubList.get(b) + (long) loginObj.get("public_repos"); get_gis = gisList.get(b) + (long) loginObj.get("public_gists"); get_fol = folList.get(b) + (long) loginObj.get("followers"); get_fow = fowList.get(b) + (long) loginObj.get("following"); location = (String) loginObj.get("location"); createdAt = (String) loginObj.get("created_at"); updatedAt = (String) loginObj.get("updated_at"); pubList.set(b, get_up); gisList.set(b, get_gis); folList.set(b, get_fol); fowList.set(b, get_fow); locationSet.add(location); createdSet.add(createdAt); updatedSet.add(updatedAt); } if (lList.get(b).equals("login######")) { pubList.set(b, pubList.get(b) + get_up); gisList.set(b, gisList.get(b) + get_gis); folList.set(b, folList.get(b) + get_fol); fowList.set(b, fowList.get(b) + get_fow); locationSet.add("location"); createdSet.add("created"); updatedSet.add("updated"); } } /// Split them here.. ArrayList<String> locateList = new ArrayList<>(); ArrayList<String> createdList = new ArrayList<>(); ArrayList<String> updatedList = new ArrayList<>(); Iterator locat = locationSet.iterator(); Iterator create = createdSet.iterator(); Iterator update = updatedSet.iterator(); while (locat.hasNext()) { locateList.add((String) locat.next()); } while (create.hasNext()) { createdList.add((String) create.next()); } while (update.hasNext()) { updatedList.add((String) update.next()); } List<String> allList = new ArrayList<>(); allList.add(date1 + " - " + date2); allList.add(String.valueOf(pl)); allList.add(String.valueOf(pc)); allList.add(String.valueOf(is)); allList.add(String.valueOf(ic)); allList.add(String.valueOf(f)); allList.add(String.valueOf(w)); if (i == 0) { allList.add(projectName); } else { allList.add("-"); } ///System.out.println(nList+"\t"+eList+"\t"+lList+"\t"+createdList+"\t"+updatedList+"\t"+pubList+"\t"+gisList+"\t"+folList+"\t"+fowList+"\t"+commList+"\t"+chaList+"\t"+addList+"\t"+delList); if (shaLists.size() > 0) { for (int z = 0; z < lList.size(); z++) { allList.add(nList.get(z) + "/" + eList.get(z) + "/" + lList.get(z) + "/" + createdList.get(z) + "/" + updatedList.get(z) + "/" + pubList.get(z) + "/" + gisList.get(z) + "/" + folList.get(z) + "/" + fowList.get(z) + "/" + commList.get(z) + "_" + chaList.get(z) + "_" + addList.get(z) + "_" + delList.get(z)); } datas = new Object[allList.size()]; datas = allList.toArray(datas); /// putting the bodies in to the arraylist.. } datas = new Object[allList.size()]; datas = allList.toArray(datas); System.out.print(shaLists + "\t\t pr_O: " + pl + ", Closed: " + pc + " IS_OP:" + is + ", IS_CL: " + ic + ", FORK: " + f + ", WATCH: " + w + " \t Login: " + loginSet + "\t name: " + nList + "\t email: " + eList + "\t Location: " + locList + " , Updated: " + pubList + ",Gis: " + gisList + ",Followers: " + folList + ",Following: " + fowList + ", Created_At: " + createdSet + ", Updated: " + updatedSet + " \t Commits: " + commList + " , Changes:" + commList + ", Added: " + chaList + ", Deleted: " + addList); System.out.println("**************************"); //System.out.println(datas); return datas; }
From source file:es.pode.catalogadorWeb.presentacion.categoriasAvanzado.tecnica.TecnicaControllerImpl.java
private void cambioFormulario(HttpServletRequest request, int longitudFormatos, int longitudLocalizacion, int longitudRequisitos, int[] longitudAgregadores, int longitudNotasDeInstalacion, int longitudMasRequerimientos, int longitudDescDuracion) throws Exception { String source = AgregaPropertiesImpl.getInstance().getProperty("esquemaDeMetadatos"); formatos = new FormatoVO[longitudFormatos];//form.getIdentificadores().size() localizaciones = new LocalizacionVO[longitudLocalizacion];//form.getIdiomas().size() requisitos = new RequisitoVO[longitudRequisitos];//form.getDescripciones().size() // agregadores = new AgregadorORVO[longitudAgregadores];//form.getPalabrasClave().size() notasDeInstalacion = new PautasInstalacionVO[1]; masRequisitos = new OtrosRequisitosVO[1]; duracion = new DuracionVO(); duracionDesc = new DescripcionVO[1]; String[] formatoValor = new String[longitudFormatos]; String[] localiza = new String[longitudLocalizacion]; ArrayList[] tipos = new ArrayList[longitudAgregadores.length]; ArrayList[] nombres = new ArrayList[longitudAgregadores.length]; ArrayList[] minimos = new ArrayList[longitudAgregadores.length]; ArrayList[] maximos = new ArrayList[longitudAgregadores.length]; String[] idiomaIns = new String[longitudNotasDeInstalacion]; String[] texIns = new String[longitudNotasDeInstalacion]; String[] idiomaMasReq = new String[longitudMasRequerimientos]; String[] texMasReq = new String[longitudMasRequerimientos]; DescripcionVO[] textDura = new DescripcionVO[1]; String[] descDura = new String[longitudDescDuracion]; String[] idiomaDura = new String[longitudDescDuracion]; for (Enumeration names = request.getParameterNames(); names.hasMoreElements();) { String name = String.valueOf(names.nextElement()); if (name.startsWith("Form")) { int i = Integer.parseInt(name.substring(4, name.length())); formatoValor[i] = request.getParameter(name); }/* w w w . java 2 s .c o m*/ if (name.startsWith("Tam")) { tamao = request.getParameter(name); } if (name.startsWith("Loc")) { int i = Integer.parseInt(name.substring(3, name.length())); localiza[i] = request.getParameter(name); } if (name.startsWith("Tipo")) { String[] namePartido = name.split("_"); int i = Integer.parseInt(namePartido[0].substring(4, namePartido[0].length())); int j = Integer.parseInt(namePartido[1].substring(0, namePartido[1].length())); ArrayList lTipos = tipos[i]; if (lTipos == null) { lTipos = new ArrayList(); for (int k = 0; k < longitudAgregadores[i]; k++) lTipos.add(""); } lTipos.set(j, request.getParameter(name)); tipos[i] = lTipos; } if (name.startsWith("Nom")) { String[] namePartido = name.split("_"); int i = Integer.parseInt(namePartido[0].substring(3, namePartido[0].length())); int j = Integer.parseInt(namePartido[1].substring(0, namePartido[1].length())); ArrayList lNom = nombres[i]; if (lNom == null) { lNom = new ArrayList(); for (int k = 0; k < longitudAgregadores[i]; k++) lNom.add(""); } lNom.set(j, request.getParameter(name)); nombres[i] = lNom; } if (name.startsWith("Mini")) { String[] namePartido = name.split("_"); int i = Integer.parseInt(namePartido[0].substring(4, namePartido[0].length())); int j = Integer.parseInt(namePartido[1].substring(0, namePartido[1].length())); ArrayList lMin = minimos[i]; if (lMin == null) { lMin = new ArrayList(); for (int k = 0; k < longitudAgregadores[i]; k++) lMin.add(""); } lMin.set(j, request.getParameter(name)); minimos[i] = lMin; } if (name.startsWith("Max")) { String[] namePartido = name.split("_"); int i = Integer.parseInt(namePartido[0].substring(3, namePartido[0].length())); int j = Integer.parseInt(namePartido[1].substring(0, namePartido[1].length())); ArrayList lMax = maximos[i]; if (lMax == null) { lMax = new ArrayList(); for (int k = 0; k < longitudAgregadores[i]; k++) lMax.add(""); } lMax.set(j, request.getParameter(name)); maximos[i] = lMax; } if (name.startsWith("Ins")) { if (name.startsWith("InsTex")) { int i = Integer.parseInt(name.substring(6, name.length())); texIns[i] = request.getParameter(name); } if (name.startsWith("InsIdio")) { int i = Integer.parseInt(name.substring(7, name.length())); idiomaIns[i] = request.getParameter(name); } } if (name.startsWith("MasReq")) { if (name.startsWith("MasReqTex")) { int i = Integer.parseInt(name.substring(9, name.length())); texMasReq[i] = request.getParameter(name); } if (name.startsWith("MasReqIdio")) { int i = Integer.parseInt(name.substring(10, name.length())); idiomaMasReq[i] = request.getParameter(name); } } if (name.equals("Anyos")) anyos = request.getParameter(name); if (name.equals("Meses")) meses = request.getParameter(name); if (name.equals("Dias")) dias = request.getParameter(name); if (name.equals("Horas")) horas = request.getParameter(name); if (name.equals("Minutos")) minutos = request.getParameter(name); if (name.equals("SegundosP1")) segundosP1 = request.getParameter(name); if (name.equals("SegundosP2")) segundosP2 = request.getParameter(name); if (name.startsWith("DesDur")) { if (name.startsWith("DesDurTex")) { int i = Integer.parseInt(name.substring(9, name.length())); descDura[i] = request.getParameter(name); } if (name.startsWith("DesDurIdio")) { int i = Integer.parseInt(name.substring(10, name.length())); idiomaDura[i] = request.getParameter(name); } } } for (int i = 0; i < formatoValor.length; i++) { FormatoVO formVO = new FormatoVO(); String formatoValorI = formatoValor[i] != null ? formatoValor[i] : ""; formVO.setTexto(formatoValorI.trim()); formatos[i] = formVO; } for (int i = 0; i < localiza.length; i++) { LocalizacionVO localizaVO = new LocalizacionVO(); String localizaI = localiza[i] != null ? localiza[i] : ""; localizaVO.setTexto(localizaI.trim()); localizaciones[i] = localizaVO; } for (int i = 0; i < longitudAgregadores.length; i++) { RequisitoVO requi = new RequisitoVO(); AgregadorORVO[] lAgregadores = new AgregadorORVO[longitudAgregadores[i]]; for (int j = 0; j < longitudAgregadores[i]; j++) { AgregadorORVO agregad = new AgregadorORVO(); SourceValueVO type = new SourceValueVO(); String tiposIJ = ""; if ((tipos[i] != null) && (tipos[i].get(j) != null)) { tiposIJ = tipos[i].get(j).toString(); } type.setValor(tiposIJ.trim()); type.setSource(source); SourceValueVO name = new SourceValueVO(); String nombresIJ = ""; if ((nombres[i] != null) && (nombres[i].get(j) != null)) { nombresIJ = nombres[i].get(j).toString(); } name.setValor(nombresIJ.trim()); name.setSource(source); VersionMinVO min = new VersionMinVO(); String minimosIJ = ""; if ((minimos[i] != null) && (minimos[i].get(j) != null)) { minimosIJ = minimos[i].get(j).toString(); } min.setTexto(minimosIJ.trim()); VersionMaxVO max = new VersionMaxVO(); String maximosIJ = ""; if ((maximos[i] != null) && (maximos[i].get(j) != null)) { maximosIJ = maximos[i].get(j).toString(); } max.setTexto(maximosIJ.trim()); agregad.setTipo(type); agregad.setNombre(name); agregad.setVersionMin(min); agregad.setVersionMax(max); lAgregadores[j] = agregad; } requi.setAgregadoresOR(lAgregadores); requisitos[i] = requi; } PautasInstalacionVO pautas = new PautasInstalacionVO(); LangStringVO[] aLangPautas = new LangStringVO[texIns.length]; for (int i = 0; i < longitudNotasDeInstalacion; i++) { LangStringVO langPauta = new LangStringVO(); String texInsI = texIns[i] != null ? texIns[i] : ""; langPauta.setTexto(texInsI.trim()); langPauta.setIdioma(idiomaIns[i]); aLangPautas[i] = langPauta; } pautas.setTextos(aLangPautas); notasDeInstalacion[0] = pautas; OtrosRequisitosVO otros = new OtrosRequisitosVO(); LangStringVO[] aLangOtros = new LangStringVO[texMasReq.length]; for (int i = 0; i < longitudMasRequerimientos; i++) { LangStringVO langOtro = new LangStringVO(); String texMasReqI = texMasReq[i] != null ? texMasReq[i] : ""; langOtro.setTexto(texMasReqI.trim()); String idiomaMasReqI = idiomaMasReq[i] != null ? idiomaMasReq[i] : ""; langOtro.setIdioma(idiomaMasReqI); aLangOtros[i] = langOtro; } otros.setTextos(aLangOtros); masRequisitos[0] = otros; // descripcion duracion DescripcionVO taDescVO = new DescripcionVO(); LangStringVO[] aLangTADesc = new LangStringVO[descDura.length]; for (int i = 0; i < descDura.length; i++) { LangStringVO langTADesc = new LangStringVO(); String descDuraI = descDura[i] != null ? descDura[i] : ""; langTADesc.setTexto(descDuraI.trim()); String idiomaDuraI = idiomaDura[i] != null ? idiomaDura[i] : ""; langTADesc.setIdioma(idiomaDuraI); aLangTADesc[i] = langTADesc; } taDescVO.setTextos(aLangTADesc); textDura[0] = taDescVO; duracionDesc[0] = taDescVO; duracion.setDescripcion(duracionDesc[0]); }
From source file:com.yoctopuce.YoctoAPI.YModule.java
public String calibConvert(String param, String currentFuncValue, String unit_name, String sensorType) { int paramVer; int funVer;//from w w w . ja va2 s . c o m int funScale; int funOffset; int paramScale; int paramOffset; ArrayList<Integer> words = new ArrayList<Integer>(); ArrayList<String> words_str = new ArrayList<String>(); ArrayList<Double> calibData = new ArrayList<Double>(); ArrayList<Integer> iCalib = new ArrayList<Integer>(); int calibType; int i; int maxSize; double ratio; int nPoints; double wordVal; // Initial guess for parameter encoding paramVer = calibVersion(param); funVer = calibVersion(currentFuncValue); funScale = calibScale(unit_name, sensorType); funOffset = calibOffset(unit_name); paramScale = funScale; paramOffset = funOffset; if (funVer < 3) { if (funVer == 2) { words = SafeYAPI()._decodeWords(currentFuncValue); if ((words.get(0).intValue() == 1366) && (words.get(1).intValue() == 12500)) { funScale = 1; funOffset = 0; } else { funScale = words.get(1).intValue(); funOffset = words.get(0).intValue(); } } else { if (funVer == 1) { if (currentFuncValue.equals("") || (YAPI._atoi(currentFuncValue) > 10)) { funScale = 0; } } } } calibData.clear(); calibType = 0; if (paramVer < 3) { if (paramVer == 2) { words = SafeYAPI()._decodeWords(param); if ((words.get(0).intValue() == 1366) && (words.get(1).intValue() == 12500)) { paramScale = 1; paramOffset = 0; } else { paramScale = words.get(1).intValue(); paramOffset = words.get(0).intValue(); } if ((words.size() >= 3) && (words.get(2).intValue() > 0)) { maxSize = 3 + 2 * ((words.get(2).intValue()) % (10)); if (maxSize > words.size()) { maxSize = words.size(); } i = 3; while (i < maxSize) { calibData.add((double) words.get(i).intValue()); i = i + 1; } } } else { if (paramVer == 1) { words_str = new ArrayList<String>(Arrays.asList(param.split(","))); for (String ii : words_str) { words.add(YAPI._atoi(ii)); } if (param.equals("") || (words.get(0).intValue() > 10)) { paramScale = 0; } if ((words.size() > 0) && (words.get(0).intValue() > 0)) { maxSize = 1 + 2 * ((words.get(0).intValue()) % (10)); if (maxSize > words.size()) { maxSize = words.size(); } i = 1; while (i < maxSize) { calibData.add((double) words.get(i).intValue()); i = i + 1; } } } else { if (paramVer == 0) { ratio = Double.valueOf(param); if (ratio > 0) { calibData.add(0.0); calibData.add(0.0); calibData.add((double) Math.round(65535 / ratio)); calibData.add(65535.0); } } } } i = 0; while (i < calibData.size()) { if (paramScale > 0) { calibData.set(i, (calibData.get(i).doubleValue() - paramOffset) / paramScale); } else { calibData.set(i, SafeYAPI()._decimalToDouble((int) (double) Math.round(calibData.get(i).doubleValue()))); } i = i + 1; } } else { iCalib = SafeYAPI()._decodeFloats(param); calibType = (int) (double) Math.round(iCalib.get(0).doubleValue() / 1000.0); if (calibType >= 30) { calibType = calibType - 30; } i = 1; while (i < iCalib.size()) { calibData.add(iCalib.get(i).doubleValue() / 1000.0); i = i + 1; } } if (funVer >= 3) { if (calibData.size() == 0) { param = "0,"; } else { param = Integer.toString(30 + calibType); i = 0; while (i < calibData.size()) { if (((i) & (1)) > 0) { param = param + ":"; } else { param = param + " "; } param = param + Integer .toString((int) (double) Math.round(calibData.get(i).doubleValue() * 1000.0 / 1000.0)); i = i + 1; } param = param + ","; } } else { if (funVer >= 1) { nPoints = ((calibData.size()) / (2)); param = Integer.toString(nPoints); i = 0; while (i < 2 * nPoints) { if (funScale == 0) { wordVal = SafeYAPI() ._doubleToDecimal((int) (double) Math.round(calibData.get(i).doubleValue())); } else { wordVal = calibData.get(i).doubleValue() * funScale + funOffset; } param = param + "," + Double.toString((double) Math.round(wordVal)); i = i + 1; } } else { if (calibData.size() == 4) { param = Double.toString((double) Math .round(1000 * (calibData.get(3).doubleValue() - calibData.get(1).doubleValue()) / calibData.get(2).doubleValue() - calibData.get(0).doubleValue())); } } } return param; }
From source file:com.cohort.util.String2.java
/** * Given an arrayList which alternates attributeName (a String) and * attributeValue (an object), this either removes the attribute * (if value == null), adds the attribute and value (if it isn't in the list), * or changes the value (if the attriubte is in the list). * * @param arrayList //from www . jav a 2s . c om * @param attributeName * @param value the value associated with the attributeName * @return the previous value for the attribute (or null) * @throws RuntimeException of trouble (e.g., if arrayList is null) */ public static Object alternateSetValue(ArrayList arrayList, String attributeName, Object value) { if (arrayList == null) throw new SimpleException(ERROR + " in String2.alternateSetValue: arrayList is null."); int n = arrayList.size(); for (int i = 0; i < n; i += 2) { if (arrayList.get(i).toString().equals(attributeName)) { Object oldValue = arrayList.get(i + 1); if (value == null) { arrayList.remove(i + 1); //order of removal is important arrayList.remove(i); } else arrayList.set(i + 1, value); return oldValue; } } //attributeName not found? if (value == null) return null; else { //add it arrayList.add(attributeName); arrayList.add(value); return null; } }
From source file:org.akaza.openclinica.control.submit.DataEntryServlet.java
/** * Retrieve the DisplaySectionBean which will be used to display the Event CRF Section on the JSP, and also is used to controll processRequest. * @param request TODO/*from w w w .j ava2 s . co m*/ */ protected ArrayList getAllDisplayBeans(HttpServletRequest request) throws Exception { EventCRFBean ecb = (EventCRFBean) request.getAttribute(INPUT_EVENT_CRF); ArrayList sections = new ArrayList(); HttpSession session = request.getSession(); StudyBean study = (StudyBean) session.getAttribute("study"); SectionDAO sdao = new SectionDAO(getDataSource()); ItemDataDAO iddao = new ItemDataDAO(getDataSource(), locale); // ALL_SECTION_BEANS ArrayList<SectionBean> allSectionBeans = (ArrayList<SectionBean>) request.getAttribute(ALL_SECTION_BEANS); for (int j = 0; j < allSectionBeans.size(); j++) { SectionBean sb = allSectionBeans.get(j); DisplaySectionBean section = new DisplaySectionBean(); section.setEventCRF(ecb); if (sb.getParentId() > 0) { SectionBean parent = (SectionBean) sdao.findByPK(sb.getParentId()); sb.setParent(parent); } section.setSection(sb); CRFVersionDAO cvdao = new CRFVersionDAO(getDataSource()); CRFVersionBean cvb = (CRFVersionBean) cvdao.findByPK(ecb.getCRFVersionId()); section.setCrfVersion(cvb); CRFDAO cdao = new CRFDAO(getDataSource()); CRFBean cb = (CRFBean) cdao.findByPK(cvb.getCrfId()); section.setCrf(cb); EventDefinitionCRFDAO edcdao = new EventDefinitionCRFDAO(getDataSource()); EventDefinitionCRFBean edcb = edcdao.findByStudyEventIdAndCRFVersionId(study, ecb.getStudyEventId(), cvb.getId()); section.setEventDefinitionCRF(edcb); // setup DAO's here to avoid creating too many objects ItemDAO idao = new ItemDAO(getDataSource()); ItemFormMetadataDAO ifmdao = new ItemFormMetadataDAO(getDataSource()); iddao = new ItemDataDAO(getDataSource(), locale); // get all the display item beans ArrayList displayItems = getParentDisplayItems(false, sb, edcb, idao, ifmdao, iddao, false, request); LOGGER.debug("222 just ran get parent display, has group " + " FALSE has ungrouped FALSE"); // now sort them by ordinal Collections.sort(displayItems); // now get the child DisplayItemBeans for (int i = 0; i < displayItems.size(); i++) { DisplayItemBean dib = (DisplayItemBean) displayItems.get(i); dib.setChildren(getChildrenDisplayItems(dib, edcb, request)); if (shouldLoadDBValues(dib)) { LOGGER.trace("should load db values is true, set value"); dib.loadDBValue(); } displayItems.set(i, dib); } section.setItems(displayItems); sections.add(section); } return sections; }