code
stringlengths
10
174k
nl
stringlengths
3
129k
public static int[] reduce(int[] n1){ for (int i=0; i < n1.length; i++) { if (n1[i] != 0) { if (i == 0) return copy(n1); int[] newVal=new int[n1.length - i]; extract(newVal,0,n1,i,n1.length - i); return newVal; } } return new int[]{0}; }
Strip leading zeros to reduce. Always returns a new copy of the value, never the input even when no zeros.
@CanIgnoreReturnValue @Deprecated @Override public ImmutableSet<V> replaceValues(K key,Iterable<? extends V> values){ throw new UnsupportedOperationException(); }
Guaranteed to throw an exception and leave the multimap unmodified.
public static void deleteDirectory(final File directory){ final File[] filesInTestDir=directory.listFiles(); if (filesInTestDir != null) { for ( final File eachFile : filesInTestDir) { eachFile.delete(); } } directory.delete(); }
Deletes directory's content and then deletes directory itself. Deleting is not recursive.
public static int testIfRead5Snippet(int a){ if (a < 0) { container.a=10; } return container.a; }
Here the read should float to the end.
public void cancel(){ mTN.hide(); try { getService().cancelToast(mContext.getPackageName(),mTN); } catch ( RemoteException e) { } }
Close the view if it's showing, or don't show it if it isn't showing yet. You do not normally have to call this. Normally view will disappear on its own after the appropriate duration.
public MatsimNetworkReader(Network network){ this(new IdentityTransformation(),network); }
Creates a new reader for MATSim network files.
boolean nextRow(){ currRowSeq++; if (rows == 0 || currRowSubimg >= rows - 1) { if (pass == 7) { ended=true; return false; } setPass(pass + 1); if (rows == 0) { currRowSeq--; return nextRow(); } setRow(0); } else { setRow(currRowSubimg + 1); } return true; }
Skips passes with no rows. Return false is no more rows
public EmbeddedSingleNodeKafkaCluster(Properties brokerConfig){ this.brokerConfig=new Properties(); this.brokerConfig.putAll(brokerConfig); }
Creates and starts a Kafka cluster.
public static void main(String[] args){ Scanner input=new Scanner(System.in); System.out.print("Enter three sides of the triangle: "); double side1=input.nextDouble(); double side2=input.nextDouble(); double side3=input.nextDouble(); System.out.print("Enter a color: "); String color=input.next(); System.out.print("Is the triangle filled (true / false)? "); boolean filled=input.nextBoolean(); Triangle triangle=new Triangle(side1,side2,side3,color,filled); System.out.println(triangle); }
Main method
@Override public String toString(){ StringBuilder stringBuilder=new StringBuilder(); stringBuilder.append(String.format("%nLocalName : %s",this.getLocalName())); stringBuilder.append(String.format("%nNamespaceURI : %s",this.getNamespaceURI())); return stringBuilder.toString(); }
toString() method of DOMNodeElementTuple
private void showFeedback(String message){ if (myHost != null) { myHost.showFeedback(message); } else { System.out.println(message); } }
Used to communicate feedback pop-up messages between a plugin tool and the main Whitebox user-interface.
protected void Literal() throws javax.xml.transform.TransformerException { int last=m_token.length() - 1; char c0=m_tokenChar; char cX=m_token.charAt(last); if (((c0 == '\"') && (cX == '\"')) || ((c0 == '\'') && (cX == '\''))) { int tokenQueuePos=m_queueMark - 1; m_ops.m_tokenQueue.setElementAt(null,tokenQueuePos); Object obj=new XString(m_token.substring(1,last)); m_ops.m_tokenQueue.setElementAt(obj,tokenQueuePos); m_ops.setOp(m_ops.getOp(OpMap.MAPINDEX_LENGTH),tokenQueuePos); m_ops.setOp(OpMap.MAPINDEX_LENGTH,m_ops.getOp(OpMap.MAPINDEX_LENGTH) + 1); nextToken(); } else { error(XPATHErrorResources.ER_PATTERN_LITERAL_NEEDS_BE_QUOTED,new Object[]{m_token}); } }
The value of the Literal is the sequence of characters inside the " or ' characters>. Literal ::= '"' [^"]* '"' | "'" [^']* "'"
public void handleEvent(Event evt){ handleDOMSubtreeModifiedEvent((MutationEvent)evt); }
Handles 'DOMSubtreeModified' event type.
public title addElement(String hashcode,String element){ addElementToRegistry(hashcode,element); return (this); }
Adds an Element to the element.
private List<Substitution<ReferenceType>> collectSubstitutions(List<TypeVariable> typeParameters,Substitution<ReferenceType> substitution){ List<TypeVariable> genericParameters=new ArrayList<>(); List<TypeVariable> nongenericParameters=new ArrayList<>(); List<TypeVariable> captureParameters=new ArrayList<>(); for ( TypeVariable variable : typeParameters) { if (variable.hasGenericBound()) { genericParameters.add(variable); } else { if (variable.isCaptureVariable()) { captureParameters.add(variable); } else { nongenericParameters.add(variable); } } } List<Substitution<ReferenceType>> substitutionList=new ArrayList<>(); if (!genericParameters.isEmpty()) { TypeCheck typeCheck=TypeCheck.forParameters(genericParameters); if (!nongenericParameters.isEmpty()) { List<List<ReferenceType>> nonGenCandidates=getCandidateTypeLists(nongenericParameters); if (nonGenCandidates.isEmpty()) { return new ArrayList<>(); } ListEnumerator<ReferenceType> enumerator=new ListEnumerator<>(nonGenCandidates); while (enumerator.hasNext()) { Substitution<ReferenceType> initialSubstitution=substitution.extend(Substitution.forArgs(nongenericParameters,enumerator.next())); List<TypeVariable> parameters=new ArrayList<>(); for ( TypeVariable variable : genericParameters) { TypeVariable param=(TypeVariable)variable.apply(initialSubstitution); parameters.add(param); } substitutionList.addAll(collectSubstitutions(parameters,initialSubstitution)); } } else { substitutionList=getInstantiations(genericParameters,substitution,typeCheck); } if (substitutionList.isEmpty()) { return substitutionList; } } else if (!nongenericParameters.isEmpty()) { substitution=selectAndExtend(nongenericParameters,substitution); if (substitution == null) { return new ArrayList<>(); } substitutionList.add(substitution); } if (!captureParameters.isEmpty()) { List<Substitution<ReferenceType>> substList=new ArrayList<>(); if (substitutionList.isEmpty()) { substList.add(selectAndExtend(captureParameters,substitution)); } else { for ( Substitution<ReferenceType> s : substitutionList) { substList.add(selectAndExtend(captureParameters,s)); } } substitutionList=substList; } return substitutionList; }
Recursive function to collect the list of substitutions that extend a substitution for the given type parameters.
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.
public Period plusDays(int days){ if (days == 0) { return this; } int[] values=getValues(); getPeriodType().addIndexedField(this,PeriodType.DAY_INDEX,values,days); return new Period(values,getPeriodType()); }
Returns a new period plus the specified number of days added. <p> This period instance is immutable and unaffected by this method call.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:55:07.354 -0500",hash_original_method="537B18CC29F2C70486994281CB29500B",hash_generated_method="6A482BE6A74E58339F6E34A315D068FB") public PathHeader createPathHeader(Address address){ if (address == null) throw new NullPointerException("null address!"); Path path=new Path(); path.setAddress(address); return path; }
PATH header
public void test_INSERT_veryLargeLiteral() throws Exception { final Graph g=new LinkedHashModel(); final URI s=new URIImpl("http://www.bigdata.com/"); final URI p=RDFS.LABEL; final Literal o=getVeryLargeLiteral(); final Statement stmt=new StatementImpl(s,p,o); g.add(stmt); assertEquals(1L,doInsertByBody("POST",RDFFormat.RDFXML,g,null)); final Graph g2; { final String queryStr="DESCRIBE <" + s.stringValue() + ">"; final GraphQuery query=cxn.prepareGraphQuery(QueryLanguage.SPARQL,queryStr); g2=asGraph(query.evaluate()); } assertEquals(1,g2.size()); assertTrue(g2.match(s,p,o).hasNext()); }
Test of insert and retrieval of a large literal.
public static void testFulkersonBFS(){ FlowNetworkArray network=new FlowNetworkArray(6,0,5,edges.iterator()); FordFulkerson ffa=new FordFulkerson(network,new BFS_SearchArray(network)); ffa.compute(); validate(network); }
Run in debugger to validate augmenting paths...
public BaseAdapterHelper linkify(int viewId){ TextView view=retrieveView(viewId); Linkify.addLinks(view,Linkify.ALL); return this; }
Add links into a TextView.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-02-25 10:38:06.772 -0500",hash_original_method="D0F10B1E844DBE54E1C95079D90DDAB9",hash_generated_method="D470C4BE1EF8CCE32AD669400786EA9D") public Reader retrieveArticleBody(String articleId,ArticlePointer pointer) throws IOException { return __retrieve(NNTPCommand.BODY,articleId,pointer); }
Retrieves an article body from the NNTP server. The article is referenced by its unique article identifier (including the enclosing &lt and &gt). The article number and identifier contained in the server reply are returned through an ArticlePointer. The <code> articleId </code> field of the ArticlePointer cannot always be trusted because some NNTP servers do not correctly follow the RFC 977 reply format. <p> A DotTerminatedMessageReader is returned from which the article can be read. If the article does not exist, null is returned. <p> You must not issue any commands to the NNTP server (i.e., call any other methods) until you finish reading the message from the returned Reader instance. The NNTP protocol uses the same stream for issuing commands as it does for returning results. Therefore the returned Reader actually reads directly from the NNTP connection. After the end of message has been reached, new commands can be executed and their replies read. If you do not follow these requirements, your program will not work properly. <p>
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-09-03 14:59:48.386 -0400",hash_original_method="F3793FD3E2505AD035424F13E8FC4E3E",hash_generated_method="A58E4C50621A1951F80865295014D02B") public String decode(String pString,String charset) throws DecoderException, UnsupportedEncodingException { if (pString == null) { return null; } return new String(decode(pString.getBytes(StringEncodings.US_ASCII)),charset); }
Decodes a URL safe string into its original form using the specified encoding. Escaped characters are converted back to their original representation.
public double norm2(){ return s[0]; }
Two norm
protected void testPut() throws Throwable { Operation op=Operation.createPut(URI.create(echoServiceUri)); testEchoOperation(op); }
Tests that PUT method is correctly forwarded to JS and response is correctly forwarded back
public static Number[] createNumberArray(double[] data){ Number[] result=new Number[data.length]; for (int i=0; i < data.length; i++) { result[i]=new Double(data[i]); } return result; }
Constructs an array of Number objects from an array of doubles.
public boolean attempt(ObjectReference old,ObjectReference val,Offset offset){ return this.plus(offset).attempt(old,val); }
Attempt an atomic store operation. This must be associated with a related call to prepare.
public GuildMemberUpdateHandler(ImplDiscordAPI api){ super(api,true,"GUILD_MEMBER_UPDATE"); }
Creates a new instance of this class.
public static void makeAdvancedBoundingBlock(World world,int x,int y,int z,Coord4D orig){ world.setBlock(x,y,z,MekanismBlocks.BoundingBlock,1,0); if (!world.isRemote) { ((TileEntityAdvancedBoundingBlock)world.getTileEntity(x,y,z)).setMainLocation(orig.xCoord,orig.yCoord,orig.zCoord); } }
Places a fake advanced bounding block at the defined location.
private void synchronizeThreads(final TargetProcessThread oldThread,final TargetProcessThread newThread){ if (oldThread != null) { oldThread.removeListener(m_internalThreadListener); } if (newThread == null) { CDebuggerPainter.clearDebuggerHighlighting(m_graph); } else { newThread.addListener(m_internalThreadListener); } }
Keeps listeners on the active thread.
private void showFeedback(String message){ if (myHost != null) { myHost.showFeedback(message); } else { System.out.println(message); } }
Used to communicate feedback pop-up messages between a plugin tool and the main Whitebox user-interface.
public static byte[] decodeHex(final char[] data) throws IllegalArgumentException { final int len=data.length; if ((len & 0x01) != 0) { throw new IllegalArgumentException("Odd number of characters."); } final byte[] out=new byte[len >> 1]; for (int i=0, j=0; j < len; i++) { int f=toDigit(data[j],j) << 4; j++; f=f | toDigit(data[j],j); j++; out[i]=(byte)(f & 0xFF); } return out; }
Converts an array of characters representing hexadecimal values into an array of bytes of those same values. The returned array will be half the length of the passed array, as it takes two characters to represent any given byte. An exception is thrown if the passed char array has an odd number of elements.
public StorageUnitEntity createStorageUnitEntity(String storageName,String storagePlatform,BusinessObjectDataKey businessObjectDataKey,Boolean businessObjectDataLatestVersion,String businessObjectDataStatusCode,String storageUnitStatus,String storageDirectoryPath){ StorageEntity storageEntity=storageDao.getStorageByName(storageName); if (storageEntity == null) { storageEntity=storageDaoTestHelper.createStorageEntity(storageName,storagePlatform); } BusinessObjectDataEntity businessObjectDataEntity=businessObjectDataDao.getBusinessObjectDataByAltKey(businessObjectDataKey); if (businessObjectDataEntity == null) { businessObjectDataEntity=businessObjectDataDaoTestHelper.createBusinessObjectDataEntity(businessObjectDataKey,businessObjectDataLatestVersion,businessObjectDataStatusCode); } return createStorageUnitEntity(storageEntity,businessObjectDataEntity,storageUnitStatus,storageDirectoryPath); }
Creates and persists a new storage unit entity.
protected void appendAndPush(StylesheetHandler handler,ElemTemplateElement elem) throws org.xml.sax.SAXException { handler.pushElemTemplateElement(elem); }
Append the current template element to the current template element, and then push it onto the current template element stack.
void createFbo(){ fbo=glGenFramebuffers(); glBindFramebuffer(GL_FRAMEBUFFER,fbo); glBindTexture(GL_TEXTURE_2D,depthTexture); glDrawBuffer(GL_NONE); glReadBuffer(GL_NONE); glFramebufferTexture2D(GL_FRAMEBUFFER,GL_DEPTH_ATTACHMENT,GL_TEXTURE_2D,depthTexture,0); int fboStatus=glCheckFramebufferStatus(GL_FRAMEBUFFER); if (fboStatus != GL_FRAMEBUFFER_COMPLETE) { throw new AssertionError("Could not create FBO: " + fboStatus); } glBindTexture(GL_TEXTURE_2D,0); glBindFramebuffer(GL_FRAMEBUFFER,0); }
Create the FBO to render the depth values of the light-render into the depth texture.
public NexradLayer(){ setName("Nexrad"); }
Construct the DateLayer.
@Deprecated protected void prioritizeCandidates(){ synchronized (localCandidates) { LocalCandidate[] candidates=new LocalCandidate[localCandidates.size()]; localCandidates.toArray(candidates); for ( Candidate<?> cand : candidates) { cand.computePriority(); } Arrays.sort(candidates,candidatePrioritizer); localCandidates.clear(); for ( LocalCandidate cand : candidates) localCandidates.add(cand); } }
Computes the priorities of all <tt>Candidate</tt>s and then sorts them accordingly.
public Pkcs12SignatureToken(String password,File pkcs12File){ this(password.toCharArray(),pkcs12File); }
Creates a SignatureTokenConnection with the provided password and path to PKCS#12 file object.
private void addToFavorites(){ for ( String game : list.getSelectedValuesList()) { favorites.add(game); } saveFavorites(); update(); }
Adds the currently selected games to the favorites.
private void serverClientMessage() throws Exception { Ignite ignite=grid(SERVER_NODE_IDX); ClusterGroup grp=ignite.cluster().forClients(); assert grp.nodes().size() > 0; registerListenerAndSendMessages(ignite,grp); }
Server sends a message and client receives it.
public void snackBarDismiss(@StringRes int id){ snackBar.dismiss(id); }
Use it to programmatically dismiss a SnackBar message.
public void aggregateTimerData(TimerData timerData){ super.aggregateInvocationAwareData(timerData); this.setCount(this.getCount() + timerData.getCount()); this.setDuration(this.getDuration() + timerData.getDuration()); this.calculateMax(timerData.getMax()); this.calculateMin(timerData.getMin()); if (timerData.isCpuMetricDataAvailable()) { this.setCpuDuration(this.getCpuDuration() + timerData.getCpuDuration()); this.calculateCpuMax(timerData.getCpuMax()); this.calculateCpuMin(timerData.getCpuMin()); } if (timerData.isExclusiveTimeDataAvailable()) { this.addExclusiveDuration(timerData.getExclusiveDuration()); this.setExclusiveCount(this.getExclusiveCount() + timerData.getExclusiveCount()); this.calculateExclusiveMax(timerData.getExclusiveMax()); this.calculateExclusiveMin(timerData.getExclusiveMin()); } this.charting=this.charting | timerData.isCharting(); }
Aggregates the values given in the supplied timer data parameter to the objects data.
public void prepareForSend(){ if (size() == 1) { TextModel text=get(0).getText(); if (text != null) { text.cloneText(); } } }
Make sure the text in slide 0 is no longer holding onto a reference to the text in the message text box.
public ConnectionConfig(jmri.jmrix.SerialPortAdapter p){ super(p); }
Ctor for an object being created during load process; Swing init is deferred.
public static byte[] hexStringToByteArray(String strA){ ByteArrayOutputStream result=new ByteArrayOutputStream(); byte sum=(byte)0x00; boolean nextCharIsUpper=true; for (int i=0; i < strA.length(); i++) { char c=strA.charAt(i); switch (Character.toUpperCase(c)) { case '0': if (nextCharIsUpper) { sum=(byte)0x00; nextCharIsUpper=false; } else { sum|=(byte)0x00; result.write(sum); nextCharIsUpper=true; } break; case '1': if (nextCharIsUpper) { sum=(byte)0x10; nextCharIsUpper=false; } else { sum|=(byte)0x01; result.write(sum); nextCharIsUpper=true; } break; case '2': if (nextCharIsUpper) { sum=(byte)0x20; nextCharIsUpper=false; } else { sum|=(byte)0x02; result.write(sum); nextCharIsUpper=true; } break; case '3': if (nextCharIsUpper) { sum=(byte)0x30; nextCharIsUpper=false; } else { sum|=(byte)0x03; result.write(sum); nextCharIsUpper=true; } break; case '4': if (nextCharIsUpper) { sum=(byte)0x40; nextCharIsUpper=false; } else { sum|=(byte)0x04; result.write(sum); nextCharIsUpper=true; } break; case '5': if (nextCharIsUpper) { sum=(byte)0x50; nextCharIsUpper=false; } else { sum|=(byte)0x05; result.write(sum); nextCharIsUpper=true; } break; case '6': if (nextCharIsUpper) { sum=(byte)0x60; nextCharIsUpper=false; } else { sum|=(byte)0x06; result.write(sum); nextCharIsUpper=true; } break; case '7': if (nextCharIsUpper) { sum=(byte)0x70; nextCharIsUpper=false; } else { sum|=(byte)0x07; result.write(sum); nextCharIsUpper=true; } break; case '8': if (nextCharIsUpper) { sum=(byte)0x80; nextCharIsUpper=false; } else { sum|=(byte)0x08; result.write(sum); nextCharIsUpper=true; } break; case '9': if (nextCharIsUpper) { sum=(byte)0x90; nextCharIsUpper=false; } else { sum|=(byte)0x09; result.write(sum); nextCharIsUpper=true; } break; case 'A': if (nextCharIsUpper) { sum=(byte)0xA0; nextCharIsUpper=false; } else { sum|=(byte)0x0A; result.write(sum); nextCharIsUpper=true; } break; case 'B': if (nextCharIsUpper) { sum=(byte)0xB0; nextCharIsUpper=false; } else { sum|=(byte)0x0B; result.write(sum); nextCharIsUpper=true; } break; case 'C': if (nextCharIsUpper) { sum=(byte)0xC0; nextCharIsUpper=false; } else { sum|=(byte)0x0C; result.write(sum); nextCharIsUpper=true; } break; case 'D': if (nextCharIsUpper) { sum=(byte)0xD0; nextCharIsUpper=false; } else { sum|=(byte)0x0D; result.write(sum); nextCharIsUpper=true; } break; case 'E': if (nextCharIsUpper) { sum=(byte)0xE0; nextCharIsUpper=false; } else { sum|=(byte)0x0E; result.write(sum); nextCharIsUpper=true; } break; case 'F': if (nextCharIsUpper) { sum=(byte)0xF0; nextCharIsUpper=false; } else { sum|=(byte)0x0F; result.write(sum); nextCharIsUpper=true; } break; default : break; } } if (!nextCharIsUpper) { throw new RuntimeException("The String did not contain an equal number of hex digits"); } return result.toByteArray(); }
Converts readable hex-String to byteArray
boolean hasMoreReferralExceptions(){ if (debug) System.out.println("LdapReferralException.hasMoreReferralExceptions"); return (nextReferralEx != null); }
Tests if there are any referral exceptions remaining to be processed.
private void saveDescendantState(UIComponent component,FacesContext context){ Map<String,SavedState> saved=(Map<String,SavedState>)getStateHelper().get(PropertyKeys.saved); if (component instanceof EditableValueHolder) { EditableValueHolder input=(EditableValueHolder)component; SavedState state=null; String clientId=component.getClientId(context); if (saved == null) { state=new SavedState(); } if (state == null) { state=saved.get(clientId); if (state == null) { state=new SavedState(); } } state.setValue(input.getLocalValue()); state.setValid(input.isValid()); state.setSubmittedValue(input.getSubmittedValue()); state.setLocalValueSet(input.isLocalValueSet()); if (state.hasDeltaState()) { getStateHelper().put(PropertyKeys.saved,clientId,state); } else if (saved != null) { getStateHelper().remove(PropertyKeys.saved,clientId); } } else if (component instanceof UIForm) { UIForm form=(UIForm)component; String clientId=component.getClientId(context); SavedState state=null; if (saved == null) { state=new SavedState(); } if (state == null) { state=saved.get(clientId); if (state == null) { state=new SavedState(); } } state.setSubmitted(form.isSubmitted()); if (state.hasDeltaState()) { getStateHelper().put(PropertyKeys.saved,clientId,state); } else if (saved != null) { getStateHelper().remove(PropertyKeys.saved,clientId); } } if (component.getChildCount() > 0) { for ( UIComponent uiComponent : component.getChildren()) { saveDescendantState(uiComponent,context); } } if (component.getFacetCount() > 0) { for ( UIComponent facet : component.getFacets().values()) { saveDescendantState(facet,context); } } }
<p>Save state information for the specified component and its descendants.</p>
protected POInfo initPO(Properties ctx){ POInfo poi=POInfo.getPOInfo(ctx,Table_ID,get_TrxName()); return poi; }
Load Meta Data
public Icon(String id,String sourcePath,SVGResource svgResource){ this.id=id; this.sourcePath=sourcePath; this.svgResource=svgResource; this.imageResource=null; }
Creates new icon.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:57:11.304 -0500",hash_original_method="B05B09390509B455A836B09E2A65E5D4",hash_generated_method="B303ADC082E4C769878DBBA7904F78F9") private Object awaitNanos(Node node,Slot slot,long nanos){ int spins=TIMED_SPINS; long lastTime=0; Thread w=null; for (; ; ) { Object v=node.get(); if (v != null) return v; long now=System.nanoTime(); if (w == null) w=Thread.currentThread(); else nanos-=now - lastTime; lastTime=now; if (nanos > 0) { if (spins > 0) --spins; else if (node.waiter == null) node.waiter=w; else if (w.isInterrupted()) tryCancel(node,slot); else LockSupport.parkNanos(node,nanos); } else if (tryCancel(node,slot) && !w.isInterrupted()) return scanOnTimeout(node); } }
Waits for (at index 0) and gets the hole filled in by another thread. Fails if timed out or interrupted before hole filled. Same basic logic as untimed version, but a bit messier.
public RoutingInfo(Object o){ this.text=o.toString(); }
Creates a routing info based on any object. Object's toString() method's output is used as the info text.
public UITab(IBurpExtenderCallbacks callbacks){ this.callbacks=callbacks; this.main=new UIMain(callbacks); callbacks.customizeUiComponent(main); callbacks.addSuiteTab(this); }
Create a new Tab.
private void disposeOptionalControls(String groupId){ if (optionalControls.containsKey(groupId)) { for ( Control c : optionalControls.get(groupId)) { c.dispose(); } optionalControls.remove(groupId); } mainComposite.layout(true,true); }
Disposes all optional controls that belong to the specified group ID.
public void testBug7033() throws Exception { if (!this.DISABLED_testBug7033) { Connection big5Conn=null; Statement big5Stmt=null; PreparedStatement big5PrepStmt=null; String testString="\u5957 \u9910"; try { Properties props=new Properties(); props.setProperty("useUnicode","true"); props.setProperty("characterEncoding","Big5"); big5Conn=getConnectionWithProps(props); big5Stmt=big5Conn.createStatement(); byte[] foobar=testString.getBytes("Big5"); System.out.println(Arrays.toString(foobar)); this.rs=big5Stmt.executeQuery("select 1 as '\u5957 \u9910'"); String retrString=this.rs.getMetaData().getColumnName(1); assertTrue(testString.equals(retrString)); big5PrepStmt=big5Conn.prepareStatement("select 1 as '\u5957 \u9910'"); this.rs=big5PrepStmt.executeQuery(); retrString=this.rs.getMetaData().getColumnName(1); assertTrue(testString.equals(retrString)); } finally { if (this.rs != null) { this.rs.close(); this.rs=null; } if (big5Stmt != null) { big5Stmt.close(); } if (big5PrepStmt != null) { big5PrepStmt.close(); } if (big5Conn != null) { big5Conn.close(); } } } }
Tests fix for BUG#7033 - PreparedStatements don't encode Big5 (and other multibyte) character sets correctly in static SQL strings.
public void saveQuery(final HTTPRepository repository,final String queryName,final String userName,final boolean shared,final QueryLanguage queryLanguage,final String queryText,final boolean infer,final int rowsPerPage) throws RDF4JException { if (QueryLanguage.SPARQL != queryLanguage && QueryLanguage.SERQL != queryLanguage) { throw new RepositoryException("May only save SPARQL or SeRQL queries, not" + queryLanguage.toString()); } if (0 != rowsPerPage && 10 != rowsPerPage && 20 != rowsPerPage && 50 != rowsPerPage && 100 != rowsPerPage && 200 != rowsPerPage) { throw new RepositoryException("Illegal value for rows per page: " + rowsPerPage); } this.checkQueryText(queryText); final QueryStringBuilder save=new QueryStringBuilder(SAVE); save.replaceURI(REPOSITORY,repository.getRepositoryURL()); save.replaceURI(QUERY,"urn:uuid:" + UUID.randomUUID()); save.replaceQuote(QUERY_NAME,queryName); this.replaceUpdateFields(save,userName,shared,queryLanguage,queryText,infer,rowsPerPage); updateQueryRepository(save.toString()); }
Save a query. UNSAFE from an injection point of view. It is the responsibility of the calling code to call checkAccess() with the full credentials first.
public Cache(int pref_size,int size){ cache_size=size; prefix_size=pref_size; hashes=new long[cache_size]; hashes_idx=new long[cache_size]; encodings=new byte[cache_size][]; cache=new Object[cache_size]; }
Creates the Cache object.
Block createNextBlock(@Nullable final Address to,final long version,@Nullable TransactionOutPoint prevOut,final long time,final byte[] pubKey,final Coin coinbaseValue,final int height){ Block b=new Block(params,version); b.setDifficultyTarget(difficultyTarget); b.addCoinbaseTransaction(pubKey,coinbaseValue,height); if (to != null) { Transaction t=new Transaction(params); t.addOutput(new TransactionOutput(params,t,FIFTY_COINS,to)); TransactionInput input; if (prevOut == null) { input=new TransactionInput(params,t,Script.createInputScript(EMPTY_BYTES,EMPTY_BYTES)); byte[] counter=new byte[32]; counter[0]=(byte)txCounter; counter[1]=(byte)(txCounter++ >> 8); input.getOutpoint().setHash(Sha256Hash.wrap(counter)); } else { input=new TransactionInput(params,t,Script.createInputScript(EMPTY_BYTES,EMPTY_BYTES),prevOut); } t.addInput(input); b.addTransaction(t); } b.setPrevBlockHash(getHash()); if (getTimeSeconds() >= time) b.setTime(getTimeSeconds() + 1); else b.setTime(time); b.solve(); try { b.verifyHeader(); } catch ( VerificationException e) { throw new RuntimeException(e); } if (b.getVersion() != version) { throw new RuntimeException(); } return b; }
Returns a solved block that builds on top of this one. This exists for unit tests. In this variant you can specify a public key (pubkey) for use in generating coinbase blocks.
public String stem(String word){ if (word.length() > 2) { return recodeEnding(removeEnding(word.toLowerCase())); } else { return word.toLowerCase(); } }
Returns the stemmed version of the given word. Word is converted to lower case before stemming.
@Override public <T>T[] toArray(T[] array){ return newArray(array); }
Returns all the elements in an array, and the type of the result array is the type of the argument array. If the argument array is big enough, the elements from the queue will be stored in it(element immediately following the end of the queue is set to null, if any); otherwise, it will return a new array with the size of the argument array and size of the queue.
public AttributeList(final int size){ attributeList=new ArrayList<GetterSetter<E>>(size); for (int i=0; i < size; i++) { attributeList.add(i,new GetterSetter<E>()); } }
Construct the list.
public static void main(String[] args){ String[] a=StdIn.readAllStrings(); int n=a.length; sort(a); for (int i=0; i < n; i++) StdOut.println(a[i]); }
Reads in a sequence of extended ASCII strings from standard input; MSD radix sorts them; and prints them to standard output in ascending order.
public static FetchVersionResponse send(InternalDistributedMember recipient,LocalRegion r,Object key) throws RemoteOperationException { FetchVersionResponse response=new FetchVersionResponse(r.getSystem(),recipient); RemoteFetchVersionMessage msg=new RemoteFetchVersionMessage(recipient,r.getFullPath(),response,key); Set<?> failures=r.getDistributionManager().putOutgoing(msg); if (failures != null && failures.size() > 0) { throw new RemoteOperationException(LocalizedStrings.GetMessage_FAILED_SENDING_0.toLocalizedString(msg)); } return response; }
Send RemoteFetchVersionMessage to the recipient for the given key
public static void e(String message,Throwable cause){ Log.e(LOG_TAG,"[" + message + "]",cause); }
<p><b>ERROR:</b> This level of logging should be used when something fatal has happened, i.e. something that will have user-visible consequences and won't be recoverable without explicitly deleting some data, uninstalling applications, wiping the data partitions or reflashing the entire phone (or worse). Issues that justify some logging at the ERROR level are typically good candidates to be reported to a statistics-gathering server.</p> <p/> <p><b>This level is always logged.</b></p>
GridJettyRestHandler(GridRestProtocolHandler hnd,IgniteClosure<String,Boolean> authChecker,IgniteLogger log){ assert hnd != null; assert log != null; this.hnd=hnd; this.log=log; this.authChecker=authChecker; this.jsonMapper=new GridJettyObjectMapper(); try { initDefaultPage(); if (log.isDebugEnabled()) log.debug("Initialized default page."); } catch ( IOException e) { U.warn(log,"Failed to initialize default page: " + e.getMessage()); } try { initFavicon(); if (log.isDebugEnabled()) log.debug(favicon != null ? "Initialized favicon, size: " + favicon.length : "Favicon is null."); } catch ( IOException e) { U.warn(log,"Failed to initialize favicon: " + e.getMessage()); } }
Creates new HTTP requests handler.
public void prepareTaskWorkDir(File path) throws IgniteCheckedException { try { if (path.exists()) throw new IOException("Task local directory already exists: " + path); if (!path.mkdir()) throw new IOException("Failed to create directory: " + path); for ( File resource : rsrcSet) { File symLink=new File(path,resource.getName()); try { Files.createSymbolicLink(symLink.toPath(),resource.toPath()); } catch ( IOException e) { String msg="Unable to create symlink \"" + symLink + "\" to \""+ resource+ "\"."; if (U.isWindows() && e instanceof FileSystemException) msg+="\n\nAbility to create symbolic links is required!\n" + "On Windows platform you have to grant permission 'Create symbolic links'\n" + "to your user or run the Accelerator as Administrator.\n"; throw new IOException(msg,e); } } } catch ( IOException e) { throw new IgniteCheckedException("Unable to prepare local working directory for the task " + "[jobId=" + jobId + ", path="+ path+ ']',e); } }
Prepares working directory for the task. <ul> <li>Creates working directory.</li> <li>Creates symbolic links to all job resources in working directory.</li> </ul>
public static Map<Unit,Unit> mapTransportsToLoad(final Collection<Unit> units,final Collection<Unit> transports){ final List<Unit> canBeTransported=sortByTransportCostDescending(units); final List<Unit> canTransport=sortByTransportCapacityDescendingThenMovesDescending(transports); final Map<Unit,Unit> mapping=new HashMap<>(); final IntegerMap<Unit> addedLoad=new IntegerMap<>(); for ( final Unit unit : canBeTransported) { final Optional<Unit> transport=loadUnitIntoFirstAvailableTransport(unit,canTransport,mapping,addedLoad); if (transport.isPresent()) { canTransport.remove(transport.get()); canTransport.add(transport.get()); } } return mapping; }
Returns a map of unit -> transport. Tries to load units evenly across all transports.
public long skipBytes(long n) throws IOException { return checkInputFile().skipBytes((int)n); }
Skip over n bytes in the input file
public static InputStream openStream(File file) throws FileNotFoundException, IOException { return openStream(file.getAbsolutePath()); }
Return an input stream with BOM consumed...
private void revokeCameraPolicy(org.wso2.emm.agent.beans.Operation operation){ if (!operation.isEnabled()) { devicePolicyManager.setCameraDisabled(deviceAdmin,false); } }
Revokes camera policy on the device.
public int tileYToY(int ty){ return ty * tileHeight + tileGridYOffset; }
Converts a vertical tile index into the Y coordinate of its upper left pixel. This is a convenience method. No attempt is made to detect out-of-range indices.
public DataTable createPairwiseDataTable(boolean showSymetrical){ return new DataTablePairwiseMatrixExtractionAdapter(this,this.rowNames,this.columnNames,new String[]{firstAttributeName,secondAttributeName,name},showSymetrical); }
This creates a pairwise data table. If isSymetrical is true, only the pairs of one triangle of the matrix are returned.
public boolean offerFirst(E e){ addFirst(e); return true; }
Inserts the specified element at the front of this list.
@SuppressWarnings("unchecked") public void fillSettings(Properties mapping){ for ( String key : mapping.stringPropertyNames()) { if (key.equalsIgnoreCase("horizon")) { horizon=Integer.parseInt(mapping.getProperty(key)); } else if (key.equalsIgnoreCase("discount")) { discountFactor=Double.parseDouble(mapping.getProperty(key)); } else if (key.equalsIgnoreCase("gui")) { showGUI=Boolean.parseBoolean(mapping.getProperty(key)); } else if (key.equalsIgnoreCase("user")) { userInput=mapping.getProperty(key); } else if (key.equalsIgnoreCase("speech_user")) { userSpeech=mapping.getProperty(key); } else if (key.equalsIgnoreCase("speech_system")) { systemSpeech=mapping.getProperty(key); } else if (key.equalsIgnoreCase("floor")) { floor=mapping.getProperty(key); } else if (key.equalsIgnoreCase("system")) { systemOutput=mapping.getProperty(key); } else if (key.equalsIgnoreCase("monitor")) { String[] split=mapping.getProperty(key).split(","); for (int i=0; i < split.length; i++) { if (split[i].trim().length() > 0) { varsToMonitor.add(split[i].trim()); } } } else if (key.equalsIgnoreCase("samples")) { nbSamples=Integer.parseInt(mapping.getProperty(key)); } else if (key.equalsIgnoreCase("timeout")) { maxSamplingTime=Integer.parseInt(mapping.getProperty(key)); } else if (key.equalsIgnoreCase("discretisation")) { discretisationBuckets=Integer.parseInt(mapping.getProperty(key)); } else if (key.equalsIgnoreCase("recording")) { if (mapping.getProperty(key).trim().equalsIgnoreCase("last")) { recording=Recording.LAST_INPUT; } else if (mapping.getProperty(key).trim().equalsIgnoreCase("all")) { recording=Recording.ALL; } else { recording=Recording.NONE; } } else if (key.equalsIgnoreCase("connect")) { String[] splits=mapping.getProperty(key).split(","); for ( String split : splits) { if (split.contains(":")) { String address=split.split(":")[0]; int port=Integer.parseInt(split.split(":")[1]); remoteConnections.put(address,port); } else { log.warning("address of remote connection must contain port"); } } } else if (key.equalsIgnoreCase("modules") || key.equalsIgnoreCase("module")) { String[] split=mapping.getProperty(key).split(","); for (int i=0; i < split.length; i++) { if (split[i].trim().length() > 0) { Class<?> clazz; try { clazz=Class.forName(split[i].trim()); for (int j=0; j < clazz.getInterfaces().length; j++) { if (Module.class.isAssignableFrom(clazz.getInterfaces()[j]) && !modules.contains(clazz)) { modules.add((Class<Module>)clazz); } } if (!modules.contains(clazz)) { log.warning("class " + split[i].trim() + " is not a module"); log.fine("interfaces " + Arrays.asList(clazz.getInterfaces())); } } catch ( ClassNotFoundException e) { log.warning("class not found: " + split[i].trim()); } } } } else { params.put(key,mapping.getProperty(key)); } } explicitSettings.addAll(mapping.stringPropertyNames()); }
Fills the current settings with the values provided as argument. Existing values are overridden.
public static BranchCoverageTestFitness createBranchCoverageTestFitness(ControlDependency cd){ return createBranchCoverageTestFitness(cd.getBranch(),cd.getBranchExpressionValue()); }
Create a fitness function for branch coverage aimed at executing the given ControlDependency.
protected boolean hasAttemptRemaining(){ return mCurrentRetryCount <= mMaxNumRetries; }
Returns true if this policy has attempts remaining, false otherwise.
protected PropertyImpl(){ super(); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public TestResult start(String[] args) throws Exception { String testCase=""; String method=""; boolean wait=false; for (int i=0; i < args.length; i++) { if (args[i].equals("-wait")) { wait=true; } else if (args[i].equals("-c")) { testCase=extractClassName(args[++i]); } else if (args[i].equals("-m")) { String arg=args[++i]; int lastIndex=arg.lastIndexOf('.'); testCase=arg.substring(0,lastIndex); method=arg.substring(lastIndex + 1); } else if (args[i].equals("-v")) { System.err.println("JUnit " + Version.id() + " by Kent Beck and Erich Gamma"); } else { testCase=args[i]; } } if (testCase.equals("")) { throw new Exception("Usage: TestRunner [-wait] testCaseName, where name is the name of the TestCase class"); } try { if (!method.equals("")) { return runSingleMethod(testCase,method,wait); } Test suite=getTest(testCase); return doRun(suite,wait); } catch ( Exception e) { throw new Exception("Could not create and run test suite: " + e); } }
Starts a test run. Analyzes the command line arguments and runs the given test suite.
public static int compareVersions(String version1,String version2,String split){ String[] components1=version1.split(split); String[] components2=version2.split(split); int length=Math.min(components1.length,components2.length); for (int i=0; i < length; i++) { int result=new Integer(components1[i]).compareTo(Integer.parseInt(components2[i])); if (result != 0) { return result; } } return Integer.compare(components1.length,components2.length); }
Compare two versions string, splitted by VERSION_SPLIT static var. Version 1 is old if -1.
public CourseComponent find(Filter<CourseComponent> matcher){ if (matcher.apply(this)) return this; if (!isContainer()) return null; CourseComponent found=null; for ( CourseComponent c : children) { found=c.find(matcher); if (found != null) return found; } return null; }
recursively find the first node by matcher. return null if get nothing.
protected boolean isGzipCompression(){ return usegzip; }
Get GZIP compression flag.
@Override public boolean equals(Object obj){ if (obj instanceof UnResolvedCallSite) { UnResolvedCallSite cs=(UnResolvedCallSite)obj; return methodRef.equals(cs.methodRef) && bcIndex == cs.bcIndex; } else { return false; } }
Determine if two call sites are the same. Exact match: no wild cards.
@Override public String toString(){ return "cudaDeviceProp[" + createString(",") + "]"; }
Returns a String representation of this object.
private void arrangeAgentDeparture(final MobsimAgent agent){ double now=this.getSimTimer().getTimeOfDay(); String mode=agent.getMode(); Id<Link> linkId=agent.getCurrentLinkId(); events.processEvent(new PersonDepartureEvent(now,agent.getId(),linkId,mode)); for ( DepartureHandler departureHandler : this.departureHandlers) { if (departureHandler.handleDeparture(now,agent,linkId)) { return; } } }
Informs the simulation that the specified agent wants to depart from its current activity. The simulation can then put the agent onto its vehicle on a link or teleport it to its destination.
private void remove(){ before.after=after; after.before=before; }
Removes this entry from the linked list.
public void clearBookmarkedURLS(){ bookmarkedURLS.clear(); }
Removes all BookmarkedURLs from user's bookmarks.
public static DoubleMatrix[] jblas_fullSVD(double[][] A){ return org.jblas.Singular.fullSVD(new DoubleMatrix(A)); }
Compute a singular-value decomposition of A.
private void leaveBusy(){ busyLock.readLock().unlock(); }
Leaves busy state.
private void isiDeleteFS(IsilonApi isi,FileDeviceInputOutput args) throws IsilonException { isiDeleteExports(isi,args); isiDeleteShares(isi,args); if (args.getFsExtensions() != null && args.getFsExtensions().containsKey(QUOTA)) { isi.deleteQuota(args.getFsExtensions().get(QUOTA)); args.getFsExtensions().remove(QUOTA); } isiDeleteSnapshots(isi,args); isiDeleteQuotaDirs(isi,args); isi.deleteDir(args.getFsMountPath(),true); isiDeleteSnapshotSchedules(isi,args); }
Deleting a file share: - deletes existing exports and smb shares for the file share (only created by storage os)
@Override public void drawItem(Graphics2D g2,XYItemRendererState state,Rectangle2D dataArea,PlotRenderingInfo info,XYPlot plot,ValueAxis domainAxis,ValueAxis rangeAxis,XYDataset dataset,int series,int item,CrosshairState crosshairState,int pass){ PlotOrientation orientation=plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { drawHorizontalItem(g2,dataArea,info,plot,domainAxis,rangeAxis,dataset,series,item,crosshairState,pass); } else if (orientation == PlotOrientation.VERTICAL) { drawVerticalItem(g2,dataArea,info,plot,domainAxis,rangeAxis,dataset,series,item,crosshairState,pass); } }
Draws the visual representation of a single data item.
public boolean isMissingDataNotificationEnabled(){ return missingDataNotificationEnabled; }
Returns the missingDataNotificationEnabled.
public static TranBlob createBlob(InputStream stream) throws IOException { return new TranBlob(new BlobImpl(stream,stream.available()),false); }
Create a new <tt>Blob</tt>. The returned object will be initially immutable.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-09-03 15:01:13.678 -0400",hash_original_method="BC19E5D6974D4B9B20F25E42BD4200C9",hash_generated_method="862EAF4E6CE0FFE06A4D15D2B126DC2E") protected ForkJoinWorkerThread(ForkJoinPool pool){ super("aForkJoinWorkerThread"); this.pool=pool; this.workQueue=pool.registerWorker(this); }
Creates a ForkJoinWorkerThread operating in the given pool.
public static String convertISO8601DurationToNormalTime(String isoTime){ String formattedTime=new String(); if (isoTime.contains("H") && isoTime.contains("M") && isoTime.contains("S")) { String hours=isoTime.substring(isoTime.indexOf('T') + 1,isoTime.indexOf('H')); String minutes=isoTime.substring(isoTime.indexOf('H') + 1,isoTime.indexOf('M')); String seconds=isoTime.substring(isoTime.indexOf('M') + 1,isoTime.indexOf('S')); formattedTime=hours + ":" + formatTo2Digits(minutes)+ ":"+ formatTo2Digits(seconds); } else if (!isoTime.contains("H") && isoTime.contains("M") && isoTime.contains("S")) { String minutes=isoTime.substring(isoTime.indexOf('T') + 1,isoTime.indexOf('M')); String seconds=isoTime.substring(isoTime.indexOf('M') + 1,isoTime.indexOf('S')); formattedTime=minutes + ":" + formatTo2Digits(seconds); } else if (isoTime.contains("H") && !isoTime.contains("M") && isoTime.contains("S")) { String hours=isoTime.substring(isoTime.indexOf('T') + 1,isoTime.indexOf('H')); String seconds=isoTime.substring(isoTime.indexOf('H') + 1,isoTime.indexOf('S')); formattedTime=hours + ":00:" + formatTo2Digits(seconds); } else if (isoTime.contains("H") && isoTime.contains("M") && !isoTime.contains("S")) { String hours=isoTime.substring(isoTime.indexOf('T') + 1,isoTime.indexOf('H')); String minutes=isoTime.substring(isoTime.indexOf('H') + 1,isoTime.indexOf('M')); formattedTime=hours + ":" + formatTo2Digits(minutes)+ ":00"; } else if (!isoTime.contains("H") && !isoTime.contains("M") && isoTime.contains("S")) { String seconds=isoTime.substring(isoTime.indexOf('T') + 1,isoTime.indexOf('S')); formattedTime="0:" + formatTo2Digits(seconds); } else if (!isoTime.contains("H") && isoTime.contains("M") && !isoTime.contains("S")) { String minutes=isoTime.substring(isoTime.indexOf('T') + 1,isoTime.indexOf('M')); formattedTime=minutes + ":00"; } else if (isoTime.contains("H") && !isoTime.contains("M") && !isoTime.contains("S")) { String hours=isoTime.substring(isoTime.indexOf('T') + 1,isoTime.indexOf('H')); formattedTime=hours + ":00:00"; } return formattedTime; }
Converting ISO8601 formatted duration to normal readable time
private void returnData(Object ret){ if (myHost != null) { myHost.returnData(ret); } }
Used to communicate a return object from a plugin tool to the main Whitebox user-interface.
public static void assertEqualsToString(String expected,TreeLayout<StringTreeNode> actual){ String actualString=toString(actual); assertEquals(expected,actualString); }
Check if toString(actuals) is the expected string.
@Override public ODataResponse readEntitySimpleProperty(GetSimplePropertyUriInfo uri_info,String content_type) throws ODataException { Object value=readPropertyValue(uri_info); EdmProperty target=uri_info.getPropertyPath().get(uri_info.getPropertyPath().size() - 1); return EntityProvider.writeProperty(content_type,target,value); }
Writes a Property eg: http://dhus.gael.fr/odata/v1/Products('8')/Name/
@Bean public CacheManager listAdministratorsCacheManager(){ CacheBuilder<Object,Object> cacheBuilder=CacheBuilder.newBuilder().expireAfterWrite(1,TimeUnit.MINUTES).maximumSize(1000); GuavaCacheManager cacheManager=new GuavaCacheManager("listAdministrators"); cacheManager.setCacheBuilder(cacheBuilder); return cacheManager; }
administrators cache, refresh every one minutes. no need to distribute if we have multiple web servers (user just not see new administrators)
public void cacheUnit(UnitInterface unit){ allUnits.add(unit); }
add new unit to cache
public void cancel(){ mCancel=true; }
cannot guarantee immediately cancel
public String toCommaSeparatedString(){ String result=""; for (int i=0; i < contents.size(); i++) { if (result.equals("")) { result=contents.elementAt(i); } else { result=result + ", " + contents.elementAt(i); } } return result; }
Returns the comma-separated list of all the elements of the list. It returns "" if the set is empty.