language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _get_submap(self, eopatch): """ Returns a new geopandas dataframe with same structure as original one (columns) except that it contains only polygons that are contained within the given bbox. :param eopatch: input EOPatch :type eopatch: EOPatch :return: New EOPatch ...
java
@Override public void apply(final X509CRL crl) throws ExpiredCRLException { val cutoff = ZonedDateTime.now(ZoneOffset.UTC); if (CertUtils.isExpired(crl, cutoff)) { if (CertUtils.isExpired(crl, cutoff.minusSeconds(this.threshold))) { throw new ExpiredCRLException(crl.toStr...
java
private NodeDO modelToDo(Node node) { NodeDO nodeDo = new NodeDO(); try { nodeDo.setId(node.getId()); nodeDo.setIp(node.getIp()); nodeDo.setName(node.getName()); nodeDo.setPort(node.getPort()); nodeDo.setDescription(node.getDescription()); ...
java
public I_CmsWidget getWidgetObject() { if (getWidget() == null) { if (m_params == null) { return new CmsInputWidget(); } else { return new CmsInputWidget(m_params); } } try { if (m_params == null) { ...
python
def get_function_from_signature(self, function_signature): """ Return a function from a signature Args: function_signature (str): signature of the function (without return statement) Returns: Function """ return next((f for f in self.functions ...
java
public static double[] createBoundingBox(double[][][] input) { double[] bbox = createBoundingBox(input[0]); for (int i = 1; i < input.length; i++) { double[] current = createBoundingBox(input[i]); mergeInto(bbox, current); } return bbox; }
java
@Override public String getTypeName() { String type; if (isGeometry()) { type = geometryType.name(); } else { type = super.getTypeName(); } return type; }
java
public static SenseIdValue makeSenseIdValue(String id, String siteIri) { return factory.getSenseIdValue(id, siteIri); }
java
private final String internalGetMessage(String key) { if(getResourceBundlePath() == null) return getDefaultMessage(key); else { /* ensure that the correct resource bundles are created */ if(_resourceBundle == null) { _resourceBundle = createResourceBun...
java
private MetadataDatabase getDatabase(String deviceUrl) throws TheDavidBoxClientException{ ResponseCheckDatabase responseCheckDatabase = buildCheckDatabaseOperation(deviceUrl).execute(); String databasePath = responseCheckDatabase.getDatabasePath(); MetadataDatabase database = new MetadataDatabase(deviceUr...
python
def write(self, data): """Write data into the device input buffer. :param data: single element byte :type data: bytes """ logger.debug('Writing into device input buffer: %r' % data) if not isinstance(data, bytes): raise TypeError('data must be an instance of ...
java
public CmsWaitHandle getWaitHandleForUpdateTask() { CmsWaitHandle handle = new CmsWaitHandle(true); m_workQueue.add(handle); return handle; }
python
def getAll(self, symbol): """ Get all available quote data for the given ticker symbol. Returns a dictionary. """ values = self.__request(symbol, 'l1c1va2xj1b4j4dyekjm3m4rr5p5p6s7').split(',') data = {} data['price'] = values[0] data['change'] = va...
python
def wrheader(self, write_dir=''): """ Write a wfdb header file. The signals are not used. Before writing: - Get the fields used to write the header for this instance. - Check each required field. - Check that the fields are cohesive with one another. Parameters ...
python
def _get_unknown_error_response(self, request, exc): """ Generate HttpResponse for unknown exceptions. todo: this should be more informative.. """ logging.getLogger('devil').error( 'while doing %s on %s with [%s], devil caught: %s' % ( request.method, reques...
python
def _compute_top_of_rupture_depth_term(self, C, rup): """ Compute and return top of rupture depth term, that is the seventh term in equation 1, page 74. The calculation of this term is explained in paragraph 'Depth-to-Top of Rupture Model', page 78. """ if rup.ztor >= 10....
python
def list(cls, session, mailbox): """Return conversations in a mailbox. Args: session (requests.sessions.Session): Authenticated session. mailbox (helpscout.models.Mailbox): Mailbox to list. Returns: RequestPaginator(output_type=helpscout.models.Conversation)...
java
private String getContentItemForXPath(Map<String, String> contentItems, String xpath) { if (contentItems.get(xpath) != null) { // content item found for XPath return contentItems.get(xpath); } else { // try a multiple value mapping and ensure that the values are in correct order. ...
python
def get_bounding_boxes(self, trt=None, mag=None): """ :param trt: a tectonic region type (used for the integration distance) :param mag: a magnitude (used for the integration distance) :returns: a list of bounding boxes, one per site """ bbs = [] for site in self....
java
public String getMimeType() { if (mediaType == null || untrustedAgent) { return mimeTypeResolver.getMimeType(fileName); } return mediaType.getType() + "/" + mediaType.getSubtype(); }
java
public Observable<Void> publishEventsAsync(String topicHostname, List<EventGridEvent> events) { return publishEventsWithServiceResponseAsync(topicHostname, events).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { ...
java
public Options setIntegrationOptions(String integrationKey, Map<String, Object> options) { integrations.put(integrationKey, options); return this; }
java
protected final ActionBinding findActionBinding(ActionContext actionContext) { for (ActionBinding actionBinding : this.actionBindings) { if (actionBinding.supports(actionContext)) { return actionBinding; } } return null; }
java
public synchronized void enqueue(final byte[] array) throws IOException { assert array != null; byteDiskQueue.enqueueInt(array.length); byteDiskQueue.enqueue(array); size++; }
python
def declare_string(self, value): # type: (Union[Text, str]) -> Tuple[ProvEntity,Text] """Save as string in UTF-8.""" byte_s = BytesIO(str(value).encode(ENCODING)) data_file = self.research_object.add_data_file(byte_s, content_type=TEXT_PLAIN) checksum = posixpath.basename(data_fi...
python
def start_health_check_for(self, node_address: Address): """Start health checking `node_address`. This function is a noop during initialization, because health checking can be started as a side effect of some events (e.g. new channel). For these cases the healthcheck will be started by ...
java
public void addOption(final String name, final String meta, final String help) { if (name.isEmpty()) { throw new IllegalArgumentException("empty name"); } else if (name.charAt(0) != '-') { throw new IllegalArgumentException("name must start with a `-':...
java
private static void setRectangleProperties(Rectangle rect, Properties attributes) { String value; value = attributes.getProperty(ElementTags.BORDERWIDTH); if (value != null) { rect.setBorderWidth(Float.parseFloat(value + "f")); } int border = 0; if (Utilities.checkTrueOrFalse(attributes, ElementTags.L...
python
def _commit_with_retry(client, write_pbs, transaction_id): """Call ``Commit`` on the GAPIC client with retry / sleep. Retries the ``Commit`` RPC on Unavailable. Usually this RPC-level retry is handled by the underlying GAPICd client, but in this case it doesn't because ``Commit`` is not always idempote...
python
def delete(cls, repo, path): """Delete the reference at the given path :param repo: Repository to delete the reference from :param path: Short or full path pointing to the reference, i.e. refs/myreference or just "myreference", hence 'refs/' is implied. ...
java
public PlatformApplication withAttributes(java.util.Map<String, String> attributes) { setAttributes(attributes); return this; }
python
def scan_in_memory(node, env, path=()): """ "Scans" a Node.FS.Dir for its in-memory entries. """ try: entries = node.entries except AttributeError: # It's not a Node.FS.Dir (or doesn't look enough like one for # our purposes), which can happen if a target list containing ...
java
private static void copyProperties(Map<String, JsonNode> props, Schema schema) { Preconditions.checkNotNull(schema); // (if null, don't copy but do not throw exception) if (null != props) { for (Map.Entry<String, JsonNode> prop : props.entrySet()) { schema.addProp(prop.getKey(), prop.getValue...
java
public static @CheckForNull <T> T lookup(Class<T> type) { Jenkins j = Jenkins.getInstanceOrNull(); return j != null ? j.lookup.get(type) : null; }
python
def remove_entry(self, fs_entry): """Removes an FSEntry object from this METS document. Any children of this FSEntry will also be removed. This will be removed as a child of it's parent, if any. :param metsrw.mets.FSEntry fs_entry: FSEntry to remove from the METS """ tr...
java
public void addBundle(ExtendedBundle bundle) { if (classResolverRegistration == null) { throw new IllegalStateException("The service is stoped and no more bundles could be added"); } synchronized (bundles) { bundles.put(bundle.getBundle().getSymbolicName(), bundle.getBund...
java
private static void checkSchemeConsistency(URI u) throws IOException { String scheme = u.getScheme(); // the URI should have a proper scheme if(scheme == null) { throw new IOException("Undefined scheme for " + u); } }
python
def remove_environment(environment_var_name, system=False): """ Remove the specified environment setting from the appropriate config file. :param environment_var_name: The name of the environment setting to remove. :keyword system: Set to True to modify the system configuration file. ...
java
public AnnotatedTypeBuilder<X> removeFromMethod(Method method, Class<? extends Annotation> annotationType) { if (methods.get(method) == null) { throw new IllegalArgumentException("Method not present " + method.toString() + " on " + javaClass); } else { methods.get(method).remove(anno...
java
public void signIn(Map<String, Object> formParams) throws AuthenticationApiException { Headers.Builder headerBuilder = new Headers.Builder(); headerBuilder.add("Accept", "*/*"); headerBuilder.add("Content-Type", "application/x-www-form-urlencoded"); Request request = new Request.Builder...
python
async def rename(self, src, dst): """ Rename key ``src`` to ``dst`` Cluster impl: This operation is no longer atomic because each key must be querried then set in separate calls because they maybe will change cluster node """ if src == dst: ra...
python
def isFits(input): """ Returns -------- isFits: tuple An ``(isfits, fitstype)`` tuple. The values of ``isfits`` and ``fitstype`` are specified as: - ``isfits``: True|False - ``fitstype``: if True, one of 'waiver', 'mef', 'simple'; if False, None Notes ----- ...
java
protected List<Element> select(String selector, Element context) { NodeList<Element> elements = CmsDomUtil.querySelectorAll(selector, context); List<Element> result = new ArrayList<Element>(); for (int i = 0; i < elements.getLength(); i++) { result.add(elements.getItem(i)); ...
java
protected void updatePartnerServiceData() throws Exception { if (tc.isEntryEnabled()) Tr.entry(tc, "updatePartnerServiceData"); try { // // Check we have a recoverableUnit and three sections to add the data. // On recovery we check that all service data s...
python
def successors(self, state, addr=None, jumpkind=None, default_engine=False, procedure_engine=False, engines=None, **kwargs): """ Perform execution using any applicable engine. Enumerate the current engines and use the first one that works. Engines are enumerated in order, spec...
java
public Next<Flow<T>> getOrCreateNext() { List<Node> nodeList = childNode.get("next"); if (nodeList != null && nodeList.size() > 0) { return new NextImpl<Flow<T>>(this, "next", childNode, nodeList.get(0)); } return createNext(); }
java
public synchronized PacketBuilder withFloat(final float f) { checkBuilt(); try { dataOutputStream.writeFloat(f); } catch (final IOException e) { logger.error("Unable to add float: {} : {}", e.getClass(), e.getMessage()); } retur...
java
@Override public void createRetentionPolicy(final String rpName, final String database, final String duration, final String shardDuration, final int replicationFactor, final boolean isDefault) { Preconditions.checkNonEmptyString(rpName, "retentionPolicyName"); Preconditions...
java
public String getHeadings(int i) { if (DataTable_Type.featOkTst && ((DataTable_Type)jcasType).casFeat_headings == null) jcasType.jcas.throwFeatMissing("headings", "ch.epfl.bbp.uima.types.DataTable"); jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((DataTable_Type)jcasType).casFeatCode...
java
public static int cuStreamAddCallback(CUstream hStream, CUstreamCallback callback, Object userData, int flags) { return checkResult(cuStreamAddCallbackNative(hStream, callback, userData, flags)); }
python
def generate_aliases_global(fieldfile, **kwargs): """ A saved_file signal handler which generates thumbnails for all field, model, and app specific aliases matching the saved file's field, also generating thumbnails for each project-wide alias. """ # Avoids circular import. from easy_thumbna...
java
private MBeanServerConnection getNetworkConnection() { try { JMXServiceURL url = new JMXServiceURL(getEndpointConfiguration().getServerUrl()); String[] creds = {getEndpointConfiguration().getUsername(), getEndpointConfiguration().getPassword()}; JMXConnector networkConnector ...
python
def convolve(self, signal, mode='full'): """ Convolve series data against another signal. Parameters ---------- signal : array Signal to convolve with (must be 1D) mode : str, optional, default='full' Mode of convolution, options are 'full', 'sam...
python
def copy_course_content(self, course_id, exclude=None, only=None, source_course=None): """ Copy course content. DEPRECATED: Please use the {api:ContentMigrationsController#create Content Migrations API} Copies content from one course into another. The default is to copy a...
java
public OvhIpxe ipxeScript_name_GET(String name) throws IOException { String qPath = "/me/ipxeScript/{name}"; StringBuilder sb = path(qPath, name); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhIpxe.class); }
python
def to_bytes(self, request=None): '''Called to transform the collection of ``streams`` into the content string. This method can be overwritten by derived classes. :param streams: a collection (list or dictionary) containing ``strings/bytes`` used to build the final ``string/...
python
def animate(self, duration = None, easing = None, on_complete = None, on_update = None, round = False, **kwargs): """Request parent Scene to Interpolate attributes using the internal tweener. Specify sprite's attributes that need changing. `duration` defaults to 0.4 seconds...
java
public void setNull(long mask) { for (int i = 0; i < this.numFields; i++, mask >>>= 1) { if ((mask & 0x1) != 0) { internallySetField(i, null); } } }
python
def convert_table(self, block): """"Converts a table to grid table format""" lines_orig = block.split('\n') lines_orig.pop() # Remove extra newline at end of block widest_cell = [] # Will hold the width of the widest cell for each column widest_word = [] # Will hold the width of ...
python
def copy_file_if_newer( src_fs, # type: Union[FS, Text] src_path, # type: Text dst_fs, # type: Union[FS, Text] dst_path, # type: Text ): # type: (...) -> bool """Copy a file from one filesystem to another, checking times. If the destination exists, and is a file, it will be first trunca...
java
public T payload(Resource payloadResource, Charset charset) { try { setPayload(FileUtils.readToString(payloadResource, charset)); } catch (IOException e) { throw new CitrusRuntimeException("Failed to read payload resource", e); } return self; }
python
def Scroll_down(self, n, dl = 0): """鼠标滚轮向下n次 """ self.Delay(dl) self.mouse.scroll(vertical = -n)
java
public static long copySome(final InputStream input, final OutputStream output, final int size, final long length) throws IOException { return copySome(input, output, new byte[size], length); }
python
def hbas(self): """ :class:`~zhmcclient.HbaManager`: Access to the :term:`HBAs <HBA>` in this Partition. If the "dpm-storage-management" feature is enabled, this property is `None`. """ # We do here some lazy loading. if not self._hbas: try: ...
java
public void sudo(String sudoAsUsername) throws GitLabApiException { if (sudoAsUsername == null || sudoAsUsername.trim().length() == 0) { apiClient.setSudoAsId(null); return; } // Get the User specified by username, if you are not an admin or the username is not found, t...
java
public CmsLink addLink(CmsRelationType type, String targetUri, boolean internal) { CmsLink link = new CmsLink(LINK_PREFIX + m_linkTable.size(), type, targetUri, internal); m_linkTable.put(link.getName(), link); return link; }
python
def _FormatIPToken(self, token_data): """Formats an IPv4 packet header token as a dictionary of values. Args: token_data (bsm_token_data_ip): AUT_IP token data. Returns: dict[str, str]: token values. """ data = ''.join(['{0:02x}'.format(byte) for byte in token_data.data]) return {'...
python
def validate_wavelengths(wavelengths): """Check wavelengths for ``synphot`` compatibility. Wavelengths must satisfy these conditions: * valid unit type, if given * no zeroes * monotonic ascending or descending * no duplicate values Parameters ---------- wavelengths...
java
public static void append(File file, Writer writer, String charset) throws IOException { appendBuffered(file, writer, charset); }
python
def add_custom(self, name, input_names, output_names, custom_proto_spec = None): """ Add a custom layer. Parameters ---------- name: str The name of this layer. input_names: [str] The input blob names to this layer. output_names: [str] ...
python
def read_git_branch(): """Read version information from VERSION file""" try: with open(CC_INIT, "r") as f: found = False while not found: line = f.readline().strip().split() try: found = True if line[0] == '_git_branch' else Fal...
java
protected void eventPostCommitAdd(SIMPMessage msg, TransactionCommon transaction) throws SIDiscriminatorSyntaxException, SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "eventPostCommitAdd", new Object[] { msg, transactio...
java
byte[] DERToJOSE(byte[] derSignature) throws SignatureException { // DER Structure: http://crypto.stackexchange.com/a/1797 boolean derEncoded = derSignature[0] == 0x30 && derSignature.length != ecNumberSize * 2; if (!derEncoded) { throw new SignatureException("Invalid DER signature f...
java
public static void swap(char[] charArray1, int array1Index, char[] charArray2, int array2Index) { if(charArray1[array1Index] != charArray2[array2Index]) { char hold = charArray1[array1Index]; charArray1[array1Index] = charArray2[array2Index]; charArray2[array2Index] = hold; ...
python
def get_users( self, user_ids: Iterable[Union[int, str]] ) -> Union["pyrogram.User", List["pyrogram.User"]]: """Use this method to get information about a user. You can retrieve up to 200 users at once. Args: user_ids (``iterable``): A list of Use...
python
def measure_observables(qc: QuantumComputer, tomo_experiment: TomographyExperiment, n_shots: int = 10000, progress_callback=None, active_reset=False, symmetrize_readout: str = 'exhaustive', calibrate_readout: str = 'plus-eig'): """ Measure ...
java
protected void initializeBMD(BeanMetaData bmd) throws Exception { if (bmd.ivDeferEJBInitialization) { // Before WCCM data structures are cleared, determine if // early reference processing is needed for this EJB. For // example, if the bean has java:global modules, those nee...
python
def make_python_name(s, default=None, number_prefix='N',encoding="utf-8"): """Returns a unicode string that can be used as a legal python identifier. :Arguments: *s* string *default* use *default* if *s* is ``None`` *number_prefix* string to prepend if *s* starts wi...
python
def scope(cls, f): """Decorator which can dynamically attach a query scope to the model.""" if not hasattr(cls, "scopes"): cls.scopes = copy(STANDARD_SCOPES) cls.scopes.append(f) def create_builder(self, *args, **kwargs): bldr = ScopeBuilder(cls, cls.scopes) ...
java
private static boolean polylineTouchesPoint_(Polyline polyline_a, Point point_b, double tolerance, ProgressTracker progress_tracker) { // Quick rasterize test to see whether the the geometries are disjoint. if (tryRasterizedContainsOrDisjoint_(polyline_a, point_b, tolerance, false) == Relation.disjoint) r...
java
@Override public Cursor<S> fetchSlice(long from, Long to) { checkSliceArguments(from, to); return EmptyCursor.the(); }
java
public String print( Duration<?> duration, TextWidth width, boolean printZero, int maxLength ) { if (maxLength < 1) { throw new IllegalArgumentException( "Max length is invalid: " + maxLength); } // special case of empty duration ...
java
private void parseResponse(ModelNode response, AsyncCallback<Map<String,String>> callback) { //System.out.println(response.toString()); Map<String, String> serverValues = new HashMap<String,String>(); if(isStandalone) { serverValues.put("Standalone Server", response.get(RE...
python
def get_private_file(self): """ Return all relevant data in a single object, so this is easy to extend and server implementations can pick what they need. """ return PrivateFile( request=self.request, storage=self.get_storage(), relative_name=s...
python
def remove(id_): """ Remove the callback and its schedule """ with LOCK: thread = REGISTRY.pop(id_, None) if thread is not None: thread.cancel() return thread
java
public String getPath(boolean p_includeQueryString, boolean p_includeFragment) { StringBuffer pathString = new StringBuffer(m_path); if (p_includeQueryString && m_queryString != null) { pathString.append('?'); pathString.append(m_queryString); } if (p_include...
python
def main(extension, strict_extensions, default_extension, x): """Top level zipline entry point. """ # install a logbook handler before performing any other operations logbook.StderrHandler().push_application() create_args(x, zipline.extension_args) load_extensions( default_extension, ...
java
private static double[] reversed(double[] a) { // TODO: there doesn't appear to be a nicer version in Java, unfortunately. Arrays.sort(a); for(int i = 0, j = a.length - 1; i < j; i++, j--) { double tmp = a[i]; a[i] = a[j]; a[j] = tmp; } return a; }
python
def _run_custom_data_engine(self, start_id_obj, end_id_obj, start_timeperiod, end_timeperiod): """ fine-tuned data engine. MongoDB legacy """ collection_name = context.process_context[self.process_name].source iteration = 0 while True: cursor = self.ds.cursor_fine(collection_...
python
def find_matches_by_sigma(cos_vects, unc_vect, cut_sigma): """Find all the pairs of sources within a given distance of each other. Parameters ---------- cos_vects : np.ndarray(3,nsrc) Directional cosines (i.e., x,y,z component) values of all the sources unc_vect : np.ndarray(nsrc) ...
java
private void handleWaterMarkEvent(Event<T> waterMarkEvent) { long watermarkTs = waterMarkEvent.getTimestamp(); List<Long> eventTs = windowManager.getSlidingCountTimestamps(lastProcessedTs, watermarkTs, count); for (long ts : eventTs) { evictionPolicy.setContext(ts); handl...
python
def aliased_as(self, name): """ Create an alias of this stream. Returns an alias of this stream with name `name`. When invocation of an SPL operator requires an :py:class:`~streamsx.spl.op.Expression` against an input port this can be used to ensure expression ma...
java
public Reader getCharacterStream(long pos, long length) throws SQLException { if (length > Integer.MAX_VALUE) { throw Util.outOfRangeArgument("length: " + length); } return new StringReader(getSubString(pos, (int) length)); }
java
void onWritingThreadFinished(WebSocketFrame closeFrame) { synchronized (mThreadsLock) { mWritingThreadFinished = true; mClientCloseFrame = closeFrame; if (mReadingThreadFinished == false) { // Wait for the reading thread to finish. ...
python
def date_added(self, date_added): """Set Indicator dateAdded.""" self._group_data['dateAdded'] = self._utils.format_datetime( date_added, date_format='%Y-%m-%dT%H:%M:%SZ' )
python
def predict(self, X, nsamples=200, likelihood_args=()): """ Predict target values from Bayesian generalized linear regression. Parameters ---------- X : ndarray (N*,d) array query input dataset (N* samples, d dimensions). nsamples : int, optional ...
python
def set(self, path, data): """ Sets the content of a ZooKeeper node :param path: Z-Path :param data: New content """ return self._zk.set(self.__path(path), data)
java
public Map<String, ? extends Attachment> attachmentsForRevision(final InternalDocumentRevision rev) throws AttachmentException { try { return get(queue.submit(new SQLCallable<Map<String, ? extends Attachment>>() { @Override public Map<String, ? extends At...
java
private static void checkOrcVersion(OrcDataSource orcDataSource, List<Integer> version) { if (version.size() >= 1) { int major = version.get(0); int minor = 0; if (version.size() > 1) { minor = version.get(1); } if (major > CURRENT...
java
@Deprecated public void importResources( CmsObject cms, String importPath, I_CmsReport report, File importResource, ZipFile importZip, Document docXml) { CmsImportParameters params = new CmsImportParameters(importResource.getAbsolutePath(), importPath, true);...