code
stringlengths
10
174k
nl
stringlengths
3
129k
public VolumeMonitor(SpeechController speechController,TalkBackService context){ if (speechController == null) throw new IllegalStateException(); mContext=context; mSpeechController=speechController; mAudioManager=(AudioManager)context.getSystemService(Context.AUDIO_SERVICE); mTelephonyManager=(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); }
Creates and initializes a new volume monitor.
public ResourceLineage(){ resourceMap=new LinkedMap<>(); }
Empty lineage for objects rooted in the URL.
public void normalise(){ this.dirty=true; float mag=(float)Math.sqrt(points[3] * points[3] + points[0] * points[0] + points[1] * points[1] + points[2] * points[2]); points[3]=points[3] / mag; points[0]=points[0] / mag; points[1]=points[1] / mag; points[2]=points[2] / mag; }
Normalise this Quaternion into a unity Quaternion.
protected void _addFields(){ final AnnotationIntrospector ai=_annotationIntrospector; for ( AnnotatedField f : _classDef.fields()) { String implName=f.getName(); String explName; if (ai == null) { explName=null; } else if (_forSerialization) { explName=ai.findSerializablePropertyName(f); } else { explName=ai.findDeserializablePropertyName(f); } if ("".equals(explName)) { explName=implName; } boolean visible=(explName != null); if (!visible) { visible=_visibilityChecker.isFieldVisible(f); } boolean ignored=(ai != null) && ai.hasIgnoreMarker(f); _property(implName).addField(f,explName,visible,ignored); } }
Method for collecting basic information on all fields found
public ParsedURL(String urlStr){ userAgent=getGlobalUserAgent(); data=parseURL(urlStr); }
Construct a ParsedURL from the given url string.
public static void main(final String[] args){ DOMTestCase.doMain(attrgetownerelement04.class,args); }
Runs this test from the command line.
private void _shutdownScheduledExecutorService(){ _logger.info("Shutting down scheduled disable warden alerts executor service"); _scheduledExecutorService.shutdown(); try { if (!_scheduledExecutorService.awaitTermination(5,TimeUnit.SECONDS)) { _logger.warn("Shutdown of scheduled disable warden alerts executor service timed out after 5 seconds."); _scheduledExecutorService.shutdownNow(); } } catch ( InterruptedException ex) { _logger.warn("Shutdown of executor service was interrupted."); Thread.currentThread().interrupt(); } }
Shuts down the scheduled executor service.
public final void removePoint(double x){ dataPoints--; if (dataPoints <= 0) { initialize(); } else { sumX-=x; sumXSq-=x * x; } }
Remove a X data point only.
public synchronized MetaStore storeTerm(long term){ LOGGER.debug("Store term {}",term); buffer.writeLong(0,term).flush(); return this; }
Stores the current server term.
public EmailIntentBuilder bcc(@NonNull Collection<String> bcc){ checkNotNull(bcc); for ( String email : bcc) { checkEmail(email); } this.bcc.addAll(bcc); return this; }
Add an email address to be used in the "bcc" field.
public static java.lang.String valueOf(char c){ return null; }
Returns the string representation of the char argument.
public static final boolean isASCII(Resources res,int resId) throws IOException, NotFoundException { BufferedReader buffer=new BufferedReader(new InputStreamReader(res.openRawResource(resId))); boolean isASCII=isASCII(buffer); buffer.close(); return isASCII; }
Determine if a given resource appears to be in ASCII format.
public synchronized void addTextListener(TextListener cl){ m_textListeners.addElement(cl); }
Add a text listener
private void tellClients(){ Player partner=SingletonRepository.getRuleProcessor().getPlayer(partnerName); if (partner == null) { player.addEvent(new TradeStateChangeEvent(-1,tradeState,TradeState.NO_ACTIVE_TRADE)); } else { player.addEvent(new TradeStateChangeEvent(partner.getInt("id"),tradeState,partner.getTradeState())); partner.addEvent(new TradeStateChangeEvent(player.getInt("id"),partner.getTradeState(),tradeState)); partner.notifyWorldAboutChanges(); } player.notifyWorldAboutChanges(); }
inform both clients about the current state of trading.
private void distributeExtraSpace(int extraHeight){ int topSpacerHeight; int middleSpacerHeight; int bottomSpacerHeight; if (extraHeight < mTotalSpacerHeight) { topSpacerHeight=Math.round(extraHeight * (TOP_SPACER_HEIGHT_DP / TOTAL_SPACER_HEIGHT_DP)); extraHeight-=topSpacerHeight; middleSpacerHeight=Math.round(extraHeight * (MIDDLE_SPACER_HEIGHT_DP / (MIDDLE_SPACER_HEIGHT_DP + BOTTOM_SPACER_HEIGHT_DP))); extraHeight-=middleSpacerHeight; bottomSpacerHeight=extraHeight; } else { topSpacerHeight=mTopSpacerHeight; middleSpacerHeight=mMiddleSpacerHeight; bottomSpacerHeight=mBottomSpacerHeight; extraHeight-=mTotalSpacerHeight; topSpacerHeight+=(extraHeight + 1) / 2; bottomSpacerHeight+=extraHeight / 2; } int widthSpec=MeasureSpec.makeMeasureSpec(0,MeasureSpec.EXACTLY); mTopSpacer.measure(widthSpec,MeasureSpec.makeMeasureSpec(topSpacerHeight,MeasureSpec.EXACTLY)); mMiddleSpacer.measure(widthSpec,MeasureSpec.makeMeasureSpec(middleSpacerHeight,MeasureSpec.EXACTLY)); mBottomSpacer.measure(widthSpec,MeasureSpec.makeMeasureSpec(bottomSpacerHeight,MeasureSpec.EXACTLY)); }
Distribute extra vertical space between the three spacer views.
public static void updateVArrayRelations(Collection<StoragePort> ports,Collection<StoragePort> remPorts,DbClient dbClient,CoordinatorClient coordinator){ HashSet<URI> systemsToProcess=getStorageSytemsFromPorts(ports,remPorts); for ( URI systemUri : systemsToProcess) { updateSystemVarrays(systemUri,dbClient); } }
Given the changes made to a list of ports' varray associations, update the pools associations.
public XMLSignatureInput resolve(Attr uri,String baseURI,boolean secureValidation) throws ResourceResolverException { ResourceResolverContext context=new ResourceResolverContext(uri,baseURI,secureValidation); return resolverSpi.engineResolveURI(context); }
Method resolve
@Deprecated public static Uri addToGroup(ContentResolver resolver,long personId,long groupId){ ContentValues values=new ContentValues(); values.put(GroupMembership.PERSON_ID,personId); values.put(GroupMembership.GROUP_ID,groupId); return resolver.insert(GroupMembership.CONTENT_URI,values); }
Adds a person to a group.
public static boolean putFloat(ContentResolver cr,String name,float value){ return putFloatForUser(cr,name,value,UserHandle.myUserId()); }
Convenience function for updating a single settings value as a floating point number. This will either create a new entry in the table if the given name does not exist, or modify the value of the existing row with that name. Note that internally setting values are always stored as strings, so this function converts the given value to a string before storing it.
public CompactConcurrentHashSet2(int initialCapacity){ if (initialCapacity < 0) throw new IllegalArgumentException(); int cap=((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY : tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1)); this.sizeCtl=cap; }
Creates a new, empty map with an initial table size accommodating the specified number of elements without the need to dynamically resize.
protected void parseStartSound(InStream in) throws IOException { int id=in.readUI16(); SoundInfo info=new SoundInfo(in); tagtypes.tagStartSound(id,info); }
Description of the Method
public static void process(Process p,LineConsumer stdout) throws IOException { try (BufferedReader inputReader=new BufferedReader(new InputStreamReader(p.getInputStream()))){ String line; while ((line=inputReader.readLine()) != null) { stdout.writeLine(line); } } }
Writes stdout of the process to consumer.<br> Supposes that stderr of the process is redirected to stdout.
public UDView bringToFront(){ final View view=getView(); if (view != null) { view.bringToFront(); } return this; }
bring a view to front
public void runTest() throws Throwable { String namespaceURI="http://www.ecommerce.org/schema"; String qualifiedName="y:x"; Document doc; DocumentType docType=null; DOMImplementation domImpl; Document aNewDoc; String nodeName; String nodeValue; doc=(Document)load("staffNS",false); domImpl=doc.getImplementation(); aNewDoc=domImpl.createDocument(namespaceURI,qualifiedName,docType); nodeName=aNewDoc.getNodeName(); nodeValue=aNewDoc.getNodeValue(); assertEquals("nodeName","#document",nodeName); assertNull("nodeValue",nodeValue); }
Runs the test case.
public boolean usesClass(String className){ return findClass(className) != NOT_FOUND; }
Checks if the constant pool contains a reference to the provided class. NB: Most uses of a type do <em>NOT</em> show up as a class in the constant pool. For example, the parameter types and return type of any method you invoke or declare, are stored as signatures and not as type references, but the type to which any method you invoke belongs, is. Read the JVM Specification for more information.
boolean verifyDeveloperPayload(Purchase p){ String payload=p.getDeveloperPayload(); return true; }
Verifies the developer payload of a purchase.
public static String printInferenceResult(InferenceResult ir){ StringBuilder sb=new StringBuilder(); sb.append("InferenceResult.isTrue=" + ir.isTrue()); sb.append("\n"); sb.append("InferenceResult.isPossiblyFalse=" + ir.isPossiblyFalse()); sb.append("\n"); sb.append("InferenceResult.isUnknownDueToTimeout=" + ir.isUnknownDueToTimeout()); sb.append("\n"); sb.append("InferenceResult.isPartialResultDueToTimeout=" + ir.isPartialResultDueToTimeout()); sb.append("\n"); sb.append("InferenceResult.#Proofs=" + ir.getProofs().size()); sb.append("\n"); int proofNo=0; for ( Proof p : ir.getProofs()) { proofNo++; sb.append("InferenceResult.Proof#" + proofNo + "=\n"+ ProofPrinter.printProof(p)); } return sb.toString(); }
Utility method for outputting InferenceResults in a formatted textual representation.
private void validateUserNamespaceAuthorizationCreateRequest(UserNamespaceAuthorizationCreateRequest request){ Assert.notNull(request,"A user namespace authorization create request must be specified."); validateUserNamespaceAuthorizationKey(request.getUserNamespaceAuthorizationKey()); validateNamespacePermissions(request.getNamespacePermissions()); }
Validates the user namespace authorization create request. This method also trims the request parameters.
final int dec(int i){ return ((i == 0) ? items.length : i) - 1; }
Circularly decrement i.
public boolean isMarkSeen(){ return fieldMarkSeen; }
Returns the markSeen.
public void addPlayer(final Player player){ this.onlinePlayers.add(player); }
Adds a player object to the list of players.
public void checkLoadScript(String scriptType,ParsedURL scriptURL,ParsedURL docURL) throws SecurityException { ScriptSecurity s=getScriptSecurity(scriptType,scriptURL,docURL); if (s != null) { s.checkLoadScript(); } }
This method throws a SecurityException if the script of given type, found at url and referenced from docURL should not be loaded. This is a convenience method to call checkLoadScript on the ScriptSecurity strategy returned by getScriptSecurity.
static public long longFactorial(int k) throws IllegalArgumentException { if (k < 0) throw new IllegalArgumentException("Negative k"); if (k < longFactorials.length) return longFactorials[k]; throw new IllegalArgumentException("Overflow"); }
Instantly returns the factorial <tt>k!</tt>.
private void generatePaySelect(){ if (miniTable.getRowCount() == 0) return; miniTable.setSelectedIndices(new int[]{0}); calculateSelection(); if (m_noSelected == 0) return; String msg=generatePaySelect(miniTable,(ValueNamePair)fieldPaymentRule.getSelectedItem().getValue(),new Timestamp(fieldPayDate.getComponent().getValue().getTime()),(BankInfo)fieldBankAccount.getSelectedItem().getValue()); if (msg != null && msg.length() > 0) { FDialog.error(m_WindowNo,form,"SaveError",msg); return; } if (!FDialog.ask(m_WindowNo,form,"VPaySelectGenerate?","(" + m_ps.getName() + ")")) return; int AD_Proces_ID=155; ProcessModalDialog dialog=new ProcessModalDialog(this,m_WindowNo,AD_Proces_ID,X_C_PaySelection.Table_ID,m_ps.getC_PaySelection_ID(),false); if (dialog.isValid()) { try { dialog.setWidth("500px"); dialog.setVisible(true); dialog.setPage(form.getPage()); dialog.doModal(); } catch ( SuspendNotAllowedException e) { log.log(Level.SEVERE,e.getLocalizedMessage(),e); } catch ( InterruptedException e) { log.log(Level.SEVERE,e.getLocalizedMessage(),e); } } }
Generate PaySelection
public StatelessSection(int headerResourceId,int footerResourceId,int itemResourceId){ this(headerResourceId,itemResourceId); this.footerResourceId=footerResourceId; this.hasFooter=true; }
Create a Section object with loading/failed states, a custom header and footer
@Override public Object eGet(int featureID,boolean resolve,boolean coreType){ switch (featureID) { case UmplePackage.ANONYMOUS_EVENT_DEFINITION_1__PARAMETER_LIST_1: return getParameterList_1(); } return super.eGet(featureID,resolve,coreType); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public static void d(String tag,String msg,Throwable tr){ println(DEBUG,tag,msg,tr); }
Prints a message at DEBUG priority.
public void evalMinAggregatedValue(final String field,final String fieldValue,final long value) throws RequiredInputMissingException { if (StringUtils.isBlank(field)) throw new RequiredInputMissingException("Missing required input for parameter 'field'"); if (StringUtils.isBlank(fieldValue)) throw new RequiredInputMissingException("Missing required input for parameter 'fieldValue'"); String fieldKey=StringUtils.lowerCase(StringUtils.trim(field)); String fieldValueKey=StringUtils.lowerCase(StringUtils.trim(fieldValue)); Map<String,Long> fieldAggregationValues=this.aggregatedValues.get(fieldKey); if (fieldAggregationValues == null) fieldAggregationValues=new HashMap<>(); long aggregationValue=(fieldAggregationValues.containsKey(fieldValueKey) ? fieldAggregationValues.get(fieldValueKey) : Integer.MAX_VALUE); if (value < aggregationValue) { fieldAggregationValues.put(fieldValueKey,value); this.aggregatedValues.put(fieldKey,fieldAggregationValues); } }
Evaluates the referenced aggregated value against the provided value and saves the smaller one
public void receiveResendFileTransferInvitation(FileSharingSession session,ContactId remoteContact,String displayName){ if (sLogger.isActivated()) { sLogger.info("Receive resend FT invitation from " + remoteContact + " displayName="+ displayName); } OneToOneFileTransferImpl oneToOneFileTransfer=getOrCreateOneToOneFileTransfer(session.getFileTransferId()); session.addListener(oneToOneFileTransfer); }
Receive a new resend file transfer invitation
public static ConjunctionOfClauses convert(Sentence s){ ConjunctionOfClauses result=null; Sentence cnfSentence=ConvertToCNF.convert(s); List<Clause> clauses=new ArrayList<Clause>(); clauses.addAll(ClauseCollector.getClausesFrom(cnfSentence)); result=new ConjunctionOfClauses(clauses); return result; }
Returns the specified sentence in its logically equivalent conjunction of clauses.
public void registerConverter(final SingleValueConverter converter){ registerConverter(converter,PRIORITY_NORMAL); }
Register a single value converter with normal priority.
public SelfSignSslOkHttpStack(OkHttpClient okHttpClient,Map<String,SSLSocketFactory> factoryMap){ this.okHttpClient=okHttpClient; this.socketFactoryMap=factoryMap; }
Create a OkHttpStack with a custom OkHttpClient
public AppletServer(int port,ClassPool src) throws IOException, NotFoundException, CannotCompileException { this(new ClassPool(src),new StubGenerator(),port); }
Constructs a web server.
public void taskClassName(String taskClsName){ this.taskClsName=taskClsName; }
Sets name of the task class that triggered this event.
@Override public ServiceExceptionNotAuthorized rethrow(String msg){ return new ServiceExceptionNotAuthorized(msg,this); }
Rethrows an exception to record the full stack trace, both caller and callee.
public List<Option> asSortedList(){ ArrayList<Option> options=new ArrayList<Option>(); if (if_match_list != null) for ( byte[] value : if_match_list) options.add(new Option(OptionNumberRegistry.IF_MATCH,value)); if (hasUriHost()) options.add(new Option(OptionNumberRegistry.URI_HOST,getUriHost())); if (etag_list != null) for ( byte[] value : etag_list) options.add(new Option(OptionNumberRegistry.ETAG,value)); if (hasIfNoneMatch()) options.add(new Option(OptionNumberRegistry.IF_NONE_MATCH)); if (hasUriPort()) options.add(new Option(OptionNumberRegistry.URI_PORT,getUriPort())); if (location_path_list != null) for ( String str : location_path_list) options.add(new Option(OptionNumberRegistry.LOCATION_PATH,str)); if (uri_path_list != null) for ( String str : uri_path_list) options.add(new Option(OptionNumberRegistry.URI_PATH,str)); if (hasContentFormat()) options.add(new Option(OptionNumberRegistry.CONTENT_FORMAT,getContentFormat())); if (hasMaxAge()) options.add(new Option(OptionNumberRegistry.MAX_AGE,getMaxAge())); if (uri_query_list != null) for ( String str : uri_query_list) options.add(new Option(OptionNumberRegistry.URI_QUERY,str)); if (hasAccept()) options.add(new Option(OptionNumberRegistry.ACCEPT,getAccept())); if (location_query_list != null) for ( String str : location_query_list) options.add(new Option(OptionNumberRegistry.LOCATION_QUERY,str)); if (hasProxyUri()) options.add(new Option(OptionNumberRegistry.PROXY_URI,getProxyUri())); if (hasProxyScheme()) options.add(new Option(OptionNumberRegistry.PROXY_SCHEME,getProxyScheme())); if (hasObserve()) options.add(new Option(OptionNumberRegistry.OBSERVE,getObserve())); if (hasBlock1()) options.add(new Option(OptionNumberRegistry.BLOCK1,getBlock1().getValue())); if (hasBlock2()) options.add(new Option(OptionNumberRegistry.BLOCK2,getBlock2().getValue())); if (hasSize1()) options.add(new Option(OptionNumberRegistry.SIZE1,getSize1())); if (hasSize2()) options.add(new Option(OptionNumberRegistry.SIZE2,getSize2())); if (others != null) options.addAll(others); Collections.sort(options); return options; }
Returns all options in a list sorted according to their option number. The list cannot be use to modify the OptionSet of the message, since it is a copy.
public SubscriptionMigrationException(){ super(); }
Constructs a new exception with <code>null</code> as its detail message. The cause is not initialized.
public void clear(){ m.clear(); }
Removes all of the elements from this set. The set will be empty after this call returns.
public Node encode(Object obj){ Node node=null; if (obj != null) { String name=mxCodecRegistry.getName(obj); mxObjectCodec enc=mxCodecRegistry.getCodec(name); if (enc != null) { node=enc.encode(this,obj); } else { if (obj instanceof Node) { node=((Node)obj).cloneNode(true); } else { System.err.println("No codec for " + name); } } } return node; }
Encodes the specified object and returns the resulting XML node.
@Override public Adapter createAdapter(Notifier target){ return modelSwitch.doSwitch((EObject)target); }
Creates an adapter for the <code>target</code>. <!-- begin-user-doc --> <!-- end-user-doc -->
@Override public Automaton<LR1Item,LR1State> createAutomaton() throws GeneratorException { return new LALR1AutomatonFactory().createAutomaton(this,grammarInfo); }
Creates the DFA of the parser, consisting of states and edges (for shift and goto) connecting them.
public void close(){ AQUtility.close(close); close=null; }
Close any opened inputstream associated with the response. Call this method when finish parsing the response of a synchronous call.
public static void dropTable(SQLiteDatabase db,boolean ifExists){ String sql="DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "'ADDRESS_BOOK'"; db.execSQL(sql); }
Drops the underlying database table.
public void progressbarReady(TextView downloadStatus,ProgressBar progressBar){ int status=Variable.getVariable().getDownloadStatus(); if (status == Constant.DOWNLOADING || status == Constant.PAUSE) { try { this.downloadStatusTV=downloadStatus; initProgressBar(progressBar); this.vh=(View)progressBar.getParent(); itemPosition=mapsRV.getChildAdapterPosition(vh); } catch ( Exception e) { e.getStackTrace(); } } }
Recycler view is ready to use
public Object runSafely(Catbert.FastStack stack) throws Exception { Widget cw=getWidget(stack); Widget pw=getWidget(stack); if (SageConstants.LITE) return null; if (cw != null && pw != null && pw.willContain(cw)) WidgetFidget.contain(pw,cw); return null; }
Creates a parent-child relationship between two Widgets. If the relationship already exists, this call has no effect. This new child will be the last child of the parent.
protected static String urlDecode(String str) throws UnsupportedEncodingException { return URLDecoder.decode(str.replace("+","%2B"),"UTF-8"); }
Decode URL-encoded strings as UTF-8, and avoid converting "+" to space
@SuppressWarnings({"unchecked","rawtypes"}) public static LineByLineFileInputOperator restoreCheckPoint(LineByLineFileInputOperator checkPointOper,ByteArrayOutputStream bos) throws Exception { Kryo kryo=new Kryo(); Input lInput=new Input(bos.toByteArray()); LineByLineFileInputOperator oper=kryo.readObject(lInput,checkPointOper.getClass()); lInput.close(); return oper; }
Restores the checkpointed operator.
public Weight(String magnitude,WeightUnit unit){ this.magnitude=new BigDecimal(magnitude); this.unit=unit; }
Create a new <code>Weight</code>.
public SerialTurnout(String systemName,String userName){ super(systemName,userName); tSystemName=systemName; tBit=SerialAddress.getBitFromSystemName(systemName); }
Create a Turnout object, with both system and user names. <P> 'systemName' was previously validated in SerialTurnoutManager
public DistributedLogClientBuilder handshakeWithClientInfo(boolean enabled){ DistributedLogClientBuilder newBuilder=newBuilder(this); newBuilder._clientConfig.setHandshakeWithClientInfo(enabled); return newBuilder; }
Whether to use the new handshake endpoint to exchange ownership cache. Enable this when the servers are updated to support handshaking with client info.
public void fireSynapseChanged(final Synapse changed){ for ( SynapseListener listener : synapseListeners) { listener.synapseChanged(new NetworkEvent<Synapse>(this,changed)); } }
Fire a synapse changed event to all registered model listeners.
public boolean checkValidity(){ Matcher matcher=sValidityPattern.matcher(getFieldName()); isValid=matcher.find(); return isValid; }
Check validity of field name
public void ensureCapacity(int additionalCapacity){ int sizeNeeded=size + additionalCapacity; if (sizeNeeded >= threshold) resize(MathUtils.nextPowerOfTwo((int)(sizeNeeded / loadFactor))); }
Increases the size of the backing array to acommodate the specified number of additional items. Useful before adding many items to avoid multiple backing array resizes.
public synchronized void write(byte b[],int off,int len) throws IOException { out.write(b,off,len); incCount(len); }
Writes <code>len</code> bytes from the specified byte array starting at offset <code>off</code> to the underlying output stream. If no exception is thrown, the counter <code>written</code> is incremented by <code>len</code>.
private Headers parseResponseHeaders(URI uri,int responseCode,Map<String,List<String>> responseHeaders){ try { NoHttp.getCookieManager().put(uri,responseHeaders); } catch ( IOException e) { Logger.e(e,"Save cookie filed: " + uri.toString() + "."); } Headers headers=new HttpHeaders(); headers.set(responseHeaders); headers.set(Headers.HEAD_KEY_RESPONSE_CODE,Integer.toString(responseCode)); for ( String headKey : headers.keySet()) { List<String> headValues=headers.getValues(headKey); for ( String headValue : headValues) { StringBuilder builder=new StringBuilder(); if (!TextUtils.isEmpty(headKey)) builder.append(headKey).append(": "); if (!TextUtils.isEmpty(headValue)) builder.append(headValue); Logger.i(builder.toString()); } } return headers; }
Parse server response headers, here will save cookies.
protected void illegalMessageReceived(OFMessage m){ String msg=getSwitchStateMessage(m,"Switch should never send this message in the current state"); throw new SwitchStateException(msg); }
We have an OFMessage we didn't expect given the current state and we want to treat this as an error. We currently throw an exception that will terminate the connection However, we could be more forgiving
public WordsToTokens(Parser p){ parser=p; }
Creates the parser.
public static ArrayList<Coords> intervening(Coords src,Coords dest,boolean split){ IdealHex iSrc=IdealHex.get(src); IdealHex iDest=IdealHex.get(dest); int[] directions=new int[3]; int centerDirection=src.direction(dest); if (split) { centerDirection=(int)Math.round(src.radian(dest) + 0.0001 / HEXSIDE) % 6; } directions[2]=centerDirection; directions[1]=(centerDirection + 5) % 6; directions[0]=(centerDirection + 1) % 6; ArrayList<Coords> hexes=new ArrayList<>(); Coords current=src; hexes.add(current); while (!dest.equals(current)) { current=Coords.nextHex(current,iSrc,iDest,directions); hexes.add(current); } return hexes; }
Returns an array of the Coords of hexes that are crossed by a straight line from the center of src to the center of dest, including src & dest. The returned coordinates are in line order, and if the line passes directly between two hexes, it returns them both. Based on the degree of the angle, the next hex is going to be one of three hexes. We check those three hexes, sides first, add the first one that intersects and continue from there. Based off of some of the formulas at Amit's game programming site. (http://www-cs-students.stanford.edu/~amitp/gameprog.html) Note: this function can return Coordinates that are not on the board.
private GeofenceErrorMessages(){ }
Prevents instantiation.
public static <STATE,ACTION,PLAYER>IterativeDeepeningAlphaBetaSearch<STATE,ACTION,PLAYER> createFor(Game<STATE,ACTION,PLAYER> game,double utilMin,double utilMax,int time){ return new IterativeDeepeningAlphaBetaSearch<STATE,ACTION,PLAYER>(game,utilMin,utilMax,time); }
Creates a new search object for a given game.
public Depend_ createDepend_(){ Depend_Impl depend_=new Depend_Impl(); return depend_; }
<!-- begin-user-doc --> <!-- end-user-doc -->
public DragControl(){ }
Creates a new drag control that issues repaint requests as an item is dragged.
public double eval(double params[]){ double p1=params[0]; double p2=params[1]; return (p1 != p2) ? p1 : p2; }
Evaluate Ifne2 with the 2 parameters x,y such that If (x != y) then x else y.
public final GVector subSelf(GVector vector){ if (length != vector.length) { throw new MatrixSizeException(); } for (int i=0; i < length; i++) { this.values[i]-=vector.values[i]; } return this; }
Sets the value of this vector to the vector difference of itself and vector (this = this - vector).
public void add(Collection geometries){ for (Iterator i=geometries.iterator(); i.hasNext(); ) { Geometry geometry=(Geometry)i.next(); add(geometry); } }
Adds a collection of Geometries to be processed. May be called multiple times. Any dimension of Geometry may be added; the constituent linework will be extracted.
public boolean hasOpenTradePosition(){ if (null == getOpenTradePosition()) { return false; } return true; }
Method hasOpenTradePosition.
@Override public synchronized void removeConfigurationListener(ConfigurationListener cl){ }
We don't have to keep track of configuration listeners (see the documentation for ConfigurationListener/ConfigurationEvent).
protected void showPopup(Iterator<String> iter){ getPopupComponent(); boolean different=false; Vector<String> v=new Vector<String>(); ListModel<String> model=entryList.getModel(); for (int i=0; iter.hasNext(); i++) { String next=iter.next(); v.add(next); if (!different && i < model.getSize()) different|=!next.equals(model.getElementAt(i)); } different|=model.getSize() != v.size(); if (different) { entryList.setListData(v); entryList.clearSelection(); } entryList.setCurrentText(getText()); showPopup(); }
Fills the popup with text & shows it.
public boolean isHighlightable(OMGraphic omg){ return false; }
Don't need DTEDFrames highlighting themselves.
@ObjectiveCName("registerApplePushWithApnsId:withToken:") public void registerApplePush(int apnsId,String token){ modules.getPushesModule().registerApplePush(apnsId,token); }
Register apple push
public StructImpl(StructTypeImpl type,Object[] values){ if (type == null) { throw new IllegalArgumentException(LocalizedStrings.StructImpl_TYPE_MUST_NOT_BE_NULL.toLocalizedString()); } this.type=type; this.values=values; if (this.values != null) { for ( Object o : values) { if (o instanceof PdxInstance || o instanceof PdxString) { this.hasPdx=true; break; } } } }
Creates a new instance of StructImpl
public GOCDataBuilder withSeverity(final int smSeverityc){ this.smSeverityc=smSeverityc; return this; }
Specifies the severity.
@Override public Experiment read(File file){ Experiment result; FileReader freader; BufferedReader breader; String line; result=null; freader=null; breader=null; try { freader=new FileReader(file); breader=new BufferedReader(freader); line=breader.readLine(); result=OptionUtils.fromCommandLine(Experiment.class,line); } catch ( Exception e) { result=null; handleException("Failed to read experiment from: " + file,e); } finally { FileUtils.closeQuietly(breader); FileUtils.closeQuietly(freader); } return result; }
Reads an experiment from disk.
int encryptFinal(byte[] plain,int plainOffset,int plainLen,byte[] cipher,int cipherOffset){ int oddBytes=plainLen % numBytes; int len=encrypt(plain,plainOffset,(plainLen - oddBytes),cipher,cipherOffset); plainOffset+=len; cipherOffset+=len; if (oddBytes != 0) { embeddedCipher.encryptBlock(register,0,k,0); for (int i=0; i < oddBytes; i++) { cipher[i + cipherOffset]=(byte)(k[i] ^ plain[i + plainOffset]); } } return plainLen; }
Performs the last encryption operation. <p>The input plain text <code>plain</code>, starting at <code>plainOffset</code> and ending at <code>(plainOffset + plainLen - 1)</code>, is encrypted. The result is stored in <code>cipher</code>, starting at <code>cipherOffset</code>.
public static <T>T deserializeFile(String path,Class<T> clazz){ try { JAXBContext context=JAXBContext.newInstance(clazz); Unmarshaller m=context.createUnmarshaller(); Object o=m.unmarshal(new FileInputStream(path)); return clazz.cast(o); } catch ( JAXBException e) { e.printStackTrace(); } catch ( FileNotFoundException e) { e.printStackTrace(); } return null; }
Reads a file and deserializes it to an object of given class.
private void addHyperlinkToken(int start,int end,int tokenType){ int so=start + offsetShift; addToken(zzBuffer,start,end,tokenType,so,true); }
Adds the token specified to the current linked list of tokens.
public boolean hasRemaining(){ boolean rem=_buf.hasRemaining(); return rem; }
Returns true if this buffer has remaining bytes, false otherwise.
public static boolean exists(String path){ File f=new File(path); return f.exists(); }
Checks if the path given exists. No distinction is made between a file or directory
public boolean isEmpty(){ return count == 0; }
<p> Tests if this hashtable maps no keys to values. </p>
private void closeRepository(String name,RepositoryHolder holder) throws IOException { logger.debug("closing repository [{}][{}]",holder.type,name); if (holder.repository != null) { holder.repository.close(); } }
Closes the repository
public StrBuilder deleteAll(final StrMatcher matcher){ return replace(matcher,null,0,size,-1); }
Deletes all parts of the builder that the matcher matches. <p> Matchers can be used to perform advanced deletion behaviour. For example you could write a matcher to delete all occurrences where the character 'a' is followed by a number.
public static boolean[] copyOfRange(boolean[] original,int start,int end){ if (start <= end) { if (original.length >= start && 0 <= start) { int length=end - start; int copyLength=Math.min(length,original.length - start); boolean[] copy=new boolean[length]; System.arraycopy(original,start,copy,0,copyLength); return copy; } throw new ArrayIndexOutOfBoundsException(); } throw new IllegalArgumentException(); }
Copies elements in original array to a new array, from index start(inclusive) to end(exclusive). The first element (if any) in the new array is original[from], and other elements in the new array are in the original order. The padding value whose index is bigger than or equal to original.length - start is false.
@Pure public final int hashCode(){ return super.hashCode(); }
Returns a hash code for this enum constant.
private boolean checkPlayServices(){ int resultCode=GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if (resultCode != ConnectionResult.SUCCESS) { if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) { GooglePlayServicesUtil.getErrorDialog(resultCode,this,PLAY_SERVICES_RESOLUTION_REQUEST).show(); } else { Log.i("LOG","This device is not supported."); finish(); } return false; } return true; }
Check the device to make sure it has the Google Play Services APK. If it doesn't, display a dialog that allows users to download the APK from the Google Play Store or enable it in the device's system settings.
public BooleanPropertyAttributeType createBooleanPropertyAttributeTypeFromString(EDataType eDataType,String initialValue){ BooleanPropertyAttributeType result=BooleanPropertyAttributeType.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 -->
protected GraphicsNode instantiateGraphicsNode(){ return null; }
Creates the GraphicsNode depending on the GraphicsNodeBridge implementation.
protected void uploadTestDataFilesToS3(String s3KeyPrefix,List<ManifestFile> manifestFiles) throws Exception { uploadTestDataFilesToS3(s3KeyPrefix,manifestFiles,new ArrayList<String>()); }
Creates locally and uploads to S3 the specified list of test data files.
static public String name(){ String releaseName; if (official) { String addOn; if ("unknown".equals(revisionId)) { addOn=buildDate; } else { addOn="R" + revisionId; } releaseName=major + "." + minor+ getModifier()+ "-"+ addOn; } else { String addOn; if ("unknown".equals(revisionId)) { addOn=buildDate + "-" + buildUser; } else { addOn=buildDate + "-" + buildUser+ "-R"+ revisionId; } releaseName=major + "." + minor+ getModifier()+ "-"+ addOn; } return releaseName; }
Provide the current version string. <P> This string is built using various known build parameters, including the versionBundle.{major,minor,build} values, the Git revision ID (if known) and the official property
@DSComment("OS Bundle data structure") @DSSafe(DSCat.DATA_STRUCTURE) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:33:36.474 -0500",hash_original_method="E7336EB9055C9F862A0B8D336BB5AE0F",hash_generated_method="9B77596588C53FA62A7F6A9D3F01E4F8") public void putString(String key,String value){ unparcel(); mMap.put(key,value); }
Inserts a String value into the mapping of this Bundle, replacing any existing value for the given key. Either key or value may be null.
@Deprecated public void compact(int[] map,int numValuesAllocated){ if (true) { throw new UnsupportedOperationException(); } ArrayList<ValueNumber> oldList=this.allocatedValueList; ArrayList<ValueNumber> newList=new ArrayList<ValueNumber>(Collections.<ValueNumber>nCopies(numValuesAllocated,null)); for ( ValueNumber value : oldList) { int newNumber=map[value.getNumber()]; if (newNumber >= 0) { newList.set(newNumber,value); } } this.allocatedValueList=newList; }
Compact the value numbers produced by this factory.