code
stringlengths
10
174k
nl
stringlengths
3
129k
public static List<String> splitForSearch(final String phraze,final int charThreshold){ if (phraze != null) { String[] token=StringUtils.splitPreserveAllTokens(phraze,"| ;,."); List<String> words=new ArrayList<String>(token.length); for ( final String aToken : token) { if (StringUtils.isNotBlank(aToken)) { final String clean=aToken.trim(); if (clean.length() >= charThreshold) { words.add(clean); } } } return words; } return Collections.EMPTY_LIST; }
Tokenize search phraze and clean from empty strings.
public static List<ItemStack> requestItem(ItemStack stack,ICorporeaSpark spark,boolean checkNBT,boolean doit){ return requestItem(stack,stack.stackSize,spark,checkNBT,doit); }
Bridge for requestItem() using an ItemStack.
@Deprecated public LuceneDocument(){ this(null); }
To be removed, no longer used.
public static boolean isAuthenticated(){ SecurityContext securityContext=SecurityContextHolder.getContext(); Collection<? extends GrantedAuthority> authorities=securityContext.getAuthentication().getAuthorities(); if (authorities != null) { for ( GrantedAuthority authority : authorities) { if (authority.getAuthority().equals(AuthoritiesConstants.ANONYMOUS)) { return false; } } } return true; }
Check if a user is authenticated.
public void handleClientMembership(String clientId,int eventType){ String notifType=null; List<ManagedResource> cleanedUp=null; if (eventType == ClientMembershipMessage.LEFT) { notifType=NOTIF_CLIENT_LEFT; cleanedUp=cleanupBridgeClientResources(clientId); } else if (eventType == ClientMembershipMessage.CRASHED) { notifType=NOTIF_CLIENT_CRASHED; cleanedUp=cleanupBridgeClientResources(clientId); } else if (eventType == ClientMembershipMessage.JOINED) { notifType=NOTIF_CLIENT_JOINED; } if (cleanedUp != null) { for ( ManagedResource resource : cleanedUp) { MBeanUtil.unregisterMBean(resource); } } Helper.sendNotification(this,new Notification(notifType,this.modelMBean,Helper.getNextNotificationSequenceNumber(),clientId)); }
Implementation handles client membership changes.
public SizeSorter(boolean ascending){ super(ascending); }
Creates a new instance of SizeSorter
@Override public String toString(){ if (eIsProxy()) return super.toString(); StringBuffer result=new StringBuffer(super.toString()); result.append(" (event_1: "); result.append(event_1); result.append(')'); return result.toString(); }
<!-- begin-user-doc --> <!-- end-user-doc -->
@After public void cleanup(){ for ( File f : indexDir.listFiles()) f.delete(); indexDir.delete(); }
Cleanup tests
public synchronized boolean isCoverageAvailable(int transport){ int available=getAvailableTransportCoverage(); if ((available & transport) > 0) return true; else return false; }
Determines if a specific transport is available based on connectivity and service availability. In other words this method will return true only for those available transports for which there is sufficient coverage on the device and there is a service book present. Although having a transport in coverage means that we can attempt to create a connection over this transport, connections can still fail due to other network factors (e.g. server outage)
public void writeReport(BenchInfo[] binfo,Properties props) throws IOException { PrintStream p=new PrintStream(out); float total=0.0f; p.println("\n" + title); p.println(pad('-',title.length())); p.println(""); for (int i=0; i < PROPNAMES.length; i++) { p.println(fit(PROPNAMES[i] + ":",PROPNAME_WIDTH) + props.getProperty(PROPNAMES[i])); } p.println(""); p.println(fit("#",INDEX_WIDTH) + " " + fit("Benchmark Name",NAME_WIDTH)+ " "+ fit("Time (ms)",TIME_WIDTH)+ " "+ fit("Score",SCORE_WIDTH)); p.println(pad('-',INDEX_WIDTH + NAME_WIDTH + TIME_WIDTH+ SCORE_WIDTH+ 6)); for (int i=0; i < binfo.length; i++) { BenchInfo b=binfo[i]; p.print(fit(Integer.toString(i),INDEX_WIDTH) + " "); p.print(fit(b.getName(),NAME_WIDTH) + " "); if (b.getTime() != -1) { float score=b.getTime() * b.getWeight(); total+=score; p.print(fit(Long.toString(b.getTime()),TIME_WIDTH) + " "); p.println(fit(Util.floatToString(score,PRECISION),SCORE_WIDTH)); } else { p.print(fit("--",TIME_WIDTH) + " "); p.println(fit("--",SCORE_WIDTH)); } } p.println(pad('-',INDEX_WIDTH + NAME_WIDTH + TIME_WIDTH+ SCORE_WIDTH+ 6)); p.println(fit("Total score",INDEX_WIDTH + NAME_WIDTH + TIME_WIDTH+ 4) + " " + Util.floatToString(total,PRECISION)); p.println(""); p.println("-----"); p.println("Report generated on " + new Date() + "\n"); p.println(""); }
Generate text report.
public static boolean isInstanceOf(Object object,Class target){ if (object == null || target == null) { return false; } return target.isInstance(object); }
Safe version of <code>isInstance</code>, returns <code>false</code> if any of the arguments is <code>null</code>.
private static void applyOpenSSLFix() throws SecurityException { if ((Build.VERSION.SDK_INT < VERSION_CODE_JELLY_BEAN) || (Build.VERSION.SDK_INT > VERSION_CODE_JELLY_BEAN_MR2)) { return; } try { Class.forName("org.apache.harmony.xnet.provider.jsse.NativeCrypto").getMethod("RAND_seed",byte[].class).invoke(null,generateSeed()); int bytesRead=(Integer)Class.forName("org.apache.harmony.xnet.provider.jsse.NativeCrypto").getMethod("RAND_load_file",String.class,long.class).invoke(null,"/dev/urandom",1024); if (bytesRead != 1024) { throw new IOException("Unexpected number of bytes read from Linux PRNG: " + bytesRead); } } catch ( Exception e) { throw new SecurityException("Failed to seed OpenSSL PRNG",e); } }
Applies the fix for OpenSSL PRNG having low entropy. Does nothing if the fix is not needed.
private boolean listItemExists(ListItemEntry listItem,URL feedUrl,SitesService sitesService){ try { Map<String,String> values=Maps.newHashMap(); for ( Field field : listItem.getFields()) { values.put(field.getIndex(),field.getValue()); } ContentQuery query=new ContentQuery(feedUrl); String parentId=listItem.getLink(SitesLink.Rel.PARENT,ILink.Type.ATOM).getHref(); query.setParent(parentId.substring(parentId.lastIndexOf('/') + 1)); query.setKind("listitem"); List<BaseContentEntry<?>> entries=entryProvider.getEntries(query,sitesService); for ( BaseContentEntry<?> entry : entries) { ListItemEntry item=(ListItemEntry)(BaseContentEntry)entry; if (item.getFields().size() == listItem.getFields().size()) { boolean equal=true; for ( Field field : item.getFields()) { if (!values.get(field.getIndex()).equals(field.getValue())) { equal=false; } } if (equal) { return true; } } } return false; } catch ( IOException e) { LOGGER.log(Level.WARNING,"Error communicating with the server.",e); return false; } catch ( ServiceException e) { LOGGER.log(Level.WARNING,"Error communicating with the server.",e); return false; } }
Returns whether or not an identical list item to the one given exists at the given feed URL.
public boolean skipDelimiters(){ int workingPosition=position; boolean workingEmptyReturned=emptyReturned; boolean onToken=advancePosition(); tokenCount=-1; while (position != workingPosition || emptyReturned != workingEmptyReturned) { if (onToken) { position=workingPosition; emptyReturned=workingEmptyReturned; return true; } workingPosition=position; workingEmptyReturned=emptyReturned; onToken=advancePosition(); } return false; }
Advances the current position so it is before the next token. <p> This method skips nontoken delimiters but does not skip token delimiters. <p> This method is useful when switching to the new delimiter sets (see the second example in the class comment.)
private void backupFavorites(BackupDataOutput data) throws IOException { ContentResolver cr=mContext.getContentResolver(); Cursor cursor=cr.query(Favorites.CONTENT_URI,FAVORITE_PROJECTION,getUserSelectionArg(),null,null); try { cursor.moveToPosition(-1); while (cursor.moveToNext()) { final long id=cursor.getLong(ID_INDEX); final long updateTime=cursor.getLong(ID_MODIFIED); Key key=getKey(Key.FAVORITE,id); mKeys.add(key); final String backupKey=keyToBackupKey(key); if (!mExistingKeys.contains(backupKey) || updateTime >= mLastBackupRestoreTime || restoredBackupVersion < 4) { writeRowToBackup(key,packFavorite(cursor),data); } else { if (DEBUG) Log.d(TAG,"favorite already backup up: " + id); } } } finally { cursor.close(); } }
Write all modified favorites to the data stream.
public LargeDeltas(LargeDeltas other){ __isset_bitfield=other.__isset_bitfield; if (other.isSetB1()) { this.b1=new Bools(other.b1); } if (other.isSetB10()) { this.b10=new Bools(other.b10); } if (other.isSetB100()) { this.b100=new Bools(other.b100); } this.check_true=other.check_true; if (other.isSetB1000()) { this.b1000=new Bools(other.b1000); } this.check_false=other.check_false; if (other.isSetVertwo2000()) { this.vertwo2000=new VersioningTestV2(other.vertwo2000); } if (other.isSetA_set2500()) { Set<String> __this__a_set2500=new HashSet<String>(other.a_set2500); this.a_set2500=__this__a_set2500; } if (other.isSetVertwo3000()) { this.vertwo3000=new VersioningTestV2(other.vertwo3000); } if (other.isSetBig_numbers()) { List<Integer> __this__big_numbers=new ArrayList<Integer>(other.big_numbers); this.big_numbers=__this__big_numbers; } }
Performs a deep copy on <i>other</i>.
void sendPasswordRecoveryMails(PlatformUser pUser,EmailType mailType,String marketplaceId,Object[] obj) throws MailOperationException { Marketplace marketplace=null; if (marketplaceId != null) { marketplace=new Marketplace(); marketplace.setMarketplaceId(marketplaceId); marketplace=(Marketplace)dm.find(marketplace); } cs.sendMail(pUser,mailType,obj,marketplace); }
Sends an email to the given platform user.
protected void onRemoveNoExternalMessages(String channel,String sourceNick,String sourceLogin,String sourceHostname){ }
Called when a channel is set to allow messages from any user, even if they are not actually in the channel. <p> This is a type of mode change and is also passed to the onMode method in the PircBot class. <p> The implementation of this method in the PircBot abstract class performs no actions and may be overridden as required.
@Nonnull static public String contentsToString(){ StringBuilder retval=new StringBuilder(); for ( Class<?> c : managerLists.keySet()) { retval.append("List of "); retval.append(c); retval.append(" with "); retval.append(Integer.toString(getList(c).size())); retval.append(" objects\n"); for ( Object o : getList(c)) { retval.append(" "); retval.append(o.getClass().toString()); retval.append("\n"); } } return retval.toString(); }
Dump generic content of InstanceManager by type.
public AvsPlayContentItem(String token,Uri uri){ super(token); mUri=uri; }
Create a new local play item
public static synchronized void moveLogsFromLegacyDirIfNecessary(){ File sdcardDir=Environment.getExternalStorageDirectory(); File legacyDir=new File(sdcardDir,LEGACY_SAVED_LOGS_DIR); if (legacyDir.exists() && legacyDir.isDirectory()) { File savedLogsDir=getSavedLogsDirectory(); for ( File file : legacyDir.listFiles()) { file.renameTo(new File(savedLogsDir,file.getName())); } legacyDir.delete(); } }
I used to save logs to /sdcard/catlog_saved_logs. Now it's /sdcard/catlog/saved_logs. Move any files that need to be moved to the new directory.
public Object encode(Object raw) throws EncoderException { if (!(raw instanceof byte[])) { throw new EncoderException("argument not a byte array"); } return toAsciiChars((byte[])raw); }
Converts an array of raw binary data into an array of ascii 0 and 1 chars.
public static HttpVersion parse(final String s) throws ProtocolException { if (s == null) { throw new IllegalArgumentException("String may not be null"); } if (!s.startsWith("HTTP/")) { throw new ProtocolException("Invalid HTTP version string: " + s); } int major, minor; int i1="HTTP/".length(); int i2=s.indexOf(".",i1); if (i2 == -1) { throw new ProtocolException("Invalid HTTP version number: " + s); } try { major=Integer.parseInt(s.substring(i1,i2)); } catch ( final NumberFormatException e) { throw new ProtocolException("Invalid HTTP major version number: " + s); } i1=i2 + 1; i2=s.length(); try { minor=Integer.parseInt(s.substring(i1,i2)); } catch ( final NumberFormatException e) { throw new ProtocolException("Invalid HTTP minor version number: " + s); } return new HttpVersion(major,minor); }
Parses the textual representation of the given HTTP protocol version.
public PSPCommunicationException(String message,ApplicationExceptionBean bean){ super(message,bean); }
Constructs a new exception with the specified detail message and bean for JAX-WS exception serialization.
private void initialize(){ this.setLayout(new BorderLayout()); this.setName(Constant.messages.getString("output.panel.title")); if (Model.getSingleton().getOptionsParam().getViewParam().getWmUiHandlingOption() == 0) { this.setSize(243,119); } this.setIcon(new ImageIcon(OutputPanel.class.getResource("/resource/icon/16/172.png"))); this.setDefaultAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() | Event.SHIFT_MASK,false)); this.setMnemonic(Constant.messages.getChar("output.panel.mnemonic")); this.add(getMainPanel(),BorderLayout.CENTER); this.setShowByDefault(true); }
This method initializes this
public static String suppressWhiteSpace(String str){ int len=str.length(); StringBuilder sb=new StringBuilder(len); char c; char buffer=0; for (int i=0; i < len; i++) { c=str.charAt(i); if (c == '\n' || c == '\r') buffer='\n'; else if (isWhiteSpace(c)) { if (buffer == 0) buffer=c; } else { if (buffer != 0) { sb.append(buffer); buffer=0; } sb.append(c); } } if (buffer != 0) sb.append(buffer); return sb.toString(); }
remove all white spaces followd by whitespaces
public static void shuffle(Object[] a,int lo,int hi){ if (lo < 0 || lo > hi || hi >= a.length) throw new RuntimeException("Illegal subarray range"); for (int i=lo; i <= hi; i++) { int r=i + uniform(hi - i + 1); Object temp=a[i]; a[i]=a[r]; a[r]=temp; } }
Rearrange the elements of the subarray a[lo..hi] in random order.
private SwipeMode computeInputMode(long time,float x,float y,float dx,float dy){ if (!mStacks[1].isDisplayable()) return SwipeMode.SEND_TO_STACK; int currentIndex=getTabStackIndex(); if (currentIndex != getViewportParameters().getStackIndexAt(x,y)) { return SwipeMode.SWITCH_STACK; } float relativeX=mLastOnDownX - (x + dx); float relativeY=mLastOnDownY - (y + dy); float distanceToDownSqr=dx * dx + dy * dy; float switchDelta=getOrientation() == Orientation.PORTRAIT ? relativeX : relativeY; float otherDelta=getOrientation() == Orientation.PORTRAIT ? relativeY : relativeX; if (distanceToDownSqr > mMinDirectionThreshold * mMinDirectionThreshold && Math.abs(otherDelta) > Math.abs(switchDelta)) { return SwipeMode.SEND_TO_STACK; } if (Math.abs(switchDelta) > mMinDirectionThreshold) { if ((currentIndex == 0) ^ (switchDelta > 0) ^ (getOrientation() == Orientation.PORTRAIT && LocalizationUtils.isLayoutRtl())) { return SwipeMode.SEND_TO_STACK; } } if (isDraggingStackInWrongDirection(mLastOnDownX,mLastOnDownY,x,y,dx,dy,getOrientation(),currentIndex)) { return SwipeMode.SWITCH_STACK; } if (time - mLastOnDownTimeStamp > THRESHOLD_TIME_TO_SWITCH_STACK_INPUT_MODE) { return SwipeMode.SEND_TO_STACK; } if (distanceToDownSqr > mMinShortPressThresholdSqr) { return SwipeMode.SWITCH_STACK; } return SwipeMode.NONE; }
Computes the input mode for drag and fling based on the first event position.
void skipData(int count) throws IOException { if (bufAvail >= count) { bufAvail-=count; bufPtr+=count; return; } if (bufAvail > 0) { count-=bufAvail; bufAvail=0; bufPtr=0; } if (iis.skipBytes(count) != count) { throw new IIOException("Image format Error"); } }
Skips <code>count</code> bytes, leaving the buffer in an appropriate state. If the end of the stream is encountered, an <code>IIOException</code> is thrown with the message "Image Format Error".
public synchronized void die(){ if (connected) { packetUpdate.signalStop(); connThread.interrupt(); send(new Packet(Packet.COMMAND_CLOSE_CONNECTION)); flushConn(); } connected=false; if (connection != null) { connection.close(); } for (int i=0; i < closeClientListeners.size(); i++) { closeClientListeners.elementAt(i).clientClosed(); } if (log != null) { try { log.close(); } catch ( IOException e) { System.err.print("Exception closing logfile: "); e.printStackTrace(); } } System.out.println("client: died"); System.out.flush(); }
Shuts down threads and sockets
public void addSeries(final String title,final double[] xs,final double[] ys){ XYSeries series=new XYSeries(title,false,true); for (int i=0, n=Math.min(xs.length,ys.length); i < n; i++) { series.add(xs[i],ys[i]); } this.dataset.addSeries(series); }
Adds a new data series to the chart with the specified title. <code>xs<code> and <code>ys</code> should have the same length. If not, only as many items are shown as the shorter array contains.
@Override protected void initData(){ this.getContentResolver().registerContentObserver(MessageContentProvider.MESSAGE_URI,true,new MessageProviderObserver(new Handler())); this.adapter=new ProviderRecyclerViewAdapter(this.getContentResolver(),MessageContentProvider.MESSAGE_URI); this.providerRV.setAdapter(this.adapter); ArrayList<SQLiteData> allData=new ArrayList<>(); allData.add(new SQLiteData()); this.adapter.setList(allData); this.adapter.notifyDataSetChanged(); }
Initialize the Activity data
private String toComparableString(final byte[] memory){ final StringBuffer stringBuffer=new StringBuffer(); for ( final byte b : memory) { stringBuffer.append(Convert.byteToHexString(b)); } return stringBuffer.toString(); }
Turns a byte array into a string.
public static ECKey fromASN1(byte[] asn1privkey){ return extractKeyFromASN1(asn1privkey); }
Construct an ECKey from an ASN.1 encoded private key. These are produced by OpenSSL and stored by Bitcoin Core in its wallet. Note that this is slow because it requires an EC point multiply.
public AcelaTurnout(String systemName,String userName,AcelaSystemConnectionMemo memo){ super(systemName,userName); _memo=memo; prefix=_memo.getSystemPrefix() + "T"; initializeTurnout(systemName); }
Create a Light object, with both system and user names. <P> 'systemName' was previously validated in AcelaLightManager
public R paramsToFormEntity(){ mHttpEntity=createFormEntity(); return (R)this; }
convert params to Form Entity.
protected void restoreGraphics(Graphics g){ Graphics2D g2D=(Graphics2D)g; g2D.setStroke(saveStroke); g2D.setPaint(savePaint); }
Restores previous settings to the Graphics. Beware : no verification is made to be sure that it is the same Graphics ...
private void saveImageBase(){ try { final CAddress imageBase=new CAddress(Convert.hexStringToLong(m_debuggerPanel.getImageBase())); if (m_addressSpace == null) { m_module.getConfiguration().setImageBase(imageBase); } else { m_addressSpace.getContent().setImageBase(m_module,imageBase); } } catch ( final CouldntSaveDataException e) { CUtilityFunctions.logException(e); final String message="E00166: " + "Could not change the module image base"; final String description=CUtilityFunctions.createDescription("The new module image base could not be saved to the database.",new String[]{"There was a problem with the connection to the database while the module image base was saved"},new String[]{"The module image base was not saved. Please try to find out what went wrong with the database connection and try to save the module image base again."}); NaviErrorDialog.show(SwingUtilities.getWindowAncestor(this),message,description,e); } }
Saves the module image base to the database.
private void select(final JSpinner spinnerComponent){ final JComponent editor=spinnerComponent.getEditor(); if (!(editor instanceof JSpinner.DateEditor)) return; final JSpinner.DateEditor dateEditor=(JSpinner.DateEditor)editor; final JFormattedTextField ftf=dateEditor.getTextField(); final Format format=dateEditor.getFormat(); Object value; if (format == null || (value=spinnerComponent.getValue()) == null) return; final SpinnerDateModel model=dateEditor.getModel(); final DateFormat.Field field=DateFormat.Field.ofCalendarField(model.getCalendarField()); if (field == null) return; try { final AttributedCharacterIterator iterator=format.formatToCharacterIterator(value); if (!select(ftf,iterator,field) && field == DateFormat.Field.HOUR0) { select(ftf,iterator,DateFormat.Field.HOUR1); } } catch ( final IllegalArgumentException iae) { } }
If the spinner's editor is a DateEditor, this selects the field associated with the value that is being incremented.
public boolean tryNext(final T element){ Item<T> item=head; while (item != null) { if (equivalent(item.element,element)) { return false; } item=item.next; } final Item<T> newHead=new Item<>(); newHead.element=element; newHead.next=head; head=newHead; return true; }
Announce the next element and report whether that one is currently in the stack. That is, element should only be processed by caller if this method returns true.
public synchronized void close(){ if (!this.mIsClosed) { this.mSocket.close(); this.mIsClosed=true; } }
close the UDP socket
public void clearOpciones(){ opciones.clear(); }
Elimina todas las opciones de la lista.
protected void creditInventoryAndAssert(final long warehouseId,final String skuCode,final String creditQuantity,final String expectedAvailable,final String expectedReserved){ final Warehouse warehouse=warehouseService.findById(warehouseId); skuWarehouseService.credit(warehouse,skuCode,new BigDecimal(creditQuantity)); assertInventory(warehouseId,skuCode,expectedAvailable,expectedReserved); }
Add quantity to warehouse and assert inventory state.
protected void report(GroovyExceptionInterface e,boolean child){ println(((Exception)e).getMessage()); stacktrace((Exception)e,false); }
For GroovyException.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-09-03 15:01:15.195 -0400",hash_original_method="01CB53E47AF5384558F5A1C3FDB268E6",hash_generated_method="A37A31244848C5A0C7DA46E18C1DFDCA") final boolean acquireQueued(final Node node,long arg){ boolean failed=true; try { boolean interrupted=false; for (; ; ) { final Node p=node.predecessor(); if (p == head && tryAcquire(arg)) { setHead(node); p.next=null; failed=false; return interrupted; } if (shouldParkAfterFailedAcquire(p,node) && parkAndCheckInterrupt()) interrupted=true; } } finally { if (failed) cancelAcquire(node); } }
Acquires in exclusive uninterruptible mode for thread already in queue. Used by condition wait methods as well as acquire.
public void parse(String theSrcText,String testName) throws Exception { System.out.println("-------------------------------"); System.out.println(" " + testName); System.out.println("-------------------------------"); try { Reader reader=new BufferedReader(new StringReader(theSrcText)); GroovyRecognizer recognizer=GroovyRecognizer.make(reader); recognizer.compilationUnit(); System.out.println(decorateWithLineNumbers(theSrcText)); } catch ( RecognitionException parseException) { System.out.println(decorateWithLineNumbersAndErrorMessage(theSrcText,parseException)); throw parseException; } System.out.println("-------------------------------"); }
run the JSR parser implementation over the supplied source text
private void startPolling(){ String notifier=Preference.getString(context,Constants.PreferenceFlag.NOTIFIER_TYPE); if (Constants.NOTIFIER_LOCAL.equals(notifier)) { Log.i(TAG,"EMM auto enrollment, initiating polling task."); LocalNotification.startPolling(context); } }
Starts server polling task.
protected HashEntry createEntry(HashEntry next,int hashCode,Object key,Object value){ return new HashEntry(next,hashCode,key,value); }
Creates an entry to store the key-value data. <p> This implementation creates a new HashEntry instance. Subclasses can override this to return a different storage class, or implement caching.
@Override public String toString(){ if (eIsProxy()) return super.toString(); StringBuffer result=new StringBuffer(super.toString()); result.append(" (index_1: "); result.append(index_1); result.append(')'); return result.toString(); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public PutIndexTemplateRequest alias(Alias alias){ aliases.add(alias); return this; }
Adds an alias that will be added when the index gets created.
private CipherBox(){ this.protocolVersion=ProtocolVersion.DEFAULT; this.cipher=null; this.cipherType=STREAM_CIPHER; this.fixedIv=new byte[0]; this.key=null; this.mode=Cipher.ENCRYPT_MODE; this.random=null; this.tagSize=0; this.recordIvSize=0; }
NULL cipherbox. Identity operation, no encryption.
public static <A>EvalTValue<A> of(final AnyMValue<Eval<A>> monads){ return new EvalTValue<>(monads); }
Construct an MaybeT from an AnyM that wraps a monad containing Maybes
public static void write(JsonElement element,JsonWriter writer) throws IOException { TypeAdapters.JSON_ELEMENT.write(writer,element); }
Writes the JSON element to the writer, recursively.
public void appendToLog(String s){ append("\n" + s); }
Outputs the string as a new line of log data in the LogView.
public boolean serialize(DataObject obj,RowMutator mutator){ try { String id=obj.getId().toString(); if (isLazyLoaded() || _property.getReadMethod() == null) { return false; } Object val=_property.getReadMethod().invoke(obj); if (val == null) { return false; } boolean changed=false; switch (_colType) { case NamedURI: case Primitive: { if (!obj.isChanged(_name)) { return false; } changed=addColumn(id,getColumnName(null,mutator),val,mutator,obj); break; } case TrackingSet: { AbstractChangeTrackingSet valueSet=(AbstractChangeTrackingSet)val; Set<?> addedSet=valueSet.getAddedSet(); if (addedSet != null) { Iterator<?> it=valueSet.getAddedSet().iterator(); while (it.hasNext()) { Object itVal=it.next(); String targetVal=valueSet.valToString(itVal); changed|=addColumn(id,getColumnName(targetVal,mutator),itVal,mutator); } } Set<?> removedVal=valueSet.getRemovedSet(); if (removedVal != null) { Iterator<?> removedIt=removedVal.iterator(); while (removedIt.hasNext()) { String targetVal=valueSet.valToString(removedIt.next()); if (_index == null) { changed|=removeColumn(id,new ColumnWrapper(getColumnName(targetVal,mutator),targetVal),mutator); } else { addDeletionMark(id,getColumnName(targetVal,mutator),mutator); changed=true; } } } break; } case TrackingMap: { AbstractChangeTrackingMap valueMap=(AbstractChangeTrackingMap)val; Set<String> changedSet=valueMap.getChangedKeySet(); if (changedSet != null) { Iterator<String> it=valueMap.getChangedKeySet().iterator(); while (it.hasNext()) { String key=it.next(); Object entryVal=valueMap.get(key); CompositeColumnName colName=getColumnName(key,mutator); if (clockIndValue != null) { int ordinal=((ClockIndependentValue)entryVal).ordinal(); colName=getColumnName(key,String.format("%08d",ordinal),mutator); } changed|=addColumn(id,colName,valueMap.valToByte(entryVal),mutator); } } Set<String> removedKey=valueMap.getRemovedKeySet(); if (removedKey != null) { Iterator<String> removedIt=removedKey.iterator(); while (removedIt.hasNext()) { String key=removedIt.next(); CompositeColumnName colName=getColumnName(key,mutator); if (clockIndValue != null) { Object removedVal=valueMap.getRemovedValue(key); if (removedVal != null) { colName=getColumnName(key,String.format("%08d",((ClockIndependentValue)removedVal).ordinal()),mutator); } } if (_index == null) { changed|=removeColumn(id,new ColumnWrapper(colName,null),mutator); } else { addDeletionMark(id,colName,mutator); changed=true; } } } break; } case TrackingSetMap: { AbstractChangeTrackingSetMap valueMap=(AbstractChangeTrackingSetMap)val; Set<String> keys=valueMap.keySet(); if (keys != null) { Iterator<String> it=keys.iterator(); while (it.hasNext()) { String key=it.next(); AbstractChangeTrackingSet valueSet=valueMap.get(key); Set<?> addedSet=valueSet.getAddedSet(); if (addedSet != null) { Iterator<?> itSet=valueSet.getAddedSet().iterator(); while (itSet.hasNext()) { String value=valueSet.valToString(itSet.next()); changed|=addColumn(id,getColumnName(key,value,mutator),value,mutator); } } Set<?> removedVal=valueSet.getRemovedSet(); if (removedVal != null) { Iterator<?> removedIt=removedVal.iterator(); while (removedIt.hasNext()) { String targetVal=valueSet.valToString(removedIt.next()); if (_index == null) { changed|=removeColumn(id,new ColumnWrapper(getColumnName(key,targetVal,mutator),targetVal),mutator); } else { addDeletionMark(id,getColumnName(key,targetVal,mutator),mutator); changed=true; } } } } } break; } case NestedObject: { if (!obj.isChanged(_name)) { break; } AbstractSerializableNestedObject nestedObject=(AbstractSerializableNestedObject)val; changed|=addColumn(id,getColumnName(null,mutator),nestedObject.toBytes(),mutator); } } return changed; } catch (final InvocationTargetException e) { throw DatabaseException.fatals.serializationFailedId(obj.getId(),e); } catch (final IllegalAccessException e) { throw DatabaseException.fatals.serializationFailedId(obj.getId(),e); } }
Serializes object field into database updates
public void age(Network network){ for ( Vertex vertex : network.findAll()) { int level=vertex.getConsciousnessLevel(); if (level > 0) { vertex.decrementConsciousnessLevel(level / 2); } } }
Age the network, decrease consciousness level by 10%.
public static String buildFilterClause(final String sql,final Object value,final List<Object> preparedArgs){ if (value != null) { preparedArgs.add(value); return sql; } else { return null; } }
Returns the sql filter clause when value to set as prepared argument isn't null otherwise null is returned.
public void assertArrayEqual(short[] expected,short[] actual,String errorMessage){ TestUtils.assertArrayEqual(expected,actual,errorMessage); }
This method just invokes the test utils method, it is here for convenience
@SuppressWarnings("unchecked") @Override public NotificationChain eInverseAdd(InternalEObject otherEnd,int featureID,NotificationChain msgs){ switch (featureID) { case SexecPackage.EXECUTION_STATE__SUB_SCOPES: return ((InternalEList<InternalEObject>)(InternalEList<?>)getSubScopes()).basicAdd(otherEnd,msgs); case SexecPackage.EXECUTION_STATE__SUPER_SCOPE: if (superScope != null) msgs=((InternalEObject)superScope).eInverseRemove(this,SexecPackage.EXECUTION_SCOPE__SUB_SCOPES,ExecutionScope.class,msgs); return basicSetSuperScope((ExecutionScope)otherEnd,msgs); } return super.eInverseAdd(otherEnd,featureID,msgs); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public StackedXYAreaRendererState(PlotRenderingInfo info){ super(info); this.seriesArea=null; this.line=new Line2D.Double(); this.lastSeriesPoints=new Stack(); this.currentSeriesPoints=new Stack(); }
Creates a new state for the renderer.
private void writeStubMethod(IndentingWriter p,int opnum) throws IOException { RemoteClass.Method method=remoteMethods[opnum]; MethodDoc methodDoc=method.methodDoc(); String methodName=methodDoc.name(); Type[] paramTypes=method.parameterTypes(); String paramNames[]=nameParameters(paramTypes); Type returnType=methodDoc.returnType(); ClassDoc[] exceptions=method.exceptionTypes(); p.pln("// implementation of " + Util.getFriendlyUnqualifiedSignature(methodDoc)); p.p("public " + returnType.toString() + " "+ methodName+ "("); for (int i=0; i < paramTypes.length; i++) { if (i > 0) { p.p(", "); } p.p(paramTypes[i].toString() + " " + paramNames[i]); } p.plnI(")"); if (exceptions.length > 0) { p.p("throws "); for (int i=0; i < exceptions.length; i++) { if (i > 0) { p.p(", "); } p.p(exceptions[i].qualifiedName()); } p.pln(); } p.pOlnI("{"); List<ClassDoc> catchList=computeUniqueCatchList(exceptions); if (catchList.size() > 0) { p.plnI("try {"); } if (version == StubVersion.VCOMPAT) { p.plnI("if (useNewInvoke) {"); } if (version == StubVersion.VCOMPAT || version == StubVersion.V1_2) { if (!Util.isVoid(returnType)) { p.p("Object $result = "); } p.p("ref.invoke(this, " + methodFieldNames[opnum] + ", "); if (paramTypes.length > 0) { p.p("new java.lang.Object[] {"); for (int i=0; i < paramTypes.length; i++) { if (i > 0) p.p(", "); p.p(wrapArgumentCode(paramTypes[i],paramNames[i])); } p.p("}"); } else { p.p("null"); } p.pln(", " + method.methodHash() + "L);"); if (!Util.isVoid(returnType)) { p.pln("return " + unwrapArgumentCode(returnType,"$result") + ";"); } } if (version == StubVersion.VCOMPAT) { p.pOlnI("} else {"); } if (version == StubVersion.V1_1 || version == StubVersion.VCOMPAT) { p.pln(REMOTE_CALL + " call = ref.newCall((" + REMOTE_OBJECT+ ") this, operations, "+ opnum+ ", interfaceHash);"); if (paramTypes.length > 0) { p.plnI("try {"); p.pln("java.io.ObjectOutput out = call.getOutputStream();"); writeMarshalArguments(p,"out",paramTypes,paramNames); p.pOlnI("} catch (java.io.IOException e) {"); p.pln("throw new " + MARSHAL_EXCEPTION + "(\"error marshalling arguments\", e);"); p.pOln("}"); } p.pln("ref.invoke(call);"); if (Util.isVoid(returnType)) { p.pln("ref.done(call);"); } else { p.pln(returnType.toString() + " $result;"); p.plnI("try {"); p.pln("java.io.ObjectInput in = call.getInputStream();"); boolean objectRead=writeUnmarshalArgument(p,"in",returnType,"$result"); p.pln(";"); p.pOlnI("} catch (java.io.IOException e) {"); p.pln("throw new " + UNMARSHAL_EXCEPTION + "(\"error unmarshalling return\", e);"); if (objectRead) { p.pOlnI("} catch (java.lang.ClassNotFoundException e) {"); p.pln("throw new " + UNMARSHAL_EXCEPTION + "(\"error unmarshalling return\", e);"); } p.pOlnI("} finally {"); p.pln("ref.done(call);"); p.pOln("}"); p.pln("return $result;"); } } if (version == StubVersion.VCOMPAT) { p.pOln("}"); } if (catchList.size() > 0) { for ( ClassDoc catchClass : catchList) { p.pOlnI("} catch (" + catchClass.qualifiedName() + " e) {"); p.pln("throw e;"); } p.pOlnI("} catch (java.lang.Exception e) {"); p.pln("throw new " + UNEXPECTED_EXCEPTION + "(\"undeclared checked exception\", e);"); p.pOln("}"); } p.pOln("}"); }
Writes the stub method for the remote method with the given operation number.
public BulkRetrievalEvent(BulkRetrievable source,String eventType,String item){ super(source); this.eventType=eventType; this.item=item; }
Creates a new event.
@NotNull public List<? extends TargetBuilder<?,?>> createBuilders(){ return Collections.emptyList(); }
Returns the list of non-module target builders contributed by this plugin.
public TrieTest(String name){ super(name); }
Constructs the <code>TrieTest</code>.
protected ModbusSlave(int port,int poolSize) throws ModbusException { this(ModbusSlaveType.TCP,port,poolSize,null); }
Creates a TCP modbus slave
public final boolean readBoolean() throws IOException { int ch=in.read(); if (ch < 0) throw new EOFException(); return (ch != 0); }
See the general contract of the <code>readBoolean</code> method of <code>DataInput</code>. <p> Bytes for this operation are read from the contained input stream.
public ReaderComponent(String name,ReaderWorld newWorld){ super(name); world=newWorld; init(); }
Construct a component from an existing world; used in deserializing.
public TenantDeletionConstraintException(String message,TenantDeletionConstraintException.Reason reason){ super(message); setMessageKey(getMessageKey() + "." + reason.toString()); }
Constructs a new exception with the given detail message, and appends the specified reason to the message key.
protected void onPushDismiss(Context context,Intent intent){ }
Called when the push notification is dismissed. By default, nothing is performed on notification dismissal.
public void resetDocumentLocator(String publicid,String systemid){ thePublicid=publicid; theSystemid=systemid; theLastLine=theLastColumn=theCurrentLine=theCurrentColumn=0; }
Reset document locator, supplying systemid and publicid.
public void doPrint(){ PrintController printer=new PrintController(); printer.printComponent(getFrame(),jTextArea1,"Print Errors"); }
doPrint()() -
public void removeStream(String streamName){ StreamMeta sm=logicalPlan.getStream(streamName); if (sm == null) { return; } if (physicalPlan != null) { physicalPlan.removeLogicalStream(sm); } sm.remove(); }
Remove the named stream. Ignored when stream does not exist.
public NameNotFoundException(String message,Throwable cause){ super(message,cause); }
Constructs instance of ObjectNameNotFoundException with error message and cause
public void computeRangeFacet(String facet){ Map<String,StatsCollector[]> f=rangeFacetCollectors.get(facet); for ( StatsCollector[] arr : f.values()) { for ( StatsCollector b : arr) { b.compute(); } } }
Finalizes the statistics within the a specific range facet before exporting;
protected String normalizeNewlines(String source){ return perl.substitute("s/\r[\n]/\n/g",source); }
Normalizes lines to account for platform differences. Macs use a single \r, DOS derived operating systems use \r\n, and Unix uses \n. Replace each with a single \n.
public static List<Object> parseParams(WarpScriptStack stack,int... numparams) throws WarpScriptException { List<Object> params=new ArrayList<Object>(); int count=0; Arrays.sort(numparams); int maxparams=numparams[numparams.length - 1]; while (0 != stack.depth() && count <= maxparams) { Object top=stack.pop(); if (top instanceof PGraphics) { params.add(top); Collections.reverse(params); break; } params.add(top); count++; } if (Arrays.binarySearch(numparams,count) < 0) { throw new WarpScriptException("Invalid number of parameters, expected one of " + Arrays.toString(numparams) + " but found "+ count); } return params; }
Retrieve parameters from the stack until a PGraphics instance is found.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:55:09.403 -0500",hash_original_method="2022581A914A53DEAB486C7C21721639",hash_generated_method="0B028D7882C237D4D15E9A31C97182E9") public int compareMediaRange(String media){ return (mediaRange.type + "/" + mediaRange.subtype).compareToIgnoreCase(media); }
compare two MediaRange headers.
public void copy(BytesRef bytes,BytesRef out){ int left=blockSize - upto; if (bytes.length > left || currentBlock == null) { if (currentBlock != null) { addBlock(currentBlock); didSkipBytes=true; } currentBlock=new byte[blockSize]; upto=0; left=blockSize; assert bytes.length <= blockSize; } out.bytes=currentBlock; out.offset=upto; out.length=bytes.length; System.arraycopy(bytes.bytes,bytes.offset,currentBlock,upto,bytes.length); upto+=bytes.length; }
Copy BytesRef in, setting BytesRef out to the result. Do not use this if you will use freeze(true). This only supports bytes.length &lt;= blockSize
void addFillComponents(Container panel,int[] cols,int[] rows){ Dimension filler=new Dimension(10,10); boolean filled_cell_11=false; CellConstraints cc=new CellConstraints(); if (cols.length > 0 && rows.length > 0) { if (cols[0] == 1 && rows[0] == 1) { panel.add(Box.createRigidArea(filler),cc.xy(1,1)); filled_cell_11=true; } } for (int index=0; index < cols.length; index++) { if (cols[index] == 1 && filled_cell_11) { continue; } panel.add(Box.createRigidArea(filler),cc.xy(cols[index],1)); } for (int index=0; index < rows.length; index++) { if (rows[index] == 1 && filled_cell_11) { continue; } panel.add(Box.createRigidArea(filler),cc.xy(1,rows[index])); } }
Adds fill components to empty cells in the first row and first column of the grid. This ensures that the grid spacing will be the same as shown in the designer.
private void handleEventSynchronous(Event event) throws ReplicatorException { EventRequest request=null; try { request=eventDispatcher.put(event); request.get(); } catch ( InterruptedException e) { logger.warn("Event processing was interrupted: " + event.getClass().getName()); Thread.currentThread().interrupt(); return; } catch ( ExecutionException e) { logger.warn("Event processing failed: " + event.getClass().getName(),e); return; } Object annotation=request.getAnnotation(); if (annotation instanceof ReplicatorException) { ReplicatorException e=(ReplicatorException)annotation; if (logger.isDebugEnabled()) logger.debug("Event processing failed",e); throw e; } }
Wrapper method for methods that submits a synchronous event with proper MBean error handling. This translates the various state machine exceptions into a proper replicator exception.
public static void assertNull(Object object,String message){ if (object != null) { throw new IllegalArgumentException("assertion failed:" + message); } }
Asserts that the given object is <code>null</code>. If this is not the case, a <code>IllegalArgumentException</code> is thrown. The given message is included in that exception, to aid debugging.
protected void endDocument() throws XMLStreamException { this.writer.writeEndElement(); this.writer.writeEndElement(); this.writer.writeEndDocument(); this.writer.close(); }
End the KML document.
@Override public void onDestroyView(){ mHandler.removeCallbacks(mRequestFocus); mList=null; mListShown=false; mEmptyView=mProgressContainer=mListContainer=null; mStandardEmptyView=null; super.onDestroyView(); }
Detach from list view.
private static String grabLine(BufferedReader r) throws Exception { int index=0; String line=r.readLine(); while (line.startsWith("//") || line.length() < 1) line=r.readLine(); while ((index=line.indexOf("\\n")) != -1) { StringBuffer temp=new StringBuffer(line); temp.replace(index,index + 2,"\n"); line=temp.toString(); } while ((index=line.indexOf("\\u")) != -1) { StringBuffer temp=new StringBuffer(line); String value=temp.substring(index + 2,index + 6); char aChar=(char)Integer.parseInt(value,16); String unicodeChar="" + aChar; temp.replace(index,index + 6,unicodeChar); line=temp.toString(); } return line; }
Reads a line from the input file. Keeps reading lines until a non empty non comment line is read. If the line contains a \n then these two characters are replaced by a newline char. If a \\uxxxx sequence is read then the sequence is replaced by the unicode char.
public EdgeInfo(int start,int end,int cap,int cost){ this.start=start; this.end=end; this.capacity=cap; this.cost=cost; }
Construct EdgeInfo from (start,end) vertices with given capacity.
static public double perc(int value,int max){ return perc((double)value,(double)max); }
It returns the percentage 100 * <tt>value</tt> / <tt>max</tt>.
public static boolean isExternalStorageAvailable(){ String state=Environment.getExternalStorageState(); boolean mExternalStorageAvailable, mExternalStorageWriteable; if (Environment.MEDIA_MOUNTED.equals(state)) { mExternalStorageAvailable=mExternalStorageWriteable=true; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { mExternalStorageAvailable=true; mExternalStorageWriteable=false; } else { mExternalStorageAvailable=mExternalStorageWriteable=false; } return mExternalStorageAvailable && mExternalStorageWriteable; }
Checks if SD card available
@Override public void put(String name,boolean value){ emulatedFields.put(name,value); }
Find and set the boolean value of a given field named <code>name</code> in the receiver.
public BubbleChart(XYMultipleSeriesDataset dataset,XYMultipleSeriesRenderer renderer){ super(dataset,renderer); }
Builds a new bubble chart instance.
public boolean hasAdds(){ return !addedClusters.isEmpty() || !addedHosts.isEmpty() || !addedInitiators.isEmpty(); }
Returns true is export group state has additions (new hosts, new clusters, new initiators)
private void _serializeList(PageContext pc,Set test,List list,StringBuilder sb,boolean serializeQueryByColumns,Set<Object> done) throws ConverterException { sb.append(goIn()); sb.append("["); boolean doIt=false; ListIterator it=list.listIterator(); while (it.hasNext()) { if (doIt) sb.append(','); doIt=true; _serialize(pc,test,it.next(),sb,serializeQueryByColumns,done); } sb.append(']'); }
serialize a List (as Array)
public NSData(byte[] bytes){ this.bytes=bytes; }
Creates the NSData object from the binary representation of it.
public Object runSafely(Catbert.FastStack stack) throws Exception { Airing a=getAir(stack); if (a == null) return new Long(0); Watched w=Wizard.getInstance().getWatch(a); if (w != null) return new Long(w.getRealWatchStart()); if (stack.getUIMgrSafe() != null && stack.getUIMgrSafe().getVideoFrame().hasFile()) { MediaFile mf=stack.getUIMgrSafe().getVideoFrame().getCurrFile(); if (mf != null && mf.getContentAiring() == a) return new Long(stack.getUIMgrSafe().getVideoFrame().getRealWatchStart()); } return new Long(0); }
Gets the time the user started watching this Airing, in real time.
public String toString(){ return ((primaryGroup ? rb.getString("SolarisNumericGroupPrincipal.Primary.Group.") + name : rb.getString("SolarisNumericGroupPrincipal.Supplementary.Group.") + name)); }
Return a string representation of this <code>SolarisNumericGroupPrincipal</code>. <p>
@PostConstruct public void build(){ try { if (eventStream == null) { logger.info("Building event stream..."); } else { logger.info("Rebuilding event stream.."); eventStream.setActive(false); } eventStream=makeEventStream(); eventStream.setActive(true); logger.info("Success building event stream."); } catch ( Exception e) { logger.error("Fail to build event stream reason : " + e.getMessage(),e); } }
Build event stream
public static int discrete(double[] probabilities){ if (probabilities == null) throw new NullPointerException("argument array is null"); double EPSILON=1E-14; double sum=0.0; for (int i=0; i < probabilities.length; i++) { if (!(probabilities[i] >= 0.0)) throw new IllegalArgumentException("array entry " + i + " must be nonnegative: "+ probabilities[i]); sum+=probabilities[i]; } if (sum > 1.0 + EPSILON || sum < 1.0 - EPSILON) throw new IllegalArgumentException("sum of array entries does not approximately equal 1.0: " + sum); while (true) { double r=uniform(); sum=0.0; for (int i=0; i < probabilities.length; i++) { sum=sum + probabilities[i]; if (sum > r) return i; } } }
Returns a random integer from the specified discrete distribution.
public Builder singleShot(long shotId){ showcaseView.setSingleShot(shotId); return this; }
Set the ShowcaseView to only ever show once.
public PostfixOperator createPostfixOperatorFromString(EDataType eDataType,String initialValue){ PostfixOperator result=PostfixOperator.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '"+ eDataType.getName()+ "'"); return result; }
<!-- begin-user-doc --> <!-- end-user-doc -->
public void hidePalette(){ WindowSupport ws=getWindowSupport(); if (ws != null) { ws.killWindow(); } }
Hide the layer's palette.
public void addCatch(char startPc,char endPc,char handlerPc,char catchType){ catchInfo.append(new char[]{startPc,endPc,handlerPc,catchType}); }
Add a catch clause to code.