code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public boolean isValid(int timeout) throws SQLException {
synchronized (getConnectionMutex()) {
if (isClosed()) {
return false;
}
try {
try {
pingInternal(false,timeout * 1000);
}
catch ( Throwable t) {
try {
abortInternal();
}
catch ( Throwable ignoreThrown) {
}
return false;
}
}
catch ( Throwable t) {
return false;
}
return true;
}
}
| Returns true if the connection has not been closed and is still valid. The driver shall submit a query on the connection or use some other mechanism that positively verifies the connection is still valid when this method is called. <p> The query submitted by the driver to validate the connection shall be executed in the context of the current transaction. |
public span(String value){
addElement(value);
}
| Use the set* methods to set the values of the attributes. |
@Deprecated public void addImmutableType(final Class<?> type){
addImmutableType(type,true);
}
| Add immutable types. The value of the instances of these types will always be written into the stream even if they appear multiple times. However, references are still supported at deserialization time. |
public boolean equals(XObject obj2){
try {
return m_val == obj2.bool();
}
catch ( javax.xml.transform.TransformerException te) {
throw new org.apache.xml.utils.WrappedRuntimeException(te);
}
}
| Tell if two objects are functionally equal. |
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 ActionForward executeAction(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response){
Sesion oSesion=AutenticacionAdministracion.obtenerDatosEntidad(request);
SesionAdministracion poSesion=new SesionAdministracion();
poSesion.setIdEntidad(oSesion.getIdEntidad());
poSesion.setIdSesion(oSesion.getIdSesion());
poSesion.setIdUsuario(oSesion.getUsuario());
request.getSession().setAttribute(ConstantesSesionAdmin.ID_SESION_ADMINISTRACION,poSesion);
return mapping.findForward(SUCCESS_FORWARD);
}
| Method execute |
private ParamBinder obtainJobParamBinder(String classQualifiedName,String context){
return paramBinderCache.getBinderForClassNameAndContext(classQualifiedName,context);
}
| We could end up not finding the binder or having problems to access or instantiate it. Even if it should not be possible to happen, we are going to catch the exceptions and propagate it to the final user. |
@SuppressWarnings("unchecked") public <R>SimpleReactStream<R> from(final Collection<R> collection){
return from(collection.stream());
}
| Start a reactive flow from a Collection using an Iterator |
public void write(@WillClose OutputStream out) throws IOException {
Properties props=new SortedProperties();
for (int i=0; i < recentProjectsList.size(); i++) {
String projectName=recentProjectsList.get(i);
String key="recent" + i;
props.put(key,projectName);
}
Iterator<Entry<String,Boolean>> it=detectorEnablementMap.entrySet().iterator();
while (it.hasNext()) {
Entry<String,Boolean> entry=it.next();
props.put("detector" + entry.getKey(),entry.getKey() + BOOL_SEPARATOR + String.valueOf(entry.getValue().booleanValue()));
}
props.put(FILTER_SETTINGS_KEY,filterSettings.toEncodedString());
props.put(FILTER_SETTINGS2_KEY,filterSettings.hiddenToEncodedString());
props.put(DETECTOR_THRESHOLD_KEY,String.valueOf(filterSettings.getMinPriorityAsInt()));
props.put(RUN_AT_FULL_BUILD,String.valueOf(runAtFullBuild));
props.setProperty(EFFORT_KEY,effort);
if (cloudId != null) {
props.setProperty(CLOUD_ID_KEY,cloudId);
}
writeProperties(props,KEY_INCLUDE_FILTER,includeFilterFiles);
writeProperties(props,KEY_EXCLUDE_FILTER,excludeFilterFiles);
writeProperties(props,KEY_EXCLUDE_BUGS,excludeBugsFiles);
writeProperties(props,KEY_PLUGIN,customPlugins);
OutputStream prefStream=null;
try {
prefStream=new BufferedOutputStream(out);
props.store(prefStream,"FindBugs User Preferences");
prefStream.flush();
}
finally {
try {
if (prefStream != null) {
prefStream.close();
}
}
catch ( IOException ioe) {
}
}
}
| Write UserPreferences to given OutputStream. The OutputStream is guaranteed to be closed by this method. |
private boolean isIndexedType(Class<?> raw){
return raw.isArray() || Collection.class.isAssignableFrom(raw) || Map.class.isAssignableFrom(raw);
}
| Helper method used to distinguish structured type, which with JAXB use different rules for defining content types. |
public static <T>Set<T> randomSample(List<T> items,int m){
if (items.size() <= m) {
return new HashSet<>(items);
}
Random rnd=new Random(100);
HashSet<T> res=new HashSet<>(m);
int n=items.size();
for (int i=n - m; i < n; i++) {
int pos=rnd.nextInt(i + 1);
T item=items.get(pos);
if (res.contains(item)) res.add(items.get(i));
else res.add(item);
}
return res;
}
| get a random sample from the given points |
public SolrCore(String name,CoreDescriptor cd){
coreDescriptor=cd;
this.setName(name);
this.schema=null;
this.dataDir=null;
this.solrConfig=null;
this.startTime=System.currentTimeMillis();
this.maxWarmingSearchers=2;
this.resourceLoader=null;
this.updateHandler=null;
this.isReloaded=true;
this.reqHandlers=null;
this.searchComponents=null;
this.updateProcessorChains=null;
this.infoRegistry=null;
this.codec=null;
this.ruleExpiryLock=null;
solrCoreState=null;
}
| Creates a new core that is to be loaded lazily. i.e. lazyLoad="true" in solr.xml |
public void flush() throws IOException {
out.flush();
}
| Flushes this output stream and forces any buffered output bytes to be written out to the stream. <p> The <code>flush</code> method of <code>FilterOutputStream</code> calls the <code>flush</code> method of its underlying output stream. |
public static AsymmetricCipherKeyPair generateUserID(){
return generateDHKeyPair();
}
| Generates a user's long-term ID, which potentially has two parts (public/private). |
public static String removeNotation(String name){
if (name.matches("^m[A-Z]{1}")) {
return name.substring(1,2).toLowerCase();
}
else if (name.matches("m[A-Z]{1}.*")) {
return name.substring(1,2).toLowerCase() + name.substring(2);
}
return name;
}
| Get the name of the field removing hungarian notation |
final int findFreePages(int pages){
starting_page_search: for (int i=0; i < NUM_PAGES; i++) {
if (getPage(i) == null) {
int start=i;
int end=i + pages;
for (; i <= end; i++) {
if (getPage(i) != null) {
continue starting_page_search;
}
}
return start << OFFSET_BITS;
}
}
throw new Error("No mappable consecutive pages found for an anonymous map of size" + (pages * PAGE_SIZE));
}
| Find free consecutive pages |
public List<List<Integer>> toFinalList(){
final List<List<Integer>> alignment=new ArrayList<>(trgPoints.size());
if (trgPoints.isEmpty()) {
return alignment;
}
final ListIterator<AlignedSourceTokens> it=trgPoints.listIterator();
it.next();
while (it.hasNext()) {
final AlignedSourceTokens alignedSourceTokens=it.next();
if (it.hasNext()) {
final List<Integer> newAlignedSourceTokens=new ArrayList<>();
for ( Integer sourceIndex : alignedSourceTokens) {
newAlignedSourceTokens.add(sourceIndex - 1);
}
alignment.add(newAlignedSourceTokens);
}
}
return alignment;
}
| builds the final alignment list. each entry in the list corresponds to a list of aligned source tokens. First and last item in trgPoints is skipped. |
protected void tryToPrepare(){
if (this.surfaceIsReady && this.videoIsReady) {
if (this.mediaPlayer != null) {
this.initialMovieWidth=this.mediaPlayer.getVideoWidth();
this.initialMovieHeight=this.mediaPlayer.getVideoHeight();
}
resize();
stopLoading();
currentState=State.PREPARED;
if (shouldAutoplay) start();
if (this.preparedListener != null) this.preparedListener.onPrepared(mediaPlayer);
}
}
| Try to call state PREPARED Only if SurfaceView is already created and MediaPlayer is prepared Video is loaded and is ok to play. |
public static void lockdown(){
locked=true;
}
| Locks down the error consumer and prevents any further changes to the handler. |
public static void printArrayOfBigInts(InputStream in) throws IOException {
BigInt[] A=ByteUtils.readSizeArrayOfSizeBigInts(in);
for (int i=0; i < A.length; i++) {
ToolIO.out.println(A[i]);
}
}
| Print array of big integers read from a input stream |
public void addHouseNumber(HouseNumber houseNumber){
if (houseNumber != null) {
SortedSet<HouseNumber> currentHouseNumbers=getHouseNumbers();
if (currentHouseNumbers == null) {
currentHouseNumbers=new TreeSet<HouseNumber>(houseNumberComparator);
}
currentHouseNumbers.add(houseNumber);
this.setHouseNumbers(currentHouseNumbers);
houseNumber.setStreet(this);
}
}
| Do a double set : add the house number to the current street and set this street as the street of the specified AlternateName |
private void validateSignatureReferences(XMLSignature xmlSignature,DOMValidateContext valContext,Document document,Node timestampNode) throws XMLSignatureException {
assert xmlSignature != null;
assert valContext != null;
assert document != null;
assert timestampNode != null;
Node soapBody=getSoapBody(document);
Node wsTrustNode=getWsTrustNode(soapBody);
boolean foundTimestampElement=false;
boolean foundBodyOrWSTrustElement=false;
List<Reference> references=xmlSignature.getSignedInfo().getReferences();
if ((references == null) || (references.size() == 0)) {
throw new XMLSignatureException("Signature's SignInfo does not contain any references.");
}
for ( Reference reference : references) {
if (reference != null) {
validateReferenceTransforms(reference);
validateReferenceUri(reference);
if (!reference.validate(valContext)) {
throw new XMLSignatureException(String.format("Signature reference '%s' is invalid.",reference.getURI()));
}
if (!foundTimestampElement || !foundBodyOrWSTrustElement) {
String id=org.jcp.xml.dsig.internal.dom.Utils.parseIdFromSameDocumentURI(reference.getURI());
Node referencedNode=document.getElementById(id);
foundTimestampElement=(foundTimestampElement) || (timestampNode.isSameNode(referencedNode));
foundBodyOrWSTrustElement=(foundBodyOrWSTrustElement) || (soapBody.isSameNode(referencedNode)) || (wsTrustNode.isSameNode(referencedNode));
}
}
}
if (!foundTimestampElement || !foundBodyOrWSTrustElement) {
throw new XMLSignatureException("Signature must include <wsu:Timestamp> and either SoapBody, or the WSTrust element within it.");
}
}
| Validate references present in the XmlSignature. |
public void writeData(DataOutput dout) throws IOException {
dout.write(getMessage());
}
| writeData -- output the completed Modbus message to dout |
@DSComment("not sensitive") @DSSafe(DSCat.SAFE_OTHERS) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:56:40.790 -0500",hash_original_method="B09EB233D31BD7460B333EC44F947FB5",hash_generated_method="E7CB9BC1806291A715CC7DD98DB83FD9") @Override public void close() throws IOException {
synchronized (lock) {
if (!isClosed()) {
in.close();
buf=null;
}
}
}
| Closes this reader. This implementation closes the buffered source reader and releases the buffer. Nothing is done if this reader has already been closed. |
private long calculateLastCompleted(long index){
long lastCompleted=index;
for ( ServerSessionContext session : executor.context().sessions().sessions.values()) {
lastCompleted=Math.min(lastCompleted,session.getLastCompleted());
}
return lastCompleted;
}
| Calculates the last completed session event index. |
@POST @Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON}) @Path("/{id}/register") @CheckPermission(roles={Role.SYSTEM_ADMIN,Role.RESTRICTED_SYSTEM_ADMIN}) public StorageSystemRestRep registerStorageSystem(@PathParam("id") URI id) throws ControllerException {
ArgValidator.checkFieldUriType(id,StorageSystem.class,"id");
StorageSystem storageSystem=_dbClient.queryObject(StorageSystem.class,id);
ArgValidator.checkEntity(storageSystem,id,isIdEmbeddedInURL(id));
if (RegistrationStatus.UNREGISTERED.toString().equalsIgnoreCase(storageSystem.getRegistrationStatus())) {
storageSystem.setRegistrationStatus(RegistrationStatus.REGISTERED.toString());
_dbClient.persistObject(storageSystem);
startStorageSystem(storageSystem);
auditOp(OperationTypeEnum.REGISTER_STORAGE_SYSTEM,true,null,storageSystem.getId().toString(),id.toString());
}
URIQueryResultList storagePoolURIs=new URIQueryResultList();
_dbClient.queryByConstraint(ContainmentConstraint.Factory.getStorageDeviceStoragePoolConstraint(id),storagePoolURIs);
Iterator<URI> storagePoolIter=storagePoolURIs.iterator();
List<StoragePool> registeredPools=new ArrayList<StoragePool>();
while (storagePoolIter.hasNext()) {
StoragePool pool=_dbClient.queryObject(StoragePool.class,storagePoolIter.next());
if (pool.getInactive() || DiscoveredDataObject.RegistrationStatus.REGISTERED.toString().equals(pool.getRegistrationStatus())) {
continue;
}
registerStoragePool(pool);
registeredPools.add(pool);
}
URIQueryResultList storagePortURIs=new URIQueryResultList();
_dbClient.queryByConstraint(ContainmentConstraint.Factory.getStorageDeviceStoragePortConstraint(id),storagePortURIs);
Iterator<URI> storagePortIter=storagePortURIs.iterator();
while (storagePortIter.hasNext()) {
StoragePort port=_dbClient.queryObject(StoragePort.class,storagePortIter.next());
if (port.getInactive() || DiscoveredDataObject.RegistrationStatus.REGISTERED.toString().equals(port.getRegistrationStatus())) {
continue;
}
registerStoragePort(port);
}
StringBuffer errorMessage=new StringBuffer();
ImplicitPoolMatcher.matchModifiedStoragePoolsWithAllVirtualPool(registeredPools,_dbClient,_coordinator,errorMessage);
return map(storageSystem);
}
| Allows the user register the storage system with the passed id. |
public AnnotationResizeHelper(final WorkflowAnnotation resized,final ResizeDirection direction,final Point origin){
if (resized == null) {
throw new IllegalArgumentException("resized must not be null!");
}
if (origin == null) {
throw new IllegalArgumentException("origin must not be null!");
}
this.resized=resized;
this.direction=direction;
this.origin=origin;
}
| Creates a new resize helper which keeps track of the resizing state. |
@Override public Object eGet(int featureID,boolean resolve,boolean coreType){
switch (featureID) {
case RegularExpressionPackage.LOOK_AHEAD__NOT:
return isNot();
case RegularExpressionPackage.LOOK_AHEAD__PATTERN:
return getPattern();
}
return super.eGet(featureID,resolve,coreType);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public static void max(TextField campo,int maxLength){
campo.textProperty().addListener(null);
}
| Limitar o quantidade de caractres do campo de texto |
public static Class<?> lookupClass(String className){
ClassLoader loader=Util.getCurrentLoader(null);
if (loader == null) {
return null;
}
return getMetaData(loader,className).lookupClass();
}
| <p>Obtain a <code>Class</code> instance based on the provided String name.</p> |
private IElementUpdater findElementUpdater(String commandId){
if (IWorkbenchCommandConstants.FILE_EXPORT.equals(commandId)) {
return new WizardHandler.Export();
}
else if (IWorkbenchCommandConstants.FILE_IMPORT.equals(commandId)) {
return new WizardHandler.Import();
}
return null;
}
| Finds an element updater that knows how to decorate UI elements like the real handler of the command. |
public static FeatureSet of(final Feature... features){
return new FeatureSet(ImmutableSet.copyOf(features),ImmutableSet.of());
}
| Create a new feature set with the given features enabled. |
public boolean isMulticastEnabled(){
return multicastEnabled;
}
| Returns whether multicast communication is enabled for the Region. |
void informReferenceChange(ReferenceEvent e){
for ( INodeChangeListener listener : nodeChangeListeners) {
listener.informReferenceChange(e);
}
}
| Inform the registered listeners about changes to the class reference structure. Note that this method is synchronized. As it is ensured that only one thread can actively change the structure this synchronization does not really hinder us. But is provides an additional level of safety as the indexers can assume that they are only called single threaded for sure. |
public static AnnotationPart unmap(AnnotationDesc node){
List<AnnotationPart> list=unmapAnnotations(new ArrayList<AnnotationDesc>(Collections.singletonList(node)));
return list.get(0);
}
| Unmap annotation. |
public void rotate(float angle,int pivotX,int pivotY){
impl.rotate(nativeGraphics,angle,pivotX,pivotY);
}
| Rotates the coordinate system around a radian angle using the affine transform |
public boolean isNeedClientAuth(){
return needClientAuth;
}
| Returns <tt>true</tt> if the engine will <em>require</em> client authentication. This option is only useful to engines in the server mode. |
public AppCardBuilder iPhoneId(String appIPhoneId){
this.appIPhoneId=appIPhoneId;
return this;
}
| Sets the Apple App Store id for the promoted iOS app shown on iOS displays. |
private String createStyleDefinition(){
int fontSize=getFont().getSize() + 2;
return "<style type=\"text/css\">body {font-family:" + fontName + "; font-size:"+ fontSize+ "; margin:12px} p {margin:4px 0px} a {color:#a00000} li, ul {margin-left:10px}</style>";
}
| StyleSheet for the scroll html areas. Margins are needed to avoid drawing over the scroll borders. |
public DOMWriter(Writer output){
super(output);
}
| Creates a new DOM writer on the given output writer. |
protected static void println(String msg){
System.out.println(msg);
}
| Print a message to stdout with trailing new line character. |
@Override public Enumeration<Option> listOptions(){
Vector<Option> result=new Vector<Option>();
result.addElement(new Option("\tThe max size of the Ngram (default = 3).","max",1,"-max <int>"));
result.addElement(new Option("\tThe min size of the Ngram (default = 1).","min",1,"-min <int>"));
result.addAll(Collections.list(super.listOptions()));
return result.elements();
}
| Returns an enumeration of all the available options.. |
public static void register(){
RxJavaPlugins instance=RxJavaPlugins.getInstance();
if (!(instance.getErrorHandler() instanceof RethrowerJavaErrorHandler)) {
unregister();
instance.registerErrorHandler(new RethrowerJavaErrorHandler());
}
}
| Registers an error handler to allow for errors to crash the tests since Espresso execution seems to prevent it from crashing. |
public static void assignToCatalogEntry(DataService mgr,Category category,CatalogEntry ce) throws ObjectNotFoundException, NonUniqueBusinessKeyException {
CategoryToCatalogEntry cc=new CategoryToCatalogEntry();
cc.setCatalogEntry(ce);
cc.setCategory(mgr.getReference(Category.class,category.getKey()));
mgr.persist(cc);
}
| Assign a category to an existing catalog entry. |
public boolean isCreateSingleOrder(){
Object oo=get_Value(COLUMNNAME_IsCreateSingleOrder);
if (oo != null) {
if (oo instanceof Boolean) return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
| Get Create Single Order. |
public Object runSafely(Catbert.FastStack stack) throws Exception {
String[] tzids=java.util.TimeZone.getAvailableIDs();
java.util.Vector rv=new java.util.Vector();
java.util.TimeZone lastTZ=null;
String lastTZStr="";
for (int i=0; i < tzids.length; i++) {
java.util.TimeZone tz=java.util.TimeZone.getTimeZone(tzids[i]);
if (lastTZ == null || !lastTZ.hasSameRules(tz)) {
if (lastTZ != null) {
lastTZStr+=")";
rv.add(lastTZStr);
}
lastTZ=tz;
lastTZStr=tz.getDisplayName(true,java.util.TimeZone.SHORT,Sage.userLocale) + " " + tz.getDisplayName(Sage.userLocale)+ " ("+ tzids[i];
}
else {
lastTZStr+=", " + tzids[i];
}
}
rv.add(lastTZStr + ")");
return rv;
}
| Gets the list of all of the valid time zone names |
public void resetWithEmpty(){
_inputStart=-1;
_currentSize=0;
_inputLen=0;
_inputBuffer=null;
_resultString=null;
_resultArray=null;
if (_hasSegments) {
clearSegments();
}
}
| Method called to clear out any content text buffer may have, and initializes buffer to use non-shared data. |
public NumericPrediction(double actual,double predicted,double weight,double[][] predInt){
m_Actual=actual;
m_Predicted=predicted;
m_Weight=weight;
setPredictionIntervals(predInt);
}
| Creates the NumericPrediction object. |
private String serializeColorMap(){
String output="";
for ( Map.Entry<String,BiomeColorJson> pairs : getSortedColorMapEntries()) {
output+="[ \"" + pairs.getKey() + "\", { ";
output+="\"r\":" + pairs.getValue().getR() + ", ";
output+="\"g\":" + pairs.getValue().getG() + ", ";
output+="\"b\":" + pairs.getValue().getB() + " } ],\r\n";
}
return output.substring(0,output.length() - 3);
}
| This method uses the sorted color map, so the serialization will have a reproducible order. |
public static TermsQueryBuilder termsQuery(String name,Object... values){
return new TermsQueryBuilder(name,values);
}
| A filer for a field based on several terms matching on any of them. |
public void configure(){
this.getSystemConnectionMemo().getSprogTrafficController().connectPort(this);
this.getSystemConnectionMemo().configureCommandStation();
this.getSystemConnectionMemo().configureManagers();
if (this.getSystemConnectionMemo().getSprogMode() == SprogMode.OPS) {
jmri.jmrix.sprog.ActiveFlagCS.setActive();
}
else {
jmri.jmrix.sprog.ActiveFlag.setActive();
}
if (getOptionState("TrackPowerState") != null && getOptionState("TrackPowerState").equals("Powered On")) {
try {
this.getSystemConnectionMemo().getPowerManager().setPower(jmri.PowerManager.ON);
}
catch ( jmri.JmriException e) {
log.error(e.toString());
}
}
}
| set up all of the other objects to operate with an Sprog command station connected to this port |
private AdvertiseData buildAdvertiseData(){
AdvertiseData.Builder dataBuilder=new AdvertiseData.Builder();
dataBuilder.addServiceUuid(Constants.Service_UUID);
dataBuilder.setIncludeDeviceName(true);
return dataBuilder.build();
}
| Returns an AdvertiseData object which includes the Service UUID and Device Name. |
public ConfiguratorDescriptor(final String className){
this.className=className;
}
| Create a zone configurator descriptor. |
long readObjectRef(){
return readID(vm.sizeofObjectRef);
}
| Read object represented as vm specific byte sequence. |
@Override public void visitClass(PsiClass psiClass){
if (!EndpointUtilities.isEndpointClass(psiClass)) {
return;
}
PsiMethod[] allMethods=psiClass.getMethods();
Map<String,PsiMethod> javaMethodNames=Maps.newHashMap();
for ( PsiMethod psiMethod : allMethods) {
validateBackendMethodNameUnique(psiMethod,javaMethodNames);
}
}
| Flags methods that have a duplicate full java name. |
public boolean isHalfSupported(){
return hasExtension("cl_khr_fp16");
}
| Whether this device supports the <a href="http://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/cl_khr_fp16.html">cl_khr_fp16 extension</a>. |
private void ensureFreq() throws IOException {
int currentDoc=docID();
if (lastScoredDoc != currentDoc) {
setFreqCurrentDoc();
lastScoredDoc=currentDoc;
}
}
| Ensure setFreqCurrentDoc is called, if not already called for the current doc. |
public String toString(){
return "Analysis for " + Utils.doubleToString(count,0) + " points:\n"+ " "+ " Column 1"+ " Column 2"+ " Difference\n"+ "Minimums "+ Utils.doubleToString(xStats.min,17,4)+ Utils.doubleToString(yStats.min,17,4)+ Utils.doubleToString(differencesStats.min,17,4)+ '\n'+ "Maximums "+ Utils.doubleToString(xStats.max,17,4)+ Utils.doubleToString(yStats.max,17,4)+ Utils.doubleToString(differencesStats.max,17,4)+ '\n'+ "Sums "+ Utils.doubleToString(xStats.sum,17,4)+ Utils.doubleToString(yStats.sum,17,4)+ Utils.doubleToString(differencesStats.sum,17,4)+ '\n'+ "SumSquares "+ Utils.doubleToString(xStats.sumSq,17,4)+ Utils.doubleToString(yStats.sumSq,17,4)+ Utils.doubleToString(differencesStats.sumSq,17,4)+ '\n'+ "Means "+ Utils.doubleToString(xStats.mean,17,4)+ Utils.doubleToString(yStats.mean,17,4)+ Utils.doubleToString(differencesStats.mean,17,4)+ '\n'+ "SDs "+ Utils.doubleToString(xStats.stdDev,17,4)+ Utils.doubleToString(yStats.stdDev,17,4)+ Utils.doubleToString(differencesStats.stdDev,17,4)+ '\n'+ "Prob(differences) "+ Utils.doubleToString(differencesProbability,4)+ " (sigflag "+ differencesSignificance+ ")\n"+ "Correlation "+ Utils.doubleToString(correlation,4)+ "\n";
}
| Returns statistics on the paired comparison. |
public void test_ticket_1105_quads_select1() throws Exception {
new TestHelper("ticket_1105_quads_select1","ticket_1105_select1.rq","ticket_1105.trig","ticket_1105.srx").runTest();
}
| Query: <code> SELECT ?s ?p ?o FROM NAMED <http://example/c> WHERE { ?s ?p ?o } </code> runs fine in quads mode. |
public void visitBooleanExpression(BooleanExpression expression){
controller.getCompileStack().pushBooleanExpression();
int mark=controller.getOperandStack().getStackLength();
Expression inner=expression.getExpression();
inner.visit(this);
controller.getOperandStack().castToBool(mark,true);
controller.getCompileStack().pop();
}
| return a primitive boolean value of the BooleanExpression. |
final public void startServer(int port) throws IOException {
serverSocket=new ServerSocket(port,50);
serverInstance=new Thread(this);
serverInstance.start();
}
| Start a server on port <i>port</i>. It will call serviceRequest() for each new connection. |
protected void onActionEnd(){
}
| Called once in the same tick when trigger was released. |
public static <K,V>MutableMap<K,V> rejectMapOnEntry(Map<K,V> map,Predicate2<? super K,? super V> predicate){
return MapIterate.rejectMapOnEntry(map,predicate,UnifiedMap.newMap());
}
| For each <em>value</em> of the map, predicate is evaluated with the element as the parameter. Each element which causes predicate to evaluate to false is included in the new collection. |
private void returnData(Object ret){
if (myHost != null) {
myHost.returnData(ret);
}
}
| Used to communicate a return object from a plugin tool to the main Whitebox user-interface. |
private void returnData(Object ret){
if (myHost != null) {
myHost.returnData(ret);
}
}
| Used to communicate a return object from a plugin tool to the main Whitebox user-interface. |
public Envelope boundary(){
minXEnvelope=this.rawPolygonRDD.min((PolygonXMinComparator)GeometryComparatorFactory.createComparator("polygon","x","min")).getEnvelopeInternal();
Double minLongitude=minXEnvelope.getMinX();
maxXEnvelope=this.rawPolygonRDD.max((PolygonXMaxComparator)GeometryComparatorFactory.createComparator("polygon","x","max")).getEnvelopeInternal();
Double maxLongitude=maxXEnvelope.getMaxX();
minYEnvelope=this.rawPolygonRDD.min((PolygonYMinComparator)GeometryComparatorFactory.createComparator("polygon","y","min")).getEnvelopeInternal();
Double minLatitude=minYEnvelope.getMinY();
maxYEnvelope=this.rawPolygonRDD.max((PolygonYMaxComparator)GeometryComparatorFactory.createComparator("polygon","y","max")).getEnvelopeInternal();
Double maxLatitude=maxYEnvelope.getMaxY();
this.boundary[0]=minLongitude;
this.boundary[1]=minLatitude;
this.boundary[2]=maxLongitude;
this.boundary[3]=maxLatitude;
this.boundaryEnvelope=new Envelope(boundary[0],boundary[2],boundary[1],boundary[3]);
return new Envelope(boundary[0],boundary[2],boundary[1],boundary[3]);
}
| Return the boundary of the entire SpatialRDD in terms of an envelope format |
public WebSocketImpl(URI location,Map<String,WebSocketExtensionFactorySpi> extensionFactories) throws URISyntaxException {
this(location,extensionFactories,HttpRedirectPolicy.ALWAYS,null,null,new HashMap<String,WsExtensionParameterValuesSpiImpl>(),null,0);
}
| Creates a WebSocket that opens up a full-duplex connection to the target location on a supported WebSocket provider. Call connect() to establish the location after adding event listeners. |
public static void addPurificationChamberRecipe(ItemStack input,ItemStack output){
try {
Class recipeClass=Class.forName("mekanism.common.recipe.RecipeHandler");
Method m=recipeClass.getMethod("addPurificationChamberRecipe",ItemStack.class,ItemStack.class);
m.invoke(null,input,output);
}
catch ( Exception e) {
System.err.println("Error while adding recipe: " + e.getMessage());
}
}
| Add a Purification Chamber recipe. |
public static PartnerBookmarksProviderIterator createIfAvailable(ContentResolver contentResolver){
Cursor cursor=contentResolver.query(BOOKMARKS_CONTENT_URI,BOOKMARKS_PROJECTION,null,null,BOOKMARKS_SORT_ORDER);
if (cursor == null) return null;
return new PartnerBookmarksProviderIterator(cursor);
}
| Creates the bookmarks iterator if possible. |
public View findViewById(int id){
View v;
if (mSlidingMenu != null) {
v=mSlidingMenu.findViewById(id);
if (v != null) return v;
}
return null;
}
| Finds a view that was identified by the id attribute from the XML that was processed in onCreate(Bundle). |
public boolean expectPassed(){
for (int i=0; i < TEST_NUM_EXPECTS; i++) {
if (expects[i] == true) {
return false;
}
}
for (int i=0; i < TEST_NUM_EXPECTS; i++) {
if (eventsReceived[i] && notExpecting[i]) {
return false;
}
}
return true;
}
| Test to see if current expectations match recieved information |
public void paintListBorder(SynthContext context,Graphics g,int x,int y,int w,int h){
paintBorder(context,g,x,y,w,h,null);
}
| Paints the border of a list. |
private void findAny(List<Trade> trades){
Optional<Trade> anyTrade=trades.stream().filter(null).findAny();
System.out.println("First trade (uisng findAny function): " + anyTrade.get());
}
| Method that demonstrates the findAny function |
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 static void main(String... args) throws Exception {
if (System.getProperty("boot.module.loader") == null) {
System.setProperty("boot.module.loader","org.wildfly.swarm.bootstrap.modules.BootModuleLoader");
}
Module bootstrap=Module.getBootModuleLoader().loadModule(ModuleIdentifier.create("swarm.application"));
ServiceLoader<ContainerFactory> factory=bootstrap.loadService(ContainerFactory.class);
Iterator<ContainerFactory> factoryIter=factory.iterator();
if (!factoryIter.hasNext()) {
simpleMain(args);
}
else {
factoryMain(factoryIter.next(),args);
}
}
| Main entry-point. |
public static String createTestPtTravelTimesAndDistancesCSVFile(){
String location=TempDirectoryUtil.createCustomTempDirectory("ptStopFileDir") + "/ptTravelInfo.csv";
BufferedWriter bw=IOUtils.getBufferedWriter(location);
try {
for (int origin=1; origin <= 4; origin++) {
for (int destination=1; destination <= 4; destination++) {
if (origin == destination) bw.write(origin + " " + destination+ " 0"+ org.matsim.contrib.matsim4urbansim.utils.InternalConstants.NEW_LINE);
else bw.write(origin + " " + destination+ " 100"+ org.matsim.contrib.matsim4urbansim.utils.InternalConstants.NEW_LINE);
}
}
bw.flush();
bw.close();
}
catch ( Exception e) {
e.printStackTrace();
}
return location;
}
| This methods creates a csv file with informations about pt travel times and pt distances for the test network from createTestNetwork(). We set the pt travel time between all pairs of pt stops to 100 seconds, except pairs of same pt stops where the travel time is 0 seconds. We set the pt distance between all pairs of pt stops to 100 meter, except pairs of same pt stops where the distance is 0 meter. Because the data in the csv file does not need an entity, you can use the same csv file for both informations. |
private List<ValidationError> toErrors(final Map errors){
List<ValidationError> validationErrors;
validationErrors=new LinkedList<ValidationError>();
final Set<Entry> errorEntries=errors.entrySet();
for ( final Entry entry : errorEntries) validationErrors.add(new ValidationError(entry.getKey().toString(),entry.getValue().toString()));
return validationErrors;
}
| Converts a map of validation errors to a list of ValidationError objects assuming that key = error key and value = error message |
public void stop(){
advertiser.stop();
webHandler.stop();
started=false;
}
| Stops advertising and handling the Homekit accessories. |
public Card popCard(){
int i=size() - 1;
return popCard(i);
}
| Removes and returns the last card. |
private void createAttachMenuBar(){
JMenuBar bar=new JMenuBar();
JMenu fileMenu=new JMenu("File");
for ( Action action : actionManager.getOpenSavePlotActions()) {
fileMenu.add(action);
}
fileMenu.addSeparator();
fileMenu.add(new CloseAction(this.getWorkspaceComponent()));
JMenu editMenu=new JMenu("Edit");
editMenu.add(new JMenuItem(TimeSeriesPlotActions.getPropertiesDialogAction(timeSeriesPanel)));
JMenu helpMenu=new JMenu("Help");
ShowHelpAction helpAction=new ShowHelpAction("Pages/Plot/time_series.html");
JMenuItem helpItem=new JMenuItem(helpAction);
helpMenu.add(helpItem);
bar.add(fileMenu);
bar.add(editMenu);
bar.add(helpMenu);
getParentFrame().setJMenuBar(bar);
}
| Creates the menu bar. |
protected void drawWithOffset(float zone,int pointsRight,int pointsLeft,float fixedPoints,Canvas canvas,Paint paint){
int position=getPositionForZone(zone);
int firstPosition=(int)(position - pointsLeft - fixedPoints);
int lastPosition=(int)(position + pointsRight + fixedPoints);
if (lastPosition > pointsNumber - 1 && lastPosition != pointsNumber) {
int offset=lastPosition - pointsNumber - 1;
float[] pointsF=getArrayFloat(points.subList(0,offset));
lastPosition=pointsNumber - 1;
canvas.drawPoints(pointsF,paint);
}
if (firstPosition < 0) {
int offset=Math.abs(firstPosition);
float[] pointsF=getArrayFloat(points.subList((pointsNumber - 1) - offset,pointsNumber - 1));
canvas.drawPoints(pointsF,paint);
firstPosition=0;
}
float[] pointsF=getArrayFloat(points.subList(firstPosition,lastPosition));
canvas.drawPoints(pointsF,paint);
}
| Paint a line with a offset for right and left |
synchronized protected void timeout(){
JOptionPane.showMessageDialog(null,"Timeout talking to SPROG","Timeout",JOptionPane.ERROR_MESSAGE);
state=State.IDLE;
}
| Internal routine to handle a timeout |
@Beta public static <K,V>ImmutableSortedMap<K,V> copyOf(Iterable<? extends Entry<? extends K,? extends V>> entries){
@SuppressWarnings("unchecked") Ordering<K> naturalOrder=(Ordering<K>)NATURAL_ORDER;
return copyOf(entries,naturalOrder);
}
| Returns an immutable map containing the given entries, with keys sorted by the provided comparator. <p>This method is not type-safe, as it may be called on a map with keys that are not mutually comparable. |
private void registerHook(final String requestUrl,final String target,String[] methods,Integer expireTime,int resourceExpireTime){
String body="{ \"destination\":\"" + target + "\"";
String m=null;
if (methods != null) {
for ( String method : methods) {
m+="\"" + method + "\", ";
}
m=m.endsWith(", ") ? m.substring(0,m.lastIndexOf(",")) : m;
m="\"methods\": [" + m + "]";
}
body+=expireTime != null ? ", \"expireTime\" : " + expireTime : "";
body=body + "}";
with().body(body).header("x-expire-after",String.valueOf(resourceExpireTime)).put(requestUrl).then().assertThat().statusCode(200);
}
| Registers a hook. |
public synchronized void unhidePieces(){
for (int i=0; i < 8; i++) {
for (int j=0; j < 8; j++) {
squares[i][j].setHidingPiece(false);
}
}
for ( PieceJailChessSquare pieceJailSquare : pieceJailSquares) {
if (pieceJailSquare != null) {
pieceJailSquare.setHidingPiece(false);
}
}
}
| Unhides the pieces on all of the squares. |
public void printOptions(PrintWriter pw,int width,Options options,int leftPad,int descPad){
StringBuffer sb=new StringBuffer();
renderOptions(sb,width,options,leftPad,descPad);
pw.println(sb.toString());
}
| <p>Print the help for the specified Options to the specified writer, using the specified width, left padding and description padding.</p> |
private ConstCollector(SsaMethod ssaMethod){
this.ssaMeth=ssaMethod;
}
| Constructs an instance. |
private void fireObjectRemoved(Binding oldBd,long changeID){
if (namingListeners == null || namingListeners.size() == 0) return;
NamingEvent e=new NamingEvent(eventSrc,NamingEvent.OBJECT_REMOVED,null,oldBd,new Long(changeID));
support.queueEvent(e,namingListeners);
}
| Fire an "object removed" event to registered NamingListeners. |
public void testDoConfigureSetsDomainVersion() throws Exception {
configuration.setProperty(WebLogicPropertySet.DOMAIN_VERSION,DOMAIN_VERSION);
configuration.doConfigure(container);
String config=configuration.getFileHandler().readTextFile(DOMAIN_HOME + "/config/config.xml","UTF-8");
XMLAssert.assertXpathEvaluatesTo(DOMAIN_VERSION,"//weblogic:domain-version",config);
}
| Test changing domain version. |
public ByteBuffer buildPacket(int encap,short destUdp,short srcUdp){
ByteBuffer result=ByteBuffer.allocate(MAX_LENGTH);
InetAddress destIp=mClientIp;
InetAddress srcIp=mYourIp;
fillInPacket(encap,destIp,srcIp,destUdp,srcUdp,result,DHCP_BOOTREPLY,mBroadcast);
result.flip();
return result;
}
| Fills in a packet with the requested NAK attributes. |
public final CC sizeGroupY(String s){
ver.setSizeGroup(s);
return this;
}
| The size group that this component should be placed in. <p> For a more thorough explanation of what this constraint does see the white paper or cheat Sheet at www.migcomponents.com. |
@Override protected void entryRemoved(boolean evicted,String key,BitmapDrawable oldValue,BitmapDrawable newValue){
if (RecyclingBitmapDrawable.class.isInstance(oldValue)) {
((RecyclingBitmapDrawable)oldValue).setIsCached(false);
}
else {
}
}
| Notify the removed entry that is no longer being cached |
public byte[] processPacket(byte[] in,int inOff,int inLen) throws IllegalStateException, InvalidCipherTextException {
byte[] output;
if (forEncryption) {
output=new byte[inLen + macSize];
}
else {
if (inLen < macSize) {
throw new InvalidCipherTextException("data too short");
}
output=new byte[inLen - macSize];
}
processPacket(in,inOff,inLen,output,0);
return output;
}
| Process a packet of data for either CCM decryption or encryption. |
public void copyFrom(P2Model other){
ius.addAll(other.ius);
repos.addAll(other.repos);
metadataRepos.addAll(other.metadataRepos);
artifactRepos.addAll(other.artifactRepos);
}
| Copies everything from the other model into this one. |
public JSONArray put(Object value){
this.myArrayList.add(value);
return this;
}
| Append an object value. This increases the array's length by one. |
public boolean isCurrentIgnoreSpace(String str){
if (!hasNext()) return false;
int start=getPos();
removeSpace();
boolean is=isCurrent(str);
setPos(start);
return is;
}
| Gibt zurueck ob das naechste Zeichen das selbe ist wie das Eingegebene. |
public final char yycharat(int pos){
return zzBuffer[zzStartRead + pos];
}
| Returns the character at position <tt>pos</tt> from the matched text. It is equivalent to yytext().charAt(pos), but faster |
public static double calculateJulianDate(GregorianCalendar cal){
int year=cal.get(Calendar.YEAR);
int month=cal.get(Calendar.MONTH);
int day=cal.get(Calendar.DAY_OF_MONTH);
month++;
if ((month == 1) || (month == 2)) {
year-=1;
month+=12;
}
int A=year / 100;
int B=(int)(2 - A + (A / 4));
int C=(int)(365.25 * (float)year);
int D=(int)(30.6001 * (float)(month + 1));
double julianDate=(double)(B + C + D+ day) + 1720994.5;
return julianDate;
}
| Given a date from a gregorian calendar, give back a julian date. From Duffett-Smith, chapter 4. |
public static Declaration lookupMemberForBackend(List<Declaration> members,String name,Backends backends){
for ( Declaration dec : members) {
if (isResolvable(dec) && isNamed(name,dec)) {
Backends bs=dec.getNativeBackends();
if (bs.none()) {
return dec;
}
else if (backends.supports(bs)) {
return dec;
}
}
}
return null;
}
| Find the declaration with the given name that occurs in the list of members, taking into account the given backends, if any. Does not take into account Java overloading |
private void handleMobileCellScroll(){
mIsMobileScrolling=handleMobileCellScroll(mHoverCellCurrentBounds);
}
| Determines whether this listview is in a scrolling state invoked by the fact that the hover cell is out of the bounds of the listview; |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.