code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
private Job createJobWithParameters(S3PropertiesLocation jobDefinitionS3PropertiesLocation,List<Parameter> jobDefinitionParameters,S3PropertiesLocation jobCreateRequestS3PropertiesLocation,List<Parameter> jobCreateRequestParameters) throws Exception {
namespaceDaoTestHelper.createNamespaceEntity(TEST_ACTIVITI_NAMESPACE_CD);
JobDefinitionCreateRequest jobDefinitionCreateRequest=jobDefinitionServiceTestHelper.createJobDefinitionCreateRequest();
jobDefinitionCreateRequest.setParameters(jobDefinitionParameters);
jobDefinitionCreateRequest.setS3PropertiesLocation(jobDefinitionS3PropertiesLocation);
jobDefinitionService.createJobDefinition(jobDefinitionCreateRequest,false);
JobCreateRequest jobCreateRequest=jobServiceTestHelper.createJobCreateRequest(TEST_ACTIVITI_NAMESPACE_CD,TEST_ACTIVITI_JOB_NAME);
jobCreateRequest.setParameters(jobCreateRequestParameters);
jobCreateRequest.setS3PropertiesLocation(jobCreateRequestS3PropertiesLocation);
return jobService.createAndStartJob(jobCreateRequest);
}
| Creates a new job definition, and a job using the default values and given parameters configurations. |
protected void subdivide(Line2D src,Line2D left,Line2D right){
double x1=src.getX1();
double y1=src.getY1();
double x2=src.getX2();
double y2=src.getY2();
double mx=x1 + (x2 - x1) / 2.0;
double my=y1 + (y2 - y1) / 2.0;
if (left != null) {
left.setLine(x1,y1,mx,my);
}
if (right != null) {
right.setLine(mx,my,x2,y2);
}
}
| divide a Line2D into 2 new Line2Ds that are returned in the passed left and right instances, if non-null |
@PreDestroy @Override public void dispose(){
logger.info(getClass().getName() + " dispose...");
active.set(false);
dequeueService.shutdownNow();
workerService.shutdown();
long stop=System.currentTimeMillis() + 60000;
while (numActive.get() != 0 && stop > System.currentTimeMillis()) {
try {
Thread.sleep(1000);
}
catch ( Exception ignored) {
}
}
logger.info(getClass().getName() + " thread shutdown completed.");
}
| The dispose operation is called at the end of a components lifecycle. Instances of this class use this method to release and destroy any resources that they own. <p/> This implementation shuts down the LinearProcessors managed by this JamesSpoolManager |
public Zone selectExistingZoneForInitiatorPort(NetworkLite network,String initiatorWwn,String portWwn,List<Zone> existingZones){
if (existingZones == null || existingZones.isEmpty()) {
return null;
}
boolean existingZone=true;
Zone foundZone=null;
String key=FCZoneReference.makeEndpointsKey(initiatorWwn,portWwn);
List<FCZoneReference> fcZoneRefs=getFCZoneReferencesForKey(key);
if (!fcZoneRefs.isEmpty()) {
Zone matchedZone=null;
_log.info("Found {} FCZoneReference for key {}",fcZoneRefs.size(),key);
for ( FCZoneReference fcZoneRef : fcZoneRefs) {
if (network.getNetworkSystems().contains(fcZoneRef.getNetworkSystemUri().toString()) && network.getNativeId().equals(fcZoneRef.getFabricId())) {
_log.debug("Found an FCZoneReference for zone {}",fcZoneRef.getZoneName());
matchedZone=findZoneByNameAndPort(fcZoneRef.getZoneName(),portWwn,existingZones);
if (matchedZone != null) {
_log.debug("Found the zone for FCZoneReference {} in the initiator existing zones",fcZoneRef.getZoneName());
_log.debug(matchedZone.getLogString());
foundZone=matchedZone;
if (!fcZoneRef.getExistingZone()) {
existingZone=false;
_log.debug("Selected zone {} because it was created by ViPR",foundZone.getName());
break;
}
}
}
}
}
if (foundZone != null) {
_log.debug("Selected existing Zone {} as it is already used by ViPR",foundZone.getName());
}
else {
outer: for ( Zone curZone : existingZones) {
for ( ZoneMember member : curZone.getMembers()) {
if (member.getAddress() != null && member.getAddress().equals(portWwn)) {
foundZone=curZone;
if (curZone.getMembers().size() == 2) {
_log.debug("Selected existing Zone {} as it has only 2 members",foundZone.getName());
break outer;
}
}
}
}
}
if (foundZone != null) {
foundZone.setExistingZone(existingZone);
}
return foundZone;
}
| Search the list of existing zones for the initiator-port pair to decide which to use. Preference is given to zones according to this priority: <ol> <li>The zone is in ViPR DB and was created by ViPR</li> <li>The zone is in ViPR DB but was not created by ViPR</li> <li>The zone follows the single initiator-target pair per zone</li> <li>The last zone in the list</li> </ol> If no zone can be found for the initiator-port pair, null is returned. |
public void initialise(int dimensions,int base,double epsilon){
this.epsilon=epsilon;
usingSingleKernelWidthValue=true;
mvke.initialise(dimensions,epsilon);
initialiseCommon(base);
}
| Initialise using the supplied kernel width for all continuous variables |
public void addFooterStatement(String footerStatement){
footerStatements.add(footerStatement);
}
| Adds a footer statement. |
public void resultChanged(Result res){
fireResultChanged(res);
}
| Signal that a result has changed (public API) |
public void testUrlValidWithSimplePath(){
setParameterToInitMockMethod("http://myurl.com/myPage",TestSolution.PASSED);
SeoRule01081 test=new SeoRule01081();
test.setProcessResultDataService(mockProcessResultDataService);
test.setTest(mockTest);
ProcessResult processResult=test.processImpl(mockSspHandler);
assertEquals(mockDefiniteResult,processResult);
}
| Test to validate an url with a specified page after the slash character. |
@Nullable public static Class<?>[] readClassArray(ObjectInput in) throws IOException, ClassNotFoundException {
int len=in.readInt();
Class<?>[] arr=null;
if (len > 0) {
arr=new Class<?>[len];
for (int i=0; i < len; i++) arr[i]=(Class<?>)in.readObject();
}
return arr;
}
| Reads array from input stream. |
private void rotateTurntable(double distance){
rotate.fromAngleNormalAxis(azimuth,Vector3.NEG_UNIT_Z);
workRot.fromAngleNormalAxis(elevation,Vector3.UNIT_X);
rotate.multiplyLocal(workRot);
location.set(Vector3.UNIT_Z);
rotate.applyPost(location,location);
location.normalizeLocal();
location.multiplyLocal(distance);
location.addLocal(camera.getLookAt());
camera.setFrame(location,rotate);
updateFromCamera();
updateGeometricState(0);
changed.set(true);
Dert.getMainWindow().updateCompass(azimuth);
}
| Rotate around the center of rotation point (look at point) while facing the CoR. |
@Override public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
| Called when the activity is first created. |
public Set<String> knownClasses(){
Set<String> r=new HashSet<String>();
r.addAll(branchMap.keySet());
r.addAll(branchlessMethods.keySet());
if (logger.isDebugEnabled()) {
logger.debug("Known classes: " + r);
}
return r;
}
| Returns a Set containing all classes for which this pool knows Branches for as Strings |
@Override public Object clone() throws CloneNotSupportedException {
XYSeries clone=(XYSeries)super.clone();
clone.data=(List)ObjectUtilities.deepClone(this.data);
return clone;
}
| Returns a clone of the series. |
void replaceAtt(int nTargetNode,String sName,ArrayList<String> values){
Attribute newAtt=new Attribute(sName,values);
if (m_Instances.classIndex() == nTargetNode) {
m_Instances.setClassIndex(-1);
m_Instances.deleteAttributeAt(nTargetNode);
m_Instances.insertAttributeAt(newAtt,nTargetNode);
m_Instances.setClassIndex(nTargetNode);
}
else {
m_Instances.deleteAttributeAt(nTargetNode);
m_Instances.insertAttributeAt(newAtt,nTargetNode);
}
}
| replace attribute with specified name and values |
public static void compileFiles(List<File> files) throws IOException {
JavaCompiler compiler=ToolProvider.getSystemJavaCompiler();
try (StandardJavaFileManager fileManager=compiler.getStandardFileManager(null,null,null)){
Iterable<? extends JavaFileObject> compilationUnit=fileManager.getJavaFileObjectsFromFiles(files);
compiler.getTask(null,fileManager,null,null,null,compilationUnit).call();
}
}
| Takes a list of files and compile these files into the working directory. |
public head(Element value){
addElement(value);
}
| This method creates a <head> tag and sets it value |
public static void e(String tag,String msg,Throwable thr){
log(LEVEL.ERROR,tag,msg,thr);
}
| Send a ERROR log message and log the exception. |
public Credentials withToken(Token token){
this.token=token;
return this;
}
| Sets the token of this credentials |
private static RPClass createRPClass(){
final RPClass rpclass=new RPClass("area");
rpclass.isA("entity");
rpclass.addAttribute(ATTR_NAME,Type.STRING);
return rpclass;
}
| Define the RPClass. |
public double distanceSq(final java.awt.geom.Point2D p){
final double dx=(double)this.x - p.getX();
final double dy=(double)this.y - p.getY();
return (dx * dx + dy * dy);
}
| Returns the distance FROM this Double2D TO the specified point |
private void prepareInitiatorData() throws Exception {
String currentLabel="RPInitiator1";
Initiator initiator=new Initiator();
initiator.setId(URIUtil.createId(Initiator.class));
initiator.setHostName(currentLabel);
initiator.setInitiatorPort("PORT");
initiator.setInitiatorNode("NODE");
initiator.setProtocol("FC");
initiator.setIsManualCreation(false);
_dbClient.createObject(initiator);
rpTestInitiatorURIs.add(initiator.getId());
rpTestInitiators.add(initiator);
currentLabel="RPInitiator2";
initiator=new Initiator();
initiator.setId(URIUtil.createId(Initiator.class));
initiator.setHostName(currentLabel);
initiator.setInitiatorPort("PORT");
initiator.setInitiatorNode("NODE");
initiator.setProtocol("FC");
initiator.setIsManualCreation(false);
_dbClient.createObject(initiator);
rpTestInitiatorURIs.add(initiator.getId());
rpTestInitiators.add(initiator);
currentLabel="RegularInitiator1";
initiator=new Initiator();
initiator.setId(URIUtil.createId(Initiator.class));
initiator.setHostName(NullColumnValueGetter.getNullStr());
initiator.setInitiatorPort("PORT");
initiator.setInitiatorNode("NODE");
initiator.setProtocol("FC");
initiator.setIsManualCreation(false);
_dbClient.createObject(initiator);
rpTestInitiatorURIs.add(initiator.getId());
rpTestInitiators.add(initiator);
currentLabel="RegularInitiator2";
initiator=new Initiator();
initiator.setId(URIUtil.createId(Initiator.class));
initiator.setHostName(NullColumnValueGetter.getNullStr());
initiator.setInitiatorPort("PORT");
initiator.setInitiatorNode("NODE");
initiator.setProtocol("FC");
initiator.setIsManualCreation(false);
_dbClient.createObject(initiator);
rpTestInitiatorURIs.add(initiator.getId());
rpTestInitiators.add(initiator);
List<URI> initiatorURIs=_dbClient.queryByType(Initiator.class,false);
int count=0;
for ( @SuppressWarnings("unused") URI ignore : initiatorURIs) {
count++;
}
Assert.assertTrue("Expected 4 Initiators, found only " + count,count == 4);
}
| Prepares the data for volume tests. |
private boolean isDominated(State newState){
for (Iterator<State> it=bestStatesAtEdge.get(newState.backEdge).iterator(); it.hasNext(); ) {
State existingState=it.next();
if (dominates(existingState,newState)) {
return true;
}
else if (dominates(newState,existingState)) {
it.remove();
}
}
return false;
}
| Given a new state, check whether it is dominated by any existing state that resulted from traversing the same edge. Side effect: Boot out any existing states that are dominated by the new one. |
public boolean isUnset(String name){
return (values.get(name) == null);
}
| Check if the value for an undocumented option has not been set. |
public Vector decodeEvents(final String document){
if (document != null) {
if (document.trim().equals("")) {
return null;
}
String newDoc=null;
String newPartialEvent=null;
if (document.lastIndexOf(RECORD_END) == -1) {
partialEvent=partialEvent + document;
return null;
}
if (document.lastIndexOf(RECORD_END) + RECORD_END.length() < document.length()) {
newDoc=document.substring(0,document.lastIndexOf(RECORD_END) + RECORD_END.length());
newPartialEvent=document.substring(document.lastIndexOf(RECORD_END) + RECORD_END.length());
}
else {
newDoc=document;
}
if (partialEvent != null) {
newDoc=partialEvent + newDoc;
}
partialEvent=newPartialEvent;
Document doc=parse(newDoc);
if (doc == null) {
return null;
}
return decodeEvents(doc);
}
return null;
}
| Decodes a String representing a number of events into a Vector of LoggingEvents. |
public BasePermissionRequest(String requestUrl,IOneDriveClient client,List<Option> options){
super(requestUrl,client,options,Permission.class);
}
| The request for the Permission |
public Method var(int opcode,int from,int to){
if (from < to) {
for (; from <= to; from++) {
this.insnList.add(new VarInsnNode(opcode,from));
}
}
else if (from > to) {
for (; from >= to; from--) {
this.insnList.add(new VarInsnNode(opcode,from));
}
}
else {
this.insnList.add(new VarInsnNode(opcode,from));
}
return this;
}
| Load a range of vars of the same type |
@Override public boolean clonePropertiesOf(PLIObject object){
if (object != null) {
this.setXAxisEnabled(object.isXAxisEnabled());
this.setYAxisEnabled(object.isYAxisEnabled());
this.setZAxisEnabled(object.isZAxisEnabled());
this.setPitchEnabled(object.isPitchEnabled());
this.setYawEnabled(object.isYawEnabled());
this.setRollEnabled(object.isRollEnabled());
this.setReverseRotation(object.isReverseRotation());
this.setYZAxisInverseRotation(object.isYZAxisInverseRotation());
this.setXRange(object.getXRange());
this.setYRange(object.getYRange());
this.setZRange(object.getZRange());
this.setPitchRange(object.getPitchRange());
this.setYawRange(object.getYawRange());
this.setRollRange(object.getRollRange());
this.setX(object.getX());
this.setY(object.getY());
this.setZ(object.getZ());
this.setPitch(object.getPitch());
this.setYaw(object.getYaw());
this.setRoll(object.getRoll());
this.setDefaultAlpha(object.getDefaultAlpha());
this.setAlpha(object.getAlpha());
return true;
}
return false;
}
| clone methods |
protected AbstractMapEntry(K key,V value){
super(key,value);
}
| Constructs a new entry with the given key and given value. |
public static boolean showSoftInput(Activity activity){
if (activity.getCurrentFocus() != null) {
InputMethodManager imm=(InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
return imm.showSoftInput(activity.getCurrentFocus(),InputMethodManager.SHOW_FORCED);
}
return false;
}
| Show Soft Input |
public GroovyClassDoc[] innerClasses(){
Collections.sort(nested);
return nested.toArray(new GroovyClassDoc[nested.size()]);
}
| returns a sorted array of nested classes and interfaces |
public static Distribution guessAlpha(DataSet d){
return new Uniform(1e-3,1.0);
}
| Guesses the distribution to use for the α parameter |
public void freeConnection(final HttpConnection conn){
final HostConfiguration connectionConfiguration=configurationForConnection(conn);
if (LOG.isDebugEnabled()) {
LOG.debug("Freeing connection, hostConfig=" + connectionConfiguration);
}
synchronized (this) {
if (shutdown) {
conn.close();
return;
}
final HostConnectionPool hostPool=getHostPool(connectionConfiguration,true);
hostPool.freeConnections.add(conn);
if (hostPool.numConnections == 0) {
LOG.error("Host connection pool not found, hostConfig=" + connectionConfiguration);
hostPool.numConnections=1;
}
freeConnections.add(conn);
removeReferenceToConnection((HttpConnectionWithReference)conn);
if (numConnections == 0) {
LOG.error("Host connection pool not found, hostConfig=" + connectionConfiguration);
numConnections=1;
}
idleConnectionHandler.add(conn);
notifyWaitingThread(hostPool);
}
}
| Marks the given connection as free. |
public void notationDecl(String name,String publicId,String systemId) throws SAXException {
}
| Receive notification of a notation declaration event. <p> It is up to the application to record the notation for later reference, if necessary. </p> <p> At least one of publicId and systemId must be non-null. If a system identifier is present, and it is a URL, the SAX parser must resolve it fully before passing it to the application through this event. </p> <p> There is no guarantee that the notation declaration will be reported before any unparsed entities that use it. </p> |
private void updateProgress(int progress){
if (myHost != null && progress != previousProgress) {
myHost.updateProgress(progress);
}
previousProgress=progress;
}
| Used to communicate a progress update between a plugin tool and the main Whitebox user interface. |
public void createPush(RTLExpression value,StatementSequence seq){
createSPIncrement(-(value.getBitWidth() / 8),seq);
seq.addLast(new RTLMemoryAssignment(ExpressionFactory.createMemoryLocation(sp,arch.getAddressBitWidth()),value));
}
| Add a the statements equivalent to a push instruction to the end of a sequence. |
public int V(){
return V;
}
| Returns the number of vertices in this edge-weighted graph. |
public final AssertSubscriber<T> assertError(Class<? extends Throwable> clazz){
assertNotComplete();
int s=errors.size();
if (s == 0) {
throw new AssertionError("No error",null);
}
if (s == 1) {
Throwable e=errors.get(0);
if (!clazz.isInstance(e)) {
throw new AssertionError("Error class incompatible: expected = " + clazz + ", actual = "+ e,null);
}
}
if (s > 1) {
throw new AssertionError("Multiple errors: " + s,null);
}
return this;
}
| Assert an error signal has been received. |
public WavBuffer(java.io.File file) throws java.io.IOException {
if (file == null) {
throw new java.io.IOException("Null file during ctor");
}
java.io.InputStream s=new java.io.BufferedInputStream(new java.io.FileInputStream(file));
try {
buffer=new byte[(int)file.length()];
s.read(buffer);
initFmt();
initData();
}
catch ( java.io.IOException e1) {
log.error("error reading file",e1);
throw e1;
}
finally {
try {
s.close();
}
catch ( java.io.IOException e2) {
log.error("Exception closing file",e2);
}
}
}
| Create from contents of file. The file contents are expected to be in .wav format, starting with a RIFF header. |
public synchronized void put(Object key,Object value){
if (key == null) {
String message=Logging.getMessage("nullValue.KeyIsNull");
Logging.logger().severe(message);
throw new IllegalArgumentException(message);
}
this.entries.put(key,value);
}
| Adds an entry in the cache with a specified key and value. If the cache size after adding the new entry is greater than its capacity, this evicts the eldest entry in the cache. |
public void deleteImageSharings() throws RemoteException {
mRichcallService.tryToDeleteImageSharings();
}
| Deletes all image sharing from history and abort/reject any associated ongoing session if such exists. |
default Class<?> validateToClass(){
return Object.class;
}
| Return the generic class to check the object |
public HornExecution(TransitSectionAction tsa){
_tsa=tsa;
}
| A runnable to implement horn execution |
@ModelAttribute public void addDataToModel(ModelMap model){
SearchData dataForSearchBar=new SearchData();
dataForSearchBar.setSearchMode("natural");
dataForSearchBar.setCurrentPage(1);
dataForSearchBar.setQueryText(null);
dataForSearchBar.setNumberResultsPerPage(10);
model.put("advancedSearchData",dataForSearchBar);
}
| Add an empty searchData object to the model |
private void onPrintJobSent(PrintJob printJob){
printJob.start();
}
| Called on the main thread, when the job was sent to the printer |
private boolean isOperationMethod(Method method){
Class<?>[] paramTypes=method.getParameterTypes();
return paramTypes.length == 1 && paramTypes[0] == Commit.class;
}
| Returns a boolean value indicating whether the given method is an operation method. |
public JComponent createComponent(){
return createHorizontalRangeSlider();
}
| Create a new horizontal range slider for interacting with the query. |
public void testGetInternalSubset() throws Throwable {
Document doc;
DocumentType docType;
DOMImplementation domImpl;
String internal;
String nullNS=null;
doc=(Document)load("staffNS",builder);
domImpl=doc.getImplementation();
docType=domImpl.createDocumentType("l2:root",nullNS,nullNS);
internal=docType.getInternalSubset();
assertNull("internalSubsetNull",internal);
}
| Runs the test case. |
public static String translateLogicalProcessorConstraint(License license){
String limit;
try {
limit=license.getConstraints().getConstraintValue(ProductConstraintManager.INSTANCE.getLogicalProcessorConstraint());
}
catch ( ConstraintNotRestrictedException e) {
limit=I18N.getMessage(I18N.getGUIBundle(),"gui.license.constraint.value.unlimited.label");
}
return I18N.getMessage(I18N.getGUIBundle(),"gui.license.constraint.logical_processor.label",limit);
}
| Translates the logical processor constraint with the license. |
public boolean inviteContactToSharePresence(ContactId contact) throws PayloadException, NetworkException {
mXdm.removeContactFromBlockedList(contact);
mXdm.removeContactFromRevokedList(contact);
HttpResponse response=mXdm.addContactToGrantedList(contact);
if ((response != null) && response.isSuccessfullResponse()) {
return true;
}
return false;
}
| Invite a contact to share its presence |
public void customizerClosing(){
m_dataVis.setOffscreenXAxis(m_xAxisBack);
m_dataVis.setOffscreenWidth(m_widthBack);
m_dataVis.setOffscreenHeight(m_heightBack);
m_dataVis.setOffscreenAdditionalOpts(m_optsBack);
m_dataVis.setOffscreenRendererName(m_rendererNameBack);
}
| Gets called if the use closes the dialog via the close widget on the window - is treated as cancel, so restores the ImageSaver to its previous state. |
@Nullable public V pop(){
return (V)mFreeList.poll();
}
| Remove the first item (if any) from the freelist. Returns null if the free list is empty Does not update the bucket inUse count |
public void testParameterParser() throws Exception {
if (!versionMeetsMinimum(5,0)) {
return;
}
CallableStatement cstmt=null;
try {
createTable("t1","(id char(16) not null default '', data int not null)");
createTable("t2","(s char(16), i int, d double)");
createProcedure("foo42","() insert into test.t1 values ('foo', 42);");
this.conn.prepareCall("{CALL foo42()}");
this.conn.prepareCall("{CALL foo42}");
createProcedure("bar","(x char(16), y int, z DECIMAL(10)) insert into test.t1 values (x, y);");
cstmt=this.conn.prepareCall("{CALL bar(?, ?, ?)}");
ParameterMetaData md=cstmt.getParameterMetaData();
assertEquals(3,md.getParameterCount());
assertEquals(Types.CHAR,md.getParameterType(1));
assertEquals(Types.INTEGER,md.getParameterType(2));
assertEquals(Types.DECIMAL,md.getParameterType(3));
createProcedure("p","() label1: WHILE @a=0 DO SET @a=1; END WHILE");
this.conn.prepareCall("{CALL p()}");
createFunction("f","() RETURNS INT NO SQL return 1; ");
cstmt=this.conn.prepareCall("{? = CALL f()}");
md=cstmt.getParameterMetaData();
assertEquals(Types.INTEGER,md.getParameterType(1));
}
finally {
if (cstmt != null) {
cstmt.close();
}
}
}
| Tests the new parameter parser that doesn't require "BEGIN" or "\n" at end of parameter declaration |
public static boolean canFileBeStoredOnCurrentFilesystem(String fileName){
if (fileName == null) {
return false;
}
String osName=System.getProperty("os.name");
boolean checkColon=osName == null ? true : osName.toLowerCase(Locale.ENGLISH).contains("windows") ? true : false;
if (checkColon && fileName.contains(":")) {
return false;
}
try {
File file=new File(System.getProperty("java.io.tmpdir") + File.separator + fileName);
if (!file.exists()) {
file.createNewFile();
if (file.exists()) {
file.delete();
return true;
}
else {
return false;
}
}
}
catch ( IOException e) {
return false;
}
catch ( SecurityException e) {
return false;
}
catch ( Exception e) {
LogService.getRoot().log(Level.WARNING,"Failed to check filename for illegal characters.",e);
return false;
}
return true;
}
| This method tests if a file with the given file name could be stored on the current filesystem the program is working on. For example, if working on Windows the string <code>foo:bar</code> would return <code>false</code> (because <code>:</code> is forbidden). The string <code>foo_bar</code> would return <code>true</code>. |
public void sub(IntegerPolynomial b,int modulus){
sub(b);
mod(modulus);
}
| Subtracts another polynomial which can have a different number of coefficients, and takes the coefficient values mod <code>modulus</code>. |
public void connect() throws MqttPersistenceException {
MqttToken token=new MqttToken(client.getClientId());
token.setActionCallback(this);
token.setUserContext(this);
persistence.open(client.getClientId(),client.getServerURI());
if (options.isCleanSession()) {
persistence.clear();
}
if (options.getMqttVersion() == MqttConnectOptions.MQTT_VERSION_DEFAULT) {
options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
}
try {
comms.connect(options,token);
}
catch ( MqttException e) {
onFailure(token,e);
}
}
| Start the connect processing |
public double doOperation() throws OperatorFailedException {
NodeRef node0=tree.getInternalNode(MathUtils.nextInt(tree.getInternalNodeCount()));
NodeRef node1=tree.getChild(node0,0);
NodeRef node2=tree.getChild(node0,1);
if (swapRates) {
if (swapAtRoot) {
double[] rates=new double[]{tree.getNodeRate(node0),tree.getNodeRate(node1),tree.getNodeRate(node2)};
int r1=MathUtils.nextInt(3);
tree.setNodeRate(node0,rates[r1]);
rates[r1]=rates[2];
int r2=MathUtils.nextInt(2);
tree.setNodeRate(node1,rates[r2]);
rates[r2]=rates[1];
tree.setNodeRate(node2,rates[0]);
}
else {
double tmp=tree.getNodeRate(node1);
tree.setNodeRate(node1,tree.getNodeRate(node2));
tree.setNodeRate(node2,tmp);
}
}
if (swapTraits) {
if (swapAtRoot) {
double[] traits=new double[]{tree.getNodeTrait(node0,TRAIT),tree.getNodeTrait(node1,TRAIT),tree.getNodeTrait(node2,TRAIT)};
int r1=MathUtils.nextInt(3);
tree.setNodeTrait(node0,TRAIT,traits[r1]);
traits[r1]=traits[2];
int r2=MathUtils.nextInt(2);
tree.setNodeTrait(node1,TRAIT,traits[r2]);
traits[r2]=traits[1];
tree.setNodeTrait(node2,TRAIT,traits[0]);
}
else {
double tmp=tree.getNodeTrait(node1,TRAIT);
tree.setNodeTrait(node1,TRAIT,tree.getNodeTrait(node2,TRAIT));
tree.setNodeTrait(node2,TRAIT,tmp);
}
}
if (!tree.isRoot(node0) && moveHeight) {
double lower=tree.getNodeHeightLower(node0);
double upper=tree.getNodeHeightUpper(node0);
double newValue=(MathUtils.nextDouble() * (upper - lower)) + lower;
tree.setNodeHeight(node0,newValue);
}
return 0.0;
}
| Do a probablistic subtree slide move. |
public Coord4D difference(Coord4D other){
return new Coord4D(xCoord - other.xCoord,yCoord - other.yCoord,zCoord - other.zCoord,dimensionId);
}
| Creates and returns a new Coord4D with values representing the difference between the defined Coord4D |
public byte[] calculateChecksum(byte[] baseKey,int usage,byte[] input,int start,int len) throws GeneralSecurityException {
if (!KeyUsage.isValid(usage)) {
throw new GeneralSecurityException("Invalid key usage number: " + usage);
}
byte[] constant=new byte[5];
constant[0]=(byte)((usage >> 24) & 0xff);
constant[1]=(byte)((usage >> 16) & 0xff);
constant[2]=(byte)((usage >> 8) & 0xff);
constant[3]=(byte)(usage & 0xff);
constant[4]=(byte)0x99;
byte[] Kc=dk(baseKey,constant);
if (debug) {
System.err.println("usage: " + usage);
traceOutput("input",input,start,Math.min(len,32));
traceOutput("constant",constant,0,constant.length);
traceOutput("baseKey",baseKey,0,baseKey.length);
traceOutput("Kc",Kc,0,Kc.length);
}
try {
byte[] hmac=getHmac(Kc,input);
if (debug) {
traceOutput("hmac",hmac,0,hmac.length);
}
if (hmac.length == getChecksumLength()) {
return hmac;
}
else if (hmac.length > getChecksumLength()) {
byte[] buf=new byte[getChecksumLength()];
System.arraycopy(hmac,0,buf,0,buf.length);
return buf;
}
else {
throw new GeneralSecurityException("checksum size too short: " + hmac.length + "; expecting : "+ getChecksumLength());
}
}
finally {
Arrays.fill(Kc,0,Kc.length,(byte)0);
}
}
| Calculate the checksum |
public boolean isCurrentNumber(){
if (!isValidIndex()) return false;
return lcText[pos] >= '0' && lcText[pos] <= '9';
}
| returns if the current character is a number (0-9) |
public void push(final long value){
if (value == 0L || value == 1L) {
mv.visitInsn(Opcodes.LCONST_0 + (int)value);
}
else {
mv.visitLdcInsn(new Long(value));
}
}
| Generates the instruction to push the given value on the stack. |
public static double min(double[] array){
if (array == null) {
throw new IllegalArgumentException("The Array must not be null");
}
else if (array.length == 0) {
throw new IllegalArgumentException("Array cannot be empty.");
}
double min=array[0];
for (int i=1; i < array.length; i++) {
if (Double.isNaN(array[i])) {
return Double.NaN;
}
if (array[i] < min) {
min=array[i];
}
}
return min;
}
| <p>Returns the minimum value in an array.</p> |
public AttributeInfo copy(ConstPool newCp,Map classnames){
Copier copier=new Copier(info,constPool,newCp,classnames);
try {
copier.parameters();
return new ParameterAnnotationsAttribute(newCp,getName(),copier.close());
}
catch ( Exception e) {
throw new RuntimeException(e.toString());
}
}
| Copies this attribute and returns a new copy. |
@Override public boolean equals(Object obj){
if (obj == this) {
return true;
}
if (!(obj instanceof OHLC)) {
return false;
}
OHLC that=(OHLC)obj;
if (this.open != that.open) {
return false;
}
if (this.close != that.close) {
return false;
}
if (this.high != that.high) {
return false;
}
if (this.low != that.low) {
return false;
}
return true;
}
| Tests this instance for equality with an arbitrary object. |
public static String decodeJavaOpts(String encodedJavaOpts){
String javaOptsBase64=encodedJavaOpts.replaceAll("^\"+","").replaceAll("\\s+$","").replace("=","=");
return new String(DatatypeConverter.parseBase64Binary(javaOptsBase64),Charset.forName("UTF-8"));
}
| Decode the JVM options <br> 1. strip \" at the start and at the end <br> 2. replace "&equals;" with "=" <br> 3. Revert from Base64 format |
public synchronized void unset(){
try {
ClassLoader contextClassLoader=Thread.currentThread().getContextClassLoader();
this.unset(contextClassLoader);
}
catch ( SecurityException e) {
}
}
| Unsets the value associated with the current thread's context classloader |
public AcquireTokenByGssInitiateRequestBuilder(TokenSpec tokenSpec,byte[] initialLeg,boolean hokConfirmation,JAXBContext jaxbContext,int requestValidityInSeconds){
super(tokenSpec,hokConfirmation,jaxbContext,requestValidityInSeconds);
assert initialLeg != null;
this.leg=initialLeg;
this.contextId=Util.randomNCNameUUID();
}
| Create the request builder. |
private static char[] zzUnpackCMap(String packed){
char[] map=new char[0x10000];
int i=0;
int j=0;
while (i < 42) {
int count=packed.charAt(i++);
char value=packed.charAt(i++);
do map[j++]=value;
while (--count > 0);
}
return map;
}
| Unpacks the compressed character translation table. |
private void placeVolumeToMaskWithLeastNumberOfVolumes(URI volumeURI,Map<URI,ExportMask> placedMasks){
log.info("These exportMasks are pointing to the same cluster: {}",placedMasks.keySet());
int leastNumberOfVolumes=Integer.MAX_VALUE;
Set<URI> exportMaskWithMoreVolumes=new HashSet<>();
ExportMask currMaskWithLeastVolumes=null;
for ( ExportMask mask : placedMasks.values()) {
int totalVolumeCount=mask.returnTotalVolumeCount();
if (totalVolumeCount < leastNumberOfVolumes) {
if (currMaskWithLeastVolumes != null) {
exportMaskWithMoreVolumes.add(currMaskWithLeastVolumes.getId());
}
leastNumberOfVolumes=totalVolumeCount;
currMaskWithLeastVolumes=mask;
}
else {
exportMaskWithMoreVolumes.add(mask.getId());
}
}
if (currMaskWithLeastVolumes != null) {
log.info(String.format("ExportMask %s was selected for volume %s, as it has %d total volumes",currMaskWithLeastVolumes.getId(),volumeURI,currMaskWithLeastVolumes.returnTotalVolumeCount()));
}
log.info("Determined that this volume {} can be unplaced from these ExportMasks: {}",volumeURI,exportMaskWithMoreVolumes);
log.info("placeVolumeToMaskWithLeastNumberOfVolumes - PlacementDescriptor before:\n{}",placementDescriptor.toString());
for ( URI exportMaskURI : exportMaskWithMoreVolumes) {
placementDescriptor.unplaceVolumeFromMask(volumeURI,exportMaskURI);
}
log.info("placeVolumeToMaskWithLeastNumberOfVolumes - PlacementDescriptor after:\n{}",placementDescriptor.toString());
}
| Routine will adjust the placementDescriptor.placedVolumes, such that the volume will be placed only to one ExportMask (the one with least number of volumes). NB: This routine is to be run in the context of determining volumes that are placed against multiple ExportMasks. The ExportMasks would be pointing to the same cluster, so only a single ExportMask would be required. So, the placedMasks map should contain ExportMasks that point to the same VPlex cluster. |
public static void check(final boolean b){
check(b,"");
}
| Checks if b holds. Call this method to check assertions like pre- and post-conditions. |
public boolean isCellEditable(int rowIndex,int columnIndex){
assert 0 <= rowIndex && rowIndex < rows;
assert 0 <= columnIndex && columnIndex < columns;
return false;
}
| It returns whether the given cell is editable. Right now, no cells are editable. |
protected void focusNext(View view){
int nextId=view.getNextFocusRightId();
if (nextId == NO_ID) {
return;
}
View nextView=findViewById(nextId);
if (nextView.getVisibility() != View.VISIBLE) {
focusNext(nextView);
return;
}
nextView.requestFocus();
currentFocus=nextView;
buttonFocusChangeListener.onFocusChange(nextView,true);
}
| Focuses the next visible view specified in the <code>view</code> |
protected Criteria createCriteriaInternal(){
Criteria criteria=new Criteria();
return criteria;
}
| This method was generated by MyBatis Generator. This method corresponds to the database table iteration_object |
public String prefix(){
return prefix;
}
| Get prefix. |
private void checkPath(String path){
if (!StringUtils.equals(path,_basePath)) {
String root=_basePath + "/";
if (!StringUtils.startsWith(path,root)) {
_log.debug("path '{}' is not within base path '{}'",path,_basePath);
throw CoordinatorException.fatals.dataManagerPathOutOfBounds(path,_basePath);
}
else if (StringUtils.countMatches(StringUtils.remove(path,root),"/") > 0) {
_log.debug("path '{}' is more than one level deep below base path '{}'",path,_basePath);
throw CoordinatorException.fatals.dataManagerPathOutOfBounds(path,_basePath);
}
}
}
| Check that the requested path is acceptable for this data manager |
public JSONException syntaxError(String message,Throwable causedBy){
return new JSONException(message + this.toString(),causedBy);
}
| Make a JSONException to signal a syntax error. |
private String readAttributeName(boolean returnLowerCase){
skipWhitespace();
int c=find(ATTRIBUTE_NAME_TERMINATORS);
String forSubstring=returnLowerCase ? inputLowerCase : input;
String result=pos < c ? forSubstring.substring(pos,c) : null;
pos=c;
return result;
}
| Returns the next attribute name, or null if the input has been exhausted. Returns wth the cursor on the delimiter that follows. |
public char readChar() throws EOFException, FormatException {
try {
int retv=read();
if (retv == -1) {
throw new EOFException("Error in ReadChar, EOF reached");
}
return (char)retv;
}
catch ( IOException i) {
throw new FormatException("IOException in ReadChar: " + i.getMessage());
}
}
| Reads and returns a single byte, cast to a char. |
public void checkStateErrors(MediaRecorderStateErrors stateErrors){
assertTrue(!stateErrors.errorInInitializedState);
assertTrue(stateErrors.errorInInitialState);
assertTrue(stateErrors.errorInInitialStateAfterReset);
assertTrue(stateErrors.errorInInitialStateAfterStop);
assertTrue(stateErrors.errorInPreparedState);
assertTrue(stateErrors.errorInRecordingState);
assertTrue(stateErrors.errorInErrorState);
assertTrue(stateErrors.errorInDataSourceConfiguredState);
}
| 1. It is valid to call setOutputFormat() in the following states: {Initialized}. 2. It is invalid to call setOutputFormat() in the following states: {Initial, Prepared, DataSourceConfigured, Recording, Error} |
public BurlapInput(InputStream is){
init(is);
}
| Creates a new Burlap input stream, initialized with an underlying input stream. |
@Override protected Instances determineOutputFormat(Instances inputFormat) throws Exception {
Instances result;
Attribute att;
Attribute attSorted;
ArrayList<Attribute> atts;
ArrayList<String> values;
Vector<String> sorted;
int i;
int n;
m_AttributeIndices.setUpper(inputFormat.numAttributes() - 1);
atts=new ArrayList<Attribute>();
m_NewOrder=new int[inputFormat.numAttributes()][];
for (i=0; i < inputFormat.numAttributes(); i++) {
att=inputFormat.attribute(i);
if (!att.isNominal() || !m_AttributeIndices.isInRange(i)) {
m_NewOrder[i]=new int[0];
atts.add((Attribute)inputFormat.attribute(i).copy());
continue;
}
sorted=new Vector<String>();
for (n=0; n < att.numValues(); n++) {
sorted.add(att.value(n));
}
Collections.sort(sorted,m_Comparator);
m_NewOrder[i]=new int[att.numValues()];
values=new ArrayList<String>();
for (n=0; n < att.numValues(); n++) {
m_NewOrder[i][n]=sorted.indexOf(att.value(n));
values.add(sorted.get(n));
}
attSorted=new Attribute(att.name(),values);
attSorted.setWeight(att.weight());
atts.add(attSorted);
}
result=new Instances(inputFormat.relationName(),atts,0);
result.setClassIndex(inputFormat.classIndex());
return result;
}
| Determines the output format based on the input format and returns this. |
public static int execCommand(String[] commands,boolean isRoot){
int result=-1;
if (commands == null || commands.length == 0) {
return result;
}
Process process=null;
BufferedReader succBR=null;
BufferedReader errorBR=null;
DataOutputStream dos=null;
try {
process=Runtime.getRuntime().exec(isRoot ? COMMAND_SU : COMMAND_SH);
dos=new DataOutputStream(process.getOutputStream());
for ( String command : commands) {
if (command == null) {
continue;
}
dos.write(command.getBytes());
dos.writeBytes(COMMAND_LINE_END);
dos.flush();
}
dos.writeBytes(COMMAND_EXIT);
dos.flush();
result=process.waitFor();
}
catch ( IOException e) {
e.printStackTrace();
}
catch ( Exception e) {
e.printStackTrace();
}
finally {
IOUtils.close(dos);
IOUtils.close(succBR);
IOUtils.close(errorBR);
if (process != null) {
process.destroy();
}
}
return result;
}
| Exec shell command |
public void save(String filename){
g.save(savePath(filename));
}
| Intercepts any relative paths to make them absolute (relative to the sketch folder) before passing to save() in PImage. (Changed in 0100) |
@Override public void eSet(int featureID,Object newValue){
switch (featureID) {
case MappingPackage.INFO_MODEL_ATTRIBUTE_SOURCE__ATTRIBUTE:
setAttribute((ModelAttribute)newValue);
return;
}
super.eSet(featureID,newValue);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public MatteBorder(Insets borderInsets,Color matteColor){
super(borderInsets);
this.color=matteColor;
}
| Creates a matte border with the specified insets and color. |
public void findAndUndo(Object someObj){
if (someObj == md) {
md=null;
}
if (someObj instanceof MapBean) {
((MapBean)someObj).removeProjectionListener(this);
setProjection((Projection)null);
}
if (someObj instanceof LayerHandler) {
LayerHandler lh=(LayerHandler)someObj;
lh.removeLayerListener(this);
setLayers((Layer[])null);
}
}
| Called by childrenRemoved. |
public int size(){
return sharedQueue.size();
}
| The size of the shared queue (approximate). |
public void printShortString(PrintWriter pw){
pw.print('[');
pw.print(left);
pw.print(',');
pw.print(top);
pw.print("][");
pw.print(right);
pw.print(',');
pw.print(bottom);
pw.print(']');
}
| Print short representation to given writer. |
public LiveRef(int port,RMIClientSocketFactory csf,RMIServerSocketFactory ssf){
this((new ObjID()),port,csf,ssf);
}
| Construct a new live reference for a server object in the local address space, to use sockets of the specified type. |
public boolean equals(Object object){
return (super.equals(object) && object instanceof MediaSize);
}
| Returns whether this media size attribute is equivalent to the passed in object. To be equivalent, all of the following conditions must be true: <OL TYPE=1> <LI> <CODE>object</CODE> is not null. <LI> <CODE>object</CODE> is an instance of class MediaSize. <LI> This media size attribute's X dimension is equal to <CODE>object</CODE>'s X dimension. <LI> This media size attribute's Y dimension is equal to <CODE>object</CODE>'s Y dimension. </OL> |
protected final boolean isTransientEntity(final Object object){
return object instanceof Identifiable && ((Identifiable)object).getId() <= 0L;
}
| Check if object is transient (i.e. new). |
protected AbstractVisionWorldModel(){
super();
setSource(this);
}
| Create a new abstract vision world model. |
public static Mapping serializableInstance(){
return new Mapping(SemIm.serializableInstance(),Parameter.serializableInstance(),new TetradMatrix(0,0),1,1);
}
| Generates a simple exemplar of this class to test serialization. |
@Override public ImmutableMap<String,BlobMetaData> listBlobs() throws IOException {
throw new UnsupportedOperationException("URL repository doesn't support this operation");
}
| This operation is not supported by URLBlobContainer |
public void pushCurrentTemplateRuleIsNull(boolean b){
m_currentTemplateRuleIsNull.push(b);
}
| Push true if the current template rule is null, false otherwise. |
public FolderControl(final Composite parent,final int style,final boolean includeFiles){
this(parent,style,includeFiles,true);
}
| Create a new FolderControl. |
public RuleNode leftNode(){
return m_left;
}
| Get the left child of this node |
public void create(View view){
InstanceConfig instance=new InstanceConfig();
saveProperties(instance);
EditText text=(EditText)findViewById(R.id.templateText);
instance.template=text.getText().toString().trim();
CheckBox checkbox=(CheckBox)findViewById(R.id.forkingCheckBox);
instance.allowForking=checkbox.isChecked();
HttpAction action=new HttpCreateAction(this,instance);
action.execute();
}
| Create the instance. |
public boolean hasNext(){
if (firstIdx < buff.length) {
long[] bucket=buff[firstIdx];
if (bucket != null && secondIdx < bucket.length && bucket[secondIdx] > 0) {
return true;
}
else {
for (int i=firstIdx + 1; i < buff.length; i++) {
if (buff[i] != null && buff[i].length > 0 && buff[i][0] > 0) {
return true;
}
}
}
}
return false;
}
| Returns <tt>true</tt> if the iteration has more elements. (In other words, returns <tt>true</tt> if <tt>next</tt> would return an element rather than throwing an exception.) |
public ElixirEffect addAttributeModifier(IAttribute attribute,String uuid,double modifier,int operation){
if (this.potionEffect != null) {
this.potionEffect.registerPotionAttributeModifier(attribute,uuid,modifier,operation);
}
else {
this.elixirAttributeModifiers.add(new ElixirAttributeModifier(attribute,uuid,modifier,operation));
}
return this;
}
| Adds an entity attribute modifier that is applied when the potion is active. |
public Builder title(String title){
event.title=title;
return this;
}
| Sets event title |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.