code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public double computeAverageLocal(int var1[],int var2[],int cond[]){
initialise();
addObservations(var1,var2,cond);
return computeAverageLocalOfObservations();
}
| Standalone routine to compute average conditional MI for a given set of variables. |
protected void connect() throws Exception {
FloodlightModuleContext fmc=new FloodlightModuleContext();
ThreadPool tp=new ThreadPool();
syncManager=new RemoteSyncManager();
fmc.addService(IThreadPoolService.class,tp);
fmc.addService(ISyncService.class,syncManager);
fmc.addConfigParam(syncManager,"hostname",settings.hostname);
fmc.addConfigParam(syncManager,"port",Integer.toString(settings.port));
if (settings.authScheme != null) {
fmc.addConfigParam(syncManager,"authScheme",settings.authScheme.toString());
fmc.addConfigParam(syncManager,"keyStorePath",settings.keyStorePath);
fmc.addConfigParam(syncManager,"keyStorePassword",settings.keyStorePassword);
}
tp.init(fmc);
syncManager.init(fmc);
tp.startUp(fmc);
syncManager.startUp(fmc);
out.println("Using remote sync service at " + settings.hostname + ":"+ settings.port);
}
| Set up the remote sync manager and prepare for requests |
AtomicLongChunks(final long length,final int chunkBits){
mLength=length;
assert chunkBits >= 0 && chunkBits <= 31;
mChunkBits=chunkBits;
mChunkSize=1 << mChunkBits;
mChunkMask=mChunkSize - 1;
final long ch=(length + mChunkSize - 1) / mChunkSize;
if (ch > Integer.MAX_VALUE) {
throw new RuntimeException("length requested too long length=" + length + " mChunkSize="+ mChunkSize);
}
final int chunks=(int)ch;
mArray=new AtomicLongArray[chunks];
long left=mLength;
for (int i=0; i < chunks; i++) {
final int assignedLength=left <= mChunkSize ? (int)left : mChunkSize;
assert assignedLength != 0;
mArray[i]=new AtomicLongArray(assignedLength);
left-=assignedLength;
}
assert left == 0;
}
| Constructs an index by splitting into array chunks. This version sets the size of the chunks - it should only be used for testing. |
protected RequestTask(KMLNetworkLink link,String address){
if (link == null) {
String message=Logging.getMessage("nullValue.ObjectIsNull");
Logging.logger().severe(message);
throw new IllegalArgumentException(message);
}
if (address == null) {
String message=Logging.getMessage("nullValue.PathIsNull");
Logging.logger().severe(message);
throw new IllegalArgumentException(message);
}
this.link=link;
this.address=address;
}
| Construct a request task for a specified network link resource. |
public DefaultContainerCapabilityFactory(ClassLoader classLoader){
super();
AbstractFactoryRegistry.register(classLoader,this);
}
| Register container capability name mappings. |
public InQueryExp(ValueExp v1,ValueExp items[]){
val=v1;
valueList=items;
}
| Creates a new InQueryExp with the specified ValueExp to be found in a specified array of ValueExp. |
@Override public void dropPartition(String dbName,String tableName,String partitionName,boolean deleteData) throws HiveMetastoreException {
HiveObjectSpec partitionSpec=new HiveObjectSpec(dbName,tableName,partitionName);
if (!existsPartition(dbName,tableName,partitionName)) {
throw new HiveMetastoreException("Missing partition: " + partitionSpec);
}
specToPartition.remove(partitionSpec);
}
| Drops the partition, but for safety, doesn't delete the data. |
private void jbInit() throws Exception {
Charset[] charsets=Ini.getAvailableCharsets();
for (int i=0; i < charsets.length; i++) fCharset.appendItem(charsets[i].displayName(),charsets[i]);
bFile.setLabel(Msg.getMsg(Env.getCtx(),"FileImportFile"));
bFile.setTooltiptext(Msg.getMsg(Env.getCtx(),"FileImportFileInfo"));
bFile.addEventListener(Events.ON_CLICK,this);
fCharset.setMold("select");
fCharset.setRows(0);
fCharset.setTooltiptext(Msg.getMsg(Env.getCtx(),"Charset",false));
info.setValue(" ");
labelFormat.setValue(Msg.translate(Env.getCtx(),"AD_ImpFormat_ID"));
pickFormat.setMold("select");
pickFormat.setRows(0);
bNext.setTooltiptext(Msg.getMsg(Env.getCtx(),"Next"));
bNext.setLabel(">");
bNext.addEventListener(Events.ON_CLICK,this);
record.setValue("------");
bPrevious.setTooltiptext(Msg.getMsg(Env.getCtx(),"Previous"));
bPrevious.setLabel("<");
bPrevious.addEventListener(Events.ON_CLICK,this);
northPanel.appendChild(bFile);
northPanel.appendChild(fCharset);
northPanel.appendChild(info);
northPanel.appendChild(labelFormat);
northPanel.appendChild(pickFormat);
northPanel.appendChild(bPrevious);
northPanel.appendChild(record);
northPanel.appendChild(bNext);
rawData.setWidth("100%");
rawData.setCols(80);
rawData.setRows(MAX_SHOWN_LINES);
rawData.setHeight("40%");
previewPanel.setWidth("100%");
previewPanel.setHeight("58%");
previewPanel.setStyle("overflow: auto");
centerPanel.setWidth("100%");
centerPanel.setHeight("100%");
centerPanel.appendChild(rawData);
centerPanel.appendChild(new Separator());
centerPanel.appendChild(previewPanel);
confirmPanel.addActionListener(Events.ON_CLICK,this);
}
| Static Init |
private void updateProgress(String progressLabel,int progress){
if (myHost != null && ((progress != previousProgress) || (!progressLabel.equals(previousProgressLabel)))) {
myHost.updateProgress(progressLabel,progress);
}
else {
System.out.println(progressLabel + " " + progress+ "%");
}
previousProgress=progress;
previousProgressLabel=progressLabel;
}
| Used to communicate a progress update between a plugin tool and the main Whitebox user interface. |
@Override public void run(){
amIActive=true;
String inputFile=null;
String outputFile=null;
int v;
int a;
int i;
double sigmaX;
double sigmaY;
double N;
double sigmaXY;
double sigmaXsqr;
double sigmaYsqr;
double mean;
double meanY;
double radians2Deg=180 / Math.PI;
double slope;
double slopeInDegrees;
double slopeM1;
double slopeM2;
double slopeRMA;
double slopeDegM1;
double slopeDegM2;
double slopeDegRMA;
int progress;
int oldProgress=-1;
double midX=0;
double midY=0;
double maxLineLength=100;
double lineLength;
double Sxx, Syy, Sxy;
double centroidX;
double centroidY;
double deltaX, deltaY;
int[] parts={0};
int[] partStart={0};
boolean[] partHoleData={false};
double x, y;
int pointSt, pointEnd;
boolean useElongationRatio=true;
if (args.length <= 0) {
showFeedback("Plugin parameters have not been set.");
return;
}
inputFile=args[0];
outputFile=args[1];
maxLineLength=Double.parseDouble(args[2]);
useElongationRatio=Boolean.parseBoolean(args[3]);
if ((inputFile == null) || (outputFile == null)) {
showFeedback("One or more of the input parameters have not been set properly.");
return;
}
try {
ShapeFile input=new ShapeFile(inputFile);
double numberOfRecords=input.getNumberOfRecords();
if (input.getShapeType().getBaseType() != ShapeType.POLYGON) {
showFeedback("This function can only be applied to polygon type shapefiles.");
return;
}
DBFField fields[]=new DBFField[3];
fields[0]=new DBFField();
fields[0].setName("FID");
fields[0].setDataType(DBFField.DBFDataType.NUMERIC);
fields[0].setFieldLength(10);
fields[0].setDecimalCount(0);
if (!useElongationRatio) {
fields[1]=new DBFField();
fields[1].setName("LINEARITY");
fields[1].setDataType(DBFField.DBFDataType.NUMERIC);
fields[1].setFieldLength(10);
fields[1].setDecimalCount(3);
fields[2]=new DBFField();
fields[2].setName("ORIENT");
fields[2].setDataType(DBFField.DBFDataType.NUMERIC);
fields[2].setFieldLength(10);
fields[2].setDecimalCount(3);
}
else {
fields[1]=new DBFField();
fields[1].setName("ELONGATION");
fields[1].setDataType(DBFField.DBFDataType.NUMERIC);
fields[1].setFieldLength(10);
fields[1].setDecimalCount(3);
fields[2]=new DBFField();
fields[2].setName("ELONG_DIR");
fields[2].setDataType(DBFField.DBFDataType.NUMERIC);
fields[2].setFieldLength(10);
fields[2].setDecimalCount(3);
}
ShapeFile output=new ShapeFile(outputFile,ShapeType.POLYLINE,fields);
ShapeType inputType=input.getShapeType();
double[][] vertices=null;
double[] regressionData;
double rSquare;
if (!useElongationRatio) {
for ( ShapeFileRecord record : input.records) {
if (record.getShapeType() != ShapeType.NULLSHAPE) {
switch (inputType) {
case POLYGON:
whitebox.geospatialfiles.shapefile.Polygon recPolygon=(whitebox.geospatialfiles.shapefile.Polygon)(record.getGeometry());
vertices=recPolygon.getPoints();
partStart=recPolygon.getParts();
partHoleData=recPolygon.getPartHoleData();
midX=recPolygon.getXMin() + (recPolygon.getXMax() - recPolygon.getXMin()) / 2;
midY=recPolygon.getYMin() + (recPolygon.getYMax() - recPolygon.getYMin()) / 2;
break;
case POLYGONZ:
PolygonZ recPolygonZ=(PolygonZ)(record.getGeometry());
vertices=recPolygonZ.getPoints();
partStart=recPolygonZ.getParts();
partHoleData=recPolygonZ.getPartHoleData();
midX=recPolygonZ.getXMin() + (recPolygonZ.getXMax() - recPolygonZ.getXMin()) / 2;
midY=recPolygonZ.getYMin() + (recPolygonZ.getYMax() - recPolygonZ.getYMin()) / 2;
break;
case POLYGONM:
PolygonM recPolygonM=(PolygonM)(record.getGeometry());
vertices=recPolygonM.getPoints();
partStart=recPolygonM.getParts();
partHoleData=recPolygonM.getPartHoleData();
midX=recPolygonM.getXMin() + (recPolygonM.getXMax() - recPolygonM.getXMin()) / 2;
midY=recPolygonM.getYMin() + (recPolygonM.getYMax() - recPolygonM.getYMin()) / 2;
break;
}
int numParts=partStart.length;
for (int p=0; p < numParts; p++) {
if (!partHoleData[p]) {
regressionData=new double[5];
rSquare=0;
slope=0;
slopeInDegrees=0;
slopeDegM1=0;
slopeDegM2=0;
slopeDegRMA=0;
slopeM1=0;
slopeM2=0;
slopeRMA=0;
pointSt=partStart[p];
if (p < numParts - 1) {
pointEnd=partStart[p + 1];
}
else {
pointEnd=vertices.length;
}
N=pointEnd - pointSt;
for (v=pointSt; v < pointEnd; v++) {
x=vertices[v][0] - midX;
y=vertices[v][1] - midY;
regressionData[0]+=x;
regressionData[1]+=y;
regressionData[2]+=x * y;
regressionData[3]+=x * x;
regressionData[4]+=y * y;
}
sigmaX=regressionData[0];
mean=sigmaX / N;
sigmaY=regressionData[1];
meanY=sigmaY / N;
sigmaXY=regressionData[2];
sigmaXsqr=regressionData[3];
sigmaYsqr=regressionData[4];
if ((sigmaXsqr - mean * sigmaX) > 0) {
slopeM1=(sigmaXY - mean * sigmaY) / (sigmaXsqr - mean * sigmaX);
slopeDegM1=(Math.atan(slopeM1) * radians2Deg);
if (slopeDegM1 < 0) {
slopeDegM1=90 + -1 * slopeDegM1;
}
else {
slopeDegM1=90 - slopeDegM1;
}
}
Sxx=(sigmaXsqr / N - mean * mean);
Syy=(sigmaYsqr / N - (sigmaY / N) * (sigmaY / N));
Sxy=(sigmaXY / N - (sigmaX * sigmaY) / (N * N));
if (Math.sqrt(Sxx * Syy) != 0) {
rSquare=((Sxy / Math.sqrt(Sxx * Syy)) * (Sxy / Math.sqrt(Sxx * Syy)));
}
slopeRMA=Math.sqrt(Syy / Sxx);
if ((sigmaXY - mean * sigmaY) / (sigmaXsqr - mean * sigmaX) < 0) {
slopeRMA=-slopeRMA;
}
slopeDegRMA=(Math.atan(slopeRMA) * radians2Deg);
if (slopeDegRMA < 0) {
slopeDegRMA=90 + -1 * slopeDegRMA;
}
else {
slopeDegRMA=90 - slopeDegRMA;
}
if ((sigmaYsqr - meanY * sigmaY) > 0) {
slopeM2=(sigmaXY - meanY * sigmaX) / (sigmaYsqr - meanY * sigmaY);
slopeM2=1 / slopeM2;
slopeDegM2=(Math.atan(slopeM2) * radians2Deg);
if (slopeDegM2 < 0) {
slopeDegM2=90 + -1 * slopeDegM2;
}
else {
slopeDegM2=90 - slopeDegM2;
}
}
if (slopeDegM2 < 6 || slopeDegM2 > 174) {
slope=slopeM2;
slopeInDegrees=slopeDegM2;
}
else if (slopeDegM1 > 84 && slopeDegM1 < 96) {
slope=slopeM1;
slopeInDegrees=slopeDegM1;
}
else {
slope=slopeRMA;
slopeInDegrees=slopeDegRMA;
}
centroidX=mean + midX;
centroidY=meanY + midY;
lineLength=maxLineLength * rSquare;
double[][] points=new double[2][2];
if (slopeInDegrees > 0) {
deltaX=Math.cos(slope) * lineLength;
deltaY=Math.sin(slope) * lineLength;
points[0][0]=centroidX - deltaX / 2.0;
points[0][1]=centroidY - deltaY / 2.0;
points[1][0]=centroidX + deltaX / 2.0;
points[1][1]=centroidY + deltaY / 2.0;
}
else {
points[0][0]=centroidX - lineLength / 2.0;
points[0][1]=centroidY;
points[1][0]=centroidX + lineLength / 2.0;
points[1][1]=centroidY;
}
PolyLine poly=new PolyLine(parts,points);
Object[] rowData=new Object[3];
rowData[0]=new Double(record.getRecordNumber());
rowData[1]=new Double(rSquare);
rowData[2]=new Double(slopeInDegrees);
output.addRecord(poly,rowData);
}
}
if (cancelOp) {
cancelOperation();
return;
}
progress=(int)(record.getRecordNumber() / numberOfRecords * 100);
if (progress > oldProgress) {
updateProgress(progress);
}
oldProgress=progress;
}
}
}
else {
double[][] verticesRotated=null;
double[] newBoundingBox=new double[4];
double psi=0;
double DegreeToRad=Math.PI / 180;
double[] axes=new double[2];
double newXAxis=0;
double newYAxis=0;
double longAxis;
double shortAxis;
double elongation=0;
double bearing=0;
final double rightAngle=Math.toRadians(90);
double boxCentreX=0;
double boxCentreY=0;
slope=0;
for (ShapeFileRecord record : input.records) {
switch (inputType) {
case POLYGON:
whitebox.geospatialfiles.shapefile.Polygon recPolygon=(whitebox.geospatialfiles.shapefile.Polygon)(record.getGeometry());
vertices=recPolygon.getPoints();
midX=recPolygon.getXMin() + (recPolygon.getXMax() - recPolygon.getXMin()) / 2;
midY=recPolygon.getYMin() + (recPolygon.getYMax() - recPolygon.getYMin()) / 2;
break;
case POLYGONZ:
PolygonZ recPolygonZ=(PolygonZ)(record.getGeometry());
vertices=recPolygonZ.getPoints();
midX=recPolygonZ.getXMin() + (recPolygonZ.getXMax() - recPolygonZ.getXMin()) / 2;
midY=recPolygonZ.getYMin() + (recPolygonZ.getYMax() - recPolygonZ.getYMin()) / 2;
break;
case POLYGONM:
PolygonM recPolygonM=(PolygonM)(record.getGeometry());
vertices=recPolygonM.getPoints();
midX=recPolygonM.getXMin() + (recPolygonM.getXMax() - recPolygonM.getXMin()) / 2;
midY=recPolygonM.getYMin() + (recPolygonM.getYMax() - recPolygonM.getYMin()) / 2;
break;
}
int numVertices=vertices.length;
verticesRotated=new double[numVertices][2];
axes[0]=9999999;
axes[1]=9999999;
double sumX=0;
double sumY=0;
N=0;
boolean calculatedCentroid=false;
for (int m=0; m <= 180; m++) {
psi=-m * 0.5 * DegreeToRad;
for (int n=0; n < numVertices; n++) {
x=vertices[n][0] - midX;
y=vertices[n][1] - midY;
if (!calculatedCentroid) {
sumX+=x;
sumY+=y;
N++;
}
verticesRotated[n][0]=(x * Math.cos(psi)) - (y * Math.sin(psi));
verticesRotated[n][1]=(x * Math.sin(psi)) + (y * Math.cos(psi));
}
newBoundingBox[0]=Double.MAX_VALUE;
newBoundingBox[1]=Double.MIN_VALUE;
newBoundingBox[2]=Double.MAX_VALUE;
newBoundingBox[3]=Double.MIN_VALUE;
for (int n=0; n < numVertices; n++) {
x=verticesRotated[n][0];
y=verticesRotated[n][1];
if (x < newBoundingBox[0]) {
newBoundingBox[0]=x;
}
if (x > newBoundingBox[1]) {
newBoundingBox[1]=x;
}
if (y < newBoundingBox[2]) {
newBoundingBox[2]=y;
}
if (y > newBoundingBox[3]) {
newBoundingBox[3]=y;
}
}
newXAxis=newBoundingBox[1] - newBoundingBox[0] + 1;
newYAxis=newBoundingBox[3] - newBoundingBox[2] + 1;
if ((axes[0] * axes[1]) > (newXAxis * newYAxis)) {
axes[0]=newXAxis;
axes[1]=newYAxis;
if (axes[0] > axes[1]) {
slope=-psi;
}
else {
slope=-(rightAngle + psi);
}
x=newBoundingBox[0] + newXAxis / 2;
y=newBoundingBox[2] + newYAxis / 2;
boxCentreX=midX + (x * Math.cos(-psi)) - (y * Math.sin(-psi));
boxCentreY=midY + (x * Math.sin(-psi)) + (y * Math.cos(-psi));
}
}
longAxis=Math.max(axes[0],axes[1]);
shortAxis=Math.min(axes[0],axes[1]);
elongation=1 - shortAxis / longAxis;
centroidX=(sumX / N) + midX;
centroidY=(sumY / N) + midY;
lineLength=maxLineLength * elongation;
double[][] points=new double[2][2];
deltaX=Math.cos(slope) * lineLength;
deltaY=Math.sin(slope) * lineLength;
points[0][0]=boxCentreX - deltaX / 2.0;
points[0][1]=boxCentreY - deltaY / 2.0;
points[1][0]=boxCentreX + deltaX / 2.0;
points[1][1]=boxCentreY + deltaY / 2.0;
PolyLine poly=new PolyLine(parts,points);
Object[] rowData=new Object[3];
rowData[0]=new Double(record.getRecordNumber());
rowData[1]=new Double(elongation);
bearing=90 - Math.toDegrees(slope);
rowData[2]=new Double(bearing);
output.addRecord(poly,rowData);
if (cancelOp) {
cancelOperation();
return;
}
progress=(int)(record.getRecordNumber() / numberOfRecords * 100);
if (progress > oldProgress) {
updateProgress(progress);
}
oldProgress=progress;
}
}
output.write();
returnData(outputFile);
}
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. |
protected void prepare() throws IllegalStateException {
startLoading();
this.videoIsReady=false;
this.initialMovieHeight=-1;
this.initialMovieWidth=-1;
this.mediaPlayer.setOnPreparedListener(this);
this.mediaPlayer.setOnErrorListener(this);
this.mediaPlayer.setOnSeekCompleteListener(this);
this.mediaPlayer.setOnInfoListener(this);
this.mediaPlayer.setOnVideoSizeChangedListener(this);
this.mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
this.currentState=State.PREPARING;
this.mediaPlayer.prepareAsync();
}
| Calls prepare() method of MediaPlayer |
public NormalizedIndicator(Problem problem,NondominatedPopulation referenceSet,double[] referencePoint){
super();
this.problem=problem;
normalizer=new Normalizer(problem,referenceSet,referencePoint);
normalizedReferenceSet=normalizer.normalize(referenceSet);
}
| Constructs a normalized indicator for the specified problem and corresponding reference set. This version allows the use of a custom reference point. |
public InvalidPathException(String input,String reason){
this(input,reason,-1);
}
| Constructs an instance from the given input string and reason. The resulting object will have an error index of <tt>-1</tt>. |
public void testDoCheckWithDefaultDetectionResultAndDetectionResultOverridenByConstructor(){
LOGGER.debug("doCheckWithDefaultDetectionResultAndDetectionResultOverridenByConstructor");
elements.add(element);
expect(mockTextElementBuilder.buildTextFromElement(element)).andReturn("test");
mockTestSolutionHandler.addTestSolution(TestSolution.NEED_MORE_INFO);
expectLastCall().once();
expect(mockNomenclature.getValueList()).andReturn(Arrays.asList("test"));
mockProcessRemarkService.addSourceCodeRemarkOnElement(TestSolution.NEED_MORE_INFO,element,DETECTION_MSG,null);
expectLastCall().once();
TextBelongsToBlackListChecker instance=new TextBelongsToBlackListChecker(mockTextElementBuilder,BLACKLIST_NOM_NAME,TestSolution.NEED_MORE_INFO,DETECTION_MSG);
instance.setNomenclatureLoaderService(mockNomenclatureLoaderService);
instance.setProcessRemarkService(mockProcessRemarkService);
replay(mockTextElementBuilder,mockSSPHandler,mockTestSolutionHandler,mockNomenclature,mockNomenclatureLoaderService,mockProcessRemarkService);
instance.doCheck(mockSSPHandler,elements,mockTestSolutionHandler);
verify(mockTextElementBuilder,mockSSPHandler,mockTestSolutionHandler,mockNomenclature,mockNomenclatureLoaderService,mockProcessRemarkService);
}
| Test of doCheck method, of class TextBelongsToBlackListChecker. |
public static void saveX509Cert(Certificate cert,File certFile) throws GeneralSecurityException, IOException {
saveX509Cert(new Certificate[]{cert},certFile);
}
| Save a certificate to a file. Remove all the content in the file if there is any before. |
@Override public boolean eIsSet(int featureID){
switch (featureID) {
case N4JSPackage.BINARY_BITWISE_EXPRESSION__LHS:
return lhs != null;
case N4JSPackage.BINARY_BITWISE_EXPRESSION__OP:
return op != OP_EDEFAULT;
case N4JSPackage.BINARY_BITWISE_EXPRESSION__RHS:
return rhs != null;
}
return super.eIsSet(featureID);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
@LargeTest public void testPropertiesGIFFile() throws Exception {
final String imageItemFilename=INPUT_FILE_PATH + "IMG_640x480.gif";
final int imageItemDuration=10000;
final int renderingMode=MediaItem.RENDERING_MODE_BLACK_BORDER;
boolean flagForException=false;
try {
new MediaImageItem(mVideoEditor,"m1",imageItemFilename,imageItemDuration,renderingMode);
}
catch ( IllegalArgumentException e) {
flagForException=true;
}
assertTrue("Media Properties for a GIF File -- Unsupported file type",flagForException);
}
| To test Media Properties for file GIF - Unsupported type |
public String doNotCheckCapabilitiesTipText(){
return "If set, associator capabilities are not checked before associator is built" + " (Use with caution to reduce runtime).";
}
| Returns the tip text for this property |
public void compileSingleFiles(List<File> projectRoots,List<File> modelFiles) throws N4JSCompileException {
compileSingleFiles(projectRoots,modelFiles,new DismissingIssueAcceptor());
}
| Compile multiple Files |
private boolean isHiraganaDakuten(char c){
return inside(c,h2d,'\u304b') && c == lookupHiraganaDakuten(c);
}
| Hiragana dakuten predicate |
private void writeAttribute(java.lang.String namespace,java.lang.String attName,java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
if (namespace.equals("")) {
xmlWriter.writeAttribute(attName,attValue);
}
else {
registerPrefix(xmlWriter,namespace);
xmlWriter.writeAttribute(namespace,attName,attValue);
}
}
| Util method to write an attribute without the ns prefix |
public boolean isLoaded(){
return loaded;
}
| Gets the value of the loaded property. |
public void destroySelf(){
if (mViewPager == null || mViewPager.getAdapter() == null) {
return;
}
mBaseCyclePageChangeListener.removeAdapterDataChangeObserverListener();
removeAllViews();
}
| clear self means unregister the dataset observer and remove all the child views(indicators). |
public static int computeTagSize(final int fieldNumber){
return computeRawVarint32Size(WireFormat.makeTag(fieldNumber,0));
}
| Compute the number of bytes that would be needed to encode a tag. |
public static <T>ManyAssociationContainsPredicate<T> contains(ManyAssociation<T> manyAssoc,T value){
return new ManyAssociationContainsPredicate<>(manyAssociation(manyAssoc),value);
}
| Create a new CONTAINS specification for a ManyAssociation. |
public SignerInformationStore generateCounterSigners(SignerInformation signer) throws CMSException {
return this.generate(new CMSProcessableByteArray(null,signer.getSignature()),false).getSignerInfos();
}
| generate a set of one or more SignerInformation objects representing counter signatures on the passed in SignerInformation object. |
protected void checkHistory(final List<DomainHistoryObject<?>> historyList){
final DomainHistoryObject<?> history=historyList.get(historyList.size() - 1);
ModificationType modificationType=history.getModtype();
if (!modificationType.equals(ModificationType.DELETE)) {
fail("The last version of history object is not DELETED type. Object was not correctly deleted.");
}
}
| Helper method for checking last entry of history table for status DELETED. |
private void push(final int type){
if (outputStack == null) {
outputStack=new int[10];
}
int n=outputStack.length;
if (outputStackTop >= n) {
int[] t=new int[Math.max(outputStackTop + 1,2 * n)];
System.arraycopy(outputStack,0,t,0,n);
outputStack=t;
}
outputStack[outputStackTop++]=type;
int top=owner.inputStackTop + outputStackTop;
if (top > owner.outputStackMax) {
owner.outputStackMax=top;
}
}
| Pushes a new type onto the output frame stack. |
public TypeNode typeNode(Type type){
if (type == null || !(type instanceof PrimType || type instanceof RefType)) {
throw new InternalTypingException();
}
TypeNode typeNode=typeNodeMap.get(type);
if (typeNode == null) {
throw new InternalTypingException();
}
return typeNode;
}
| Get the type node for the given type. |
private void put(final Item i){
if (index > threshold) {
int ll=items.length;
int nl=ll * 2 + 1;
Item[] newItems=new Item[nl];
for (int l=ll - 1; l >= 0; --l) {
Item j=items[l];
while (j != null) {
int index=j.hashCode % newItems.length;
Item k=j.next;
j.next=newItems[index];
newItems[index]=j;
j=k;
}
}
items=newItems;
threshold=(int)(nl * 0.75);
}
int index=i.hashCode % items.length;
i.next=items[index];
items[index]=i;
}
| Puts the given item in the constant pool's hash table. The hash table <i>must</i> not already contains this item. |
@Override public String toString(){
TextBuilder tb=new TextBuilder();
tb.append('{');
int length=_mapping.length << 6;
for (int i=0; i < length; i++) {
if (this.contains((char)i)) {
if (tb.length() > 1) {
tb.append(',');
tb.append(' ');
}
tb.append('\'');
tb.append((char)i);
tb.append('\'');
}
}
tb.append('}');
return tb.toString();
}
| Returns the textual representation of this character set. |
public void testCsiX(){
withTerminalSized(13,2).enterString("abcdefghijkl\b\b\b\b\b\033[X").assertLinesAre("abcdefg ijkl "," ");
withTerminalSized(13,2).enterString("abcdefghijkl\b\b\b\b\b\033[1X").assertLinesAre("abcdefg ijkl "," ");
withTerminalSized(13,2).enterString("abcdefghijkl\b\b\b\b\b\033[2X").assertLinesAre("abcdefg jkl "," ");
withTerminalSized(13,2).enterString("abcdefghijkl\b\b\b\b\b\033[20X").assertLinesAre("abcdefg "," ");
}
| CSI Ps X Erase Ps Character(s) (default = 1) (ECH). |
static int popLength(InputStream stream){
byte[] lengthBytes=new byte[Integer.SIZE / Byte.SIZE];
try {
stream.read(lengthBytes);
}
catch ( IOException e) {
Log.e(TAG,"IOException popping length from input stream: " + e);
return -1;
}
ByteBuffer buffer=ByteBuffer.wrap(lengthBytes);
buffer.order(ByteOrder.BIG_ENDIAN);
return buffer.getInt();
}
| Take the output of lengthValueEncode() and decode it to a Message of the given type. |
protected Locale determineLocale(HttpContext context){
return Locale.getDefault();
}
| Determines the locale of the response. The implementation in this class always returns the default locale. |
@Override public Object eInvoke(int operationID,EList<?> arguments) throws InvocationTargetException {
switch (operationID) {
case N4JSPackage.PROPERTY_ASSIGNMENT___GET_DEFINED_MEMBER:
return getDefinedMember();
case N4JSPackage.PROPERTY_ASSIGNMENT___IS_VALID_NAME:
return isValidName();
case N4JSPackage.PROPERTY_ASSIGNMENT___GET_NAME:
return getName();
case N4JSPackage.PROPERTY_ASSIGNMENT___APPLIES_ONLY_TO_BLOCK_SCOPED_ELEMENTS:
return appliesOnlyToBlockScopedElements();
}
return super.eInvoke(operationID,arguments);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
protected double calculateHighestVisibleTickValue(){
double unit=getTickUnit().getSize();
double index=Math.floor(getRange().getUpperBound() / unit);
return index * unit;
}
| Calculates the value of the highest visible tick on the axis. |
private String nextAT() throws IOException {
hasQE=false;
for (; pos < chars.length && chars[pos] == ' '; pos++) {
}
if (pos == chars.length) {
return null;
}
beg=pos;
pos++;
for (; pos < chars.length && chars[pos] != '=' && chars[pos] != ' '; pos++) {
}
if (pos >= chars.length) {
throw new IOException("Invalid distinguished name string");
}
end=pos;
if (chars[pos] == ' ') {
for (; pos < chars.length && chars[pos] != '=' && chars[pos] == ' '; pos++) {
}
if (chars[pos] != '=' || pos == chars.length) {
throw new IOException("Invalid distinguished name string");
}
}
pos++;
for (; pos < chars.length && chars[pos] == ' '; pos++) {
}
if ((end - beg > 4) && (chars[beg + 3] == '.') && (chars[beg] == 'O' || chars[beg] == 'o')&& (chars[beg + 1] == 'I' || chars[beg + 1] == 'i')&& (chars[beg + 2] == 'D' || chars[beg + 2] == 'd')) {
beg+=4;
}
return new String(chars,beg,end - beg);
}
| Returns the next attribute type: (ALPHA 1*keychar) / oid |
public JmsQueueListener(Delegator delegator,String jndiServer,String jndiName,String queueName,String userName,String password){
super(delegator);
this.jndiServer=jndiServer;
this.jndiName=jndiName;
this.queueName=queueName;
this.userName=userName;
this.password=password;
}
| Creates a new JmsQueueListener - Should only be called by the JmsListenerFactory. |
public boolean isActiveSite(){
try {
SiteState state=getSiteFromLocalVdc(coordinator.getSiteId()).getState();
return ACTIVE_SITE_STATES.contains(state);
}
catch ( RetryableCoordinatorException ex) {
if (ServiceCode.COORDINATOR_SITE_NOT_FOUND == ex.getServiceCode()) {
return true;
}
log.error("Unexpected error to check active site",ex);
}
return false;
}
| Check if current site is active |
public RayTracer(Entity entity){
this(new Ray(entity.position().add(entity.components.has(Living.class) ? entity.components.get(Living.class).faceDisplacement.get() : Vector3D.ZERO),entity.rotation().applyTo(Vector3DUtil.FORWARD)));
}
| Does an entity look ray trace to see which block the entity is looking at. |
boolean canBeWalkedInNaturalDocOrderStatic(){
if (null != m_firstWalker) {
AxesWalker walker=m_firstWalker;
int prevAxis=-1;
boolean prevIsSimpleDownAxis=true;
for (int i=0; null != walker; i++) {
int axis=walker.getAxis();
if (walker.isDocOrdered()) {
boolean isSimpleDownAxis=((axis == Axis.CHILD) || (axis == Axis.SELF) || (axis == Axis.ROOT));
if (isSimpleDownAxis || (axis == -1)) walker=walker.getNextWalker();
else {
boolean isLastWalker=(null == walker.getNextWalker());
if (isLastWalker) {
if (walker.isDocOrdered() && (axis == Axis.DESCENDANT || axis == Axis.DESCENDANTORSELF || axis == Axis.DESCENDANTSFROMROOT || axis == Axis.DESCENDANTSORSELFFROMROOT) || (axis == Axis.ATTRIBUTE)) return true;
}
return false;
}
}
else return false;
}
return true;
}
return false;
}
| Tell if the nodeset can be walked in doc order, via static analysis. |
@Override public void runAndUpdate(final Runnable r){
r.run();
if (getScope().isPaused()) {
updateDisplay(true);
}
if (animator.isPaused()) {
animator.resume();
animator.pause();
}
}
| Method waitForUpdateAndRun() |
private Response doQUIT(SMTPSession session,String argument){
if ((argument == null) || (argument.length() == 0)) {
StringBuilder response=new StringBuilder();
response.append(DSNStatus.getStatus(DSNStatus.SUCCESS,DSNStatus.UNDEFINED_STATUS)).append(" ").append(session.getConfiguration().getHelloName()).append(" Service closing transmission channel");
SMTPResponse ret=new SMTPResponse(SMTPRetCode.SYSTEM_QUIT,response);
ret.setEndSession(true);
return ret;
}
else {
return SYNTAX_ERROR;
}
}
| Handler method called upon receipt of a QUIT command. This method informs the client that the connection is closing. |
public void writeImmediateAlert(final boolean on){
if (!isConnected()) return;
if (mAlertLevelCharacteristic != null) {
mAlertLevelCharacteristic.setValue(on ? HIGH_ALERT : NO_ALERT);
writeCharacteristic(mAlertLevelCharacteristic);
mAlertOn=on;
}
else {
DebugLogger.w(TAG,"Immediate Alert Level Characteristic is not found");
}
}
| Writes the HIGH ALERT or NO ALERT command to the target device |
private PostgreSQLGuacamoleProperties(){
}
| This class should not be instantiated. |
public static void main(final String[] args){
DOMTestCase.doMain(documentimportnode11.class,args);
}
| Runs this test from the command line. |
public UnifyMapping(UnifyElement sourceElement,UnifyElement destinationElement){
this(sourceElement);
destinationElements=createDestinationElements();
addDestinationElement(destinationElement);
}
| Creates a new UnifyMapping from one source element to one destination element. You cann add more destination elements later by method <code>addDestinationElement(..)</code>. |
@Override public int eDerivedStructuralFeatureID(int baseFeatureID,Class<?> baseClass){
if (baseClass == VariableEnvironmentElement.class) {
switch (baseFeatureID) {
default :
return -1;
}
}
if (baseClass == NamedElement.class) {
switch (baseFeatureID) {
default :
return -1;
}
}
if (baseClass == PropertyNameOwner.class) {
switch (baseFeatureID) {
case N4JSPackage.PROPERTY_NAME_OWNER__DECLARED_NAME:
return N4JSPackage.PROPERTY_ASSIGNMENT__DECLARED_NAME;
default :
return -1;
}
}
if (baseClass == TypableElement.class) {
switch (baseFeatureID) {
default :
return -1;
}
}
return super.eDerivedStructuralFeatureID(baseFeatureID,baseClass);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public static boolean isSymbolicLink(File file) throws IOException {
try {
Class<?> filesClass=Class.forName("java.nio.file.Files");
Class<?> pathClass=Class.forName("java.nio.file.Path");
Object path=File.class.getMethod("toPath").invoke(file);
return ((Boolean)filesClass.getMethod("isSymbolicLink",pathClass).invoke(null,path)).booleanValue();
}
catch ( InvocationTargetException exception) {
Throwable cause=exception.getCause();
Throwables.propagateIfPossible(cause,IOException.class);
throw new RuntimeException(cause);
}
catch ( ClassNotFoundException exception) {
}
catch ( IllegalArgumentException exception) {
}
catch ( SecurityException exception) {
}
catch ( IllegalAccessException exception) {
}
catch ( NoSuchMethodException exception) {
}
if (File.separatorChar == '\\') {
return false;
}
File canonical=file;
if (file.getParent() != null) {
canonical=new File(file.getParentFile().getCanonicalFile(),file.getName());
}
return !canonical.getCanonicalFile().equals(canonical.getAbsoluteFile());
}
| Returns whether the given file is a symbolic link. |
@Override protected void onDraw(Canvas canvas){
if (canvas != null) {
super.onDraw(canvas);
}
mTotalWidth=0;
final int height=getHeight();
if (mBgPadding == null) {
mBgPadding=new Rect(0,0,0,0);
if (getBackground() != null) {
getBackground().getPadding(mBgPadding);
}
mDivider.setBounds(0,0,mDivider.getIntrinsicWidth(),mDivider.getIntrinsicHeight());
}
final int count=mSuggestions.size();
final Rect bgPadding=mBgPadding;
final Paint paint=mPaint;
final int touchX=mTouchX;
final int scrollX=getScrollX();
final boolean scrolled=mScrolled;
final boolean typedWordValid=mTypedWordValid;
final int y=(int)(height + mPaint.getTextSize() - mDescent) / 2;
boolean existsAutoCompletion=false;
int x=0;
for (int i=0; i < count; i++) {
CharSequence suggestion=mSuggestions.get(i);
if (suggestion == null) continue;
final int wordLength=suggestion.length();
paint.setColor(mColorNormal);
if (mHaveMinimalSuggestion && ((i == 1 && !typedWordValid) || (i == 0 && typedWordValid))) {
paint.setTypeface(Typeface.DEFAULT_BOLD);
paint.setColor(mColorRecommended);
existsAutoCompletion=true;
}
else if (i != 0 || (wordLength == 1 && count > 1)) {
paint.setColor(mColorOther);
}
int wordWidth;
if ((wordWidth=mWordWidth[i]) == 0) {
float textWidth=paint.measureText(suggestion,0,wordLength);
wordWidth=Math.max(mMinTouchableWidth,(int)textWidth + X_GAP * 2);
mWordWidth[i]=wordWidth;
}
mWordX[i]=x;
if (touchX != OUT_OF_BOUNDS_X_COORD && !scrolled && touchX + scrollX >= x && touchX + scrollX < x + wordWidth) {
if (canvas != null && !mShowingAddToDictionary) {
canvas.translate(x,0);
mSelectionHighlight.setBounds(0,bgPadding.top,wordWidth,height);
mSelectionHighlight.draw(canvas);
canvas.translate(-x,0);
}
mSelectedString=suggestion;
mSelectedIndex=i;
}
if (canvas != null) {
canvas.drawText(suggestion,0,wordLength,x + wordWidth / 2,y,paint);
paint.setColor(mColorOther);
canvas.translate(x + wordWidth,0);
if (!(mShowingAddToDictionary && i == 1)) {
mDivider.draw(canvas);
}
canvas.translate(-x - wordWidth,0);
}
paint.setTypeface(Typeface.DEFAULT);
x+=wordWidth;
}
if (!isInEditMode()) mService.onAutoCompletionStateChanged(existsAutoCompletion);
mTotalWidth=x;
if (mTargetScrollX != scrollX) {
scrollToTarget();
}
}
| If the canvas is null, then only touch calculations are performed to pick the target candidate. |
public void addDataFile(List<ExtensionMapping> mappings,@Nullable Integer rowLimit) throws IOException, IllegalArgumentException, InterruptedException, GeneratorException {
checkForInterruption();
if (mappings == null || mappings.isEmpty()) {
return;
}
currRecords=0;
currRecordsSkipped=0;
Extension ext=mappings.get(0).getExtension();
currExtension=ext.getTitle();
for ( ExtensionMapping m : mappings) {
if (!ext.equals(m.getExtension())) {
throw new IllegalArgumentException("All mappings for a single data file need to be mapped to the same extension: " + ext.getRowType());
}
}
ArchiveFile af=ArchiveFile.buildTabFile();
af.setRowType(TERM_FACTORY.findTerm(ext.getRowType()));
af.setEncoding(CHARACTER_ENCODING);
af.setDateFormat("YYYY-MM-DD");
ArchiveField idField=new ArchiveField();
idField.setIndex(ID_COLUMN_INDEX);
af.setId(idField);
Set<Term> mappedConceptTerms=addFieldsToArchive(mappings,af);
List<ExtensionProperty> propertyList=getOrderedMappedExtensionProperties(ext,mappedConceptTerms);
assignIndexesOrderedByExtension(propertyList,af);
int totalColumns=1 + propertyList.size();
String extensionName=(ext.getName() == null) ? "f" : ext.getName().toLowerCase().replaceAll("\\s","_");
String fn=createFileName(dwcaFolder,extensionName);
File dataFile=new File(dwcaFolder,fn);
Writer writer=org.gbif.utils.file.FileUtils.startNewUtf8File(dataFile);
af.addLocation(dataFile.getName());
addMessage(Level.INFO,"Start writing data file for " + currExtension);
try {
boolean headerWritten=false;
for ( ExtensionMapping m : mappings) {
PropertyMapping[] inCols=new PropertyMapping[totalColumns];
for ( ArchiveField f : af.getFields().values()) {
if (f.getIndex() != null && f.getIndex() > ID_COLUMN_INDEX) {
inCols[f.getIndex()]=m.getField(f.getTerm().qualifiedName());
}
}
if (!headerWritten) {
writeHeaderLine(propertyList,totalColumns,af,writer);
headerWritten=true;
}
dumpData(writer,inCols,m,totalColumns,rowLimit,resource.getDoi());
recordsByExtension.put(ext.getRowType(),currRecords);
}
}
catch ( IOException e) {
log.error("Fatal DwC-A Generator Error encountered while writing header line to data file",e);
setState(e);
throw new GeneratorException("Error writing header line to data file",e);
}
finally {
writer.close();
}
if (resource.getCoreRowType().equalsIgnoreCase(ext.getRowType())) {
archive.setCore(af);
}
else {
archive.addExtension(af);
}
addMessage(Level.INFO,"Data file written for " + currExtension + " with "+ currRecords+ " records and "+ totalColumns+ " columns");
if (currRecordsSkipped > 0) {
addMessage(Level.WARN,"!!! " + currRecordsSkipped + " records were skipped for "+ currExtension+ " due to errors interpreting line, or because the line was empty");
}
}
| Adds a single data file for a list of extension mappings that must all be mapped to the same extension. </br> The ID column is always the 1st column (index 0) and is always equal to the core record identifier that has been mapped (e.g. occurrenceID, taxonID, etc). |
public Filter createFilter(BridgeContext ctx,Element filterElement,Element filteredElement,GraphicsNode filteredNode,Filter inputFilter,Rectangle2D filterRegion,Map filterMap){
List srcs=extractFeMergeNode(filterElement,filteredElement,filteredNode,inputFilter,filterMap,ctx);
if (srcs == null) {
return null;
}
if (srcs.size() == 0) {
return null;
}
Iterator iter=srcs.iterator();
Rectangle2D defaultRegion=(Rectangle2D)((Filter)iter.next()).getBounds2D().clone();
while (iter.hasNext()) {
defaultRegion.add(((Filter)iter.next()).getBounds2D());
}
Rectangle2D primitiveRegion=SVGUtilities.convertFilterPrimitiveRegion(filterElement,filteredElement,filteredNode,defaultRegion,filterRegion,ctx);
Filter filter=new CompositeRable8Bit(srcs,CompositeRule.OVER,true);
handleColorInterpolationFilters(filter,filterElement);
filter=new PadRable8Bit(filter,primitiveRegion,PadMode.ZERO_PAD);
updateFilterMap(filterElement,filter,filterMap);
return filter;
}
| Creates a <tt>Filter</tt> primitive according to the specified parameters. |
public RandomPlayer(char mark){
super(mark);
}
| Construct a Random player who determines a move randomly from available open cells. |
private void addEntryMarkdownToExport(Entry entry,StringBuilder result,SourcesHashList sources,boolean includeQuotations,boolean includeReferencesSection,boolean skipThisLevel) throws IOException {
if (!skipThisLevel) {
final Entry source=dbLogic.getEntryById(entry.getSourceId());
int sourceId=0;
if (source != null) {
sourceId=sources.add(source);
}
if (includeQuotations && entry.hasQuotation()) {
result.append(markdownBlockquote(entry.getQuotation("")));
if (includeReferencesSection) {
if (sourceId != 0) {
result.append(" [Reference" + sourceId + "] [Reference"+ sourceId+ "]");
}
}
result.append("\n\n");
}
if (entry.hasNote()) {
result.append(entry.getNote("").replace("\n"," \n") + "\n\n");
}
}
List<?> childrenFromDb=dbLogic.getEntriesByParentId(entry.getId());
if (!childrenFromDb.isEmpty()) {
final Hashtable<String,Entry> children=new Hashtable<String,Entry>();
Entry first=null;
for ( final Object childObject : childrenFromDb) {
final Entry child=(Entry)childObject;
children.put(child.getId(),child);
if (!child.hasPreviousSiblingId()) {
first=child;
}
}
if (first != null) {
Entry child=first;
for (int i=0; i < children.size(); ++i) {
if (child == null) {
break;
}
addEntryMarkdownToExport(child,result,sources,includeQuotations,includeReferencesSection,false);
if (!child.hasNextSiblingId()) {
break;
}
final String nextId=child.getNextSiblingId();
child=children.get(nextId);
}
}
else {
final Iterator<Map.Entry<String,Entry>> iterator=children.entrySet().iterator();
while (iterator.hasNext()) {
final Map.Entry<String,Entry> mapEntry=iterator.next();
final Entry child=mapEntry.getValue();
addEntryMarkdownToExport(child,result,sources,includeQuotations,includeReferencesSection,false);
}
}
}
}
| Helper method. Adds the Markdown for an entry to an export. |
private void displaySimple(PrintStream output){
output.println("First-Order Effects");
for (int j=0; j < P; j++) {
double[] a0=new double[N];
double[] a1=new double[N];
double[] a2=new double[N];
for (int i=0; i < N; i++) {
a0[i]=A[i];
a1[i]=C_A[i][j];
a2[i]=B[i];
}
double value=computeFirstOrder(a0,a1,a2,N);
output.print(value < 0 ? 0.0 : value);
if (j < P - 1) {
output.print('\t');
}
}
output.println();
output.println("Total-Order Effects");
for (int j=0; j < P; j++) {
double[] a0=new double[N];
double[] a1=new double[N];
double[] a2=new double[N];
for (int i=0; i < N; i++) {
a0[i]=A[i];
a1[i]=C_A[i][j];
a2[i]=B[i];
}
double value=computeTotalOrder(a0,a1,a2,N);
output.print(value < 0 ? 0.0 : value);
if (j < P - 1) {
output.print('\t');
}
}
output.println();
}
| Computes and displays the first- and total-order Sobol' sensitivites and 50% bootstrap confidence intervals. |
public ByteBuffer read(final long off,final int nbytes) throws IOException {
final ByteBuffer tmp=ByteBuffer.allocate(nbytes);
FileChannelUtility.readAll(this,tmp,off);
tmp.flip();
return tmp;
}
| Read some data out of the file. |
public AddReviewerResult(String reviewer,boolean confirm){
this(reviewer);
this.confirm=confirm;
}
| Constructs a needs-confirmation result for the given account. |
private JFrame createMainFrame(){
JFrame result=new JFrame();
result.setPreferredSize(new Dimension(400,300));
JTextPane textPane=new JTextPane();
myAppender=createAppender(textPane);
textPane.setEditable(false);
JScrollPane scrollPane=new JScrollPane(textPane);
scrollPane.setPreferredSize(new Dimension(400,300));
result.getContentPane().add(scrollPane,BorderLayout.CENTER);
String fontFamily="Courier New";
Font font=new Font(fontFamily,Font.PLAIN,1);
textPane.setFont(font);
result.pack();
result.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
return result;
}
| createMainFrame <p> |
public boolean isJsonNull(){
return this instanceof JsonNull;
}
| provides check for verifying if this element represents a null value or not. |
public static Seconds seconds(int seconds){
switch (seconds) {
case 0:
return ZERO;
case 1:
return ONE;
case 2:
return TWO;
case 3:
return THREE;
case Integer.MAX_VALUE:
return MAX_VALUE;
case Integer.MIN_VALUE:
return MIN_VALUE;
default :
return new Seconds(seconds);
}
}
| Obtains an instance of <code>Seconds</code> that may be cached. <code>Seconds</code> is immutable, so instances can be cached and shared. This factory method provides access to shared instances. |
public void testGetters3(){
LayoutBuilder b=builder().setIncludePad(true).setWidth(50);
FontMetricsInt fmi=b.paint.getFontMetricsInt();
Layout l=b.build();
assertVertMetrics(l,fmi.top - fmi.ascent,fmi.bottom - fmi.descent,fmi.top,fmi.descent,fmi.ascent,fmi.bottom);
}
| Basic test showing effect of includePad = true wrapping to 2 lines. Ascent of top line and descent of bottom line are affected. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-08-13 13:14:14.274 -0400",hash_original_method="4681265216BD04726C8DE86640D9EBFD",hash_generated_method="96212B4C3BFA1663294F6F4C683E643F") public static String toASCII(String input,int flags){
return NativeIDN.toASCII(input,flags);
}
| Transform a Unicode String to ASCII Compatible Encoding String according to the algorithm defined in <a href="http://www.ietf.org/rfc/rfc3490.txt">RFC 3490</a>. <p>If the transformation fails (because the input is not a valid IDN), an exception will be thrown. <p>This method can handle either an individual label or an entire domain name. In the latter case, the separators are: U+002E (full stop), U+3002 (ideographic full stop), U+FF0E (fullwidth full stop), and U+FF61 (halfwidth ideographic full stop). All of these will become U+002E (full stop) in the result. |
public void startCDATA() throws org.xml.sax.SAXException {
m_cdataStartCalled=true;
}
| Report the start of a CDATA section. |
public MoveDescription waitForMove(final IPlayerBridge bridge){
return m_movePanel.waitForMove(bridge);
}
| Blocks until the user moves units. |
private boolean isNegative(final String input){
requireNonNull(input);
for ( final String negativeString : negativeStrings) {
if (input.equalsIgnoreCase(negativeString)) {
return true;
}
}
return false;
}
| Checks if a user's input matches one of the negative strings. |
public boolean matchType(Properties jobProp){
if (_confName == null || _confPattern == null) {
return false;
}
return jobProp.containsKey(_confName) && _confPattern.matcher((String)jobProp.get(_confName)).matches();
}
| Check if a JobType matches a property |
@Override public void load(Entity unit) throws IllegalArgumentException {
if (!canLoad(unit)) {
throw new IllegalArgumentException("Can not load " + unit.getShortName() + " into this bay. "+ currentSpace);
}
currentSpace-=1;
if ((unit.game.getPhase() != IGame.Phase.PHASE_DEPLOYMENT) && (unit.game.getPhase() != IGame.Phase.PHASE_LOUNGE)) {
loadedThisTurn+=1;
}
troops.addElement(unit.getId());
}
| Load the given unit. |
public boolean isProjectionStep(){
return projectionStep;
}
| Returns whether or not the projection step is in use after each iteration |
protected int skipWhitespace(int c) throws IOException {
while (c == ' ' || c == '\t') {
c=readCodePoint();
}
return c;
}
| Reads characters from reader until it finds a character that is not a space or tab, and returns this last character code point. In case the end of the character stream has been reached, -1 is returned. |
private void generateRandom(){
int step=k - overlap;
int numberOfFunctions=(n - k) / step + 1;
function=new double[numberOfFunctions][1 << k];
permutation=new int[n];
for (int i=0; i + k <= n; i+=step) {
double max=Double.NEGATIVE_INFINITY;
for (int j=0; j < (1 << k); j++) {
double value=PRNG.nextDouble();
function[i / step][j]=value;
max=Math.max(max,value);
}
}
for (int i=0; i < n; i++) {
permutation[i]=i;
}
PRNG.shuffle(permutation);
}
| Generates a new, random problem instance. |
private int checkInterruptWhileWaiting(Node node){
return Thread.interrupted() ? (transferAfterCancelledWait(node) ? THROW_IE : REINTERRUPT) : 0;
}
| Checks for interrupt, returning THROW_IE if interrupted before signalled, REINTERRUPT if after signalled, or 0 if not interrupted. |
@DSComment("Private Method") @DSBan(DSCat.PRIVATE_METHOD) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:33:07.036 -0500",hash_original_method="35C4B35D5036F5DD5E458797A063F760",hash_generated_method="06BDD6176671442A00DBFA1F4DCB3855") private void nativeNotifyAnimationStarted(int nativeClass){
addTaint(nativeClass);
}
| Notify webkit that animations have begun (on the hardware accelerated content) |
public void copyFrom(ParameterProperty other){
this.bits=other.bits;
}
| Make this object the same as the given one. |
public static String format(String message,Object[] arguments){
return MessageFormat.format(message,arguments);
}
| Formats the given string with the given argument. |
static void paintDisabledText(Style style,Graphics g,String text,int x,int y){
g.setColor(style.getHighLightColor());
g.drawString(text,x + 1,y + 1);
g.setColor(style.getShadowColor());
g.drawString(text,x,y);
}
| Paint disabled text using a style's highlight and shadow colors. |
public void assertSame(Object expected,Object actual,String errorMessage){
TestUtils.assertSame(expected,actual,errorMessage);
}
| This method just invokes the test utils method, it is here for convenience |
public static byte[] decodeFromFile(String filename) throws java.io.IOException {
byte[] decodedData=null;
Base64.InputStream bis=null;
try {
java.io.File file=new java.io.File(filename);
byte[] buffer=null;
int length=0;
int numBytes=0;
if (file.length() > Integer.MAX_VALUE) {
throw new java.io.IOException("File is too big for this convenience method (" + file.length() + " bytes).");
}
buffer=new byte[(int)file.length()];
bis=new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(file)),Base64.DECODE);
while ((numBytes=bis.read(buffer,length,4096)) >= 0) {
length+=numBytes;
}
decodedData=new byte[length];
System.arraycopy(buffer,0,decodedData,0,length);
}
catch ( java.io.IOException e) {
throw e;
}
finally {
try {
bis.close();
}
catch ( Exception e) {
}
}
return decodedData;
}
| Convenience method for reading a base64-encoded file and decoding it. <p>As of v 2.3, if there is a error, the method will throw an java.io.IOException. <b>This is new to v2.3!</b> In earlier versions, it just returned false, but in retrospect that's a pretty poor way to handle it.</p> |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:58:22.129 -0500",hash_original_method="A70831539166366B9681E2ACC95982AC",hash_generated_method="1AEA9BD8E826B96D44420B922A4B6FA3") private void parseSmsStatusReport(PduParser p,int firstByte){
isStatusReportMessage=true;
forSubmit=(firstByte & 0x20) == 0x00;
messageRef=p.getByte();
recipientAddress=p.getAddress();
scTimeMillis=p.getSCTimestampMillis();
dischargeTimeMillis=p.getSCTimestampMillis();
status=p.getByte();
if (p.moreDataPresent()) {
int extraParams=p.getByte();
int moreExtraParams=extraParams;
while ((moreExtraParams & 0x80) != 0) {
moreExtraParams=p.getByte();
}
if ((extraParams & 0x01) != 0) {
protocolIdentifier=p.getByte();
}
if ((extraParams & 0x02) != 0) {
dataCodingScheme=p.getByte();
}
if ((extraParams & 0x04) != 0) {
boolean hasUserDataHeader=(firstByte & 0x40) == 0x40;
parseUserData(p,hasUserDataHeader);
}
}
}
| Parses a SMS-STATUS-REPORT message. |
public void snippetResin3xLocalDeploy() throws Exception {
InstalledLocalContainer container=new Resin3xInstalledLocalContainer(new Resin3xStandaloneLocalConfiguration("target/myresin3x"));
container.setHome("c:/apps/resin-3.0.18");
container.start();
Deployable war=new WAR("path/to/simple.war");
Deployer deployer=new ResinInstalledLocalDeployer(container);
deployer.deploy(war);
deployer.deploy(war,new URLDeployableMonitor(new URL("http://server:port/some/url")));
container.stop();
}
| Snippet for local deployment on a Resin 3.x container. |
public List<String> hostVcenterChangeDeclineDetails(URI hostId,URI clusterId,URI datacenterId,boolean isVcenter){
Host host=_dbClient.queryObject(Host.class,hostId);
return Lists.newArrayList(ComputeSystemDialogProperties.getMessage("ComputeSystem.hostVcenterChangeDeclineDetails",host.getLabel()));
}
| Get details for a decline event for hostVcenterChange NOTE: In order to maintain backwards compatibility, do not change the signature of this method. |
private void fillComboReport(int AD_PrintFormat_ID){
comboReport.removeEventListener(Events.ON_SELECT,this);
comboReport.getItems().clear();
KeyNamePair selectValue=null;
String sql=MRole.getDefault().addAccessSQL("SELECT AD_PrintFormat_ID, Name, Description " + "FROM AD_PrintFormat " + "WHERE AD_Table_ID=? "+ "AND IsActive='Y' "+ "ORDER BY Name","AD_PrintFormat",MRole.SQL_NOTQUALIFIED,MRole.SQL_RO);
int AD_Table_ID=m_reportEngine.getPrintFormat().getAD_Table_ID();
try {
PreparedStatement pstmt=DB.prepareStatement(sql,null);
pstmt.setInt(1,AD_Table_ID);
ResultSet rs=pstmt.executeQuery();
while (rs.next()) {
KeyNamePair pp=new KeyNamePair(rs.getInt(1),rs.getString(2));
Listitem li=comboReport.appendItem(pp.getName(),pp.getKey());
if (rs.getInt(1) == AD_PrintFormat_ID) {
selectValue=pp;
if (selectValue != null) comboReport.setSelectedItem(li);
}
}
rs.close();
pstmt.close();
}
catch ( SQLException e) {
log.log(Level.SEVERE,sql,e);
}
StringBuffer sb=new StringBuffer("** ").append(Msg.getMsg(Env.getCtx(),"NewReport")).append(" **");
KeyNamePair pp=new KeyNamePair(-1,sb.toString());
comboReport.appendItem(pp.getName(),pp.getKey());
sb=new StringBuffer("** ").append(Msg.getMsg(m_ctx,"CopyReport")).append(" **");
pp=new KeyNamePair(-2,sb.toString());
comboReport.addItem(pp);
comboReport.addEventListener(Events.ON_SELECT,this);
}
| Fill ComboBox comboReport (report options) |
public FileDocument(final File file){
if (file == null) {
throw new NullPointerException();
}
if (!file.exists()) {
throw new DSSException("File Not Found: " + file.getAbsolutePath());
}
this.file=file;
this.name=file.getName();
this.mimeType=MimeType.fromFileName(file.getName());
}
| Create a FileDocument |
T versionStrict(boolean versionStrict){
this.versionStrict=versionStrict;
return this_;
}
| Sets whether to exclude properties that do not support the target version from the written vCard. |
public ConstraintExpr_ createConstraintExpr_(){
ConstraintExpr_Impl constraintExpr_=new ConstraintExpr_Impl();
return constraintExpr_;
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public static void sendRefusal(InternalDistributedMember recipient,int processorId,DM dm){
Assert.assertTrue(recipient != null,"ManageBackupBucketReplyMessage NULL reply message");
ManageBackupBucketReplyMessage m=new ManageBackupBucketReplyMessage(processorId,false,false);
m.setRecipient(recipient);
dm.putOutgoing(m);
}
| Refuse the request to manage the bucket |
public static ListContainersParams create(){
return new ListContainersParams();
}
| Creates and returns arguments holder. |
public OFRoleVendorData(int dataType,int role){
super(dataType);
this.role=role;
}
| Construct an OFRoleVendorData with the specified data type (i.e. either request or reply) and role (i.e. one of of master, slave, or other). |
public SpringWriteTemplate(TransactionManager transactionManager) throws Exception {
setTransactionManager(transactionManager);
afterPropertiesSet();
}
| Create a new SpringWriteTemplate instance. |
private void assertActive() throws ReplicatorException {
if (!active) {
throw new ReplicatorException("Channel assignment service is not enabled");
}
}
| Ensures that the service is active. |
private boolean processAuthenticationResponse(final HttpMethod method){
LOG.trace("enter HttpMethodBase.processAuthenticationResponse(" + "HttpState, HttpConnection)");
try {
switch (method.getStatusCode()) {
case HttpStatus.SC_UNAUTHORIZED:
return processWWWAuthChallenge(method);
case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
return processProxyAuthChallenge(method);
default :
return false;
}
}
catch (final Exception e) {
if (LOG.isErrorEnabled()) {
LOG.error(e.getMessage(),e);
}
return false;
}
}
| Processes a response that requires authentication |
public static float toUnit(short fromUnit,float value,short toUnit){
if (fromUnit == 1) {
fromUnit=2;
}
if (toUnit == 1) {
toUnit=2;
}
return (float)(K[fromUnit - 2][toUnit - 2] * value);
}
| Converts an angle from one unit to another. |
public void testLotsOfBindings() throws Exception {
doTestLotsOfBindings(Byte.MAX_VALUE - 1);
doTestLotsOfBindings(Byte.MAX_VALUE);
doTestLotsOfBindings(Byte.MAX_VALUE + 1);
}
| tests huge amounts of variables in the expression |
public void doTestEntityExpiration() throws Exception {
IDeviceListener mockListener=createMock(IDeviceListener.class);
expect(mockListener.getName()).andReturn("mockListener").anyTimes();
expect(mockListener.isCallbackOrderingPostreq((String)anyObject(),(String)anyObject())).andReturn(false).atLeastOnce();
expect(mockListener.isCallbackOrderingPrereq((String)anyObject(),(String)anyObject())).andReturn(false).atLeastOnce();
ITopologyService mockTopology=createMock(ITopologyService.class);
expect(mockTopology.isAttachmentPointPort(DatapathId.of(anyLong()),OFPort.of(anyShort()))).andReturn(true).anyTimes();
expect(mockTopology.isBroadcastDomainPort(DatapathId.of(1L),OFPort.of(1))).andReturn(false).anyTimes();
expect(mockTopology.isBroadcastDomainPort(DatapathId.of(5L),OFPort.of(1))).andReturn(false).anyTimes();
expect(mockTopology.getL2DomainId(DatapathId.of(1L))).andReturn(DatapathId.of(1L)).anyTimes();
expect(mockTopology.getL2DomainId(DatapathId.of(5L))).andReturn(DatapathId.of(5L)).anyTimes();
expect(mockTopology.isConsistent(DatapathId.of(1L),OFPort.of(1),DatapathId.of(5L),OFPort.of(1))).andReturn(false).anyTimes();
Date topologyUpdateTime=new Date();
expect(mockTopology.getLastUpdateTime()).andReturn(topologyUpdateTime).anyTimes();
replay(mockTopology);
deviceManager.topology=mockTopology;
Calendar c=Calendar.getInstance();
Entity entity1=new Entity(MacAddress.of(1L),null,IPv4Address.of(2),DatapathId.of(1L),OFPort.of(1),c.getTime());
c.add(Calendar.MILLISECOND,-DeviceManagerImpl.ENTITY_TIMEOUT - 1);
Entity entity2=new Entity(MacAddress.of(1L),null,IPv4Address.of(1),DatapathId.of(5L),OFPort.of(1),c.getTime());
deviceManager.learnDeviceByEntity(entity1);
IDevice d=deviceManager.learnDeviceByEntity(entity2);
assertArrayEquals(new IPv4Address[]{IPv4Address.of(1),IPv4Address.of(2)},d.getIPv4Addresses());
assertArrayEquals(new SwitchPort[]{new SwitchPort(DatapathId.of(1L),OFPort.of(1)),new SwitchPort(DatapathId.of(5L),OFPort.of(1))},d.getAttachmentPoints());
Iterator<? extends IDevice> diter=deviceManager.queryClassDevices(d.getEntityClass(),null,null,IPv4Address.of(1),null,null);
assertTrue(diter.hasNext());
assertEquals(d.getDeviceKey(),diter.next().getDeviceKey());
diter=deviceManager.queryClassDevices(d.getEntityClass(),null,null,IPv4Address.of(2),null,null);
assertTrue(diter.hasNext());
assertEquals(d.getDeviceKey(),diter.next().getDeviceKey());
replay(mockListener);
deviceManager.addListener(mockListener);
verify(mockListener);
reset(mockListener);
mockListener.deviceIPV4AddrChanged(isA(IDevice.class));
replay(mockListener);
deviceManager.entityCleanupTask.reschedule(0,null);
d=deviceManager.getDevice(d.getDeviceKey());
assertArrayEquals(new IPv4Address[]{IPv4Address.of(2)},d.getIPv4Addresses());
assertArrayEquals(new SwitchPort[]{new SwitchPort(DatapathId.of(1L),OFPort.of(1)),new SwitchPort(DatapathId.of(5L),OFPort.of(1))},d.getAttachmentPoints());
diter=deviceManager.queryClassDevices(d.getEntityClass(),null,null,IPv4Address.of(2),null,null);
assertTrue(diter.hasNext());
assertEquals(d.getDeviceKey(),diter.next().getDeviceKey());
diter=deviceManager.queryClassDevices(d.getEntityClass(),null,null,IPv4Address.of(1),null,null);
assertFalse(diter.hasNext());
d=deviceManager.findDevice(MacAddress.of(1L),null,null,null,null);
assertArrayEquals(new IPv4Address[]{IPv4Address.of(2)},d.getIPv4Addresses());
assertArrayEquals(new SwitchPort[]{new SwitchPort(DatapathId.of(1L),OFPort.of(1)),new SwitchPort(DatapathId.of(5L),OFPort.of(1))},d.getAttachmentPoints());
verify(mockListener);
}
| Note: Entity expiration does not result in device moved notification. |
public String encode(String str){
if (str == null) {
str="null";
}
int n=str.length();
int j=_first.firstEncodedOffset(str,0,n);
if (j == n) {
return Encode.encode(_last,str);
}
final int remaining=n - j;
final int m=j + _first.maxEncodedLength(n);
CharBuffer input=CharBuffer.allocate(m);
str.getChars(0,j,input.array(),0);
str.getChars(j,n,input.array(),m - remaining);
input.limit(m).position(m - remaining);
CharBuffer tmp=input.duplicate();
tmp.position(j);
CoderResult cr=_first.encode(input,tmp,true);
assert cr.isUnderflow() : "maxEncodedLength was incorrect";
CharBuffer output=CharBuffer.allocate(_last.maxEncodedLength(tmp.position()));
tmp.flip();
cr=_last.encode(tmp,output,true);
assert cr.isUnderflow() : "maxEncodedLength was incorrect";
return new String(output.array(),0,output.position());
}
| Encodes an input string to an output string. |
protected void recalculateInsetRect(Rect outerBounds){
final int parentWidth=outerBounds.width();
final int parentHeight=outerBounds.height();
if (!mIsWidthSet) {
mInsetRect.left=outerBounds.left + (mIsLeftPercent ? parentWidth * mLeft / 100 : mLeft);
mInsetRect.right=outerBounds.right - (mIsRightPercent ? parentWidth * mRight / 100 : mRight);
}
else if (mIsRightSet && !mIsLeftSet) {
mInsetRect.right=outerBounds.right - (mIsRightPercent ? parentWidth * mRight / 100 : mRight);
mInsetRect.left=mInsetRect.right - (mIsWidthPercent ? parentWidth * mWidth / 100 : mWidth);
}
else {
mInsetRect.left=outerBounds.left + (mIsLeftPercent ? parentWidth * mLeft / 100 : mLeft);
mInsetRect.right=mInsetRect.left + (mIsWidthPercent ? parentWidth * mWidth / 100 : mWidth);
}
if (!mIsHeightSet) {
mInsetRect.top=outerBounds.top + (mIsTopPercent ? parentHeight * mTop / 100 : mTop);
mInsetRect.bottom=outerBounds.bottom - (mIsBottomPercent ? parentHeight * mBottom / 100 : mBottom);
}
else if (mIsBottomSet && !mIsTopSet) {
mInsetRect.bottom=outerBounds.bottom - (mIsBottomPercent ? parentHeight * mBottom / 100 : mBottom);
mInsetRect.top=mInsetRect.bottom - (mIsHeightPercent ? parentHeight * mHeight / 100 : mHeight);
}
else {
mInsetRect.top=outerBounds.top + (mIsTopPercent ? parentHeight * mTop / 100 : mTop);
mInsetRect.bottom=mInsetRect.top + (mIsHeightPercent ? parentHeight * mHeight / 100 : mHeight);
}
}
| Update the inset bounds based on provided outer bounds and this layer's state |
private static void sbrHfInverseFilter(float alpha0[][],float alpha1[][],final float Xlow[][][],int k0){
float phi[][][]=new float[3][2][2];
for (int k=0; k < k0; k++) {
SBRDSP.autocorrelate(Xlow[k],phi);
float dk=phi[2][1][0] * phi[1][0][0] - (phi[1][1][0] * phi[1][1][0] + phi[1][1][1] * phi[1][1][1]) / 1.000001f;
if (dk == 0f) {
alpha1[k][0]=0f;
alpha1[k][1]=0f;
}
else {
float tempReal, tempIm;
tempReal=phi[0][0][0] * phi[1][1][0] - phi[0][0][1] * phi[1][1][1] - phi[0][1][0] * phi[1][0][0];
tempIm=phi[0][0][0] * phi[1][1][1] + phi[0][0][1] * phi[1][1][0] - phi[0][1][1] * phi[1][0][0];
alpha1[k][0]=tempReal / dk;
alpha1[k][1]=tempIm / dk;
}
if (phi[1][0][0] == 0f) {
alpha0[k][0]=0f;
alpha0[k][1]=0f;
}
else {
float tempReal, tempIm;
tempReal=phi[0][0][0] + alpha1[k][0] * phi[1][1][0] + alpha1[k][1] * phi[1][1][1];
tempIm=phi[0][0][1] + alpha1[k][1] * phi[1][1][0] - alpha1[k][0] * phi[1][1][1];
alpha0[k][0]=-tempReal / phi[1][0][0];
alpha0[k][1]=-tempIm / phi[1][0][0];
}
if (alpha1[k][0] * alpha1[k][0] + alpha1[k][1] * alpha1[k][1] >= 16.0f || alpha0[k][0] * alpha0[k][0] + alpha0[k][1] * alpha0[k][1] >= 16.0f) {
alpha1[k][0]=0f;
alpha1[k][1]=0f;
alpha0[k][0]=0f;
alpha0[k][1]=0f;
}
}
}
| High Frequency Generation (14496-3 sp04 p214+) and Inverse Filtering (14496-3 sp04 p214) Warning: This routine does not seem numerically stable. |
protected void addTrailerToOutput(byte[] msg,int offset,AbstractMRMessage m){
msg[offset]=0x03;
}
| Add trailer to the outgoing byte stream. |
static public ISeq list(){
return null;
}
| **************************************** list support |
public boolean hasClosedDate(){
return hasExtension(ClosedDate.class);
}
| Returns whether it has the closed date. |
public GetIDs(int i){
m_i=i;
}
| Get IDs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.