positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def curate(community): """Index page with uploader and list of existing depositions. :param community_id: ID of the community to curate. """ if request.method == 'POST': action = request.json.get('action') recid = request.json.get('recid') # 'recid' is mandatory if not ...
Index page with uploader and list of existing depositions. :param community_id: ID of the community to curate.
def completions(self, symbol, attribute, recursive = False): """Finds all possible symbol completions of the given symbol that belong to this module and its dependencies. :arg symbol: the code symbol that needs to be completed. :arg attribute: one of ['dependencies', 'publics', 'members...
Finds all possible symbol completions of the given symbol that belong to this module and its dependencies. :arg symbol: the code symbol that needs to be completed. :arg attribute: one of ['dependencies', 'publics', 'members', 'types', 'executables'] for specifying which collections t...
def do_rm(self, params): """ \x1b[1mNAME\x1b[0m rm - Remove the znode \x1b[1mSYNOPSIS\x1b[0m rm <path> [path] [path] ... [path] \x1b[1mEXAMPLES\x1b[0m > rm /foo > rm /foo /bar """ for path in params.paths: try: self.client_context.de...
\x1b[1mNAME\x1b[0m rm - Remove the znode \x1b[1mSYNOPSIS\x1b[0m rm <path> [path] [path] ... [path] \x1b[1mEXAMPLES\x1b[0m > rm /foo > rm /foo /bar
def do_watch(self, *args): """ Watch Dynamo tables consumed capacity """ tables = [] if not self.engine.cached_descriptions: self.engine.describe_all() all_tables = list(self.engine.cached_descriptions) for arg in args: candidates = set((t for t in all_tab...
Watch Dynamo tables consumed capacity
def children_rest_names(self): """ Gets the list of all possible children ReST names. Returns: list: list containing all possible rest names as string Example: >>> entity = NUEntity() >>> entity.children_rest_names ["foo",...
Gets the list of all possible children ReST names. Returns: list: list containing all possible rest names as string Example: >>> entity = NUEntity() >>> entity.children_rest_names ["foo", "bar"]
def update(self,**kwargs): """ Updates the values for a QuantFigure The key-values are automatically assigned to the correct section of the QuantFigure """ if 'columns' in kwargs: self._d=ta._ohlc_dict(self.df,columns=kwargs.pop('columns',None)) schema=self._get_schema() annotations=kwargs.pop('anno...
Updates the values for a QuantFigure The key-values are automatically assigned to the correct section of the QuantFigure
def get_kbs_info(kbtype="", searchkbname=""): """A convenience method. :param kbtype: type of kb -- get only kb's of this type :param searchkbname: get only kb's where this sting appears in the name """ # query + order by query = models.KnwKB.query.order_by( models.KnwKB.name) # fil...
A convenience method. :param kbtype: type of kb -- get only kb's of this type :param searchkbname: get only kb's where this sting appears in the name
def pytype_to_ctype(t): """ Python -> pythonic type binding. """ if isinstance(t, List): return 'pythonic::types::list<{0}>'.format( pytype_to_ctype(t.__args__[0]) ) elif isinstance(t, Set): return 'pythonic::types::set<{0}>'.format( pytype_to_ctype(t.__args__...
Python -> pythonic type binding.
def utc_datetime_and_leap_second(self): """Convert to a Python ``datetime`` in UTC, plus a leap second value. Convert this time to a `datetime`_ object and a leap second:: dt, leap_second = t.utc_datetime_and_leap_second() If the third-party `pytz`_ package is available, then its ...
Convert to a Python ``datetime`` in UTC, plus a leap second value. Convert this time to a `datetime`_ object and a leap second:: dt, leap_second = t.utc_datetime_and_leap_second() If the third-party `pytz`_ package is available, then its ``utc`` timezone will be used as the timezo...
def get_raw_token(self, header): """ Extracts an unvalidated JSON web token from the given "Authorization" header value. """ parts = header.split() if len(parts) == 0: # Empty AUTHORIZATION header sent return None if parts[0] not in AUTH_...
Extracts an unvalidated JSON web token from the given "Authorization" header value.
def ipop_range(self, start=0, stop=-1, callback=None, withscores=True): '''pop a range from the :class:`OrderedMixin`''' backend = self.backend res = backend.structure(self).ipop_range(start, stop, withscores=withscores) if not callba...
pop a range from the :class:`OrderedMixin`
def _periodically_flush_profile_events(self): """Drivers run this as a thread to flush profile data in the background.""" # Note(rkn): This is run on a background thread in the driver. It uses # the raylet client. This should be ok because it doesn't read # from the raylet client...
Drivers run this as a thread to flush profile data in the background.
def ReplaceIxes(self, path, old_prefix, old_suffix, new_prefix, new_suffix): """ Replace old_prefix with new_prefix and old_suffix with new_suffix. env - Environment used to interpolate variables. path - the path that will be modified. old_prefix - construction variable for the ...
Replace old_prefix with new_prefix and old_suffix with new_suffix. env - Environment used to interpolate variables. path - the path that will be modified. old_prefix - construction variable for the old prefix. old_suffix - construction variable for the old suffix. new_prefix - c...
def subcmd_list_parser(subcmd): """ list subcommand """ subcmd.add_argument( '--broker', action='store', dest='broker', help=u'Route to the Ansible Service Broker' ) subcmd.add_argument( '--secure', action='store_true', dest='verify', help=...
list subcommand
def _glslify(r): """Transform a string or a n-tuple to a valid GLSL expression.""" if isinstance(r, string_types): return r else: assert 2 <= len(r) <= 4 return 'vec{}({})'.format(len(r), ', '.join(map(str, r)))
Transform a string or a n-tuple to a valid GLSL expression.
def wait_for_window_map_state(self, window, state): """ Wait for a window to have a specific map state. State possibilities: IsUnmapped - window is not displayed. IsViewable - window is mapped and shown (though may be clipped by windows on top of it) ...
Wait for a window to have a specific map state. State possibilities: IsUnmapped - window is not displayed. IsViewable - window is mapped and shown (though may be clipped by windows on top of it) IsUnviewable - window is mapped but a parent window is unmapped. ...
def absolute_abundance(coverage, total_bases): """ absolute abundance = (number of bases mapped to genome / total number of bases in sample) * 100 """ absolute = {} for genome in coverage: absolute[genome] = [] index = 0 for calc in coverage[genome]: bases = calc[0] total = total_bases[index] absolu...
absolute abundance = (number of bases mapped to genome / total number of bases in sample) * 100
def add_value(self, field_name: str, value: object = None, json_path: str = None, json_path_extraction: str = None, keep_empty: bool = False) -> None: """ Add a value to knowledge graph. Input can either be a value or a json_path. If the input is json_path, the helper function ...
Add a value to knowledge graph. Input can either be a value or a json_path. If the input is json_path, the helper function _add_doc_value is called. If the input is a value, then it is handled Args: field_name: str, the field name in the knowledge graph value: th...
def meff_SO(self, **kwargs): ''' Returns the split-off hole effective mass calculated from Eg_Gamma(T), Delta_SO, Ep and F. Interpolation of Eg_Gamma(T), Delta_SO, Ep and luttinger1, and then calculation of meff_SO is recommended for alloys. ''' Eg = self...
Returns the split-off hole effective mass calculated from Eg_Gamma(T), Delta_SO, Ep and F. Interpolation of Eg_Gamma(T), Delta_SO, Ep and luttinger1, and then calculation of meff_SO is recommended for alloys.
def parse_config(filename): """ Parses a versionupgrade configuration file. Example: tag v{VERSION} branch v{VERSION} message Prepare {VERSION} release upgrade setup.py: version = '{VERSION}' upgrade __init__.py:__version__ = '{VERSION}' sub docs/changelog/v{VERSION}.md:# v{VER...
Parses a versionupgrade configuration file. Example: tag v{VERSION} branch v{VERSION} message Prepare {VERSION} release upgrade setup.py: version = '{VERSION}' upgrade __init__.py:__version__ = '{VERSION}' sub docs/changelog/v{VERSION}.md:# v{VERSION} (unreleased):# v{VERSION} ({DA...
def getObjectives(self): """ Get all the objectives declared. """ objectives = lock_and_call( lambda: self._impl.getObjectives(), self._lock ) return EntityMap(objectives, Objective)
Get all the objectives declared.
def convert_ages_to_calendar_year(self, er_ages_rec): """ convert all age units to calendar year Parameters ---------- er_ages_rec : Dict type object containing preferbly at least keys 'age', 'age_unit', and either 'age_range_high', 'age_range_low' or 'ag...
convert all age units to calendar year Parameters ---------- er_ages_rec : Dict type object containing preferbly at least keys 'age', 'age_unit', and either 'age_range_high', 'age_range_low' or 'age_sigma' Returns ------- er_ages_rec : Same dict ...
def id_pseudopath(self): """ Looks like a path, but with ids stuck in when available """ try: pseudopath = Fields(str(self.value[auto_id_field])) except (TypeError, AttributeError, KeyError): # This may not be all the interesting exceptions pseudopath = se...
Looks like a path, but with ids stuck in when available
def plot_two_columns(self, reset_xlimits=False, reset_ylimits=False): """Simple line plot for two selected columns.""" self.clear_plot() if self.tab is None: # No table data to plot return plt_kw = { 'lw': self.settings.get('linewidth', 1), 'ls': se...
Simple line plot for two selected columns.
def _build(self): """Returns a tuple containing observation and target one-hot tensors.""" q = tf.FIFOQueue( self._queue_capacity, [self._dtype, self._dtype], shapes=[[self._num_steps, self._batch_size, self._vocab_size]]*2) obs, target = tf.py_func(self._get_batch, [], [tf.int32, tf.int32])...
Returns a tuple containing observation and target one-hot tensors.
def set_length_and_maybe_checksums(self, record, payload_offset=None): '''Set the content length and possibly the checksums.''' if self._params.digests: record.compute_checksum(payload_offset) else: record.set_content_length()
Set the content length and possibly the checksums.
def create(self): """POST /datastores: Create a new item.""" # url('datastores') content = request.environ['wsgi.input'].read(int(request.environ['CONTENT_LENGTH'])) content = content.decode('utf8') content = simplejson.loads(content) new = DataStore(content['name'], ...
POST /datastores: Create a new item.
def get_cdr(self, start=0, count=-1, **kwargs): """Request range of CDR messages""" sha = encode_to_sha("{:d},{:d}".format(start, count)) return self._queue_msg({'cmd': cmd.CMD_MESSAGE_CDR, 'sha': sha}, **kwargs)
Request range of CDR messages
def send(self, **extra): """ Sends email batch. :return: Information about sent emails. :rtype: `list` """ emails = self.as_dict(**extra) responses = [self._manager._send_batch(*batch) for batch in chunks(emails, self.MAX_SIZE)] return sum(responses, [])
Sends email batch. :return: Information about sent emails. :rtype: `list`
async def start_child(): """ Start the child process that will look for changes in modules. """ logger.info('Started to watch for code changes') loop = asyncio.get_event_loop() watcher = aionotify.Watcher() flags = ( aionotify.Flags.MODIFY | aionotify.Flags.DELETE | ...
Start the child process that will look for changes in modules.
def plot_expected_repeat_purchases( model, title="Expected Number of Repeat Purchases per Customer", xlabel="Time Since First Purchase", ax=None, label=None, **kwargs ): """ Plot expected repeat purchases on calibration period . Parameters ---------- model: lifetimes model ...
Plot expected repeat purchases on calibration period . Parameters ---------- model: lifetimes model A fitted lifetimes model. max_frequency: int, optional The maximum frequency to plot. title: str, optional Figure title xlabel: str, optional Figure xlabel ax:...
def request_location(cls, text, *, resize=None, single_use=None, selective=None): """ Creates a new button that will request the user's location upon being clicked. ``resize``, ``single_use`` and ``selective`` are documented in `text`. """ return...
Creates a new button that will request the user's location upon being clicked. ``resize``, ``single_use`` and ``selective`` are documented in `text`.
def centroid_distance(item_a, time_a, item_b, time_b, max_value): """ Euclidean distance between the centroids of item_a and item_b. Args: item_a: STObject from the first set in ObjectMatcher time_a: Time integer being evaluated item_b: STObject from the second set in ObjectMatcher ...
Euclidean distance between the centroids of item_a and item_b. Args: item_a: STObject from the first set in ObjectMatcher time_a: Time integer being evaluated item_b: STObject from the second set in ObjectMatcher time_b: Time integer being evaluated max_value: Maximum distan...
def checks(self): '''Return the list of all check methods.''' condition = lambda a: a.startswith('check_') return (getattr(self, a) for a in dir(self) if condition(a))
Return the list of all check methods.
def add(self, node): """Add Node, replace existing node if node with node_id is present.""" if not isinstance(node, Node): raise TypeError() for i, j in enumerate(self.__nodes): if j.node_id == node.node_id: self.__nodes[i] = node return ...
Add Node, replace existing node if node with node_id is present.
def move_back_boxed_texts(self): """ The only intended use for this function is to patch a problem seen in at least one PLoS article (journal.pgen.0020002). This will move any <boxed-text> elements over to the receiving element, which is probably the main body. """ ...
The only intended use for this function is to patch a problem seen in at least one PLoS article (journal.pgen.0020002). This will move any <boxed-text> elements over to the receiving element, which is probably the main body.
def is_refreshable_url(self, request): """Takes a request and returns whether it triggers a refresh examination :arg HttpRequest request: :returns: boolean """ # Do not attempt to refresh the session if the OIDC backend is not used backend_session = request.session.get...
Takes a request and returns whether it triggers a refresh examination :arg HttpRequest request: :returns: boolean
def add_or_update(self, app_id): ''' Add or update the category. ''' logger.info('Collect info: user-{0}, uid-{1}'.format(self.userinfo.uid, app_id)) MCollect.add_or_update(self.userinfo.uid, app_id) out_dic = {'success': True} return json.dump(out_dic, self)
Add or update the category.
def makeMany2ManyRelatedManager(formodel, name_relmodel, name_formodel): '''formodel is the model which the manager .''' class _Many2ManyRelatedManager(Many2ManyRelatedManager): pass _Many2ManyRelatedManager.formodel = formodel _Many2ManyRelatedManager.name_relmodel = name_relmodel ...
formodel is the model which the manager .
def next(self, n=1): """Move up by `n` steps in the Hilbert space:: >>> hs = LocalSpace('tls', basis=('g', 'e')) >>> ascii(BasisKet('g', hs=hs).next()) '|e>^(tls)' >>> ascii(BasisKet(0, hs=hs).next()) '|e>^(tls)' We can also go multiple step...
Move up by `n` steps in the Hilbert space:: >>> hs = LocalSpace('tls', basis=('g', 'e')) >>> ascii(BasisKet('g', hs=hs).next()) '|e>^(tls)' >>> ascii(BasisKet(0, hs=hs).next()) '|e>^(tls)' We can also go multiple steps: >>> hs = LocalS...
def load_data(self, filename, ext): """Load data from filename""" from spyder_kernels.utils.iofuncs import iofunctions from spyder_kernels.utils.misc import fix_reference_name glbs = self._mglobals() load_func = iofunctions.load_funcs[ext] data, error_message = load_fun...
Load data from filename
def post(self, request, hook_id): """ Process Telegram webhook. 1. Serialize Telegram message 2. Get an enabled Telegram bot 3. Create :class:`Update <permabots.models.telegram_api.Update>` 5. Delay processing to a task 6. Response provid...
Process Telegram webhook. 1. Serialize Telegram message 2. Get an enabled Telegram bot 3. Create :class:`Update <permabots.models.telegram_api.Update>` 5. Delay processing to a task 6. Response provider
def index_template_exists(name, hosts=None, profile=None): ''' Return a boolean indicating whether given index template exists name Index template name CLI example:: salt myminion elasticsearch.index_template_exists testindex_templ ''' es = _get_instance(hosts, profile) tr...
Return a boolean indicating whether given index template exists name Index template name CLI example:: salt myminion elasticsearch.index_template_exists testindex_templ
def get_verbatim(key, **kwargs): ''' Gets a verbatim occurrence record without any interpretation :param key: [int] A GBIF occurrence key :return: A dictionary, of results Usage:: from pygbif import occurrences occurrences.get_verbatim(key = 1258202889) occurrences.get_ve...
Gets a verbatim occurrence record without any interpretation :param key: [int] A GBIF occurrence key :return: A dictionary, of results Usage:: from pygbif import occurrences occurrences.get_verbatim(key = 1258202889) occurrences.get_verbatim(key = 1227768771) occurrences....
def Compile(self, filter_implemention): """Returns the data_store filter implementation from the attribute.""" return self.operator_method(self.attribute_obj, filter_implemention, *self.args)
Returns the data_store filter implementation from the attribute.
def dataset(self): """A Tablib Dataset containing the row.""" data = tablib.Dataset() data.headers = self.keys() row = _reduce_datetimes(self.values()) data.append(row) return data
A Tablib Dataset containing the row.
def add_0x(string): """Add 0x to string at start. """ if isinstance(string, bytes): string = string.decode('utf-8') return '0x' + str(string)
Add 0x to string at start.
def add_to_cart(item_id): """ Cart with Product """ cart = Cart(session['cart']) if cart.change_item(item_id, 'add'): session['cart'] = cart.to_dict() return list_products()
Cart with Product
def build_headers(self): ''' Return the list of headers as two-tuples ''' if not 'Content-Type' in self.headers: content_type = self.content_type if self.encoding != DEFAULT_ENCODING: content_type += '; charset=%s' % self.encoding self....
Return the list of headers as two-tuples
def sort_members(tup, names): """Return two pairs of members, scalar and tuple members. The scalars will be sorted s.t. the unbound members are at the top. """ scalars, tuples = partition(lambda x: not is_tuple_node(tup.member[x].value), names) unbound, bound = partition(lambda x: tup.member[x].value.is_unbo...
Return two pairs of members, scalar and tuple members. The scalars will be sorted s.t. the unbound members are at the top.
def pool_build(name, **kwargs): ''' Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding de...
Build a defined libvirt storage pool. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 ...
def create_stack(StackName=None, TemplateBody=None, TemplateURL=None, Parameters=None, DisableRollback=None, TimeoutInMinutes=None, NotificationARNs=None, Capabilities=None, ResourceTypes=None, RoleARN=None, OnFailure=None, StackPolicyBody=None, StackPolicyURL=None, Tags=None, ClientRequestToken=None): """ Crea...
Creates a stack as specified in the template. After the call completes successfully, the stack creation starts. You can check the status of the stack via the DescribeStacks API. See also: AWS API Documentation :example: response = client.create_stack( StackName='string', TemplateBody=...
def maybe_convert_platform(values): """ try to do platform conversion, allow ndarray or list here """ if isinstance(values, (list, tuple)): values = construct_1d_object_array_from_listlike(list(values)) if getattr(values, 'dtype', None) == np.object_: if hasattr(values, '_values'): ...
try to do platform conversion, allow ndarray or list here
def cli(env, volume_id, replicant_id, immediate): """Failover a block volume to the given replicant volume.""" block_storage_manager = SoftLayer.BlockStorageManager(env.client) success = block_storage_manager.failover_to_replicant( volume_id, replicant_id, immediate ) if su...
Failover a block volume to the given replicant volume.
def on_exception(func): """ Run a function when a handler thows an exception. It's return value is returned to AWS. Usage:: >>> # to create a reusable decorator >>> @on_exception ... def handle_errors(exception): ... print(exception) ... return {'statusC...
Run a function when a handler thows an exception. It's return value is returned to AWS. Usage:: >>> # to create a reusable decorator >>> @on_exception ... def handle_errors(exception): ... print(exception) ... return {'statusCode': 500, 'body': 'uh oh'} ...
def saveh5(self, h5file, qpi_slice=None, series_slice=None, time_interval=None, count=None, max_count=None): """Save the data set as an hdf5 file (qpimage.QPSeries format) Parameters ---------- h5file: str, pathlib.Path, or h5py.Group Where to store the series...
Save the data set as an hdf5 file (qpimage.QPSeries format) Parameters ---------- h5file: str, pathlib.Path, or h5py.Group Where to store the series data qpi_slice: tuple of (slice, slice) If not None, only store a slice of each QPImage in `h5file`. A...
def addmul_number_dicts(series): '''Multiply dictionaries by a numeric values and add them together. :parameter series: a tuple of two elements tuples. Each serie is of the form:: (weight,dictionary) where ``weight`` is a number and ``dictionary`` is a dictionary with numeric values. :parameter s...
Multiply dictionaries by a numeric values and add them together. :parameter series: a tuple of two elements tuples. Each serie is of the form:: (weight,dictionary) where ``weight`` is a number and ``dictionary`` is a dictionary with numeric values. :parameter skip: optional list of field names to ski...
def init_from_fcnxs(ctx, fcnxs_symbol, fcnxs_args_from, fcnxs_auxs_from): """ use zero initialization for better convergence, because it tends to oputut 0, and the label 0 stands for background, which may occupy most size of one image. """ fcnxs_args = fcnxs_args_from.copy() fcnxs_auxs = fcnxs_auxs_...
use zero initialization for better convergence, because it tends to oputut 0, and the label 0 stands for background, which may occupy most size of one image.
def _sighash_prep(self, index, script): ''' SproutTx, int, byte-like -> SproutTx Sighashes suck Performs the sighash setup described here: https://en.bitcoin.it/wiki/OP_CHECKSIG#How_it_works https://bitcoin.stackexchange.com/questions/3374/how-to-redeem-a-basic-tx ...
SproutTx, int, byte-like -> SproutTx Sighashes suck Performs the sighash setup described here: https://en.bitcoin.it/wiki/OP_CHECKSIG#How_it_works https://bitcoin.stackexchange.com/questions/3374/how-to-redeem-a-basic-tx We save on complexity by refusing to support OP_CODESEPARAT...
def sd_journal_send(**kwargs): """ Send a message to the journald log. @param kwargs: Mapping between field names to values, both as bytes. @raise IOError: If the operation failed. """ # The function uses printf formatting, so we need to quote # percentages. fields = [ _ffi.new...
Send a message to the journald log. @param kwargs: Mapping between field names to values, both as bytes. @raise IOError: If the operation failed.
def show(self, item, variant): """ Show a variant. :param item: Item object or id :param variant: Variant object or id :return: """ url = self._build_url(self.endpoint.show(item, variant)) return self._get(url)
Show a variant. :param item: Item object or id :param variant: Variant object or id :return:
def unfinished_objects(self): ''' Leaves only versions of those objects that has some version with `_end == None` or with `_end > right cutoff`. ''' mask = self._end_isnull if self._rbound is not None: mask = mask | (self._end > self._rbound) oids = se...
Leaves only versions of those objects that has some version with `_end == None` or with `_end > right cutoff`.
async def get_next_opponent(self): """ Get the opponent of the potential next match. See :func:`get_next_match` |methcoro| Raises: APIException """ next_match = await self.get_next_match() if next_match is not None: opponent_id = next_match.play...
Get the opponent of the potential next match. See :func:`get_next_match` |methcoro| Raises: APIException
def copyToLocal(self, paths, dst, check_crc=False): ''' Copy files that match the file source pattern to the local name. Source is kept. When copying multiple, files, the destination must be a directory. :param paths: Paths to copy :type paths: list of strings :param d...
Copy files that match the file source pattern to the local name. Source is kept. When copying multiple, files, the destination must be a directory. :param paths: Paths to copy :type paths: list of strings :param dst: Destination path :type dst: string :param ch...
def hessian(self, coordinates): """Compute the force-field Hessian for the given coordinates. Argument: | ``coordinates`` -- A numpy array with the Cartesian atom coordinates, with shape (N,3). Returns: | ``hessian`` -- A numpy arr...
Compute the force-field Hessian for the given coordinates. Argument: | ``coordinates`` -- A numpy array with the Cartesian atom coordinates, with shape (N,3). Returns: | ``hessian`` -- A numpy array with the Hessian, with shape (3*N, ...
def update_frame(self, key, ranges=None, element=None): """ Update the internal state of the Plot to represent the given key tuple (where integers represent frames). Returns this state. """ reused = isinstance(self.hmap, DynamicMap) and self.overlaid if not reused...
Update the internal state of the Plot to represent the given key tuple (where integers represent frames). Returns this state.
def ReadFromFile(self, artifacts_reader, filename): """Reads artifact definitions into the registry from a file. Args: artifacts_reader (ArtifactsReader): an artifacts reader. filename (str): name of the file to read from. """ for artifact_definition in artifacts_reader.ReadFile(filename): ...
Reads artifact definitions into the registry from a file. Args: artifacts_reader (ArtifactsReader): an artifacts reader. filename (str): name of the file to read from.
def optimize(self): """Optimize certain stacked wildcard patterns.""" subpattern = None if (self.content is not None and len(self.content) == 1 and len(self.content[0]) == 1): subpattern = self.content[0][0] if self.min == 1 and self.max == 1: if self....
Optimize certain stacked wildcard patterns.
def stop(self): """ Stop tracing. Reinstalls the :ref:`hunter.Tracer.previous` tracer. """ if self._handler is not None: sys.settrace(self._previous) self._handler = self._previous = None if self.threading_support is None or self.threading_support: ...
Stop tracing. Reinstalls the :ref:`hunter.Tracer.previous` tracer.
def stable_u_range_dict(self, chempot_range, ref_delu, no_doped=True, no_clean=False, delu_dict={}, miller_index=(), dmu_at_0=False, return_se_dict=False): """ Creates a dictionary where each entry is a key pointing to a chemical potential ...
Creates a dictionary where each entry is a key pointing to a chemical potential range where the surface of that entry is stable. Does so by enumerating through all possible solutions (intersect) for surface energies of a specific facet. Args: chempot_range ([max_chempot, min...
def delete_account_metadata(self, prefix=None): """ Removes all metadata matching the specified prefix from the account. By default, the standard account metadata prefix ('X-Account-Meta-') is prepended to the header name if it isn't present. For non-standard headers, you must i...
Removes all metadata matching the specified prefix from the account. By default, the standard account metadata prefix ('X-Account-Meta-') is prepended to the header name if it isn't present. For non-standard headers, you must include a non-None prefix, such as an empty string.
def write(self, data): """ write data on the OUT endpoint associated to the HID interface """ for _ in range(64 - len(data)): data.append(0) #logging.debug("send: %s", data) self.device.write(bytearray([0]) + data) return
write data on the OUT endpoint associated to the HID interface
def strip_textpad(text): """ Attempt to intelligently strip excess whitespace from the output of a curses textpad. """ if text is None: return text # Trivial case where the textbox is only one line long. if '\n' not in text: return text.r...
Attempt to intelligently strip excess whitespace from the output of a curses textpad.
def user_tickets_assigned(self, user_id, external_id=None, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/tickets#allowed-for" api_path = "/api/v2/users/{user_id}/tickets/assigned.json" api_path = api_path.format(user_id=user_id) api_query = {} if "query" in kwargs....
https://developer.zendesk.com/rest_api/docs/core/tickets#allowed-for
def memoryview_safe(x): """Make array safe to run in a Cython memoryview-based kernel. These kernels typically break down with the error ``ValueError: buffer source array is read-only`` when running in dask distributed. See Also -------- https://github.com/dask/distributed/issues/1978 https...
Make array safe to run in a Cython memoryview-based kernel. These kernels typically break down with the error ``ValueError: buffer source array is read-only`` when running in dask distributed. See Also -------- https://github.com/dask/distributed/issues/1978 https://github.com/cggh/scikit-allel...
def whoami(self, note=None, loglevel=logging.DEBUG): """Returns the current user by executing "whoami". @param note: See send() @return: the output of "whoami" @rtype: string """ shutit = self.shutit shutit.handle_note(note) res = self.send_and_get_output(' command whoami',...
Returns the current user by executing "whoami". @param note: See send() @return: the output of "whoami" @rtype: string
def to_rgba(color, alpha): """ Converts from hex|rgb to rgba Parameters: ----------- color : string Color representation on hex or rgb alpha : float Value from 0 to 1.0 that represents the alpha value. Example: ...
Converts from hex|rgb to rgba Parameters: ----------- color : string Color representation on hex or rgb alpha : float Value from 0 to 1.0 that represents the alpha value. Example: to_rgba('#E1E5ED',0.6) ...
def sum(self, default=None): """ Calculate the sum of all the values in the times series. :param default: Value to return as a default should the calculation not be possible. :return: Float representing the sum or `None`. """ return numpy.asscalar(numpy.sum(self.values))...
Calculate the sum of all the values in the times series. :param default: Value to return as a default should the calculation not be possible. :return: Float representing the sum or `None`.
def _create_B(self,Y): """ Creates OLS coefficient matrix Parameters ---------- Y : np.array The dependent variables Y Returns ---------- The coefficient matrix B """ Z = self._create_Z(Y) return np.dot(np.dot(Y,np.t...
Creates OLS coefficient matrix Parameters ---------- Y : np.array The dependent variables Y Returns ---------- The coefficient matrix B
def configure_shellwidget(self, give_focus=True): """Configure shellwidget after kernel is started""" if give_focus: self.get_control().setFocus() # Set exit callback self.shellwidget.set_exit_callback() # To save history self.shellwidget.executing....
Configure shellwidget after kernel is started
def _full_sub_array(data_obj, xj_path, create_dict_path): """Retrieves all array or dictionary elements for '*' JSON path marker. :param dict|list data_obj: The current data object. :param str xj_path: A json path. :param bool create_dict_path create a dict path. :return: tuple with two values: fir...
Retrieves all array or dictionary elements for '*' JSON path marker. :param dict|list data_obj: The current data object. :param str xj_path: A json path. :param bool create_dict_path create a dict path. :return: tuple with two values: first is a result and second a boolean flag telling if ...
def infer_bulk_complete_from_fs(datetimes, datetime_to_task, datetime_to_re): """ Efficiently determines missing datetimes by filesystem listing. The current implementation works for the common case of a task writing output to a ``FileSystemTarget`` whose path is built using strftime with format li...
Efficiently determines missing datetimes by filesystem listing. The current implementation works for the common case of a task writing output to a ``FileSystemTarget`` whose path is built using strftime with format like '...%Y...%m...%d...%H...', without custom ``complete()`` or ``exists()``. (Eve...
def _db_to_python(db_data: dict, table: LdapObjectClass, dn: str) -> LdapObject: """ Convert a DbDate object to a LdapObject. """ fields = table.get_fields() python_data = table({ name: field.to_python(db_data[name]) for name, field in fields.items() if field.db_field }) pyt...
Convert a DbDate object to a LdapObject.
def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6): """Numpy implementation of the Frechet Distance. The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1) and X_2 ~ N(mu_2, C_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)). St...
Numpy implementation of the Frechet Distance. The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1) and X_2 ~ N(mu_2, C_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)). Stable version by Dougal J. Sutherland. Params: -- mu1: The mean ...
def download(cls, filename, input_dir, dl_dir=None): """Download the resource from the storage.""" file_info = cls.parse_remote(filename) if not dl_dir: dl_dir = os.path.join(input_dir, file_info.container, os.path.dirname(file_info.blob)) ...
Download the resource from the storage.
def _start_connection_setup(self): """Start the connection setup by refreshing the TOCs""" logger.info('We are connected[%s], request connection setup', self.link_uri) self.platform.fetch_platform_informations(self._platform_info_fetched)
Start the connection setup by refreshing the TOCs
def _create_centerline(self): """ Calculate the centerline of a polygon. Densifies the border of a polygon which is then represented by a Numpy array of points necessary for creating the Voronoi diagram. Once the diagram is created, the ridges located within the polygon are ...
Calculate the centerline of a polygon. Densifies the border of a polygon which is then represented by a Numpy array of points necessary for creating the Voronoi diagram. Once the diagram is created, the ridges located within the polygon are joined and returned. Returns: ...
def flatten(it): """ Flattens any iterable From: http://stackoverflow.com/questions/11503065/python-function-to-flatten-generator-containing-another-generator :param it: Iterator, iterator to flatten :return: Generator, A generator of the flattened values """ for x in it: if...
Flattens any iterable From: http://stackoverflow.com/questions/11503065/python-function-to-flatten-generator-containing-another-generator :param it: Iterator, iterator to flatten :return: Generator, A generator of the flattened values
def _recurse(self, path): ''' Get a list of all specified files ''' files = {} empty_dirs = [] try: sub_paths = os.listdir(path) except OSError as exc: if exc.errno == errno.ENOENT: # Path does not exist sys....
Get a list of all specified files
def after_request(self, func: Callable, name: AppOrBlueprintKey=None) -> Callable: """Add an after request function. This is designed to be used as a decorator. An example usage, .. code-block:: python @app.after_request def func(response): return respo...
Add an after request function. This is designed to be used as a decorator. An example usage, .. code-block:: python @app.after_request def func(response): return response Arguments: func: The after request function itself. name:...
def _parse_config_file_impl(filename): """ Format for the file is: credentials: email: ... api_token: ... :param filename: The filename to parse :return: A tuple with: - email - api_token """ api_key = None email = ...
Format for the file is: credentials: email: ... api_token: ... :param filename: The filename to parse :return: A tuple with: - email - api_token
def shuffle(args): """ %prog shuffle p1.fastq p2.fastq Shuffle pairs into interleaved format. """ p = OptionParser(shuffle.__doc__) p.set_tag() opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) p1, p2 = args pairsfastq = pairspf((p1, p2)) ...
%prog shuffle p1.fastq p2.fastq Shuffle pairs into interleaved format.
def process_transaction(self, transaction): """Add a transaction to ledger, updating the current state as needed. Parameters ---------- transaction : zp.Transaction The transaction to execute. """ asset = transaction.asset if isinstance(asset, Future)...
Add a transaction to ledger, updating the current state as needed. Parameters ---------- transaction : zp.Transaction The transaction to execute.
def installedOn(self): """ If this item is installed on another item, return the install target. Otherwise return None. """ try: return self.store.findUnique(_DependencyConnector, _DependencyConnector.installee == self ...
If this item is installed on another item, return the install target. Otherwise return None.
def global_workflow_run(name_or_id, alias=None, input_params={}, always_retry=True, **kwargs): """ Invokes the /globalworkflow-xxxx/run API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Global-Workflows#API-method:-/globalworkflow-xxxx%5B/yyyy%5D/run """ input_param...
Invokes the /globalworkflow-xxxx/run API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Global-Workflows#API-method:-/globalworkflow-xxxx%5B/yyyy%5D/run
def statcast_batter(start_dt=None, end_dt=None, player_id=None): """ Pulls statcast pitch-level data from Baseball Savant for a given batter. ARGUMENTS start_dt : YYYY-MM-DD : the first date for which you want a player's statcast data end_dt : YYYY-MM-DD : the final date for which you want data ...
Pulls statcast pitch-level data from Baseball Savant for a given batter. ARGUMENTS start_dt : YYYY-MM-DD : the first date for which you want a player's statcast data end_dt : YYYY-MM-DD : the final date for which you want data player_id : INT : the player's MLBAM ID. Find this by calling pybaseball.pla...
def main(argv=None): '''Command line options.''' if argv is None: argv = sys.argv else: sys.argv.extend(argv) parser = ArgumentParser() parser.add_argument('-u', '--url', dest='url', required=True, help="base url (has to contain versions json)") parser.add_argument('-o', '--out...
Command line options.
def save(self, path, group=None, ifo='P1'): """ Save frequency series to a Numpy .npy, hdf, or text file. The first column contains the sample frequencies, the second contains the values. In the case of a complex frequency series saved as text, the imaginary part is written as a ...
Save frequency series to a Numpy .npy, hdf, or text file. The first column contains the sample frequencies, the second contains the values. In the case of a complex frequency series saved as text, the imaginary part is written as a third column. When using hdf format, the data is stored ...
def forward(self,pixx,pixy): """ Transform the input pixx,pixy positions in the input frame to pixel positions in the output frame. This method gets passed to the drizzle algorithm. """ # This matches WTRAXY results to better than 1e-4 pixels. skyx,skyy = self.in...
Transform the input pixx,pixy positions in the input frame to pixel positions in the output frame. This method gets passed to the drizzle algorithm.
def get_object( self, object_t, object_id=None, relation=None, parent=None, **kwargs ): """ Actually query the Deezer API to retrieve the object :returns: json dictionary """ url = self.object_url(object_t, object_id, relation, **kwargs) response = self.sessi...
Actually query the Deezer API to retrieve the object :returns: json dictionary