text
stringlengths
78
104k
score
float64
0
0.18
def guarded(meth): """A decorator to add a sanity check to ConnectionResource methods.""" @functools.wraps(meth) def _check(self, *args, **kwargs): self._check_conn_validity(meth.__name__) return meth(self, *args, **kwargs) return _check
0.00369
def run_cutadapt(job, r1_id, r2_id, fwd_3pr_adapter, rev_3pr_adapter): """ Adapter trimming for RNA-seq data :param JobFunctionWrappingJob job: passed automatically by Toil :param str r1_id: FileStoreID of fastq read 1 :param str r2_id: FileStoreID of fastq read 2 (if paired data) :param str fw...
0.00359
def is_uid(str): """ Input: string to check Output: True if UID, otherwise False """ import re if len(str)!=16: return False pattern = r'[^\.a-f0-9]' if re.search(pattern, str.lower()): return False return True
0.011236
async def send_initial_metadata(self, *, metadata=None): """Coroutine to send headers with initial metadata to the client. In gRPC you can send initial metadata as soon as possible, because gRPC doesn't use `:status` pseudo header to indicate success or failure of the current request. g...
0.001635
def postcode_in_state(self, state_abbr=None): """ :example '4703' """ if state_abbr is None: state_abbr = self.random_element(self.states_abbr) if state_abbr in self.states_abbr: postcode = "%d" % (self.generator.random.randint( ...
0.003247
def plot_rebit_prior(prior, rebit_axes=REBIT_AXES, n_samples=2000, true_state=None, true_size=250, force_mean=None, legend=True, mean_color_index=2 ): """ Plots rebit states drawn from a given prior. :param qinfer.tomography.DensityOperatorDistribution prior: Distributio...
0.008398
def get_inputs( self, start=0, stop=None, threshold=None, security_level=None, ): # type: (int, Optional[int], Optional[int], Optional[int]) -> dict """ Gets all possible inputs of a seed and returns them, along with the tot...
0.001512
def ndarray_to_instances(array, relation, att_template="Att-#", att_list=None): """ Converts the numpy matrix into an Instances object and returns it. :param array: the numpy ndarray to convert :type array: numpy.darray :param relation: the name of the dataset :type relation: str :param att...
0.002581
def _load_metadata(self): """Load metadata from the archive file""" logger.debug("Loading metadata infomation of archive %s", self.archive_path) cursor = self._db.cursor() select_stmt = "SELECT origin, backend_name, backend_version, " \ "category, backend_params, ...
0.003125
def rehighlight(self): """ Rehighlight the entire document, may be slow. """ start = time.time() QtWidgets.QApplication.setOverrideCursor( QtGui.QCursor(QtCore.Qt.WaitCursor)) try: super(SyntaxHighlighter, self).rehighlight() except Runtime...
0.003497
def get_project_logs(self, request): """ Get logs from log service. Unsuccessful opertaion will cause an LogException. :type request: GetProjectLogsRequest :param request: the GetProjectLogs request parameters class. :return: GetLogsResponse ...
0.008584
def fetchGroupInfo(self, *group_ids): """ Get groups' info from IDs, unordered :param group_ids: One or more group ID(s) to query :return: :class:`models.Group` objects, labeled by their ID :rtype: dict :raises: FBchatException if request failed """ threa...
0.004769
def outliers_grubbs(x, hypo = False, alpha = 0.05): """ Grubbs' Test for Outliers [1]_. This is the two-sided version of the test. The null hypothesis implies that there are no outliers in the data set. Parameters ---------- x : array_like or ndarray, 1d An array, any object exposing ...
0.004271
def create(self, public_key, friendly_name=values.unset, account_sid=values.unset): """ Create a new PublicKeyInstance :param unicode public_key: A URL encoded representation of the public key :param unicode friendly_name: A string to describe the resource :param ...
0.005714
def find_srv_by_name_and_hostname(self, host_name, sdescr): """Get a specific service based on a host_name and service_description :param host_name: host name linked to needed service :type host_name: str :param sdescr: service name we need :type sdescr: str :return: th...
0.004124
def get_store_env_tmp(): '''Returns an unused random filepath.''' tempdir = tempfile.gettempdir() temp_name = 'envstore{0:0>3d}' temp_path = unipath(tempdir, temp_name.format(random.getrandbits(9))) if not os.path.exists(temp_path): return temp_path else: return get_store_env_tm...
0.003096
def log_user_in(app_id, token, ticket, response, cookie_name='user', url_detail='https://pswdless.appspot.com/rest/detail'): ''' Log the user in setting the user data dictionary in cookie Returns a command that execute the logic ''' return LogUserIn(app_id, token, ticket, response, c...
0.002915
def get_aws_secrets_from_file(credentials_file): # type: (str) -> Set[str] """Extract AWS secrets from configuration files. Read an ini-style configuration file and return a set with all found AWS secret access keys. """ aws_credentials_file_path = os.path.expanduser(credentials_file) if not o...
0.001057
def _load_config_files(self): # type: () -> None """Loads configuration from configuration files """ config_files = dict(self._iter_config_files()) if config_files[kinds.ENV][0:1] == [os.devnull]: logger.debug( "Skipping loading configuration files due...
0.002876
def export2hub(weight_file, hub_dir, options): """Exports a TF-Hub module """ spec = make_module_spec(options, str(weight_file)) try: with tf.Graph().as_default(): module = hub.Module(spec) with tf.Session() as sess: sess.run(tf.global_variables_initial...
0.00207
def up_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): """Monitors a local directory and generates sets of new files to be uploaded to FlashAir. Sets to upload are generated in a tuple like (Direction.up, {...}). The generator yields before each upload actually takes place.""" lo...
0.002475
def start(self, plugin_name=None, kwargs=None): """Start method: initial data structures and store some meta data.""" self.output = [] # Start basically resets the output data super(WorkbenchRenderer, self).start(plugin_name=plugin_name) return self
0.010676
def handle_tabbed_response(self, tab_group, context): """Sends back an AJAX-appropriate response for the tab group if needed. Otherwise renders the response as normal. """ if self.request.is_ajax(): if tab_group.selected: return http.HttpResponse(tab_group.se...
0.00432
def filter_status(self, sample=None, subset=None, stds=False): """ Prints the current status of filters for specified samples. Parameters ---------- sample : str Which sample to print. subset : str Specify a subset stds : bool ...
0.002083
def toggle_custom_value(self): """Enable or disable the custom value line edit.""" radio_button_checked_id = self.input_button_group.checkedId() if (radio_button_checked_id == len(self._parameter.options) - 1): self.custom_value.setDisabled(False) else: ...
0.00554
def get_in_srvc_node_ip_addr(cls, tenant_id): """Retrieves the IN service node IP address. """ if tenant_id not in cls.serv_obj_dict: LOG.error("Fabric not prepared for tenant %s", tenant_id) return tenant_obj = cls.serv_obj_dict.get(tenant_id) in_subnet_dict = te...
0.004494
def get_parentparser(parser, description=None, help=True): """ :param parser: :class:`argparse.ArgumentParser` instance or None :param description: string used to build a new parser if parser is None :param help: flag used to build a new parser if parser is None :returns: if parser is None the new p...
0.001527
def load_module(self, fullname): """ load_module is always called with the same argument as finder's find_module, see "How Import Works" """ mod = super(JsonLoader, self).load_module(fullname) try: with codecs.open(self.cfg_file, 'r', 'utf-8') as f: ...
0.002625
def wireHandlers(cfg): """ If the device is configured to run against a remote server, ping that device on a scheduled basis with our current state. :param cfg: the config object. :return: """ logger = logging.getLogger('recorder') httpPoster = cfg.handlers.get('remote') csvLogger = ...
0.00487
def product(self): """ Return the USB device's product string descriptor. This property will cause some USB traffic the first time it is accessed and cache the resulting value for future use. """ if self._product is None: self._product = util.get_string(self, self.iP...
0.005618
def parse_option(self, option, block_name, *values): """ Parse duration option for timer. """ try: if len(values) != 1: raise TypeError self.total_duration = int(values[0]) if self.total_duration <= 0: raise ValueError ...
0.004435
def _selftoken_expired(): ''' Validate the current token exists and is still valid ''' try: verify = __opts__['vault'].get('verify', None) url = '{0}/v1/auth/token/lookup-self'.format(__opts__['vault']['url']) if 'token' not in __opts__['vault']['auth']: return True ...
0.001395
def createLabels2D(self): """ 2D labeling at zmax """ logger.debug(" Creating 2D labels...") self.zmax = np.argmax(self.values,axis=1) self.vmax = self.values[np.arange(len(self.pixels),dtype=int),self.zmax] kwargs=dict(pixels=self.pixels,values=self.vmax,nside=self.nside, ...
0.022764
def url(self, name): """ Since we assume all public storage with no authorization keys, we can just simply dump out a URL rather than having to query S3 for new keys. """ name = urllib.quote_plus(self._clean_name(name), safe='/') if self.bucket_cname: return ...
0.003425
def dumps(data, ac_parser=None, **options): """ Return string representation of 'data' in forced type format. :param data: Config data object to dump :param ac_parser: Forced parser type or ID or parser object :param options: see :func:`dump` :return: Backend-specific string representation for...
0.002101
def _getter(self): """ Return a function object suitable for the "get" side of the attribute property descriptor. """ def get_attr_value(obj): attr_str_value = obj.get(self._clark_name) if attr_str_value is None: raise InvalidXmlError( ...
0.003361
def loggerLevel(self, logger): """ Returns the level for the inputed logger. :param logger | <str> :return <int> """ try: return self._loggerLevels[logger] except KeyError: items = sorted(self._loggerLe...
0.008333
def open_in_browser(self, session, output_filename=None): """ Open the rendered HTML in a webbrowser. If output_filename=None (the default), a tempfile is used. The filename of the HTML file is returned. """ if output_filename is None: output_file = tempfil...
0.004706
def delete_virtual_mfa_device(serial, region=None, key=None, keyid=None, profile=None): ''' Deletes the specified virtual MFA device. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_virtual_mfa_device serial_num ''' conn = __utils__['boto3.get_connection_func']('iam')(...
0.002614
def get_album_songs(self, album_id): """Get a album's all songs. warning: use old api. :params album_id: album id. :return: a list of Song object. """ url = 'http://music.163.com/api/album/{}/'.format(album_id) result = self.get_request(url) songs = res...
0.004662
def get(self, request, username, course_key, subsection_id): """ Returns completion for a (user, subsection, course). """ def get_completion(course_completions, all_blocks, block_id): """ Recursively get the aggregate completion for a subsection, given...
0.004006
def perform_smooth(x_values, y_values, span=None, smoother_cls=None): """ Convenience function to run the basic smoother. Parameters ---------- x_values : iterable List of x value observations y_ values : iterable list of y value observations span : float, optional F...
0.001294
def cancel_task(self, task_id): """Cancel or 'un-schedule' a task. :param task_id: identifier of the task to cancel :raises NotFoundError: raised when the requested task is not found in the registry """ self.registry.remove(task_id) self._scheduler.cancel_jo...
0.005195
def _inc_path(self): """:returns: The path of the next sibling of a given node path.""" newpos = self._str2int(self.path[-self.steplen:]) + 1 key = self._int2str(newpos) if len(key) > self.steplen: raise PathOverflow(_("Path Overflow from: '%s'" % (self.path, ))) retu...
0.004301
def get_prep_value(self, value): """Override the base class so it doesn't cast all values to strings. psqlextra supports expressions in hstore fields, so casting all values to strings is a bad idea.""" value = Field.get_prep_value(self, value) if isinstance(value, dict...
0.002587
def stop_cfms(self, stop_cfms): '''Set the CFM values for this object's DOF limits. Parameters ---------- stop_cfms : float or sequence of float A CFM value to set on all degrees of freedom limits, or a list containing one such value for each degree of freedom li...
0.004819
def listChecksumAlgorithms(self, vendorSpecific=None): """See Also: listChecksumAlgorithmsResponse() Args: vendorSpecific: Returns: """ response = self.listChecksumAlgorithmsResponse(vendorSpecific) return self._read_dataone_type_response(response, 'ChecksumA...
0.008982
def _marker(self, lat, long, text, xmap, color=None, icon=None, text_mark=False, style=None): """ Adds a marker to the default map """ kwargs = {} if icon is not None: kwargs["icon"] = icon if color is not None: kwargs["color"] = co...
0.002778
def _openResources(self): """ Uses numpy.loadtxt to open the underlying file. """ try: rate, data = scipy.io.wavfile.read(self._fileName, mmap=True) except Exception as ex: logger.warning(ex) logger.warning("Unable to read wav with memmory mapping. Try...
0.00625
def fromrdd(rdd, dims=None, nrecords=None, dtype=None, labels=None, ordered=False): """ Load images from a Spark RDD. Input RDD must be a collection of key-value pairs where keys are singleton tuples indexing images, and values are 2d or 3d ndarrays. Parameters ---------- rdd : SparkRD...
0.00208
def get_nlcd_fn(): """Calls external shell script `get_nlcd.sh` to fetch: 2011 Land Use Land Cover (nlcd) grids, 30 m http://www.mrlc.gov/nlcd11_leg.php """ #This is original filename, which requires ~17 GB #nlcd_fn = os.path.join(datadir, 'nlcd_2011_landcover_2011_edition_2014_10_10/nlcd_...
0.012376
def inject_documentation(**options): """ Generate configuration documentation in reStructuredText_ syntax. :param options: Any keyword arguments are passed on to the :class:`ConfigLoader` initializer. This methods injects the generated documentation into the output generated by...
0.002058
def start(self): """ Start the daemon """ # Check for a pidfile to see if the daemon already runs try: pf = file(self.pidfile, 'r') pid = int(pf.read().strip()) pf.close() os.kill(pid, 0) except IOError: pid = No...
0.003373
def validate(self): """ Validates that all required fields are present """ if not self.start: raise ValueError("Event has no start date") if not self.end: raise ValueError("Event has no end date") if self.end < self.start: raise ValueError("Start date is after end date") if self...
0.011475
def setMethod(self, method, override_analyses=False): """ Sets the specified method to the Analyses from the Worksheet. Only sets the method if the Analysis allows to keep the integrity. If an analysis has already been assigned to a method, it won't be overriden. ...
0.002217
def _getitem(item, i): """Extract value or values from dicts. Covers the case of a single key or multiple keys. If not found, return placeholders instead. """ if not isinstance(i, (tuple, list)): return item.get(i, _none) type_ = list if isinstance(item, list) else tuple return typ...
0.002833
def remove_nondescendants_of(self, node): """Remove all of the non-descendants operation nodes of node.""" if isinstance(node, int): warnings.warn('Calling remove_nondescendants_of() with a node id is deprecated,' ' use a DAGNode instead', ...
0.005042
def nanvar(values, axis=None, skipna=True, ddof=1, mask=None): """ Compute the variance along given axis while ignoring NaNs Parameters ---------- values : ndarray axis: int, optional skipna : bool, default True ddof : int, default 1 Delta Degrees of Freedom. The divisor used in...
0.000482
def get_query_kwargs(es_defs): """ Reads the es_defs and returns a dict of special kwargs to use when query for data of an instance of a class reference: rdfframework.sparl.queries.sparqlAllItemDataTemplate.rq """ rtn_dict = {} if es_defs: if es_defs.get("kds_esSpecialUnion"): ...
0.001779
def load_cifar10_dataset(cifar_dir, mode='supervised'): """Load the cifar10 dataset. :param cifar_dir: path to the dataset directory (cPicle format from: https://www.cs.toronto.edu/~kriz/cifar.html) :param mode: 'supervised' or 'unsupervised' mode :return: train, test data: for (X,...
0.000712
def provides(arg_name=None, annotated_with=None, in_scope=None): """Modifies the binding of a provider method. If arg_name is specified, then the created binding is for that arg name instead of the one gotten from the provider method name (e.g., 'foo' from 'provide_foo'). If annotated_with is spec...
0.001601
def load_json(self): """Load JSON from the request body and store them in self.request.arguments, like Tornado does by default for POSTed form parameters. If JSON cannot be decoded :raises ValueError: JSON Could not be decoded """ try: self.request.a...
0.003795
def from_env(parser_modules: t.Optional[t.Union[t.List[str], t.Tuple[str]]] = DEFAULT_PARSER_MODULES, env: t.Optional[t.Dict[str, str]] = None, silent: bool = False, suppress_logs: bool = False, extra: t.Optional[dict] = None) -> 'ConfigLoader': ...
0.006333
def untrain_token(self, word, count): """ Untrains a particular token (decreases the weight/count of it) :param word: the token we're going to train :type word: str :param count: the number of occurances in the sample :type count: int """ if word not in s...
0.003731
def quaternion_about_axis(angle, axis): """Return quaternion for rotation about axis. >>> q = quaternion_about_axis(0.123, [1, 0, 0]) >>> np.allclose(q, [0.99810947, 0.06146124, 0, 0]) True """ q = np.array([0.0, axis[0], axis[1], axis[2]]) qlen = vector_norm(q) if qlen > _EPS: ...
0.0025
def decrypt_get_item(decrypt_method, crypto_config_method, read_method, **kwargs): # type: (Callable, Callable, Callable, **Any) -> Dict # TODO: narrow this down """Transparently decrypt an item after getting it from the table. :param callable decrypt_method: Method to use to decrypt item :param ca...
0.004073
def check_rdd_dtype(rdd, expected_dtype): """Checks if the blocks in the RDD matches the expected types. Parameters: ----------- rdd: splearn.BlockRDD The RDD to check expected_dtype: {type, list of types, tuple of types, dict of types} Expected type(s). If the RDD is a DictRDD the ...
0.000765
def parse(self, buf): '''parse a FD FDM buffer''' try: t = struct.unpack(self.pack_string, buf) except struct.error as msg: raise fgFDMError('unable to parse - %s' % msg) self.values = list(t)
0.008065
def _hour_angle_to_hours(times, hourangle, longitude, equation_of_time): """converts hour angles in degrees to hours as a numpy array""" naive_times = times.tz_localize(None) # naive but still localized tzs = 1 / NS_PER_HR * ( naive_times.astype(np.int64) - times.astype(np.int64)) hours = (hour...
0.002445
def is_merc_projection(srs): """ Return true if the map projection matches that used by VEarth, Google, OSM, etc. Is currently necessary for zoom-level shorthand for scale-denominator. """ if srs.lower() == '+init=epsg:900913': return True # observed srs = dict([p.split('=') fo...
0.007585
def remove(self, **kwargs): ''' :raises: :exc:`~dxpy.exceptions.DXError` if no project is associated with the object Permanently removes the associated remote object from the associated project. ''' if self._proj is None: raise DXError("Remove called when a ...
0.006515
def notes_master_part(self): """ Return the |NotesMasterPart| object for this presentation. If the presentation does not have a notes master, one is created from a default template. The same single instance is returned on each call. """ try: return sel...
0.003597
def start(self): """Begin listening for events from the Client and acting upon them. Note: If configuration has not already been loaded, it will be loaded immediately before starting to listen for events. Calling this method without having specified and/or loaded a configuration will re...
0.003008
def delete_pool(hostname, username, password, name): ''' Delete an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool which will be deleted ''' re...
0.001971
def parse_data(self, selected_region_data, selected_values, full_load=False, extension="gdm"): """ Parses all of the region data :param selected_region_data: the columns of region data that are needed :param selected_values: the selected values to be put in the matrix cells :para...
0.006361
def trace_region(self, region_index): """Retrieves the properties of a trace region. Args: self (JLink): the ``JLink`` instance. region_index (int): the trace region index. Returns: An instance of ``JLinkTraceRegion`` describing the specified region. """ ...
0.003044
def create(self, vips): """ Method to create vip's :param vips: List containing vip's desired to be created on database :return: None """ data = {'vips': vips} return super(ApiVipRequest, self).post('api/v3/vip-request/', data)
0.007018
def register_regex_entity(self, regex_str, domain=0): """ A regular expression making use of python named group expressions. Example: (?P<Artist>.*) Args: regex_str(str): a string representing a regular expression as defined above domain(str): a string represent...
0.007477
def container_fabric(container_maps=None, docker_client=None, clients=None, client_implementation=None): """ :param container_maps: Container map or a tuple / list thereof. :type container_maps: list[dockermap.map.config.main.ContainerMap] | dockermap.map.config.main.ContainerMap :param docker_client: D...
0.005046
def set_sequestered(self, sequestered): """Sets the sequestered flag. arg: sequestered (boolean): the new sequestered flag raise: InvalidArgument - ``sequestered`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must ...
0.003053
def ensure_str(data: Union[str, bytes]) -> str: """ Convert data in str if data are bytes :param data: Data :rtype str: """ if isinstance(data, bytes): return str(data, 'utf-8') return data
0.004405
def height(cls, path): """ Get the locally-stored block height """ if os.path.exists( path ): sb = os.stat( path ) h = (sb.st_size / BLOCK_HEADER_SIZE) - 1 return h else: return None
0.022222
def findNext(self, name=None, attrs={}, text=None, **kwargs): """Returns the first item that matches the given criteria and appears after this Tag in the document.""" return self._findOne(self.findAllNext, name, attrs, text, **kwargs)
0.007752
def slicenet_internal(inputs, targets, target_space, hparams, run_decoder=True): """The slicenet model, main step used for training.""" with tf.variable_scope("slicenet"): # Project to hidden size if necessary if inputs.get_shape().as_list()[-1] != hparams.hidden_size: inputs = common_layers.conv_bloc...
0.004202
def beacon(config): ''' Poll imgadm and compare available images ''' ret = [] # NOTE: lookup current images current_images = __salt__['imgadm.list'](verbose=True) # NOTE: apply configuration if IMGADM_STATE['first_run']: log.info('Applying configuration for imgadm beacon') ...
0.001425
def find_next_word_ending(self, include_current_position=False, count=1, WORD=False): """ Return an index relative to the cursor position pointing to the end of the next word. Return `None` if nothing was found. """ if count < 0: return self.find_previous_word_ending(...
0.003236
def base(self, du): """Return the base CLB for a given DU""" parameter = 'base' if parameter not in self._by: self._by[parameter] = {} for clb in self.upi.values(): if clb.floor == 0: self._by[parameter][clb.du] = clb return sel...
0.005882
def download_url_with_progress(url, stream, disable_progress): """ Downloads a given url in chunks and writes to the provided stream (can be any io stream). Displays the progress bar for the download. """ resp = requests.get(url, timeout=float(os.environ.get('PIP_TIMEOUT', 2)), s...
0.007321
def split_value(val): """ Splits a value *val* into its significand and decimal exponent (magnitude) and returns them in a 2-tuple. *val* might also be a numpy array. Example: .. code-block:: python split_value(1) # -> (1.0, 0) split_value(0.123) # -> (1.23, -1) split_value...
0.002899
def save(self, identifier=None, is_best=False, save_all=False): """ Stores checkpoint to a file. :param identifier: identifier for periodic checkpoint :param is_best: if True stores checkpoint to 'model_best.pth' :param save_all: if True stores checkpoint after completed trainin...
0.001407
def unduplicate_field_names(field_names): """Append a number to duplicate field names to make them unique. """ res = [] for k in field_names: if k in res: i = 1 while k + '_' + str(i) in res: i += 1 k += '_' + str(i) res.append(k) retur...
0.003077
def QA_indicator_SKDJ(DataFrame, N=9, M=3): """ 1.指标>80 时,回档机率大;指标<20 时,反弹机率大; 2.K在20左右向上交叉D时,视为买进信号参考; 3.K在80左右向下交叉D时,视为卖出信号参考; 4.SKDJ波动于50左右的任何讯号,其作用不大。 """ CLOSE = DataFrame['close'] LOWV = LLV(DataFrame['low'], N) HIGHV = HHV(DataFrame['high'], N) RSV = EMA((CLOSE - LOWV) /...
0.00432
def connect_get_namespaced_pod_portforward(self, name, namespace, **kwargs): # noqa: E501 """connect_get_namespaced_pod_portforward # noqa: E501 connect GET requests to portforward of Pod # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HT...
0.001576
def _parse_conf(conf_file=_DEFAULT_CONF): ''' Parse a logrotate configuration file. Includes will also be parsed, and their configuration will be stored in the return dict, as if they were part of the main config file. A dict of which configs came from which includes will be stored in the 'include ...
0.000428
def camelize(word): """Convert a word from lower_with_underscores to CamelCase. Args: word: The string to convert. Returns: The modified string. """ return ''.join(w[0].upper() + w[1:] for w in re.sub('[^A-Z^a-z^0-9^:]+', ' ', word).split(' '))
0.003333
def browse(self, endpoint="hot", category_path="", seed="", q="", timerange="24hr", tag="", offset=0, limit=10): """Fetch deviations from public endpoints :param endpoint: The endpoint from which the deviations will be fetched (hot/morelikethis/newest/undiscovered/popular/tags) :param category...
0.011236
def dist(self, src, tar): """Return the NCD between two strings using bzip2 compression. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison Returns ------- float Compres...
0.001709
def begin_update(self, x_data, h_0=None, drop=0.0): """Return the output of the wrapped PyTorch model for the given input, along with a callback to handle the backward pass. """ x_var = torch.autograd.Variable(xp2torch(x_data), requires_grad=True) # Make prediction out, ...
0.001976
def blobs(shape: List[int], porosity: float = 0.5, blobiness: int = 1): """ Generates an image containing amorphous blobs Parameters ---------- shape : list The size of the image to generate in [Nx, Ny, Nz] where N is the number of voxels porosity : float If specified, ...
0.000769
def play_list_detail(id, limit=20): """获取歌单中的所有音乐。由于获取精品中,只能看到歌单名字和 ID 并没有歌单的音乐,因此增加该接口传入歌单 ID 获取歌单中的所有音乐. :param id: 歌单的ID :param limit: (optional) 数据上限多少行,默认 20 """ if id is None: raise ParamsError() r = NCloudBot() r.method = 'PLAY_LIST_DETAIL' r.data = {'id': id, 'limit'...
0.002618