code
stringlengths
10
174k
nl
stringlengths
3
129k
public boolean isModified(){ return modified; }
This returns if the json object has been modified
private static List<Result> queryContacts(ContentResolver resolver,String input,HashSet<String> addressesRetVal){ String where=null; String[] whereArgs=null; if (!TextUtils.isEmpty(input)) { where=CONTACTS_WHERE; String param1=input + "%"; String param2="% " + input + "%"; whereArgs=new String[]{param1,param2,param1,param2}; } Cursor c=resolver.query(CommonDataKinds.StructuredPostal.CONTENT_URI,CONTACTS_PROJECTION,where,whereArgs,Contacts.DISPLAY_NAME + " ASC"); try { Map<String,List<Result>> nameToAddresses=new HashMap<String,List<Result>>(); c.moveToPosition(-1); while (c.moveToNext()) { String name=c.getString(CONTACTS_INDEX_DISPLAY_NAME); String address=c.getString(CONTACTS_INDEX_ADDRESS); if (name != null) { List<Result> addressesForName=nameToAddresses.get(name); Result result; if (addressesForName == null) { Uri contactPhotoUri=null; if (c.getLong(CONTACTS_INDEX_PHOTO_ID) > 0) { contactPhotoUri=ContentUris.withAppendedId(Contacts.CONTENT_URI,c.getLong(CONTACTS_INDEX_CONTACT_ID)); } addressesForName=new ArrayList<Result>(); nameToAddresses.put(name,addressesForName); result=new Result(name,address,R.drawable.ic_contact_picture,contactPhotoUri); } else { result=new Result(null,address,null,null); } addressesForName.add(result); addressesRetVal.add(address); } } List<Result> allResults=new ArrayList<Result>(); for ( List<Result> result : nameToAddresses.values()) { allResults.addAll(result); } return allResults; } finally { if (c != null) { c.close(); } } }
Matches the input string against contacts names and addresses.
public static <K,V>ObjectObjectHashMap<K,V> newMap(int expectedElements){ return new ObjectObjectHashMap<>(expectedElements); }
Returns a new map with the given number of expected elements.
public VisorTaskArgument(Collection<UUID> nodes,boolean debug){ this(nodes,null,debug); }
Create Visor task argument with nodes, but without actual argument.
public void addBitmapToCache(String data,BitmapDrawable value){ if (data == null || value == null) { return; } if (mMemoryCache != null) { if (RecyclingBitmapDrawable.class.isInstance(value)) { ((RecyclingBitmapDrawable)value).setIsCached(true); } mMemoryCache.put(data,value); } }
Adds a bitmap to both memory and disk cache.
public void duration(long duration){ min=Math.min(min,duration); max=Math.max(max,duration); sum+=duration; cnt++; }
Adds this value to statistics.
public Decimal subtract(Decimal decimal){ assertDefined(); if (null == m_value) { return (decimal); } BigDecimal value=m_value.subtract(decimal.getBigDecimalValue()); return new Decimal(value,SCALE); }
Subtracts two decimal objects
public Population(){ super(); data=new ArrayList<Solution>(); }
Constructs an empty population.
public void clear() throws SchedulerException { sched.clear(); }
<p> Calls the equivalent method on the 'proxied' <code>QuartzScheduler</code>. </p>
private Set intersectIP(Set permitted,Set ips){ Set intersect=new HashSet(); for (Iterator it=ips.iterator(); it.hasNext(); ) { byte[] ip=ASN1OctetString.getInstance(((GeneralSubtree)it.next()).getBase().getName()).getOctets(); if (permitted == null) { if (ip != null) { intersect.add(ip); } } else { Iterator it2=permitted.iterator(); while (it2.hasNext()) { byte[] _permitted=(byte[])it2.next(); intersect.addAll(intersectIPRange(_permitted,ip)); } } } return intersect; }
Returns the intersection of the permitted IP ranges in <code>permitted</code> with <code>ip</code>.
public int addBlocks(int resId){ InputStream blockIs=mResources.openRawResource(resId); try { return loadBlocks(blockIs); } catch ( IOException e) { throw new IllegalStateException("Failed to load block defintions from resource: " + mResources.getResourceEntryName(resId)); } }
Loads and adds block templates from a resource.
public Element(Locator locator,String uri,String localName,String qName,Attributes atts,boolean retainAttributes,List<PrefixMapping> prefixMappings){ super(locator); this.uri=uri; this.localName=localName; this.qName=qName; if (retainAttributes) { this.attributes=atts; } else { this.attributes=new AttributesImpl(atts); } this.prefixMappings=prefixMappings; }
The contructor.
public Mono<T> mono(){ return Mono.from(flux()); }
Create a pushable Mono
public static Resource parseResource(String nTriplesResource,ValueFactory valueFactory) throws IllegalArgumentException { if (nTriplesResource.startsWith("<")) { return parseURI(nTriplesResource,valueFactory); } else if (nTriplesResource.startsWith("_:")) { return parseBNode(nTriplesResource,valueFactory); } else { throw new IllegalArgumentException("Not a legal N-Triples resource: " + nTriplesResource); } }
Parses an N-Triples resource, creates an object for it using the supplied ValueFactory and returns this object.
public void reset(ActionMapping mapping,HttpServletRequest request){ op=""; distPrefId=""; distType=Preference.BLANK_PREF_VALUE; prefLevel=Preference.BLANK_PREF_VALUE; subjectArea=DynamicList.getInstance(new ArrayList(),factory); courseNbr=DynamicList.getInstance(new ArrayList(),factory); exam=DynamicList.getInstance(new ArrayList(),factory); filterSubjectAreaId=null; filterCourseNbr=null; filterSubjectAreas=new ArrayList(); iExamType=null; }
Method reset
@Deprecated public static char[] encode(final String unescapedComponent,final BitSet allowed,final String charset) throws URIException { return URI.encode(unescapedComponent,allowed,charset); }
Escape and encode a given string with allowed characters not to be escaped.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 13:00:51.416 -0500",hash_original_method="E1FBF626549ACB1158CD9E14F440ADC4",hash_generated_method="0E00904E93A6F196E058B95B3DFA9B3A") public static void validate(int[] oid){ if (oid == null) { throw new IllegalArgumentException("oid == null"); } if (oid.length < 2) { throw new IllegalArgumentException("OID MUST have at least 2 subidentifiers"); } if (oid[0] > 2) { throw new IllegalArgumentException("Valid values for first subidentifier are 0, 1 and 2"); } else if (oid[0] != 2 && oid[1] > 39) { throw new IllegalArgumentException("If the first subidentifier has 0 or 1 value the " + "second subidentifier value MUST be less than 40"); } for ( int anOid : oid) { if (anOid < 0) { throw new IllegalArgumentException("Subidentifier MUST have positive value"); } } }
Validates ObjectIdentifier (OID).
boolean implementsAlg(String serv,String alg,String attribute,String val){ String servAlg=serv + "." + alg; String prop=getPropertyIgnoreCase(servAlg); if (prop == null) { alg=getPropertyIgnoreCase("Alg.Alias." + servAlg); if (alg != null) { servAlg=serv + "." + alg; prop=getPropertyIgnoreCase(servAlg); } } if (prop != null) { if (attribute == null) { return true; } return checkAttribute(servAlg,attribute,val); } return false; }
Returns true if this provider implements the given algorithm. Caller must specify the cryptographic service and specify constraints via the attribute name and value.
public void wipeDevice(String code,String data){ String inputPin; String savedPin=Preference.getString(context,resources.getString(R.string.shared_pref_pin)); try { JSONObject wipeKey=new JSONObject(data); inputPin=(String)wipeKey.get(resources.getString(R.string.shared_pref_pin)); String status; if (inputPin.trim().equals(savedPin.trim())) { status=resources.getString(R.string.shared_pref_default_status); } else { status=resources.getString(R.string.shared_pref_false_status); } resultBuilder.build(code,status); if (inputPin.trim().equals(savedPin.trim())) { Toast.makeText(context,resources.getString(R.string.toast_message_wipe),Toast.LENGTH_LONG).show(); try { Thread.sleep(PRE_WIPE_WAIT_TIME); } catch ( InterruptedException e) { Log.e(TAG,"Wipe pause interrupted :" + e.toString()); } devicePolicyManager.wipeData(ACTIVATION_REQUEST); } else { Toast.makeText(context,resources.getString(R.string.toast_message_wipe_failed),Toast.LENGTH_LONG).show(); } } catch ( JSONException e) { Log.e(TAG,"Invalid JSON format." + e); } }
Wipe the device.
public double coefficientOfVariance(){ return Math.sqrt(variance()) / mean(); }
Returns the coefficient of variance.
int parseYear(String source,String token,int ofs) throws ParseException { int year=parseNumber(source,ofs,"year",-1,-1); int len=source.length(); int tokenLen=token.length(); int thisYear=Calendar.getInstance().get(Calendar.YEAR); if ((len == 2) && (tokenLen < 3)) { int c=(thisYear / 100) * 100; year+=c; if (year > (thisYear + 20)) { year-=100; } } validateNumber(year,ofs,"year",1000,thisYear + 1000); return year; }
Parse a year value. If the year is a two digit value, if the value is within 20 years ahead of the current year, current century will be used (ie. if current year is 2013, a value of "33" will return 2033), otherwise previous century is used (ie. with current year of 2012, a value of 97 will return "1997"). See Java 6 documentation for more details of this algorithm.
public boolean isWildcardExport(){ return wildcardExport; }
<!-- begin-user-doc --> <!-- end-user-doc -->
public final void testGetItemId(){ CharSequence[] entries=new CharSequence[]{"entry1","entry2"}; ProxySpinnerAdapter proxySpinnerAdapter=createAdapter(entries); assertEquals(proxySpinnerAdapter.getAdapter().hasStableIds(),proxySpinnerAdapter.hasStableIds()); assertEquals(-1,proxySpinnerAdapter.getItemId(0)); assertEquals(0,proxySpinnerAdapter.getItemId(1)); assertEquals(1,proxySpinnerAdapter.getItemId(2)); }
Tests the functionality of the getItemId-method.
public static byte[] patternToHash(List<LockPatternView.Cell> pattern){ if (pattern == null) { return null; } else { int size=pattern.size(); byte[] res=new byte[size]; for (int i=0; i < size; i++) { LockPatternView.Cell cell=pattern.get(i); res[i]=(byte)cell.getIndex(); } MessageDigest md=null; try { md=MessageDigest.getInstance("SHA-1"); return md.digest(res); } catch ( NoSuchAlgorithmException e) { e.printStackTrace(); return res; } } }
Generate an SHA-1 hash for the pattern. Not the most secure, but it is at least a second level of protection. First level is that the file is in a location only readable by the system process.
private static SecretKeySpec generateKey(final String password) throws NoSuchAlgorithmException, UnsupportedEncodingException { final MessageDigest digest=MessageDigest.getInstance(HASH_ALGORITHM); byte[] bytes=password.getBytes("UTF-8"); digest.update(bytes,0,bytes.length); byte[] key=digest.digest(); SecretKeySpec secretKeySpec=new SecretKeySpec(key,"AES"); return secretKeySpec; }
Generates SHA256 hash of the password which is used as key
protected void invoke(String path) throws TomcatManagerException, IOException { invoke(path,null,null); }
Invokes Tomcat manager with the specified command.
private void analize(){ StringTokenizer tokenizer=new StringTokenizer(sourceData,","); String nextToken=null; style=Integer.parseInt(tokenizer.nextToken()); iconSrc=Integer.parseInt(tokenizer.nextToken()); iconId=Integer.parseInt(tokenizer.nextToken()); nextToken=tokenizer.nextToken(); tooltip=nextToken.substring(1,nextToken.length() - 1); actionType=Integer.parseInt(tokenizer.nextToken()); actionId=Integer.parseInt(tokenizer.nextToken()); }
Private methods
public static DistributionConfigImpl produce(Properties props){ if (props != null) { Object o=props.get(DS_CONFIG_NAME); if (o instanceof DistributionConfigImpl) { return (DistributionConfigImpl)o; } } return new DistributionConfigImpl(props,false,false); }
Produce a DistributionConfigImpl for the given properties and return it.
synchronized void useMultiplexer(ConnectionMultiplexer newMultiplexer){ multiplexer=newMultiplexer; usingMultiplexer=true; }
Use given connection multiplexer object to obtain new connections through this channel.
public JSearchPanel createSearchPanel(boolean monitorKeystrokes){ JSearchPanel jsp=new JSearchPanel(m_set,m_field,monitorKeystrokes); if (m_lock != null) { jsp.setLock(m_lock); } return jsp; }
Create a new search text panel for searching over the data.
@NotNull public String readCurrentBranch(){ return branchExist() ? DvcsUtil.tryLoadFileOrReturn(myCurrentBranch,HgRepository.DEFAULT_BRANCH) : HgRepository.DEFAULT_BRANCH; }
Return current branch
public static void uiImpl(){ UIManager.put("ToolBar.isPaintPlainBackground",Boolean.FALSE); UIManager.put("ToolBar.shadow",new ColorUIResource(new Color(180,183,187))); UIManager.put("ToolBar.highlight",new ColorUIResource(Color.white)); UIManager.put("ToolBar.dockingBackground",new ColorUIResource(BeautyEyeLNFHelper.commonBackgroundColor)); UIManager.put("ToolBar.floatingBackground",new ColorUIResource(BeautyEyeLNFHelper.commonBackgroundColor)); UIManager.put("ToolBar.background",new ColorUIResource(BeautyEyeLNFHelper.commonBackgroundColor)); UIManager.put("ToolBar.foreground",new ColorUIResource(BeautyEyeLNFHelper.commonForegroundColor)); UIManager.put("ToolBar.border",new BorderUIResource(new org.jb2011.lnf.beautyeye.ch8_toolbar.BEToolBarUI.ToolBarBorder(UIManager.getColor("ToolBar.shadow"),UIManager.getColor("ToolBar.highlight"),new Insets(6,0,11,0)))); UIManager.put("ToolBarSeparatorUI",org.jb2011.lnf.beautyeye.ch8_toolbar.BEToolBarSeparatorUI.class.getName()); UIManager.put("ToolBarUI",org.jb2011.lnf.beautyeye.ch8_toolbar.BEToolBarUI.class.getName()); }
Ui impl.
public void fireScrollEvent(int scrollX,int scrollY,int oldscrollX,int oldscrollY){ if (listeners == null || listeners.size() == 0) { return; } boolean isEdt=Display.getInstance().isEdt(); if (isEdt && listeners.size() == 1) { ScrollListener a=(ScrollListener)listeners.get(0); a.scrollChanged(scrollX,scrollY,oldscrollX,oldscrollY); return; } ScrollListener[] array; synchronized (this) { array=new ScrollListener[listeners.size()]; int alen=array.length; for (int iter=0; iter < alen; iter++) { array[iter]=(ScrollListener)listeners.get(iter); } } if (isEdt) { fireScrollSync(array,scrollX,scrollY,oldscrollX,oldscrollY); } else { scrollListenerArray=true; Runnable cl=new CallbackClass(array,new int[]{scrollX,scrollY,oldscrollX,oldscrollY}); if (blocking) { Display.getInstance().callSeriallyAndWait(cl); } else { Display.getInstance().callSerially(cl); } } }
Fires the event safely on the EDT without risk of concurrency errors
private void savePreset(Preset preset){ String key="presets." + preset.pref + "."; preset.jar=jdbcDrvJarTf.getText(); setStringProp(key + "jar",preset.jar); preset.drv=jdbcDrvClsTf.getText(); setStringProp(key + "drv",preset.drv); preset.url=jdbcUrlTf.getText(); setStringProp(key + "url",preset.url); preset.user=userTf.getText(); setStringProp(key + "user",preset.user); savePreferences(); }
Save preset.
protected OMGraphic createOMGraphicFromBufferedImage(BufferedImage bi,int x,int y,int zoomLevel,Projection proj) throws InterruptedException { OMGraphic raster=null; if (bi != null) { BufferedImage rasterImage=preprocessImage(bi,bi.getWidth(),bi.getHeight()); if (proj instanceof Mercator) { raster=getTileMatchingProjectionType(rasterImage,x,y,zoomLevel); } else { raster=getTileNotMatchingProjectionType(rasterImage,x,y,zoomLevel); } if (mapTileLogger.isLoggable(Level.FINE)) { raster.putAttribute(OMGraphic.LABEL,new OMTextLabeler("Tile: " + zoomLevel + "|"+ x+ "|"+ y,OMText.JUSTIFY_CENTER)); raster.setSelected(true); } } return raster; }
Creates an OMRaster appropriate for projection and other parameters from a buffered image.
public Builder enableLog(final boolean logEnable){ this.logEnable=logEnable; return this; }
Set the Context used to instantiate the EasyGcm
protected void onEntranceTransitionStart(){ }
Callback when entrance transition is started.
public void clear(){ oredCriteria.clear(); orderByClause=null; distinct=false; }
This method was generated by MyBatis Generator. This method corresponds to the database table address
private void groupPlayerStandingCSV(){ for ( PlayerQB p : teamQBs) { if (p.year == 0) teamRSs.add(p); else if (p.year == 1) teamFRs.add(p); else if (p.year == 2) teamSOs.add(p); else if (p.year == 3) teamJRs.add(p); else if (p.year == 4) teamSRs.add(p); } for ( PlayerRB p : teamRBs) { if (p.year == 0) teamRSs.add(p); else if (p.year == 1) teamFRs.add(p); else if (p.year == 2) teamSOs.add(p); else if (p.year == 3) teamJRs.add(p); else if (p.year == 4) teamSRs.add(p); } for ( PlayerWR p : teamWRs) { if (p.year == 0) teamRSs.add(p); else if (p.year == 1) teamFRs.add(p); else if (p.year == 2) teamSOs.add(p); else if (p.year == 3) teamJRs.add(p); else if (p.year == 4) teamSRs.add(p); } for ( PlayerK p : teamKs) { if (p.year == 0) teamRSs.add(p); else if (p.year == 1) teamFRs.add(p); else if (p.year == 2) teamSOs.add(p); else if (p.year == 3) teamJRs.add(p); else if (p.year == 4) teamSRs.add(p); } for ( PlayerOL p : teamOLs) { if (p.year == 0) teamRSs.add(p); else if (p.year == 1) teamFRs.add(p); else if (p.year == 2) teamSOs.add(p); else if (p.year == 3) teamJRs.add(p); else if (p.year == 4) teamSRs.add(p); } for ( PlayerS p : teamSs) { if (p.year == 0) teamRSs.add(p); else if (p.year == 1) teamFRs.add(p); else if (p.year == 2) teamSOs.add(p); else if (p.year == 3) teamJRs.add(p); else if (p.year == 4) teamSRs.add(p); } for ( PlayerCB p : teamCBs) { if (p.year == 0) teamRSs.add(p); else if (p.year == 1) teamFRs.add(p); else if (p.year == 2) teamSOs.add(p); else if (p.year == 3) teamJRs.add(p); else if (p.year == 4) teamSRs.add(p); } for ( PlayerF7 p : teamF7s) { if (p.year == 0) teamRSs.add(p); else if (p.year == 1) teamFRs.add(p); else if (p.year == 2) teamSOs.add(p); else if (p.year == 3) teamJRs.add(p); else if (p.year == 4) teamSRs.add(p); } }
For news stories or other info gathering, setup player groups by student standing Run through each type of player, add them to the appropriate year
public boolean isWasAdmin(){ return wasAdmin; }
Gets the wasAdmin value for this Usuario.
@Override public final boolean onCreateOptionsMenu(final Menu menu){ final MenuInflater inflater=getMenuInflater(); inflater.inflate(R.menu.control_menu,menu); return true; }
Create context menu with start and stop buttons for "tracking" mode.
protected void sequence_VariableRef(ISerializationContext context,VariableRef semanticObject){ if (errorAcceptor != null) { if (transientValues.isValueTransient(semanticObject,GamlPackage.Literals.VARIABLE_REF__REF) == ValueTransient.YES) errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject,GamlPackage.Literals.VARIABLE_REF__REF)); } SequenceFeeder feeder=createSequencerFeeder(context,semanticObject); feeder.accept(grammarAccess.getVariableRefAccess().getRefVarDefinitionValid_IDParserRuleCall_1_0_1(),semanticObject.getRef()); feeder.finish(); }
Contexts: Expression returns VariableRef Pair returns VariableRef Pair.Pair_1_0_0 returns VariableRef If returns VariableRef If.If_1_0 returns VariableRef Or returns VariableRef Or.Expression_1_0 returns VariableRef And returns VariableRef And.Expression_1_0 returns VariableRef Cast returns VariableRef Cast.Cast_1_0_0 returns VariableRef Comparison returns VariableRef Comparison.Expression_1_0_0 returns VariableRef Addition returns VariableRef Addition.Expression_1_0_0 returns VariableRef Multiplication returns VariableRef Multiplication.Expression_1_0_0 returns VariableRef Exponentiation returns VariableRef Exponentiation.Expression_1_0_0 returns VariableRef Binary returns VariableRef Binary.Binary_1_0_0 returns VariableRef Unit returns VariableRef Unit.Unit_1_0_0 returns VariableRef Unary returns VariableRef Access returns VariableRef Access.Access_1_0 returns VariableRef Primary returns VariableRef AbstractRef returns VariableRef VariableRef returns VariableRef Constraint: ref=[VarDefinition|Valid_ID]
void initFromCameraParameters(Camera camera){ Camera.Parameters parameters=camera.getParameters(); previewFormat=parameters.getPreviewFormat(); previewFormatString=parameters.get("preview-format"); Log.d(TAG,"Default preview format: " + previewFormat + '/'+ previewFormatString); WindowManager manager=(WindowManager)context.getSystemService(Context.WINDOW_SERVICE); Display display=manager.getDefaultDisplay(); screenResolution=new Point(display.getWidth(),display.getHeight()); Log.d(TAG,"Screen resolution: " + screenResolution); Point screenResolutionForCamera=new Point(); screenResolutionForCamera.x=screenResolution.x; screenResolutionForCamera.y=screenResolution.y; if (screenResolution.x < screenResolution.y) { screenResolutionForCamera.x=screenResolution.y; screenResolutionForCamera.y=screenResolution.x; } cameraResolution=getCameraResolution(parameters,screenResolutionForCamera); Log.d(TAG,"Camera resolution: " + screenResolution); }
Reads, one time, values from the camera that are needed by the app.
static void testValidity(Object o) throws JSONException { if (o != null) { if (o instanceof Double) { if (((Double)o).isInfinite() || ((Double)o).isNaN()) { throw new JSONException("JSON does not allow non-finite numbers."); } } else if (o instanceof Float) { if (((Float)o).isInfinite() || ((Float)o).isNaN()) { throw new JSONException("JSON does not allow non-finite numbers."); } } } }
Throw an exception if the object is an NaN or infinite number.
private void animateProperty(int constantName,float toValue){ float fromValue=getValue(constantName); float deltaValue=toValue - fromValue; animatePropertyBy(constantName,fromValue,deltaValue); }
Utility function, called by the various x(), y(), etc. methods. This stores the constant name for the property along with the from/delta values that will be used to calculate and set the property during the animation. This structure is added to the pending animations, awaiting the eventual start() of the underlying animator. A Runnable is posted to start the animation, and any pending such Runnable is canceled (which enables us to end up starting just one animator for all of the properties specified at one time).
public static boolean validateThreads(final CFlags flags){ if (flags.isSet(THREADS_FLAG)) { final int threads=(Integer)flags.getValue(THREADS_FLAG); if (threads <= 0) { Diagnostic.error(ErrorType.INVALID_MIN_INTEGER_FLAG_VALUE,"--" + THREADS_FLAG,threads + "","1"); return false; } final int maxThreads=Environment.getAvailableProcessors() * 10; if (threads > maxThreads) { Diagnostic.error(ErrorType.INVALID_MAX_INTEGER_FLAG_VALUE,"--" + THREADS_FLAG,threads + "",maxThreads + ""); return false; } } return true; }
Validate the threads flags.
public final CC gapTop(String boundsSize){ ver.setGapBefore(ConstraintParser.parseBoundSize(boundsSize,true,false)); return this; }
Sets the gap above the component.
private void updateProgress(String progressLabel,int progress){ if (myHost != null && ((progress != previousProgress) || (!progressLabel.equals(previousProgressLabel)))) { myHost.updateProgress(progressLabel,progress); } previousProgress=progress; previousProgressLabel=progressLabel; }
Used to communicate a progress update between a plugin tool and the main Whitebox user interface.
public ZDT3(int numberOfVariables){ super(numberOfVariables); }
Constructs a ZDT3 test problem with the specified number of decision variables.
public boolean pageScroll(int direction){ int width=getWidth(); int height=getHeight(); if (direction == View.FOCUS_UP) { mTempRect.top=getScrollY() - height; if (mTempRect.top < 0) { mTempRect.top=0; } mTempRect.bottom=mTempRect.top + height; return scrollAndFocusVertically(direction,mTempRect.top,mTempRect.bottom); } else if (direction == View.FOCUS_DOWN) { mTempRect.top=getScrollY() + height; int count=getChildCount(); if (count > 0) { View view=getChildAt(count - 1); if (mTempRect.top + height > view.getBottom()) { mTempRect.top=view.getBottom() - height; } } mTempRect.bottom=mTempRect.top + height; return scrollAndFocusVertically(direction,mTempRect.top,mTempRect.bottom); } else if (direction == View.FOCUS_LEFT) { mTempRect.left=getScrollX() - width; if (mTempRect.left < 0) { mTempRect.left=0; } mTempRect.right=mTempRect.left + width; return scrollAndFocusHorizontally(direction,mTempRect.left,mTempRect.right); } else { mTempRect.left=getScrollX() + width; int count=getChildCount(); if (count > 0) { View view=getChildAt(0); if (mTempRect.left + width > view.getRight()) { mTempRect.left=view.getRight() - width; } } mTempRect.right=mTempRect.left + width; return scrollAndFocusHorizontally(direction,mTempRect.left,mTempRect.right); } }
<p>Handles scrolling in response to a "page up/down" shortcut press. This method will scroll the view by one page left or right and give the focus to the leftmost/rightmost component in the new visible area. If no component is a good candidate for focus, this scrollview reclaims the focus.</p>
public static void i(String msg,Throwable thr){ log(LEVEL.INFO,null,msg,thr); }
Send a INFO log message and log the exception.
protected ReactionPropertyImpl(){ super(); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public static void disableConnectionReuseIfNecessary(){ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) { System.setProperty("http.keepAlive","false"); } }
Workaround for bug pre-Froyo, see here for more info: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
public void addMethodRefs(Map<String,ConfigurationMethodRef> configs){ methodInvocationRef.putAll(configs); }
Adds cache configs for method invocations for from-clause.
public static void applyFilters(List<Integer> filterIds,Script script){ ScriptFilterDao dao=new ScriptFilterDao(); applyFiltersToScript(dao.findForIds(filterIds),script); }
Applys the filters specified by filterIds
private void writeXMLContent(char[] content,int start,int length,boolean escapeChars) throws XMLStreamException { if (!escapeChars) { _writer.write(content,start,length); return; } int startWritePos=start; final int end=start + length; for (int index=start; index < end; index++) { char ch=content[index]; if (!_writer.canEncode(ch)) { _writer.write(content,startWritePos,index - startWritePos); _writer.write(ENCODING_PREFIX); _writer.write(Integer.toHexString(ch)); _writer.write(SEMICOLON); startWritePos=index + 1; continue; } switch (ch) { case OPEN_START_TAG: _writer.write(content,startWritePos,index - startWritePos); _writer.write("&lt;"); startWritePos=index + 1; break; case AMPERSAND: _writer.write(content,startWritePos,index - startWritePos); _writer.write("&amp;"); startWritePos=index + 1; break; case CLOSE_START_TAG: _writer.write(content,startWritePos,index - startWritePos); _writer.write("&gt;"); startWritePos=index + 1; break; } } _writer.write(content,startWritePos,end - startWritePos); }
Writes XML content to underlying writer. Escapes characters unless escaping character feature is turned off.
public Set<String> addIncrementalContent(IndependentDistribution content,boolean followPrevious){ if (!paused) { curState.addToState_incremental(content.toDiscrete(),followPrevious); return update(); } else { log.info("system is paused, ignoring content " + content); return Collections.emptySet(); } }
Adds the incremental content (expressed as a distribution over variables) to the current dialogue state, and subsequently updates it. If followPrevious is set to true, the content is concatenated with the current distribution for the variable.
@Override public Object parseObject(final String source,final ParsePosition pos){ return parser.parseObject(source,pos); }
Uses the parser Format instance.
protected CCProgressTimer(CCTexture2D texture){ super(); sprite_=CCSprite.sprite(texture); percentage_=0.f; vertexDataCount_=0; setAnchorPoint(CGPoint.ccp(.5f,.5f)); setContentSize(sprite_.getContentSize()); type_=kCCProgressTimerTypeRadialCCW; }
Creates a progress timer with the texture as the shape the timer goes through
private static char[] zzUnpackCMap(String packed){ char[] map=new char[0x10000]; int i=0; int j=0; while (i < 184) { int count=packed.charAt(i++); char value=packed.charAt(i++); do map[j++]=value; while (--count > 0); } return map; }
Unpacks the compressed character translation table.
@Override public ScoringFunction createNewScoringFunction(Person person){ final CharyparNagelScoringParameters parameters=params.getScoringParameters(person); SumScoringFunction sumScoringFunction=new SumScoringFunction(); sumScoringFunction.addScoringFunction(new CharyparNagelActivityScoring(parameters)); sumScoringFunction.addScoringFunction(new CharyparNagelLegScoring(parameters,this.network)); sumScoringFunction.addScoringFunction(new CharyparNagelMoneyScoring(parameters)); sumScoringFunction.addScoringFunction(new CharyparNagelAgentStuckScoring(parameters)); return sumScoringFunction; }
In every iteration, the framework creates a new ScoringFunction for each Person. A ScoringFunction is much like an EventHandler: It reacts to scoring-relevant events by accumulating them. After the iteration, it is asked for a score value. Since the factory method gets the Person, it can create a ScoringFunction which depends on Person attributes. This implementation does not. <li>The fact that you have a person-specific scoring function does not mean that the "creative" modules (such as route choice) are person-specific. This is not a bug but a deliberate design concept in order to reduce the consistency burden. Instead, the creative modules should generate a diversity of possible solutions. In order to do a better job, they may (or may not) use person-specific info. kai, apr'11 </ul>
FieldArray(){ this(10); }
Creates a new FieldArray containing no fields.
public Object runSafely(Catbert.FastStack stack) throws Exception { return sage.plugin.CorePluginManager.getInstance().getLatestRepoPlugins(); }
Returns an array of Plugin objects which represent all the plugins available in the plugin repository.
@Override public void visit(NodeVisitor v){ if (v.visit(this)) { for ( AstNode label : labels) { label.visit(v); } statement.visit(v); } }
Visits this node, then each label in the label-list, and finally the statement.
static String build(final String accountId,final String region,final DateTime instanceLaunchTime){ return Paths.get(accountId,region,instanceLaunchTime.toString("YYYY"),instanceLaunchTime.toString("MM"),instanceLaunchTime.toString("dd")).toString() + "/"; }
Builds the prefix that will be prepended to the 'bucketname'<br/> Something like '123456789/eu-west-1/2015/06/12/'
public GVTGlyphVector createGlyphVector(FontRenderContext frc,char[] chars){ StringCharacterIterator sci=new StringCharacterIterator(new String(chars)); GlyphVector gv=awtFont.createGlyphVector(frc,chars); return new AWTGVTGlyphVector(gv,this,scale,sci); }
Returns a new GlyphVector object created with the specified array of characters and the specified FontRenderContext.
public Long deleteRoom(Rooms r){ log.debug("deleteRoom"); try { r.setDeleted("true"); r.setUpdatetime(new Date()); if (r.getRooms_id() == null) { em.persist(r); } else { if (!em.contains(r)) { em.merge(r); } } return r.getRooms_id(); } catch ( Exception ex2) { log.error("[deleteRoomsOrganisation] ",ex2); } return null; }
deletes a Room by given Room-Object
public ExternalEvent nextEvent(){ int responseSize=0; int msgSize; int interval; int from; int to; from=drawHostAddress(this.hostRange); to=drawToAddress(hostRange,from); msgSize=drawMessageSize(); interval=drawNextEventTimeDiff(); MessageCreateEvent mce=new MessageCreateEvent(from,to,this.getID(),msgSize,responseSize,this.nextEventsTime); this.nextEventsTime+=interval; if (this.msgTime != null && this.nextEventsTime > this.msgTime[1]) { this.nextEventsTime=Double.MAX_VALUE; } return mce; }
Returns the next message creation event
public void sortByKeys(SortOrder order){ final int size=this.keys.size(); final DefaultKeyedValue[] data=new DefaultKeyedValue[size]; for (int i=0; i < size; i++) { data[i]=new DefaultKeyedValue((Comparable)this.keys.get(i),(Number)this.values.get(i)); } Comparator comparator=new KeyedValueComparator(KeyedValueComparatorType.BY_KEY,order); Arrays.sort(data,comparator); clear(); for (int i=0; i < data.length; i++) { final DefaultKeyedValue value=data[i]; addValue(value.getKey(),value.getValue()); } }
Sorts the items in the list by key.
protected void moveRandomly(float factor){ double hor=Math.random() - .5; double vert=Math.random() - .5; setLat(getLat() + (float)vert / factor); setLon(getLon() + (float)hor / factor); }
A little method that will cause the location to move around a little.
public static String defaultString(Object obj){ return defaultString(obj,""); }
<p> Returns either the passed in <code>Object</code> as a String, or, if the <code>Object</code> is <code>null</code> , an empty String. </p>
public DimensionalNode parent(IMultiPoint value){ if (value == null) { throw new IllegalArgumentException("unable to insert null value into KDTree"); } if (root == null) { return null; } DimensionalNode node=root; DimensionalNode next; while (node != null) { if (node.isBelow(value)) { next=node.getBelow(); if (next == null) { break; } else { node=next; } } else { next=node.getAbove(); if (next == null) { break; } else { node=next; } } } return node; }
Return the parent of the point IF the point were to be inserted into the kd-tree. Returns null only if the tree is empty to begin with (i.e., there are no parents). Note that you will have to inspect the dimension for the DimensionalNode to determine if this is a Below or an Above parent.
protected void makeInputNodes(MethodScope methodScope,LoopScope loopScope,Node node,boolean updateUsages){ Edges edges=node.getNodeClass().getEdges(Edges.Type.Inputs); for (int index=0; index < edges.getDirectCount(); index++) { if (skipEdge(node,edges,index,true,true)) { continue; } int orderId=readOrderId(methodScope); Node value=ensureNodeCreated(methodScope,loopScope,orderId); edges.initializeNode(node,index,value); if (updateUsages && value != null && !value.isDeleted()) { edges.update(node,null,value); } } for (int index=edges.getDirectCount(); index < edges.getCount(); index++) { if (skipEdge(node,edges,index,false,true)) { continue; } int size=methodScope.reader.getSVInt(); if (size != -1) { NodeList<Node> nodeList=new NodeInputList<>(node,size); edges.initializeList(node,index,nodeList); for (int idx=0; idx < size; idx++) { int orderId=readOrderId(methodScope); Node value=ensureNodeCreated(methodScope,loopScope,orderId); nodeList.initialize(idx,value); if (updateUsages && value != null && !value.isDeleted()) { edges.update(node,null,value); } } } } }
Process the input edges of a node. Input nodes that have not yet been created must be non-fixed nodes (because fixed nodes are processed in reverse postorder. Such non-fixed nodes are created on demand (recursively since they can themselves reference not yet created nodes).
synchronized protected void timeout(){ if (progState != NOTPROGRAMMING) { if (log.isDebugEnabled()) { log.debug("timeout!"); } progState=NOTPROGRAMMING; if (tc.getProtocol() == Mx1Packetizer.ASCII) { tc.sendMx1Message(tc.getCommandStation().resetModeMsg(),this); } notifyProgListenerEnd(_val,jmri.ProgListener.FailedTimeout); } }
Internal routine to handle a timeout
public boolean isPlaylistSessionReady(){ return mSessionReady; }
Returns whether or not the playlist session is ready to be played
@Override public boolean isCellEditable(int row,int col){ return false; }
Is the cell at the given row and column position editable?
public JDIPermission(String name){ super(name); if (!name.equals("virtualMachineManager")) { throw new IllegalArgumentException("name: " + name); } }
The <code>JDIPermission</code> class represents access rights to the <code>VirtualMachineManager</code>
public static Angle average(Angle a,Angle b,Angle c){ if (a == null || b == null || c == null) { String message=Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } return Angle.fromDegrees((a.degrees + b.degrees + c.degrees) / 3); }
Obtains the average of three angles. The order of parameters does not matter.
public void runTest() throws Throwable { Document doc; NodeList elementList; Node employeeNode; NodeList childList; Node createdNode; Node lchild; String childName; Node appendedChild; doc=(Document)load("hc_staff",true); elementList=doc.getElementsByTagName("p"); employeeNode=elementList.item(1); childList=employeeNode.getChildNodes(); createdNode=doc.createElement("br"); appendedChild=employeeNode.appendChild(createdNode); lchild=employeeNode.getLastChild(); childName=lchild.getNodeName(); assertEqualsAutoCase("element","nodeName","br",childName); }
Runs the test case.
private void create3WayNetwork(Scenario sc){ Network net=sc.getNetwork(); NetworkFactory fac=net.getFactory(); Node n1, n2, n3, n4; Link l; n1=fac.createNode(Id.create(1,Node.class),new Coord(0.0,0.0)); net.addNode(n1); double x=-10.0; n2=fac.createNode(Id.create(2,Node.class),new Coord(x,10.0)); net.addNode(n2); n3=fac.createNode(Id.create(3,Node.class),new Coord(0.0,10.0)); net.addNode(n3); n4=fac.createNode(Id.create(4,Node.class),new Coord(10.0,8.0)); net.addNode(n4); l=fac.createLink(Id.create(13,Link.class),n1,n3); net.addLink(l); l=fac.createLink(Id.create(31,Link.class),n3,n1); net.addLink(l); l=fac.createLink(Id.create(23,Link.class),n2,n3); net.addLink(l); l=fac.createLink(Id.create(32,Link.class),n3,n2); net.addLink(l); l=fac.createLink(Id.create(34,Link.class),n3,n4); net.addLink(l); l=fac.createLink(Id.create(43,Link.class),n4,n3); net.addLink(l); }
Creates a three waynetwork that looks like: <p> 2----- 3 ------ 4 | | | 1 </p>
public static void assertEqual(byte expected,byte actual,String errorMessage){ if (verbose) { log("assertEqual(" + expected + ", "+ actual+ ", "+ errorMessage+ ")"); } assertBool(expected == actual,errorMessage); }
Asserts that the given bytes are equal
public static double pdf(double x,double m,double shape){ double a=Math.sqrt(shape / (2.0 * Math.PI * x* x* x)); double b=((-shape) * (x - m) * (x - m)) / (2.0 * m * m* x); return a * Math.exp(b); }
probability density function
public TwoColumnOutput(OutputStream out,int leftWidth,int rightWidth,String spacer){ this(new OutputStreamWriter(out),leftWidth,rightWidth,spacer); }
Constructs an instance.
private void recordSlavePartitionsText(){ try { ITypedRegion[] partitions=TextUtilities.computePartitioning(tempDocument,partitioning,0,tempDocument.getLength(),false); savedPartitionText=new String[partitions.length]; for (int i=0; i < savedPartitionText.length; i++) { if (!isSlaveContentType(partitions[i].getType())) { continue; } savedPartitionText[i]=tempDocument.get(partitions[i].getOffset(),partitions[i].getLength()); } } catch ( BadLocationException e) { } }
Records the text of partitions for which we have a slave formatting strategy.
public void testDivideRoundCeilingNeg(){ String a="-92948782094488478231212478987482988429808779810457634781384756794987"; int aScale=-24; String b="7472334223847623782375469293018787918347987234564568"; int bScale=13; String c="-1.24390557635720517122423359799283E+53"; int resScale=-21; BigDecimal aNumber=new BigDecimal(new BigInteger(a),aScale); BigDecimal bNumber=new BigDecimal(new BigInteger(b),bScale); BigDecimal result=aNumber.divide(bNumber,resScale,BigDecimal.ROUND_CEILING); assertEquals("incorrect value",c,result.toString()); assertEquals("incorrect scale",resScale,result.scale()); }
Divide: rounding mode is ROUND_CEILING, result is negative
public static int instanceOf(Object o,Class<?> c){ if (o == null) return FALSE; return c.isAssignableFrom(o.getClass()) ? TRUE : FALSE; }
Replacement function for the Java instanceof instruction, which returns a distance integer
public ServiceExtensionManager(ImsModule imsModule,Context ctx,Core core,RcsSettings rcsSettings){ mCtx=ctx; mCore=core; mRcsSettings=rcsSettings; mSupportedExtensionUpdater=new SupportedExtensionUpdater(mCtx,imsModule,mRcsSettings,this); }
Monitor the application package changes to update RCS supported extensions
public TextureAtlas(int initialWidth,int initialHeight,int maxWidth,int maxHeight){ this(initialWidth,initialHeight,maxWidth,maxHeight,DEFAULT_USE_MIP_MAPS,DEFAULT_USE_ANISOTROPY); }
Constructs a texture atlas with the specified initial and maximum dimensions. All dimensions must be greater than zero, and the maximum dimensions must be greater than or equal to the initial dimensions. The constructed texture atlas generates mip-maps and applies an anisotropic filter to each element.
public void testMergeOneFilterIntoDocumentWithSameFilterAndParam() throws Exception { String srcXml="<web-app>" + " <filter>" + " <filter-name>f1</filter-name>"+ " <filter-class>fclass1</filter-class>"+ " </filter>"+ "</web-app>"; WebXml srcWebXml=WebXmlIo.parseWebXml(new ByteArrayInputStream(srcXml.getBytes("UTF-8")),null); String mergeXml="<web-app>" + " <filter>" + " <filter-name>f1</filter-name>"+ " <filter-class>fclass1</filter-class>"+ " <init-param>"+ " <param-name>f1param1</param-name>"+ " <param-value>f1param1value</param-value>"+ " </init-param>"+ " </filter>"+ "</web-app>"; WebXml mergeWebXml=WebXmlIo.parseWebXml(new ByteArrayInputStream(mergeXml.getBytes("UTF-8")),null); WebXmlMerger merger=new WebXmlMerger(srcWebXml); merger.mergeFilters(mergeWebXml); assertTrue(WebXmlUtils.hasFilter(srcWebXml,"f1")); List<String> initParams=WebXmlUtils.getFilterInitParamNames(srcWebXml,"f1"); assertEquals(1,initParams.size()); assertEquals("f1param1",initParams.get(0)); }
Tests whether a filter initialization parameter is merged into the descriptor only once.
private void generateSerializerRegistration() throws SAXException { final SerializerCreation sc=this.creation.getSerializerCreation(); if (sc == null) { return; } handler.startElement("",TOP_SERIALIZER_REGISTRATION,TOP_SERIALIZER_REGISTRATION,EMPTY); for ( Class c : sc.getSerializerRegistrations()) { handler.startElement("",SERIALIZER_REGISTRATION,SERIALIZER_REGISTRATION,EMPTY); handler.startElement("",CLASS_NAME,CLASS_NAME,EMPTY); handler.characters(c.getName().toCharArray(),0,c.getName().length()); handler.endElement("",CLASS_NAME,CLASS_NAME); handler.endElement("",SERIALIZER_REGISTRATION,SERIALIZER_REGISTRATION); } for ( Map.Entry<Class,Integer> e : sc.getInstantiatorRegistrations().entrySet()) { Class c=e.getKey(); Integer i=e.getValue(); AttributesImpl atts=new AttributesImpl(); atts.addAttribute("","",ID,"",i.toString()); handler.startElement("",INSTANTIATOR_REGISTRATION,INSTANTIATOR_REGISTRATION,atts); handler.startElement("",CLASS_NAME,CLASS_NAME,EMPTY); handler.characters(c.getName().toCharArray(),0,c.getName().length()); handler.endElement("",CLASS_NAME,CLASS_NAME); handler.endElement("",INSTANTIATOR_REGISTRATION,INSTANTIATOR_REGISTRATION); } handler.endElement("",TOP_SERIALIZER_REGISTRATION,TOP_SERIALIZER_REGISTRATION); }
Generates the <code>serializer-registration</code> element.
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 sort(Object[] array){ ComparableTimSort.sort(array); }
Sorts the specified array in ascending natural order.
@action(name="cfp",args={@arg(name=GamaMessageType.MESSAGE_STR,type=IType.MESSAGE,optional=false,doc=@doc("The message to be replied")),@arg(name=GamaMessage.CONTENTS,type=IType.LIST,optional=false,doc=@doc("The content of the replying message"))},doc=@doc("Replies a message with a 'cfp' performative message.")) public Object primCfp(final IScope scope) throws GamaRuntimeException { final IList originals=getMessageArg(scope); if (originals == null || originals.size() == 0) { throw GamaRuntimeException.error("No message to reply",scope); } return replyMessage(scope,originals,CFP,getContentArg(scope)); }
Prim cfp.
public Command show(int top,int bottom,int left,int right,boolean includeTitle,boolean modal){ this.top=top; this.bottom=bottom; if (isRTL()) { this.left=right; this.right=left; } else { this.left=left; this.right=right; } setDisposed(false); this.modal=modal; lastCommandPressed=null; showModal(this.top,this.bottom,this.left,this.right,includeTitle,modal,false); return lastCommandPressed; }
This method shows the form as a modal alert allowing us to produce a behavior of an alert/dialog box. This method will block the calling thread even if the calling thread is the EDT. Notice that this method will not release the block until dispose is called even if show() from another form is called! <p>Modal dialogs Allow the forms "content" to "hang in mid air" this is especially useful for dialogs where you would want the underlying form to "peek" from behind the form.
public static StartupSettings fromJSONFile(File jsonFile) throws JSONException, FileNotFoundException, IOException { StringBuffer buffer=new StringBuffer(); try (BufferedReader br=new BufferedReader(new FileReader(jsonFile))){ String line; while ((line=br.readLine()) != null) { buffer.append(line.trim()); } } JSONObject jsonObject=new JSONArray(buffer.toString()).getJSONObject(0); int port=jsonObject.getInt("port"); String id=jsonObject.getString("id"); int gossipInterval=jsonObject.getInt("gossip_interval"); int cleanupInterval=jsonObject.getInt("cleanup_interval"); String cluster=jsonObject.getString("cluster"); if (cluster == null) { throw new IllegalArgumentException("cluster was null. It is required"); } StartupSettings settings=new StartupSettings(id,port,new GossipSettings(gossipInterval,cleanupInterval),cluster); String configMembersDetails="Config-members ["; JSONArray membersJSON=jsonObject.getJSONArray("members"); for (int i=0; i < membersJSON.length(); i++) { JSONObject memberJSON=membersJSON.getJSONObject(i); RemoteGossipMember member=new RemoteGossipMember(memberJSON.getString("cluster"),memberJSON.getString("host"),memberJSON.getInt("port"),""); settings.addGossipMember(member); configMembersDetails+=member.getAddress(); if (i < (membersJSON.length() - 1)) configMembersDetails+=", "; } log.info(configMembersDetails + "]"); return settings; }
Parse the settings for the gossip service from a JSON file.
public void ensureCapacity(int minCapacity){ elements=cern.colt.Arrays.ensureCapacity(elements,minCapacity); }
Ensures that the receiver can hold at least the specified number of elements without needing to allocate new internal memory. If necessary, allocates new internal memory and increases the capacity of the receiver.
public void skipWhile(String skip) throws IOException { char ch; do { ch=read(); } while (skip.indexOf(ch) > -1); unreadCharacter(ch); }
Skips char any contiguous characters in skip. Will also skip comments.
public DeleteWarmerRequest names(@Nullable String... names){ this.names=names; return this; }
The name (or wildcard expression) of the index warmer to delete, or null to delete all warmers.
public boolean arrayContains(int[] ar,int value){ for (int i=0; i < ar.length; i++) { if (ar[i] == value) { return true; } } return false; }
See if an integer array contains the desired value.
private void skipSynchOrStartServiceOnPeer(Operation peerOp,String link,SynchronizePeersRequest request){ if (request.options.contains(ServiceOption.ON_DEMAND_LOAD)) { peerOp.complete(); return; } Operation checkGet=Operation.createGet(UriUtils.buildUri(peerOp.getUri(),link)).addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NO_FORWARDING).setConnectionSharing(true).setExpiration(Utils.fromNowMicrosUtc(TimeUnit.SECONDS.toMicros(2))).setCompletion(null); sendRequest(checkGet); }
The service state on the peer node is identical to best state. We should skip sending a synchronization POST, if the service is already started