code
stringlengths
10
174k
nl
stringlengths
3
129k
@Override public Object clone(){ try { IdentityHashMap<K,V> cloneHashMap=(IdentityHashMap<K,V>)super.clone(); cloneHashMap.elementData=newElementArray(elementData.length); System.arraycopy(elementData,0,cloneHashMap.elementData,0,elementData.length); return cloneHashMap; } catch ( CloneNotSupportedException e) { throw new AssertionError(e); } }
Returns a new IdentityHashMap with the same mappings and size as this one.
@Override public void detach(){ super.detach(); modules.getFilesModule().unbindUploadFile(rid,callback); }
Detach UploadFileVM from Messenger. Don't use object after detaching.
public SVGEllipseElementBridge(){ }
Constructs a new bridge for the &lt;ellipse> element.
public boolean isInBoundsX(float x){ if (isInBoundsLeft(x) && isInBoundsRight(x)) return true; else return false; }
BELOW METHODS FOR BOUNDS CHECK
@Override public int describeContents(){ return 0; }
Describe the kinds of special objects contained in the marshalled representation.
public boolean matches(String storageSystemNativeGuid){ String vplexStorageSystemId=getUniqueId(); s_logger.info(String.format("Matching the storageSystemNativeGuid %s with %s",storageSystemNativeGuid,vplexStorageSystemId)); if (storageSystemNativeGuid.contains(vplexStorageSystemId.trim())) { return true; } if (storageSystemNativeGuid.startsWith("IBMXIV+IBM")) { int decimalNum=0; try { decimalNum=Integer.parseInt(vplexStorageSystemId); } catch ( NumberFormatException nfe) { return false; } String hexString=Integer.toHexString(decimalNum); String subHexString=hexString.substring(1,hexString.length()); String decimalString=Integer.toString(Integer.parseInt(subHexString,16)); if (storageSystemNativeGuid.endsWith(decimalString)) { return true; } } return false; }
Check if the storageSystemNativeGuid matches with Vplex storage systems unique Id.
@RequestMapping(value=ApiUrl.COMPLAINT_UPDATE_STATUS,method=RequestMethod.PUT,produces=MediaType.TEXT_PLAIN_VALUE) public ResponseEntity<String> updateComplaintStatus(@PathVariable final String complaintNo,@RequestBody final JSONObject jsonData){ try { final Complaint complaint=complaintService.getComplaintByCRN(complaintNo); final ComplaintStatus cmpStatus=complaintStatusService.getByName(jsonData.get("action").toString()); String citizenfeedback=jsonData.get("feedback").toString(); if (complaint.getStatus().getName().equals("COMPLETED")) { if (UNSATISFACTORY.equals(citizenfeedback)) citizenfeedback=CitizenFeedback.TWO.name(); else if (SATISFACTORY.equals(citizenfeedback)) citizenfeedback=CitizenFeedback.FIVE.name(); complaint.setCitizenFeedback(CitizenFeedback.valueOf(citizenfeedback)); } complaint.setStatus(cmpStatus); complaintService.update(complaint,Long.valueOf(0),jsonData.get("comment").toString()); return getResponseHandler().success("",getMessage("msg.complaint.status.update.success")); } catch ( final Exception e) { LOGGER.error("EGOV-API ERROR ",e); return getResponseHandler().error(getMessage("server.error")); } }
This will update the status of the complaint.
public Html download(String url,String charset){ Page page=download(new Request(url),Site.me().setCharset(charset).toTask()); return (Html)page.getHtml(); }
A simple method to download a url.
@DSComment("Private Method") @DSBan(DSCat.PRIVATE_METHOD) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:58:22.871 -0500",hash_original_method="4DDABCDA44FFF28C561B2585B61E25F7",hash_generated_method="672B038178BC088608C17482EB0C7D6B") private void handleStatusReport(AsyncResult ar){ String pduString=(String)ar.result; SmsMessage sms=SmsMessage.newFromCDS(pduString); if (sms != null) { int tpStatus=sms.getStatus(); int messageRef=sms.messageRef; for (int i=0, count=deliveryPendingList.size(); i < count; i++) { SmsTracker tracker=deliveryPendingList.get(i); if (tracker.mMessageRef == messageRef) { if (tpStatus >= Sms.STATUS_FAILED || tpStatus < Sms.STATUS_PENDING) { deliveryPendingList.remove(i); } PendingIntent intent=tracker.mDeliveryIntent; Intent fillIn=new Intent(); fillIn.putExtra("pdu",IccUtils.hexStringToBytes(pduString)); fillIn.putExtra("format",android.telephony.SmsMessage.FORMAT_3GPP); try { intent.send(mContext,Activity.RESULT_OK,fillIn); } catch ( CanceledException ex) { } break; } } } acknowledgeLastIncomingSms(true,Intents.RESULT_SMS_HANDLED,null); }
Called when a status report is received. This should correspond to a previously successful SEND.
private void calculateUniqueValue(Object[] minValue,Object[] uniqueValue){ for (int i=0; i < measureCount; i++) { if (type[i] == CarbonCommonConstants.BIG_INT_MEASURE) { uniqueValue[i]=(long)minValue[i] - 1; } else if (type[i] == CarbonCommonConstants.BIG_DECIMAL_MEASURE) { BigDecimal val=(BigDecimal)minValue[i]; uniqueValue[i]=(val.subtract(new BigDecimal(1.0))); } else { uniqueValue[i]=(double)minValue[i] - 1; } } }
This method will calculate the unique value which will be used as storage key for null values of measures
private boolean isStreamCommand(String action){ switch (StreamAction.getEnum(action)) { case CREATE_STREAM: case DELETE_STREAM: case RELEASE_STREAM: case PUBLISH: case PLAY: case PLAY2: case SEEK: case PAUSE: case PAUSE_RAW: case CLOSE_STREAM: case RECEIVE_VIDEO: case RECEIVE_AUDIO: return true; default : log.debug("Stream action {} is not a recognized command",action); return false; } }
Checks if the passed action is a reserved stream method.
public static CCSplitRows action(int r,float d){ return new CCSplitRows(r,d); }
creates the action with the number of rows to split and the duration
public Type type(){ return type; }
Returns the type of the visit.
private synchronized CachedTexture resample(int width,int height){ for ( ResampleInfo resampleInfo : resampleInfos) { if (resampleInfo.matches(width,height)) { return resampleInfo.getCachedTextureResampled(); } } return resampleTexture(width,height); }
This method has to be synchronized because it can be used but multiple renderer threads in parallel (see RendererExecutor).
@Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.path_animations); mCanvasView=(CanvasView)findViewById(R.id.canvas); mCanvasView.addOnLayoutChangeListener(this); ((RadioGroup)findViewById(R.id.path_animation_type)).setOnCheckedChangeListener(this); }
Called when the activity is first created.
public static void evaluateCircuit(LogicCircuit lc,GateLibrary gate_library,Args options){ refreshGateAttributes(lc,gate_library); if (options.get_circuit_type() == DNACompiler.CircuitType.sequential) { SequentialHelper.setInitialRPUs(lc,gate_library); HashMap<String,ArrayList<ArrayList<Double>>> track_rpus=new HashMap<>(); for ( Gate g : lc.get_Gates()) { track_rpus.put(g.Name,new ArrayList<ArrayList<Double>>()); ArrayList<Double> copy_rpus=new ArrayList<Double>(g.get_outrpus()); track_rpus.get(g.Name).add(copy_rpus); track_rpus.get(g.Name).add(copy_rpus); } boolean converges=SequentialHelper.convergeRPUs(lc,gate_library,options,track_rpus); if (!converges) { lc.get_scores().set_onoff_ratio(0.0); lc.get_scores().set_noise_margin_contract(false); return; } } else if (options.get_circuit_type() == DNACompiler.CircuitType.combinational) { simulateRPU(lc,gate_library,options); } evaluateCircuitONOFFRatio(lc); if (options.is_noise_margin()) { evaluateCircuitNoiseMargin(lc,options); } if (options.is_snr()) { evaluateCircuitSNR(lc,options); } }
The function evaluateCircuit calls other evaluate functions based on the circuit_score chose by user. -circuit_score onoff_ratio score = log(ON/OFF), where ON is the lowest ON in the truthtable, and OFF is the highest off in the truthtable -circuit_score noise_margin noise margin is computed from input RPU distance from low margin (if low) or high margin (if high) score = average noise margin of all logic gates used for NOR/NOT only, and cannot be used if there are input gates and no logic gates -circuit_score histogram score = 1 - overlap penalty, where overlap is from the worst pair among ONs and OFFs in the truthtable Circuit is evaluated by evaluating each gate, so the same function calls appear but with a Gate parameter instead of LogicCircuit parameter
protected boolean mustShowHostileIndicator(){ String id=this.symbolCode.getStandardIdentity(); boolean isHostile=SymbologyConstants.STANDARD_IDENTITY_HOSTILE.equalsIgnoreCase(id) || SymbologyConstants.STANDARD_IDENTITY_SUSPECT.equalsIgnoreCase(id) || SymbologyConstants.STANDARD_IDENTITY_FAKER.equalsIgnoreCase(id)|| SymbologyConstants.STANDARD_IDENTITY_JOKER.equalsIgnoreCase(id); return this.isShowHostileIndicator() && isHostile; }
Indicates whether or not the graphic must display the hostile/enemy indicator, if the graphic supports the indicator.
public ObjectMatrix1D like(int size){ return new SparseObjectMatrix1D(size); }
Construct and returns a new empty matrix <i>of the same dynamic type</i> as the receiver, having the specified size. For example, if the receiver is an instance of type <tt>DenseObjectMatrix1D</tt> the new matrix must also be of type <tt>DenseObjectMatrix1D</tt>, if the receiver is an instance of type <tt>SparseObjectMatrix1D</tt> the new matrix must also be of type <tt>SparseObjectMatrix1D</tt>, etc. In general, the new matrix should have internal parametrization as similar as possible.
@Override public IBinder onBind(Intent intent){ return syncAdapter.getSyncAdapterBinder(); }
Return an object that allows the system to invoke the sync adapter.
public static double convertMillisToMinutes(double millis){ return millis / MINUTE_TO_MILLIS; }
Converts time in milliseconds to time in minutes.
@Override public void actionPerformed(ActionEvent evt){ kseFrame.setDefaultStatusBarText(); if (!recentFile.isFile()) { JMenuItemRecentFile jmiRecentFile=(JMenuItemRecentFile)evt.getSource(); JMenuRecentFiles jmRecentFiles=jmiRecentFile.getRecentFilesMenu(); jmRecentFiles.invalidate(jmiRecentFile); JOptionPane.showMessageDialog(kseFrame.getUnderlyingFrame(),MessageFormat.format(res.getString("RecentKeyStoreFileActionListener.NotFile.message"),recentFile),res.getString("RecentKeyStoreFileActionListener.OpenKeyStore.Title"),JOptionPane.WARNING_MESSAGE); return; } OpenAction openAction=new OpenAction(kseFrame); openAction.openKeyStore(recentFile); }
Action to perform to open the KeyStore file in response to an ActionEvent.
@Override public void start(){ if (started) return; server.getActivation().haStarted(); started=true; }
starts the HA manager.
@Override public List<Metric> transform(List<Metric> metrics){ return union(metrics); }
If constants is not null, apply mapping transform to metrics list. Otherwise, apply reduce transform to metrics list
protected void comment(Element elem) throws BadLocationException, IOException { AttributeSet as=elem.getAttributes(); if (matchNameAttribute(as,HTML.Tag.COMMENT)) { Object comment=as.getAttribute(HTML.Attribute.COMMENT); if (comment instanceof String) { writeComment((String)comment); } else { writeComment(null); } } }
Writes out comments.
public static void nullifyWorkDirectory(){ igniteWork=null; }
Nullifies work directory. For test purposes only.
protected WeaponFireInfo(Princess owner){ this.owner=owner; }
For unit testing.
public MosaicDefinitionCreationTransaction(final TimeInstant timeStamp,final Account sender,final MosaicDefinition mosaicDefinition){ this(timeStamp,sender,mosaicDefinition,MosaicConstants.MOSAIC_CREATION_FEE_SINK,Amount.fromNem(50000)); }
Creates a new mosaic definition creation transaction.
static byte[] hmacMD5(final byte[] value,final byte[] key) throws AuthenticationException { final HMACMD5 hmacMD5=new HMACMD5(key); hmacMD5.update(value); return hmacMD5.getOutput(); }
Calculates HMAC-MD5
public FilteredTollHandler(final double simulationEndTime,final int numberOfTimeBins,final String shapeFile,final Network network){ this(simulationEndTime,numberOfTimeBins,shapeFile,network,null); LOGGER.info("Area filtering is used, result will include links falls inside the given shape and persons from all user groups."); }
Area filtering will be used, result will include links falls inside the given shape and persons from all user groups.
public void destroySubcontext(String name) throws NamingException { destroySubcontext(nameParser.parse(name)); }
Destroys subcontext with name name.
public MutableLong(final String value) throws NumberFormatException { super(); this.value=Long.parseLong(value); }
Constructs a new MutableLong parsing the given string.
@Override public String toString(){ return new String(toByteArray()); }
Gets the curent contents of this byte stream as a string.
public float fastLength(){ return Vector3.fastLength(this); }
Returns a fast approximation of this vector's length.
public long addJustifications(final IChunkedIterator<Justification> itr){ try { if (!itr.hasNext()) return 0; final long begin=System.currentTimeMillis(); long nwritten=0; final IIndex ndx=getJustificationIndex(); final JustificationTupleSerializer tupleSer=(JustificationTupleSerializer)ndx.getIndexMetadata().getTupleSerializer(); while (itr.hasNext()) { final Justification[] a=itr.nextChunk(); final int n=a.length; Arrays.sort(a); final byte[][] keys=new byte[n][]; for (int i=0; i < n; i++) { keys[i]=tupleSer.serializeKey(a[i]); } final LongAggregator aggregator=new LongAggregator(); ndx.submit(0,n,keys,null,WriteJustificationsProcConstructor.INSTANCE,aggregator); nwritten+=aggregator.getResult(); } final long elapsed=System.currentTimeMillis() - begin; if (log.isInfoEnabled()) log.info("Wrote " + nwritten + " justifications in "+ elapsed+ " ms"); return nwritten; } finally { itr.close(); } }
Adds justifications to the store.
public void processItem(Item item,StringTokenizer numberTokens){ if (numberTokens.hasMoreTokens()) { int firstNumber=Integer.valueOf(numberTokens.nextToken()); if (numberTokens.hasMoreTokens()) { Item child=(Item)getItemMap().get(firstNumber - 1); if (child == null) { String itemName=item.getNumberString(); for (int i=0; i < numberTokens.countTokens(); i++) { if (itemName.lastIndexOf('.') != -1) { itemName=itemName.substring(0,itemName.lastIndexOf('.')); } } child=new Item(itemName); child.setNumberString(itemName); getItemMap().put(firstNumber - 1,child); } if (getLog().isDebugEnabled()) { getLog().debug(getName() + " - branch: " + child.getName()+ " - child added: "+ item.getName()); } child.processItem(item,numberTokens); } else { getItemMap().put(firstNumber - 1,item); if (getLog().isDebugEnabled()) { getLog().debug(getName() + " - new child: " + (firstNumber - 1)+ "-"+ item.getName()); } } } }
Adds the item as child if there is only one token left in numberTokens Theses last token is the child number. If there is more than one token left, the item is passed to the child with the first token number.
public boolean isTechnologyProviderDisabled(){ return isTechnologyProvider() && isPersistedRole(OrganizationRoleType.TECHNOLOGY_PROVIDER); }
Reflects the state of the role in relation to persisted object.
public void exportXML(File xml) throws DataIOException, FileNotFoundException { FileOutputStream xmlFos=new FileOutputStream(xml); GraphMLWriter writer=new GraphMLWriter(); writer.writeGraph(getExportGraph(),xmlFos); }
Writes the graphs XML content to the provided File.
@Override public boolean equals(Object object){ if (this == object) { return true; } if (object instanceof Map) { Map<?,?> map=(Map)object; if (size() != map.size()) { return false; } Set<Entry<K,V>> set=entrySet(); return set.equals(map.entrySet()); } return false; }
Compares this map with other objects. This map is equal to another map is it represents the same set of mappings. With this map, two mappings are the same if both the key and the value are equal by reference. When compared with a map that is not an IdentityHashMap, the equals method is neither necessarily symmetric (a.equals(b) implies b.equals(a)) nor transitive (a.equals(b) and b.equals(c) implies a.equals(c)).
@Override public TopicSession createTopicSession(final boolean transacted,final int acknowledgeMode) throws JMSException { if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("createTopicSession(" + transacted + ", "+ acknowledgeMode+ ")"); } checkClosed(); if (type == ActiveMQRAConnectionFactory.QUEUE_CONNECTION || type == ActiveMQRAConnectionFactory.XA_QUEUE_CONNECTION) { throw new IllegalStateException("Can not get a topic session from a queue connection"); } return allocateConnection(transacted,acknowledgeMode,type); }
Create a topic session
public SpanWithinQuery(SpanQuery big,SpanQuery little){ super(big,little); }
Construct a SpanWithinQuery matching spans from <code>little</code> that are inside of <code>big</code>. This query has the boost of <code>little</code>. <code>big</code> and <code>little</code> must be in the same field.
public void receiveErrorqueryDRSMigrationCapabilityForPerformance(java.lang.Exception e){ }
auto generated Axis2 Error handler override this method for handling error response from queryDRSMigrationCapabilityForPerformance operation
public MessageBox.Result confirm(String msg){ this.msg=msg; if (choice == YES_TO_ALL || choice == NO_TO_ALL) return choice; FutureTask<MessageBox.Result> fut=new FutureTask<>(this); Platform.runLater(fut); try { return fut.get(); } catch ( Exception ignored) { return NO; } }
Execute confirmation in EDT thread.
public boolean isLogicalFunction(){ return false; }
Min3 is not a logical function.
public boolean equals(Object other){ if (!this.getClass().equals(other.getClass())) return false; else { TCPMessageChannel that=(TCPMessageChannel)other; if (this.mySock != that.mySock) return false; else return true; } }
Equals predicate.
protected List<MailetMatcherDescriptor> buildDescriptors(MavenProject project){ logProject(project); return new DefaultDescriptorsExtractor().extract(project,getLog()).descriptors(); }
Builds descriptors for the given project only, without recursion.
MethodDoc methodDoc(){ return methodDoc; }
Returns the MethodDoc object corresponding to this method of a remote interface.
public void add(final long commitTime){ if (commitTime == 0L) throw new IllegalArgumentException(); final byte[] key=encodeKey(commitTime); if (!super.contains(key)) { super.insert(key,null); } }
Add an entry for the commitTime.
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { request.getSession().setAttribute("school","lyun"); response.sendRedirect("servlet/SchoolServlet"); return; }
The doGet method of the servlet. <br> This method is called when a form has its tag value method equals to get.
@SuppressWarnings("unused") private void debugTime(String s,boolean collectGarbage){ if (false) { if (collectGarbage) System.gc(); System.out.println(s + ": " + System.currentTimeMillis()); } }
This debug/profiling function will print the current time (in milliseconds) to the log. If the boolean is true, the garbage collector will be called in an attempt to minimize timing errors. You should try and minimize applications being run in the background when using this function. Note that MS Windows only has 10 milisecond resolution. The function should be optimized completely out of the code when the first if-statement below reads "if (false)...", so performance shouldn't be impacted if you leave calls to this function in the code (I think).
public static void waitForClientAck() throws Exception { final long maxWaitTime=30000; final long start=System.currentTimeMillis(); Iterator iter=pool.getThreadIdToSequenceIdMap().entrySet().iterator(); SequenceIdAndExpirationObject seo=null; if (!iter.hasNext()) { fail("map is empty"); } Map.Entry entry=(Map.Entry)iter.next(); seo=(SequenceIdAndExpirationObject)entry.getValue(); for (; ; ) { if (seo.getAckSend()) { break; } assertTrue("Waited over " + maxWaitTime + " for client ack ",+(System.currentTimeMillis() - start) < maxWaitTime); sleep(1000); } LogWriterUtils.getLogWriter().info("seo = " + seo); assertTrue("Creation time " + creationTime + " supposed to be same as seo "+ seo.getCreationTime(),creationTime == seo.getCreationTime()); }
Wait for acknowledgment from client, verify creation time is correct
@Override public void onClick(AjaxRequestTarget aTarget){ curationPanel.resetEditor(aTarget); List<SourceDocument> listOfSourceDocuements=getListOfDocs(); int currentDocumentIndex=listOfSourceDocuements.indexOf(bModel.getDocument()); if (currentDocumentIndex == 0) { aTarget.appendJavaScript("alert('This is the first document!')"); } else { bModel.setDocumentName(listOfSourceDocuements.get(currentDocumentIndex - 1).getName()); bModel.setDocument(listOfSourceDocuements.get(currentDocumentIndex - 1)); try { repository.upgradeCasAndSave(bModel.getDocument(),Mode.CURATION,bModel.getUser().getUsername()); loadDocumentAction(aTarget); } catch ( IOException|UIMAException|ClassNotFoundException|BratAnnotationException e) { aTarget.add(getFeedbackPanel()); error(e.getCause().getMessage()); } } }
Get the current beginning sentence address and add on it the size of the display window
public ViewPropertyAnimator scaleX(float value){ animateProperty(SCALE_X,value); return this; }
This method will cause the View's <code>scaleX</code> property to be animated to the specified value. Animations already running on the property will be canceled.
@Override public Object eGet(int featureID,boolean resolve,boolean coreType){ switch (featureID) { case RegularExpressionPackage.CHARACTER_CLASS_ATOM__CHARACTER: return getCharacter(); } return super.eGet(featureID,resolve,coreType); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public void testSameNodeInFromToSetCheapest(){ Fixture f=new Fixture(); TestTimeCost tc=new TestTimeCost(); tc.setData(Id.create(1,Link.class),2.0,2.0); tc.setData(Id.create(2,Link.class),1.0,1.0); tc.setData(Id.create(3,Link.class),3.0,3.0); tc.setData(Id.create(4,Link.class),2.0,2.0); tc.setData(Id.create(5,Link.class),1.0,1.0); tc.setData(Id.create(6,Link.class),3.0,3.0); tc.setData(Id.create(7,Link.class),4.0,4.0); MultiNodeDijkstra dijkstra=new MultiNodeDijkstra(f.network,tc,tc); Map<Node,InitialNode> fromNodes=new HashMap<Node,InitialNode>(); fromNodes.put(f.network.getNodes().get(Id.create(2,Node.class)),new InitialNode(2.0,2.0)); fromNodes.put(f.network.getNodes().get(Id.create(4,Node.class)),new InitialNode(1.0,1.0)); Map<Node,InitialNode> toNodes=new HashMap<Node,InitialNode>(); toNodes.put(f.network.getNodes().get(Id.create(4,Node.class)),new InitialNode(1.0,1.0)); toNodes.put(f.network.getNodes().get(Id.create(6,Node.class)),new InitialNode(3.0,3.0)); Path p=dijkstra.calcLeastCostPath(fromNodes,toNodes,null); assertNotNull("no path found!",p); assertEquals(0,p.links.size()); assertEquals(1,p.nodes.size()); assertEquals("4",p.nodes.get(0).getId().toString()); }
Tests that a path is found if some links are in the set of start as well as in the set of end nodes and the path only containing of this node is the cheapest.
public int searchUShort(int startIndex,int startOffset,int endIndex,int endOffset,int length,int key){ int location=0; int bottom=0; int top=length; while (top != bottom) { location=(top + bottom) / 2; int locationStart=this.readUShort(startIndex + location * startOffset); if (key < locationStart) { top=location; } else { int locationEnd=this.readUShort(endIndex + location * endOffset); if (key <= locationEnd) { return location; } bottom=location + 1; } } return -1; }
Search for the key value in the range tables provided. The search looks through the start-end pairs looking for the key value. It is assumed that the start-end pairs are both represented by UShort values, ranges do not overlap, and are monotonically increasing.
public CtClass makeClass(ClassFile classfile) throws RuntimeException { return makeClass(classfile,true); }
Creates a new class (or interface) from the given class file. If there already exists a class with the same name, the new class overwrites that previous class. <p>This method is used for creating a <code>CtClass</code> object directly from a class file. The qualified class name is obtained from the class file; you do not have to explicitly give the name.
protected void closeDatabase(final DefaultIndexImpl<?,?> indexImpl) throws NoSuchFieldException, IllegalAccessException { final Field firstDatabaseField=indexImpl.getClass().getDeclaredField(DATABASE_FIELD_NAME); firstDatabaseField.setAccessible(true); final Database firstDatabase=(Database)firstDatabaseField.get(indexImpl); if (firstDatabase != null) { firstDatabase.close(); } }
Before environment can be closed all opened databases should be closed first. Links to these databases stored in fields of DefaultBiIndexImpl. We obtain them by their names. It is not good. But it seems that there is not way to obtain them from Environment instance.
public void forceReloadAll(){ fFilesToReoad.addAll(fStateMap.keySet()); }
Adds all the indicator files in this project to the list of files need to be reloaded.
@RequestProcessing(value="/activities",method=HTTPRequestMethod.GET) @Before(adviceClass={StopwatchStartAdvice.class,LoginCheck.class}) @After(adviceClass=StopwatchEndAdvice.class) public void showActivities(final HTTPRequestContext context,final HttpServletRequest request,final HttpServletResponse response) throws Exception { request.setAttribute(Keys.TEMAPLTE_DIR_NAME,Symphonys.get("skinDirName")); final AbstractFreeMarkerRenderer renderer=new SkinRenderer(); context.setRenderer(renderer); renderer.setTemplateName("/home/activities.ftl"); final Map<String,Object> dataModel=renderer.getDataModel(); filler.fillHeaderAndFooter(request,response,dataModel); filler.fillRandomArticles(dataModel); filler.fillHotArticles(dataModel); filler.fillSideTags(dataModel); filler.fillLatestCmts(dataModel); }
Shows activity page.
public boolean equals(Object obj){ if (obj == this) { return true; } if (!(obj instanceof VwapDataset)) { return false; } VwapDataset that=(VwapDataset)obj; if (!this.xPosition.equals(that.xPosition)) { return false; } return ObjectUtilities.equal(this.data,that.data); }
Tests this instance for equality with an arbitrary object.
public static void paintText(Graphics g,AbstractButton b,Rectangle textRect,String text,int textShiftOffset){ FontMetrics fm=MySwingUtilities2.getFontMetrics(b,g); int mnemIndex=b.getDisplayedMnemonicIndex(); if (isMnemonicHidden() == true) { mnemIndex=-1; } { paintClassicText(b,g,textRect.x + textShiftOffset,textRect.y + fm.getAscent() + textShiftOffset,text,mnemIndex); } }
Renders a text String in Windows without the mnemonic. This is here because the WindowsUI hiearchy doesn't match the Component heirarchy. All the overriden paintText methods of the ButtonUI delegates will call this static method. <p>
public static String toString(Object bean){ try { final ByteArrayOutputStream baos=new ByteArrayOutputStream(); final Marshaller m=createMarshaller(); m.setProperty(m.JAXB_FRAGMENT,Boolean.TRUE); m.marshal(bean,baos); return baos.toString(); } catch ( JAXBException x) { final IllegalArgumentException iae=new IllegalArgumentException("Failed to write SessionConfigBean: " + x,x); throw iae; } }
Creates an XML string representation of the given bean.
public void prepare() throws ReplicatorException, InterruptedException { }
Connect to the underlying database containing THL.
@SuppressWarnings("unchecked") protected void notifyTestSetProduced(TestSetEvent tse){ Vector<TestSetListener> l; synchronized (this) { l=(Vector<TestSetListener>)m_listeners.clone(); } if (l.size() > 0) { for (int i=0; i < l.size(); i++) { if (m_receivedStopNotification) { if (m_logger != null) { m_logger.logMessage("[TestSetMaker] " + statusMessagePrefix() + " stopping."); m_logger.statusMessage(statusMessagePrefix() + "INTERRUPTED"); } m_receivedStopNotification=false; break; } l.elementAt(i).acceptTestSet(tse); } } }
Tells all listeners that a test set is available
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:36:01.266 -0500",hash_original_method="A041F8E96FF7F1638DE5EDEE0D23FE8B",hash_generated_method="5EF2B59EC71A41C6F2469CE5E44BCCC8") public boolean isGroupOwner(){ return (groupCapability & GROUP_CAPAB_GROUP_OWNER) != 0; }
Returns true if the device is a group owner
@Override public void configureZone(final StendhalRPZone zone,final Map<String,String> attributes){ buildNPC(zone); }
Configure a zone.
String findAndBind(Properties ldapProperties,String baseDN,String searchFilter,String password) throws LoginException { String realUserDN=null; boolean bindSuccessful=false; try { realUserDN=userSearch(ldapProperties,baseDN,searchFilter); if (realUserDN == null) { throw new LoginException("No User found for '" + searchFilter + "'."); } bindSuccessful=bindAsUser(ldapProperties,realUserDN,password); if (bindSuccessful == false) { throw new LoginException("Bind with DN '" + realUserDN + "' failed."); } } catch ( NamingException e) { throw new LoginException(e.toString()); } return realUserDN; }
Search the user in the LDAP and perform a bind to his data name.
public int noOfKthNearest(){ return m_KthNearestSize; }
returns the number of k nearest.
public static boolean isWhitespace(char c){ return !RegExpUtils.resetAndTest(regexpNotWhitespace,String.valueOf(c)); }
Returns true if a character is whitespace according to Unicode 6.0.
public static final Field TRUNCATE_COLUMN(int length){ if (length <= 0) throw new IllegalArgumentException("The truncation length must be positive"); return Field.create("column.truncate.to." + length + ".chars").withValidation(null).withDescription("A comma-separated list of regular expressions matching fully-qualified names of columns that should " + "be truncated to " + length + " characters."); }
Method that generates a Field for specifying that string columns whose names match a set of regular expressions should have their values truncated to be no longer than the specified number of characters.
public Book(String id,String name,String author,String description){ this.id=id; this.name=name; this.description=description; this.author=author; }
Creates a new instance of Book
@Override public int eDerivedStructuralFeatureID(int baseFeatureID,Class<?> baseClass){ if (baseClass == TAnnotableElement.class) { switch (baseFeatureID) { case TypesPackage.TANNOTABLE_ELEMENT__ANNOTATIONS: return TypesPackage.TFORMAL_PARAMETER__ANNOTATIONS; default : return -1; } } if (baseClass == SyntaxRelatedTElement.class) { switch (baseFeatureID) { case TypesPackage.SYNTAX_RELATED_TELEMENT__AST_ELEMENT: return TypesPackage.TFORMAL_PARAMETER__AST_ELEMENT; default : return -1; } } return super.eDerivedStructuralFeatureID(baseFeatureID,baseClass); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public static String createHash(String password) throws NoSuchAlgorithmException, InvalidKeySpecException { return createHash(password.toCharArray()); }
Returns a salted PBKDF2 hash of the password.
public boolean onBackPressed(){ return false; }
Listener the back key click event.
private void putAllUsers(Map<String,User> users,LDAPConnection ldapConnection,String usernameAttribute) throws GuacamoleException { try { LDAPSearchResults results=ldapConnection.search(confService.getUserBaseDN(),LDAPConnection.SCOPE_SUB,"(&(objectClass=*)(" + escapingService.escapeLDAPSearchFilter(usernameAttribute) + "=*))",null,false); while (results.hasMore()) { LDAPEntry entry=results.next(); LDAPAttribute username=entry.getAttribute(usernameAttribute); if (username == null) { logger.warn("Queried user is missing the username attribute \"{}\".",usernameAttribute); continue; } String identifier=username.getStringValue(); if (users.put(identifier,new SimpleUser(identifier)) != null) logger.warn("Possibly ambiguous user account: \"{}\".",identifier); } } catch ( LDAPException e) { throw new GuacamoleServerException("Error while querying users.",e); } }
Adds all Guacamole users accessible to the user currently bound under the given LDAP connection to the provided map. Only users with the specified attribute are added. If the same username is encountered multiple times, warnings about possible ambiguity will be logged.
public DataOutputStream(java.io.OutputStream out){ }
Creates a new data output stream to write data to the specified underlying output stream. out - the underlying output stream, to be saved for later use.
public boolean isPreDestroyCalled(){ return this.preDestroyCalled; }
Getter for property preDestroyCalled.
private void updateProgress(int progress){ if (myHost != null && progress != previousProgress) { myHost.updateProgress(progress); } previousProgress=progress; }
Used to communicate a progress update between a plugin tool and the main Whitebox user interface.
protected boolean ensureFreeCapacity(){ return true; }
Returns whether there is capacity for at least one more element. The default implementation always returns true. Derived classes that implement a Cache limit (LFU, LRU, ...) can either create free room or return false if the Cache is full.
private String loadHTMLData(String body){ StringBuilder builder=new StringBuilder().append(UIManager.WEB_STYLE).append(UIManager.WEB_LOAD_IMAGES); SharedPreferences preferences=SharePreferenceManager.getApplicationSetting(this); int theme=preferences.getInt(ApplicationSetting.KEY_THEME,ApplicationTheme.LIGHT.getKey()); if (theme == SharePreferenceManager.ApplicationSetting.ApplicationTheme.DARK.getKey()) { builder.append("<body class='night'><div class='contentstyle' id='article_body'>"); } else { builder.append("<body><div class='contentstyle' id='article_body'>"); } return builder.append(setupContentImage(body)).append("</div></body>").toString(); }
load html form remote
public java.io.InputStream readAsciiStream() throws SQLException { return (java.io.InputStream)getNextAttribute(); }
Returns the next attribute in this <code>SQLInputImpl</code> object as a stream of ASCII characters. <P> This method does not perform type-safe checking to determine if the returned type is the expected type as this responsibility is delegated to the UDT mapping as implemented by a <code>SQLData</code> implementation.
public boolean parseXmlResource(Object resourceName,InputSource source){ XMLReader reader; source.setEncoding("UTF8"); try { reader=XMLReaderFactory.createXMLReader(); } catch ( SAXException e) { if (logger.isLoggable(Level.SEVERE)) { logger.warning("Failed to create reader for " + resourceName + ": "+ e.getMessage()); } return false; } boolean status=false; reader.setContentHandler(this); reader.setErrorHandler(this); try { reader.parse(source); status=true; } catch ( SAXParseException e) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Failed to parse " + resourceName + " Line: "+ e.getLineNumber()+ " Col: "+ e.getColumnNumber()+ ": "+ e); } } catch ( SAXException e) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Failed to parse " + resourceName + e.getMessage()); } } catch ( IOException e) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Failed to parse " + resourceName + ":"+ e.getMessage()); } } return status; }
Parse from the given source. The source will not be closed after the parse: the caller should do this. Exceptions are logged rather than thrown. If an exception occurs the return value will be false to indicate that fact.
private static int findFreePort(){ ServerSocket socket=null; try { socket=new ServerSocket(0); socket.setReuseAddress(true); int port=socket.getLocalPort(); try { socket.close(); } catch ( IOException e) { } return port; } catch ( Exception e) { } finally { if (socket != null) { try { socket.close(); } catch ( IOException e) { throw new RuntimeException(e); } } } return 2181; }
For finding the free port available.
@DSComment("no security concern") @DSSafe(DSCat.SAFE_OTHERS) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 13:01:45.818 -0500",hash_original_method="33160DF8469148C6436960E1E1B046E8",hash_generated_method="3B463090CD85133EA75742B90CB4B38A") public HttpEntityWrapper(HttpEntity wrapped){ super(); if (wrapped == null) { throw new IllegalArgumentException("wrapped entity must not be null"); } wrappedEntity=wrapped; }
Creates a new entity wrapper.
public void highlight(double x,double y,double width,double height){ ps.append(String.format(Locale.US,"%1.3f %1.3f %1.3f %1.3f highlight\n",x,y,width,height)); }
Make red box
public static SAXParser newSAXParser(String schemaLanguage,File schema) throws SAXException, ParserConfigurationException { return newSAXParser(schemaLanguage,true,false,schema); }
Factory method to create a SAXParser configured to validate according to a particular schema language and a File containing the schema to validate against. The created SAXParser will be namespace-aware and not validate against DTDs.
@Override public String toString(){ StringBuilder sb=new StringBuilder(256); sb.append("("); sb.append(getSubject()); sb.append(", "); sb.append(getPredicate()); sb.append(", "); sb.append(getObject()); sb.append(")"); return sb.toString(); }
Gives a String-representation of this Statement that can be used for debugging.
public PostgreSQLEnvironment() throws GuacamoleException { super(); Boolean disallowSimultaneous=getProperty(PostgreSQLGuacamoleProperties.POSTGRESQL_DISALLOW_SIMULTANEOUS_CONNECTIONS); Boolean disallowDuplicate=getProperty(PostgreSQLGuacamoleProperties.POSTGRESQL_DISALLOW_DUPLICATE_CONNECTIONS); if (disallowSimultaneous != null) { if (disallowSimultaneous) { DEFAULT_MAX_CONNECTIONS=1; DEFAULT_MAX_GROUP_CONNECTIONS=0; } else { DEFAULT_MAX_CONNECTIONS=0; DEFAULT_MAX_GROUP_CONNECTIONS=0; } logger.warn("The \"{}\" property is deprecated. Use \"{}\" and \"{}\" instead.",PostgreSQLGuacamoleProperties.POSTGRESQL_DISALLOW_SIMULTANEOUS_CONNECTIONS.getName(),PostgreSQLGuacamoleProperties.POSTGRESQL_DEFAULT_MAX_CONNECTIONS.getName(),PostgreSQLGuacamoleProperties.POSTGRESQL_DEFAULT_MAX_GROUP_CONNECTIONS.getName()); logger.info("To achieve the same result of setting \"{}\" to \"{}\", set \"{}\" to \"{}\" and \"{}\" to \"{}\".",PostgreSQLGuacamoleProperties.POSTGRESQL_DISALLOW_SIMULTANEOUS_CONNECTIONS.getName(),disallowSimultaneous,PostgreSQLGuacamoleProperties.POSTGRESQL_DEFAULT_MAX_CONNECTIONS.getName(),DEFAULT_MAX_CONNECTIONS,PostgreSQLGuacamoleProperties.POSTGRESQL_DEFAULT_MAX_GROUP_CONNECTIONS.getName(),DEFAULT_MAX_GROUP_CONNECTIONS); } if (disallowDuplicate != null) { if (disallowDuplicate) { DEFAULT_MAX_CONNECTIONS_PER_USER=1; DEFAULT_MAX_GROUP_CONNECTIONS_PER_USER=1; } else { DEFAULT_MAX_CONNECTIONS_PER_USER=0; DEFAULT_MAX_GROUP_CONNECTIONS_PER_USER=0; } logger.warn("The \"{}\" property is deprecated. Use \"{}\" and \"{}\" instead.",PostgreSQLGuacamoleProperties.POSTGRESQL_DISALLOW_DUPLICATE_CONNECTIONS.getName(),PostgreSQLGuacamoleProperties.POSTGRESQL_DEFAULT_MAX_CONNECTIONS_PER_USER.getName(),PostgreSQLGuacamoleProperties.POSTGRESQL_DEFAULT_MAX_GROUP_CONNECTIONS.getName()); logger.info("To achieve the same result of setting \"{}\" to \"{}\", set \"{}\" to \"{}\" and \"{}\" to \"{}\".",PostgreSQLGuacamoleProperties.POSTGRESQL_DISALLOW_DUPLICATE_CONNECTIONS.getName(),disallowDuplicate,PostgreSQLGuacamoleProperties.POSTGRESQL_DEFAULT_MAX_CONNECTIONS_PER_USER.getName(),DEFAULT_MAX_CONNECTIONS_PER_USER,PostgreSQLGuacamoleProperties.POSTGRESQL_DEFAULT_MAX_GROUP_CONNECTIONS_PER_USER.getName(),DEFAULT_MAX_GROUP_CONNECTIONS_PER_USER); } }
Constructs a new PostgreSQLEnvironment, providing access to PostgreSQL-specific configuration options.
public Object remove(int index){ Object old=get(index); content.remove(index); modCount++; return old; }
Removes the element at the specified position in this list (optional operation). Shifts any subsequent elements to the left (subtracts one from their indices). Returns the element that was removed from the list.<p>
protected SampledVertexDecorator(V delegate){ super(delegate); }
Creates a new decorator for <tt>delegate</tt>.
protected void processCloudletSubmit(SimEvent ev,boolean ack){ updateCloudletProcessing(); try { Cloudlet cl=(Cloudlet)ev.getData(); if (cl.isFinished()) { String name=CloudSim.getEntityName(cl.getUserId()); Log.printConcatLine(getName(),": Warning - Cloudlet #",cl.getCloudletId()," owned by ",name," is already completed/finished."); Log.printLine("Therefore, it is not being executed again"); Log.printLine(); if (ack) { int[] data=new int[3]; data[0]=getId(); data[1]=cl.getCloudletId(); data[2]=CloudSimTags.FALSE; int tag=CloudSimTags.CLOUDLET_SUBMIT_ACK; sendNow(cl.getUserId(),tag,data); } sendNow(cl.getUserId(),CloudSimTags.CLOUDLET_RETURN,cl); return; } cl.setResourceParameter(getId(),getCharacteristics().getCostPerSecond(),getCharacteristics().getCostPerBw()); int userId=cl.getUserId(); int vmId=cl.getVmId(); double fileTransferTime=predictFileTransferTime(cl.getRequiredFiles()); Host host=getVmAllocationPolicy().getHost(vmId,userId); Vm vm=host.getVm(vmId,userId); CloudletScheduler scheduler=vm.getCloudletScheduler(); double estimatedFinishTime=scheduler.cloudletSubmit(cl,fileTransferTime); if (estimatedFinishTime > 0.0 && !Double.isInfinite(estimatedFinishTime)) { estimatedFinishTime+=fileTransferTime; send(getId(),estimatedFinishTime,CloudSimTags.VM_DATACENTER_EVENT); } if (ack) { int[] data=new int[3]; data[0]=getId(); data[1]=cl.getCloudletId(); data[2]=CloudSimTags.TRUE; int tag=CloudSimTags.CLOUDLET_SUBMIT_ACK; sendNow(cl.getUserId(),tag,data); } } catch ( ClassCastException c) { Log.printLine(getName() + ".processCloudletSubmit(): " + "ClassCastException error."); c.printStackTrace(); } catch ( Exception e) { Log.printLine(getName() + ".processCloudletSubmit(): " + "Exception error."); e.printStackTrace(); } checkCloudletCompletion(); }
Processes a Cloudlet submission.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 13:01:49.717 -0500",hash_original_method="8F463ADE51DCD8AE5187274242206DA5",hash_generated_method="C72D96C65490338F57465927F7F16D28") public boolean containsHeader(String name){ for (int i=0; i < headers.size(); i++) { Header header=(Header)headers.get(i); if (header.getName().equalsIgnoreCase(name)) { return true; } } return false; }
Tests if headers with the given name are contained within this group. <p>Header name comparison is case insensitive.
private void pop(char c) throws JSONException { if (this.top <= 0) { throw new JSONException("Nesting error."); } char m=this.stack[this.top - 1] == null ? 'a' : 'k'; if (m != c) { throw new JSONException("Nesting error."); } this.top-=1; this.mode=this.top == 0 ? 'd' : this.stack[this.top - 1] == null ? 'a' : 'k'; }
Pop an array or object scope.
public QueueListNode(){ }
Creates a new queue list node with node data payload.
public TriggerExactlyInListCondition(final String... trigger){ this(Arrays.asList(trigger)); }
Creates a new TriggerExactlyInListCondition.
public String toString(){ StringBuffer sb=new StringBuffer("MIssueProject["); sb.append(get_ID()).append("-").append(getName()).append(",A_Asset_ID=").append(getA_Asset_ID()).append(",C_Project_ID=").append(getC_Project_ID()).append("]"); return sb.toString(); }
String Representation
protected void appendDetail(StringBuffer buffer,String fieldName,double[] array){ buffer.append(arrayStart); for (int i=0; i < array.length; i++) { if (i > 0) { buffer.append(arraySeparator); } appendDetail(buffer,fieldName,array[i]); } buffer.append(arrayEnd); }
<p>Append to the <code>toString</code> the detail of a <code>double</code> array.</p>
private X500Name createX500NameForDevice(Device device) throws KeyStoreException { X509Certificate deviceTypeCertificate=(X509Certificate)keyStore.getCertificate("private"); Principal principal=deviceTypeCertificate.getSubjectDN(); String country=getPrincipalAttributeValue(principal,"C","DE"); String organization=getPrincipalAttributeValue(principal,"O","SAP Trust Community"); String unit=getPrincipalAttributeValue(principal,"OU","SAP POC IOT"); String name=getPrincipalAttributeValue(principal,"CN",""); Matcher matcher=DEVICE_TYPE_PATTERN.matcher(name); String tenantId=null; if (matcher.find()) { if (matcher.groupCount() == 2) { tenantId=matcher.group(2); } } String commonName="deviceId:".concat(device.getId()).concat("|tenantId:").concat(tenantId); X500Name x500Name=null; try { x500Name=new X500Name(commonName,unit,organization,"","",country); } catch ( IOException e) { throw new KeyStoreException("Unable to create X500 name for a device",e); } return x500Name; }
Creates a subject name using the device id and other values from the device type certificate
public static <T>CompletionStage<T> dereference(CompletionStage<? extends CompletionStage<T>> stage){ return stage.thenCompose(Identity.INSTANCE); }
This takes a stage of a stage of a value and returns a plain stage of a value.
public int compareTo(Object o){ Span otherSpan=(Span)o; float otherStart=otherSpan.getStart(); int result; if (mStart < otherStart) { result=-1; } else if (mStart > otherStart) { result=1; } else { result=0; } return result; }
Rank spans according to their starting position. The end position is ignored in this ranking.