code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public Class load(String type) throws Exception {
ClassLoader loader=getClassLoader();
if (loader == null) {
loader=getCallerClassLoader();
}
return loader.loadClass(type);
}
| This method is used to acquire the class of the specified name. Loading is performed by the thread context class loader as this will ensure that the class loading strategy can be changed as requirements dictate. Typically the thread context class loader can handle all serialization requirements. |
private double euclideanDistance(DoubleArrayListWritable v1,DoubleArrayListWritable v2,int dim){
double distance=0.0;
for (int i=0; i < dim; i++) {
distance+=math.pow(v1.get(i).get() - v2.get(i).get(),2);
}
return math.sqrt(distance);
}
| Calculates the Euclidean distance between two vectors of doubles |
private List<FacetResult> facetsWithSearch() throws IOException {
DirectoryReader indexReader=DirectoryReader.open(indexDir);
IndexSearcher searcher=new IndexSearcher(indexReader);
TaxonomyReader taxoReader=new DirectoryTaxonomyReader(taxoDir);
FacetsCollector fc=new FacetsCollector();
FacetsCollector.search(searcher,new MatchAllDocsQuery(),10,fc);
List<FacetResult> results=new ArrayList<>();
Facets facets=new FastTaxonomyFacetCounts(taxoReader,config,fc);
results.add(facets.getTopChildren(10,"Author"));
results.add(facets.getTopChildren(10,"Publish Date"));
indexReader.close();
taxoReader.close();
return results;
}
| User runs a query and counts facets. |
public boolean wasAtRest(){
return mWasAtRest;
}
| Check if the spring was at rest in the prior iteration. This is used for ensuring the ending callbacks are fired as the spring comes to a rest. |
protected CIMObjectPath createSubscription(CimFilterInfo filterInfo) throws WBEMException, ConnectionManagerException {
CIMObjectPath filterPath;
if (filterInfo instanceof CimManagedFilterInfo) {
filterPath=createFilter((CimManagedFilterInfo)filterInfo);
}
else {
filterPath=getInstance(CimConstants.CIM_FILTER_NAME,filterInfo.getName()).getObjectPath();
}
s_logger.trace("filterPath :{}",filterPath);
CIMProperty<?> filterProp=new CIMProperty<CIMObjectPath>(CimConstants.SUBSCRIPTION_PROP_FILTER,new CIMDataType(CimConstants.CIM_FILTER_NAME),filterPath);
CIMProperty<?> handlerProp=new CIMProperty<CIMObjectPath>(CimConstants.SUBSCRIPTION_PROP_HANDLER,new CIMDataType(CimConstants.CIM_HANDLER_NAME),getHandler());
s_logger.trace("filterProp :{}",filterProp);
s_logger.trace("handlerProp :{}",handlerProp);
CIMProperty<?>[] subscriptionProperties=new CIMProperty[]{filterProp,handlerProp};
CIMObjectPath subscriptionPath=createInstance(CimConstants.CIM_SUBSCRIPTION_NAME,subscriptionProperties);
_subscriptionPaths.add(subscriptionPath);
s_logger.trace("subscriptionPath :{}",subscriptionPath);
return subscriptionPath;
}
| Creates an indication subscription in the CIMOM for the given filter. |
private void updatePopulation(int[] ids){
List<Integer> archivedIds=new ArrayList<Integer>();
for ( int id : ids) {
archivedIds.add(id);
}
solutions.keySet().retainAll(archivedIds);
}
| Updates the population, retaining only those solutions with the specified identifiers. |
private void updateProgress(String progressLabel,int progress){
if (myHost != null && ((progress != previousProgress) || (!progressLabel.equals(previousProgressLabel)))) {
myHost.updateProgress(progressLabel,progress);
}
previousProgress=progress;
previousProgressLabel=progressLabel;
}
| Used to communicate a progress update between a plugin tool and the main Whitebox user interface. |
private void initializeSparseSlider(){
sparsitySlider.setMajorTickSpacing(10);
sparsitySlider.setMinorTickSpacing(2);
sparsitySlider.setPaintTicks(true);
Hashtable<Integer,JLabel> labelTable2=new Hashtable<Integer,JLabel>();
labelTable2.put(new Integer(0),new JLabel("0%"));
labelTable2.put(new Integer(100),new JLabel("100%"));
sparsitySlider.setLabelTable(labelTable2);
sparsitySlider.setPaintLabels(true);
}
| Initializes the sparse slider. |
public boolean isStereo(){
return (channelMode != 3);
}
| Whether stereo playback mode is used |
@Override public Overlay buildOverlay(MapView map,Style defaultStyle,Styler styler,KmlPlacemark kmlPlacemark,KmlDocument kmlDocument){
Marker marker=new Marker(map);
marker.setTitle(kmlPlacemark.mName);
marker.setSnippet(kmlPlacemark.mDescription);
marker.setSubDescription(kmlPlacemark.getExtendedDataAsText());
marker.setPosition(getPosition());
marker.setRelatedObject(this);
if (styler == null) {
applyDefaultStyling(marker,defaultStyle,kmlPlacemark,kmlDocument,map);
}
else styler.onPoint(marker,kmlPlacemark,this);
return marker;
}
| Build the corresponding Marker overlay |
public static boolean startsWithIgnoreCase(String searchIn,String searchFor){
return startsWithIgnoreCase(searchIn,0,searchFor);
}
| Determines whether or not the string 'searchIn' contains the string 'searchFor', dis-regarding case. Shorthand for a String.regionMatch(...) |
public void removeListener(ColorMapListener listener){
if (listener == null) return;
listeners.remove(listener);
}
| Remove a color map listener |
public T adwordsId(String value){
setString(ADWORDS_ID,value);
return (T)this;
}
| <div class="ind"> <p> Optional. </p> <p>Specifies the Google AdWords Id.</p> <table border="1"> <tbody> <tr> <th>Parameter</th> <th>Value Type</th> <th>Default Value</th> <th>Max Length</th> <th>Supported Hit Types</th> </tr> <tr> <td><code>gclid</code></td> <td>text</td> <td><span class="none">None</span> </td> <td><span class="none">None</span> </td> <td>all</td> </tr> </tbody> </table> <div> Example value: <code>CL6Q-OXyqKUCFcgK2goddQuoHg</code><br> Example usage: <code>gclid=CL6Q-OXyqKUCFcgK2goddQuoHg</code> </div> </div> |
@HLEUnimplemented @HLEFunction(nid=0x9E8AAF8D,version=271) public int sceUsbCamGetZoom(TPointer32 zoomAddr){
zoomAddr.setValue(zoom);
return 0;
}
| Gets the current zoom. |
@Override public Object eGet(int featureID,boolean resolve,boolean coreType){
switch (featureID) {
case MappingPackage.OPERATION_SOURCE__OPERATION:
if (resolve) return getOperation();
return basicGetOperation();
}
return super.eGet(featureID,resolve,coreType);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public static boolean screenshot(Activity activity,String filePath){
View decorView=activity.getWindow().getDecorView();
decorView.setDrawingCacheEnabled(true);
decorView.buildDrawingCache();
Bitmap bitmap=decorView.getDrawingCache();
File imagePath=new File(filePath);
FileOutputStream fos=null;
try {
fos=new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.JPEG,100,fos);
fos.flush();
return true;
}
catch ( Exception e) {
e.printStackTrace();
}
finally {
try {
fos.close();
if (null != bitmap) {
bitmap.recycle();
bitmap=null;
}
}
catch ( Exception e) {
}
decorView.destroyDrawingCache();
decorView.setDrawingCacheEnabled(false);
}
return false;
}
| take a screenshot |
private Counter<String> computeGradient(List<Datum> dataset,Counter<String> weights,int batchSize){
Counter<String> gradient=new ClassicCounter<String>(weights.keySet().size());
for ( Datum datum : dataset) {
double sum=0;
for ( String feature : datum.vX.keySet()) {
sum+=weights.getCount(feature) * datum.vX.getCount(feature);
}
double expSum, derivativeIncrement;
if (datum.label == Label.NEGATIVE) {
expSum=Math.exp(sum);
derivativeIncrement=1.0 / (1.0 + (1.0 / expSum));
}
else {
expSum=Math.exp(-sum);
derivativeIncrement=-1.0 / (1.0 + (1.0 / expSum));
}
for ( String feature : datum.vX.keySet()) {
double g=datum.vX.getCount(feature) * derivativeIncrement;
gradient.incrementCount(feature,g);
}
}
if (this.l2Regularization && dataset.size() > 0) {
final Set<String> features=new HashSet<String>(weights.keySet());
features.addAll(gradient.keySet());
final double dataFraction=dataset.size() / ((double)2 * xi * tuneSetSize);
final double scaledSigmaSquared=sigmaSq / dataFraction;
for ( String key : features) {
double x=weights.getCount(key);
gradient.incrementCount(key,x / scaledSigmaSquared);
}
}
return gradient;
}
| Compute the gradient for the specified set of PRO samples. |
public void testSizingWithWidthConstraint(){
RectangleConstraint constraint=new RectangleConstraint(10.0,new Range(10.0,10.0),LengthConstraintType.FIXED,0.0,new Range(0.0,0.0),LengthConstraintType.NONE);
BlockContainer container=new BlockContainer(new BorderArrangement());
BufferedImage image=new BufferedImage(200,100,BufferedImage.TYPE_INT_RGB);
Graphics2D g2=image.createGraphics();
container.add(new EmptyBlock(5.0,6.0));
Size2D size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(6.0,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(15.0,16.0));
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(16.0,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(12.3,45.6),RectangleEdge.RIGHT);
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(45.6,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(7.0,20.0));
container.add(new EmptyBlock(8.0,45.6),RectangleEdge.RIGHT);
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(45.6,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(12.3,45.6),RectangleEdge.LEFT);
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(45.6,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(10.0,20.0));
container.add(new EmptyBlock(12.3,45.6),RectangleEdge.LEFT);
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(45.6,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(10.0,20.0),RectangleEdge.RIGHT);
container.add(new EmptyBlock(12.3,45.6),RectangleEdge.LEFT);
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(45.6,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(10.0,20.0));
container.add(new EmptyBlock(12.3,45.6),RectangleEdge.LEFT);
container.add(new EmptyBlock(5.4,3.2),RectangleEdge.RIGHT);
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(45.6,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(12.3,45.6),RectangleEdge.BOTTOM);
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(45.6,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(10.0,20.0));
container.add(new EmptyBlock(12.3,45.6),RectangleEdge.BOTTOM);
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(65.6,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(10.0,20.0),RectangleEdge.RIGHT);
container.add(new EmptyBlock(12.3,45.6),RectangleEdge.BOTTOM);
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(65.6,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(21.0,12.3));
container.add(new EmptyBlock(10.0,20.0),RectangleEdge.RIGHT);
container.add(new EmptyBlock(12.3,45.6),RectangleEdge.BOTTOM);
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(65.6,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(10.0,20.0),RectangleEdge.LEFT);
container.add(new EmptyBlock(12.3,45.6),RectangleEdge.BOTTOM);
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(65.6,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(21.0,12.3));
container.add(new EmptyBlock(10.0,20.0),RectangleEdge.LEFT);
container.add(new EmptyBlock(12.3,45.6),RectangleEdge.BOTTOM);
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(65.6,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(21.0,12.3),RectangleEdge.RIGHT);
container.add(new EmptyBlock(10.0,20.0),RectangleEdge.LEFT);
container.add(new EmptyBlock(12.3,45.6),RectangleEdge.BOTTOM);
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(65.6,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(3.0,4.0),RectangleEdge.BOTTOM);
container.add(new EmptyBlock(5.0,6.0),RectangleEdge.LEFT);
container.add(new EmptyBlock(7.0,8.0),RectangleEdge.RIGHT);
container.add(new EmptyBlock(9.0,10.0));
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(14.0,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(12.3,45.6),RectangleEdge.TOP);
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(45.6,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(10.0,20.0));
container.add(new EmptyBlock(12.3,45.6),RectangleEdge.TOP);
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(65.6,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(10.0,20.0),RectangleEdge.RIGHT);
container.add(new EmptyBlock(12.3,45.6),RectangleEdge.TOP);
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(65.6,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(21.0,12.3));
container.add(new EmptyBlock(10.0,20.0),RectangleEdge.TOP);
container.add(new EmptyBlock(12.3,45.6),RectangleEdge.RIGHT);
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(65.6,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(10.0,20.0),RectangleEdge.LEFT);
container.add(new EmptyBlock(12.3,45.6),RectangleEdge.TOP);
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(65.6,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(21.0,12.3));
container.add(new EmptyBlock(10.0,20.0),RectangleEdge.TOP);
container.add(new EmptyBlock(12.3,45.6),RectangleEdge.LEFT);
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(65.6,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(21.0,12.3),RectangleEdge.RIGHT);
container.add(new EmptyBlock(10.0,20.0),RectangleEdge.TOP);
container.add(new EmptyBlock(12.3,45.6),RectangleEdge.LEFT);
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(65.6,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(1.0,2.0),RectangleEdge.TOP);
container.add(new EmptyBlock(5.0,6.0),RectangleEdge.LEFT);
container.add(new EmptyBlock(7.0,8.0),RectangleEdge.RIGHT);
container.add(new EmptyBlock(9.0,10.0));
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(12.0,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(10.0,20.0),RectangleEdge.TOP);
container.add(new EmptyBlock(12.3,45.6),RectangleEdge.BOTTOM);
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(65.6,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(21.0,12.3));
container.add(new EmptyBlock(10.0,20.0),RectangleEdge.TOP);
container.add(new EmptyBlock(12.3,45.6),RectangleEdge.BOTTOM);
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(77.9,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(21.0,12.3),RectangleEdge.RIGHT);
container.add(new EmptyBlock(10.0,20.0),RectangleEdge.TOP);
container.add(new EmptyBlock(12.3,45.6),RectangleEdge.BOTTOM);
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(77.9,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(1.0,2.0),RectangleEdge.TOP);
container.add(new EmptyBlock(3.0,4.0),RectangleEdge.BOTTOM);
container.add(new EmptyBlock(7.0,8.0),RectangleEdge.RIGHT);
container.add(new EmptyBlock(9.0,10.0));
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(16.0,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(21.0,12.3),RectangleEdge.LEFT);
container.add(new EmptyBlock(10.0,20.0),RectangleEdge.TOP);
container.add(new EmptyBlock(12.3,45.6),RectangleEdge.BOTTOM);
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(77.9,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(1.0,2.0),RectangleEdge.TOP);
container.add(new EmptyBlock(3.0,4.0),RectangleEdge.BOTTOM);
container.add(new EmptyBlock(5.0,6.0),RectangleEdge.LEFT);
container.add(new EmptyBlock(9.0,10.0));
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(16.0,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(1.0,2.0),RectangleEdge.TOP);
container.add(new EmptyBlock(3.0,4.0),RectangleEdge.BOTTOM);
container.add(new EmptyBlock(5.0,6.0),RectangleEdge.LEFT);
container.add(new EmptyBlock(7.0,8.0),RectangleEdge.RIGHT);
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(14.0,size.height,EPSILON);
container.clear();
container.add(new EmptyBlock(1.0,2.0),RectangleEdge.TOP);
container.add(new EmptyBlock(3.0,4.0),RectangleEdge.BOTTOM);
container.add(new EmptyBlock(5.0,6.0),RectangleEdge.LEFT);
container.add(new EmptyBlock(7.0,8.0),RectangleEdge.RIGHT);
container.add(new EmptyBlock(9.0,10.0));
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(16.0,size.height,EPSILON);
container.clear();
size=container.arrange(g2,constraint);
assertEquals(10.0,size.width,EPSILON);
assertEquals(0.0,size.height,EPSILON);
}
| Run some checks on sizing when there is a fixed width constraint. |
private void receivedFollowerOrSubscriberCount(FollowerInfo followerInfo){
if (followerInfo.requestError) {
return;
}
StreamInfo streamInfo=api.getStreamInfo(followerInfo.stream,null);
boolean changed=false;
if (followerInfo.type == Follower.Type.SUBSCRIBER) {
changed=streamInfo.setSubscriberCount(followerInfo.total);
}
else if (followerInfo.type == Follower.Type.FOLLOWER) {
changed=streamInfo.setFollowerCount(followerInfo.total);
}
if (changed && streamInfo.isValid()) {
streamStatusWriter.streamStatus(streamInfo);
}
}
| Set follower/subscriber count in StreamInfo and send to Stream Status Writer. |
public FrameSlot findOrAddFrameSlot(Object identifier,FrameSlotKind kind){
FrameSlot result=findFrameSlot(identifier);
if (result != null) {
return result;
}
return addFrameSlot(identifier,kind);
}
| Finds an existing slot or creates new one. This is a slow operation. |
private static boolean isValidVersionNumber(final String version){
if (version == null) {
return false;
}
final String[] parts=version.split("\\.");
if (parts.length != 3) {
return false;
}
for ( final String part : parts) {
if (!Convert.isDecString(part)) {
return false;
}
}
return true;
}
| Checks whether a given version string is a valid version string. |
@ObjectiveCName("isInAppNotificationsEnabled") public boolean isInAppNotificationsEnabled(){
return modules.getSettingsModule().isInAppEnabled();
}
| Is in-app notifications enabled |
@Override public void intervalAdded(ListDataEvent event){
calculatePositionArray();
setPreferredSize(calculatePreferredSize());
}
| Listen for items being added to the model. |
public static MaterialColor fromInt(@ColorInt int color){
return new MaterialColor(color);
}
| Create a MaterialColor from the provided color value. |
public void shouldHandleThrowingFutureCallable(){
assertThrows(null,ExecutionException.class,IllegalArgumentException.class);
assertThrows(null,ExecutionException.class,IllegalArgumentException.class);
assertThrows(null,ExecutionException.class,IllegalArgumentException.class);
}
| Assert handles a callable that throws instead of returning a future. |
public CategoricalColumn(){
super(ColumnType.CATEGORICAL);
}
| Instantiates a new categorical column. |
@MethodDesc(description="Starts the replicator service",usage="start") public void start(boolean forceOffline) throws Exception {
try {
handleEventSynchronous(new StartEvent());
if (sm.getState().getName().equals("OFFLINE:NORMAL")) {
boolean autoEnabled=new Boolean(properties.getBoolean(ReplicatorConf.AUTO_ENABLE));
if (!forceOffline && autoEnabled) {
logger.info("Replicator auto-enabling is engaged; going online automatically");
online();
}
}
}
catch ( Exception e) {
logger.error("Start operation failed",e);
throw new Exception("Start operation failed: " + e.getMessage());
}
this.doneLatch=new CountDownLatch(1);
}
| Start Replicator Node Manager JMX service. |
Alerter(AlertService service,int timeout,AtomicInteger jobCounter){
this.service=service;
this.timeout=timeout;
this.jobCounter=jobCounter;
}
| Creates a new Alerter object. |
private void removeAnyCallbacks(){
if (mPerformSearchRunnable != null) {
mHandler.removeCallbacks(mPerformSearchRunnable);
}
}
| Removes any pending callbacks(if any) from the handler |
@Override public Object eGet(int featureID,boolean resolve,boolean coreType){
switch (featureID) {
case EipPackage.GATEWAY__NAME:
return getName();
case EipPackage.GATEWAY__TO_CHANNELS:
return getToChannels();
case EipPackage.GATEWAY__FROM_CHANNELS:
return getFromChannels();
}
return super.eGet(featureID,resolve,coreType);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
static void appendDate(StringBuilder buff,long dateValue){
int y=DateTimeUtils.yearFromDateValue(dateValue);
int m=DateTimeUtils.monthFromDateValue(dateValue);
int d=DateTimeUtils.dayFromDateValue(dateValue);
if (y > 0 && y < 10000) {
StringUtils.appendZeroPadded(buff,4,y);
}
else {
buff.append(y);
}
buff.append('-');
StringUtils.appendZeroPadded(buff,2,m);
buff.append('-');
StringUtils.appendZeroPadded(buff,2,d);
}
| Append a date to the string builder. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-09-03 14:59:54.006 -0400",hash_original_method="FFD73B06BFF281953B16F54803697DC3",hash_generated_method="9914BD0B75BD9C1F8FA2F0E0462B401B") protected FalseFileFilter(){
}
| Restrictive consructor. |
@Inline public static boolean fits(Word val,int bits){
Word o=val.rsha(bits - 1);
return (o.isZero() || o.isMax());
}
| Finds out whether a given signed value can be represented in a given number of bits. |
public static Map<String,Object> removeDuplicateScrumRevision(DispatchContext ctx,Map<String,? extends Object> context){
Delegator delegator=ctx.getDelegator();
LocalDispatcher dispatcher=ctx.getDispatcher();
String repositoryRoot=(String)context.get("repositoryRoot");
Map<String,Object> result=ServiceUtil.returnSuccess();
try {
List<EntityCondition> exprsAnd=FastList.newInstance();
String revisionLink=repositoryRoot.substring(repositoryRoot.lastIndexOf("svn/") + 4,repositoryRoot.length()) + "&revision=";
exprsAnd.add(EntityCondition.makeCondition("workEffortContentTypeId",EntityOperator.EQUALS,"TASK_SUB_INFO"));
exprsAnd.add(EntityCondition.makeCondition("contentTypeId",EntityOperator.EQUALS,"DOCUMENT"));
exprsAnd.add(EntityCondition.makeCondition("drObjectInfo",EntityOperator.LIKE,revisionLink + "%"));
List<GenericValue> workEffortDataResourceList=EntityQuery.use(delegator).from("WorkEffortAndContentDataResource").where(exprsAnd).queryList();
if (UtilValidate.isNotEmpty(workEffortDataResourceList)) {
Debug.logInfo("Total Content Size ============== >>>>>>>>>>> " + workEffortDataResourceList.size(),module);
Set<String> keys=FastSet.newInstance();
Set<GenericValue> exclusions=FastSet.newInstance();
for ( GenericValue workEffort : workEffortDataResourceList) {
String drObjectInfo=workEffort.getString("drObjectInfo");
if (keys.contains(drObjectInfo)) {
exclusions.add(workEffort);
}
else {
keys.add(drObjectInfo);
}
}
Debug.logInfo("Remove size ============== >>>>>>>>>>> " + exclusions.size(),module);
if (UtilValidate.isNotEmpty(exclusions)) {
for ( GenericValue contentResourceMap : exclusions) {
Debug.logInfo("Remove contentId ============== >>>>>>>>>>> " + contentResourceMap.getString("contentId"),module);
GenericValue dataResourceMap=EntityQuery.use(delegator).from("DataResource").where("dataResourceId",contentResourceMap.getString("dataResourceId")).queryOne();
GenericValue contentMap=EntityQuery.use(delegator).from("Content").where("contentId",contentResourceMap.getString("contentId")).queryOne();
contentMap.removeRelated("WorkEffortContent");
contentMap.removeRelated("ContentRole");
contentMap.remove();
dataResourceMap.removeRelated("DataResourceRole");
dataResourceMap.remove();
}
}
}
}
catch ( GenericEntityException entityEx) {
entityEx.printStackTrace();
return ServiceUtil.returnError(entityEx.getMessage());
}
return result;
}
| removeDuplicateScrumRevision <p> Use for remove duplicate scrum revision |
private void updateProgress(String progressLabel,int progress){
if (myHost != null && ((progress != previousProgress) || (!progressLabel.equals(previousProgressLabel)))) {
myHost.updateProgress(progressLabel,progress);
}
previousProgress=progress;
previousProgressLabel=progressLabel;
}
| Used to communicate a progress update between a plugin tool and the main Whitebox user interface. |
private void checkCapture(GenericClassType genericClassType,ReferenceType paramType,ReferenceType actualArgType,List<TypedOperation> genericOperations){
InstantiatedType finalType=genericClassType.instantiate(actualArgType);
InstantiatedType instantiatedType=sourceType.instantiate(paramType);
Substitution<ReferenceType> substitution=instantiatedType.getTypeSubstitution();
for ( TypedOperation op : genericOperations) {
InstantiatedType argumentType=getArgumentType(op).apply(substitution);
InstantiatedType convertedArgumentType=argumentType.applyCaptureConversion();
List<TypeVariable> arguments=convertedArgumentType.getTypeParameters();
if (arguments.size() > 0) {
Substitution<ReferenceType> wcSubst=Substitution.forArgs(arguments,actualArgType);
convertedArgumentType=convertedArgumentType.apply(wcSubst);
}
if (op.hasWildcardTypes()) {
assertEquals("should be instantiated type for method " + op.getName() + " argument.",finalType,convertedArgumentType);
}
else {
assertEquals("should not be converted " + op.getName(),argumentType,convertedArgumentType);
}
}
}
| Checks the capture conversion over a set of types with wildcard (given as the input types to operations). Checks that the conversion followed by the substitution for the capture variable result in the class type instantiated by the actual argument type. |
public static synchronized LogStream switchLog(final File newLog){
if (sLogStream != null) {
userLog("Switching logfile to:" + newLog.getAbsolutePath());
final File file=sLogStream.file();
if (newLog.equals(file)) {
return sLogStream;
}
sLogStream.removeLog();
}
if (!newLog.getParentFile().exists()) {
if (!newLog.getParentFile().mkdirs()) {
throw new RuntimeException("Unable to create directory for log file.");
}
}
sLogStream=new LogFile(newLog);
sLogClosed=false;
logEnvironment();
return sLogStream;
}
| Switch the log to a (usually) different output file. |
protected SimState(MersenneTwisterFast random,Schedule schedule){
this(0,random,schedule);
}
| Creates a SimState with the given random number generator and schedule, and sets the seed to a bogus value (0). This should only be used by SimState subclasses which need to use an existing random number generator and schedule. |
public void addEditor(){
removeEditor();
editor=comboBox.getEditor().getEditorComponent();
if (editor != null) {
configureEditor();
comboBox.add(editor);
if (comboBox.isFocusOwner()) {
editor.requestFocusInWindow();
}
}
}
| This public method is implementation specific and should be private. do not call or override. To implement a specific editor create a custom <code>ComboBoxEditor</code> |
public void init(int value){
if (value == -1) {
throw new IllegalArgumentException("IntConstant cannot be initialized with a value of -1");
}
synchronized (this) {
if (this.value != -1) {
throw new IllegalStateException("IntConstant already initialized!");
}
this.value=value;
}
}
| Initializes the constant. This method can only be called once. |
public StAndrewsSimulation(long seed){
super(seed);
}
| Create a new StAndrewsSimulation with the given randomization seed. |
public AuthenticationNotSupportedException(){
super();
}
| Constructs a new instance of AuthenticationNotSupportedException all name resolution fields and explanation initialized to null. |
public synchronized void addMemberAsync(Contact contact){
notifyMemberJoined(contact);
}
| Adds a member to this group. TODO: more docs on async callbacks. |
public Record(){
super();
setEntity(new Entity(TYPE_ID));
getEntity().initDefaultValues(getTypeFactory());
}
| Creates an empty asset |
@Override protected void makeCastlingMove(Move move){
FischerRandomUtils.makeCastlingMove(this,move,initialKingFile,initialShortRookFile,initialLongRookFile);
}
| Overridden to handle special FR castling rules. |
@DSComment("Package priviledge") @DSBan(DSCat.DEFAULT_MODIFIER) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:29:52.081 -0500",hash_original_method="0309B89A8A5C20FB439CB65AA9DE3FAA",hash_generated_method="0309B89A8A5C20FB439CB65AA9DE3FAA") void enforceSealed(){
if (!isSealed()) {
throw new IllegalStateException("Cannot perform this " + "action on a not sealed instance.");
}
}
| Enforces that this instance is sealed. |
public void unload(){
GLES20.glDeleteShader(mVShaderHandle);
GLES20.glDeleteShader(mFShaderHandle);
GLES20.glDeleteProgram(mProgram);
}
| Unloads and deletes references to the shader program |
default <T>T newInstance(Class<T> concreteClass){
try {
return concreteClass.newInstance();
}
catch ( Exception ex) {
throw new UncheckedException(ex);
}
}
| Called to construct actor. |
@Override public boolean createFrom(final IScope scope,final List<Map<String,Object>> inits,final Integer max,final Object input,final Arguments init,final CreateStatement statement){
final GamaGridFile file=(GamaGridFile)input;
final int num=max == null ? file.length(scope) : CmnFastMath.min(file.length(scope),max);
for (int i=0; i < num; i++) {
final IShape g=file.get(scope,i);
final Map map=g.getOrCreateAttributes();
map.put(IKeyword.SHAPE,g);
statement.fillWithUserInit(scope,map);
inits.add(map);
}
return true;
}
| Method createFrom() Method used to read initial values and attributes from a GRID file. |
protected void processFiles(String ext,boolean recursive,File outDir,serverObjects post,File[] inFiles,List<File> processedFiles,Map<String,Throwable> failures) throws IOException {
for ( File inFile : inFiles) {
if (inFile.isDirectory()) {
if (recursive) {
File subDir=new File(outDir,inFile.getName());
subDir.mkdirs();
processFiles(ext,recursive,subDir,post,inFile.listFiles(),processedFiles,failures);
}
}
else {
processedFiles.add(inFile);
processFile(ext,outDir,post,failures,inFile);
}
}
}
| Process inFiles and update processedFiles list and failures map. All parameters must not be null. |
private void languageComboChanged(){
String langName=(String)languageCombo.getSelectedItem();
Language language=Language.getLanguage(langName);
Language.setLoginLanguage(language);
Env.setContext(m_ctx,Env.LANGUAGE,language.getAD_Language());
Locale loc=language.getLocale();
Locale.setDefault(loc);
this.setLocale(loc);
res=ResourceBundle.getBundle(RESOURCE,loc);
this.setTitle(res.getString("Login"));
hostLabel.setText(res.getString("Host"));
userLabel.setText(res.getString("User"));
userLabel.setToolTipText(res.getString("EnterUser"));
passwordLabel.setText(res.getString("Password"));
passwordLabel.setToolTipText(res.getString("EnterPassword"));
languageLabel.setText(res.getString("Language"));
languageLabel.setToolTipText(res.getString("SelectLanguage"));
roleLabel.setText(res.getString("Role"));
clientLabel.setText(res.getString("Client"));
orgLabel.setText(res.getString("Organization"));
dateLabel.setText(res.getString("Date"));
warehouseLabel.setText(res.getString("Warehouse"));
printerLabel.setText(res.getString("Printer"));
defaultPanel.setToolTipText(res.getString("Defaults"));
connectionPanel.setToolTipText(res.getString("Connection"));
txt_NotConnected=res.getString("NotConnected");
txt_NoDatabase=res.getString("DatabaseNotFound");
txt_UserPwdError=res.getString("UserPwdError");
txt_RoleError=res.getString("RoleNotFound");
txt_LoggedIn=res.getString("Authorized");
loginTabPane.setTitleAt(0,res.getString("Connection"));
loginTabPane.setTitleAt(1,res.getString("Defaults"));
confirmPanel.getOKButton().setToolTipText(res.getString("Ok"));
confirmPanel.getCancelButton().setToolTipText(res.getString("Cancel"));
dateField.setFormat();
dateField.setValue(new Timestamp(System.currentTimeMillis()));
if (m_connectionOK) {
this.setTitle(hostField.getDisplay());
statusBar.setStatusLine(txt_LoggedIn);
}
else {
this.setTitle(res.getString("Login"));
statusBar.setStatusLine(txt_NotConnected,true);
}
}
| Change Language |
@Override protected void prepare(){
AD_User_ID=Env.getAD_User_ID(getCtx());
p_Record_ID=getRecord_ID();
for ( ProcessInfoParameter para : getParameter()) {
String name=para.getParameterName();
if (para.getParameter() == null) ;
else if (name.equals("WM_Area_Type_ID")) {
p_WM_Area_Type_ID=para.getParameterAsInt();
}
else if (name.equals("WM_Section_Type_ID")) {
p_WM_Section_Type_ID=para.getParameterAsInt();
}
else if (name.equals("DeliveryRule")) {
p_DeliveryRule=(String)para.getParameter();
}
else if (name.equals("DocAction")) {
p_DocAction=(String)para.getParameter();
}
else if (name.equals("C_DocType_ID")) {
p_C_DocType_ID=para.getParameterAsInt();
}
else if (name.equals("M_Locator_ID")) {
p_M_Locator_ID=para.getParameterAsInt();
m_locator=new MLocator(getCtx(),p_M_Locator_ID,get_TrxName());
}
else if (name.equals("IsPrintPickList")) {
p_IsPrintPickList="Y".equals(para.getParameter());
}
else if (name.equals("IsCreateSupply")) {
p_IsCreateSupply="Y".equals(para.getParameter());
}
else log.log(Level.SEVERE,"Unknown Parameter: " + name);
}
}
| Get Parameters |
private void buildSpellTables(){
try {
final SpellGroupsXMLLoader loader=new SpellGroupsXMLLoader(new URI("/data/conf/spells.xml"));
List<DefaultSpell> loadedDefaultSpells=loader.load();
for ( DefaultSpell defaultSpell : loadedDefaultSpells) {
addSpell(defaultSpell);
}
}
catch ( Exception e) {
LOGGER.error("spells.xml could not be loaded",e);
}
}
| builds the spell tables |
public LogEventReplReader(LogRecord logRecord,Serializer serializer,boolean checkCRC) throws ReplicatorException {
this.logRecord=logRecord;
this.serializer=serializer;
this.checkCRC=checkCRC;
try {
load();
}
catch ( IOException e) {
throw new THLException("I/O error while loading log record header: offset=" + logRecord.getOffset(),e);
}
}
| Instantiate the reader and load header information. |
public static IndexKeyRange bounded(IndexRowType indexRowType,IndexBound lo,boolean loInclusive,IndexBound hi,boolean hiInclusive){
if (lo == null || hi == null) {
throw new IllegalArgumentException("IndexBound arguments must not be null");
}
return new IndexKeyRange(indexRowType,lo,loInclusive,hi,hiInclusive,IndexKind.CONVENTIONAL);
}
| Describes a range of keys between lo and hi. The bounds are inclusive or not depending on loInclusive and hiInclusive. lo and hi must both be non-null. There are constraints on the bounds: - The ColumnSelectors for lo and hi must select for the same columns. - The selected columns must be leading columns of the index. |
@Override public void updateRef(int columnIndex,Ref x) throws SQLException {
throw unsupported("ref");
}
| [Not supported] |
public NavigationModel(String id){
super(id);
}
| Construct a new emtpy NavigationModel with the specified ID. |
@NotNull default B append(double d) throws BufferOverflowException {
BytesInternal.append((StreamingDataOutput)this,d);
return (B)this;
}
| Append a double in decimal notation |
@Entrypoint @UnpreemptibleNoWarn static void deliverHardwareException(int trapCode,Word trapInfo){
if (VM.verboseSignalHandling) VM.sysWriteln("delivering hardware exception");
RVMThread myThread=RVMThread.getCurrentThread();
if (VM.verboseSignalHandling) VM.sysWriteln("we have a thread = ",Magic.objectAsAddress(myThread));
if (VM.verboseSignalHandling) VM.sysWriteln("it's in state = ",myThread.getExecStatus());
AbstractRegisters exceptionRegisters=myThread.getExceptionRegisters();
if (VM.verboseSignalHandling) VM.sysWriteln("we have exception registers = ",Magic.objectAsAddress(exceptionRegisters));
if ((trapCode == TRAP_STACK_OVERFLOW || trapCode == TRAP_JNI_STACK) && myThread.getStack().length < (StackFrameLayout.getMaxStackSize() >> LOG_BYTES_IN_ADDRESS) && !myThread.hasNativeStackFrame()) {
if (trapCode == TRAP_JNI_STACK) {
RVMThread.resizeCurrentStack(myThread.getStackLength() + StackFrameLayout.getJNIStackGrowthSize(),exceptionRegisters);
}
else {
RVMThread.resizeCurrentStack(myThread.getStackLength() + StackFrameLayout.getStackGrowthSize(),exceptionRegisters);
}
if (VM.VerifyAssertions) VM._assert(exceptionRegisters.getInUse());
exceptionRegisters.setInUse(false);
Magic.restoreHardwareExceptionState(exceptionRegisters);
if (VM.VerifyAssertions) VM._assert(NOT_REACHED);
}
if (canForceGC()) {
System.gc();
}
if (!VM.sysFailInProgress()) {
Address fp=exceptionRegisters.getInnermostFramePointer();
int compiledMethodId=Magic.getCompiledMethodID(fp);
if (compiledMethodId != StackFrameLayout.getInvisibleMethodID()) {
CompiledMethod compiledMethod=CompiledMethods.getCompiledMethod(compiledMethodId);
Address ip=exceptionRegisters.getInnermostInstructionAddress();
Offset instructionOffset=compiledMethod.getInstructionOffset(ip);
if (compiledMethod.isWithinUninterruptibleCode(instructionOffset)) {
switch (trapCode) {
case TRAP_NULL_POINTER:
VM.sysWriteln("\nFatal error: NullPointerException within uninterruptible region.");
break;
case TRAP_ARRAY_BOUNDS:
VM.sysWriteln("\nFatal error: ArrayIndexOutOfBoundsException within uninterruptible region (index was ",trapInfo.toInt(),").");
break;
case TRAP_DIVIDE_BY_ZERO:
VM.sysWriteln("\nFatal error: DivideByZero within uninterruptible region.");
break;
case TRAP_STACK_OVERFLOW:
case TRAP_JNI_STACK:
VM.sysWriteln("\nFatal error: StackOverflowError within uninterruptible region.");
break;
case TRAP_CHECKCAST:
VM.sysWriteln("\nFatal error: ClassCastException within uninterruptible region.");
break;
case TRAP_MUST_IMPLEMENT:
VM.sysWriteln("\nFatal error: IncompatibleClassChangeError within uninterruptible region.");
break;
case TRAP_STORE_CHECK:
VM.sysWriteln("\nFatal error: ArrayStoreException within uninterruptible region.");
break;
case TRAP_UNREACHABLE_BYTECODE:
VM.sysWriteln("\nFatal error: Reached a bytecode that was determined to be unreachable within uninterruptible region.");
break;
default :
VM.sysWriteln("\nFatal error: Unknown hardware trap within uninterruptible region.");
break;
}
VM.sysWriteln("trapCode = ",trapCode);
VM.sysWriteln("trapInfo = ",trapInfo.toAddress());
VM.sysFail("Exiting virtual machine due to uninterruptibility violation.");
}
}
}
Throwable exceptionObject;
switch (trapCode) {
case TRAP_NULL_POINTER:
exceptionObject=new java.lang.NullPointerException();
break;
case TRAP_ARRAY_BOUNDS:
exceptionObject=new java.lang.ArrayIndexOutOfBoundsException(trapInfo.toInt());
break;
case TRAP_DIVIDE_BY_ZERO:
exceptionObject=new java.lang.ArithmeticException();
break;
case TRAP_STACK_OVERFLOW:
case TRAP_JNI_STACK:
exceptionObject=new java.lang.StackOverflowError();
break;
case TRAP_CHECKCAST:
exceptionObject=new java.lang.ClassCastException();
break;
case TRAP_MUST_IMPLEMENT:
exceptionObject=new java.lang.IncompatibleClassChangeError();
break;
case TRAP_STORE_CHECK:
exceptionObject=new java.lang.ArrayStoreException();
break;
case TRAP_UNREACHABLE_BYTECODE:
exceptionObject=new java.lang.InternalError(UNREACHABLE_BC_MESSAGE);
break;
default :
exceptionObject=new java.lang.UnknownError();
RVMThread.traceback("UNKNOWN ERROR");
break;
}
VM.disableGC();
deliverException(exceptionObject,exceptionRegisters);
}
| Deliver a hardware exception to current java thread. <p> Does not return. (stack is unwound, starting at trap site, and execution resumes in a catch block somewhere up the stack) /or/ execution resumes at instruction following trap (for TRAP_STACK_OVERFLOW) <p> Note: Control reaches here by the actions of an external "C" signal handler which saves the register state of the trap site into the "exceptionRegisters" field of the current Thread object. The signal handler also inserts a <hardware trap> frame onto the stack immediately above this frame, for use by HardwareTrapGCMapIterator during garbage collection. |
public static BigInteger[] transformRawSignature(byte[] raw) throws IOException {
BigInteger[] output=new BigInteger[2];
output[0]=new BigInteger(1,Arrays.copyOfRange(raw,0,32));
output[1]=new BigInteger(1,Arrays.copyOfRange(raw,32,64));
return output;
}
| From byte[] to Big Integers r,s UAF_ALG_SIGN_SECP256K1_ECDSA_SHA256_RAW 0x05 An ECDSA signature on the secp256k1 curve which must have raw R and S buffers, encoded in big-endian order. I.e.[R (32 bytes), S (32 bytes)] |
public static void println(Object self,Object value){
if (self instanceof Writer) {
final PrintWriter pw=new GroovyPrintWriter((Writer)self);
pw.println(value);
}
else {
System.out.println(InvokerHelper.toString(value));
}
}
| Print a value formatted Groovy style (followed by a newline) to self if it is a Writer, otherwise to the standard output stream. |
protected void checkProcessorVersion(Hashtable h){
if (null == h) h=new Hashtable();
try {
final String XALAN1_VERSION_CLASS="org.apache.xalan.xslt.XSLProcessorVersion";
Class clazz=ObjectFactory.findProviderClass(XALAN1_VERSION_CLASS,ObjectFactory.findClassLoader(),true);
StringBuffer buf=new StringBuffer();
Field f=clazz.getField("PRODUCT");
buf.append(f.get(null));
buf.append(';');
f=clazz.getField("LANGUAGE");
buf.append(f.get(null));
buf.append(';');
f=clazz.getField("S_VERSION");
buf.append(f.get(null));
buf.append(';');
h.put(VERSION + "xalan1",buf.toString());
}
catch ( Exception e1) {
h.put(VERSION + "xalan1",CLASS_NOTPRESENT);
}
try {
final String XALAN2_VERSION_CLASS="org.apache.xalan.processor.XSLProcessorVersion";
Class clazz=ObjectFactory.findProviderClass(XALAN2_VERSION_CLASS,ObjectFactory.findClassLoader(),true);
StringBuffer buf=new StringBuffer();
Field f=clazz.getField("S_VERSION");
buf.append(f.get(null));
h.put(VERSION + "xalan2x",buf.toString());
}
catch ( Exception e2) {
h.put(VERSION + "xalan2x",CLASS_NOTPRESENT);
}
try {
final String XALAN2_2_VERSION_CLASS="org.apache.xalan.Version";
final String XALAN2_2_VERSION_METHOD="getVersion";
final Class noArgs[]=new Class[0];
Class clazz=ObjectFactory.findProviderClass(XALAN2_2_VERSION_CLASS,ObjectFactory.findClassLoader(),true);
Method method=clazz.getMethod(XALAN2_2_VERSION_METHOD,noArgs);
Object returnValue=method.invoke(null,new Object[0]);
h.put(VERSION + "xalan2_2",(String)returnValue);
}
catch ( Exception e2) {
h.put(VERSION + "xalan2_2",CLASS_NOTPRESENT);
}
}
| Report product version information from Xalan-J. Looks for version info in xalan.jar from Xalan-J products. |
public void deinstall(JEditorPane c){
c.removeCaretListener(inputAttributeUpdater);
c.removePropertyChangeListener(inputAttributeUpdater);
currentRun=null;
currentParagraph=null;
}
| Called when the kit is being removed from the JEditorPane. This is used to unregister any listeners that were attached. |
public void dismissAndSwitch(){
final int numIcons=mIcons.length;
RecentTag tag=null;
for (int i=0; i < numIcons; i++) {
if (mIcons[i].getVisibility() != View.VISIBLE) {
break;
}
if (i == 0 || mIcons[i].hasFocus()) {
tag=(RecentTag)mIcons[i].getTag();
if (mIcons[i].hasFocus()) {
break;
}
}
}
if (tag != null) {
switchTo(tag);
}
dismiss();
}
| Dismiss the dialog and switch to the selected application. |
public byte toReal(){
return _real;
}
| Returns the real value. |
public void updateParameterInfo(@NotNull final PyArgumentList arglist,@NotNull final UpdateParameterInfoContext context){
if (context.getParameterOwner() != arglist) {
context.removeHint();
return;
}
List<PyExpression> flat_args=PyUtil.flattenedParensAndLists(arglist.getArguments());
int alleged_cursor_offset=context.getOffset();
final TextRange argListTextRange=arglist.getTextRange();
if (!argListTextRange.contains(alleged_cursor_offset) && arglist.getText().endsWith(")")) {
context.removeHint();
return;
}
PsiFile file=context.getFile();
CharSequence chars=file.getViewProvider().getContents();
int offset=-1;
for ( PyExpression arg : flat_args) {
TextRange range=arg.getTextRange();
int left=CharArrayUtil.shiftBackward(chars,range.getStartOffset() - 1," \t\r\n");
int right=CharArrayUtil.shiftForwardCarefully(chars,range.getEndOffset()," \t\r\n");
if (arg.getParent() instanceof PyListLiteralExpression || arg.getParent() instanceof PyTupleExpression) {
right=CharArrayUtil.shiftForward(chars,range.getEndOffset()," \t\r\n])");
}
if (left <= alleged_cursor_offset && right >= alleged_cursor_offset) {
offset=range.getStartOffset();
break;
}
}
context.setCurrentParameter(offset);
}
| <b>Note: instead of parameter index, we directly store parameter's offset for later use.</b><br/> We cannot store an index since we cannot determine what is an argument until we actually map arguments to parameters. This is because a tuple in arguments may be a whole argument or map to a tuple parameter. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:36:13.915 -0500",hash_original_method="E54E1790034E06C2564EA8F8D322C604",hash_generated_method="4A4D6596F1AA464E59CD29757B0A54BF") @Deprecated public SslError(int error,SslCertificate certificate){
this(error,certificate,"");
}
| Creates a new SslError object using the supplied error and certificate. The URL will be set to the empty string. |
private static boolean hasXMPHeader(byte[] data){
if (data.length < XMP_HEADER_SIZE) {
return false;
}
try {
byte[] header=new byte[XMP_HEADER_SIZE];
System.arraycopy(data,0,header,0,XMP_HEADER_SIZE);
if (new String(header,"UTF-8").equals(XMP_HEADER)) {
return true;
}
}
catch ( UnsupportedEncodingException e) {
return false;
}
return false;
}
| Checks whether the byte array has XMP header. The XMP section contains a fixed length header XMP_HEADER. |
public ButtonFactory(ResourceBundle rb,ActionMap am){
super(rb);
actions=am;
}
| Creates a new button factory |
private void updateRangesFields(){
fRanges=(mask & ~(1 << 31));
fContextual=((mask & (1 << 31)) != 0);
if (fContextual) {
fRanges=(mask & ~(1 << 31));
fDefaultContextIndex=key;
}
else {
fRanges=mask;
fSingleRangeIndex=key;
}
}
| Updates all private serialized fields for object to be correctly serialized according to the serialized form of this class mentioned in the documentation. |
public void startCountdown(int sec){
mCountdownView.startCountDown(sec);
}
| Starts the countdown timer. |
public long readLongFromXML(Element node) throws Exception {
if (DEBUG) {
trace(new Throwable(),node.getAttribute(ATT_NAME));
}
m_CurrentNode=node;
return ((Long)getPrimitive(node)).longValue();
}
| builds the primitive from the given DOM node. |
public static ZeroConfService create(String type,String name,int port,int weight,int priority,HashMap<String,String> properties){
ZeroConfService s;
if (ZeroConfService.services().containsKey(ZeroConfService.key(type,name))) {
s=ZeroConfService.services().get(ZeroConfService.key(type,name));
log.debug("Using existing ZeroConfService {}",s.key());
}
else {
properties.put("version",jmri.Version.name());
properties.put("jmri",jmri.Version.getCanonicalVersion());
properties.put("node",NodeIdentity.identity());
s=new ZeroConfService(ServiceInfo.create(type,name,port,weight,priority,properties));
log.debug("Creating new ZeroConfService {} with properties {}",s.key(),properties);
}
return s;
}
| Create a ZeroConfService. The property <i>version</i> is added or replaced with the current JMRI version as its value. The property <i>jmri</i> is added or replaced with the JMRI major.minor.test version string as its value. <p> If a service with the same key as the new service is already published, the original service is returned unmodified. |
public void cancelChallanReceiptOnCreation(final ReceiptHeader receiptHeader){
final ReceiptHeader receiptHeaderToBeCancelled=receiptHeaderService.findById(receiptHeader.getReceiptHeader().getId(),false);
receiptHeaderToBeCancelled.setStatus(collectionsUtil.getStatusForModuleAndCode(CollectionConstants.MODULE_NAME_RECEIPTHEADER,CollectionConstants.RECEIPT_STATUS_CODE_CANCELLED));
receiptHeaderService.persist(receiptHeaderToBeCancelled);
}
| This method cancels the receipt against a challan. The reason for cancellation is set and the staus is changed to CANCELLED. |
public static double nextDouble(double value,boolean increment){
return increment ? nextDouble(value) : previousDouble(value);
}
| Returns the double value which is closest to the specified double but either larger or smaller as specified. |
private void checkSourceVersionCompatibility(Source source,Log log){
SourceVersion procSourceVersion=processor.getSupportedSourceVersion();
if (procSourceVersion.compareTo(Source.toSourceVersion(source)) < 0) {
log.warning("proc.processor.incompatible.source.version",procSourceVersion,Wrappers.unwrapProcessorClass(processor).getName(),source.name);
}
}
| Checks whether or not a processor's source version is compatible with the compilation source version. The processor's source version needs to be greater than or equal to the source version of the compile. |
void openPolicy(String filename) throws FileNotFoundException, PolicyParser.ParsingException, KeyStoreException, CertificateException, InstantiationException, MalformedURLException, IOException, NoSuchAlgorithmException, IllegalAccessException, NoSuchMethodException, UnrecoverableKeyException, NoSuchProviderException, ClassNotFoundException, PropertyExpander.ExpandException, InvocationTargetException {
newWarning=false;
policyEntries=new Vector<PolicyEntry>();
parser=new PolicyParser();
warnings=new Vector<String>();
setPolicyFileName(null);
clearKeyStoreInfo();
if (filename == null) {
modified=false;
return;
}
setPolicyFileName(filename);
parser.read(new FileReader(filename));
openKeyStore(parser.getKeyStoreUrl(),parser.getKeyStoreType(),parser.getKeyStoreProvider(),parser.getStorePassURL());
Enumeration<PolicyParser.GrantEntry> enum_=parser.grantElements();
while (enum_.hasMoreElements()) {
PolicyParser.GrantEntry ge=enum_.nextElement();
if (ge.signedBy != null) {
String signers[]=parseSigners(ge.signedBy);
for (int i=0; i < signers.length; i++) {
PublicKey pubKey=getPublicKeyAlias(signers[i]);
if (pubKey == null) {
newWarning=true;
MessageFormat form=new MessageFormat(getMessage("Warning.A.public.key.for.alias.signers.i.does.not.exist.Make.sure.a.KeyStore.is.properly.configured."));
Object[] source={signers[i]};
warnings.addElement(form.format(source));
}
}
}
ListIterator<PolicyParser.PrincipalEntry> prinList=ge.principals.listIterator(0);
while (prinList.hasNext()) {
PolicyParser.PrincipalEntry pe=prinList.next();
try {
verifyPrincipal(pe.getPrincipalClass(),pe.getPrincipalName());
}
catch ( ClassNotFoundException fnfe) {
newWarning=true;
MessageFormat form=new MessageFormat(getMessage("Warning.Class.not.found.class"));
Object[] source={pe.getPrincipalClass()};
warnings.addElement(form.format(source));
}
}
Enumeration<PolicyParser.PermissionEntry> perms=ge.permissionElements();
while (perms.hasMoreElements()) {
PolicyParser.PermissionEntry pe=perms.nextElement();
try {
verifyPermission(pe.permission,pe.name,pe.action);
}
catch ( ClassNotFoundException fnfe) {
newWarning=true;
MessageFormat form=new MessageFormat(getMessage("Warning.Class.not.found.class"));
Object[] source={pe.permission};
warnings.addElement(form.format(source));
}
catch ( InvocationTargetException ite) {
newWarning=true;
MessageFormat form=new MessageFormat(getMessage("Warning.Invalid.argument.s.for.constructor.arg"));
Object[] source={pe.permission};
warnings.addElement(form.format(source));
}
if (pe.signedBy != null) {
String signers[]=parseSigners(pe.signedBy);
for (int i=0; i < signers.length; i++) {
PublicKey pubKey=getPublicKeyAlias(signers[i]);
if (pubKey == null) {
newWarning=true;
MessageFormat form=new MessageFormat(getMessage("Warning.A.public.key.for.alias.signers.i.does.not.exist.Make.sure.a.KeyStore.is.properly.configured."));
Object[] source={signers[i]};
warnings.addElement(form.format(source));
}
}
}
}
PolicyEntry pEntry=new PolicyEntry(this,ge);
policyEntries.addElement(pEntry);
}
modified=false;
}
| Open and read a policy file |
private T[] ensureCapacity(int minCapacity){
if (tmp.length < minCapacity) {
int newSize=minCapacity;
newSize|=newSize >> 1;
newSize|=newSize >> 2;
newSize|=newSize >> 4;
newSize|=newSize >> 8;
newSize|=newSize >> 16;
newSize++;
if (newSize < 0) newSize=minCapacity;
else newSize=Math.min(newSize,a.length >>> 1);
@SuppressWarnings({"unchecked","UnnecessaryLocalVariable"}) T[] newArray=(T[])new Object[newSize];
tmp=newArray;
}
return tmp;
}
| Ensures that the external array tmp has at least the specified number of elements, increasing its size if necessary. The size increases exponentially to ensure amortized linear time complexity. |
public static short[] toShortArray(int[] array){
short[] result=new short[array.length];
for (int i=0; i < array.length; i++) {
result[i]=(short)array[i];
}
return result;
}
| Coverts given ints array to array of shorts. |
public void deleteThreadVars() throws IOException {
print("deleteThreadVars",null);
}
| Description of the Method |
public static void main(String[] args){
try {
File testF=new File(new File(System.getProperty("user.dir")),"testOut.zip");
OutputZipper oz=new OutputZipper(testF);
oz.zipit("Here is some test text to be zipped","testzip");
oz.zipit("Here is a second entry to be zipped","testzip2");
oz.finished();
}
catch ( Exception ex) {
ex.printStackTrace();
System.err.println(ex.getMessage());
}
}
| Main method for testing this class |
public void createOffspring(Turkanian parent){
if (parent.energy <= birthEnergy) {
return;
}
Turkanian offspring=new Turkanian(this,parent.x,parent.y);
parent.energy-=birthEnergy;
offspring.energy=0;
agents.add(offspring);
agentGrid.setObjectLocation(offspring,offspring.x,offspring.y);
schedule.scheduleOnce(offspring);
}
| Create offspring of the current agent and add them to the grid in the same cell. |
public static <T>Supplier<T> prevNoDupSupplier(final Cursor cursor,ByteArrayConverter<T> converter){
DatabaseEntry key=new DatabaseEntry();
DatabaseEntry data=new DatabaseEntry();
return null;
}
| Supplies previous key, ignore duplicates, produce the key value, NOT the associated data. |
private static void enableObjectAddressRemapper(){
Magic.setObjectAddressRemapper(BootImageObjectAddressRemapper.getInstance());
}
| Begin recording objects referenced by RVM classes during loading/resolution/instantiation. These references will be converted to bootimage addresses when those objects are copied into bootimage. |
public void transformNode(int node) throws TransformerException {
setExtensionsTable(getStylesheet());
synchronized (m_serializationHandler) {
m_hasBeenReset=false;
XPathContext xctxt=getXPathContext();
DTM dtm=xctxt.getDTM(node);
try {
pushGlobalVars(node);
StylesheetRoot stylesheet=this.getStylesheet();
int n=stylesheet.getGlobalImportCount();
for (int i=0; i < n; i++) {
StylesheetComposed imported=stylesheet.getGlobalImport(i);
int includedCount=imported.getIncludeCountComposed();
for (int j=-1; j < includedCount; j++) {
Stylesheet included=imported.getIncludeComposed(j);
included.runtimeInit(this);
for (ElemTemplateElement child=included.getFirstChildElem(); child != null; child=child.getNextSiblingElem()) {
child.runtimeInit(this);
}
}
}
DTMIterator dtmIter=new org.apache.xpath.axes.SelfIteratorNoPredicate();
dtmIter.setRoot(node,xctxt);
xctxt.pushContextNodeList(dtmIter);
try {
this.applyTemplateToNode(null,null,node);
}
finally {
xctxt.popContextNodeList();
}
if (null != m_serializationHandler) {
m_serializationHandler.endDocument();
}
}
catch ( Exception se) {
while (se instanceof org.apache.xml.utils.WrappedRuntimeException) {
Exception e=((org.apache.xml.utils.WrappedRuntimeException)se).getException();
if (null != e) se=e;
}
if (null != m_serializationHandler) {
try {
if (se instanceof org.xml.sax.SAXParseException) m_serializationHandler.fatalError((org.xml.sax.SAXParseException)se);
else if (se instanceof TransformerException) {
TransformerException te=((TransformerException)se);
SAXSourceLocator sl=new SAXSourceLocator(te.getLocator());
m_serializationHandler.fatalError(new org.xml.sax.SAXParseException(te.getMessage(),sl,te));
}
else {
m_serializationHandler.fatalError(new org.xml.sax.SAXParseException(se.getMessage(),new SAXSourceLocator(),se));
}
}
catch ( Exception e) {
}
}
if (se instanceof TransformerException) {
m_errorHandler.fatalError((TransformerException)se);
}
else if (se instanceof org.xml.sax.SAXParseException) {
m_errorHandler.fatalError(new TransformerException(se.getMessage(),new SAXSourceLocator((org.xml.sax.SAXParseException)se),se));
}
else {
m_errorHandler.fatalError(new TransformerException(se));
}
}
finally {
this.reset();
}
}
}
| Process the source node to the output result, if the processor supports the "http://xml.org/trax/features/dom/input" feature. %REVIEW% Do we need a Node version of this? |
@Override protected RdKNNEntry createRootEntry(){
return new RdKNNDirectoryEntry(0,null,Double.NaN);
}
| Creates an entry representing the root node. |
public static byte[] readBytes(Path self) throws IOException {
return Files.readAllBytes(self);
}
| Reads the content of the file into a byte array. |
public void showURLInBrowser(final URL url){
try {
if (Desktop.isDesktopSupported()) try {
Desktop.getDesktop().browse(url.toURI());
return;
}
catch ( final Exception e) {
}
String[] cmdArray=null;
if (LEnv.OS == OpSys.WINDOWS) {
cmdArray=new String[]{"rundll32","url.dll,FileProtocolHandler",url.toString()};
}
else {
final String[] browsers={"firefox","google-chrome","opera","konqueror","epiphany","mozilla","netscape"};
for ( final String browser : browsers) if (Runtime.getRuntime().exec(new String[]{"which",browser}).waitFor() == 0) {
cmdArray=new String[]{browser,url.toString()};
break;
}
}
if (cmdArray != null) Runtime.getRuntime().exec(cmdArray);
}
catch ( final Exception e) {
LEnv.LOGGER.info("Failed to open URL: " + url,e);
}
}
| Opens the web page specified by the URL in the system's default browser. |
private void updateProgress(String progressLabel,int progress){
if (myHost != null && ((progress != previousProgress) || (!progressLabel.equals(previousProgressLabel)))) {
myHost.updateProgress(progressLabel,progress);
}
previousProgress=progress;
previousProgressLabel=progressLabel;
}
| Used to communicate a progress update between a plugin tool and the main Whitebox user interface. |
public void addInputProducer(PValue expandedInput,TransformTreeNode producer){
checkState(!finishedSpecifying);
inputs.put(expandedInput,producer);
}
| Adds an input to the transform node. |
public Clustering<Model> run(Relation<Model> relation){
HashMap<Model,ModifiableDBIDs> modelMap=new HashMap<>();
for (DBIDIter iditer=relation.iterDBIDs(); iditer.valid(); iditer.advance()) {
Model model=relation.get(iditer);
ModifiableDBIDs modelids=modelMap.get(model);
if (modelids == null) {
modelids=DBIDUtil.newHashSet();
modelMap.put(model,modelids);
}
modelids.add(iditer);
}
Clustering<Model> result=new Clustering<>("By Model Clustering","bymodel-clustering");
for ( Entry<Model,ModifiableDBIDs> entry : modelMap.entrySet()) {
final Model model=entry.getKey();
final ModifiableDBIDs ids=entry.getValue();
final String name=(model instanceof GeneratorInterface) ? ((GeneratorInterface)model).getName() : model.toString();
Cluster<Model> c=new Cluster<>(name,ids,model);
if (noisepattern != null && noisepattern.matcher(name).find()) {
c.setNoise(true);
}
result.addToplevelCluster(c);
}
return result;
}
| Run the actual clustering algorithm. |
String rrToString(){
StringBuffer sb=new StringBuffer();
sb.append(Type.string(covered));
sb.append(" ");
sb.append(alg);
sb.append(" ");
sb.append(labels);
sb.append(" ");
sb.append(origttl);
sb.append(" ");
if (Options.check("multiline")) sb.append("(\n\t");
sb.append(FormattedTime.format(expire));
sb.append(" ");
sb.append(FormattedTime.format(timeSigned));
sb.append(" ");
sb.append(footprint);
sb.append(" ");
sb.append(signer);
if (Options.check("multiline")) {
sb.append("\n");
sb.append(base64.formatString(signature,64,"\t",true));
}
else {
sb.append(" ");
sb.append(base64.toString(signature));
}
return sb.toString();
}
| Converts the RRSIG/SIG Record to a String |
private boolean isModel(JavaContext context,Node classDeclaration){
String classFilePackage=PackageManager.getPackage(context,classDeclaration);
return classFilePackage.contains(".models.");
}
| Check if a class is a Model (is inside a package called 'models'). |
public void addPlugin(final IPlugin<IPluginInterface> plugin){
Preconditions.checkNotNull(plugin,"Error: Plugin argument can not be null");
m_registry.addPlugin(plugin);
}
| Add a new plugin to the list of registered plugins. |
private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {
s.defaultWriteObject();
s.writeInt(table.length);
s.writeInt(count);
for (int index=table.length - 1; index >= 0; index--) {
Entry entry=table[index];
while (entry != null) {
s.writeObject(entry.key);
s.writeObject(entry.value);
entry=entry.next;
}
}
}
| Save the state of the <tt>IdentityHashMap</tt> instance to a stream (i.e., serialize it). |
@Override protected void mouseClicked(int par1,int par2,int par3) throws IOException {
super.mouseClicked(par1,par2,par3);
tokenBox.mouseClicked(par1,par2,par3);
if (tokenBox.isFocused()) {
errorText="";
helpText="";
}
}
| Called when the mouse is clicked. |
public Object call(Object object,String name,Object[] args) throws BSFException {
if (object == null) {
try {
object=interpreter.get("global");
}
catch ( EvalError e) {
throw new BSFException("bsh internal error: " + e.toString());
}
}
if (object instanceof bsh.This) {
try {
return ((bsh.This)object).invokeMethod(name,args);
}
catch ( InterpreterError e) {
throw new BSFException("BeanShell interpreter internal error: " + e);
}
catch ( TargetError e2) {
throw new BSFException("The application script threw an exception: " + e2.getTarget());
}
catch ( EvalError e3) {
throw new BSFException("BeanShell script error: " + e3);
}
}
else {
throw new BSFException("Cannot invoke method: " + name + ". Object: "+ object+ " is not a BeanShell scripted object.");
}
}
| Invoke method name on the specified bsh scripted object. The object may be null to indicate the global namespace of the interpreter. |
@DSComment("Private Method") @DSBan(DSCat.PRIVATE_METHOD) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:31:30.536 -0500",hash_original_method="55F676D436FF1EC67ECC1C028E81ED27",hash_generated_method="AC9FD73229CF68305BF944740C6C29B7") private View moveSelection(int delta,int childrenTop,int childrenBottom){
final int fadingEdgeLength=getVerticalFadingEdgeLength();
final int selectedPosition=mSelectedPosition;
final int numColumns=mNumColumns;
final int verticalSpacing=mVerticalSpacing;
int oldRowStart;
int rowStart;
int rowEnd=-1;
if (!mStackFromBottom) {
oldRowStart=(selectedPosition - delta) - ((selectedPosition - delta) % numColumns);
rowStart=selectedPosition - (selectedPosition % numColumns);
}
else {
int invertedSelection=mItemCount - 1 - selectedPosition;
rowEnd=mItemCount - 1 - (invertedSelection - (invertedSelection % numColumns));
rowStart=Math.max(0,rowEnd - numColumns + 1);
invertedSelection=mItemCount - 1 - (selectedPosition - delta);
oldRowStart=mItemCount - 1 - (invertedSelection - (invertedSelection % numColumns));
oldRowStart=Math.max(0,oldRowStart - numColumns + 1);
}
final int rowDelta=rowStart - oldRowStart;
final int topSelectionPixel=getTopSelectionPixel(childrenTop,fadingEdgeLength,rowStart);
final int bottomSelectionPixel=getBottomSelectionPixel(childrenBottom,fadingEdgeLength,numColumns,rowStart);
mFirstPosition=rowStart;
View sel;
View referenceView;
if (rowDelta > 0) {
final int oldBottom=mReferenceViewInSelectedRow == null ? 0 : mReferenceViewInSelectedRow.getBottom();
sel=makeRow(mStackFromBottom ? rowEnd : rowStart,oldBottom + verticalSpacing,true);
referenceView=mReferenceView;
adjustForBottomFadingEdge(referenceView,topSelectionPixel,bottomSelectionPixel);
}
else if (rowDelta < 0) {
final int oldTop=mReferenceViewInSelectedRow == null ? 0 : mReferenceViewInSelectedRow.getTop();
sel=makeRow(mStackFromBottom ? rowEnd : rowStart,oldTop - verticalSpacing,false);
referenceView=mReferenceView;
adjustForTopFadingEdge(referenceView,topSelectionPixel,bottomSelectionPixel);
}
else {
final int oldTop=mReferenceViewInSelectedRow == null ? 0 : mReferenceViewInSelectedRow.getTop();
sel=makeRow(mStackFromBottom ? rowEnd : rowStart,oldTop,true);
referenceView=mReferenceView;
}
if (!mStackFromBottom) {
fillUp(rowStart - numColumns,referenceView.getTop() - verticalSpacing);
adjustViewsUpOrDown();
fillDown(rowStart + numColumns,referenceView.getBottom() + verticalSpacing);
}
else {
fillDown(rowEnd + numColumns,referenceView.getBottom() + verticalSpacing);
adjustViewsUpOrDown();
fillUp(rowStart - 1,referenceView.getTop() - verticalSpacing);
}
return sel;
}
| Fills the grid based on positioning the new selection relative to the old selection. The new selection will be placed at, above, or below the location of the new selection depending on how the selection is moving. The selection will then be pinned to the visible part of the screen, excluding the edges that are faded. The grid is then filled upwards and downwards from there. |
public synchronized void clear(){
super.clear();
mValue.clear();
initRange();
}
| Removes all the values from the series. |
public static void fill(int[][][] matrix,int value){
int rows=matrix.length;
for (int r=0; r < rows; r++) {
int cols=matrix[r].length;
for (int c=0; c < cols; c++) {
int height=matrix[r][c].length;
for (int h=0; h < height; h++) {
matrix[r][c][h]=value;
}
}
}
}
| Initialises all values in the matrix to the given value |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.