code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def pickle_dumps(self, protocol=None): """ Return a string with the pickle representation. `protocol` selects the pickle protocol. self.pickle_protocol is used if `protocol` is None """ strio = StringIO() pmg_pickle_dump(self, strio, proto...
Return a string with the pickle representation. `protocol` selects the pickle protocol. self.pickle_protocol is used if `protocol` is None
async def message_data(request): """ As an example of aiohttp providing a non-html response, we load the actual messages for the "messages" view above via ajax using this endpoint to get data. see static/message_display.js for details of rendering. """ messages = [] # {% if database.is_none %} ...
As an example of aiohttp providing a non-html response, we load the actual messages for the "messages" view above via ajax using this endpoint to get data. see static/message_display.js for details of rendering.
def cache_file(package, mode): """ Yields a file-like object for the purpose of writing to or reading from the cache. The code: with cache_file(...) as f: # do stuff with f is guaranteed to convert any exceptions to warnings (*), both in the cache_file(...) call and the 'd...
Yields a file-like object for the purpose of writing to or reading from the cache. The code: with cache_file(...) as f: # do stuff with f is guaranteed to convert any exceptions to warnings (*), both in the cache_file(...) call and the 'do stuff with f' block. The file is...
def deserialize(doc_xml, pyxb_binding=None): """Deserialize DataONE XML types to PyXB. Args: doc_xml: UTF-8 encoded ``bytes`` pyxb_binding: PyXB binding object. If not specified, the correct one should be selected automatically. Returns: PyXB object See Also: ``deserial...
Deserialize DataONE XML types to PyXB. Args: doc_xml: UTF-8 encoded ``bytes`` pyxb_binding: PyXB binding object. If not specified, the correct one should be selected automatically. Returns: PyXB object See Also: ``deserialize_d1_exception()`` for deserializing DataONE Excep...
def _validate_value(self, proposal): "Replace all values with the actual objects in the options list" try: return tuple(findvalue(self._options_values, i, self.equals) for i in proposal.value) except ValueError: raise TraitError('Invalid selection: value not found')
Replace all values with the actual objects in the options list
def get_seq_seq(self,obj,default=None): """Return sequence of sequences.""" if is_sequence2(obj): return [self.get_seq(o,default) for o in obj] else: return [self.get_seq(obj,default)]
Return sequence of sequences.
def _create(cls, configuration=None, remoteckan=None, **kwargs): # type: (Optional['Configuration'], Optional[ckanapi.RemoteCKAN], Any) -> str """ Create HDX configuration Args: configuration (Optional[Configuration]): Configuration instance. Defaults to setting one up from ...
Create HDX configuration Args: configuration (Optional[Configuration]): Configuration instance. Defaults to setting one up from passed arguments. remoteckan (Optional[ckanapi.RemoteCKAN]): CKAN instance. Defaults to setting one up from configuration. **kwargs: See below ...
def _put_resource(self, url, body): """ When I Work PUT method. """ headers = {"Content-Type": "application/json", "Accept": "application/json"} if self.token: headers["W-Token"] = "%s" % self.token response = WhenIWork_DAO().putURL(url, hea...
When I Work PUT method.
def get_player_summaries(players, **kwargs): """ Get players steam profile from their steam ids """ if (isinstance(players, list)): params = {'steamids': ','.join(str(p) for p in players)} elif (isinstance(players, int)): params = {'steamids': players} else: raise ValueEr...
Get players steam profile from their steam ids
def filter_publication(publication, cache=_CACHE): """ Deduplication function, which compares `publication` with samples stored in `cache`. If the match NOT is found, `publication` is returned, else None. Args: publication (obj): :class:`.Publication` instance. cache (obj): Cache which ...
Deduplication function, which compares `publication` with samples stored in `cache`. If the match NOT is found, `publication` is returned, else None. Args: publication (obj): :class:`.Publication` instance. cache (obj): Cache which is used for lookups. Returns: obj/None: Depends wh...
def get_image_file_path(instance, filename): """Returns a unique filename for images.""" ext = filename.split('.')[-1] filename = '%s.%s' % (uuid.uuid4(), ext) return os.path.join( 'user_media', str(instance.user.pk), 'images', filename)
Returns a unique filename for images.
def _prepare(self): """Builds a URL and return a PreparedRequest. Returns (requests.PreparedRequest) Raises UberIllegalState (APIError) """ if self.method not in http.ALLOWED_METHODS: raise UberIllegalState('Unsupported HTTP Method.') ...
Builds a URL and return a PreparedRequest. Returns (requests.PreparedRequest) Raises UberIllegalState (APIError)
def check_action_type(self, value): """Set the value for the CheckActionType, validating input""" if value is not None: if not isinstance(value, ActionType): raise AttributeError("Invalid check action %s" % value) self._check_action_type = value
Set the value for the CheckActionType, validating input
def get_all_projects(url, token, top=HARD_CODED_TOP): """ Returns a list of all projects with their collection info from the server. Currently limited functionality to only return the first 1000 projects. #TODO refactor to add multiple calls to api to retrieve all projects if more exist beyond top. """ ...
Returns a list of all projects with their collection info from the server. Currently limited functionality to only return the first 1000 projects. #TODO refactor to add multiple calls to api to retrieve all projects if more exist beyond top.
def extract_features(self, dataset, feature, batch_size=64, verbose=False): """ Parameters ---------- dataset: SFrame SFrame of images """ from ._mxnet._mx_sframe_iter import SFrameImageIter as _SFrameImageIter from six.moves.queue import Queue as _Que...
Parameters ---------- dataset: SFrame SFrame of images
def get_object(self, queryset=None): """ Fetch the object using a translated slug. """ if queryset is None: queryset = self.get_queryset() slug = self.kwargs[self.slug_url_kwarg] choices = self.get_language_choices() obj = None using_fallback...
Fetch the object using a translated slug.
def connect(self, src, dst=None, callback=None): ''' :param src: source node, if dst is None it will be destination node and the root (dummy) node will be source :param dst: destination node (default: None) :type callback: func(fuzzer, edge, response) -> None :param callback: a f...
:param src: source node, if dst is None it will be destination node and the root (dummy) node will be source :param dst: destination node (default: None) :type callback: func(fuzzer, edge, response) -> None :param callback: a function to be called after the response for src received and before d...
def _start_local_queue_process(self): """ TODO: docstring """ comm_q = Queue(maxsize=10) self.queue_proc = Process(target=interchange.starter, args=(comm_q,), kwargs={"client_ports": (self.outgoing_q.port, ...
TODO: docstring
def filter_by_background(in_vcf, full_vcf, background, data): """Filter SV calls also present in background samples. Skips filtering of inversions, which are not characterized differently between cases and controls in test datasets. """ Filter = collections.namedtuple('Filter', ['id', 'desc']) ...
Filter SV calls also present in background samples. Skips filtering of inversions, which are not characterized differently between cases and controls in test datasets.
def n1qlQueryAll(self, *args, **kwargs): """ Execute a N1QL query, retrieving all rows. This method returns a :class:`Deferred` object which is executed with a :class:`~.N1QLRequest` object. The object may be iterated over to yield the rows in the result set. This metho...
Execute a N1QL query, retrieving all rows. This method returns a :class:`Deferred` object which is executed with a :class:`~.N1QLRequest` object. The object may be iterated over to yield the rows in the result set. This method is similar to :meth:`~couchbase.bucket.Bucket.n1ql_query` ...
def _get_reg_software(include_components=True, include_updates=True): ''' This searches the uninstall keys in the registry to find a match in the sub keys, it will return a dict with the display name as the key and the version as the value Args: include_components (bo...
This searches the uninstall keys in the registry to find a match in the sub keys, it will return a dict with the display name as the key and the version as the value Args: include_components (bool): Include sub components of installed software. Default is ``True`` include_upda...
def ingest_resources(mapping, schema_dir): """Consume the Swagger schemas and produce a queryable datastructure. :param mapping: Map from resource name to filepath of its api declaration :type mapping: dict :param schema_dir: the directory schema files live inside :type schema_dir: string :retu...
Consume the Swagger schemas and produce a queryable datastructure. :param mapping: Map from resource name to filepath of its api declaration :type mapping: dict :param schema_dir: the directory schema files live inside :type schema_dir: string :returns: A list of mapping from :class:`RequestMatcher...
def set_branch_capacity(network, args): """ Set branch capacity factor of lines and transformers, different factors for HV (110kV) and eHV (220kV, 380kV). Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA args: dict Settings in appl.py ""...
Set branch capacity factor of lines and transformers, different factors for HV (110kV) and eHV (220kV, 380kV). Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA args: dict Settings in appl.py
def line_on_device( device: 'cirq.google.XmonDevice', length: int, method: LinePlacementStrategy = greedy.GreedySequenceSearchStrategy() ) -> GridQubitLineTuple: """Searches for linear sequence of qubits on device. Args: device: Google Xmon device instance. length: Desir...
Searches for linear sequence of qubits on device. Args: device: Google Xmon device instance. length: Desired number of qubits making up the line. method: Line placement method. Defaults to cirq.greedy.GreedySequenceSearchMethod. Returns: Line sequences search re...
def get_object(self, path): """Get single object.""" key = self.native_container.get_key(path) return self.obj_cls.from_key(self, key)
Get single object.
def remote_command(session, command, vehicle_index, poll=True): """Send a remote command.""" if command not in SUPPORTED_COMMANDS: raise MoparError("unsupported command: " + command) profile = get_profile(session) _validate_vehicle(vehicle_index, profile) if command in [COMMAND_LOCK, COMMAND...
Send a remote command.
def _calculate_osdb_hash(self): """ Calculate OSDB (OpenSubtitleDataBase) hash of this VideoFile :return: hash as string """ log.debug('_calculate_OSDB_hash() of "{path}" ...'.format(path=self._filepath)) f = self._filepath.open(mode='rb') file_size = self.get_si...
Calculate OSDB (OpenSubtitleDataBase) hash of this VideoFile :return: hash as string
def get_subscribers(object_type: str) -> List[str]: """Get the list of subscribers to events of the object type. Args: object_type (str): Type of object. Returns: List[str], list of subscriber names. """ return DB.get_list(_keys.subscribers(object_type))
Get the list of subscribers to events of the object type. Args: object_type (str): Type of object. Returns: List[str], list of subscriber names.
def property_pickled(f): """Same thing as above but the result will be stored on disk The path of the pickle file will be determined by looking for the `cache_dir` attribute of the instance containing the cached property. If no `cache_dir` attribute exists the `p` attribute will be accessed with the...
Same thing as above but the result will be stored on disk The path of the pickle file will be determined by looking for the `cache_dir` attribute of the instance containing the cached property. If no `cache_dir` attribute exists the `p` attribute will be accessed with the name of the property being cach...
async def lookup(client: Client, search: str) -> dict: """ GET UID/Public key data :param client: Client to connect to the api :param search: UID or public key :return: """ return await client.get(MODULE + '/lookup/%s' % search, schema=LOOKUP_SCHEMA)
GET UID/Public key data :param client: Client to connect to the api :param search: UID or public key :return:
def dump_limits(conf_file, limits_file, debug=False): """ Dump the current limits from the Redis database. :param conf_file: Name of the configuration file, for connecting to the Redis database. :param limits_file: Name of the XML file that the limits will be ...
Dump the current limits from the Redis database. :param conf_file: Name of the configuration file, for connecting to the Redis database. :param limits_file: Name of the XML file that the limits will be dumped to. Use '-' to dump to stdout. :param debug: If Tru...
def _characterize_header(self, header, hgroups): """Characterize header groups into different data types. """ out = [] for h in [header[g[0]] for g in hgroups]: this_ctype = None for ctype, names in self._col_types.items(): if h.startswith(names): ...
Characterize header groups into different data types.
def getInterval(self, alpha): """ Evaluate the interval corresponding to a C.L. of (1-alpha)%. Parameters ---------- alpha : limit confidence level. """ dlnl = twosided_cl_to_dlnl(1.0 - alpha) lo_lim = self.getDeltaLogLike(dlnl, upper=False) hi_lim = self...
Evaluate the interval corresponding to a C.L. of (1-alpha)%. Parameters ---------- alpha : limit confidence level.
def _drawContents(self, reason=None, initiator=None): """ Draws the plot contents from the sliced array of the collected repo tree item. The reason parameter is used to determine if the axes will be reset (the initiator parameter is ignored). See AbstractInspector.updateContents for the...
Draws the plot contents from the sliced array of the collected repo tree item. The reason parameter is used to determine if the axes will be reset (the initiator parameter is ignored). See AbstractInspector.updateContents for their description.
def _encode_datetime(name, value, dummy0, dummy1): """Encode datetime.datetime.""" millis = _datetime_to_millis(value) return b"\x09" + name + _PACK_LONG(millis)
Encode datetime.datetime.
def filter_format(filter_template, assertion_values): """ filter_template String containing %s as placeholder for assertion values. assertion_values List or tuple of assertion values. Length must match count of %s in filter_template. """ assert isinstance(filter_templat...
filter_template String containing %s as placeholder for assertion values. assertion_values List or tuple of assertion values. Length must match count of %s in filter_template.
def plot_prh_des_asc(p, r, h, asc, des): '''Plot pitch, roll, and heading during the descent and ascent dive phases Args ---- p: ndarray Derived pitch data r: ndarray Derived roll data h: ndarray Derived heading data des: ndarray boolean mask for slicing desc...
Plot pitch, roll, and heading during the descent and ascent dive phases Args ---- p: ndarray Derived pitch data r: ndarray Derived roll data h: ndarray Derived heading data des: ndarray boolean mask for slicing descent phases of dives from tag dta asc: ndarra...
def from_config(config): """ Creates new Parameters from ConfigMap object. :param config: a ConfigParams that contain parameters. :return: a new Parameters object. """ result = Parameters() if config == None or len(config) == 0: return resul...
Creates new Parameters from ConfigMap object. :param config: a ConfigParams that contain parameters. :return: a new Parameters object.
def render(self): """Render this page and return the rendition. Converts the markdown content to html, and then renders the (mako) template specified in the config, using that html. The task of writing of the rendition to a real file is responsibility of the generate method. ...
Render this page and return the rendition. Converts the markdown content to html, and then renders the (mako) template specified in the config, using that html. The task of writing of the rendition to a real file is responsibility of the generate method.
def _is_modification_or_activity(feature): """Return True if the feature is a modification""" if not (isinstance(feature, _bp('ModificationFeature')) or \ isinstance(feature, _bpimpl('ModificationFeature'))): return None mf_type = feature.getModificationType() if mf_type is None: ...
Return True if the feature is a modification
def contains(self, token: str) -> bool: """Return if the token is in the list or not.""" self._validate_token(token) return token in self
Return if the token is in the list or not.
def _replace_link_brackets(msg_body): """ Normalize links i.e. replace '<', '>' wrapping the link with some symbols so that '>' closing the link couldn't be mistakenly taken for quotation marker. Converts msg_body into a unicode """ if isinstance(msg_body, bytes): msg_body = msg_bod...
Normalize links i.e. replace '<', '>' wrapping the link with some symbols so that '>' closing the link couldn't be mistakenly taken for quotation marker. Converts msg_body into a unicode
def get_backend_name(self, location): """ Return the name of the version control backend if found at given location, e.g. vcs.get_backend_name('/path/to/vcs/checkout') """ for vc_type in self._registry.values(): logger.debug('Checking in %s for %s (%s)...', ...
Return the name of the version control backend if found at given location, e.g. vcs.get_backend_name('/path/to/vcs/checkout')
def evaluate_topic_models(data, varying_parameters, constant_parameters=None, n_max_processes=None, return_models=False, metric=None, **metric_kwargs): """ Compute several Topic Models in parallel using the "lda" package. Calculate the models using a list of varying parameters `var...
Compute several Topic Models in parallel using the "lda" package. Calculate the models using a list of varying parameters `varying_parameters` on a single Document-Term-Matrix `data`. Pass parameters in `constant_parameters` dict to each model calculation. Use at maximum `n_max_processes` processors or use all ...
def delkey(ctx, pubkeys): """ Delete a private key from the wallet """ if not pubkeys: pubkeys = click.prompt("Public Keys").split(" ") if click.confirm( "Are you sure you want to delete keys from your wallet?\n" "This step is IRREVERSIBLE! If you don't have a backup, " "...
Delete a private key from the wallet
def get_work_item_type_field_with_references(self, project, type, field, expand=None): """GetWorkItemTypeFieldWithReferences. [Preview API] Get a field for a work item type with detailed references. :param str project: Project ID or project name :param str type: Work item type. :...
GetWorkItemTypeFieldWithReferences. [Preview API] Get a field for a work item type with detailed references. :param str project: Project ID or project name :param str type: Work item type. :param str field: :param str expand: Expand level for the API response. Properties: to incl...
def get_metadata(audio_filepaths): """ Return a tuple of album, artist, has_embedded_album_art from a list of audio files. """ artist, album, has_embedded_album_art = None, None, None for audio_filepath in audio_filepaths: try: mf = mutagen.File(audio_filepath) except Exception: continue i...
Return a tuple of album, artist, has_embedded_album_art from a list of audio files.
def StopToTuple(stop): """Return tuple as expected by javascript function addStopMarkerFromList""" return (stop.stop_id, stop.stop_name, float(stop.stop_lat), float(stop.stop_lon), stop.location_type)
Return tuple as expected by javascript function addStopMarkerFromList
def is_ready(self): """Check if the current model is ready to be used.""" if not self.provisioning_state: raise exception.ServiceException("The object doesn't contain " "`provisioningState`.") elif self.provisioning_state == constant.FAILE...
Check if the current model is ready to be used.
def _class_dispatch(args, kwargs): """See 'class_multimethod'.""" _ = kwargs if not args: raise ValueError( "Multimethods must be passed at least one positional arg.") if not isinstance(args[0], type): raise TypeError( "class_multimethod must be called with a typ...
See 'class_multimethod'.
def from_phononwfkq_work(cls, phononwfkq_work, nscf_vars={}, remove_wfkq=True, with_ddk=True, manager=None): """ Construct a `GKKPWork` from a `PhononWfkqWork` object. The WFQ are the ones used for PhononWfkqWork so in principle have only valence bands """ # Get list of qpoints f...
Construct a `GKKPWork` from a `PhononWfkqWork` object. The WFQ are the ones used for PhononWfkqWork so in principle have only valence bands
def split_locator(self, path): """ Split the path into a pair (locator, path). args: path (str): Absolute path or URL. Returns: tuple of str: locator, path. """ relative = self.relpath(path) try: locator, tail = relative.split...
Split the path into a pair (locator, path). args: path (str): Absolute path or URL. Returns: tuple of str: locator, path.
def _get_internal_min_value(self): """ This is supposed to be only used by fitting engines to get the minimum value in internal representation. It is supposed to be called only once before doing the minimization/sampling, to set the range of the parameter :return: minimum value in inter...
This is supposed to be only used by fitting engines to get the minimum value in internal representation. It is supposed to be called only once before doing the minimization/sampling, to set the range of the parameter :return: minimum value in internal representation (or None if there is no minimum)
def stop_process(self): """ Stops the child process. """ self._process.terminate() if not self._process.waitForFinished(100): self._process.kill()
Stops the child process.
def report_changes(self, content): """ 1) Write changes in file, 2) Commit changes in git 3.1) If something changed, return tuple(True, changes) 3.2) If nothing changed, return tuple(False, None) If style is "verbose", return changes in human-friendly format, els...
1) Write changes in file, 2) Commit changes in git 3.1) If something changed, return tuple(True, changes) 3.2) If nothing changed, return tuple(False, None) If style is "verbose", return changes in human-friendly format, else use unified diff
def installed(): """ Returns whether or not Google Chrome is installed Determines the application data path for Google Chrome and checks if the path exists. If so, returns True, otherwise it will return False. Returns bool - True if Chrome is insta...
Returns whether or not Google Chrome is installed Determines the application data path for Google Chrome and checks if the path exists. If so, returns True, otherwise it will return False. Returns bool - True if Chrome is installed
def snapshot_registry(self): ''' Give the dictionary of recorders detached from the existing instances. It is safe to store those references for future use. Used by feattool. ''' unserializer = banana.Unserializer(externalizer=self) serializer = banana.Serializer(external...
Give the dictionary of recorders detached from the existing instances. It is safe to store those references for future use. Used by feattool.
def get_song_urls(song_input): """ Gather all urls, titles for a search query from youtube """ YOUTUBECLASS = 'spf-prefetch' html = requests.get("https://www.youtube.com/results", params={'search_query': song_input}) soup = BeautifulSoup(html.text, 'html.parser') ...
Gather all urls, titles for a search query from youtube
def diff_objects(self, latest_commit_sha): """ Push all changes to origin, based on objects, not on commits. Important: Call this push after every new commit, or we lose commits. """ base = ['git', '--bare', '--git-dir', self.git_path] object_shas...
Push all changes to origin, based on objects, not on commits. Important: Call this push after every new commit, or we lose commits.
def annotate(args): """ %prog annotate coordsfile Annotate coordsfile to append an additional column, with the following overlaps: {0}. """ p = OptionParser(annotate.__doc__.format(", ".join(Overlap_types))) p.add_option("--maxhang", default=100, type="int", help="Max hang ...
%prog annotate coordsfile Annotate coordsfile to append an additional column, with the following overlaps: {0}.
def _get_dest(*args, **kwargs): # pragma: no cover """ Duplicate argument names processing logic from argparse. argparse stores the variable in the namespace using the provided dest name, the first long option string, or the first short option string """ prefix_chars = kwargs.get('prefix_char...
Duplicate argument names processing logic from argparse. argparse stores the variable in the namespace using the provided dest name, the first long option string, or the first short option string
def standings(date=datetime.now()): """Return Standings object that contains standings info date should be a datetime object, leave empty to get current standings """ data = mlbgame.info.standings(date) return mlbgame.info.Standings(data)
Return Standings object that contains standings info date should be a datetime object, leave empty to get current standings
def execute(self, jvm_options=None, args=None, executor=None, workunit_factory=None, workunit_name=None, workunit_labels=None): """Executes the ivy commandline client with the given args. Raises Ivy.Error if the command fails for any reason. :param executor: Java executor to run ivy with. ...
Executes the ivy commandline client with the given args. Raises Ivy.Error if the command fails for any reason. :param executor: Java executor to run ivy with.
def _environment_variables(**kwargs): # type: (Any) -> Any """ Overwrite keyword arguments with environment variables Args: **kwargs: See below user_agent (str): User agent string. Returns: kwargs: Changed keyword arguments """ ...
Overwrite keyword arguments with environment variables Args: **kwargs: See below user_agent (str): User agent string. Returns: kwargs: Changed keyword arguments
def update_quota(self, quota_info, error=None): '''更新网盘容量信息''' if not quota_info or quota_info['errno'] != 0: return used = quota_info['used'] total = quota_info['total'] used_size = util.get_human_size(used)[0] total_size = util.get_human_size(total)[0] ...
更新网盘容量信息
def use_any_status_sequence_rule_view(self): """Pass through to provider SequenceRuleLookupSession.use_any_status_sequence_rule_view""" self._operable_views['sequence_rule'] = ANY_STATUS # self._get_provider_session('sequence_rule_lookup_session') # To make sure the session is tracked f...
Pass through to provider SequenceRuleLookupSession.use_any_status_sequence_rule_view
def url_for(self, entity=None, object_type=None, object_id=None, **kwargs): """Return canonical view URL for given entity instance. If no view has been registered the registry will try to find an endpoint named with entity's class lowercased followed by '.view' and that accepts `object_...
Return canonical view URL for given entity instance. If no view has been registered the registry will try to find an endpoint named with entity's class lowercased followed by '.view' and that accepts `object_id=entity.id` to generates an url. :param entity: a instance of a subclass of ...
def _clear_cache_synthesizer(self): """ Clear the cache of the synthesizer """ self.log(u"Clearing synthesizer...") self.synthesizer.clear_cache() self.log(u"Clearing synthesizer... done")
Clear the cache of the synthesizer
def set_widgets(self): """Set widgets on the Aggregation Layer from Canvas tab.""" # The list is already populated in the previous step, but now we # need to do it again in case we're back from the Keyword Wizard. # First, preserve self.parent.layer before clearing the list last_...
Set widgets on the Aggregation Layer from Canvas tab.
def asyncImap(asyncCallable, *iterables): """itertools.imap for deferred callables """ deferreds = imap(asyncCallable, *iterables) return gatherResults(deferreds, consumeErrors=True)
itertools.imap for deferred callables
def _fake_openenumerateinstancepaths(self, namespace, **params): # pylint: disable=invalid-name """ Implements WBEM server responder for :meth:`~pywbem.WBEMConnection.OpenEnumerationInstancePaths` with data from the instance repository. """ self._validate_namespac...
Implements WBEM server responder for :meth:`~pywbem.WBEMConnection.OpenEnumerationInstancePaths` with data from the instance repository.
def com_find(ar_grid): """ Find the center of mass in array grid <ar_grid>. Mass elements are grid index values. Return an array, in format (x, y), i.e. col, row! """ f_x = 0 f_y = 0 f_m = 0 for i in range(len(ar_grid)): for j in range(len(ar_grid[i])): if ar_grid[i...
Find the center of mass in array grid <ar_grid>. Mass elements are grid index values. Return an array, in format (x, y), i.e. col, row!
async def release_forks(self, philosopher): '''The ``philosopher`` has just eaten and is ready to release both forks. This method releases them, one by one, by sending the ``put_down`` action to the monitor. ''' forks = self.forks self.forks = [] self.sta...
The ``philosopher`` has just eaten and is ready to release both forks. This method releases them, one by one, by sending the ``put_down`` action to the monitor.
def process_lpd(name, dir_tmp): """ Opens up json file, invokes doi_resolver, closes file, updates changelog, cleans directory, and makes new bag. :param str name: Name of current .lpd file :param str dir_tmp: Path to tmp directory :return none: """ logger_doi_main.info("enter process_lpd") ...
Opens up json file, invokes doi_resolver, closes file, updates changelog, cleans directory, and makes new bag. :param str name: Name of current .lpd file :param str dir_tmp: Path to tmp directory :return none:
def _Region1(T, P): """Basic equation for region 1 Parameters ---------- T : float Temperature, [K] P : float Pressure, [MPa] Returns ------- prop : dict Dict with calculated properties. The available properties are: * v: Specific volume, [m³/kg] ...
Basic equation for region 1 Parameters ---------- T : float Temperature, [K] P : float Pressure, [MPa] Returns ------- prop : dict Dict with calculated properties. The available properties are: * v: Specific volume, [m³/kg] * h: Specific ent...
def output(data, **kwargs): ''' Display the profiling data in a table format. ''' rows = _find_durations(data) kwargs['opts'] = __opts__ kwargs['rows_key'] = 'rows' kwargs['labels_key'] = 'labels' to_show = {'labels': ['name', 'mod.fun', 'duration (ms)'], 'rows': rows...
Display the profiling data in a table format.
def copy_to(self, dest, buffering: int = -1): ''' copy the file to dest path. `dest` canbe `str`, `FileInfo` or `DirectoryInfo`. if `dest` is `DirectoryInfo`, that mean copy into the dir with same name. ''' if isinstance(dest, str): dest_path = dest ...
copy the file to dest path. `dest` canbe `str`, `FileInfo` or `DirectoryInfo`. if `dest` is `DirectoryInfo`, that mean copy into the dir with same name.
def export_for_schema(self): """ Returns a string version of these replication options which are suitable for use in a CREATE KEYSPACE statement. """ ret = "{'class': 'NetworkTopologyStrategy'" for dc, repl_factor in sorted(self.dc_replication_factors.items()): ...
Returns a string version of these replication options which are suitable for use in a CREATE KEYSPACE statement.
def chat_meMessage(self, *, channel: str, text: str, **kwargs) -> SlackResponse: """Share a me message into a channel. Args: channel (str): The channel id. e.g. 'C1234567890' text (str): The message you'd like to share. e.g. 'Hello world' """ kwargs.update({"chan...
Share a me message into a channel. Args: channel (str): The channel id. e.g. 'C1234567890' text (str): The message you'd like to share. e.g. 'Hello world'
def parse_event_writer(self, node): """ Parses <EventWriter> @param node: Node containing the <EventWriter> element @type node: xml.etree.Element """ if 'path' in node.lattrib: path = node.lattrib['path'] else: self.raise_error('<EventWri...
Parses <EventWriter> @param node: Node containing the <EventWriter> element @type node: xml.etree.Element
def view_creatr(filename): """Name of the View File to be created""" if not check(): click.echo(Fore.RED + 'ERROR: Ensure you are in a bast app to run the create:view command') return path = os.path.abspath('.') + '/public/templates' if not os.path.exists(path): os.makedirs(path...
Name of the View File to be created
def get_message_urls(self, message_id, order="total_clicks desc"): """Returns a list of URLs you've included in a specific message. List is sorted by ``total_clicks``, starting at an optional integer ``offset``, and optionally limited to the first ``count`` items. """ req_data = [ { "me...
Returns a list of URLs you've included in a specific message. List is sorted by ``total_clicks``, starting at an optional integer ``offset``, and optionally limited to the first ``count`` items.
def restricted_activities_available_to_user(cls, user): """Find the restricted activities available to the given user.""" if not user: return [] activities = set(user.restricted_activity_set.values_list("id", flat=True)) if user and user.grade and user.grade.number and user...
Find the restricted activities available to the given user.
def from_external(external=H2OFrame): """ Creates new H2OWord2vecEstimator based on an external model. :param external: H2OFrame with an external model :return: H2OWord2vecEstimator instance representing the external model """ w2v_model = H2OWord2vecEstimator(pre_trained=...
Creates new H2OWord2vecEstimator based on an external model. :param external: H2OFrame with an external model :return: H2OWord2vecEstimator instance representing the external model
def page_for(self, member, page_size=DEFAULT_PAGE_SIZE): ''' Determine the page where a member falls in the leaderboard. @param member [String] Member name. @param page_size [int] Page size to be used in determining page location. @return the page where a member falls in the lea...
Determine the page where a member falls in the leaderboard. @param member [String] Member name. @param page_size [int] Page size to be used in determining page location. @return the page where a member falls in the leaderboard.
def get_all_tags_of_offer(self, offer_id): """ Get all tags of offer This will iterate over all pages until it gets all elements. So if the rate limit exceeded it will throw an Exception and you will get nothing :param offer_id: the offer id :return: list """ ...
Get all tags of offer This will iterate over all pages until it gets all elements. So if the rate limit exceeded it will throw an Exception and you will get nothing :param offer_id: the offer id :return: list
def get_command_templates(command_tokens, file_tokens=[], path_tokens=[], job_options=[]): """ Given a list of tokens from the grammar, return a list of commands. """ files = get_files(file_tokens) paths = get_paths(path_tokens) job_options = get_options(job_options) templates = _get_co...
Given a list of tokens from the grammar, return a list of commands.
def is_constraint(self): """ returns the expression of the constraint that constrains this parameter """ if self._is_constraint is None: return None return self._bundle.get_parameter(context='constraint', uniqueid=self._is_constraint)
returns the expression of the constraint that constrains this parameter
def files(self, data): """Set files from data.""" current_files = self.files if current_files: raise RuntimeError('Can not update existing files.') for key in data: current_files[key] = data[key]
Set files from data.
def gt(gt_value): """ Validates that a field value is greater than the value given to this validator. """ def validate(value): if value <= gt_value: return e("{} is not greater than {}", value, gt_value) return validate
Validates that a field value is greater than the value given to this validator.
def stopprocessmonitor(self, process_name): """ Stop memory and CPU monitoring @param process_name: Process name, ex: firefox-bin. @type process_name: string @return: 1 on success @rtype: integer """ if process_name in self._process_stats: # ...
Stop memory and CPU monitoring @param process_name: Process name, ex: firefox-bin. @type process_name: string @return: 1 on success @rtype: integer
def reset(self): """ Reset the wavefunction to the |000...00> state. :return: ``self`` to support method chaining. """ self.wf.fill(0) self.wf[(0,) * self.n_qubits] = complex(1.0, 0) return self
Reset the wavefunction to the |000...00> state. :return: ``self`` to support method chaining.
def get_model(self): """ Get a model if the formula was previously satisfied. """ if self.minisat and self.status == True: model = pysolvers.minisatgh_model(self.minisat) return model if model != None else []
Get a model if the formula was previously satisfied.
def route(self, dst, dev=None): """ Provide best route to IPv6 destination address, based on Scapy6 internal routing table content. When a set of address is passed (e.g. 2001:db8:cafe:*::1-5) an address of the set is used. Be aware of that behavior when using wildcards in ...
Provide best route to IPv6 destination address, based on Scapy6 internal routing table content. When a set of address is passed (e.g. 2001:db8:cafe:*::1-5) an address of the set is used. Be aware of that behavior when using wildcards in upper parts of addresses ! If 'dst' para...
def _extract_from_raw_reads(self, output_path, input_reads, raw_sequences_path, input_file_format, hits): ''' _extract_from_raw_reads - call fxtract to extract the hit sequences of the hmm/diamond search from the raw sequences file. Output into specified file Parameters ...
_extract_from_raw_reads - call fxtract to extract the hit sequences of the hmm/diamond search from the raw sequences file. Output into specified file Parameters ---------- output_path : str Path of the desired output file input_reads : list list o...
def delete(self, obj): """Required functionality.""" del_id = obj.get_id() if not del_id: return cur = self._conn().cursor() tabname = obj.__class__.get_table_name() query = 'delete from %s where id = ?' % tabname cur.execute(query, (del_id,)) ...
Required functionality.
def connect_post_node_proxy_with_path(self, name, path, **kwargs): # noqa: E501 """connect_post_node_proxy_with_path # noqa: E501 connect POST requests to proxy of Node # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please ...
connect_post_node_proxy_with_path # noqa: E501 connect POST requests to proxy of Node # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.connect_post_node_proxy_with_path(name, path, a...
def wait(self, timeout=None, do_raise=False): """ Wait for the future to complete. If *timeout* is specified, it must be a floating point number representing the maximum number of seconds to wait. :param timeout: The maximum number of seconds to wait for the future to complete. :param do_rais...
Wait for the future to complete. If *timeout* is specified, it must be a floating point number representing the maximum number of seconds to wait. :param timeout: The maximum number of seconds to wait for the future to complete. :param do_raise: Raise :class:`Timeout` when a timeout occurred. :ra...
def rescale_rows(rows, rescale): """ Take each row in rows (an iterator) and yield a fresh row with the pixels scaled according to the rescale parameters in the list `rescale`. Each element of `rescale` is a tuple of (source_bitdepth, target_bitdepth), with one element per channel. """ ...
Take each row in rows (an iterator) and yield a fresh row with the pixels scaled according to the rescale parameters in the list `rescale`. Each element of `rescale` is a tuple of (source_bitdepth, target_bitdepth), with one element per channel.
def delete(filename, retry_params=None, _account_id=None): """Delete a Google Cloud Storage file. Args: filename: A Google Cloud Storage filename of form '/bucket/filename'. retry_params: An api_utils.RetryParams for this call to GCS. If None, the default one is used. _account_id: Internal-use on...
Delete a Google Cloud Storage file. Args: filename: A Google Cloud Storage filename of form '/bucket/filename'. retry_params: An api_utils.RetryParams for this call to GCS. If None, the default one is used. _account_id: Internal-use only. Raises: errors.NotFoundError: if the file doesn't exi...