code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public SelectionColorChooserAction(DrawingEditor editor,AttributeKey<Color> key){
this(editor,key,null,null);
}
| Creates a new instance. |
@Override public void run(){
amIActive=true;
String inputHeader=null;
String outputHeader=null;
double slope;
double z, z2;
int c, i;
int progress;
int[] dY={-1,0,1,1,1,0,-1,-1};
int[] dX={1,1,1,0,-1,-1,-1,0};
int row, col, x, y;
double dist;
double maxSlope=0;
double maxZChange=0;
if (args.length <= 0) {
showFeedback("Plugin parameters have not been set.");
return;
}
for (i=0; i < args.length; i++) {
if (i == 0) {
inputHeader=args[i];
}
else if (i == 1) {
outputHeader=args[i];
}
}
if ((inputHeader == null) || (outputHeader == null)) {
showFeedback("One or more of the input parameters have not been set properly.");
return;
}
try {
WhiteboxRaster DEM=new WhiteboxRaster(inputHeader,"r");
DEM.isReflectedAtEdges=true;
int rows=DEM.getNumberRows();
int cols=DEM.getNumberColumns();
double noData=DEM.getNoDataValue();
double gridResX=DEM.getCellSizeX();
double gridResY=DEM.getCellSizeY();
double diagGridRes=Math.sqrt(gridResX * gridResX + gridResY * gridResY);
double[] gridLengths=new double[]{diagGridRes,gridResX,diagGridRes,gridResY,diagGridRes,gridResX,diagGridRes,gridResY};
WhiteboxRaster output=new WhiteboxRaster(outputHeader,"rw",inputHeader,WhiteboxRaster.DataType.FLOAT,noData);
output.setPreferredPalette("spectrum.pal");
for (row=0; row < rows; row++) {
for (col=0; col < cols; col++) {
z=DEM.getValue(row,col);
if (z != noData) {
maxSlope=-99999999;
for (c=0; c < 8; c++) {
x=col + dX[c];
y=row + dY[c];
dist=gridLengths[c];
z2=DEM.getValue(y,x);
if (z2 != noData) {
slope=(z - z2) / dist;
if (slope > maxSlope) {
maxSlope=slope;
maxZChange=z - z2;
}
}
}
if (maxSlope > 0) {
output.setValue(row,col,maxZChange);
}
else {
output.setValue(row,col,0);
}
}
else {
output.setValue(row,col,noData);
}
}
if (cancelOp) {
cancelOperation();
return;
}
progress=(int)(100f * row / (rows - 1));
updateProgress(progress);
}
output.addMetadataEntry("Created by the " + getDescriptiveName() + " tool.");
output.addMetadataEntry("Created on " + new Date());
DEM.close();
output.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. |
@Override protected final void parseArgs(String[] args) throws AdeException {
super.parseArgs(new Options(),args);
}
| Parse the input arguments |
protected void enableOtherNotifications(TransactionBuilder builder,boolean enable){
builder.notify(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_REALTIME_STEPS),enable).notify(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_SENSOR_DATA),enable);
}
| Enables or disables certain kinds of notifications that could interfere with this operation. Call this method once initially to disable other notifications, and once when this operation has finished. |
private void drawFirstAnimation(Canvas canvas){
if (radius1 < getWidth() / 2) {
Paint paint=new Paint();
paint.setAntiAlias(true);
paint.setColor(makePressColor());
radius1=(radius1 >= getWidth() / 2) ? (float)getWidth() / 2 : radius1 + 1;
canvas.drawCircle(getWidth() / 2,getHeight() / 2,radius1,paint);
}
else {
Bitmap bitmap=Bitmap.createBitmap(canvas.getWidth(),canvas.getHeight(),Bitmap.Config.ARGB_8888);
Canvas temp=new Canvas(bitmap);
Paint paint=new Paint();
paint.setAntiAlias(true);
paint.setColor(makePressColor());
temp.drawCircle(getWidth() / 2,getHeight() / 2,getHeight() / 2,paint);
Paint transparentPaint=new Paint();
transparentPaint.setAntiAlias(true);
transparentPaint.setColor(getResources().getColor(android.R.color.transparent));
transparentPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
if (cont >= 50) {
radius2=(radius2 >= getWidth() / 2) ? (float)getWidth() / 2 : radius2 + 1;
}
else {
radius2=(radius2 >= getWidth() / 2 - Utils.dpToPx(4,getResources())) ? (float)getWidth() / 2 - Utils.dpToPx(4,getResources()) : radius2 + 1;
}
temp.drawCircle(getWidth() / 2,getHeight() / 2,radius2,transparentPaint);
canvas.drawBitmap(bitmap,0,0,new Paint());
if (radius2 >= getWidth() / 2 - Utils.dpToPx(4,getResources())) cont++;
if (radius2 >= getWidth() / 2) firstAnimationOver=true;
}
}
| Draw first animation of view |
public void emitDirect(int taskId,Tuple anchor,List<Object> tuple){
emitDirect(taskId,Utils.DEFAULT_STREAM_ID,anchor,tuple);
}
| Emits a tuple directly to the specified task id on the default stream. If the target bolt does not subscribe to this bolt using a direct grouping, the tuple will not be sent. If the specified output stream is not declared as direct, or the target bolt subscribes with a non-direct grouping, an error will occur at runtime. The emitted values must be immutable. <p> <p>The default stream must be declared as direct in the topology definition. See OutputDeclarer#declare for how this is done when defining topologies in Java.</p> |
CSVReader(Reader reader,int line,CSVParser csvParser,boolean keepCR,boolean verifyReader){
this.br=(reader instanceof BufferedReader ? (BufferedReader)reader : new BufferedReader(reader,30720));
this.lineReader=new LineReader(br,keepCR);
this.skipLines=line;
this.parser=csvParser;
this.keepCR=keepCR;
this.verifyReader=verifyReader;
}
| Constructs CSVReader with supplied CSVParser. |
public static void addOsmiumCompressorRecipe(ItemStack input,ItemStack output){
try {
Class recipeClass=Class.forName("mekanism.common.recipe.RecipeHandler");
Method m=recipeClass.getMethod("addOsmiumCompressorRecipe",ItemStack.class,ItemStack.class);
m.invoke(null,input,output);
}
catch ( Exception e) {
System.err.println("Error while adding recipe: " + e.getMessage());
}
}
| Add an Osmium Compressor recipe. |
public void testPrintMessageBuilder() throws Exception {
String javaText=TextFormat.printToString(TestUtil.getAllSetBuilder());
javaText=javaText.replace(".0\n","\n");
assertEquals(allFieldsSetText,javaText);
}
| Print TestAllTypes as Builder and compare with golden file. |
@EventHandler(ignoreCancelled=true) public void onItemSpawn(ItemSpawnEvent event){
Match match=Cardinal.getMatch(event.getWorld());
MaterialData data=event.getEntity().getItemStack().getData();
for ( MaterialType type : materials.get(match)) {
if (type.isType(data)) {
event.setCancelled(true);
break;
}
}
}
| Prevent items from spawning if they are in the item-remove tag in XML. |
public boolean hasClauses(){
return !(mustClauses.isEmpty() && shouldClauses.isEmpty() && mustNotClauses.isEmpty()&& filterClauses.isEmpty());
}
| Returns <code>true</code> iff this query builder has at least one should, must, must not or filter clause. Otherwise <code>false</code>. |
public void start(@NonNull Context context,@NonNull Fragment fragment){
start(context,fragment,REQUEST_CROP);
}
| Send the crop Intent from a Fragment |
public static void checkIfSavable(final Process process) throws Exception {
for ( Operator operator : process.getAllOperators()) {
if (operator instanceof DummyOperator) {
throw new Exception("The process contains dummy operators. Remove all dummy operators or install all missing extensions in order to save the process.");
}
}
}
| Checks weather the process can be saved as is. Throws an Exception if the Process should not be saved. |
private static int decodeDigit(int[] counters) throws NotFoundException {
int bestVariance=MAX_AVG_VARIANCE;
int bestMatch=-1;
int max=PATTERNS.length;
for (int i=0; i < max; i++) {
int[] pattern=PATTERNS[i];
int variance=patternMatchVariance(counters,pattern,MAX_INDIVIDUAL_VARIANCE);
if (variance < bestVariance) {
bestVariance=variance;
bestMatch=i;
}
}
if (bestMatch >= 0) {
return bestMatch;
}
else {
throw NotFoundException.getNotFoundInstance();
}
}
| Attempts to decode a sequence of ITF black/white lines into single digit. |
@Override public void onClick(View v){
switch (v.getId()) {
case R.id.activity_create_widget_clock_day_week_doneButton:
SharedPreferences.Editor editor=getSharedPreferences(getString(R.string.sp_widget_clock_day_week_setting),MODE_PRIVATE).edit();
editor.putString(getString(R.string.key_location),location.location);
editor.putBoolean(getString(R.string.key_show_card),showCardSwitch.isChecked());
editor.putBoolean(getString(R.string.key_black_text),blackTextSwitch.isChecked());
editor.apply();
Intent intent=getIntent();
Bundle extras=intent.getExtras();
int appWidgetId=0;
if (extras != null) {
appWidgetId=extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,AppWidgetManager.INVALID_APPWIDGET_ID);
}
Intent resultValue=new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,appWidgetId);
setResult(RESULT_OK,resultValue);
Intent service=new Intent(this,WidgetClockDayWeekService.class);
startService(service);
finish();
break;
}
}
| <br> interface. |
public void testGenerateCertPath03() throws Exception {
String certPathEncoding="PkiPath";
CertificateFactory[] certFs=initCertFs();
assertNotNull("CertificateFactory objects were not created",certFs);
for (int i=0; i < certFs.length; i++) {
Iterator<String> it=certFs[0].getCertPathEncodings();
assertTrue("no CertPath encodings",it.hasNext());
assertEquals("Incorrect default encoding",certPathEncoding,it.next());
CertPath certPath=null;
InputStream fis=Support_Resources.getResourceStream(fileCertPathPki);
certPath=certFs[i].generateCertPath(fis);
fis.close();
assertEquals(defaultType,certPath.getType());
List<? extends Certificate> list1=certPath.getCertificates();
assertFalse("Result list is empty",list1.isEmpty());
}
}
| Test for <code>generateCertPath(InputStream inStream)</code> method Assertion: returns CertPath with 1 Certificate |
public void cancel(){
cancel=true;
}
| Call this method to cancel drag interaction. |
public boolean equals(JulianDate d){
return (julian == d.julian);
}
| Checks if the specified date is eual to this date. |
public void put(int key,int value){
int i=binarySearch(mKeys,0,mSize,key);
if (i >= 0) {
mValues[i]=value;
}
else {
i=~i;
if (mSize >= mKeys.length) {
int n=Math.max(mSize + 1,mKeys.length * 2);
int[] nkeys=new int[n];
int[] nvalues=new int[n];
System.arraycopy(mKeys,0,nkeys,0,mKeys.length);
System.arraycopy(mValues,0,nvalues,0,mValues.length);
mKeys=nkeys;
mValues=nvalues;
}
if (mSize - i != 0) {
System.arraycopy(mKeys,i,mKeys,i + 1,mSize - i);
System.arraycopy(mValues,i,mValues,i + 1,mSize - i);
}
mKeys[i]=key;
mValues[i]=value;
mSize++;
}
}
| Adds a mapping from the specified key to the specified value, replacing the previous mapping from the specified key if there was one. |
public List<RDOPaymentPreviewSummary> evaluateBillingResultForPaymentPreview(RDOSummary summaryTemplate,Document doc,PlatformUser user,PriceConverter formatter,Long paymentPreviewEndTime) throws XPathExpressionException, SQLException {
this.formatter=formatter;
this.document=doc;
return evaluateBillingResult(summaryTemplate,user,paymentPreviewEndTime);
}
| Evaluates a billing result and creates the corresponding data objects for payment preview report |
public TemplatePersistenceData(Template template,boolean enabled,String id){
Assert.isNotNull(template);
fOriginalTemplate=template;
fCustomTemplate=template;
fOriginalIsEnabled=enabled;
fCustomIsEnabled=enabled;
fId=id;
}
| Creates a new instance. If <code>id</code> is not <code>null</code>, the instance is represents a template that is contributed and can be identified via its id. |
public boolean equals(Object obj){
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
MessageFormat other=(MessageFormat)obj;
return (maxOffset == other.maxOffset && pattern.equals(other.pattern) && ((locale != null && locale.equals(other.locale)) || (locale == null && other.locale == null)) && Arrays.equals(offsets,other.offsets) && Arrays.equals(argumentNumbers,other.argumentNumbers) && Arrays.equals(formats,other.formats));
}
| Equality comparison between two message format objects |
public void putNull(String key){
mValues.put(key,null);
}
| Adds a null value to the set. |
public static void main(final String[] args){
DOMTestCase.doMain(elementsetattributens08.class,args);
}
| Runs this test from the command line. |
public boolean isIgnoringOrder(){
return _isIgnoringOrder;
}
| Gets IgnoringOrder flag. <p/> <br> This flag is used to determine if order in which elements occur in Golden <p/>and current Document is ignored |
public TenantDeletionConstraintException(String message){
super(message);
}
| Constructs a new exception with the specified detail message. The cause is not initialized. |
public void onClickPlaneta(View view){
Intent intent=new Intent(this,PlanetaActivity.class);
ActivityOptionsCompat opts=ActivityOptionsCompat.makeCustomAnimation(this,R.anim.slide_in_left,R.anim.slide_out_left);
ActivityCompat.startActivity(this,intent,opts.toBundle());
}
| Demonstra uma animacao customizada de entrada e saida |
public PriorityQueue(int initialCapacity){
this(initialCapacity,null);
}
| Constructs a priority queue with the specified capacity and natural ordering. |
public void deregisterPort(int port,IgnitePortProtocol proto,Class cls){
assert port > 0 && port < 65535;
assert proto != null;
assert cls != null;
synchronized (recs) {
for (Iterator<GridPortRecord> iter=recs.iterator(); iter.hasNext(); ) {
GridPortRecord pr=iter.next();
if (pr.port() == port && pr.protocol() == proto && pr.clazz().equals(cls)) iter.remove();
}
}
notifyListeners();
}
| Deregisters port used by passed class. |
public boolean isOverrides(MembershipRecord r0){
if (r0 == null) {
return true;
}
checkArgument(this.member.equals(r0.member),"Can't compare records for different members");
if (r0.status == DEAD) {
return false;
}
if (status == DEAD) {
return true;
}
if (incarnation == r0.incarnation) {
return (status != r0.status) && (status == SUSPECT);
}
else {
return incarnation > r0.incarnation;
}
}
| Checks either this record overrides given record. |
private void replaceTop(Scope topOfStack){
stack.set(stack.size() - 1,topOfStack);
}
| Replace the value on the top of the stack with the given value. |
@Override public void contextInitialized(ServletContextEvent event){
this.context=event.getServletContext();
log("contextInitialized()");
}
| Record the fact that this web application has been initialized. |
private void signIdToken(final ClientDetailsEntity client,final JWSAlgorithm signingAlg,final OAuth2AccessTokenEntity idTokenEntity,final JWTClaimsSet.Builder idClaims){
log.debug("Client {} is configured to ignore encryption",client.getClientId());
final JWT idToken;
if (signingAlg.equals(Algorithm.NONE)) {
idToken=new PlainJWT(idClaims.build());
log.debug("Client {} is configured to use an unsigned idToken",client.getClientId());
}
else {
if (signingAlg.equals(JWSAlgorithm.HS256) || signingAlg.equals(JWSAlgorithm.HS384) || signingAlg.equals(JWSAlgorithm.HS512)) {
idToken=signIdTokenForHs256Hs384Hs512(client,signingAlg,idClaims);
}
else {
idToken=signIdTokenWithDefaultService(client,signingAlg,idClaims);
}
}
idTokenEntity.setJwt(idToken);
}
| Sign id token. |
public ExitData(S source,S target){
this.source=source;
this.target=target;
}
| Instantiates a new exit data. |
private void removeMethodIfStupid(SootClass clz,SootMethod method){
boolean debug=false;
StmtBody stmtBody=null;
try {
stmtBody=(StmtBody)method.retrieveActiveBody();
}
catch ( Exception ex) {
logger.info("Exception retrieving method body {}",ex);
return;
}
if (debug) logger.debug("looking at method: {}",method);
Unit[] units=stmtBody.getUnits().toArray(new Unit[0]);
for (int i=0; i < units.length - 2; i++) if (!(units[i] instanceof JIdentityStmt)) {
if (debug) logger.debug("non identity: {}",units[i]);
return;
}
if (debug) logger.debug("Identity test pass");
boolean foundSpecialInvoke=false;
if (debug) logger.debug("invoke: {}",units[units.length - 2]);
if ((units[units.length - 2] instanceof Stmt) && ((Stmt)units[units.length - 2]).containsInvokeExpr()) {
InvokeExpr invoke=((Stmt)units[units.length - 2]).getInvokeExpr();
if (debug) logger.debug("{} {} {}",invoke instanceof SpecialInvokeExpr,method.getSubSignature().equals(invoke.getMethodRef().getSubSignature().getString()),((SpecialInvokeExpr)invoke).getBase().equals(stmtBody.getThisLocal()));
if (invoke instanceof SpecialInvokeExpr && method.getSubSignature().equals(invoke.getMethodRef().getSubSignature().getString()) && ((SpecialInvokeExpr)invoke).getBase().equals(stmtBody.getThisLocal())) {
for (int i=0; i < invoke.getArgCount(); i++) {
if (!invoke.getArg(i).equals(stmtBody.getParameterLocal(i))) {
if (debug) logger.debug("no a local? {} {}",invoke.getArg(i),stmtBody.getParameterLocal(i));
return;
}
}
foundSpecialInvoke=true;
}
}
if (!foundSpecialInvoke) {
return;
}
if (debug) logger.debug("call to super pass");
boolean correctReturn=false;
if ((units[units.length - 1] instanceof JReturnVoidStmt) && units[units.length - 2] instanceof JInvokeStmt) {
if (debug) logger.debug("Correct return void ");
correctReturn=true;
}
if ((units[units.length - 1] instanceof JReturnStmt) && units[units.length - 2] instanceof AssignStmt) {
if (((AssignStmt)units[units.length - 2]).getLeftOp().equals(((JReturnStmt)units[units.length - 1]).getOp())) {
correctReturn=true;
logger.debug("correct return");
}
}
if (!correctReturn) {
return;
}
logger.info("Removing stupid override {}",method);
clz.removeMethod(method);
}
| Remove a method if all it does is call the super method with the same args. |
public void loadMarkdown(String txt,String cssFileUrl){
loadMarkdownToView(txt,cssFileUrl);
}
| Loads the given Markdown text to the view as rich formatted HTML. The HTML output will be styled based on the given CSS file. |
protected void clearList(){
int listSize=getItemCount();
this.list.clear();
notifyItemRangeRemoved(0,listSize);
}
| Clear all items that are in the list. |
public static SearchRecentSuggestions newHelper(Context context){
return new SearchRecentSuggestions(context,AUTHORITY,MODE);
}
| Creates and returns a helper for adding recent queries or clearing the recent query history. |
@Override public boolean supportsSchemasInIndexDefinitions(){
debugCodeCall("supportsSchemasInIndexDefinitions");
return true;
}
| Returns whether the schema name in CREATE INDEX is supported. |
private IBindingSet aggregate(final Iterable<IBindingSet> solutions){
final IBindingSet aggregates=new ContextBindingSet(context,new ListBindingSet());
if (groupBy != null) {
final IBindingSet aSolution=solutions.iterator().next();
for ( IValueExpression<?> expr : groupBy) {
if (expr instanceof IVariable<?>) {
final IVariable<?> var=(IVariable<?>)expr;
final Object varValue=var.get(aSolution);
final Constant<?> val;
if (varValue == null) {
val=Constant.errorValue();
}
else {
val=new Constant(varValue.getClass().cast(varValue));
}
;
aggregates.set(var,val);
}
else if (expr instanceof IBind<?>) {
final IBind<?> bindExpr=(IBind<?>)expr;
final Constant<?> val;
final Object exprValue=bindExpr.get(aSolution);
if (exprValue == null) {
val=Constant.errorValue();
}
else {
val=new Constant(exprValue.getClass().cast(exprValue));
}
final IVariable<?> ovar=((IBind<?>)expr).getVar();
aggregates.set(ovar,val);
}
}
}
{
final boolean nestedAggregates=groupByState.isNestedAggregates();
final Iterator<Map.Entry<IAggregate<?>,IVariable<?>>> itr=rewrite.getAggExpr().entrySet().iterator();
while (itr.hasNext()) {
final Map.Entry<IAggregate<?>,IVariable<?>> e=itr.next();
doAggregate(e.getKey(),e.getValue(),nestedAggregates,aggregates,solutions,stats);
}
if (log.isTraceEnabled()) log.trace("aggregates: " + aggregates);
}
for ( IValueExpression<?> expr : rewrite.getSelect2()) {
try {
expr.get(aggregates);
}
catch ( SparqlTypeErrorException ex) {
TypeErrorLog.handleTypeError(ex,expr,stats);
continue;
}
catch ( IllegalArgumentException ex) {
TypeErrorLog.handleTypeError(ex,expr,stats);
continue;
}
}
{
final boolean drop;
final IConstraint[] having2=rewrite.getHaving2();
if (having2 != null && !BOpUtility.isConsistent(having2,aggregates)) {
drop=true;
}
else {
drop=false;
}
if (log.isInfoEnabled()) log.info((drop ? "drop" : "keep") + " : " + aggregates);
if (drop) {
return null;
}
}
final IBindingSet out;
if (groupBy == null) {
assert !aggregates.containsErrorValues();
out=aggregates.copy(groupByState.getSelectVars().toArray(new IVariable[0]));
}
else {
out=aggregates.copyMinusErrors(groupByState.getSelectVars().toArray(new IVariable[0]));
}
return out;
}
| Compute the aggregate solution for a solution multiset (aka a group). |
public CStepIntoAction(final JFrame parent,final IFrontEndDebuggerProvider debugger){
m_parent=Preconditions.checkNotNull(parent,"IE00310: Parent argument can not be null");
m_debugger=Preconditions.checkNotNull(debugger,"IE01544: Debugger argument can not be null");
putValue(Action.SHORT_DESCRIPTION,"Step Into");
}
| Creates a new single step action. |
public static void applySampledState(SampledVertex v,Attributes attrs){
String str=attrs.getValue(SAMPLED_ATTR);
if (str != null) v.sample(new Integer(str));
}
| Parses the attributes data for information of the sampled state of the vertex and sets the vertex to the corresponding state. |
private static void appendCommandStatus(final PrintWriter writer,final IStatus CommandStatus,final int nesting){
for (int i=0; i < nesting; i++) {
writer.print(" ");
}
writer.println(CommandStatus.getMessage());
final IStatus[] children=CommandStatus.getChildren();
for (int i=0; i < children.length; i++) {
appendCommandStatus(writer,children[i],nesting + 1);
}
}
| Append CommandStatus. |
private void fillFromArguments(String[] arguments){
for ( String string : arguments) {
if (!string.startsWith("--")) {
throw new IllegalArgumentException("illegal parameter: " + string);
}
String param=string.substring(2);
String params[]=param.split("=",2);
boolean found=false;
for ( ParameterNames parameterName : ParameterNames.values()) {
String name=parameterName.getParameterName().toLowerCase();
if (name.equals(params[0])) {
if (params.length == 1) {
parameterValueMap.put(params[0],"");
}
else {
parameterValueMap.put(params[0],params[1]);
}
found=true;
break;
}
}
if (!found) {
elementDesc.add(string);
}
}
verifyAllParameters();
}
| Parse arguments. |
private ExpirationAction(String name){
this.name=name;
}
| Creates a new instance of ExpirationAction. |
public void resetPattern(String pattern){
normalize(pattern);
}
| Resets the search pattern. |
public void testResourcesAvailable(){
new PortugueseAnalyzer().close();
}
| This test fails with NPE when the stopwords file is missing in classpath |
public static boolean isLauncherAppTarget(Intent launchIntent){
if (launchIntent != null && Intent.ACTION_MAIN.equals(launchIntent.getAction()) && launchIntent.getComponent() != null && launchIntent.getCategories() != null && launchIntent.getCategories().size() == 1 && launchIntent.hasCategory(Intent.CATEGORY_LAUNCHER) && TextUtils.isEmpty(launchIntent.getDataString())) {
Bundle extras=launchIntent.getExtras();
if (extras == null) {
return true;
}
else {
Set<String> keys=extras.keySet();
return keys.size() == 1 && keys.contains(ItemInfo.EXTRA_PROFILE);
}
}
;
return false;
}
| Returns true if the intent is a valid launch intent for a launcher activity of an app. This is used to identify shortcuts which are different from the ones exposed by the applications' manifest file. |
public static Class[] resolveAllInterfaces(Class type){
Set<Class> bag=new LinkedHashSet<>();
_resolveAllInterfaces(type,bag);
return bag.toArray(new Class[bag.size()]);
}
| Resolves all interfaces of a type. No duplicates are returned. Direct interfaces are prior the interfaces of subclasses in the returned array. |
public ProtocolDecoderException(Throwable cause){
super(cause);
}
| Constructs a new instance with the specified cause. |
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
s.defaultReadObject();
if (lagGraph == null) {
throw new NullPointerException();
}
}
| Adds semantic checks to the default deserialization method. This method must have the standard signature for a readObject method, and the body of the method must begin with "s.defaultReadObject();". Other than that, any semantic checks can be specified and do not need to stay the same from version to version. A readObject method of this form may be added to any class, even if Tetrad sessions were previously saved out using a version of the class that didn't include it. (That's what the "s.defaultReadObject();" is for. See J. Bloch, Effective Java, for help. |
protected SQLException logAndConvert(Exception ex){
SQLException e=DbException.toSQLException(ex);
if (trace == null) {
DbException.traceThrowable(e);
}
else {
int errorCode=e.getErrorCode();
if (errorCode >= 23000 && errorCode < 24000) {
trace.info(e,"exception");
}
else {
trace.error(e,"exception");
}
}
return e;
}
| Log an exception and convert it to a SQL exception if required. |
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 void compute_default(){
int i, prod, max_prod, max_red;
if (reduction_count == null) reduction_count=new int[production.number()];
for (i=0; i < production.number(); i++) reduction_count[i]=0;
max_prod=-1;
max_red=0;
for (i=0; i < size(); i++) if (under_term[i].kind() == parse_action.REDUCE) {
prod=((reduce_action)under_term[i]).reduce_with().index();
reduction_count[prod]++;
if (reduction_count[prod] > max_red) {
max_red=reduction_count[prod];
max_prod=prod;
}
}
default_reduce=max_prod;
}
| Compute the default (reduce) action for this row and store it in default_reduce. In the case of non-zero default we will have the effect of replacing all errors by that reduction. This may cause us to do erroneous reduces, but will never cause us to shift past the point of the error and never cause an incorrect parse. -1 will be used to encode the fact that no reduction can be used as a default (in which case error will be used). |
public void KillRandomBlordroughs(int numb){
for (int i=0; i < numb; i++) {
KillRandomBlordrough();
}
logger.debug("killed " + numb + " creatures.");
}
| function for emulating killing of blordrough soldiers by player. |
public static void error(Throwable problem){
_errorCallback.error(problem);
}
| Displays the error to the user. |
public OsmMoveAction(MapWay way,int fromNodeIdx,int toNodeIdx){
this.way=way;
fromIndex=fromNodeIdx;
toIndex=toNodeIdx;
}
| The indices correspond to the list of nodes stored with the way. |
public VPAttributeDialog(Frame frame,int M_AttributeSetInstance_ID,int M_Product_ID,int C_BPartner_ID,boolean productWindow,int AD_Column_ID,int WindowNo,boolean readWrite){
super(frame,Msg.translate(Env.getCtx(),"M_AttributeSetInstance_ID"),true);
log.config("M_AttributeSetInstance_ID=" + M_AttributeSetInstance_ID + ", M_Product_ID="+ M_Product_ID+ ", C_BPartner_ID="+ C_BPartner_ID+ ", ProductW="+ productWindow+ ", Column="+ AD_Column_ID);
m_WindowNo=Env.createWindowNo(this);
m_M_AttributeSetInstance_ID=M_AttributeSetInstance_ID;
m_M_Product_ID=M_Product_ID;
m_C_BPartner_ID=C_BPartner_ID;
m_productWindow=productWindow;
m_AD_Column_ID=AD_Column_ID;
m_WindowNoParent=WindowNo;
m_readWrite=readWrite;
m_columnName=DB.getSQLValueString(null,"SELECT ColumnName FROM AD_Column WHERE AD_Column_ID = ?",m_AD_Column_ID);
if (m_columnName == null || m_columnName.trim().length() == 0) {
m_columnName="M_AttributeSetInstance_ID";
}
try {
jbInit();
}
catch ( Exception ex) {
log.log(Level.SEVERE,"VPAttributeDialog" + ex);
}
if (!initAttributes()) {
dispose();
return;
}
AEnv.showCenterWindow(frame,this);
}
| Product Attribute Instance Dialog |
public static long quantile(long[] values,double quantile){
if (values == null) throw new IllegalArgumentException("Values cannot be null.");
if (quantile < 0.0 || quantile > 1.0) throw new IllegalArgumentException("Quantile must be between 0.0 and 1.0");
long[] copy=new long[values.length];
System.arraycopy(values,0,copy,0,copy.length);
Arrays.sort(copy);
int index=(int)(copy.length * quantile);
return copy[index];
}
| Compute the requested quantile of the given array |
public PaintListenerSupport(){
this(null);
}
| Construct a PaintListenerSupport. |
public String fromId(){
return fromId;
}
| From vertex id. |
protected void configureCoreUI(){
GinMultibinder<PreferencePagePresenter> prefBinder=GinMultibinder.newSetBinder(binder(),PreferencePagePresenter.class);
prefBinder.addBinding().to(AppearancePresenter.class);
prefBinder.addBinding().to(ExtensionManagerPresenter.class);
GinMultibinder<Theme> themeBinder=GinMultibinder.newSetBinder(binder(),Theme.class);
themeBinder.addBinding().to(DarkTheme.class);
themeBinder.addBinding().to(LightTheme.class);
bind(PartStackUIResources.class).to(Resources.class).in(Singleton.class);
bind(WorkspaceView.class).to(WorkspaceViewImpl.class).in(Singleton.class);
bind(PerspectiveView.class).to(PerspectiveViewImpl.class);
bind(MainMenuView.class).to(MainMenuViewImpl.class).in(Singleton.class);
bind(StatusPanelGroupView.class).to(StatusPanelGroupViewImpl.class).in(Singleton.class);
bind(ToolbarView.class).to(ToolbarViewImpl.class);
bind(ToolbarPresenter.class).annotatedWith(MainToolbar.class).to(ToolbarPresenter.class).in(Singleton.class);
install(new GinFactoryModuleBuilder().implement(DropDownWidget.class,DropDownWidgetImpl.class).build(DropDownListFactory.class));
bind(NotificationManagerView.class).to(NotificationManagerViewImpl.class).in(Singleton.class);
bind(EditorPartStackView.class);
bind(EditorContentSynchronizer.class).to(EditorContentSynchronizerImpl.class).in(Singleton.class);
install(new GinFactoryModuleBuilder().implement(EditorGroupSynchronization.class,EditorGroupSynchronizationImpl.class).build(EditorGroupSychronizationFactory.class));
bind(MessageDialogFooter.class);
bind(MessageDialogView.class).to(MessageDialogViewImpl.class);
bind(ConfirmDialogFooter.class);
bind(ConfirmDialogView.class).to(ConfirmDialogViewImpl.class);
bind(ChoiceDialogFooter.class);
bind(ChoiceDialogView.class).to(ChoiceDialogViewImpl.class);
bind(InputDialogFooter.class);
bind(InputDialogView.class).to(InputDialogViewImpl.class);
install(new GinFactoryModuleBuilder().implement(MessageDialog.class,MessageDialogPresenter.class).implement(ConfirmDialog.class,ConfirmDialogPresenter.class).implement(InputDialog.class,InputDialogPresenter.class).implement(ChoiceDialog.class,ChoiceDialogPresenter.class).build(DialogFactory.class));
install(new GinFactoryModuleBuilder().implement(SubPanelView.class,SubPanelViewImpl.class).build(SubPanelViewFactory.class));
install(new GinFactoryModuleBuilder().implement(SubPanel.class,SubPanelPresenter.class).build(SubPanelFactory.class));
install(new GinFactoryModuleBuilder().implement(Tab.class,TabWidget.class).build(TabItemFactory.class));
install(new GinFactoryModuleBuilder().implement(ConsoleButton.class,ConsoleButtonImpl.class).build(ConsoleButtonFactory.class));
install(new GinFactoryModuleBuilder().implement(ProjectNotificationSubscriber.class,ProjectNotificationSubscriberImpl.class).build(ImportProjectNotificationSubscriberFactory.class));
install(new GinFactoryModuleBuilder().build(FindResultNodeFactory.class));
bind(UploadFileView.class).to(UploadFileViewImpl.class);
bind(UploadFolderFromZipView.class).to(UploadFolderFromZipViewImpl.class);
bind(PreferencesView.class).to(PreferencesViewImpl.class).in(Singleton.class);
bind(NavigateToFileView.class).to(NavigateToFileViewImpl.class).in(Singleton.class);
bind(ExtensionManagerView.class).to(ExtensionManagerViewImpl.class).in(Singleton.class);
bind(AppearanceView.class).to(AppearanceViewImpl.class).in(Singleton.class);
bind(FindActionView.class).to(FindActionViewImpl.class).in(Singleton.class);
bind(HotKeysDialogView.class).to(HotKeysDialogViewImpl.class).in(Singleton.class);
bind(RecentFileList.class).to(RecentFileStore.class).in(Singleton.class);
install(new GinFactoryModuleBuilder().build(RecentFileActionFactory.class));
install(new GinFactoryModuleBuilder().build(CommandProducerActionFactory.class));
}
| Configure Core UI components, resources and views |
public void invert(final int ulx,final int uly,final int lrx,final int lry){
filter(ulx,uly,lrx,lry,FilterMode.FILTER_INVERT,-1);
}
| invert filter for a square part of the image |
public UpdateSettingsRequest(Settings settings,String... indices){
this.indices=indices;
this.settings=settings;
}
| Constructs a new request to update settings for one or more indices |
public void close() throws IOException {
mFd.close();
}
| Convenience for calling <code>getParcelFileDescriptor().close()</code>. |
@Override public int remove(final byte[] termHash,final HandleSet urlHashes) throws IOException {
this.countCache.remove(termHash);
final int removed=this.ram.remove(termHash,urlHashes);
int reduced;
try {
reduced=this.array.reduce(termHash,new RemoveReducer<ReferenceType>(urlHashes));
}
catch ( final SpaceExceededException e) {
reduced=0;
ConcurrentLog.warn("IndexCell","not possible to remove urlHashes from a RWI because of too low memory. Remove was not applied. Please increase RAM assignment");
}
return removed + (reduced / this.array.rowdef().objectsize);
}
| remove url references from a selected word hash. this deletes also in the BLOB files, which means that there exists new gap entries after the deletion The gaps are never merged in place, but can be eliminated when BLOBs are merged into new BLOBs. This returns the sum of all url references that have been removed |
public void trace(String msg){
innerLog(Level.TRACE,null,msg,UNKNOWN_ARG,UNKNOWN_ARG,UNKNOWN_ARG,null);
}
| Log a trace message. |
private boolean isInactiveField(){
return _property.getName().equals(DataObject.INACTIVE_FIELD_NAME);
}
| Time UUID is always required for inactive field. We depends on the timestamp to validate modification time of inactive field |
@Deprecated public boolean requestDefaultFocus(){
Container nearestRoot=(isFocusCycleRoot()) ? this : getFocusCycleRootAncestor();
if (nearestRoot == null) {
return false;
}
Component comp=nearestRoot.getFocusTraversalPolicy().getDefaultComponent(nearestRoot);
if (comp != null) {
comp.requestFocus();
return true;
}
else {
return false;
}
}
| In release 1.4, the focus subsystem was rearchitected. For more information, see <a href="https://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html"> How to Use the Focus Subsystem</a>, a section in <em>The Java Tutorial</em>. <p> Requests focus on this <code>JComponent</code>'s <code>FocusTraversalPolicy</code>'s default <code>Component</code>. If this <code>JComponent</code> is a focus cycle root, then its <code>FocusTraversalPolicy</code> is used. Otherwise, the <code>FocusTraversalPolicy</code> of this <code>JComponent</code>'s focus-cycle-root ancestor is used. |
private Organization createOrganization() throws Exception {
Organization organization=new Organization();
organization.setOrganizationId("testOrg");
organization.setRegistrationDate(123L);
organization.setCutOffDay(1);
mgr.persist(organization);
mgr.flush();
return organization;
}
| Helper method for creating technical product. |
public void testGetAttributes(){
char expectedId1=20;
char expectedId2=21;
char actualId1;
char actualId2;
unknownAttributesAttribute.addAttributeID(expectedId1);
unknownAttributesAttribute.addAttributeID(expectedId2);
Iterator<Character> iterator=unknownAttributesAttribute.getAttributes();
actualId1=iterator.next();
actualId2=iterator.next();
assertEquals("getAttributes() return value mismatch",expectedId1,actualId1);
assertEquals("getAttributes() return value mismatch",expectedId2,actualId2);
}
| Same as testGetAttributeID, only attribute attributes are extracted through the getAttributes()'s iterator. |
public MyHashMap(int initialCapacity){
this(initialCapacity,DEFAULT_MAX_LOAD_FACTOR);
}
| Construct a map with the specified initial capacity and default load factor |
public synchronized void flush(){
sampleHolder=new SampleHolder(SampleHolder.BUFFER_REPLACEMENT_MODE_NORMAL);
parsing=false;
result=null;
error=null;
runtimeError=null;
}
| Flushes the helper, canceling the current parsing operation, if there is one. |
@Override public void mouseReleased(GlobalMouseEvent event){
}
| Invoked when a mouse button was released. |
@Ignore @Test public final void testSaveWithNull(){
thrown.expect(ConstraintViolationException.class);
srv.save(null);
}
| Test to call save with null argument. |
public TrackerDataHelper(Context context){
this(context,NO_FORMATTER);
}
| Creates a instance with no output formatting capabilities. Useful for clients that require write-only access |
public boolean isCancelled(){
return cancelled;
}
| Returns true if task is cancelled. |
public PopupEncoder2Menu(){
super();
initialize();
}
| This method initializes |
public static LC parseLayoutConstraint(String s){
LC lc=new LC();
if (s.length() == 0) {
return lc;
}
String[] parts=toTrimmedTokens(s,',');
for (int i=0; i < parts.length; i++) {
String part=parts[i];
if (part == null) {
continue;
}
int len=part.length();
if (len == 3 || len == 11) {
if (part.equals("ltr") || part.equals("rtl") || part.equals("lefttoright")|| part.equals("righttoleft")) {
lc.setLeftToRight(part.charAt(0) == 'l' ? Boolean.TRUE : Boolean.FALSE);
parts[i]=null;
}
if (part.equals("ttb") || part.equals("btt") || part.equals("toptobottom")|| part.equals("bottomtotop")) {
lc.setTopToBottom(part.charAt(0) == 't');
parts[i]=null;
}
}
}
for ( String part : parts) {
if (part == null || part.length() == 0) {
continue;
}
try {
int ix=-1;
char c=part.charAt(0);
if (c == 'w' || c == 'h') {
ix=startsWithLenient(part,"wrap",-1,true);
if (ix > -1) {
String num=part.substring(ix).trim();
lc.setWrapAfter(num.length() != 0 ? Integer.parseInt(num) : 0);
continue;
}
boolean isHor=c == 'w';
if (isHor && (part.startsWith("w ") || part.startsWith("width "))) {
String sz=part.substring(part.charAt(1) == ' ' ? 2 : 6).trim();
lc.setWidth(parseBoundSize(sz,false,true));
continue;
}
if (!isHor && (part.startsWith("h ") || part.startsWith("height "))) {
String uvStr=part.substring(part.charAt(1) == ' ' ? 2 : 7).trim();
lc.setHeight(parseBoundSize(uvStr,false,false));
continue;
}
if (part.length() > 5) {
String sz=part.substring(5).trim();
if (part.startsWith("wmin ")) {
lc.minWidth(sz);
continue;
}
else if (part.startsWith("wmax ")) {
lc.maxWidth(sz);
continue;
}
else if (part.startsWith("hmin ")) {
lc.minHeight(sz);
continue;
}
else if (part.startsWith("hmax ")) {
lc.maxHeight(sz);
continue;
}
}
if (part.startsWith("hidemode ")) {
lc.setHideMode(Integer.parseInt(part.substring(9)));
continue;
}
}
if (c == 'g') {
if (part.startsWith("gapx ")) {
lc.setGridGapX(parseBoundSize(part.substring(5).trim(),true,true));
continue;
}
if (part.startsWith("gapy ")) {
lc.setGridGapY(parseBoundSize(part.substring(5).trim(),true,false));
continue;
}
if (part.startsWith("gap ")) {
String[] gaps=toTrimmedTokens(part.substring(4).trim(),' ');
lc.setGridGapX(parseBoundSize(gaps[0],true,true));
lc.setGridGapY(gaps.length > 1 ? parseBoundSize(gaps[1],true,false) : lc.getGridGapX());
continue;
}
}
if (c == 'd') {
ix=startsWithLenient(part,"debug",5,true);
if (ix > -1) {
String millis=part.substring(ix).trim();
lc.setDebugMillis(millis.length() > 0 ? Integer.parseInt(millis) : 1000);
continue;
}
}
if (c == 'n') {
if (part.equals("nogrid")) {
lc.setNoGrid(true);
continue;
}
if (part.equals("nocache")) {
lc.setNoCache(true);
continue;
}
if (part.equals("novisualpadding")) {
lc.setVisualPadding(false);
continue;
}
}
if (c == 'f') {
if (part.equals("fill") || part.equals("fillx") || part.equals("filly")) {
lc.setFillX(part.length() == 4 || part.charAt(4) == 'x');
lc.setFillY(part.length() == 4 || part.charAt(4) == 'y');
continue;
}
if (part.equals("flowy")) {
lc.setFlowX(false);
continue;
}
if (part.equals("flowx")) {
lc.setFlowX(true);
continue;
}
}
if (c == 'i') {
ix=startsWithLenient(part,"insets",3,true);
if (ix > -1) {
String insStr=part.substring(ix).trim();
UnitValue[] ins=parseInsets(insStr,true);
LayoutUtil.putCCString(ins,insStr);
lc.setInsets(ins);
continue;
}
}
if (c == 'a') {
ix=startsWithLenient(part,new String[]{"aligny","ay"},new int[]{6,2},true);
if (ix > -1) {
UnitValue align=parseUnitValueOrAlign(part.substring(ix).trim(),false,null);
if (align == UnitValue.BASELINE_IDENTITY) {
throw new IllegalArgumentException("'baseline' can not be used to align the whole component group.");
}
lc.setAlignY(align);
continue;
}
ix=startsWithLenient(part,new String[]{"alignx","ax"},new int[]{6,2},true);
if (ix > -1) {
lc.setAlignX(parseUnitValueOrAlign(part.substring(ix).trim(),true,null));
continue;
}
ix=startsWithLenient(part,"align",2,true);
if (ix > -1) {
String[] gaps=toTrimmedTokens(part.substring(ix).trim(),' ');
lc.setAlignX(parseUnitValueOrAlign(gaps[0],true,null));
if (gaps.length > 1) {
lc.setAlignY(parseUnitValueOrAlign(gaps[1],false,null));
}
continue;
}
}
if (c == 'p') {
if (part.startsWith("packalign ")) {
String[] packs=toTrimmedTokens(part.substring(10).trim(),' ');
lc.setPackWidthAlign(packs[0].length() > 0 ? Float.parseFloat(packs[0]) : 0.5f);
if (packs.length > 1) {
lc.setPackHeightAlign(Float.parseFloat(packs[1]));
}
continue;
}
if (part.startsWith("pack ") || part.equals("pack")) {
String ps=part.substring(4).trim();
String[] packs=toTrimmedTokens(ps.length() > 0 ? ps : "pref pref",' ');
lc.setPackWidth(parseBoundSize(packs[0],false,true));
if (packs.length > 1) {
lc.setPackHeight(parseBoundSize(packs[1],false,false));
}
continue;
}
}
if (lc.getAlignX() == null) {
UnitValue alignX=parseAlignKeywords(part,true);
if (alignX != null) {
lc.setAlignX(alignX);
continue;
}
}
UnitValue alignY=parseAlignKeywords(part,false);
if (alignY != null) {
lc.setAlignY(alignY);
continue;
}
throw new IllegalArgumentException("Unknown Constraint: '" + part + "'\n");
}
catch ( Exception ex) {
throw new IllegalArgumentException("Illegal Constraint: '" + part + "'\n"+ ex.getMessage());
}
}
return lc;
}
| Parses the layout constraints and stores the parsed values in the transient (cache) member varables. |
public static PickResults doPick(Spatial root,final Ray3 pickRay){
root.updateWorldBound(true);
final PrimitivePickResults bpr=new PrimitivePickResults();
bpr.setCheckDistance(true);
PickingUtil.findPick(root,pickRay,bpr);
if (bpr.getNumber() == 0) {
return (null);
}
PickData closest=bpr.getPickData(0);
for (int i=1; i < bpr.getNumber(); ++i) {
PickData pd=bpr.getPickData(i);
if (closest.getIntersectionRecord().getClosestDistance() > pd.getIntersectionRecord().getClosestDistance()) {
closest=pd;
}
}
return bpr;
}
| Do a pick operation on a spatial |
private MigrationInfoDumper(){
}
| Prevent instantiation. |
public void testOneTrackOneSegment() throws Exception {
Capture<Track> track=new Capture<Track>();
Location location0=createLocation(0,DATE_FORMAT_0.parse(TRACK_TIME_0).getTime());
Location location1=createLocation(1,DATE_FORMAT_1.parse(TRACK_TIME_1).getTime());
expect(myTracksProviderUtils.insertTrack((Track)AndroidMock.anyObject())).andReturn(TRACK_ID_0_URI);
expectFirstTrackPoint(location0,TRACK_ID_0,TRACK_POINT_ID_0);
expect(myTracksProviderUtils.bulkInsertTrackPoint(LocationsMatcher.eqLoc(location1),eq(1),eq(TRACK_ID_0))).andReturn(1);
expect(myTracksProviderUtils.getLastTrackPointId(TRACK_ID_0)).andReturn(TRACK_POINT_ID_1);
expect(myTracksProviderUtils.getTrack(PreferencesUtils.getLong(getContext(),R.string.recording_track_id_key))).andStubReturn(null);
expectUpdateTrack(track,true,TRACK_ID_0);
AndroidMock.replay(myTracksProviderUtils);
InputStream inputStream=new ByteArrayInputStream(VALID_ONE_TRACK_ONE_SEGMENT_GPX.getBytes());
GpxFileTrackImporter gpxFileTrackImporter=new GpxFileTrackImporter(getContext(),myTracksProviderUtils);
long trackId=gpxFileTrackImporter.importFile(inputStream);
assertEquals(TRACK_ID_0,trackId);
long time0=DATE_FORMAT_0.parse(TRACK_TIME_0).getTime();
long time1=DATE_FORMAT_1.parse(TRACK_TIME_1).getTime();
assertEquals(time1 - time0,track.getValue().getTripStatistics().getTotalTime());
AndroidMock.verify(myTracksProviderUtils);
verifyTrack(track.getValue(),TRACK_NAME_0,TRACK_DESCRIPTION_0,time0);
}
| Tests one track with one segment. |
public CloseSessionResponse CloseSession(CloseSessionRequest req) throws ServiceFaultException, ServiceResultException {
return (CloseSessionResponse)channel.serviceRequest(req);
}
| Synchronous CloseSession service request. |
public Object removeAttributeValue(AttributeKey<?> key){
return removeAttributeValue(key.getId());
}
| Remove attribute (if present). |
public Yaml(){
this(new Constructor(),new Representer(),new DumperOptions(),new Resolver());
}
| Create Yaml instance. It is safe to create a few instances and use them in different Threads. |
public TrunkingSquelchController(boolean allowSquelchOverride){
mAllowSquelchOverride=allowSquelchOverride;
mSquelchMode=SquelchMode.AUTOMATIC;
}
| Provides control over audio stream as directed by an external trunking channel state. Override automatic squelch control by setting the squelch mode to none. Disable automatic control override by setting allowManualOverride to false; Note: this control does not respond to squelch mode manual. |
final protected int depth(Node node){
int i=0;
while ((node=node.jjtGetParent()) != null) {
i++;
}
return i;
}
| Return the depth of the node in the parse tree. The depth is ZERO (0) if the node does not have a parent. |
@Override public long runTask(){
if (CurrentTime.isTest()) {
return -1;
}
_lastTime=CurrentTime.getExactTime();
while (true) {
long now=CurrentTime.getExactTime();
long next=_clock.extractAlarm(now,false);
if (next < 0) {
return 120000L;
}
else if (now < next) {
return Math.min(next - now,120000L);
}
}
}
| Runs the coordinator task. |
public void appendStart(StringBuffer buffer,Object object){
if (object != null) {
appendClassName(buffer,object);
appendIdentityHashCode(buffer,object);
appendContentStart(buffer);
if (fieldSeparatorAtStart) {
appendFieldSeparator(buffer);
}
}
}
| <p>Append to the <code>toString</code> the start of data indicator.</p> |
public void addInvokedynamic(int bootstrap,String name,String desc){
int nt=constPool.addNameAndTypeInfo(name,desc);
int dyn=constPool.addInvokeDynamicInfo(bootstrap,nt);
add(INVOKEDYNAMIC);
addIndex(dyn);
add(0,0);
growStack(Descriptor.dataSize(desc));
}
| Appends INVOKEDYNAMIC. |
public void unsetParamCode(){
this.paramCode=null;
}
| Description: <br> |
@Override public boolean onUsed(final RPEntity user){
if (!this.isContained()) {
user.sendPrivateText("The staff must be wielded.");
return false;
}
final StendhalRPZone zone=user.getZone();
if (zone.isInProtectionArea(user)) {
user.sendPrivateText("The aura of protection in this area lets the dead sleep in peace.");
return false;
}
if (zone.getNPCList().size() >= MAX_ZONE_NPCS) {
user.sendPrivateText("Mysteriously, the staff does not function! Perhaps this area is too crowded...");
logger.warn(user.getName() + " is trying to use the necromancer staff but there are too many npcs in " + zone.getName());
return false;
}
for ( final RPObject inspected : zone) {
if (inspected instanceof Corpse && user.squaredDistance(Integer.parseInt(inspected.get("x")),Integer.parseInt(inspected.get("y"))) <= SQUARED_RANGE) {
final AttackableCreature creature=pickSuitableCreature(user.getLevel());
if (creature == null) {
user.sendPrivateText("This staff does not seem to work. Maybe it has lost its unholy power.");
return false;
}
StendhalRPAction.placeat(zone,creature,Integer.parseInt(inspected.get("x")),Integer.parseInt(inspected.get("y")));
zone.remove(inspected);
creature.init();
creature.setMaster(user.getTitle());
creature.clearDropItemList();
creature.put("title_type","friend");
user.damage(HP_FACTOR * creature.getLevel(),this);
user.notifyWorldAboutChanges();
return true;
}
}
user.sendPrivateText("Step closer to corpses to awake them.");
return false;
}
| Is invoked when the necromancer staff is used. |
public CreatureRespawnPoint(final StendhalRPZone zone,final int x,final int y,final Creature creature,final int maximum){
this.zone=zone;
this.x=x;
this.y=y;
this.prototypeCreature=creature;
this.maximum=maximum;
this.respawnTime=creature.getRespawnTime();
this.creatures=new LinkedList<Creature>();
respawning=true;
SingletonRepository.getTurnNotifier().notifyInTurns(calculateNextRespawnTurn(),this);
}
| Creates a new RespawnPoint. |
public void stateChanged(ChangeEvent e){
if (settingColor) {
return;
}
Color color=getColor();
if (e.getSource() == hueSpinner) {
setHue(((Number)hueSpinner.getValue()).floatValue() / 360,false);
}
else if (e.getSource() == saturationSpinner) {
setSaturation(((Number)saturationSpinner.getValue()).floatValue() / 255);
}
else if (e.getSource() == valueSpinner) {
setBrightness(((Number)valueSpinner.getValue()).floatValue() / 255);
}
else if (e.getSource() == redSpinner) {
setRed(((Number)redSpinner.getValue()).intValue());
}
else if (e.getSource() == greenSpinner) {
setGreen(((Number)greenSpinner.getValue()).intValue());
}
else if (e.getSource() == blueSpinner) {
setBlue(((Number)blueSpinner.getValue()).intValue());
}
}
| ChangeListener method, updates the necessary display widgets. |
public Feature(String name,Object value,boolean isDefaultValue){
this.name=FeatureUtil.escapeFeatureName(name).intern();
this.value=value;
this.isDefaultValue=isDefaultValue;
}
| Creates a feature that is aware if the value is a <b>default value</b>. This information is used when filling the feature store. A sparse feature store would not add a feature if it is a default value i.e. means a feature is <i>not set</i> |
public static void doEntryOperations() throws Exception {
Region r1=cache.getRegion(Region.SEPARATOR + REGION_NAME);
String keyPrefix="server-";
for (int i=0; i < 10; i++) {
r1.put(keyPrefix + i,keyPrefix + "val-" + i);
}
}
| Do some PUT operations |
public Transit createNewTransit(String userName){
boolean found=false;
String testName="";
Transit z;
while (!found) {
int nextAutoTransitRef=lastAutoTransitRef + 1;
testName="IZ" + nextAutoTransitRef;
z=getBySystemName(testName);
if (z == null) {
found=true;
}
lastAutoTransitRef=nextAutoTransitRef;
}
return createNewTransit(testName,userName);
}
| For use with User GUI, to allow the auto generation of systemNames, where the user can optionally supply a username. Note: Since system names should be kept short for use in Dispatcher, the :AUTO:000 has been removed from automatically generated system names. Autogenerated system names will use IZnn, where nn is the first available number. |
protected static <A extends Annotation,T>Set<PersistentResource<T>> filter(Class<A> permission,Set<PersistentResource<T>> resources,boolean skipNew){
Set<PersistentResource<T>> filteredSet=new LinkedHashSet<>();
for ( PersistentResource<T> resource : resources) {
PermissionExecutor permissionExecutor=resource.getRequestScope().getPermissionExecutor();
try {
if (!(skipNew && resource.getRequestScope().getNewResources().contains(resource))) {
if (!permissionExecutor.shouldShortCircuitPermissionChecks(permission,resource.getResourceClass(),null)) {
ExpressionResult expressionResult=permissionExecutor.checkUserPermissions(resource.getResourceClass(),permission);
if (expressionResult == ExpressionResult.PASS) {
filteredSet.add(resource);
continue;
}
resource.checkFieldAwarePermissions(permission);
}
}
filteredSet.add(resource);
}
catch ( ForbiddenAccessException e) {
}
}
if (resources instanceof SingleElementSet && resources.equals(filteredSet)) {
return resources;
}
return filteredSet;
}
| Filter a set of PersistentResources. |
public void initialize(final String componentFolder) throws IOException, RequiredInputMissingException {
if (StringUtils.isBlank(componentFolder)) throw new RequiredInputMissingException("Missing required value for parameter 'componentFolder'");
File folder=new File(componentFolder);
if (!folder.isDirectory()) throw new IOException("Provided input '" + componentFolder + "' does not reference a valid folder");
File[] jarFiles=folder.listFiles();
if (jarFiles == null || jarFiles.length < 1) throw new RequiredInputMissingException("No JAR files found in folder '" + componentFolder + "'");
logger.info("Initializing component classloader [folder=" + componentFolder + "]");
for ( File jarFile : jarFiles) {
if (jarFile.isFile()) {
JarInputStream jarInputStream=null;
try {
jarInputStream=new JarInputStream(new FileInputStream(jarFile));
JarEntry jarEntry=null;
while ((jarEntry=jarInputStream.getNextJarEntry()) != null) {
String jarEntryName=jarEntry.getName();
if (StringUtils.endsWith(jarEntryName,".class")) {
jarEntryName=jarEntryName.substring(0,jarEntryName.length() - 6).replace('/','.');
this.byteCode.put(jarEntryName,loadBytes(jarInputStream));
}
else {
this.resources.put(jarEntryName,loadBytes(jarInputStream));
}
}
}
catch ( Exception e) {
logger.error("Failed to read from JAR file '" + jarFile.getAbsolutePath() + "'. Error: "+ e.getMessage());
}
finally {
try {
jarInputStream.close();
}
catch ( Exception e) {
logger.error("Failed to close open JAR file '" + jarFile.getAbsolutePath() + "'. Error: "+ e.getMessage());
}
}
}
}
logger.info("Analyzing " + this.byteCode.size() + " classes for component annotation");
for ( String cjf : this.byteCode.keySet()) {
try {
Class<?> c=loadClass(cjf);
Annotation spqrComponentAnnotation=getSPQRComponentAnnotation(c);
if (spqrComponentAnnotation != null) {
Method spqrAnnotationTypeMethod=spqrComponentAnnotation.getClass().getMethod(ANNOTATION_TYPE_METHOD,(Class[])null);
Method spqrAnnotationNameMethod=spqrComponentAnnotation.getClass().getMethod(ANNOTATION_NAME_METHOD,(Class[])null);
Method spqrAnnotationVersionMethod=spqrComponentAnnotation.getClass().getMethod(ANNOTATION_VERSION_METHOD,(Class[])null);
Method spqrAnnotationDescriptionMethod=spqrComponentAnnotation.getClass().getMethod(ANNOTATION_DESCRIPTION_METHOD,(Class[])null);
@SuppressWarnings("unchecked") Enum<MicroPipelineComponentType> o=(Enum<MicroPipelineComponentType>)spqrAnnotationTypeMethod.invoke(spqrComponentAnnotation,(Object[])null);
final MicroPipelineComponentType componentType=Enum.valueOf(MicroPipelineComponentType.class,o.name());
final String componentName=(String)spqrAnnotationNameMethod.invoke(spqrComponentAnnotation,(Object[])null);
final String componentVersion=(String)spqrAnnotationVersionMethod.invoke(spqrComponentAnnotation,(Object[])null);
final String componentDescription=(String)spqrAnnotationDescriptionMethod.invoke(spqrComponentAnnotation,(Object[])null);
this.managedComponents.put(getManagedComponentKey(componentName,componentVersion),new ComponentDescriptor(c.getName(),componentType,componentName,componentVersion,componentDescription));
logger.info("pipeline component found [type=" + componentType + ", name="+ componentName+ ", version="+ componentVersion+ "]");
;
}
}
catch ( Throwable e) {
e.printStackTrace();
logger.error("Failed to load class '" + cjf + "'. Error: "+ e.getMessage());
}
}
}
| Initializes the class loader by pointing it to folder holding managed JAR files |
public void clearSelection(){
List<CalendarDay> dates=getSelectedDates();
adapter.clearSelections();
for ( CalendarDay day : dates) {
dispatchOnDateSelected(day,false);
}
}
| Clear the currently selected date(s) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.