language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public ReshardingConfiguration withPreferredAvailabilityZones(String... preferredAvailabilityZones) { if (this.preferredAvailabilityZones == null) { setPreferredAvailabilityZones(new com.amazonaws.internal.SdkInternalList<String>(preferredAvailabilityZones.length)); } for (String ele...
java
private boolean isLogConfigurationMessage(Throwable ex) { if (ex instanceof InvocationTargetException) { return isLogConfigurationMessage(ex.getCause()); } String message = ex.getMessage(); if (message != null) { for (String candidate : LOG_CONFIGURATION_MESSAGES) { if (message.contains(candidate)) { ...
java
static <T> void bindDynamicProvider( Binder binder, Class<T> clazz, Class<? extends Annotation> annotation) { binder.getProvider(Key.get(clazz, annotation)); ParameterizedType type = Types.newParameterizedType(DynamicBindingProvider.class, clazz); DynamicBindingProvider<T> provider = new DynamicBindi...
java
public void process() { computeCovarince(); float eigenvalue = smallestEigenvalue(); // eigenvalue is the variance, convert to standard deviation double stdev = Math.sqrt(eigenvalue); // System.out.println("stdev "+stdev+" total "+norm.size()+" mean "+meanX+" "+meanY); // approximate the spread in by d...
java
protected void updatePerson(final LoginContext _login, final Person _person) throws EFapsException { for (final JAASSystem system : JAASSystem.getAllJAASSystems()) { final Set<?> users = _login.getSubject().getPrincipals(system.getPersonJAASPrincipleClass(...
python
def rbigint_to_string(obj): """ Recursively converts big integers (|>2**53-1|) to strings @obj: Any python object -> @obj, with any big integers converted to #str objects """ if isinstance(obj, (str, bytes)) or not obj: # the input is the desired one, return as is return ob...
java
public java.util.List<IpPermission> getIpPermissions() { if (ipPermissions == null) { ipPermissions = new com.amazonaws.internal.SdkInternalList<IpPermission>(); } return ipPermissions; }
java
private boolean locationInOutputDir(String location) { String expandedOutputLocation = cfgSvc.resolveString(LibertyConstants.DEFAULT_OUTPUT_LOCATION); return location.startsWith(LibertyConstants.DEFAULT_OUTPUT_LOCATION) || location.startsWith(expandedOutputLocation); }
python
def point_plane_distance(points, plane_normal, plane_origin=[0.0, 0.0, 0.0]): """ The minimum perpendicular distance of a point to a plane. Parameters ----------- points: (n, 3) float, points in space plane_normal: (3,) float, normal vecto...
java
@SuppressWarnings("unused") private static synchronized void setTimerClass(String name, Class<? extends HeartbeatTimer> timerClass) { if (timerClass == null) { sTimerClasses.remove(name); } else { sTimerClasses.put(name, timerClass); } }
python
def repository_blob(self, sha, **kwargs): """Return a file by blob SHA. Args: sha(str): ID of the blob **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabGetError: I...
python
def generate_highwire_json(highwire_elements): """Convert highwire elements into a JSON structure. Returns data as a JSON formatted string. """ highwire_dict = highwirepy2dict(highwire_elements) return json.dumps(highwire_dict, sort_keys=True, indent=4)
python
def main(**options): """Spline loc tool.""" application = Application(**options) # fails application when your defined threshold is higher than your ratio of com/loc. if not application.run(): sys.exit(1) return application
java
public Object getImageIcon(Object value) { int index = 0; if (value instanceof Integer) index = ((Integer)value).intValue(); else if (value != null) { try { index = Integer.parseInt(value.toString()); } catch (NumberFormatException ...
java
private void modifyDatastreamControlGroupAction(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String actionLabel = "modifying datastream control group"; Context context = ReadOnlyContext.getContext(Constants.HTTP_REQUEST.REST.uri, ...
java
public static boolean deepEquals(final Object a, final Object b) { if ((a == null) ? b == null : (b == null ? false : a.equals(b))) { return true; } if ((a != null) && (b != null) && a.getClass().isArray() && a.getClass().equals(b.getClass())) { return typeOf(a.get...
java
protected I_CmsSearchDocument appendType( I_CmsSearchDocument document, CmsObject cms, CmsResource resource, I_CmsExtractionResult extractionResult, List<CmsProperty> properties, List<CmsProperty> propertiesSearched) throws CmsLoaderException { // add the res...
java
public synchronized void pushAliasEntry(AliasEntry aliasEntry, DCache cache) { BatchUpdateList bul = getUpdateList(cache); bul.aliasEntryEvents.add(aliasEntry); }
python
def strip_project_url(url): """strip proto:// | openstack/ prefixes and .git | -distgit suffixes""" m = re.match(r'(?:[^:]+://)?(.*)', url) if m: url = m.group(1) if url.endswith('.git'): url, _, _ = url.rpartition('.') if url.endswith('-distgit'): url, _, _ = url.rpartition(...
python
def generate_object_graphs_by_class(classlist): """ Generate reference and backreference graphs for objects of type class for each class given in classlist. Useful for debugging reference leaks in framework etc. Usage example to generate graphs for class "someclass": >>> import someclass >>...
java
public void download(String path, String fileName, File outFile) { if (outFile.isDirectory()) { outFile = new File(outFile, fileName); } if (false == outFile.exists()) { FileUtil.touch(outFile); } try (OutputStream out = FileUtil.getOutputStream(outFile)) { download(path, fileName, out); }...
java
public static Intent newMapsIntent(String address, String placeTitle) { StringBuilder sb = new StringBuilder(); sb.append("geo:0,0?q="); String addressEncoded = Uri.encode(address); sb.append(addressEncoded); // pass text for the info window String titleEncoded = Uri.en...
java
public static TaskManager unregisterResource(Object resource) { if (resource == null) return null; synchronized (resources) { return resources.remove(resource); } }
java
public void flushTxLog() { synchronized (flushCompleteSignal) { BufferName enqueueBuffer; synchronized (txLogToVEBuf.getPot()) { // Enqueue the backup task enqueueBuffer = txLogToVEBuf.getEnqueueBuffer(); FlushNowJob flushJob = new FlushNo...
java
public void immediateDispatchTo(Object listener, Event event) { assert event != null; Iterable<BehaviorGuardEvaluator> behaviorGuardEvaluators = null; synchronized (this.behaviorGuardEvaluatorRegistry) { behaviorGuardEvaluators = AgentInternalEventsDispatcher.this.behaviorGuardEvaluatorRegistry .getBehavi...
python
def built(self): """Called just after this node is successfully built.""" # Clear the implicit dependency caches of any Nodes # waiting for this Node to be built. for parent in self.waiting_parents: parent.implicit = None self.clear() if self.pseudo: ...
java
protected void disableSessionDelivery() { bugsnag.setSessionDelivery(new Delivery() { @Override public void deliver(Serializer serializer, Object object, Map<String, String> headers) { // Do nothing } @Override public void close() { ...
java
@Override public ResponseCtx evaluate(RequestCtx reqCtx) throws PEPException { logger.debug("evaluating RequestCtx request"); return evaluate(new RequestCtx[]{reqCtx}); }
python
def get_value_as_list(self, dictionary, key): """Helper function to check and convert a value to list. Helper function to check and convert a value to json list. This helps the ribcl data to be generalized across the servers. :param dictionary: a dictionary to check in if key is presen...
python
def get(section, name): """ Wrapper around ConfigParser's ``get`` method. """ cfg = ConfigParser.SafeConfigParser({"working_dir": "/tmp", "debug": "0"}) cfg.read(CONFIG_LOCATIONS) val = cfg.get(section, name) return val.strip("'").strip('"')
python
def run(self): """ run the plugin """ dockerfile = df_parser(self.workflow.builder.df_path, workflow=self.workflow) lines = dockerfile.lines # when using final dockerfile, we should use DOCKERFILE_FILENAME # otherwise we should use the copied version if s...
python
def list_jobs(config, *, status=JobStatus.Active, filter_by_type=None, filter_by_worker=None): """ Return a list of Celery jobs. Args: config (Config): Reference to the configuration object from which the settings are retrieved. status (JobStatus): The status of the jo...
java
public static void logLoginException( CmsRequestContext requestContext, String userName, CmsException currentLoginException) { if (currentLoginException instanceof CmsAuthentificationException) { // the authentication of the user failed if (org.opencms.security....
java
private void writeDepsContent(Map<String, DependencyInfo> depsFiles, Map<String, DependencyInfo> jsFiles, PrintStream out) throws IOException { // Print all dependencies extracted from srcs. writeDepInfos(out, jsFiles.values()); // Print all dependencies extracted from deps. if (mergeStrate...
python
def delete(filething): """Remove tags from a file. Args: filething (filething) Raises: mutagen.MutagenError """ dsf_file = DSFFile(filething.fileobj) if dsf_file.dsd_chunk.offset_metdata_chunk != 0: id3_location = dsf_file.dsd_chunk.offset_metdata_chunk dsf_fil...
python
def get_object(self, request, object_id): """ Returns an instance matching the primary key provided. ``None`` is returned if no match is found (or the object_id failed validation against the primary key field). """ queryset = self.queryset(request) model = querys...
python
def _get_pkg_meta(self): """ Try to find package metadata. """ logger = logging.getLogger('pyrocore.scripts.base.version_info') pkg_info = None warnings = [] for info_ext, info_name in (('.dist-info', 'METADATA'), ('.egg-info', 'PKG-INFO')): try: ...
python
def __assert_less(expected, returned): ''' Test if a value is less than the returned value ''' result = "Pass" try: assert (expected < returned), "{0} not False".format(returned) except AssertionError as err: result = "Fail: " + six.text_type(err) ...
java
public static double[] columnStdDevs(RealMatrix matrix) { double[] retval = new double[matrix.getColumnDimension()]; for (int i = 0; i < retval.length; i++) { retval[i] = new DescriptiveStatistics(matrix.getColumn(i)).getStandardDeviation(); } return retval; }
python
def estimate_pos_and_err_parabolic(tsvals): """Solve for the position and uncertainty of source in one dimension assuming that you are near the maximum and the errors are parabolic Parameters ---------- tsvals : `~numpy.ndarray` The TS values at the maximum TS, and for each pixel on e...
python
def fetchEC2InstanceDict(regionNickname=None): """ Fetches EC2 instances types by region programmatically using the AWS pricing API. See: https://aws.amazon.com/blogs/aws/new-aws-price-list-api/ :return: A dict of InstanceType objects, where the key is the string: aws instance name (examp...
python
def init_ui(self): """Init game interface.""" board_width = self.ms_game.board_width board_height = self.ms_game.board_height self.create_grid(board_width, board_height) self.time = 0 self.timer = QtCore.QTimer() self.timer.timeout.connect(self.timing_game) ...
python
def cmdHISTORY(self, params): """ Display the command history """ cnt = 0 self.writeline('Command history\n') for line in self.history: cnt = cnt + 1 self.writeline("%-5d : %s" % (cnt, ''.join(line)))
java
@Override public UpdateLoadBalancerAttributeResult updateLoadBalancerAttribute(UpdateLoadBalancerAttributeRequest request) { request = beforeClientExecution(request); return executeUpdateLoadBalancerAttribute(request); }
python
def report_list(self, service_id=None, service_port=None, hostfilter=None): """ Returns a list of ports with IPs, banners and vulnerabilities (warning, slow!) :param service_id: t_services.id :param service_port: Port (tcp/#, udp/#, info/#) :param hostfilter: Valid hostfilter or...
python
def diff_speed(sw_dens=1.028, dens_gcm3=1.053, seal_length=300, seal_girth=200, Cd=0.09): '''Calculate terminal velocity of animal with a body size Args ---- sw_dens: float Density of seawater (g/cm^3) dens_gcm3: float Density of animal (g/cm^3) seal_length: float ...
java
private ModelNode populateModuleInfo(ModuleInfo module) throws Exception { ModelNode result = new ModelNode(); result.get("name").set(module.getName()); ModelNode value; value = result.get("main-class"); if (module.getMainClass() != null) { value.set(module.getMainCl...
java
@SuppressWarnings("unchecked") public void registerTransport(String transportClazz) { if(transportClazz == null){ return; } try { registerTransport((Class<Transport>)Class.forName(transportClazz)); } catch (ClassNotFoundException e) { return; } catch(ClassCastException cce){ throw new ApiTranspor...
java
protected Map<String, String> getElementAttributes() { // Preserve order of attributes Map<String, String> attrs = new HashMap<>(); if (this.getFor_() != null) { attrs.put("for_", this.getFor_().toString()); } if (this.getErrorTypes() != null) { attrs.put...
python
def getFriendlyString(self): """ Returns the version, printed in a friendly way. More precisely, it trims trailing zero components. """ if self._friendlyString is not None: return self._friendlyString resultComponents = [ self.getIntMajor(), ...
java
public java.util.List<SystemControl> getSystemControls() { if (systemControls == null) { systemControls = new com.amazonaws.internal.SdkInternalList<SystemControl>(); } return systemControls; }
java
private MBeanSampler makeMBeanSampler(Node sample) throws Exception { String delayString = selectParameterFromNode(sample, "delay", "60"); int delay = Integer.parseInt(delayString); String initialDelayString = selectParameterFromNode(sample, "initialdelay", "0"); int initialDelay = Integer.parseInt(initial...
java
public static void shutdownOutOfMemory(String msg) { freeMemoryBuffers(); ShutdownSystem shutdown = _activeService.get(); if (shutdown != null && ! shutdown.isShutdownOnOutOfMemory()) { System.err.println(msg); return; } else { shutdownActive(ExitCode.MEMORY, msg); ...
java
public static Integer getOrder(Class<?> type, Integer defaultOrder) { Order order = AnnotationUtils.findAnnotation(type, Order.class); if (order != null) { return order.value(); } Integer priorityOrder = getPriority(type); if (priorityOrder != null) { return priorityOrder; } return defaultOrder; }
python
def setTxPower(self, tx_power): """Set the transmission power for one or more antennas. @param tx_power: index into self.tx_power_table """ tx_pow_validated = self.get_tx_power(tx_power) logger.debug('tx_pow_validated: %s', tx_pow_validated) needs_update = False ...
java
public SIBUuid8 getSourceMEUuid() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { SibTr.entry(tc, "getSourceMEUuid"); SibTr.exit(tc, "getSourceMEUuid", sourceMEUuid); } return sourceMEUuid; }
python
def slug(self): """ Generate a short (7-character) cuid as a bytestring. While this is a convenient shorthand, this is much less likely to be unique and should not be relied on. Prefer full-size cuids where possible. """ identifier = "" # use a truncated ...
java
public void discardHeaderClick(ClickEvent event) { if (event == null) return; // Example: we use radioset on collapsible header, so stopPropagation() is needed // to suppress collapsible open/close behavior. // But preventDefault() is not needed, otherwise radios won't switch. /...
java
public void marshall(AssignInstanceRequest assignInstanceRequest, ProtocolMarshaller protocolMarshaller) { if (assignInstanceRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(assignInstanceRe...
java
public static org.ironjacamar.core.connectionmanager.pool.Capacity create( org.ironjacamar.common.api.metadata.common.Capacity metadata, ClassLoaderPlugin classLoaderPlugin) { if (metadata == null) return DefaultCapacity.INSTANCE; CapacityIncrementer incrementer = null; ...
python
def get_releases(self, project=None, definition_id=None, definition_environment_id=None, search_text=None, created_by=None, status_filter=None, environment_status_filter=None, min_created_time=None, max_created_time=None, query_order=None, top=None, continuation_token=None, expand=None, artifact_type_id=None, source_id...
python
def serveUpcoming(self, request): """Upcoming events list view.""" myurl = self.get_url(request) today = timezone.localdate() monthlyUrl = myurl + self.reverse_subpage('serveMonth', args=[today.year, today.month]) weekNum = gregor...
java
public final DataSource getDataSource(String name) { GetDataSourceRequest request = GetDataSourceRequest.newBuilder().setName(name).build(); return getDataSource(request); }
java
@Override public void sendMessage(String message) throws IOException { if (message.length() > 15) { LOGGER.warn("Firmata 2.3.6 implementation has input buffer only 32 bytes so you can safely send only 15 characters log messages"); } sendMessage(FirmataMessageFactory.stringMessage...
java
public Observable<ServiceResponseWithHeaders<Page<NodeFile>, FileListFromTaskHeaders>> listFromTaskWithServiceResponseAsync(final String jobId, final String taskId) { return listFromTaskSinglePageAsync(jobId, taskId) .concatMap(new Func1<ServiceResponseWithHeaders<Page<NodeFile>, FileListFromTas...
python
def base64_b64decode(instr): ''' Decode a base64-encoded string using the "modern" Python interface. ''' decoded = base64.b64decode(salt.utils.stringutils.to_bytes(instr)) try: return salt.utils.stringutils.to_unicode( decoded, encoding='utf8' if salt.utils.platform.i...
java
private AuthConfig getAuthConfigFromEC2InstanceRole() throws IOException { log.debug("No user and password set for ECR, checking EC2 instance role"); try (CloseableHttpClient client = HttpClients.custom().useSystemProperties().build()) { // we can set very low timeouts because the request re...
java
protected Object getDataValue(Trace trace, Node node, Direction direction, Map<String, ?> headers, Object[] values) { if (source == DataSource.Content) { return values[index]; } else if (source == DataSource.Header) { return headers.get(key); } return ...
python
def _mysql_aes_key(key): """Format key.""" final_key = bytearray(16) for i, c in enumerate(key): final_key[i % 16] ^= key[i] if PY3 else ord(key[i]) return bytes(final_key)
java
public static byte[] generateImageofMonomer(Monomer monomer, boolean rgroupsInformation) throws BuilderMoleculeException, CTKException, ChemistryException { LOG.info("Image generation process of monomer starts"); /* First build one molecule */ AbstractMolecule molecule; if (rgroupsInformation) { ...
python
def add_version_info(matrix, version): """\ Adds the version information to the matrix, for versions < 7 this is a no-op. ISO/IEC 18004:2015(E) -- 7.10 Version information (page 58) """ # # module 0 = least significant bit # module 17 = most significant bit # # Figure 27 — Version ...
java
public RedwoodConfiguration showOnlyChannels(final Object[] channels){ tasks.add(new Runnable() { public void run() { Redwood.showOnlyChannels(channels); } }); return this; }
java
public SortedMap<String, HealthCheck.Result> runHealthChecks(HealthCheckFilter filter) { final SortedMap<String, HealthCheck.Result> results = new TreeMap<>(); for (Map.Entry<String, HealthCheck> entry : healthChecks.entrySet()) { final String name = entry.getKey(); final HealthC...
java
@Nonnull private static Package createPackage(@Nonnull final String packageName) { Check.notNull(packageName, "packageName"); return packageName.isEmpty() ? Package.UNDEFINED : new Package(packageName); }
python
def set_relocated_name(self, name, rr_name): # type: (str, str) -> None ''' Set the name of the relocated directory on a Rock Ridge ISO. The ISO must be a Rock Ridge one, and must not have previously had the relocated name set. Parameters: name - The name for a...
java
public void setEntries(Map<String, String> entries) { String[][] entriesArray = null; if ((entries != null) && !entries.isEmpty()) { entriesArray = new String[entries.size()][]; int i = 0; for (Entry<String, String> entry : entries.entrySet()) { entri...
python
def signature_algo(self): """ :return: A unicode string of "rsassa_pkcs1v15", "rsassa_pss", "dsa" or "ecdsa" """ algorithm = self['algorithm'].native algo_map = { 'md2_rsa': 'rsassa_pkcs1v15', 'md5_rsa': 'rsassa_pkcs1v15', ...
java
private int readChunkLength() throws IOException { int length = 0; int ch; ReadStream is = _next; // skip whitespace for (ch = is.read(); ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n'; ch = is.read()) { } // XXX: This doesn't properly handle the case when whe...
java
public Reader getUrl(String prefix, String postfix) throws MtasParserException { String url = getString(); if ((url != null) && !url.equals("")) { if (prefix != null) { url = prefix + url; } if (postfix != null) { url = url + postfix; } if (url.startsWith("htt...
java
public Routes add(String controllerKey, Class<? extends Controller> controllerClass, String viewPath) { routeItemList.add(new Route(controllerKey, controllerClass, viewPath)); return this; }
java
public static Wallet adaptWallet(BitMarketBalance balance) { List<Balance> balances = new ArrayList<>(balance.getAvailable().size()); for (Map.Entry<String, BigDecimal> entry : balance.getAvailable().entrySet()) { Currency currency = Currency.getInstance(entry.getKey()); BigDecimal frozen = ...
java
private Event submit(final RequestContext context, final Credential credential, final MessageContext messageContext) { if (repository.submit(context, credential)) { return new EventFactorySupport().event(this, CasWebflowConstants.TRANSITION_ID_AUP_ACCEPTED); ...
python
async def full_dispatch_websocket( self, websocket_context: Optional[WebsocketContext]=None, ) -> Optional[Response]: """Adds pre and post processing to the websocket dispatching. Arguments: websocket_context: The websocket context, optional to match the Flask co...
java
public void tryCompare() throws CmsException { CmsObject cms = A_CmsUI.getCmsObject(); CheckBox check1 = m_group1.getSelected(); CheckBox check2 = m_group2.getSelected(); if (!canCompare(check1, check2)) { Notification.show( CmsVaadinUtils.getMessageText(Mess...
python
def is_command_callable(command, name=""): """ Check if command can be called. :param str command: actual command to call :param str name: nickname/alias by which to reference the command, optional :return bool: whether given command's call succeeded """ # Use `command` to see if command i...
java
@SuppressWarnings("checkstyle:npathcomplexity") public static void zipFile(File input, OutputStream output) throws IOException { try (ZipOutputStream zos = new ZipOutputStream(output)) { if (input == null) { return; } final LinkedList<File> candidates = new LinkedList<>(); candidates.add(input); ...
python
def decimal_day_to_day_hour_min_sec( self, daysFloat): """*Convert a day from decimal format to hours mins and sec* Precision should be respected. **Key Arguments:** - ``daysFloat`` -- the day as a decimal. **Return:** - ``daysInt`` -- ...
java
public List<Sheet> getSheets() { final int totalSheet = getSheetCount(); final List<Sheet> result = new ArrayList<>(totalSheet); for (int i = 0; i < totalSheet; i++) { result.add(this.workbook.getSheetAt(i)); } return result; }
python
def upload_part(self, bucket, object_name, upload_id, part_number, data=None, content_type=None, metadata={}, body_producer=None): """ Upload a part of data corresponding to a multipart upload. @param bucket: The bucket name @param object_name: Th...
java
private WMenuItem createImageMenuItem(final String resource, final String desc, final String cacheKey, final WText selectedMenuText) { WImage image = new WImage(resource, desc); image.setCacheKey(cacheKey); WDecoratedLabel label = new WDecoratedLabel(image, new WText(desc), null); WMenuItem menuItem = new...
java
public void write(WARCWritable record) throws IOException { if (record.getRecord() != null) write(record.getRecord()); }
java
public static boolean verifySignatureWithPublicKey(String base64PublicKeyData, byte[] message, byte[] signature) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, SignatureException { return verifySignatureWithPublicKey(base64PublicKeyData, message, signature...
python
def resolve(self, context, provider): """Recursively resolve any lookups with the Variable. Args: context (:class:`stacker.context.Context`): Current context for building the stack provider (:class:`stacker.provider.base.BaseProvider`): subclass of ...
python
def transform(self, key, xml, **kwargs): """ Transform the supplied XML using the transform identified by key @param key: name of the transform to apply @param xml: XML to transform @param kwargs: XSLT parameters @return: Transform output or None if transform failed ...
python
def device_gen(chain, urls): """Device object generator.""" itr = iter(urls) last = next(itr) for url in itr: yield Device(chain, make_hop_info_from_url(last), driver_name='jumphost', is_target=False) last = url yield Device(chain, make_hop_info_from_url(last), driver_name='generic',...
java
public List<String> getFileTypes() { List<String> fileTypes = getComponentModel().fileTypes; if (fileTypes == null) { return Collections.emptyList(); } return Collections.unmodifiableList(fileTypes); }
java
@Override public final void setLang(final Languages pLang) { this.lang = pLang; if (this.itsId == null) { this.itsId = new IdI18nChooseableSpecifics(); } this.itsId.setLang(this.lang); }
python
def parse(region_string): """Parse DS9 region string into a ShapeList. Parameters ---------- region_string : str Region string Returns ------- shapes : `ShapeList` List of `~pyregion.Shape` """ rp = RegionParser() ss = rp.parse(region_string) sss1 = rp.conve...
java
public static WritableRaster replaceNovalue( RenderedImage renderedImage, double newValue ) { WritableRaster tmpWR = (WritableRaster) renderedImage.getData(); RandomIter pitTmpIterator = RandomIterFactory.create(renderedImage, null); int height = renderedImage.getHeight(); int width = r...
java
public static Expectations successfullyReachedUrl(String testAction, String url) { Expectations expectations = new Expectations(); expectations.addSuccessStatusCodesForActions(new String[] { testAction }); expectations.addExpectation(new ResponseUrlExpectation(testAction, Constants.STRING_EQUALS...