code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
@Override public Iterator<Map.Entry<String,FieldAnalysis>> iterator(){
return fieldAnalysisByFieldName.entrySet().iterator();
}
| Returns an iterator over the field analyses map. |
private void decryptLastByte(byte lastIvByte){
int largestPadding;
if (firstPaddingBytes.size() == 1) {
largestPadding=firstPaddingBytes.get(0);
}
else {
largestPadding=secondPaddingBytes.get(0);
}
LOG.debug("first padding bytes: " + firstPaddingBytes.toString());
LOG.debug("second padding bytes: " + secondPaddingBytes.toString());
if (!processingLastBlock) {
iv[blockSize - 1]=(byte)(0x11 ^ largestPadding);
}
byte decryptedLastByte=(byte)(lastIvByte ^ (0x10 ^ largestPadding));
properties.setByte(blockSize - 1,decryptedLastByte);
}
| decrypt last byte to get the padding value |
public boolean isAttrFlagSet(String name,int flags){
return (null != m_attrs) ? ((m_attrs.getIgnoreCase(name) & flags) != 0) : false;
}
| Tell if any of the bits of interest are set for a named attribute type. |
private AdaBoostModel trainBoostingModel(ExampleSet trainingSet) throws OperatorException {
log("Total weight of example set at the beginning: " + this.performance);
Vector<Model> ensembleModels=new Vector<Model>();
Vector<Double> ensembleWeights=new Vector<Double>();
final int iterations=this.getParameterAsInt(PARAMETER_ITERATIONS);
for (int i=0; (i < iterations && this.performance > 0); i++) {
this.currentIteration=i;
ExampleSet iterationSet=(ExampleSet)trainingSet.clone();
Model model=applyInnerLearner(iterationSet);
iterationSet=model.apply(iterationSet);
AdaBoostPerformanceMeasures wp=new AdaBoostPerformanceMeasures(iterationSet);
this.performance=wp.reweightExamples(iterationSet);
PredictionModel.removePredictedLabel(iterationSet);
log("Total weight of example set after iteration " + (this.currentIteration + 1) + " is "+ this.performance);
if (this.isModelUseful(wp) == false) {
log("Discard model because of low advantage on training data.");
return new AdaBoostModel(trainingSet,ensembleModels,ensembleWeights);
}
ensembleModels.add(model);
double errorRate=wp.getErrorRate();
double weight;
if (errorRate == 0) {
weight=Double.POSITIVE_INFINITY;
}
else {
weight=Math.log((1.0d - errorRate) / errorRate);
}
ensembleWeights.add(weight);
}
AdaBoostModel resultModel=new AdaBoostModel(trainingSet,ensembleModels,ensembleWeights);
return resultModel;
}
| Main method for training the ensemble classifier |
public String[][][] attributeNames(){
int numValues=m_classAttribute.numValues();
String[][][] attributeNames=new String[numValues][numValues][];
for (int i=0; i < numValues; i++) {
for (int j=i + 1; j < numValues; j++) {
int numAttributes=m_classifiers[i][j].m_sparseIndices.length;
String[] attrNames=new String[numAttributes];
for (int k=0; k < numAttributes; k++) {
attrNames[k]=m_classifiers[i][j].m_data.attribute(m_classifiers[i][j].m_sparseIndices[k]).name();
}
attributeNames[i][j]=attrNames;
}
}
return attributeNames;
}
| Returns the attribute names. |
public StandardChartTheme(String name){
this(name,false);
}
| Creates a new default instance. |
public void visitClass(ClassNode classNode){
Map<Class<? extends ASTTransformation>,Set<ASTNode>> baseTransforms=classNode.getTransforms(phase);
if (!baseTransforms.isEmpty()) {
final Map<Class<? extends ASTTransformation>,ASTTransformation> transformInstances=new HashMap<Class<? extends ASTTransformation>,ASTTransformation>();
for ( Class<? extends ASTTransformation> transformClass : baseTransforms.keySet()) {
try {
transformInstances.put(transformClass,transformClass.newInstance());
}
catch ( InstantiationException e) {
source.getErrorCollector().addError(new SimpleMessage("Could not instantiate Transformation Processor " + transformClass,source));
}
catch ( IllegalAccessException e) {
source.getErrorCollector().addError(new SimpleMessage("Could not instantiate Transformation Processor " + transformClass,source));
}
}
transforms=new HashMap<ASTNode,List<ASTTransformation>>();
for ( Map.Entry<Class<? extends ASTTransformation>,Set<ASTNode>> entry : baseTransforms.entrySet()) {
for ( ASTNode node : entry.getValue()) {
List<ASTTransformation> list=transforms.get(node);
if (list == null) {
list=new ArrayList<ASTTransformation>();
transforms.put(node,list);
}
list.add(transformInstances.get(entry.getKey()));
}
}
targetNodes=new LinkedList<ASTNode[]>();
super.visitClass(classNode);
for ( ASTNode[] node : targetNodes) {
for ( ASTTransformation snt : transforms.get(node[0])) {
if (snt instanceof CompilationUnitAware) {
((CompilationUnitAware)snt).setCompilationUnit(context.getCompilationUnit());
}
snt.visit(node,source);
}
}
}
}
| Main loop entry. <p> First, it delegates to the super visitClass so we can collect the relevant annotations in an AST tree walk. <p> Second, it calls the visit method on the transformation for each relevant annotation found. |
public void revert(){
this.loca=null;
this.setModelChanged(false);
}
| Revert the loca table builder to the state contained in the last raw data set on the builder. That raw data may be that read from a font file when the font builder was created, that set by a user of the loca table builder, or null data if this builder was created as a new empty builder. |
public InternalGemFireException(String message){
super(message);
}
| Creates a new <code>InternalGemFireException</code>. |
public static void mapColumns(IndexColumn[] indexColumns,Table table){
for ( IndexColumn col : indexColumns) {
col.column=table.getColumn(col.columnName);
}
}
| Map the columns using the column names and the specified table. |
public String useVariant1TipText(){
return "set true to use variant 1 of the paper, otherwise use variant 2.";
}
| Returns the tip text for this property |
public static final int[] threshold(double rpred[],String ts){
int L=rpred.length;
double t[]=thresholdStringToArray(ts,L);
int ypred[]=new int[L];
for (int j=0; j < L; j++) {
ypred[j]=(rpred[j] >= t[j]) ? 1 : 0;
}
return ypred;
}
| Threshold - returns the labels after the prediction-confidence vector is passed through threshold(s). |
public static boolean isValidIfd(int ifdId){
return ifdId == IfdId.TYPE_IFD_0 || ifdId == IfdId.TYPE_IFD_1 || ifdId == IfdId.TYPE_IFD_EXIF || ifdId == IfdId.TYPE_IFD_INTEROPERABILITY || ifdId == IfdId.TYPE_IFD_GPS;
}
| Returns true if the given IFD is a valid IFD. |
@Override public PilotingRollData addEntityBonuses(PilotingRollData roll){
int[] locsToCheck=new int[2];
locsToCheck[0]=Mech.LOC_RLEG;
locsToCheck[1]=Mech.LOC_LLEG;
if (hasFunctionalLegAES()) {
roll.addModifier(-2,"AES bonus");
}
for (int i=0; i < locsToCheck.length; i++) {
int loc=locsToCheck[i];
if (isLocationBad(loc)) {
roll.addModifier(5,getLocationName(loc) + " destroyed");
}
else {
if (getBadCriticals(CriticalSlot.TYPE_SYSTEM,Mech.ACTUATOR_HIP,loc) > 0) {
roll.addModifier(2,getLocationName(loc) + " Hip Actuator destroyed");
if (!game.getOptions().booleanOption("tacops_leg_damage")) {
continue;
}
}
if (getBadCriticals(CriticalSlot.TYPE_SYSTEM,Mech.ACTUATOR_UPPER_LEG,loc) > 0) {
roll.addModifier(1,getLocationName(loc) + " Upper Leg Actuator destroyed");
}
if (getBadCriticals(CriticalSlot.TYPE_SYSTEM,Mech.ACTUATOR_LOWER_LEG,loc) > 0) {
roll.addModifier(1,getLocationName(loc) + " Lower Leg Actuator destroyed");
}
if (getBadCriticals(CriticalSlot.TYPE_SYSTEM,Mech.ACTUATOR_FOOT,loc) > 0) {
roll.addModifier(1,getLocationName(loc) + " Foot Actuator destroyed");
}
}
}
return super.addEntityBonuses(roll);
}
| Add in any piloting skill mods |
public static void write(float latPoint,float lonPoint,int offset_x1,int offset_y1,String stuff,String font,int just,LinkProperties properties,DataOutputStream dos) throws IOException {
dos.write(Link.TEXT_HEADER.getBytes());
dos.writeByte(GRAPHICTYPE_TEXT);
dos.writeByte(RENDERTYPE_OFFSET);
dos.writeFloat(latPoint);
dos.writeFloat(lonPoint);
dos.writeInt(offset_x1);
dos.writeInt(offset_y1);
dos.writeByte(just);
properties.setProperty(LPC_LINKTEXTSTRING,stuff);
properties.setProperty(LPC_LINKTEXTFONT,font);
properties.write(dos);
}
| Rendertype is RENDERTYPE_OFFSET. |
protected MiniFluo startMiniFluo() throws AlreadyInitializedException, TableExistsException {
final List<ObserverSpecification> observers=new ArrayList<>();
observers.add(new ObserverSpecification(TripleObserver.class.getName()));
observers.add(new ObserverSpecification(StatementPatternObserver.class.getName()));
observers.add(new ObserverSpecification(JoinObserver.class.getName()));
observers.add(new ObserverSpecification(FilterObserver.class.getName()));
final HashMap<String,String> exportParams=new HashMap<>();
final RyaExportParameters ryaParams=new RyaExportParameters(exportParams);
ryaParams.setExportToRya(true);
ryaParams.setRyaInstanceName(RYA_INSTANCE_NAME);
ryaParams.setAccumuloInstanceName(instanceName);
ryaParams.setZookeeperServers(zookeepers);
ryaParams.setExporterUsername(ITBase.ACCUMULO_USER);
ryaParams.setExporterPassword(ITBase.ACCUMULO_PASSWORD);
final ObserverSpecification exportObserverConfig=new ObserverSpecification(QueryResultObserver.class.getName(),exportParams);
observers.add(exportObserverConfig);
final FluoConfiguration config=new FluoConfiguration();
config.setMiniStartAccumulo(false);
config.setAccumuloInstance(instanceName);
config.setAccumuloUser(ACCUMULO_USER);
config.setAccumuloPassword(ACCUMULO_PASSWORD);
config.setInstanceZookeepers(zookeepers + "/fluo");
config.setAccumuloZookeepers(zookeepers);
config.setApplicationName(FLUO_APP_NAME);
config.setAccumuloTable("fluo" + FLUO_APP_NAME);
config.addObservers(observers);
FluoFactory.newAdmin(config).initialize(new FluoAdmin.InitializationOptions().setClearTable(true).setClearZookeeper(true));
return FluoFactory.newMiniFluo(config);
}
| Setup a Mini Fluo cluster that uses a temporary directory to store its data. |
public Knowledge2(){
this.forbiddenRulesSpecs=new ArrayList<>();
this.requiredRulesSpecs=new ArrayList<>();
this.knowledgeGroupRules=new HashMap<>();
this.tierSpecs=new ArrayList<>();
this.namesToVars=new HashMap<>();
}
| Constructs a blank knowledge object. |
public void count(T element){
count(element,1);
}
| Increment the count for the given element. |
private void checkForActivityStartTimeAndSimulationTime(){
BufferedWriter writer=IOUtils.getBufferedWriter(this.outputDir + "analysis/checkForActStartTime.txt");
try {
writer.write("personId \t activityType \t activityEndTime\n");
double simEndTime=LoadMyScenarios.getSimulationEndTime(configFile);
for ( Person p : sc.getPopulation().getPersons().values()) {
for ( PlanElement pe : p.getSelectedPlan().getPlanElements()) {
if (pe instanceof Activity) {
double actEndTime=((Activity)pe).getEndTime();
if (actEndTime > simEndTime) {
LOG.error("Activity end time is " + actEndTime + " whereas simulation end time is "+ simEndTime);
writer.write(p.getId() + "\t" + ((Activity)pe).getType()+ "\t"+ actEndTime+ "\n");
}
}
}
}
writer.close();
}
catch ( Exception e) {
throw new RuntimeException("Data is not written in file. Reason: " + e);
}
}
| Check if activity start time is higher than simulation end time. Such person will be "stuckAndAbort". |
public int size(){
return _queue.size();
}
| Returns the size of the Queue. |
public void writeLong(long x){
writeInt((int)(x >>> 32));
writeInt((int)x);
}
| Append a long value. This method writes two int values. |
public static String makeMetaDir(String specDir,String fromChkpt){
if (fromChkpt != null) {
return fromChkpt;
}
String metadir=TLCGlobals.metaDir;
if (metadir == null) {
metadir=specDir + TLCGlobals.metaRoot + FileUtil.separator;
}
SimpleDateFormat sdf;
if (Boolean.getBoolean(FileUtil.class.getName() + ".milliseconds")) {
sdf=new SimpleDateFormat("yy-MM-dd-HH-mm-ss.SSS");
}
else {
sdf=new SimpleDateFormat("yy-MM-dd-HH-mm-ss");
}
metadir+=sdf.format(new Date());
File filedir=new File(metadir);
Assert.check(!filedir.exists(),EC.SYSTEM_METADIR_EXISTS,metadir);
Assert.check(filedir.mkdirs(),EC.SYSTEM_METADIR_CREATION_ERROR,metadir);
return metadir;
}
| The MetaDir is fromChkpt if it is not null. Otherwise, create a new one based on the current time. |
boolean isDtoInterface(Class<?> potentialDto){
for ( DtoImpl dto : getDtoInterfaces()) {
if (dto.getDtoInterface().equals(potentialDto)) {
return true;
}
}
return false;
}
| Tests whether or not a given class is a part of our dto jar, and thus will eventually have a generated Impl that is serializable (thus allowing it to be a generic type). |
public SemEstimator(DataSet dataSet,SemPm semPm){
this(dataSet,semPm,null);
}
| Constructs a Sem Estimator that does default estimation. |
public static ByteOrder nativeOrder(){
return NATIVE_ORDER;
}
| Returns the current platform byte order. |
public int hashCode(){
return items().hashCode();
}
| Produce a hash code. |
private Stream<WordToken> removeAdditionalWords(List<WordToken> words,final PatternExtract pe,final Set<WordToken> entityWords){
return words.stream().filter(null).filter(null).filter(null);
}
| Removes the additional words from the pattern extractor. Filters out stop words and words outside the pattern. |
public void actionPerformed(ActionEvent e){
}
| Action Listener |
public static boolean isWifiConnected(Context context){
ConnectivityManager connectivityManager=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager == null) return false;
return connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected();
}
| Get whether or not a wifi connection is currently connected. |
public void remove(){
_editor.removeFromContents(this);
cleanup();
active=false;
}
| Removes this object from display and persistance |
@Deprecated public static PutResourceParams create(@NotNull String container,@NotNull String targetPath){
return new PutResourceParams().withContainer(container).withTargetPath(targetPath);
}
| Creates arguments holder with required parameters. |
public String toString(){
return Byte.toString(getValue());
}
| Obtains the string representation of this object. |
public CloudObject[] fetch(String[] cloudIds) throws CloudException {
CloudObject[] objs=new CloudObject[cloudIds.length];
for (int iter=0; iter < objs.length; iter++) {
objs[iter]=new CloudObject();
objs[iter].setCloudId(cloudIds[iter]);
}
int err=refresh(objs);
if (err == RETURN_CODE_SUCCESS) {
return objs;
}
throw new CloudException(err);
}
| Fetches the objects from the server. This operation executes immeditely without waiting for commit. |
private static void excludeRemoveInstruction(String varName,ArrayList<Instruction> deleteInst){
for (int i=0; i < deleteInst.size(); i++) {
Instruction inst=deleteInst.get(i);
if ((inst.getType() == INSTRUCTION_TYPE.CONTROL_PROGRAM || inst.getType() == INSTRUCTION_TYPE.SPARK) && ((CPInstruction)inst).getCPInstructionType() == CPINSTRUCTION_TYPE.Variable && ((VariableCPInstruction)inst).isRemoveVariable(varName)) {
deleteInst.remove(i);
}
}
}
| Exclude rmvar instruction for <varname> from deleteInst, if exists |
private DateBuilder(TimeZone tz,Locale lc){
Calendar cal=Calendar.getInstance(tz,lc);
this.tz=tz;
this.lc=lc;
month=cal.get(Calendar.MONTH) + 1;
day=cal.get(Calendar.DAY_OF_MONTH);
year=cal.get(Calendar.YEAR);
hour=cal.get(Calendar.HOUR_OF_DAY);
minute=cal.get(Calendar.MINUTE);
second=cal.get(Calendar.SECOND);
}
| Create a DateBuilder, with initial settings for the current date and time in the given timezone and locale. |
StatementPatternNode stmtPatternWithVar(final String varName,final boolean optional){
final StatementPatternNode spn=(StatementPatternNode)new Helper(){
{
tmp=statementPatternNode(varNode(varName),constantNode(a),constantNode(b));
}
}
.getTmp();
spn.setOptional(optional);
return spn;
}
| Returns a fresh statement pattern with the specified variable bound that is either optional or not, as specified by the second parameter. |
void init(int opmode,Key key,AlgorithmParameterSpec params,SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
if (((opmode == Cipher.DECRYPT_MODE) || (opmode == Cipher.UNWRAP_MODE)) && (params == null)) {
throw new InvalidAlgorithmParameterException("Parameters " + "missing");
}
if ((key == null) || (key.getEncoded() == null) || !(key.getAlgorithm().regionMatches(true,0,"PBE",0,3))) {
throw new InvalidKeyException("Missing password");
}
if (params == null) {
salt=new byte[8];
random.nextBytes(salt);
}
else {
if (!(params instanceof PBEParameterSpec)) {
throw new InvalidAlgorithmParameterException("Wrong parameter type: PBE expected");
}
salt=((PBEParameterSpec)params).getSalt();
if (salt.length != 8) {
throw new InvalidAlgorithmParameterException("Salt must be 8 bytes long");
}
iCount=((PBEParameterSpec)params).getIterationCount();
if (iCount <= 0) {
throw new InvalidAlgorithmParameterException("IterationCount must be a positive number");
}
}
byte[] derivedKey=deriveCipherKey(key);
SecretKeySpec cipherKey=new SecretKeySpec(derivedKey,0,derivedKey.length - 8,algo);
IvParameterSpec ivSpec=new IvParameterSpec(derivedKey,derivedKey.length - 8,8);
cipher.init(opmode,cipherKey,ivSpec,random);
}
| Initializes this cipher with a key, a set of algorithm parameters, and a source of randomness. The cipher is initialized for one of the following four operations: encryption, decryption, key wrapping or key unwrapping, depending on the value of <code>opmode</code>. <p>If this cipher (including its underlying feedback or padding scheme) requires any random bytes, it will get them from <code>random</code>. |
public Task performSuspendOperation(String vmId) throws IOException {
String path=String.format("%s/%s/suspend",getBasePath(),vmId);
HttpResponse httpResponse=this.restClient.perform(RestClient.Method.POST,path,null);
this.restClient.checkResponse(httpResponse,HttpStatus.SC_CREATED);
return parseTaskFromHttpResponse(httpResponse);
}
| Perform a VM Suspend Operation on specified vm. |
public boolean isTruncatingTrailingData(){
return this.truncatingTrailingData;
}
| Returns the truncatingTrailingData property. This boolean switch makes the TableReader throw an IOException when it encounters a record whose length is greater than the headers. The default behaviour is that subsequent records are ignored. The default value for this switch is true. |
public boolean isSetType(){
return this.type != null;
}
| Returns true if field type is set (has been assigned a value) and false otherwise |
public static Description createSuiteDescription(String name,Annotation... annotations){
return new Description(null,name,annotations);
}
| Create a <code>Description</code> named <code>name</code>. Generally, you will add children to this <code>Description</code>. |
void generateTrunk(){
BlockPos blockpos=this.basePos;
BlockPos blockpos1=this.basePos.up(this.height);
IBlockState block=this.logBlock;
this.func_175937_a(blockpos,blockpos1,block);
if (this.trunkSize == 2) {
this.func_175937_a(blockpos.east(),blockpos1.east(),block);
this.func_175937_a(blockpos.east().south(),blockpos1.east().south(),block);
this.func_175937_a(blockpos.south(),blockpos1.south(),block);
}
}
| Places the trunk for the big tree that is being generated. Able to generate double-sized trunks by changing a field that is always 1 to 2. |
public boolean simple_edges_bidirectional(){
return soot.PhaseOptions.getBoolean(options,"simple-edges-bidirectional");
}
| Simple Edges Bidirectional -- Equality-based analysis between variable nodes. When this option is set to true, all edges connecting variable (Green) nodes are made bidirectional, as in Steensgaard's analysis. |
public void windowClosing(java.awt.event.WindowEvent e){
doneButtonActionPerformed();
super.windowClosing(e);
}
| Method to close the window when the close box is clicked |
public void generateSinusFunctions(ExampleSet exampleSet,List<AttributePeak> attributes,Random random) throws GenerationException {
if (attributes.size() > 0) {
Collections.sort(attributes);
double totalMaxEvidence=attributes.get(0).getEvidence();
Iterator<AttributePeak> a=attributes.iterator();
while (a.hasNext()) {
AttributePeak ae=a.next();
if (ae.getEvidence() > MIN_EVIDENCE * totalMaxEvidence) {
for (int i=0; i < attributesPerPeak; i++) {
double frequency=ae.getFrequency();
switch (adaptionType) {
case UNIFORMLY:
if (attributesPerPeak != 1) {
frequency=(double)i / (double)(attributesPerPeak - 1) * 2.0d * epsilon * frequency + (frequency - epsilon * frequency);
}
break;
case UNIFORMLY_WITHOUT_NU:
if (attributesPerPeak != 1) {
frequency=(double)i / (double)(attributesPerPeak - 1) * 2.0d * epsilon + (frequency - epsilon);
}
break;
case GAUSSIAN:
frequency=random.nextGaussian() * epsilon + frequency;
break;
}
List frequencyResult=generateAttribute(exampleSet,new ConstantGenerator(frequency));
FeatureGenerator scale=new BasicArithmeticOperationGenerator(BasicArithmeticOperationGenerator.PRODUCT);
scale.setArguments(new Attribute[]{(Attribute)frequencyResult.get(0),ae.getAttribute()});
List scaleResult=generateAttribute(exampleSet,scale);
FeatureGenerator sin=new TrigonometricFunctionGenerator(TrigonometricFunctionGenerator.SINUS);
sin.setArguments(new Attribute[]{(Attribute)scaleResult.get(0)});
List<Attribute> sinResult=generateAttribute(exampleSet,sin);
for (Attribute attribute : sinResult) {
exampleSet.getAttributes().addRegular(attribute);
}
}
}
}
}
}
| Generates a new sinus function attribute for all given attribute peaks. Since the frequency cannot be calculated exactly (leakage, aliasing), several new attribute may be added for each peak. These additional attributes are randomly chosen (uniformly in epsilon range, uniformly without nu, gaussian with epsilon as standard deviation) |
default Builder withPassword(String password){
return with(PASSWORD,password);
}
| Use the given password in the resulting configuration. |
public static void fixTooltipDuration(){
noCatch(null);
}
| Uses reflection to change to tooltip delay/duration to some sane values. <p> See <a href="https://javafx-jira.kenai.com/browse/RT-19538">https://javafx-jira.kenai.com/browse/RT-19538</a> |
public void stop(){
invoke(embeddedStop);
}
| Stops the container. |
protected void addUsageDetails(UsageDetails details){
usageDetails.addUsagePeriods(details.getUsagePeriods());
usageDetails.setFactor(usageDetails.getFactor() + details.getFactor());
}
| Stores the provided usage details for the given role key. If there already is some data stored for that role, the new settings of the usage details will be added to the already existing ones. |
public static List<Number> measurements(List<EvaluationStatistics> stats,String classifier,String dataset,String measurement){
List<Number> result;
result=new ArrayList<>();
for ( EvaluationStatistics stat : stats) {
if (stat.getCommandLine().equals(classifier) && stat.getRelation().equals(dataset)) {
if (stat.containsKey(measurement)) result.add(stat.get(measurement));
}
}
return result;
}
| Returns all the values of a specific measurement for the specified classifier/dataset combination. |
public static String toString(float[] self){
return InvokerHelper.toString(self);
}
| Returns the string representation of the given array. |
public void yypushback(int number){
if (number > yylength()) zzScanError(ZZ_PUSHBACK_2BIG);
zzMarkedPos-=number;
}
| Pushes the specified amount of characters back into the input stream. They will be read again by then next call of the scanning method |
public static _Fields findByThriftId(int fieldId){
switch (fieldId) {
case 1:
return MESSAGE_TYPE;
case 2:
return SW_PORT_TUPLE;
case 3:
return DATA;
default :
return null;
}
}
| Find the _Fields constant that matches fieldId, or null if its not found. |
public void stop() throws IOException {
WebSocketFrame frame=new WebSocketFrame((byte)0x08,true,"1000".getBytes());
byte[] rawFrame=frame.encodeFrame();
getSocketOutputStream().write(rawFrame);
getSocketOutputStream().flush();
if (webSocketReceiver != null) {
webSocketReceiver.stop();
}
super.stop();
}
| Stops the module, by closing the TCP socket. |
protected void startupModules(Collection<IFloodlightModule> moduleSet) throws FloodlightModuleException {
for ( IFloodlightModule m : moduleSet) {
if (startedSet.contains(m.getClass().getCanonicalName())) continue;
startedSet.add(m.getClass().getCanonicalName());
if (logger.isDebugEnabled()) {
logger.debug("Starting " + m.getClass().getCanonicalName());
}
m.startUp(floodlightModuleContext);
}
}
| Call each loaded module's startup method |
protected String mapToJson(Object obj) throws JsonProcessingException {
ObjectMapper mapper=new ObjectMapper();
return mapper.writeValueAsString(obj);
}
| Maps an Object into a JSON String. Uses a Jackson ObjectMapper. |
public SerialMessage(String m,int l){
super(m);
setResponseLength(l);
setBinary(true);
}
| This ctor interprets the String as the exact sequence to send, byte-for-byte. |
public int equivHashCode(){
return 1729;
}
| Returns a hash code for this object, consistent with structural equality. |
public void logException(Exception ex){
if (traceLevel >= TRACE_EXCEPTION) {
checkLogFile();
ex.printStackTrace();
if (printWriter != null) ex.printStackTrace(printWriter);
}
}
| Log an exception stack trace. |
private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName,java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
if (xmlWriter.getPrefix(namespace) == null) {
xmlWriter.writeNamespace(prefix,namespace);
xmlWriter.setPrefix(prefix,namespace);
}
xmlWriter.writeAttribute(namespace,attName,attValue);
}
| Util method to write an attribute with the ns prefix |
public static double twoPow(final int power){
if (power <= -MAX_DOUBLE_EXPONENT) {
if (power >= MIN_DOUBLE_EXPONENT) {
return Double.longBitsToDouble(0x0008000000000000L >> -(power + MAX_DOUBLE_EXPONENT));
}
else {
return 0.0;
}
}
else if (power > MAX_DOUBLE_EXPONENT) {
return Double.POSITIVE_INFINITY;
}
else {
return Double.longBitsToDouble((long)(power + MAX_DOUBLE_EXPONENT) << 52);
}
}
| Returns the exact result, provided it's in double range, i.e. if power is in [-1074,1023]. |
public PTQLink2(final Link link2,QNetwork network,final QNode toNode){
this(link2,network,toNode,new FIFOVehicleQ());
}
| Initializes a QueueLink with one QueueLane. |
public static void createTable(SQLiteDatabase db,boolean ifNotExists){
String constraint=ifNotExists ? "IF NOT EXISTS " : "";
db.execSQL("CREATE TABLE " + constraint + "'DEVICE_DB' ("+ "'_id' INTEGER PRIMARY KEY NOT NULL ,"+ "'KEY' TEXT NOT NULL ,"+ "'BSSID' TEXT NOT NULL ,"+ "'TYPE' INTEGER NOT NULL ,"+ "'STATE' INTEGER NOT NULL ,"+ "'IS_OWNER' INTEGER NOT NULL ,"+ "'NAME' TEXT NOT NULL ,"+ "'ROM_VERSION' TEXT,"+ "'LATEST_ROM_VERSION' TEXT,"+ "'TIMESTAMP' INTEGER NOT NULL ,"+ "'ACTIVATED_TIME' INTEGER NOT NULL ,"+ "'USER_ID' INTEGER NOT NULL );");
}
| Creates the underlying database table. |
public EglCore(){
this(null,0);
}
| Prepares EGL display and context. <p> Equivalent to EglCore(null, 0). |
public Dimension minimumSize(){
return getMinimumSize();
}
| DEPRECATED: Replaced by getMinimumSize(). |
public static int computeMessageSizeNoTag(final MessageLite value){
final int size=value.getSerializedSize();
return computeRawVarint32Size(size) + size;
}
| Compute the number of bytes that would be needed to encode an embedded message field. |
public final void automaticallyReleaseConnectionToPool(){
automaticallyReleaseConnectionToPool=true;
if (connection != null && connectionReleased) {
client.getConnectionPool().recycle(connection);
connection=null;
}
}
| Cause the socket connection to be released to the connection pool when it is no longer needed. If it is already unneeded, it will be pooled immediately. Otherwise the connection is held so that redirects can be handled by the same connection. |
Cursor query(H2Database db,String[] projectionIn,String selection,String[] selectionArgs,String groupBy,String having,String orderBy){
return null;
}
| Run the query for the given parameters. |
private void grow(int minCapacity){
int oldCapacity=queue.length;
int newCapacity=oldCapacity + ((oldCapacity < 64) ? (oldCapacity + 2) : (oldCapacity >> 1));
if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity=hugeCapacity(minCapacity);
queue=Arrays.copyOf(queue,newCapacity);
}
| Increases the capacity of the array. |
public boolean hasValue(){
return getValue() != null;
}
| Returns whether it has the value. |
public void writeFile(ArrayList<DccLocoAddress> consistList,String fileName) throws IOException {
Element root=new Element("consist-roster-config");
Document doc=newDocument(root,dtdLocation + "consist-roster-config.dtd");
Map<String,String> m=new HashMap<String,String>();
m.put("type","text/xsl");
m.put("href",xsltLocation + "consistRoster.xsl");
ProcessingInstruction p=new ProcessingInstruction("xml-stylesheet",m);
doc.addContent(0,p);
Element roster=new Element("roster");
for (int i=0; i < consistList.size(); i++) {
Consist newConsist=consistMan.getConsist(consistList.get(i));
roster.addContent(consistToXml(newConsist));
}
root.addContent(roster);
try {
if (!checkFile(fileName)) {
File file=new File(fileName);
File parentDir=file.getParentFile();
if (!parentDir.exists()) {
if (!parentDir.mkdir()) {
throw (new IOException());
}
}
if (!file.createNewFile()) {
throw (new IOException());
}
}
writeXML(findFile(fileName),doc);
}
catch ( IOException ioe) {
log.error("IO Exception " + ioe);
throw (ioe);
}
}
| Write all consists to a file. |
private boolean isIrreducible(int[] a){
if (a[0] == 0) {
return false;
}
int d=computeDegree(a) >> 1;
int[] u={0,1};
final int[] Y={0,1};
int fieldDegree=field.getDegree();
for (int i=0; i < d; i++) {
for (int j=fieldDegree - 1; j >= 0; j--) {
u=modMultiply(u,u,a);
}
u=normalForm(u);
int[] g=gcd(add(u,Y),a);
if (computeDegree(g) != 0) {
return false;
}
}
return true;
}
| Check a polynomial for irreducibility over the field <tt>GF(2^m)</tt>. |
public void rewind() throws IOException {
seekTo(beginLocation);
}
| Rewind to the first entry in the scanner. The entry returned by the previous entry() call will be invalid. |
@Override protected String doRender(Object obj,JPanel panel){
DataTable table;
Instances data;
data=(Instances)obj;
if (data.numInstances() == 0) return new PlainTextRenderer().render(obj,panel);
table=new DataTable(new DataSortedTableModel(data));
panel.add(new BaseScrollPane(table),BorderLayout.CENTER);
return null;
}
| Performs the actual rendering. |
protected void showMsgLong(String msg){
showMsg(msg,Snackbar.LENGTH_SHORT);
}
| snack show an long message |
public void validate() throws MessageException {
List requiredFields=getRequiredFields();
Iterator paramIter=_params.getParameters().iterator();
while (paramIter.hasNext()) {
Parameter param=(Parameter)paramIter.next();
if (!param.isValid()) throw new MessageException("Invalid parameter: " + param);
}
if (requiredFields == null) return;
Iterator reqIter=requiredFields.iterator();
while (reqIter.hasNext()) {
String required=(String)reqIter.next();
if (!hasParameter(required)) throw new MessageException("Required parameter missing: " + required);
}
}
| Checks that all required parameters are present |
protected void reportReturn(String methodCall){
reportAllReturns(methodCall,"");
}
| Conveniance method to report (for logging) that a method returned (void return type). |
@Override protected final boolean operateOnRegion(DistributionManager dm,LocalRegion r,long startTime) throws EntryExistsException, RemoteOperationException {
this.setInternalDs(r.getSystem());
boolean sendReply=true;
InternalDistributedMember eventSender=originalSender;
if (eventSender == null) {
eventSender=getSender();
}
@Released EntryEventImpl eei=EntryEventImpl.create(r,getOperation(),getKey(),null,getCallbackArg(),useOriginRemote,eventSender,true,false);
this.event=eei;
try {
if (this.versionTag != null) {
this.versionTag.replaceNullIDs(getSender());
event.setVersionTag(this.versionTag);
}
this.event.setCausedByMessage(this);
event.setPossibleDuplicate(this.possibleDuplicate);
if (this.bridgeContext != null) {
event.setContext(this.bridgeContext);
}
Assert.assertTrue(eventId != null);
event.setEventId(eventId);
if (this.hasOldValue) {
if (this.oldValueIsSerialized) {
event.setSerializedOldValue(getOldValueBytes());
}
else {
event.setOldValue(getOldValueBytes());
}
}
if (this.applyDeltaBytes) {
event.setNewValue(this.valObj);
event.setDeltaBytes(this.deltaBytes);
}
else {
switch (this.deserializationPolicy) {
case DistributedCacheOperation.DESERIALIZATION_POLICY_LAZY:
event.setSerializedNewValue(getValBytes());
break;
case DistributedCacheOperation.DESERIALIZATION_POLICY_NONE:
event.setNewValue(getValBytes());
break;
default :
throw new AssertionError("unknown deserialization policy: " + deserializationPolicy);
}
}
try {
result=r.getDataView().putEntry(event,this.ifNew,this.ifOld,this.expectedOldValue,this.requireOldValue,this.lastModified,true);
if (!this.result) {
r.checkReadiness();
if (!this.ifNew && !this.ifOld) {
RemoteOperationException fre=new RemoteOperationException(LocalizedStrings.RemotePutMessage_UNABLE_TO_PERFORM_PUT_BUT_OPERATION_SHOULD_NOT_FAIL_0.toLocalizedString());
fre.setHash(key.hashCode());
sendReply(getSender(),getProcessorId(),dm,new ReplyException(fre),r,startTime);
}
}
}
catch (CacheWriterException cwe) {
sendReply(getSender(),getProcessorId(),dm,new ReplyException(cwe),r,startTime);
return false;
}
catch (PrimaryBucketException pbe) {
sendReply(getSender(),getProcessorId(),dm,new ReplyException(pbe),r,startTime);
return false;
}
setOperation(event.getOperation());
if (sendReply) {
sendReply(getSender(),getProcessorId(),dm,null,r,startTime,event);
}
return false;
}
finally {
this.event.release();
}
}
| This method is called upon receipt and make the desired changes to the Replicate Region. Note: It is very important that this message does NOT cause any deadlocks as the sender will wait indefinitely for the acknowledgement |
public static void addJarFile(String filename){
try {
if (knownFiles.contains(filename)) {
return;
}
File file=new File(filename);
if (!file.canRead()) {
return;
}
knownFiles.add(filename);
ZipFile zipFile=new ZipFile(file);
Enumeration<? extends ZipEntry> entries=zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry=entries.nextElement();
if (!entry.isDirectory()) {
String name=stripLeadingSlash(entry.getName());
contentFilenameMapping.put(name,file);
contentZipFilesMapping.put(name,zipFile);
}
}
}
catch ( IOException e) {
logger.error(e,e);
}
}
| adds a .jar file to the repository |
public static _Fields findByThriftIdOrThrow(int fieldId){
_Fields fields=findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
| Find the _Fields constant that matches fieldId, throwing an exception if it is not found. |
public void findAndUndo(Object someObj){
if (someObj instanceof MapPanel && someObj instanceof Container) {
logger.fine("OpenMapFrame: MapBean is being removed from frame");
getContentPane().remove((Container)someObj);
if (getJMenuBar() == ((MapPanel)someObj).getMapMenuBar()) {
logger.fine("OpenMapFrame: Menu Bar is being removed");
setJMenuBar(null);
}
}
if (someObj instanceof JMenuBar) {
if (getJMenuBar() == (JMenuBar)someObj) {
logger.fine("OpenMapFrame: Menu Bar is being removed");
setJMenuBar(null);
}
}
if (this.equals(someObj)) {
dispose();
}
}
| Called when an object is removed from the MapHandler. |
public void addToAttachments(Attachment elem){
if (this.attachments == null) {
this.attachments=new ArrayList<Attachment>();
}
this.attachments.add(elem);
}
| Description: <br> |
public BBOBFunction(int numberOfVariables){
super(numberOfVariables,1);
}
| Constructs a new function for the BBOB test suite. |
public static void logUserAction(String action,String... pairs){
Server server=App.getInstance().getServer();
if (server != null) {
List<String> allPairs=Lists.newArrayList("action",action);
allPairs.addAll(Arrays.asList(pairs));
server.logToServer(allPairs);
}
}
| Logs a user action by sending a dummy request to the server. (The server logs can then be scanned later to produce analytics for the client app.) |
public static String extractMusicIDFromMediaID(String mediaID){
int pos=mediaID.indexOf(LEAF_SEPARATOR);
if (pos >= 0) {
return mediaID.substring(pos + 1);
}
return null;
}
| Extracts unique musicID from the mediaID. mediaID is, by this sample's convention, a concatenation of category (eg "by_genre"), categoryValue (eg "Classical") and unique musicID. This is necessary so we know where the user selected the music from, when the music exists in more than one music list, and thus we are able to correctly build the playing queue. |
private Path convert(IgfsPath path){
URI uri=fileSystemForUser().getUri();
return new Path(uri.getScheme(),uri.getAuthority(),path.toString());
}
| Convert IGFS path into Hadoop path. |
public IgniteConsistencyException(String msg){
super(msg);
}
| Creates new exception with given error message. |
@Override protected void overrideIdentifierData(EmaApiIdentifierType identifier) throws EmaException {
}
| Set specific embed level for this event in CallHome Identifier section. |
@Override public void eUnset(int featureID){
switch (featureID) {
case N4JSPackage.ABSTRACT_CATCH_BLOCK__BLOCK:
setBlock((Block)null);
return;
}
super.eUnset(featureID);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public JSONObject makeNumberVerifiedProps(VerificationMethod verificationMethod){
JSONObject props;
try {
props=new JSONObject();
props.put("Verification Method",verificationMethod.code);
}
catch ( JSONException e) {
Logger.e(TAG,"Error building Mixpanel Props",e);
props=null;
}
return props;
}
| Create a Props object for number verified |
public StrBuilder appendNull(){
if (nullText == null) {
return this;
}
return append(nullText);
}
| Appends the text representing <code>null</code> to this string builder. |
public static String hexlify(byte[] bytes){
char[] hexChars=new char[bytes.length * 2];
for (int j=0; j < bytes.length; j++) {
int v=bytes[j] & 0xFF;
hexChars[j * 2]=hexArray[v >>> 4];
hexChars[j * 2 + 1]=hexArray[v & 0x0F];
}
String ret=new String(hexChars);
return ret;
}
| Transform a byte array into a it's hexadecimal representation |
public boolean remove(Object attrval){
int i=find(attrval);
if (i >= 0) {
values.removeElementAt(i);
return true;
}
return false;
}
| Removes a specified value from this attribute. <p> By default, <tt>Object.equals()</tt> is used when comparing <tt>attrVal</tt> with this attribute's values except when <tt>attrVal</tt> is an array. For an array, each element of the array is checked using <tt>Object.equals()</tt>. A subclass may use schema information to determine equality. |
private static long processDuration(long remainingDuration,long millisPerDuration,String durationName,StringBuilder result,boolean displayZeroDuration){
long duration=remainingDuration / millisPerDuration;
long newRemainingDuration=remainingDuration - (duration * millisPerDuration);
if (duration > 0 || displayZeroDuration) {
if (result.length() > 0) {
result.append(", ");
}
result.append(String.valueOf(duration)).append(' ').append(durationName);
if (duration != 1) {
result.append('s');
}
}
return newRemainingDuration;
}
| Process a single duration. |
void update(Context context){
Resources res=context.getResources();
DisplayMetrics dm=res.getDisplayMetrics();
displayRect.set(0,0,dm.widthPixels,dm.heightPixels);
taskStackScrollDuration=res.getInteger(R.integer.recents_animate_task_stack_scroll_duration);
TypedValue widthPaddingPctValue=new TypedValue();
res.getValue(R.dimen.recents_stack_width_padding_percentage,widthPaddingPctValue,true);
taskStackWidthPaddingPct=widthPaddingPctValue.getFloat();
TypedValue stackOverscrollPctValue=new TypedValue();
res.getValue(R.dimen.recents_stack_overscroll_percentage,stackOverscrollPctValue,true);
taskStackOverscrollPct=stackOverscrollPctValue.getFloat();
taskStackMaxDim=res.getInteger(R.integer.recents_max_task_stack_view_dim);
taskStackTopPaddingPx=res.getDimensionPixelSize(R.dimen.recents_stack_top_padding);
taskViewEnterFromHomeDelay=res.getInteger(R.integer.recents_animate_task_enter_from_home_delay);
taskViewEnterFromHomeDuration=res.getInteger(R.integer.recents_animate_task_enter_from_home_duration);
taskViewEnterFromHomeStaggerDelay=res.getInteger(R.integer.recents_animate_task_enter_from_home_stagger_delay);
taskViewRemoveAnimDuration=res.getInteger(R.integer.recents_animate_task_view_remove_duration);
taskViewRemoveAnimTranslationXPx=res.getDimensionPixelSize(R.dimen.recents_task_view_remove_anim_translation_x);
taskViewTranslationZMinPx=res.getDimensionPixelSize(R.dimen.recents_task_view_z_min);
taskViewTranslationZMaxPx=res.getDimensionPixelSize(R.dimen.recents_task_view_z_max);
}
| Updates the state, given the specified context |
public Builder precision(double precision,DistanceUnit unit){
return precision(unit.toMeters(precision));
}
| Set the precision use o make suggestions |
protected void clearError(){
synchronized (lock) {
ioError=false;
}
}
| Sets the error state of the stream to false. |
private void meekR3(Node a,Graph graph,IKnowledge knowledge){
List<Node> adjacentNodes=graph.getAdjacentNodes(a);
if (adjacentNodes.size() < 3) {
return;
}
for ( Node d : adjacentNodes) {
if (Edges.isUndirectedEdge(graph.getEdge(a,d))) {
List<Node> otherAdjacents=new ArrayList<>(adjacentNodes);
otherAdjacents.remove(d);
ChoiceGenerator cg=new ChoiceGenerator(otherAdjacents.size(),2);
int[] choice;
while ((choice=cg.next()) != null) {
List<Node> nodes=GraphUtils.asList(choice,otherAdjacents);
Node b=nodes.get(0);
Node c=nodes.get(1);
boolean isKite=isKite(a,d,b,c,graph);
if (isKite) {
if (isArrowpointAllowed(d,a,knowledge)) {
if (!isUnshieldedNoncollider(c,d,b,graph)) {
continue;
}
direct(d,a,graph);
log(SearchLogUtils.edgeOrientedMsg("Meek R3",graph.getEdge(d,a)));
}
}
}
}
}
}
| Meek's rule R3. If a--b, a--c, a--d, c-->b, d-->b, then orient a-->b. |
public GroupBuilder<T,E> closeUnion(){
return mParent;
}
| Close this union and return it's parent group builder. |
private void paintDecreaseButtonTogether(Graphics2D g,int width,int height){
paintArrowButton(g,width / 2.0,height / 2.0 - 3);
}
| DOCUMENT ME! |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.