code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
|---|---|
private void initializeLayout(){
this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
Border padding=BorderFactory.createEmptyBorder(5,5,5,5);
JPanel tPanel=new JPanel();
tPanel.setLayout(new BoxLayout(tPanel,BoxLayout.X_AXIS));
tPanel.add(cbNeuronType);
int horzStrut=30;
tPanel.add(Box.createHorizontalStrut(horzStrut));
tPanel.add(Box.createHorizontalGlue());
tPanel.add(neuronRulePanelTriangle);
tPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
tPanel.setBorder(padding);
this.add(tPanel);
this.add(Box.createRigidArea(new Dimension(0,5)));
neuronRulePanel.setAlignmentX(Component.CENTER_ALIGNMENT);
neuronRulePanel.setBorder(padding);
neuronRulePanel.setVisible(neuronRulePanelTriangle.isDown());
this.add(neuronRulePanel);
TitledBorder tb=BorderFactory.createTitledBorder("Update Rule");
this.setBorder(tb);
}
|
Lays out the components of the panel.
|
public KMLLocation(String namespaceURI){
super(namespaceURI);
}
|
Construct an instance.
|
public ProtocolVersion forVersion(int major,int minor){
if ((major == this.major) && (minor == this.minor)) {
return this;
}
if (major == 1) {
if (minor == 0) {
return HTTP_1_0;
}
if (minor == 1) {
return HTTP_1_1;
}
}
if ((major == 0) && (minor == 9)) {
return HTTP_0_9;
}
return new HttpVersion(major,minor);
}
|
Obtains a specific HTTP version.
|
@Override public Enumeration<Option> listOptions(){
Vector<Option> newVector=new Vector<Option>(5);
newVector.addElement(new Option("\tChoose attribute to be used for selection.","C",1,"-C <num>"));
newVector.addElement(new Option("\tNumber of values to retain for the sepcified attribute, \n" + "\ti.e. the ones with the most instances (default 2).","N",1,"-N <num>"));
newVector.addElement(new Option("\tInstead of values with the most instances the ones with the \n" + "\tleast are retained.\n","L",0,"-L"));
newVector.addElement(new Option("\tWhen selecting on nominal attributes, removes header\n" + "\treferences to excluded values.","H",0,"-H"));
newVector.addElement(new Option("\tInvert matching sense.","V",0,"-V"));
return newVector.elements();
}
|
Returns an enumeration describing the available options.
|
public static final <T extends EObject>List<T> collectNodes(EObject root,Class<T> cls,boolean searchForNestedNodes){
final List<T> result=new ArrayList<>();
final TreeIterator<EObject> iter=root.eAllContents();
while (iter.hasNext()) {
final EObject obj=iter.next();
if (cls.isAssignableFrom(obj.getClass())) {
@SuppressWarnings("unchecked") final T objCasted=(T)obj;
result.add(objCasted);
if (!searchForNestedNodes) iter.prune();
}
}
return result;
}
|
Search entire containment tree below 'root' for objects of type 'cls'. If last argument is <code>false</code>, then sub trees below a matching node won't be searched.
|
@DSSafe(DSCat.SAFE_LIST) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-09-03 14:59:53.347 -0400",hash_original_method="17B283E675F13C0A62946A353F07CD53",hash_generated_method="E45B81EF177F99E3E73457DF095A84DF") @Override public boolean equals(Object obj){
if (!(obj instanceof ByteOrderMark)) {
return false;
}
ByteOrderMark bom=(ByteOrderMark)obj;
if (bytes.length != bom.length()) {
return false;
}
for (int i=0; i < bytes.length; i++) {
if (bytes[i] != bom.get(i)) {
return false;
}
}
return true;
}
|
Indicates if this BOM's bytes equals another.
|
public CollectionObject(int id){
this.id=id;
}
|
This method was generated by MyBatis Generator. This method corresponds to the database table collection
|
private void plasmaStore(){
Set<BigInteger> subs=new HashSet<BigInteger>();
ByteArrayOutputStream baos=new ByteArrayOutputStream(subscriptions.size() * 16);
for ( Set<String> s : subscriptions.values()) {
for ( String ss : s) {
try {
baos.write(GTSHelper.unpackGTSId(ss));
}
catch ( IOException ioe) {
}
}
}
for ( String znode : currentPlasmaZnodes) {
try {
this.subsCurator.delete().guaranteed().forPath(znode);
}
catch ( Exception e) {
LOG.error("Error while deleting subscription znodes",e);
}
}
currentPlasmaZnodes.clear();
byte[] bytes=baos.toByteArray();
int idx=0;
while (idx < bytes.length) {
int chunksize=Math.min(this.maxPlasmaZnodeSize,bytes.length - idx);
chunksize=chunksize - (chunksize % 16);
byte[] data=new byte[chunksize];
System.arraycopy(bytes,idx,data,0,data.length);
UUID uuid=UUID.randomUUID();
long sip=SipHashInline.hash24(uuid.getMostSignificantBits(),uuid.getLeastSignificantBits(),data,0,data.length);
String path=this.plasmaZnodeRoot + "/0." + uuid.toString()+ "."+ this.plasmaTopic+ "."+ idx+ "."+ Long.toHexString(sip);
try {
this.subsCurator.create().withMode(CreateMode.EPHEMERAL).forPath(path,data);
currentPlasmaZnodes.add(path);
}
catch ( Exception e) {
LOG.error("Error while creating ZK subscription znode " + path,e);
}
idx+=data.length;
}
byte[] randomData=(this.plasmaTopic + "." + System.currentTimeMillis()).getBytes(Charsets.UTF_8);
try {
this.subsCurator.setData().forPath(this.plasmaZnodeRoot,randomData);
}
catch ( Exception e) {
LOG.error("Error while storing data for " + this.plasmaZnodeRoot,e);
}
}
|
Store the subscription so Plasma BackEnds can send us data This code is almost verbatim that of PlasmaFrontEnd.java
|
@Override public boolean deleteFile(String path){
try {
mDBApi.delete(path);
return true;
}
catch ( DropboxException e) {
e.printStackTrace();
return false;
}
}
|
Deletes a file or folder from the dropbox
|
private void require(int len){
int offset=_offset;
int length=_length;
if (offset + len < length) {
return;
}
flush(_offset);
}
|
Require empty space in the output buffer. If not enough space is available, flush the buffer.
|
private static char[] zzUnpackCMap(String packed){
char[] map=new char[0x10000];
int i=0;
int j=0;
while (i < 164) {
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.
|
public void multiplyParametersByPrepending(Object... args){
cartesianProduct(false,args);
}
|
<p>Performs a cartesian product of parameterizations by prepending each of the incoming args to each existing parameter's arg list.</p> For instance, if you have parameters <tt>[ ("A", 1, 2, 3) and ("B", 4, 5, 6) ]</tt>, and you called <tt>multiplyParametersByPrepending("foo-", 'c', "bar", 'd')</tt>, you would get the following parameterizations, in this order: <ol> <li>"foo-A", 'c', 1, 2, 3</li> <li>"bar-A", 'd', 1, 2, 3</li> <li>"foo-B", 'c', 4, 5, 6</li> <li>"bar-B", 'd', 1, 2, 3</li> </ol>
|
public static Date parseDate(final String dateValue,final Collection dateFormats) throws DateParseException {
return parseDate(dateValue,dateFormats,null);
}
|
Parses the date value using the given date formats.
|
public SpherePortrayal3D(Color color,double scale){
this(color,scale,DEFAULT_DIVISIONS);
}
|
Constructs a SpherePortrayal3D with a flat opaque appearance of the given color and the given scale.
|
public TemporalInstantRfc3339(final DateTime datetime){
dateTime=datetime;
}
|
Construct with a Joda/java v8 DateTime; TZ is preserved, but not in the key.
|
public void display() throws IOException, ObjectNotFoundException, OperationNotPermittedException, ValidationException, OrganizationAuthoritiesException {
VOSubscriptionDetails subscriptionDetails=getSubscriptionService().getSubscriptionDetails(model.getSubscription().getSubscriptionId());
VOPriceModel priceModel=subscriptionDetails.getPriceModel();
ExternalPriceModelDisplayHandler displayHandler=new ExternalPriceModelDisplayHandler();
displayHandler.setContent(priceModel.getPresentation());
displayHandler.setContentType(priceModel.getPresentationDataType());
displayHandler.display();
}
|
Method is used in UI to show external price model details.
|
public byte[] read(byte[] b) throws IOException {
if (b.length == 0) {
return b;
}
int offset=0;
if (nextByte != null) {
b[0]=nextByte;
nextByte=null;
offset=1;
}
int i=this.is.read(b,offset,b.length - offset);
if (i + offset < b.length) {
throw new IOException(String.format("End of file reading a byte[] of size %d",b.length));
}
currentByte=b[b.length - 1];
return b;
}
|
Method that let us read a complete byte array buffer. This is used when strings or other fixed arrays are presented (STR_I, OPAQUE,...). This method is intended to read known fixed sized arrays (WBXML presents this king of data always knowing the array length. The current byte is set to the last byte read.
|
public void deleteBucketLogging(GenericRequest genericRequest) throws OSSException, ClientException {
assertParameterNotNull(genericRequest,"genericRequest");
String bucketName=genericRequest.getBucketName();
assertParameterNotNull(bucketName,"bucketName");
ensureBucketNameValid(bucketName);
Map<String,String> params=new HashMap<String,String>();
params.put(SUBRESOURCE_LOGGING,null);
RequestMessage request=new OSSRequestMessageBuilder(getInnerClient()).setEndpoint(getEndpoint()).setMethod(HttpMethod.DELETE).setBucket(bucketName).setParameters(params).setOriginalRequest(genericRequest).build();
doOperation(request,emptyResponseParser,bucketName,null);
}
|
Delete bucket logging.
|
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-09-03 14:59:53.882 -0400",hash_original_method="FF8F0C2386839E04CA9A4F5B5DAFF53D",hash_generated_method="E650BB0D76E023F97A3B86724FA751F7") public static IOFileFilter sizeRangeFileFilter(long minSizeInclusive,long maxSizeInclusive){
IOFileFilter minimumFilter=new SizeFileFilter(minSizeInclusive,true);
IOFileFilter maximumFilter=new SizeFileFilter(maxSizeInclusive + 1L,false);
return new AndFileFilter(minimumFilter,maximumFilter);
}
|
Returns a filter that accepts files whose size is >= minimum size and <= maximum size.
|
public void resetTrigger(){
mHasTriggered=false;
}
|
Resets the doze trigger state.
|
@Override public void beginWindow(long windowId){
}
|
a no op
|
public boolean isDynamic(){
return true;
}
|
Overridden to always return true and force dynamic menu building.
|
@Override public void rehashFieldDependancies(AbstractSession session){
getReferenceDescriptor().rehashFieldDependancies(session);
}
|
INTERNAL: Rehash any hashtables based on fields. This is used to clone descriptors for aggregates, which hammer field names.
|
public void outputNodePop(){
pop();
}
|
Pop a frame for visible namespace.
|
@SuppressWarnings("unchecked") @Override protected Collection<Header> headers(SMTPSession session){
StringBuilder headerLineBuffer=new StringBuilder();
String heloMode=(String)session.getAttachment(SMTPSession.CURRENT_HELO_MODE,State.Connection);
String heloName=(String)session.getAttachment(SMTPSession.CURRENT_HELO_NAME,State.Connection);
headerLineBuffer.append("from ").append(session.getRemoteAddress().getHostName());
if (heloName != null) {
headerLineBuffer.append(" (").append(heloMode).append(" ").append(heloName).append(")");
}
headerLineBuffer.append(" ([").append(session.getRemoteAddress().getAddress().getHostAddress()).append("])");
Header header=new Header("Received",headerLineBuffer.toString());
headerLineBuffer=new StringBuilder();
headerLineBuffer.append("by ").append(session.getConfiguration().getHelloName()).append(" (").append(session.getConfiguration().getSoftwareName()).append(") with ").append(getServiceType(session,heloMode));
headerLineBuffer.append(" ID ").append(session.getSessionID());
if (((Collection<?>)session.getAttachment(SMTPSession.RCPT_LIST,State.Transaction)).size() == 1) {
header.add(headerLineBuffer.toString());
headerLineBuffer=new StringBuilder();
headerLineBuffer.append("for <").append(((List<MailAddress>)session.getAttachment(SMTPSession.RCPT_LIST,State.Transaction)).get(0).toString()).append(">;");
}
else {
headerLineBuffer.append(";");
}
header.add(headerLineBuffer.toString());
headerLineBuffer=new StringBuilder();
headerLineBuffer.append(DATEFORMAT.get().format(new Date()));
header.add(headerLineBuffer.toString());
return Arrays.asList(header);
}
|
Returns the Received header for the message.
|
private void disposeDecoderOut(IoSession session){
session.removeAttribute(DECODER_OUT);
}
|
Remove the decoder callback from the session's attributes.
|
@Override public void clearAnswer(){
DateTime ldt=new DateTime();
mDatePicker.init(ldt.getYear(),ldt.getMonthOfYear() - 1,ldt.getDayOfMonth(),mDateListener);
mTimePicker.setCurrentHour(ldt.getHourOfDay());
mTimePicker.setCurrentMinute(ldt.getMinuteOfHour());
}
|
Resets date to today.
|
public static final String parseInputStreamToString(InputStream stream,boolean html) throws IOException {
try (InputStreamReader inputStreamReader=new InputStreamReader(stream,StandardCharsets.UTF_8);BufferedReader reader=new BufferedReader(inputStreamReader)){
StringBuilder contentBuilder=new StringBuilder();
if (html) {
contentBuilder.append("<html>");
}
String line=reader.readLine();
while (line != null) {
contentBuilder.append(line);
if (html) {
contentBuilder.append("<br/>");
}
line=reader.readLine();
}
if (html) {
contentBuilder.append("</html>");
}
return contentBuilder.toString();
}
}
|
Reads content from the provided input stream.
|
public void openRegisters(UseCaseConf useCaseConf,Integer bookID,List listIdsRegister) throws BookException, SessionException, ValidationException, ParseException, AttributesException, SecurityException {
FlushFdrField field=new FlushFdrField();
field.setFldid(AxSf.FLD6_FIELD_ID);
field.setValue(new Integer(ISicresKeys.SCR_ESTADO_REGISTRO_COMPLETO).toString());
List fields=new ArrayList(1);
fields.add(field);
String sessionID=useCaseConf.getSessionID();
boolean canCloseRegs=SecuritySession.canOpenCloseReg(sessionID,bookID);
updateFields(useCaseConf,bookID,fields,listIdsRegister);
if (_logger.isDebugEnabled()) {
_logger.debug("openRegisters");
}
}
|
Abrir los registros que se hayan seleccionado *
|
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value="EI_EXPOSE_REP") public String[] validBaudRates(){
return validSpeeds;
}
|
Get an array of valid baud rates.
|
private static void logAndPrintError(PrintStream newStderr,String message,Throwable ex){
Log.e(TAG,message,ex);
if (newStderr != null) {
newStderr.println(message + (ex == null ? "" : ex));
}
}
|
Logs an error message and prints it to the specified stream, if provided
|
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.
|
private void handleUpgradeSubscription(TriggerProcess process,LocalizerFacade facade) throws IOException, WSDLException, ParserConfigurationException {
INotificationServiceAdapter serviceClient=getServiceClient(process.getTriggerDefinition());
VOTriggerProcess vo=TriggerProcessAssembler.toVOTriggerProcess(process,facade);
VOSubscription current=getParamValue(process.getParamValueForName(TriggerProcessParameterName.SUBSCRIPTION),VOSubscription.class);
VOService newProduct=getParamValue(process.getParamValueForName(TriggerProcessParameterName.PRODUCT),VOService.class);
serviceClient.onUpgradeSubscription(VOConverter.convertToApi(vo),VOConverter.convertToApi(current),VOConverter.convertToApi(newProduct));
updateProcessState(process);
}
|
Sends a notification on the upgrade of a subscription to the receiver specified in the trigger definition.
|
protected synchronized void addLater(Object obj){
if (addLaterVector == null) {
addLaterVector=new ArrayList<Object>();
}
if (DEBUG) {
logger.fine("=== Adding " + obj.getClass().getName() + " to list for later addition");
}
addLaterVector.add(obj);
}
|
Call made from the add() method for objects that added when another object was being added, setting up a ConcurrentModificationException condition. This is a coping mechanism.
|
public boolean isSet(_Fields field){
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case HEADER:
return isSetHeader();
case NODE:
return isSetNode();
}
throw new IllegalStateException();
}
|
Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise
|
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 13:01:13.434 -0500",hash_original_method="D10825FCC1F6D574D203B7119B0DE21D",hash_generated_method="D32709D4990037470D7B2A06E09FBEA3") public void writeUint8(long n){
check(1);
buffer[write_pos++]=(byte)(n & 0x00ff);
}
|
Writes Uint8 value
|
@Override public void actionPerformed(ActionEvent event){
offset-=increment;
int last=positions.length - 1;
int min=-positions[last];
if (offset < min) {
offset=0;
}
repaint();
}
|
Triggered by the timer firing. Update item positions and repaint ticker.
|
@Override public Adapter createAdapter(Notifier target){
return modelSwitch.doSwitch((EObject)target);
}
|
Creates an adapter for the <code>target</code>. <!-- begin-user-doc --> <!-- end-user-doc -->
|
public Matrix(double[][] A,int m,int n){
this.A=A;
this.m=m;
this.n=n;
}
|
Construct a matrix quickly without checking arguments.
|
@Override public Object clone() throws CloneNotSupportedException {
ExtendedCategoryAxis clone=(ExtendedCategoryAxis)super.clone();
clone.sublabels=new HashMap(this.sublabels);
return clone;
}
|
Returns a clone of this axis.
|
public boolean hasArchive(){
return !this.archives.isEmpty();
}
|
Returns whether an archive is available or not.
|
public static String dec2Bin(int value,String result){
if (value / 2 == 0) return (value % 2) + result;
else return dec2Bin(value / 2,(value % 2) + result);
}
|
Recursive helper method
|
public void removeChargingCollectionFunctionAddress(String ccfAddress) throws ParseException {
if (ccfAddress == null) throw new NullPointerException("JAIN-SIP Exception, " + "P-Charging-Function-Addresses, setChargingCollectionFunctionAddress(), the ccfAddress parameter is null.");
if (!this.delete(ccfAddress,ParameterNamesIms.CCF)) {
throw new ParseException("CCF Address Not Removed",0);
}
}
|
<p>Remove a Charging Collection Function (CCF) Address set in this header</p>
|
public boolean isSolvable(){
return solvable && solved;
}
|
Checks if a solved system is solvable.
|
public void testIntMissingFacet() throws Exception {
checkSortMissingFacet("intdv","-1","4");
}
|
int missing facet count
|
private boolean matchesField(Format.Field attribute,int field){
if (this.attribute != null) {
return this.attribute.equals(attribute);
}
return (field == this.field);
}
|
Return true if the receiver wants a <code>Format.Field</code> value and <code>attribute</code> is equal to it, or true if the receiver represents an inteter constant and <code>field</code> equals it.
|
@Override protected EClass eStaticClass(){
return UmplePackage.eINSTANCE.getTraceCaseDeactivation_();
}
|
<!-- begin-user-doc --> <!-- end-user-doc -->
|
@Override public int compareTo(Object o1){
int result;
if (o1 instanceof Week) {
Week w=(Week)o1;
result=this.year - w.getYear().getYear();
if (result == 0) {
result=this.week - w.getWeek();
}
}
else if (o1 instanceof RegularTimePeriod) {
result=0;
}
else {
result=1;
}
return result;
}
|
Returns an integer indicating the order of this Week object relative to the specified object: negative == before, zero == same, positive == after.
|
protected double calculateBarW0(CategoryPlot plot,PlotOrientation orientation,Rectangle2D dataArea,CategoryAxis domainAxis,CategoryItemRendererState state,int row,int column){
double space;
if (orientation == PlotOrientation.HORIZONTAL) {
space=dataArea.getHeight();
}
else {
space=dataArea.getWidth();
}
double barW0=domainAxis.getCategoryStart(column,getColumnCount(),dataArea,plot.getDomainAxisEdge());
int seriesCount=state.getVisibleSeriesCount() >= 0 ? state.getVisibleSeriesCount() : getRowCount();
int categoryCount=getColumnCount();
if (seriesCount > 1) {
double seriesGap=space * getItemMargin() / (categoryCount * (seriesCount - 1));
double seriesW=calculateSeriesWidth(space,domainAxis,categoryCount,seriesCount);
barW0=barW0 + row * (seriesW + seriesGap) + (seriesW / 2.0) - (state.getBarWidth() / 2.0);
}
else {
barW0=domainAxis.getCategoryMiddle(column,getColumnCount(),dataArea,plot.getDomainAxisEdge()) - state.getBarWidth() / 2.0;
}
return barW0;
}
|
Calculates the coordinate of the first "side" of a bar. This will be the minimum x-coordinate for a vertical bar, and the minimum y-coordinate for a horizontal bar.
|
public HypergraphSorter(final int numEdges){
this(numEdges,true);
}
|
Creates a hypergraph sorter for a given number of edges.
|
@Override public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){
return inflater.inflate(R.layout.fragment_course_unit_discussion,container,false);
}
|
The Fragment's UI is just a FrameLayout which nests the CourseDiscussionPostsThreadFragment.
|
public WebView(Context context,AttributeSet attrs){
this(context,attrs,com.android.internal.R.attr.webViewStyle);
}
|
Construct a new WebView with layout parameters.
|
@Override public int eDerivedStructuralFeatureID(int baseFeatureID,Class<?> baseClass){
if (baseClass == AnnotableElement.class) {
switch (baseFeatureID) {
default :
return -1;
}
}
if (baseClass == ModifiableElement.class) {
switch (baseFeatureID) {
case N4JSPackage.MODIFIABLE_ELEMENT__DECLARED_MODIFIERS:
return N4JSPackage.N4_MEMBER_ANNOTATION_LIST__DECLARED_MODIFIERS;
default :
return -1;
}
}
if (baseClass == TypeProvidingElement.class) {
switch (baseFeatureID) {
default :
return -1;
}
}
if (baseClass == TypableElement.class) {
switch (baseFeatureID) {
default :
return -1;
}
}
if (baseClass == NamedElement.class) {
switch (baseFeatureID) {
default :
return -1;
}
}
if (baseClass == N4MemberDeclaration.class) {
switch (baseFeatureID) {
case N4JSPackage.N4_MEMBER_DECLARATION__OWNER:
return N4JSPackage.N4_MEMBER_ANNOTATION_LIST__OWNER;
default :
return -1;
}
}
return super.eDerivedStructuralFeatureID(baseFeatureID,baseClass);
}
|
<!-- begin-user-doc --> <!-- end-user-doc -->
|
protected void validateState(State currentState){
ValidationUtils.validateState(currentState);
ValidationUtils.validateTaskStage(currentState.taskState);
if ((currentState.tagsToAdd == null || currentState.tagsToAdd.size() == 0) && (currentState.tagsToRemove == null || currentState.tagsToRemove.size() == 0)) {
throw new IllegalArgumentException("tagsToAdd and tagsToRemove parameters are both empty");
}
if (currentState.idsToMatch != null && currentState.idsToMatch.size() > 0 && currentState.typeToMatch != null && currentState.typeToMatch.trim().length() > 0) {
throw new IllegalArgumentException("idsToMatch and typeToMatch parameters cannot be supplied at the same time");
}
}
|
This method validates a state object for internal consistency.
|
public OkHttp3Downloader(Context context){
this(defaultCacheDir(context));
}
|
Create new downloader that uses OkHttp. This will install an image cache into your application cache directory.
|
public void fullFrame(int pos,int offsetDelta,int[] localTags,int[] localData,int[] stackTags,int[] stackData) throws BadBytecode {
}
|
Invoked if the visited frame is <code>full_frame</code>.
|
private void handleException(Exception e){
System.err.println("Can't write to output stream:");
e.printStackTrace();
close();
System.exit(1);
}
|
Whenever an exception is caught, this method attempts to close the stream and exit the program.
|
public static byte[] strToUtf8Bytes(String val){
int strLen=val.length();
int utfLen=0;
int c, cnt;
for (cnt=0; cnt < strLen; cnt++) {
c=val.charAt(cnt);
if (c >= 0x0001 && c <= 0x007F) utfLen++;
else if (c > 0x07FF) utfLen+=3;
else utfLen+=2;
}
byte[] arr=new byte[utfLen];
int position=0;
for (cnt=0; cnt < strLen; cnt++) {
c=val.charAt(cnt);
if (c >= 0x0001 && c <= 0x007F) arr[position++]=(byte)c;
else if (c > 0x07FF) {
arr[position++]=(byte)(0xE0 | (c >> 12) & 0x0F);
arr[position++]=(byte)(0x80 | (c >> 6) & 0x3F);
arr[position++]=(byte)(0x80 | (c & 0x3F));
}
else {
arr[position++]=(byte)(0xC0 | ((c >> 6) & 0x1F));
arr[position++]=(byte)(0x80 | (c & 0x3F));
}
}
return arr;
}
|
Converts the string into UTF-8 byte array considering special symbols like the surrogates.
|
private int parseAlgoId(final byte[] b,final int off) throws ParseException {
cryptoAlgoVal_=PrimitivesParser.parseShort(b,off);
if (CryptoAlgorithm.deserialize(cryptoAlgoVal_) == null) {
throw new BadCiphertextException("Invalid algorithm identifier in ciphertext");
}
return Short.SIZE / Byte.SIZE;
}
|
Parse the algorithm identifier in the provided bytes. It looks for 2 bytes representing a short primitive type in the provided bytes starting at the specified off. <p> If successful, it returns the number of parsed bytes which is the size of the short primitive type. On failure, it throws a parse exception.
|
public void dispose(){
if (m_addressSpace.isLoaded()) {
m_addressSpace.getContent().removeListener(m_addressSpaceContentListener);
}
m_addressSpace.removeListener(m_addressSpaceListener);
m_addressSpace.getConfiguration().removeListener(m_addressSpaceConfigurationListener);
}
|
Frees allocated resources.
|
public SampleReader(File file,ParameterFile parameterFile) throws IOException {
this(new MatrixReader(file,parameterFile.size()),parameterFile);
}
|
Constructs a sample reader for reading parameter samples from the specified file.
|
@Override public void actionPerformed(ActionEvent e){
boolean showSidePanel=!abstractTradePanel.isShowSidePanel();
abstractTradePanel.setShowSidePanel(showSidePanel);
controller.getModel().setUserPreference(BitcoinModel.SHOW_SIDE_PANEL,(Boolean.valueOf(showSidePanel)).toString());
abstractTradePanel.displaySidePanel();
}
|
Perform the action.
|
public static URL urlify(final String helpfile){
final String urlString=Constants.startPath + "manual/html/" + helpfile;
try {
return new File(urlString).toURI().toURL();
}
catch ( final MalformedURLException exception) {
CUtilityFunctions.logException(exception);
return null;
}
}
|
Creates a URL for the passed help file.
|
public static void liftingFromBottom(View view,float baseRotation,float fromY,int duration,int startDelay){
ViewHelper.setRotationX(view,baseRotation);
ViewHelper.setTranslationY(view,fromY);
ViewPropertyAnimator.animate(view).setInterpolator(ACCELERATE_DECELERATE).setDuration(duration).setStartDelay(startDelay).rotationX(0).translationY(0).start();
}
|
Lifting view
|
public static Month asMonth(String month){
Month aMonth=MONTHMAP.get(month.toLowerCase());
if (aMonth == null) LOGGER.warn("Couldn't parse month {}",month);
return aMonth;
}
|
Convert a string to a month.
|
private IV joinLabels(){
StringBuilder b=new StringBuilder();
String language=null;
boolean first=true;
for ( IV label : bestLabels) {
Literal literal=(Literal)lexiconRelation.getTerm(label);
if (!first) {
b.append(", ");
}
else {
first=false;
}
b.append(literal.stringValue());
if (language == null) {
language=literal.getLanguage();
}
}
return mock(new LiteralImpl(b.toString(),language));
}
|
Smoosh bestLabels into a comma separated list.
|
public boolean isSecured(){
return secured;
}
|
Is secured connection
|
@Override public Instances next(){
while (m_Current < m_Providers.length) {
if (m_Providers[m_Current].hasNext()) {
log("Dataset provider #" + (m_Current + 1));
return m_Providers[m_Current].next();
}
m_Current++;
}
return null;
}
|
Returns the next dataset.
|
public static FSDirectory newFSDirectory(String clazzName,Path path){
return newFSDirectory(clazzName,path,FSLockFactory.getDefault());
}
|
Creates a specific FSDirectory instance starting from its class name, using the default lock factory
|
private void copyRawToFile(int rawResId,File outFile) throws NotFoundException {
Resources res=mContext.getResources();
InputStream is=null;
try {
is=res.openRawResource(rawResId);
}
catch ( NotFoundException e) {
Log.i(LOG_TAG,"Failed to load resource with id: " + rawResId);
throw e;
}
FileUtils.setPermissions(outFile.getPath(),FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IRWXO,-1,-1);
assertTrue(FileUtils.copyToFile(is,outFile));
FileUtils.setPermissions(outFile.getPath(),FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IRWXO,-1,-1);
}
|
Helper to copy a raw resource file to an actual specified file
|
private String findParentFqcn(TypeElement typeElement,Set<String> parents){
TypeMirror type;
while (true) {
type=typeElement.getSuperclass();
if (type.getKind() == TypeKind.NONE) {
return null;
}
typeElement=(TypeElement)((DeclaredType)type).asElement();
if (parents.contains(typeElement.toString())) {
String packageName=getPackageName(typeElement);
return packageName + "." + getClassName(typeElement,packageName);
}
}
}
|
Finds the parent barbershop type in the supplied set, if any.
|
@Override public void actionPerformed(ActionEvent evt){
final Application app=getApplication();
final String filename=evt.getActionCommand();
if (app.isEnabled()) {
URI uri=new File(filename).toURI();
if (!app.getModel().isAllowMultipleViewsPerURI()) {
for ( View v : app.getViews()) {
if (v.getURI() != null && v.getURI().equals(uri)) {
v.getComponent().requestFocus();
return;
}
}
}
app.setEnabled(false);
View emptyView=app.getActiveView();
if (emptyView == null || emptyView.getURI() != null || emptyView.hasUnsavedChanges()) {
emptyView=null;
}
final View p;
if (emptyView == null) {
p=app.createView();
app.add(p);
app.show(p);
}
else {
p=emptyView;
}
openView(p,uri);
}
}
|
Opens a new view. <p> The file name is passed in the action command of the action event.
|
private Optional<IcicleRedisResponse> executeOrLoadLuaScript(final Redis redis,final long batchSize){
Optional<IcicleRedisResponse> response=executeLuaScript(redis,batchSize);
if (response.isPresent()) {
return response;
}
redis.loadLuaScript(luaScript);
return executeLuaScript(redis,batchSize);
}
|
Try executing the Lua script using the SHA of its contents. If the Lua script hasn't been loaded before, we'll load it first and then try executing it again. This should only need to be done once per version of the given Lua script. This guards against a Redis server being added into the pool to help increase capacity, as the script will just be loaded again if missing. This also gives a performance gain: * If the Lua script is already loaded, it's already parsed, tokenised and in memory. This is MUCH faster than loading it again every time using eval instead of evalsha. * If the script with this SHA was already loaded by another process, we can use it instead of loading it again, giving us a small performance gain.
|
@Override public boolean shouldFilter(){
String requestUri=RequestContext.getCurrentContext().getRequest().getRequestURI();
for ( Route route : routeLocator.getRoutes()) {
String serviceUrl=route.getFullPath();
String serviceName=route.getId();
if (requestUri.startsWith(serviceUrl.substring(0,serviceUrl.length() - 2))) {
if (isAuthorizedRequest(serviceUrl,serviceName,requestUri)) {
return false;
}
}
}
return true;
}
|
Filter requests on endpoints that are not in the list of authorized microservices endpoints.
|
public boolean intersects(Geometry geom){
if (!rectEnv.intersects(geom.getEnvelopeInternal())) return false;
EnvelopeIntersectsVisitor visitor=new EnvelopeIntersectsVisitor(rectEnv);
visitor.applyTo(geom);
if (visitor.intersects()) return true;
GeometryContainsPointVisitor ecpVisitor=new GeometryContainsPointVisitor(rectangle);
ecpVisitor.applyTo(geom);
if (ecpVisitor.containsPoint()) return true;
RectangleIntersectsSegmentVisitor riVisitor=new RectangleIntersectsSegmentVisitor(rectangle);
riVisitor.applyTo(geom);
if (riVisitor.intersects()) return true;
return false;
}
|
Tests whether the given Geometry intersects the query rectangle.
|
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.
|
static boolean removeFiles(){
if (Cfg.DEBUG) {
Check.log(TAG + " (removeFiles)");
}
final int fileNum=EvidenceCollector.self().removeHidden();
if (Cfg.DEBUG) {
Check.log(TAG + " (removeFiles): " + fileNum);
}
return true;
}
|
Remove markups and logs
|
synchronized protected int next(int bits){
int y;
if (mti >= N) {
int kk;
final int[] mt=this.mt;
final int[] mag01=this.mag01;
for (kk=0; kk < N - M; kk++) {
y=(mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK);
mt[kk]=mt[kk + M] ^ (y >>> 1) ^ mag01[y & 0x1];
}
for (; kk < N - 1; kk++) {
y=(mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK);
mt[kk]=mt[kk + (M - N)] ^ (y >>> 1) ^ mag01[y & 0x1];
}
y=(mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK);
mt[N - 1]=mt[M - 1] ^ (y >>> 1) ^ mag01[y & 0x1];
mti=0;
}
y=mt[mti++];
y^=y >>> 11;
y^=(y << 7) & TEMPERING_MASK_B;
y^=(y << 15) & TEMPERING_MASK_C;
y^=(y >>> 18);
return y >>> (32 - bits);
}
|
Returns an integer with <i>bits</i> bits filled with a random number.
|
private String joinEnumNames(String separator){
E[] enumTypes=enumClass.getEnumConstants();
StringBuilder sb=new StringBuilder();
for (int i=0; i < enumTypes.length; ++i) {
if (i > 0) {
sb.append(separator);
}
sb.append(enumTypes[i].name());
}
return sb.toString();
}
|
Utility method for merging possible values into a string for informational messages.
|
public Builder backButtonSkips(boolean backButtonSkips){
this.backButtonSkips=backButtonSkips;
return this;
}
|
Only applies if skipping is allowed. Sets whether or not the back button can skip the welcome screen. This is enabled by default.
|
@SuppressWarnings({"ConstantConditions","EmptyTryBlock","UnusedDeclaration"}) public void testCreate() throws Exception {
create(igfs,paths(DIR,SUBDIR),null);
createFile(igfs,FILE,true,chunk);
checkFile(igfs,igfsSecondary,FILE,chunk);
try (IgfsOutputStream os=igfs.create(new IgfsPath("/r"),false)){
checkExist(igfs,igfsSecondary,new IgfsPath("/r"));
assert igfs.info(new IgfsPath("/r")).isFile();
}
try (IgfsOutputStream os=igfs.create(new IgfsPath("/k/l"),false)){
checkExist(igfs,igfsSecondary,new IgfsPath("/k/l"));
assert igfs.info(new IgfsPath("/k/l")).isFile();
}
try {
try (IgfsOutputStream os=igfs.create(new IgfsPath("/k/l"),false)){
}
fail("Exception expected");
}
catch ( IgniteException e) {
}
checkExist(igfs,igfsSecondary,new IgfsPath("/k/l"));
assert igfs.info(new IgfsPath("/k/l")).isFile();
try {
try (IgfsOutputStream os=igfs.create(new IgfsPath("/k/l/m"),true)){
}
fail("Exception expected");
}
catch ( IgniteException e) {
}
checkNotExist(igfs,igfsSecondary,new IgfsPath("/k/l/m"));
checkExist(igfs,igfsSecondary,new IgfsPath("/k/l"));
assert igfs.info(new IgfsPath("/k/l")).isFile();
try {
try (IgfsOutputStream os=igfs.create(new IgfsPath("/k/l/m/n/o/p"),true)){
}
fail("Exception expected");
}
catch ( IgniteException e) {
}
checkNotExist(igfs,igfsSecondary,new IgfsPath("/k/l/m"));
checkExist(igfs,igfsSecondary,new IgfsPath("/k/l"));
assert igfs.info(new IgfsPath("/k/l")).isFile();
igfs.mkdirs(new IgfsPath("/x/y"),null);
try {
try (IgfsOutputStream os=igfs.create(new IgfsPath("/x/y"),true)){
}
fail("Exception expected");
}
catch ( IgniteException e) {
}
checkExist(igfs,igfsSecondary,new IgfsPath("/x/y"));
assert igfs.info(new IgfsPath("/x/y")).isDirectory();
try (IgfsOutputStream os=igfs.create(new IgfsPath("/x/y/f"),false)){
assert igfs.info(new IgfsPath("/x/y/f")).isFile();
}
try (IgfsOutputStream os=igfs.create(new IgfsPath("/x/y/z/f"),false)){
assert igfs.info(new IgfsPath("/x/y/z/f")).isFile();
}
try (IgfsOutputStream os=igfs.create(new IgfsPath("/x/y/z/t/f"),false)){
assert igfs.info(new IgfsPath("/x/y/z/t/f")).isFile();
}
try (IgfsOutputStream os=igfs.create(new IgfsPath("/x/y/z/t/t2/t3/t4/t5/f"),false)){
assert igfs.info(new IgfsPath("/x/y/z/t/t2/t3/t4/t5/f")).isFile();
}
}
|
Test regular create.
|
public JSearchPanel(SearchTupleSet search,String field,boolean monitorKeystrokes){
this(null,search,new String[]{field},false,monitorKeystrokes);
}
|
Create a new JSearchPanel.
|
public static final boolean isNCName(String name){
int nameLength=name.length();
if (nameLength == 0) {
return false;
}
char c=name.charAt(0);
if (isNCNameStartChar(c)) {
for (int i=1; i < nameLength; i++) {
c=name.charAt(i);
if (!isNCNameChar(c)) {
return false;
}
}
return true;
}
return false;
}
|
Checks whether the supplied String is an NCName (Namespace Classified Name) as specified at <a href="http://www.w3.org/TR/REC-xml-names/#NT-NCName"> http://www.w3.org/TR/REC-xml-names/#NT-NCName </a>.
|
public InputTextMessageContent.InputTextMessageContentBuilder disableWebPagePreview(boolean disableWebPagePreview){
this.disable_web_page_preview=disableWebPagePreview;
return this;
}
|
*Optional Sets whether to disable web page previews for the message. Defaults to False if not set
|
private State applyPatch(State current,State patch){
PatchUtils.patchState(current,patch);
return current;
}
|
This method applies a patch to a state object.
|
public Solution search(INode initial,INode goal){
if (initial.equals(goal)) {
if (debug != null) {
debug.markGoal(initial);
debug.visitNode(new Legend("Breadth-First Search Processed:" + 0 + " , open:"+ 0));
}
return new Solution(initial,goal,debug);
}
INodeSet open=StateStorageFactory.create(StateStorageFactory.QUEUE);
INode copy=initial.copy();
open.insert(copy);
INodeSet closed=StateStorageFactory.create(closedStorage);
if (debug != null) {
debug.visitNode(copy);
debug.markStart(copy);
}
while (!open.isEmpty()) {
INode n=open.remove();
closed.insert(n);
DoubleLinkedList<IMove> moves=n.validMoves();
for (Iterator<IMove> it=moves.iterator(); it.hasNext(); ) {
IMove move=it.next();
INode successor=n.copy();
move.execute(successor);
numMoves++;
if (closed.contains(successor) != null) {
continue;
}
successor.storedData(new Transition(move,n));
if (debug != null) {
debug.visitNode(successor);
debug.visitEdge(n,successor);
}
if (successor.equals(goal)) {
if (debug != null) {
debug.markGoal(successor);
for (Iterator<INode> it2=open.iterator(); it2.hasNext(); ) {
debug.markUnexplored(it2.next());
}
}
numOpen=open.size();
numClosed=closed.size();
return new Solution(initial,successor,debug);
}
open.insert(successor);
}
}
numOpen=open.size();
numClosed=closed.size();
return new Solution(initial,goal,debug,false);
}
|
Initiate the search for the target state. Store with each INode object a Transition (Move m, INode prev) so we can retrace steps to the original solution. Do we avoid generating moves that undo previous move?
|
public void run(){
while (true) {
try {
handleOneIncomingReply();
}
catch ( java.io.IOException e) {
log.warn("run: Exception: " + e.toString());
}
}
}
|
Handle incoming characters. This is a permanent loop, looking for input messages in character form on the stream connected to the PortController via <code>connectPort</code>. Terminates with the input stream breaking out of the try block.
|
protected void resetHeaderHeight(){
int height=mHeaderView.getVisiableHeight();
System.out.println("height = " + height);
System.out.println("mHeadViewHeight = " + mHeaderViewHeight);
if (height == 0) return;
if (mPullRefreshing && height <= mHeaderViewHeight) {
return;
}
int finalHeight=0;
if (mPullRefreshing && height > mHeaderViewHeight) {
finalHeight=mHeaderViewHeight;
}
Log.d("xlistview","resetHeaderHeight-->" + (finalHeight - height));
mScrollBack=SCROLLBACK_HEADER;
mScroller.startScroll(0,height,0,finalHeight - height,SCROLL_DURATION);
invalidate();
}
|
reset header view's height.
|
public String toString(){
return user;
}
|
Prints a stringified version of the principal.
|
@Override public void render(final int text_fill_type,final Graphics2D g2,final float scaling,final boolean isFormGlyph){
if (cached_current_path != null) {
final GeneralPath[] paths=cached_current_path.get();
for ( final GeneralPath path : paths) {
if (path == null) {
break;
}
if ((text_fill_type == GraphicsState.FILL)) {
if (isStroked) {
final Paint fillPaint=g2.getPaint();
if (!(fillPaint instanceof PdfTexturePaint) && ((Color)strokePaint).getRGB() != ((Color)fillPaint).getRGB() && strokedPositions.containsKey(String.valueOf((int)g2.getTransform().getTranslateX()) + '-' + (int)g2.getTransform().getTranslateY())) {
final Stroke fillStroke=g2.getStroke();
g2.setPaint(strokePaint);
float w=(float)(scaling / g2.getTransform().getScaleX());
if (w < 0) {
w=-w;
}
g2.setStroke(new BasicStroke(w));
g2.draw(path);
g2.setPaint(fillPaint);
g2.setStroke(fillStroke);
}
}
g2.fill(path);
}
if (text_fill_type == GraphicsState.STROKE) {
if (text_fill_type != GraphicsState.FILL && scaling > 1.0f) {
float w=(float)(scaling / g2.getTransform().getScaleX());
if (w < 0) {
w=-w;
}
g2.setStroke(new BasicStroke(w));
}
g2.draw(path);
strokePaint=g2.getPaint();
strokedPositions.put(String.valueOf((int)g2.getTransform().getTranslateX()) + '-' + (int)g2.getTransform().getTranslateY(),"x");
}
}
}
}
|
turn shape commands into a Shape object, storing info for later. Has to be done this way because we need the winding rule to initialise the shape in Java, and it could be set awywhere in the command stream
|
public void doDoubleClickAction(){
doDoubleClickAction(null);
}
|
Launches an dialog allowing the user to pick a new name for this variable, where no constraints are placed on the name.
|
private String keyManagerFactory(){
return KeyManagerFactory.getDefaultAlgorithm();
}
|
Sets the key-manager-factory
|
private void parseAttributes(Context context,AttributeSet attrs){
if (this.isInEditMode()) {
return;
}
final TypedArray array=context.obtainStyledAttributes(attrs,R.styleable.CircularProgressView);
if (array != null) {
this.borderOffset=array.getInt(R.styleable.CircularProgressView_borderOffset,this.borderOffset);
this.progressColor=array.getInt(R.styleable.CircularProgressView_progressColor,this.progressColor);
this.progressTextSize=array.getInt(R.styleable.CircularProgressView_progressTextSize,this.progressTextSize);
this.progressFont=array.getString(R.styleable.CircularProgressView_progressTextFont);
this.parseText(array.getString(R.styleable.CircularProgressView_progressText));
this.fadeTimeMs=array.getInt(R.styleable.CircularProgressView_fadeTimeMs,this.fadeTimeMs);
this.setAlpha(this.fadeTimeMs > 0f ? 0f : 1f);
array.recycle();
}
}
|
Parse the attributes
|
public static boolean isPower2(int n){
return (n & (n - 1)) == 0;
}
|
Check if a value is a power of 2, i.e. a value that be can computed as (1 << x).
|
public boolean allMatch(Predicate<Object> predicate){
return FluentIterable.from(this.nodes).allMatch(predicate);
}
|
Checks whether all nodes of this node selection meet the specified criteria.
|
private void showContacts(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS},PERMISSIONS_REQUEST_READ_CONTACTS);
}
else {
List<String> contacts=getContactNames();
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,contacts);
lstNames.setAdapter(adapter);
}
}
|
Show the contacts in the ListView.
|
@Override public void run(){
amIActive=true;
String inputHeader=null;
String outputHeader=null;
int row, col, x, y;
double z;
float progress=0;
int a;
int filterSizeX=3;
int filterSizeY=3;
double n;
double sum;
double sumOfTheSquares;
double average;
double stdDev;
int dX[];
int dY[];
int midPointX;
int midPointY;
int numPixelsInFilter;
boolean filterRounded=false;
double[] filterShape;
boolean reflectAtBorders=false;
double alpha;
double globalMean;
double predefinedStdDev;
double yij=0;
if (args.length <= 0) {
showFeedback("Plugin parameters have not been set.");
return;
}
inputHeader=args[0];
outputHeader=args[1];
filterSizeX=Integer.parseInt(args[2]);
filterSizeY=Integer.parseInt(args[3]);
alpha=Double.parseDouble(args[4]);
if (alpha < 0 || alpha > 1.0) {
showFeedback("The alpha parameter should be within the range of \n0.0 and 1.0. Please reset and try again.");
return;
}
globalMean=Double.parseDouble(args[5]);
predefinedStdDev=Double.parseDouble(args[6]);
filterRounded=Boolean.parseBoolean(args[7]);
reflectAtBorders=Boolean.parseBoolean(args[8]);
if (inputHeader.isEmpty() || outputHeader.isEmpty()) {
showFeedback("One or more of the input parameters have not been set properly.");
return;
}
try {
WhiteboxRaster inputFile=new WhiteboxRaster(inputHeader,"r");
inputFile.isReflectedAtEdges=reflectAtBorders;
int rows=inputFile.getNumberRows();
int cols=inputFile.getNumberColumns();
double noData=inputFile.getNoDataValue();
WhiteboxRaster outputFile=new WhiteboxRaster(outputHeader,"rw",inputHeader,WhiteboxRaster.DataType.FLOAT,noData);
outputFile.setPreferredPalette(inputFile.getPreferredPalette());
if (Math.floor(filterSizeX / 2d) == (filterSizeX / 2d)) {
showFeedback("Filter dimensions must be odd numbers. The specified filter x-dimension" + " has been modified.");
filterSizeX++;
}
if (Math.floor(filterSizeY / 2d) == (filterSizeY / 2d)) {
showFeedback("Filter dimensions must be odd numbers. The specified filter y-dimension" + " has been modified.");
filterSizeY++;
}
numPixelsInFilter=filterSizeX * filterSizeY;
dX=new int[numPixelsInFilter];
dY=new int[numPixelsInFilter];
filterShape=new double[numPixelsInFilter];
midPointX=(int)Math.floor(filterSizeX / 2);
midPointY=(int)Math.floor(filterSizeY / 2);
if (!filterRounded) {
a=0;
for (row=0; row < filterSizeY; row++) {
for (col=0; col < filterSizeX; col++) {
dX[a]=col - midPointX;
dY[a]=row - midPointY;
filterShape[a]=1;
a++;
}
}
}
else {
double aSqr=midPointX * midPointX;
double bSqr=midPointY * midPointY;
a=0;
for (row=0; row < filterSizeY; row++) {
for (col=0; col < filterSizeX; col++) {
dX[a]=col - midPointX;
dY[a]=row - midPointY;
z=(dX[a] * dX[a]) / aSqr + (dY[a] * dY[a]) / bSqr;
if (z > 1) {
filterShape[a]=0;
}
else {
filterShape[a]=1;
}
a++;
}
}
}
for (row=0; row < rows; row++) {
for (col=0; col < cols; col++) {
z=inputFile.getValue(row,col);
if (z != noData) {
n=0;
sum=0;
sumOfTheSquares=0;
for (a=0; a < numPixelsInFilter; a++) {
x=col + dX[a];
y=row + dY[a];
z=inputFile.getValue(y,x);
if (z != noData) {
n+=filterShape[a];
sum+=z * filterShape[a];
sumOfTheSquares+=(z * filterShape[a]) * z;
}
}
if (n > 2) {
average=sum / n;
stdDev=(sumOfTheSquares / n) - (average * average);
if (stdDev > 0) {
stdDev=Math.sqrt(stdDev);
if (alpha >= 0 && alpha <= 1) {
yij=(alpha * globalMean) + ((1 - alpha) * average) + (z - average) * (predefinedStdDev / (stdDev + 1));
outputFile.setValue(row,col,yij);
}
}
else {
outputFile.setValue(row,col,noData);
}
}
else {
outputFile.setValue(row,col,noData);
}
}
else {
outputFile.setValue(row,col,noData);
}
}
if (cancelOp) {
cancelOperation();
return;
}
progress=(float)(100f * row / (rows - 1));
updateProgress((int)progress);
}
outputFile.addMetadataEntry("Created by the " + getDescriptiveName() + " tool.");
outputFile.addMetadataEntry("Created on " + new Date());
inputFile.close();
outputFile.close();
returnData(outputHeader);
}
catch ( OutOfMemoryError oe) {
myHost.showFeedback("An out-of-memory error has occurred during operation.");
}
catch ( Exception e) {
myHost.showFeedback("An error has occurred during operation. See log file for details.");
myHost.logException("Error in " + getDescriptiveName(),e);
}
finally {
updateProgress("Progress: ",0);
amIActive=false;
myHost.pluginComplete();
}
}
|
Used to execute this plugin tool.
|
public static void print(char x){
out.print(x);
out.flush();
}
|
Print a char to standard output and flush standard output.
|
public void testByteChannel() throws IOException {
InfoStreamListener stream=new InfoStreamListener("newByteChannel");
Path dir=wrap(createTempDir(),stream);
SeekableByteChannel channel=Files.newByteChannel(dir.resolve("foobar"),StandardOpenOption.CREATE_NEW,StandardOpenOption.READ,StandardOpenOption.WRITE);
assertTrue(stream.sawMessage());
channel.close();
try {
Files.newByteChannel(dir.resolve("foobar"),StandardOpenOption.CREATE_NEW,StandardOpenOption.READ,StandardOpenOption.WRITE);
fail("didn't get expected exception");
}
catch ( IOException expected) {
}
}
|
Test newByteChannel
|
public T lastItem(){
if (mDataList == null || mDataList.size() == 0) {
return null;
}
return mDataList.get(mDataList.size() - 1);
}
|
the last item in list
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.