code
stringlengths
10
174k
nl
stringlengths
3
129k
public NTLMException(int errorCode,String msg){ super(msg); this.errorCode=errorCode; }
Constructs an NTLMException object.
public static Trellis orderTrellis(Trellis trel,double I[][],Random rand){ int L=I.length; int Y[]=new int[L]; ArrayList<Integer> list=new ArrayList<Integer>(); for ( int i : trel.indices) { list.add(new Integer(i)); } Y[0]=list.remove(rand.nextInt(L)); for (int j=1; j < L; j++) { double max_w=-1.; int j_=-1; for ( int j_prop : list) { double w=trel.weight(Y,j,j_prop,I); if (w >= max_w) { max_w=w; j_=j_prop; } } list.remove(new Integer(j_)); Y[j]=j_; } trel=new Trellis(Y,trel.WIDTH,trel.TYPE); return trel; }
OrderTrellis - order the trellis according to marginal label dependencies.
@Override public boolean hasName(){ log.log(Level.FINE,"hasName(): {0}",event == START_ELEMENT || event == END_ELEMENT); return event == START_ELEMENT || event == END_ELEMENT; }
returns true if the current event has a name (is a START_ELEMENT or END_ELEMENT) returns false otherwise
public boolean isListenInBackground(){ return listenInBackground; }
Returns whether this state is configured to allow background listening.
private void readObject(){ }
<!-- begin-user-doc --> Write your own initialization here <!-- end-user-doc -->
public static boolean isLongCategory(ClassNode type){ return type == long_TYPE || isIntCategory(type); }
It is of a long category, if the provided type is a long, its wrapper or if it is a long category.
public static byte[] decode(String s,int options) throws java.io.IOException { if (s == null) { throw new NullPointerException("Input string was null."); } byte[] bytes; try { bytes=s.getBytes(PREFERRED_ENCODING); } catch ( java.io.UnsupportedEncodingException uee) { bytes=s.getBytes(); } bytes=decode(bytes,0,bytes.length,options); boolean dontGunzip=(options & DONT_GUNZIP) != 0; if ((bytes != null) && (bytes.length >= 4) && (!dontGunzip)) { int head=((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); if (java.util.zip.GZIPInputStream.GZIP_MAGIC == head) { java.io.ByteArrayInputStream bais=null; java.util.zip.GZIPInputStream gzis=null; java.io.ByteArrayOutputStream baos=null; byte[] buffer=new byte[2048]; int length=0; try { baos=new java.io.ByteArrayOutputStream(); bais=new java.io.ByteArrayInputStream(bytes); gzis=new java.util.zip.GZIPInputStream(bais); while ((length=gzis.read(buffer)) >= 0) { baos.write(buffer,0,length); } bytes=baos.toByteArray(); } catch ( java.io.IOException e) { e.printStackTrace(); } finally { try { baos.close(); } catch ( Exception e) { } try { gzis.close(); } catch ( Exception e) { } try { bais.close(); } catch ( Exception e) { } } } } return bytes; }
Decodes data from Base64 notation, automatically detecting gzip-compressed data and decompressing it.
public CViewsTableRenderer(final IViewsTable table,final IViewContainer container){ this.container=Preconditions.checkNotNull(container,"IE02032: Container argument can't be null"); this.table=Preconditions.checkNotNull(table,"IE02351: table argument can not be null"); if (starImage == null) { try { starImage=new ImageIcon(CMain.class.getResource("data/star.png").toURI().toURL()).getImage(); } catch ( MalformedURLException|URISyntaxException e) { } } CWindowManager.instance().addListener(listener); for ( final CGraphWindow window : CWindowManager.instance().getOpenWindows()) { window.addListener(panelListener); } }
Creates a new renderer object.
public void output(OutputStream out){ m_html.output(out); }
Output Document
protected void sequence_ParameterizedTypeRefNominal_TypeRefWithModifiers_TypeRefWithoutModifiers(ISerializationContext context,ParameterizedTypeRef semanticObject){ genericSequencer.createSequence(context,semanticObject); }
Contexts: BogusTypeRef returns ParameterizedTypeRef TypeRefWithModifiers returns ParameterizedTypeRef Constraint: ( undefModifier=UndefModifierToken | (declaredType=[Type|TypeReferenceName] (typeArgs+=TypeArgument typeArgs+=TypeArgument*)? dynamic?='+'? undefModifier=UndefModifierToken?) )
public static ArchiveAccess createArchiveAccess(){ return new ArchiveAccessImpl(); }
Crea la instancia para obtener el acceso al sistema de archivadores.
public synchronized final int evictionCount(){ return evictionCount; }
Returns the number of values that have been evicted.
public void testAnalyse(){ System.out.println("analyse"); AuditCommandImpl instance=null; }
Test of analyse method, of class AuditCommandImpl.
public void put(final String key,final int value){ pageLookup.put(key,value); }
The pageLookup to set.
public static long estimateMemory(long nrows,long ncols,double sparsity){ double cnnz=Math.max(SparseRow.initialCapacity,Math.ceil(sparsity * ncols)); double rlen=Math.min(nrows,Math.ceil(sparsity * nrows * ncols)); double size=16; size+=rlen * (116 + cnnz * 12); size+=32 + nrows * 8d; return (long)Math.min(size,Long.MAX_VALUE); }
Get the estimated in-memory size of the sparse block in MCSR with the given dimensions w/o accounting for overallocation.
static boolean isWhiteSpace(char ch){ return ((ch == ' ') || (ch == '\n') || (ch == '\t')|| (ch == 10)|| (ch == 13)); }
Checks if the specified character is a white space or not. Exposed to packaage since used by HTMLComponent as well
protected double measureHermitianOverlap(ComplexVector other){ other.toCartesian(); double result=0; double norm1=0; double norm2=0; for (int i=0; i < dimension * 2; ++i) { result+=coordinates[i] * other.coordinates[i]; norm1+=coordinates[i] * coordinates[i]; norm2+=other.coordinates[i] * other.coordinates[i]; } return result / Math.sqrt(norm1 * norm2); }
Measure overlap, again using the Hermitian / Euclidean scalar product.
protected void baselineLayout(int targetSpan,int axis,int[] offsets,int[] spans){ int totalAscent=(int)(targetSpan * getAlignment(axis)); int totalDescent=targetSpan - totalAscent; int n=getViewCount(); for (int i=0; i < n; i++) { View v=getView(i); float align=v.getAlignment(axis); float viewSpan; if (v.getResizeWeight(axis) > 0) { float minSpan=v.getMinimumSpan(axis); float maxSpan=v.getMaximumSpan(axis); if (align == 0.0f) { viewSpan=Math.max(Math.min(maxSpan,totalDescent),minSpan); } else if (align == 1.0f) { viewSpan=Math.max(Math.min(maxSpan,totalAscent),minSpan); } else { float fitSpan=Math.min(totalAscent / align,totalDescent / (1.0f - align)); viewSpan=Math.max(Math.min(maxSpan,fitSpan),minSpan); } } else { viewSpan=v.getPreferredSpan(axis); } offsets[i]=totalAscent - (int)(viewSpan * align); spans[i]=(int)viewSpan; } }
Computes the location and extent of each child view in this <code>BoxView</code> given the <code>targetSpan</code>, which is the width (or height) of the region we have to work with.
public void validateBusinessObjectDataStatusInformation(BusinessObjectDataKey expectedBusinessObjectDataKey,String expectedBusinessObjectDataStatus,BusinessObjectDataStatusInformation businessObjectDataStatusInformation){ assertNotNull(businessObjectDataStatusInformation); assertEquals(expectedBusinessObjectDataKey,businessObjectDataStatusInformation.getBusinessObjectDataKey()); assertEquals(expectedBusinessObjectDataStatus,businessObjectDataStatusInformation.getStatus()); }
Validates the contents of a business object data status information against the specified parameters.
@Override public boolean add(E value){ final int hash; int index; if (value == null) { hash=0; index=indexOfNull(); } else { hash=value.hashCode(); index=indexOf(value,hash); } if (index >= 0) { return false; } index=~index; if (mSize >= mHashes.length) { final int n=mSize >= (BASE_SIZE * 2) ? (mSize + (mSize >> 1)) : (mSize >= BASE_SIZE ? (BASE_SIZE * 2) : BASE_SIZE); if (DEBUG) Log.d(TAG,"add: grow from " + mHashes.length + " to "+ n); final int[] ohashes=mHashes; final Object[] oarray=mArray; allocArrays(n); if (mHashes.length > 0) { if (DEBUG) Log.d(TAG,"add: copy 0-" + mSize + " to 0"); System.arraycopy(ohashes,0,mHashes,0,ohashes.length); System.arraycopy(oarray,0,mArray,0,oarray.length); } freeArrays(ohashes,oarray,mSize); } if (index < mSize) { if (DEBUG) Log.d(TAG,"add: move " + index + "-"+ (mSize - index)+ " to "+ (index + 1)); System.arraycopy(mHashes,index,mHashes,index + 1,mSize - index); System.arraycopy(mArray,index,mArray,index + 1,mSize - index); } mHashes[index]=hash; mArray[index]=value; mSize++; return true; }
Adds the specified object to this set. The set is not modified if it already contains the object.
public ArrowNeedle(boolean isArrowAtTop){ this.isArrowAtTop=isArrowAtTop; }
Constructs a new arrow needle.
public void deHalfOp(UserHostmask user){ if (user == null) throw new IllegalArgumentException("Can't remove halfop on null user"); setMode("-h " + user.getNick()); }
Removes owner privileges to a user on a channel. Successful use of this method may require the bot to have operator or halfOp status itself. <p> <b>Warning:</b> Not all IRC servers support this. Some servers may even use it to mean something else!
@Override public String address(Class<?> api,String address){ Objects.requireNonNull(address); if (address.isEmpty()) { address=addressDefault(api); } int slash=address.indexOf("/"); if (address.endsWith(":") && slash < 0) { address+="//"; } int p=address.indexOf("://"); int q=-1; if (p > 0) { q=address.indexOf('/',p + 3); } if (address.indexOf('{') > 0) { return addressBraces(api,address); } boolean isPrefix=address.startsWith("session:") || address.startsWith("pod:"); if (address.isEmpty() || p > 0 && q < 0 && isPrefix) { if (Vault.class.isAssignableFrom(api)) { TypeRef itemRef=TypeRef.of(api).to(Vault.class).param("T"); Class<?> assetClass=itemRef.rawClass(); address=address + "/" + apiAddress(assetClass); } else { address=address + "/" + apiAddress(api); } } return address; }
Calculate address from an API with an address default
private void checkOrMarkPrivateAccess(Expression source,MethodNode mn){ if (mn == null) { return; } ClassNode declaringClass=mn.getDeclaringClass(); ClassNode enclosingClassNode=typeCheckingContext.getEnclosingClassNode(); if (declaringClass != enclosingClassNode || typeCheckingContext.getEnclosingClosure() != null) { int mods=mn.getModifiers(); boolean sameModule=declaringClass.getModule() == enclosingClassNode.getModule(); String packageName=declaringClass.getPackageName(); if (packageName == null) { packageName=""; } if ((Modifier.isPrivate(mods) && sameModule)) { addPrivateFieldOrMethodAccess(source,declaringClass,StaticTypesMarker.PV_METHODS_ACCESS,mn); } else if (Modifier.isProtected(mods) && !packageName.equals(enclosingClassNode.getPackageName()) && !implementsInterfaceOrIsSubclassOf(enclosingClassNode,declaringClass)) { ClassNode cn=enclosingClassNode; while ((cn=cn.getOuterClass()) != null) { if (implementsInterfaceOrIsSubclassOf(cn,declaringClass)) { addPrivateFieldOrMethodAccess(source,cn,StaticTypesMarker.PV_METHODS_ACCESS,mn); break; } } } } }
Given a method node, checks if we are calling a private method from an inner class.
public static void zipAndEncryptAll(File inZipFile,File outFile,String password,AESEncrypter encrypter) throws IOException { AesZipFileEncrypter enc=new AesZipFileEncrypter(outFile,encrypter); try { enc.addAll(inZipFile,password); } finally { enc.close(); } }
Encrypt all files from an existing zip to one new "zipOutFile" using "password".
void resetCache(Panel boundaryPanel,DragContext context){ ArrayList<Candidate> list=new ArrayList<Candidate>(); if (context.draggable != null) { WidgetArea boundaryArea=new WidgetArea(boundaryPanel,null); for ( DropController dropController : dropControllerList) { Candidate candidate=new Candidate(dropController); Widget dropTarget=candidate.getDropTarget(); if (DOM.isOrHasChild(context.draggable.getElement(),dropTarget.getElement())) { continue; } if (candidate.getTargetArea().intersects(boundaryArea)) { list.add(candidate); } } } sortedCandidates=list.toArray(new Candidate[list.size()]); Arrays.sort(sortedCandidates); }
Cache a list of eligible drop controllers, sorted by relative DOM positions of their respective drop targets. Called at the beginning of each drag operation, or whenever drop target eligibility has changed while dragging.
public static void main(String[] args){ ArrayList<String> tmpArgs=new ArrayList<String>(Arrays.asList(args)); int numThreads=1; for (int i=0; i < tmpArgs.size() - 1; i++) { if (tmpArgs.get(i).equals("-t")) { try { numThreads=Integer.parseInt(tmpArgs.get(i + 1)); tmpArgs.remove(i + 1); tmpArgs.remove(i); } catch ( NumberFormatException e) { System.err.println("Invalid number of threads."); System.err.println(e.getStackTrace()); } } } logger.info("Number of threads:{}",numThreads); args=tmpArgs.toArray(new String[0]); StringBuilder cliString=new StringBuilder(); for (int i=0; i < args.length; i++) { cliString.append(" ").append(args[i]); } logger.debug("Command line string = {}",cliString.toString()); System.out.println("Command line string = " + cliString.toString()); Task task=null; try { task=(Task)ClassOption.cliStringToObject(cliString.toString(),Task.class,null); logger.info("Sucessfully instantiating {}",task.getClass().getCanonicalName()); } catch ( Exception e) { logger.error("Fail to initialize the task",e); System.out.println("Fail to initialize the task" + e); return; } task.setFactory(new ThreadsComponentFactory()); task.init(); ThreadsEngine.submitTopology(task.getTopology(),numThreads); }
The main method.
public void testKeyPairGenerator11() throws NoSuchAlgorithmException, NoSuchProviderException { if (!DSASupported) { fail(NotSupportMsg); return; } int[] keys={-10000,-1024,-1,0,10000}; KeyPairGenerator[] kpg=createKPGen(); assertNotNull("KeyPairGenerator objects were not created",kpg); SecureRandom random=new SecureRandom(); AlgorithmParameterSpec aps=null; for (int i=0; i < kpg.length; i++) { for (int j=0; j < keys.length; j++) { try { kpg[i].initialize(keys[j]); kpg[i].initialize(keys[j],random); } catch ( InvalidParameterException e) { } } try { kpg[i].initialize(aps); kpg[i].initialize(aps,random); } catch ( InvalidAlgorithmParameterException e) { } } }
Test for methods: <code>initialize(int keysize)</code> <code>initialize(int keysize, SecureRandom random)</code> <code>initialize(AlgorithmParameterSpec param)</code> <code>initialize(AlgorithmParameterSpec param, SecureRandom random)</code> Assertion: throws InvalidParameterException or InvalidAlgorithmParameterException when parameters keysize or param are incorrect
public static IMultiPoint[] randomPoints(int n,int d){ IMultiPoint points[]=new IMultiPoint[n]; for (int i=0; i < n; i++) { StringBuilder sb=new StringBuilder(); for (int j=0; j < d; j++) { sb.append(rGen.nextDouble()); if (j < d - 1) { sb.append(","); } } points[i]=new Hyperpoint(sb.toString()); } return points; }
generate array of n d-dimensional points whose coordinates are values in the range 0 .. 1
public ObjectMatrix2D like2D(int rows,int columns){ return new SparseObjectMatrix2D(rows,columns); }
Construct and returns a new 2-d matrix <i>of the corresponding dynamic type</i>, entirelly independent of the receiver. For example, if the receiver is an instance of type <tt>DenseObjectMatrix1D</tt> the new matrix must be of type <tt>DenseObjectMatrix2D</tt>, if the receiver is an instance of type <tt>SparseObjectMatrix1D</tt> the new matrix must be of type <tt>SparseObjectMatrix2D</tt>, etc.
public int connectSrcHandlerToPackageSync(Context srcContext,Handler srcHandler,String dstPackageName,String dstClassName){ if (DBG) log("connect srcHandler to dst Package & class E"); mConnection=new AsyncChannelConnection(); mSrcContext=srcContext; mSrcHandler=srcHandler; mSrcMessenger=new Messenger(srcHandler); mDstMessenger=null; Intent intent=new Intent(Intent.ACTION_MAIN); intent.setClassName(dstPackageName,dstClassName); boolean result=srcContext.bindService(intent,mConnection,Context.BIND_AUTO_CREATE); if (DBG) log("connect srcHandler to dst Package & class X result=" + result); return result ? STATUS_SUCCESSFUL : STATUS_BINDING_UNSUCCESSFUL; }
Connect handler to named package/class synchronously.
@Override public int read() throws IOException { synchronized (lock) { checkNotClosed(); if (pos != count) { return str.charAt(pos++); } return -1; } }
Reads a single character from the source string and returns it as an integer with the two higher-order bytes set to 0. Returns -1 if the end of the source string has been reached.
private void showFeedback(String message){ if (myHost != null) { myHost.showFeedback(message); } else { System.out.println(message); } }
Used to communicate feedback pop-up messages between a plugin tool and the main Whitebox user-interface.
public boolean canBuildFormatter(){ return isFormatter(getFormatter()); }
Returns true if toFormatter can be called without throwing an UnsupportedOperationException.
public void unsetMatchColumn(int[] columnIdxes) throws SQLException { throw new UnsupportedOperationException(); }
Unsets the designated parameter to the given int array. This was set using <code>setMatchColumn</code> as the column which will form the basis of the join. <P> The parameter value unset by this method should be same as was set.
public static boolean areColinear(Vec4 a,Vec4 b,Vec4 c){ if (a == null || b == null || c == null) { String msg=Logging.getMessage("nullValue.Vec4IsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Vec4 ab=b.subtract3(a).normalize3(); Vec4 bc=c.subtract3(b).normalize3(); return Math.abs(ab.dot3(bc)) > 0.999; }
Indicates whether three vectors are colinear.
protected void reset(Point treePoint){ this.drawPoint.x=this.bounds.x + treePoint.x; this.drawPoint.y=this.bounds.y + treePoint.y; this.screenBounds=new Rectangle(this.drawPoint.x,this.drawPoint.y,this.bounds.width,this.bounds.height); int pickX=this.pickBounds.x + treePoint.x; int pickY=this.pickBounds.y + treePoint.y; this.pickScreenBounds=new Rectangle(pickX,pickY,this.pickBounds.width,this.pickBounds.height); }
Reset the draw point to the lower left corner of the node bounds.
public SimpleName newSimpleName(String identifier){ if (identifier == null) { throw new IllegalArgumentException(); } SimpleName result=new SimpleName(this); result.setIdentifier(identifier); return result; }
Creates and returns a new unparented simple name node for the given identifier. The identifier should be a legal Java identifier, but not a keyword, boolean literal ("true", "false") or null literal ("null").
public double unweightedMacroFmeasure(){ return m_delegate.unweightedMacroFmeasure(); }
Unweighted macro-averaged F-measure. If some classes not present in the test set, they're just skipped (since recall is undefined there anyway) .
public HadoopJobHistoryNodeExtractor(Properties prop) throws Exception { this.serverURL=prop.getProperty(Constant.AZ_HADOOP_JOBHISTORY_KEY); String CURRENT_DIR=System.getProperty("user.dir"); String WH_HOME=System.getenv("WH_HOME"); String USER_HOME=System.getenv("HOME") + "/.kerberos"; String ETC="/etc"; String TMP="/var/tmp" + "/.kerberos"; String[] allPositions=new String[]{CURRENT_DIR,WH_HOME,USER_HOME,TMP}; for ( String possition : allPositions) { String gssFileName=possition + "/gss-jaas.conf"; File gssFile=new File(gssFileName); if (gssFile.exists()) { logger.debug("find gss-jaas.conf file in : {}",gssFile.getAbsolutePath()); System.setProperty("java.security.auth.login.config",gssFile.getAbsolutePath()); break; } else { logger.debug("can't find here: {}",gssFile.getAbsolutePath()); } } for ( String possition : allPositions) { String krb5FileName=possition + "/krb5.conf"; File krb5File=new File(krb5FileName); if (krb5File.exists()) { logger.debug("find krb5.conf file in : {}",krb5File.getAbsolutePath()); System.setProperty("java.security.krb5.conf",krb5File.getAbsolutePath()); break; } else { logger.debug("can't find here: {}",krb5File.getAbsolutePath()); } } if (System.getProperty("java.security.auth.login.config") == null || System.getProperty("java.security.krb5.conf") == null) { throw new Exception("Can't find java security config files"); } if (logger.isTraceEnabled()) { System.setProperty("sun.security.krb5.debug","true"); } else { System.setProperty("sun.security.krb5.debug","false"); } System.setProperty("javax.security.auth.useSubjectCredsOnly","false"); System.setProperty("java.security.krb5.realm",prop.getProperty("krb5.realm")); System.setProperty("java.security.krb5.kdc",prop.getProperty("krb5.kdc")); PoolingHttpClientConnectionManager cm=new PoolingHttpClientConnectionManager(); cm.setMaxTotal(200); cm.setDefaultMaxPerRoute(100); CredentialsProvider credsProvider=new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials("DUMMY",null)); Lookup<AuthSchemeProvider> authRegistry=RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO,new SPNegoSchemeFactory()).build(); httpClient=HttpClients.custom().setDefaultCredentialsProvider(credsProvider).setDefaultAuthSchemeRegistry(authRegistry).setConnectionManager(cm).build(); }
Use HTTPClient to connect to Hadoop job history server. Need to set the environment for kerberos, keytab...
public Interval withDurationBeforeEnd(ReadableDuration duration){ long durationMillis=DateTimeUtils.getDurationMillis(duration); if (durationMillis == toDurationMillis()) { return this; } Chronology chrono=getChronology(); long endMillis=getEndMillis(); long startMillis=chrono.add(endMillis,durationMillis,-1); return new Interval(startMillis,endMillis,chrono); }
Creates a new interval with the specified duration before the end instant.
public void yypushback(int number){ if (number > yylength()) zzScanError(ZZ_PUSHBACK_2BIG); zzMarkedPos-=number; }
Pushes the specified amount of characters back into the input stream. They will be read again by then next call of the scanning method
public Projection create(Properties props) throws ProjectionException { try { LatLonPoint llp=convertToLLP((Point2D)props.get(ProjectionFactory.CENTER)); float scale=PropUtils.floatFromProperties(props,ProjectionFactory.SCALE,10000000); int height=PropUtils.intFromProperties(props,ProjectionFactory.HEIGHT,100); int width=PropUtils.intFromProperties(props,ProjectionFactory.WIDTH,100); return new Mercator(llp,scale,width,height); } catch ( Exception e) { if (Debug.debugging("proj")) { Debug.output("MercatorLoader: problem creating Mercator projection " + e.getMessage()); } } throw new ProjectionException("MercatorLoader: problem creating Mercator projection"); }
Create the projection with the given parameters.
@Override public void zoomRangeAxes(double lowerPercent,double upperPercent,PlotRenderingInfo info,Point2D source){ XYPlot subplot=findSubplot(info,source); if (subplot != null) { subplot.zoomRangeAxes(lowerPercent,upperPercent,info,source); } else { for ( XYPlot p : this.subplots) { p.zoomRangeAxes(lowerPercent,upperPercent,info,source); } } }
Zooms in on the range axes.
private void startReconcilingPositions(){ presenter.addAllPositions(removedPositions); removedPositionCount=removedPositions.size(); }
Start reconciling positions.
public void actionPerformed(ActionEvent e){ log.info("Cmd=" + e.getActionCommand()); if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL)) { dispose(); return; } saveSelection(); if (selection != null && selection.size() > 0 && m_selectionActive && m_DD_Order_ID != null && m_MovementDate != null) generateMovements(); else dispose(); }
Action Listener
UniformModel(final int numOutcomes){ mNumOutcomes=numOutcomes; }
Construct a uniform model.
public int lengthOfLastWord(String s){ if (s == null || s.length() == 0) return 0; int len=s.length(); int count=0; for (int i=len - 1; i >= 0; i--) { if (s.charAt(i) != ' ') count++; if (s.charAt(i) == ' ' && count != 0) return count; } return count; }
Traverse backwards Use count to remember length of word Start counting from non-space char Return when next space is met and length is not zero
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 void trace(String msg,Throwable t){ }
Do nothing
@Override protected void doGet(HttpServletRequest request,HttpServletResponse response){ processGetRequest(request,response); }
Handles the HTTP <code>GET</code> method.
public ListIterator<VariableMapElement> iterator(){ return list.listIterator(0); }
Creates and returns an enumerator for this object
public GPUImage3x3ConvolutionFilter(final float[] convolutionKernel){ super(THREE_X_THREE_TEXTURE_SAMPLING_FRAGMENT_SHADER); mConvolutionKernel=convolutionKernel; }
Instantiates a new GPUimage3x3ConvolutionFilter with given convolution kernel.
@RequestMapping(value=BUSINESS_OBJECT_DATA_NOTIFICATIONS_URI_PREFIX + "/namespaces/{namespace}/notificationNames/{notificationName}",method=RequestMethod.PUT) @Secured(SecurityFunctions.FN_BUSINESS_OBJECT_DATA_NOTIFICATION_REGISTRATIONS_PUT) public BusinessObjectDataNotificationRegistration updateBusinessObjectDataNotificationRegistration(@PathVariable("namespace") String namespace,@PathVariable("notificationName") String notificationName,@RequestBody BusinessObjectDataNotificationRegistrationUpdateRequest request){ return businessObjectDataNotificationRegistrationService.updateBusinessObjectDataNotificationRegistration(new NotificationRegistrationKey(namespace,notificationName),request); }
Updates an existing business object data notification by key. <p>Requires WRITE permission on namespace</p> <p>Requires READ permission on filter namespace</p> <p>Requires EXECUTE permission on ALL job action namespaces</p>
boolean isDimming(){ return mTargetAlpha != 0; }
Return true if dim layer is showing
public static StringSet declaredSymbolsInScopeSet(ModuleNode module,Location loc){ StringSet result=new StringSet(); addDeclaredSymbolsInScopeSet(result,module,loc); return result; }
Returns a HashSet containing all user-definable names that are globally defined or declared at Location loc of the module. The returned value may or may not contain strings that are not user-definable names--in particular strings like "I!bar". If the statement at loc defines or declares a symbol, that symbol does not appear in the returned value. However, the implementation assumes that there there is no declaration or definition that begins on the same line as the beginning of loc. If there is, the symbol it defines will not appear in the returned result. The method also assumes that loc is after any EXTENDS statement in the module.
private final void increaseConcentration(double by){ setConcentration(getConcentration() + by); }
Increase the current concentration by a certain amount. According to increase the concentration the amount of nectar has to be recomputed.
public PostProcessor(int fboWidth,int fboHeight,boolean useDepth,boolean useAlphaChannel,boolean use32Bits){ this(fboWidth,fboHeight,useDepth,useAlphaChannel,use32Bits,TextureWrap.ClampToEdge,TextureWrap.ClampToEdge); }
Construct a new PostProcessor with the given parameters, defaulting to <em>TextureWrap.ClampToEdge</em> as texture wrap mode
public static void main(String[] args){ ComparableCircle comparableCircle1=new ComparableCircle(12.5); ComparableCircle comparableCircle2=new ComparableCircle(18.3); System.out.println("\nComparableCircle1:"); System.out.println(comparableCircle1); System.out.println("\nComparableCircle2:"); System.out.println(comparableCircle2); System.out.println((comparableCircle1.compareTo(comparableCircle2) == 1 ? "\nComparableCircle1 " : "\nComparableCircle2 ") + "is the larger of the two Circles"); }
Main method
public FilterQuery track(final String[] track){ this.track=track; return this; }
Sets track
public static PolygonRDD SpatialRangeQueryUsingIndex(PolygonRDD polygonRDD,Envelope envelope,Integer condition){ if (polygonRDD.indexedRDDNoId == null) { throw new NullPointerException("Need to invoke buildIndex() first, indexedRDDNoId is null"); } JavaRDD<Polygon> result=polygonRDD.indexedRDDNoId.mapPartitions(new PolygonRangeFilterUsingIndex(envelope)); return new PolygonRDD(result); }
Spatial range query on top of PolygonRDD
public byte[] analyzeWavData(InputStream i){ try { int headSize=44, metaDataSize=48; byte[] data=IOUtils.toByteArray(i); if (data.length < headSize) { throw new IOException("Wrong Wav header"); } if (this.sampleRate == 0 && data.length > 28) { this.sampleRate=readInt(data,24); } int destPos=headSize + metaDataSize; int rawLength=data.length - destPos; byte[] d=new byte[rawLength]; System.arraycopy(data,destPos,d,0,rawLength); return d; } catch ( IOException e) { Log.e(TAG,"Error while formatting header"); } return new byte[0]; }
Analyze sample rate and return the PCM data
public Quaterniond scale(double factor){ return scale(factor,this); }
Scale the rotation represented by this quaternion by the given <code>factor</code> using spherical linear interpolation. <p> This method is equivalent to performing a spherical linear interpolation between the unit quaternion and <code>this</code>, and thus equivalent to calling: <tt>new Quaterniond().slerp(this, factor)</tt> <p> Reference: <a href="http://fabiensanglard.net/doom3_documentation/37725-293747_293747.pdf">http://fabiensanglard.net</a>
private void handleDispose(){ if (infoFont != null && !infoFont.isDisposed()) { infoFont.dispose(); } infoFont=null; if (titleFont != null && !titleFont.isDisposed()) { titleFont.dispose(); } titleFont=null; }
The dialog is being disposed. Dispose of any resources allocated.
public String prepareTable(ColumnInfo[] layout,String from,String where,boolean multiSelection,String tableName,boolean addAccessSQL){ int columnIndex=0; StringBuffer sql=new StringBuffer("SELECT "); setLayout(layout); clearColumns(); setColorColumn(-1); setMultiSelection(multiSelection); for (columnIndex=0; columnIndex < layout.length; columnIndex++) { if (columnIndex > 0) { sql.append(", "); } sql.append(layout[columnIndex].getColSQL()); if (layout[columnIndex].isKeyPairCol()) { sql.append(",").append(layout[columnIndex].getKeyPairColSQL()); } addColumn(layout[columnIndex]); if (layout[columnIndex].isColorColumn()) { setColorColumn(columnIndex); } if (layout[columnIndex].getColClass() == IDColumn.class) { setKeyColumnIndex(columnIndex); } } for (columnIndex=0; columnIndex < layout.length; columnIndex++) { setColumnClass(columnIndex,layout[columnIndex].getColClass(),layout[columnIndex].isReadOnly(),layout[columnIndex].getColHeader()); } sql.append(" FROM ").append(from); sql.append(" WHERE ").append(where); if (from.length() == 0) { return sql.toString(); } if (addAccessSQL) { String finalSQL=MRole.getDefault().addAccessSQL(sql.toString(),tableName,MRole.SQL_FULLYQUALIFIED,MRole.SQL_RO); logger.finest(finalSQL); return finalSQL; } else { return sql.toString(); } }
Prepare Table and return SQL required to get resultset to populate table
public ReadInputRegistersRequest(int ref,int count){ super(); setFunctionCode(Modbus.READ_INPUT_REGISTERS); setDataLength(4); setReference(ref); setWordCount(count); }
Constructs a new <tt>ReadInputRegistersRequest</tt> instance with a given reference and count of words to be read. <p>
protected void correlatedPointAddedCallback(int correlatedTimeStep){ boolean sourceMatches=false; if (Math.abs(sourceObs - source[correlatedTimeStep]) <= kernelWidthSourceInUse) { countPastSource++; sourceMatches=true; } if (Math.abs(destNextObs - destNext[correlatedTimeStep]) <= kernelWidthsInUse[0]) { countNextPast++; if (sourceMatches) { countNextPastSource++; } } }
A callback for where a correlated point is found at correlatedTimeStep in the destination's past. Now check whether we need to increment the joint counts.
public void showFab(float translationX,float translationY){ setFabAnchor(translationX,translationY); if (!isSheetVisible()) { fab.show(translationX,translationY); } }
Shows the FAB and sets the FAB's translation.
@Override public void add(Permission permission){ if (!(permission instanceof PackagePermission)) throw new IllegalArgumentException("invalid permission: " + permission); if (isReadOnly()) throw new SecurityException("attempt to add a Permission to a " + "readonly PermissionCollection"); PackagePermission pp=(PackagePermission)permission; String name=pp.getName(); PackagePermission existing=(PackagePermission)permissions.get(name); if (existing != null) { int oldMask=existing.getMask(); int newMask=pp.getMask(); if (oldMask != newMask) { permissions.put(name,new PackagePermission(name,oldMask | newMask)); } } else { permissions.put(name,permission); } if (!all_allowed) { if (name.equals("*")) all_allowed=true; } }
Adds a permission to the <tt>PackagePermission</tt> objects. The key for the hash is the name.
protected boolean convertToUppercase(){ return false; }
Method convertToUppercase.
public void queryGreaterThan(String type,int index,String value,int page,int limit,int visibilityScope,CloudResponse<CloudObject[]> response){ try { queryImpl(type,value,index,page,limit,visibilityScope,2,0,false,false,false,response); } catch ( CloudException e) { response.onError(e); } }
Performs a query to the server finding the objects where the key value is greater than the given value. This operation executes immeditely without waiting for commit.
public static byte[] parseSchemeSpecificData(byte[] atom,UUID uuid){ Pair<UUID,byte[]> parsedAtom=parsePsshAtom(atom); if (parsedAtom == null) { return null; } if (uuid != null && !uuid.equals(parsedAtom.first)) { Log.w(TAG,"UUID mismatch. Expected: " + uuid + ", got: "+ parsedAtom.first+ "."); return null; } return parsedAtom.second; }
Parses the scheme specific data from a PSSH atom. Version 0 and 1 PSSH atoms are supported. <p> The scheme specific data is only parsed if the data is a valid PSSH atom matching the given UUID, or if the data is a valid PSSH atom of any type in the case that the passed UUID is null.
private boolean termFilter(Term term,String[] desiredFields,int minFreq,int maxFreq,int maxNonAlphabet,boolean filterNumbers,int minTermLength){ if (filterNumbers) { try { Double.parseDouble(term.text()); return false; } catch ( Exception e) { } } return termFilter(term,desiredFields,minFreq,maxFreq,maxNonAlphabet,minTermLength); }
Applies termFilter and additionally (if requested) filters out digit-only words.
protected String int2singlealphaCount(long val,CharArrayWrapper table){ int radix=table.getLength(); if (val > radix) { return getZeroString(); } else return (new Character(table.getChar((int)val - 1))).toString(); }
Convert a long integer into alphabetic counting, in other words count using the sequence A B C ... Z.
public void componentHidden(final ComponentEvent e){ setVisible(false); }
Invoked when the component has been made invisible. MenuComponent.setVisible does nothing, so we remove the ScreenMenuItem from the ScreenMenu but leave it in fItems
protected Position computeMainLabelPosition(DrawContext dc,TacticalGraphicLabel label,Position midpoint,Position posB){ Globe globe=dc.getGlobe(); Vec4 pMid=globe.computePointFromPosition(midpoint); Vec4 pB=globe.computePointFromPosition(posB); Vec4 normal=globe.computeSurfaceNormalAtPoint(pMid); Vec4 vMB=pB.subtract3(pMid); Vec4 eyePoint=dc.getView().getEyePoint(); double pixelSize=dc.getView().computePixelSizeAtDistance(eyePoint.distanceTo3(pMid)); Rectangle labelBounds=label.getBounds(dc); double labelDiagonal=labelBounds != null ? Math.hypot(labelBounds.width,labelBounds.height) : 0d; double pixelDistance=labelDiagonal / 2.0; Vec4 perpendicular=vMB.cross3(normal); perpendicular=perpendicular.normalize3().multiply3(this.getWidth() / 2.0 + pixelDistance * pixelSize); Vec4 pLabel=pMid.add3(perpendicular); return globe.computePositionFromPoint(pLabel); }
Compute the position of the graphic's main label. This label is positioned to the side of the first segment along the route.
protected void validateState(State currentState){ ValidationUtils.validateState(currentState); }
Validate the service state for coherence.
public void updateTableEntity(TableEntity tableEntity,boolean commit){ SolrInputDocument doc=new SolrInputDocument(); doc.setField(ID,tableEntity.getFqdn()); doc.setField(TYPE,TYPE_TABLE); doc.setField(DATABASE_NAME,tableEntity.getDatabaseName()); doc.setField(TABLE_NAME,tableEntity.getTableName()); doc.setField(FIELDS,tableEntity.getFieldNames()); doc.setField(TRANSFORMATION,tableEntity.getTransformationType().split(" -> ")[0]); doc.setField(EXPORTS,tableEntity.getExportNames()); doc.setField(STORAGE_FORMAT,tableEntity.getStorageFormat()); doc.setField(MATERIALIZE_ONCE,tableEntity.isMaterializeOnce()); doc.setField(EXTERNAL,tableEntity.isExternalTable()); doc.setField(CREATED_AT,tableEntity.getCreatedAt()); doc.setField(OWNER,tableEntity.getTableOwner()); doc.setField(DESCRIPTION,tableEntity.getTableDescription()); doc.setField(TAXONOMIES,tableEntity.getTaxonomyNames()); doc.setField(CATEGORIES,tableEntity.getCategoryNames()); doc.setField(CATEGORIE_OBJECTSS,tableEntity.getCategoryObjectNames()); doc.setField(TAGS,tableEntity.getTags()); doc.setField(STATUS,tableEntity.getStatus()); if (tableEntity.getComment() != null) { doc.setField(DOCUMENTATION,tableEntity.getComment().getPlainText()); String comments=""; for ( CommentEntity comment : tableEntity.getComments()) { if (!comments.isEmpty()) { comments+=" "; } comments+=comment.getUsername() + ": " + comment.getPlainText(); } if (!comments.isEmpty()) { doc.setField(COMMENTS,comments); } } addDocument(doc); if (commit) { commit(); } }
Updates the Solr document for the given table entity
private ArrayDBIDs initialSet(DBIDs sampleSet,int k,Random random){ return DBIDUtil.ensureArray(DBIDUtil.randomSample(sampleSet,k,random)); }
Returns a set of k elements from the specified sample set.
private byte[] blockFragmentizerSafe(long blockIdx) throws IOException { try { try { return block(blockIdx); } catch ( IgfsCorruptedFileException e) { if (log.isDebugEnabled()) log.debug("Failed to fetch file block [path=" + path + ", fileInfo="+ fileInfo+ ", blockIdx="+ blockIdx+ ", errMsg="+ e.getMessage()+ ']'); if (fileInfo != null && fileInfo.fileMap() != null && !fileInfo.fileMap().ranges().isEmpty()) { IgfsEntryInfo newInfo=igfsCtx.meta().info(fileInfo.id()); if (newInfo == null) throw new IgfsPathNotFoundException("Failed to read file block (file was concurrently " + "deleted) [path=" + path + ", blockIdx="+ blockIdx+ ']'); fileInfo=newInfo; locCache.clear(); if (log.isDebugEnabled()) log.debug("Updated input stream file info after block fetch failure [path=" + path + ", fileInfo="+ fileInfo+ ']'); return block(blockIdx); } throw new IOException(e.getMessage(),e); } } catch ( IgniteCheckedException e) { throw new IOException(e.getMessage(),e); } }
Method to safely retrieve file block. In case if file block is missing this method will check file map and update file info. This may be needed when file that we are reading is concurrently fragmented.
public ReplacableProperties loadProperties(){ ReplacableProperties propertiesBeingLoaded=new ReplacableProperties(); try (InputStream propertiesToLoad=PlayOnLinuxContext.class.getClassLoader().getResourceAsStream(this.getPropertyFileName())){ propertiesBeingLoaded.load(propertiesToLoad); } catch ( PlayOnLinuxException|IOException e) { throw new PlayOnLinuxRuntimeException("Cannot load properties",e); } return propertiesBeingLoaded; }
Get the properties for the current OS
public ThumbnailParameterBuilder fitWithinDimensions(boolean fit){ this.fitWithinDimensions=fit; return this; }
Sets whether or not the thumbnail should fit within the specified dimensions.
private boolean isBoundsEnforced(){ return boundsEnforced; }
True iff bounds checking is performed on variable values indices.
@SuppressWarnings("unchecked") public JdbcData(Connection connection,String table,boolean buffered){ this.connection=connection; this.table=table; setBuffered(buffered); try { setColumnTypes(getJdbcColumnTypes()); } catch ( SQLException e) { e.printStackTrace(); } }
Initializes a new instance to query the data from a specified table using a specified JDBC connection. It is assumed the table columns are constant during the connection.
public void dispatch(){ try { if (catchExceptions) { try { runnable.run(); } catch ( Throwable t) { if (t instanceof Exception) { exception=(Exception)t; } throwable=t; } } else { runnable.run(); } } finally { finishedDispatching(true); } }
Executes the Runnable's <code>run()</code> method and notifies the notifier (if any) when <code>run()</code> has returned or thrown an exception.
public void lock(){ lockPositions(true); this.locked=true; }
Lock this Order.
private int measureLong(int measureSpec){ int result; int specMode=MeasureSpec.getMode(measureSpec); int specSize=MeasureSpec.getSize(measureSpec); if ((specMode == MeasureSpec.EXACTLY) || (mViewPager == null)) { result=specSize; } else { final int count=mViewPager.getAdapter().getCount(); result=(int)(getPaddingLeft() + getPaddingRight() + (count * 2 * mRadius)+ (count - 1) * mRadius + 1); if (specMode == MeasureSpec.AT_MOST) { result=Math.min(result,specSize); } } return result; }
Determines the width of this view
public void trace(String format,Object arg1,Object arg2){ }
Do nothing
public static String makeKey(String host,int port,String transport){ return new StringBuffer(host).append(":").append(port).append("/").append(transport).toString().toLowerCase(); }
Construct a key to refer to this structure from the SIP stack
protected void buildSettings(){ SETTINGS=SEARCH_SETTINGS; }
Sets SETTINGS to be the static SEARCH_SETTINGS, instead of constructing a new one for each ResultPanel.
public void testNoElementThrowsException(){ try { util.selectElementMatchingXPath("app-deployment",testElement); fail("should have thrown an exception"); } catch ( ElementNotFoundException e) { assertEquals(testElement,e.getSearched()); } }
Test that search for a non-existing element throws an exception.
public String replace(final StringBuffer source,final int offset,final int length){ if (source == null) { return null; } final StrBuilder buf=new StrBuilder(length).append(source,offset,length); substitute(buf,0,length); return buf.toString(); }
Replaces all the occurrences of variables with their matching values from the resolver using the given source buffer as a template. The buffer is not altered by this method. <p> Only the specified portion of the buffer will be processed. The rest of the buffer is not processed, and is not returned.
public Builder addKernel(Script.KernelID k){ if (mLines.size() != 0) { throw new RSInvalidStateException("Kernels may not be added once connections exist."); } if (findNode(k) != null) { return this; } mKernelCount++; Node n=findNode(k.mScript); if (n == null) { n=new Node(k.mScript); mNodes.add(n); } n.mKernels.add(k); return this; }
Adds a Kernel to the group.
@Override public void unregisterVASACertificate(String existingCertificate) throws InvalidCertificate, InvalidSession, StorageFault { final String methodName="unregisterVASACertificate(): "; log.debug(methodName + "Entry with input existingCertificate[" + (existingCertificate != null ? "***" : null)+ "]"); try { _sslUtil.checkHttpRequest(true,true); X509Certificate x509Cert=(X509Certificate)_sslUtil.buildCertificate(existingCertificate); SimpleTimeCounter counter=new SimpleTimeCounter("unregisterVASACertificate"); unregisterCertificate(x509Cert); counter.stop(); } catch ( InvalidSession is) { log.error(methodName + "invalid session",is); throw is; } catch ( InvalidCertificate ic) { log.error(methodName + "invalid certificate",ic); throw ic; } catch ( StorageFault sf) { log.error(methodName + "storage fault occured ",sf); throw sf; } catch ( Exception e) { log.error(methodName + "unknown exception",e); throw FaultUtil.StorageFault("runtime ",e); } log.debug(methodName + "Exit"); }
vasaService interface
K key(){ return key; }
Getter of key.
private void clearListSelection(){ _pathList.clearSelection(); int state=_block.getState() & ~OBlock.ALLOCATED; _block.pseudoPropertyChange("state",Integer.valueOf(0),Integer.valueOf(state)); _length.setText(""); }
*********************** end setup
public static String[] stringArrayFromString(String string,char delimiter){ List<String> result=new ArrayList<String>(10); if (StringUtils.isNotBlank(string)) { RaptorStringTokenizer tok=new RaptorStringTokenizer(string,String.valueOf(delimiter),false); while (tok.hasMoreTokens()) { String token=tok.nextToken(); result.add(token); } } return result.toArray(new String[0]); }
Returns a String[] of strings from a string that is formatted in what toString(String[]) returns.
public boolean startsWith(XMLString prefix){ return startsWith(prefix,0); }
Tests if this string starts with the specified prefix.
public boolean isEnableMove(){ return this.enableMove; }
Specifies whether the user can move the frame by dragging the title bar.
public String toString(){ return "[Certificate Exception: " + getMessage() + "]"; }
Returns a string describing the certificate exception.