positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def _transform(comps, trans): """ Transform the given string with transform type trans """ logging.debug("== In _transform(%s, %s) ==", comps, trans) components = list(comps) action, parameter = _get_action(trans) if action == _Action.ADD_MARK and \ components[2] == "" and \ ...
Transform the given string with transform type trans
def upgrade(): """Upgrade database.""" op.create_index(op.f('ix_access_actionsroles_role_id'), 'access_actionsroles', ['role_id'], unique=False) op.drop_constraint(u'fk_access_actionsroles_role_id_accounts_role', 'access_actionsroles', type_='foreignkey') op.cr...
Upgrade database.
def features(self, expand=False): """Return the list of feature-value pairs in the conjunction.""" featvals = [] for term in self._terms: if isinstance(term, AVM): featvals.extend(term.features(expand=expand)) return featvals
Return the list of feature-value pairs in the conjunction.
def search_user(self, user_name, quiet=False, limit=9): """Search user by user name. :params user_name: user name. :params quiet: automatically select the best one. :params limit: user count returned by weapi. :return: a User object. """ result = self.search(use...
Search user by user name. :params user_name: user name. :params quiet: automatically select the best one. :params limit: user count returned by weapi. :return: a User object.
def cmd_alt(self, args): '''show altitude''' print("Altitude: %.1f" % self.status.altitude) qnh_pressure = self.get_mav_param('AFS_QNH_PRESSURE', None) if qnh_pressure is not None and qnh_pressure > 0: ground_temp = self.get_mav_param('GND_TEMP', 21) pressure = s...
show altitude
def post(self): '''return executed sql result to client. post data format: {"options": ['all', 'last', 'first', 'format'], "sql_raw": "raw sql ..."} Returns: sql result. ''' ## format sql data = request.get_json() options, sql_raw = dat...
return executed sql result to client. post data format: {"options": ['all', 'last', 'first', 'format'], "sql_raw": "raw sql ..."} Returns: sql result.
def iscsi_settings(self): """Property to provide reference to iSCSI settings instance It is calculated once when the first time it is queried. On refresh, this property gets reset. """ return ISCSISettings( self._conn, utils.get_subresource_path_by( s...
Property to provide reference to iSCSI settings instance It is calculated once when the first time it is queried. On refresh, this property gets reset.
def assert_is_instance(value, types, message=None, extra=None): """Raises an AssertionError if value is not an instance of type(s).""" assert isinstance(value, types), _assert_fail_message( message, value, types, "is not an instance of", extra )
Raises an AssertionError if value is not an instance of type(s).
def auth(self): """Performs an authentication. Uses either the private token, or the email/password pair. The `user` attribute will hold a `gitlab.objects.CurrentUser` object on success. """ if self.private_token or self.oauth_token: self._token_auth() ...
Performs an authentication. Uses either the private token, or the email/password pair. The `user` attribute will hold a `gitlab.objects.CurrentUser` object on success.
def get_line_in_facet(self, facet): """ Returns the sorted pts in a facet used to draw a line """ lines = list(facet.outer_lines) pt = [] prev = None while len(lines) > 0: if prev is None: l = lines.pop(0) else: ...
Returns the sorted pts in a facet used to draw a line
def __split_genomic_interval_filename(fn): """ Split a filename of the format chrom:start-end.ext or chrom.ext (full chrom). :return: tuple of (chrom, start, end) -- 'start' and 'end' are None if not present in the filename. """ if fn is None or fn == "": raise ValueError("invalid filename: " ...
Split a filename of the format chrom:start-end.ext or chrom.ext (full chrom). :return: tuple of (chrom, start, end) -- 'start' and 'end' are None if not present in the filename.
async def hincrbyfloat(self, name, key, amount=1.0): """ Increment the value of ``key`` in hash ``name`` by floating ``amount`` """ return await self.execute_command('HINCRBYFLOAT', name, key, amount)
Increment the value of ``key`` in hash ``name`` by floating ``amount``
def transformer_wikitext103_l4k_v0(): """HParams for training languagemodel_wikitext103_l4k.""" hparams = transformer_big() # Adafactor uses less memory than Adam. # switch to Adafactor with its recommended learning rate scheme. hparams.optimizer = "Adafactor" hparams.learning_rate_schedule = "rsqrt_decay"...
HParams for training languagemodel_wikitext103_l4k.
def __process_instr(self, instr, avoid, next_addr, initial_state, execution_state, trace_current): """Process a REIL instruction. Args: instr (ReilInstruction): Instruction to process. avoid (list): List of addresses to avoid while executing the code. next_addr (int)...
Process a REIL instruction. Args: instr (ReilInstruction): Instruction to process. avoid (list): List of addresses to avoid while executing the code. next_addr (int): Address of the following instruction. initial_state (State): Initial execution state. ...
def transcript_names(self, contig=None, strand=None): """ What are all the transcript names in the database (optionally, restrict to a given chromosome and/or strand) """ return self._all_feature_values( column="transcript_name", feature="transcript", ...
What are all the transcript names in the database (optionally, restrict to a given chromosome and/or strand)
def fetch_access_token(self): """ 获取 access token 详情请参考 https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list\ &t=resource/res_list&verify=1&id=open1419318587&token=&lang=zh_CN 这是内部刷新机制。请不要完全依赖! 因为有可能在缓存期间没有对此公众号的操作,造成refresh_token失效。 :return: 返回的 JSON...
获取 access token 详情请参考 https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list\ &t=resource/res_list&verify=1&id=open1419318587&token=&lang=zh_CN 这是内部刷新机制。请不要完全依赖! 因为有可能在缓存期间没有对此公众号的操作,造成refresh_token失效。 :return: 返回的 JSON 数据包
def __vciFormatError(library_instance, function, HRESULT): """ Format a VCI error and attach failed function and decoded HRESULT :param CLibrary library_instance: Mapped instance of IXXAT vcinpl library :param callable function: Failed function :param HRESULT HRESULT:...
Format a VCI error and attach failed function and decoded HRESULT :param CLibrary library_instance: Mapped instance of IXXAT vcinpl library :param callable function: Failed function :param HRESULT HRESULT: HRESULT returned by vcinpl call :return: ...
def _division(divisor, dividend, remainder, base): """ Get the quotient and remainder :param int divisor: the divisor :param dividend: the divident :type dividend: sequence of int :param int remainder: initial remainder :param int base: the base :returns...
Get the quotient and remainder :param int divisor: the divisor :param dividend: the divident :type dividend: sequence of int :param int remainder: initial remainder :param int base: the base :returns: quotient and remainder :rtype: tuple of (list of int) * int ...
def disconnect_entry_signals(): """ Disconnect all the signals on Entry model. """ post_save.disconnect( sender=Entry, dispatch_uid=ENTRY_PS_PING_DIRECTORIES) post_save.disconnect( sender=Entry, dispatch_uid=ENTRY_PS_PING_EXTERNAL_URLS) post_save.disconnect( ...
Disconnect all the signals on Entry model.
def _extract_program_from_pyquil_executable_response(response: PyQuilExecutableResponse) -> Program: """ Unpacks a rpcq PyQuilExecutableResponse object into a pyQuil Program object. :param response: PyQuilExecutableResponse object to be unpacked. :return: Resulting pyQuil Program object. """ p ...
Unpacks a rpcq PyQuilExecutableResponse object into a pyQuil Program object. :param response: PyQuilExecutableResponse object to be unpacked. :return: Resulting pyQuil Program object.
def parse_args(args=None): """Parse command-line arguments""" parser = argparse.ArgumentParser(description='afraid.org dyndns client') ## positional arguments parser.add_argument('user') parser.add_argument('password') parser.add_argument('hosts', nargs='*', help='(deaf...
Parse command-line arguments
def set_bool(self, location, value): """Set a boolean value. Casper booleans in XML are string literals of "true" or "false". This method sets the text value of "location" to the correct string representation of a boolean. Args: location: Element or a string path ar...
Set a boolean value. Casper booleans in XML are string literals of "true" or "false". This method sets the text value of "location" to the correct string representation of a boolean. Args: location: Element or a string path argument to find() value: Boolean or s...
def hoist_event(self, e): """ Hoist an xcb_generic_event_t to the right xcffib structure. """ if e.response_type == 0: return self._process_error(ffi.cast("xcb_generic_error_t *", e)) # We mask off the high bit here because events sent with SendEvent have # this bit set. We ...
Hoist an xcb_generic_event_t to the right xcffib structure.
def approximating_model_reg(self, beta, T, Z, R, Q, h_approx, data, X, state_no): """ Creates approximating Gaussian state space model for Skewt measurement density Parameters ---------- beta : np.array Contains untransformed starting values for latent variables ...
Creates approximating Gaussian state space model for Skewt measurement density Parameters ---------- beta : np.array Contains untransformed starting values for latent variables T, Z, R, Q : np.array State space matrices used in KFS algorithm ...
def emit_node(self, node): """Emit a single node.""" emit = getattr(self, "%s_emit" % node.kind, self.default_emit) return emit(node)
Emit a single node.
def read_vest_pickle(gname, score_dir): """Read in VEST scores for given gene. Parameters ---------- gname : str name of gene score_dir : str directory containing vest scores Returns ------- gene_vest : dict or None dict containing vest scores for gene. Returns ...
Read in VEST scores for given gene. Parameters ---------- gname : str name of gene score_dir : str directory containing vest scores Returns ------- gene_vest : dict or None dict containing vest scores for gene. Returns None if not found.
def transform(self, fn, lazy=True): """Returns a new dataset with each sample transformed by the transformer function `fn`. Parameters ---------- fn : callable A transformer function that takes a sample as input and returns the transformed sample. ...
Returns a new dataset with each sample transformed by the transformer function `fn`. Parameters ---------- fn : callable A transformer function that takes a sample as input and returns the transformed sample. lazy : bool, default True If False...
def stop(self, free_resource=False): ''' send a stop transfer request to the Aspera sdk, can be done for: cancel - stop an in progress transfer free_resource - request to the Aspera sdk free resouces related to trasnfer_id ''' if not self.is_stopped(): self._...
send a stop transfer request to the Aspera sdk, can be done for: cancel - stop an in progress transfer free_resource - request to the Aspera sdk free resouces related to trasnfer_id
def get_order_book(self, code): """ 获取实时摆盘数据 :param code: 股票代码 :return: (ret, data) ret == RET_OK 返回字典,数据格式如下 ret != RET_OK 返回错误字符串 {‘code’: 股票代码 ‘Ask’:[ (ask_price1, ask_volume1,order_num), (ask_price2, ask_volume2, ord...
获取实时摆盘数据 :param code: 股票代码 :return: (ret, data) ret == RET_OK 返回字典,数据格式如下 ret != RET_OK 返回错误字符串 {‘code’: 股票代码 ‘Ask’:[ (ask_price1, ask_volume1,order_num), (ask_price2, ask_volume2, order_num),…] ‘Bid’: [ (bid_price1, bid...
def _modifyInternal(self, *, sort=None, purge=False, done=None): """Creates a whole new database from existing one, based on given modifiers. :sort: pattern should look like this: ([(<index>, True|False)], {<level_index>: [(<index>, True|False)]}), where True|False indicate whet...
Creates a whole new database from existing one, based on given modifiers. :sort: pattern should look like this: ([(<index>, True|False)], {<level_index>: [(<index>, True|False)]}), where True|False indicate whether to reverse or not, <index> are one of Model.indexes and <level_i...
def calculate_rate(country_code, subdivision, city, address_country_code=None, address_exception=None): """ Calculates the VAT rate from the data returned by a GeoLite2 database :param country_code: Two-character country code :param subdivision: The first subdivision name :param c...
Calculates the VAT rate from the data returned by a GeoLite2 database :param country_code: Two-character country code :param subdivision: The first subdivision name :param city: The city name :param address_country_code: The user's country_code, as detected from billi...
def scrobble( self, artist, title, timestamp, album=None, album_artist=None, track_number=None, duration=None, stream_id=None, context=None, mbid=None, ): """Used to add a track-play to a user's profile. Parame...
Used to add a track-play to a user's profile. Parameters: artist (Required) : The artist name. title (Required) : The track name. timestamp (Required) : The time the track started playing, in UNIX timestamp format (integer number of seconds since 00:00:00, ...
def get_png_data_url(blob: Optional[bytes]) -> str: """ Converts a PNG blob into a local URL encapsulating the PNG. """ return BASE64_PNG_URL_PREFIX + base64.b64encode(blob).decode('ascii')
Converts a PNG blob into a local URL encapsulating the PNG.
def CheckEmail(self, email, checkTypo=False): '''Checks a Single email if it is correct''' contents = email.split('@') if len(contents) == 2: if contents[1] in self.valid: return True return False
Checks a Single email if it is correct
def _get_parameter_intervals(self): """Returns the intervals for the methods parameter. Only parameters with defined intervals can be used for optimization! :return: Returns a dictionary containing the parameter intervals, using the parameter name as key, while the value hast th...
Returns the intervals for the methods parameter. Only parameters with defined intervals can be used for optimization! :return: Returns a dictionary containing the parameter intervals, using the parameter name as key, while the value hast the following format: [minValue, maxV...
def setup_catalogs( portal, catalogs_definition={}, force_reindex=False, catalogs_extension={}, force_no_reindex=False): """ Setup the given catalogs. Redefines the map between content types and catalogs and then checks the indexes and metacolumns, if one index/column doesn't exist in th...
Setup the given catalogs. Redefines the map between content types and catalogs and then checks the indexes and metacolumns, if one index/column doesn't exist in the catalog_definition any more it will be removed, otherwise, if a new index/column is found, it will be created. :param portal: The Plone's ...
def get_timestats_str(unixtime_list, newlines=1, full=True, isutc=True): r""" Args: unixtime_list (list): newlines (bool): Returns: str: timestat_str CommandLine: python -m utool.util_time --test-get_timestats_str Example: >>> # ENABLE_DOCTEST >>> f...
r""" Args: unixtime_list (list): newlines (bool): Returns: str: timestat_str CommandLine: python -m utool.util_time --test-get_timestats_str Example: >>> # ENABLE_DOCTEST >>> from utool.util_time import * # NOQA >>> import utool as ut >...
def checkPos(self): """check all positions""" soup = BeautifulSoup(self.css1(path['movs-table']).html, 'html.parser') poss = [] for label in soup.find_all("tr"): pos_id = label['id'] # init an empty list # check if it already exist pos_list...
check all positions
def receivetime_delay(self, tid, days, session): '''taobao.trade.receivetime.delay 延长交易收货时间 延长交易收货时间''' request = TOPRequest('taobao.trade.receivetime.delay') request['tid'] = tid request['days'] = days self.create(self.execute(request, session)['trade']) ...
taobao.trade.receivetime.delay 延长交易收货时间 延长交易收货时间
def do_raise(self, arg): """Raise the last exception caught.""" self.do_continue(arg) # Annotating the exception for a continual re-raise _, exc_value, _ = self.exc_info exc_value._ipdbugger_let_raise = True raise_(*self.exc_info)
Raise the last exception caught.
def CreateApproval(self, reason=None, notified_users=None, email_cc_addresses=None): """Create a new approval for the current user to access this hunt.""" if not reason: raise ValueError("reason can't be empty") if not notified_users: ...
Create a new approval for the current user to access this hunt.
def addRNAQuantification(self, datafields): """ Adds an RNAQuantification to the db. Datafields is a tuple in the order: id, feature_set_ids, description, name, read_group_ids, programs, biosample_id """ self._rnaValueList.append(datafields) if len(self._...
Adds an RNAQuantification to the db. Datafields is a tuple in the order: id, feature_set_ids, description, name, read_group_ids, programs, biosample_id
def reverse_format(format_string, resolved_string): """ Reverse the string method format. Given format_string and resolved_string, find arguments that would give ``format_string.format(**arguments) == resolved_string`` Parameters ---------- format_string : str Format template strin...
Reverse the string method format. Given format_string and resolved_string, find arguments that would give ``format_string.format(**arguments) == resolved_string`` Parameters ---------- format_string : str Format template string as used with str.format method resolved_string : str ...
def mxmt(m1, m2): """ Multiply a 3x3 matrix and the transpose of another 3x3 matrix. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mxmt_c.html :param m1: 3x3 double precision matrix. :type m1: 3x3-Element Array of floats :param m2: 3x3 double precision matrix. :type m2: 3x3-Eleme...
Multiply a 3x3 matrix and the transpose of another 3x3 matrix. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mxmt_c.html :param m1: 3x3 double precision matrix. :type m1: 3x3-Element Array of floats :param m2: 3x3 double precision matrix. :type m2: 3x3-Element Array of floats :return...
def is_callable_tag(tag): """ Determine whether :tag: is a valid callable string tag. String is assumed to be valid callable if it starts with '{{' and ends with '}}'. :param tag: String name of tag. """ return (isinstance(tag, six.string_types) and tag.strip().startswith('{{') and...
Determine whether :tag: is a valid callable string tag. String is assumed to be valid callable if it starts with '{{' and ends with '}}'. :param tag: String name of tag.
def write_dataframe_to_idb(self, ticker): """Write Pandas Dataframe to InfluxDB database""" cachepath = self._cache cachefile = ('%s/%s-1M.csv.gz' % (cachepath, ticker)) if not os.path.exists(cachefile): log.warn('Import file does not exist: %s' % (cache...
Write Pandas Dataframe to InfluxDB database
def get_nve_vni_switch_bindings(vni, switch_ip): """Return the nexus nve binding(s) per switch.""" LOG.debug("get_nve_vni_switch_bindings() called") session = bc.get_reader_session() try: return (session.query(nexus_models_v2.NexusNVEBinding). filter_by(vni=vni, switch_ip=switch_...
Return the nexus nve binding(s) per switch.
def retry(self): """ Retry payment on this invoice if it isn't paid, closed, or forgiven.""" if not self.paid and not self.forgiven and not self.closed: stripe_invoice = self.api_retrieve() updated_stripe_invoice = ( stripe_invoice.pay() ) # pay() throws an exception if the charge is not successful. ...
Retry payment on this invoice if it isn't paid, closed, or forgiven.
def add(self, key, val, minutes): """ Store an item in the cache if it does not exist. :param key: The cache key :type key: str :param val: The cache value :type val: mixed :param minutes: The lifetime in minutes of the cached value :type minutes: int|d...
Store an item in the cache if it does not exist. :param key: The cache key :type key: str :param val: The cache value :type val: mixed :param minutes: The lifetime in minutes of the cached value :type minutes: int|datetime :rtype: bool
def compile_bundle_entry(self, spec, entry): """ Handler for each entry for the bundle method of the compile process. This copies the source file or directory into the build directory. """ modname, source, target, modpath = entry bundled_modpath = {modname: modp...
Handler for each entry for the bundle method of the compile process. This copies the source file or directory into the build directory.
def remove_group_roles(request, group, domain=None, project=None): """Removes all roles from a group on a domain or project.""" client = keystoneclient(request, admin=True) roles = client.roles.list(group=group, domain=domain, project=project) for role in roles: remove_group_role(request, role=r...
Removes all roles from a group on a domain or project.
def normalize(self, mag=1.): """Normalize a Channel, set `null` to 0 and the mag to given value. Parameters ---------- mag : float (optional) New value of mag. Default is 1. """ def f(dataset, s, null, mag): dataset[s] -= null dataset...
Normalize a Channel, set `null` to 0 and the mag to given value. Parameters ---------- mag : float (optional) New value of mag. Default is 1.
def load_many(self, keys): # type: (Iterable[Hashable]) -> Promise """ Loads multiple keys, promising an array of values >>> a, b = await my_loader.load_many([ 'a', 'b' ]) This is equivalent to the more verbose: >>> a, b = await Promise.all([ >>> my_loader.l...
Loads multiple keys, promising an array of values >>> a, b = await my_loader.load_many([ 'a', 'b' ]) This is equivalent to the more verbose: >>> a, b = await Promise.all([ >>> my_loader.load('a'), >>> my_loader.load('b') >>> ])
def resource_show(resource_id, extra_args=None, cibfile=None): ''' Show a resource via pcs command resource_id name of the resource extra_args additional options for the pcs command cibfile use cibfile instead of the live CIB CLI Example: .. code-block:: bash ...
Show a resource via pcs command resource_id name of the resource extra_args additional options for the pcs command cibfile use cibfile instead of the live CIB CLI Example: .. code-block:: bash salt '*' pcs.resource_show resource_id='galera' cibfile='/tmp/cib_for_g...
def _tokenize_wordpiece(self, text): """Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform tokenization using the given vocabulary. For example: input = "unaffable" output = ["un", "##aff", "##able"] ...
Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform tokenization using the given vocabulary. For example: input = "unaffable" output = ["un", "##aff", "##able"] Args: text: A single token or whitespa...
def get_model(self): """ Returns the model instance of the ProbModel. Return --------------- model: an instance of BayesianModel. Examples ------- >>> reader = ProbModelXMLReader() >>> reader.get_model() """ if self.probnet.get('t...
Returns the model instance of the ProbModel. Return --------------- model: an instance of BayesianModel. Examples ------- >>> reader = ProbModelXMLReader() >>> reader.get_model()
def print_preview(self, print_area, print_data): """Launch print preview""" if cairo is None: return print_info = \ self.main_window.interfaces.get_cairo_export_info("Print") if print_info is None: # Dialog has been canceled return ...
Launch print preview
def bin_remove(self): """Remove Slackware packages """ packages = self.args[1:] options = [ "-r", "--removepkg" ] additional_options = [ "--deps", "--check-deps", "--tag", "--checklist" ] ...
Remove Slackware packages
def get_key_field(ui, ui_option_name, default_val=0, default_is_number=True): """ parse an option from a UI object as the name of a key field. If the named option is not set, return the default values for the tuple. :return: a tuple of two items, first is the value of the option, second is ...
parse an option from a UI object as the name of a key field. If the named option is not set, return the default values for the tuple. :return: a tuple of two items, first is the value of the option, second is a boolean value that indicates whether the value is a column name or a colu...
def to_trajectory(self, show_ports=False, chains=None, residues=None, box=None): """Convert to an md.Trajectory and flatten the compound. Parameters ---------- show_ports : bool, optional, default=False Include all port atoms when converting to trajecto...
Convert to an md.Trajectory and flatten the compound. Parameters ---------- show_ports : bool, optional, default=False Include all port atoms when converting to trajectory. chains : mb.Compound or list of mb.Compound Chain types to add to the topology res...
def _get_entity_id(field_name, attrs): """Find the ID for a one to one relationship. The server may return JSON data in the following forms for a :class:`nailgun.entity_fields.OneToOneField`:: 'user': None 'user': {'name': 'Alice Hayes', 'login': 'ahayes', 'id': 1} 'user_id': 1 ...
Find the ID for a one to one relationship. The server may return JSON data in the following forms for a :class:`nailgun.entity_fields.OneToOneField`:: 'user': None 'user': {'name': 'Alice Hayes', 'login': 'ahayes', 'id': 1} 'user_id': 1 'user_id': None Search ``attrs`` for...
def favorite_remove(self, post_id): """Remove a post from favorites (Requires login). Parameters: post_id (int): Where post_id is the post id. """ return self._get('favorites/{0}.json'.format(post_id), method='DELETE', auth=True)
Remove a post from favorites (Requires login). Parameters: post_id (int): Where post_id is the post id.
def highlightBlock(self, text): """ Actually highlight the block""" # Note that an undefined blockstate is equal to -1, so the first block # will have the correct behaviour of starting at 0. if self._allow_highlight: start = self.previousBlockState() + 1 end...
Actually highlight the block
def export(self, nidm_version, export_dir): """ Create prov entities and activities. """ self.add_attributes(( (PROV['type'], self.type), (NIDM_GROUP_NAME, self.group_name), (NIDM_NUMBER_OF_SUBJECTS, self.num_subjects), (PROV['label'], self...
Create prov entities and activities.
def folderitems(self): """Returns an array of dictionaries, each dictionary represents an analysis row to be rendered in the list. The array returned is sorted in accordance with the layout positions set for the analyses this worksheet contains when the analyses were added in the workshe...
Returns an array of dictionaries, each dictionary represents an analysis row to be rendered in the list. The array returned is sorted in accordance with the layout positions set for the analyses this worksheet contains when the analyses were added in the worksheet. :returns: list of dic...
def get_interpolated_value(self, x): """ Returns an interpolated y value for a particular x value. Args: x: x value to return the y value for Returns: Value of y at x """ if len(self.ydim) == 1: return get_linear_interpolated_value(s...
Returns an interpolated y value for a particular x value. Args: x: x value to return the y value for Returns: Value of y at x
def from_env(key: str, default: T = None) -> Union[str, Optional[T]]: """Shortcut for safely reading environment variable. :param key: Environment var key. :param default: Return default value if environment var not found by given key. By default: ``None`` """ return os.getenv(key, ...
Shortcut for safely reading environment variable. :param key: Environment var key. :param default: Return default value if environment var not found by given key. By default: ``None``
def stop(self): """Gracefully shutdown a server that is serving forever.""" self.ready = False if self._start_time is not None: self._run_time += (time.time() - self._start_time) self._start_time = None sock = getattr(self, 'socket', None) if sock: ...
Gracefully shutdown a server that is serving forever.
def _load_parameters(self): """ Load the .mlaunch_startup file that exists in each datadir. Handles different protocol versions. """ datapath = self.dir startup_file = os.path.join(datapath, '.mlaunch_startup') if not os.path.exists(startup_file): re...
Load the .mlaunch_startup file that exists in each datadir. Handles different protocol versions.
def _handle_files(self, data): """Handle new files being uploaded""" initial = data.get("set", False) files = data["files"] for f in files: try: fobj = File( self.room, self.conn, f[0], ...
Handle new files being uploaded
def get_provides(self, ignored=tuple()): """ a map of provided classes and class members, and what provides them. ignored is an optional list of globbed patterns indicating packages, classes, etc that shouldn't be included in the provides map""" if self._provides is None: ...
a map of provided classes and class members, and what provides them. ignored is an optional list of globbed patterns indicating packages, classes, etc that shouldn't be included in the provides map
def get_certificate_issuer(self, certificate_issuer_id, **kwargs): # noqa: E501 """Get certificate issuer by ID. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.get_certificate_i...
Get certificate issuer by ID. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.get_certificate_issuer(certificate_issuer_id, asynchronous=True) >>> result = thread.get() :...
def times(self, query): """ Retorna o resultado da busca ao Cartola por um determinado termo de pesquisa. Args: query (str): Termo para utilizar na busca. Returns: Uma lista de instâncias de cartolafc.TimeInfo, uma para cada time contento o termo utilizado na busca. ...
Retorna o resultado da busca ao Cartola por um determinado termo de pesquisa. Args: query (str): Termo para utilizar na busca. Returns: Uma lista de instâncias de cartolafc.TimeInfo, uma para cada time contento o termo utilizado na busca.
def transfer(self, payment_id, data={}, **kwargs): """" Create Transfer for given Payment Id Args: payment_id : Id for which payment object has to be transfered Returns: Payment dict after getting transfered """ url = "{}/{}/transfers".format(sel...
Create Transfer for given Payment Id Args: payment_id : Id for which payment object has to be transfered Returns: Payment dict after getting transfered
def createImageObjectList(files,instrpars,group=None, undistort=True, inmemory=False): """ Returns a list of imageObject instances, 1 for each input image in the list of input filenames. """ imageObjList = [] mtflag = False mt_refimg = None for img in files: i...
Returns a list of imageObject instances, 1 for each input image in the list of input filenames.
def set_filesystems( name, device, vfstype, opts='-', mount='true', config='/etc/filesystems', test=False, match_on='auto', **kwargs): ''' .. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the ...
.. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. ...
def batchInsert(self, itemType, itemAttributes, dataRows): """ Create multiple items in the store without loading corresponding Python objects into memory. the items' C{stored} callback will not be called. Example:: myData = [(37, u"Fred", u"Wichita"), ...
Create multiple items in the store without loading corresponding Python objects into memory. the items' C{stored} callback will not be called. Example:: myData = [(37, u"Fred", u"Wichita"), (28, u"Jim", u"Fresno"), (43, u"Betty", u"Du...
def recursive_directory_listing( log, baseFolderPath, whatToList="all" ): """*list directory contents recursively.* Options to list only files or only directories. **Key Arguments:** - ``log`` -- logger - ``baseFolderPath`` -- path to the base folder to list contained files and...
*list directory contents recursively.* Options to list only files or only directories. **Key Arguments:** - ``log`` -- logger - ``baseFolderPath`` -- path to the base folder to list contained files and folders recursively - ``whatToList`` -- list files only, durectories only or all [ "...
def url_decode(s, charset='utf-8', decode_keys=False, include_empty=True, errors='replace', separator='&', cls=None): """Parse a querystring and return it as :class:`MultiDict`. Per default only values are decoded into unicode strings. If `decode_keys` is set to `True` the same will happen ...
Parse a querystring and return it as :class:`MultiDict`. Per default only values are decoded into unicode strings. If `decode_keys` is set to `True` the same will happen for keys. Per default a missing value for a key will default to an empty key. If you don't want that behavior you can set `include...
def ecc_correct_intra(ecc_manager_intra, ecc_params_intra, field, ecc, enable_erasures=False, erasures_char="\x00", only_erasures=False): """ Correct an intra-field with its corresponding intra-ecc if necessary """ fentry_fields = {"ecc_field": ecc} field_correct = [] # will store each block of the correcte...
Correct an intra-field with its corresponding intra-ecc if necessary
def download_and_uncompress(self, fileobj, dst_path): """Streams the content for the 'fileobj' and stores the result in dst_path. Args: fileobj: File handle pointing to .tar/.tar.gz content. dst_path: Absolute path where to store uncompressed data from 'fileobj'. Raises: ValueError: Unkn...
Streams the content for the 'fileobj' and stores the result in dst_path. Args: fileobj: File handle pointing to .tar/.tar.gz content. dst_path: Absolute path where to store uncompressed data from 'fileobj'. Raises: ValueError: Unknown object encountered inside the TAR file.
def _remove_unicode_keys(dictobj): """Convert keys from 'unicode' to 'str' type. workaround for <http://bugs.python.org/issue2646> """ if sys.version_info[:2] >= (3, 0): return dictobj assert isinstance(dictobj, dict) newdict = {} for key, value in dictobj.items(): if type(key) is...
Convert keys from 'unicode' to 'str' type. workaround for <http://bugs.python.org/issue2646>
def _get_numbering(document, numid, ilvl): """Returns type for the list. :Returns: Returns type for the list. Returns "bullet" by default or in case of an error. """ try: abs_num = document.numbering[numid] return document.abstruct_numbering[abs_num][ilvl]['numFmt'] except: ...
Returns type for the list. :Returns: Returns type for the list. Returns "bullet" by default or in case of an error.
def writeTicks(self, ticks): ''' read quotes ''' self.__writeData(self.targetPath(ExcelDAM.TICK), TICK_FIELDS, [[getattr(tick, field) for field in TICK_FIELDS] for tick in ticks])
read quotes
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'sentence_id') and self.sentence_id is not None: _dict['sentence_id'] = self.sentence_id if hasattr(self, 'text') and self.text is not None: _dict['text'] = sel...
Return a json dictionary representing this model.
def clear_copyright_registration(self): """Removes the copyright registration. raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from te...
Removes the copyright registration. raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.*
async def post_subscribe(request): """ --- tags: - Events summary: Subscribe to events. operationId: events.subscribe produces: - text/plain parameters: - in: body name: body description: Event message required: true schema: typ...
--- tags: - Events summary: Subscribe to events. operationId: events.subscribe produces: - text/plain parameters: - in: body name: body description: Event message required: true schema: type: object properties: ...
def run(self, collector, image, available_actions, tasks, **extras): """Run this task""" task_func = available_actions[self.action] configuration = collector.configuration.wrapped() if self.options: if image: configuration.update({"images": {image: self.optio...
Run this task
def destroy(self): """Recursively destroy all Controllers The method remove all controllers, which calls the destroy method of the child controllers. Then, all registered models are relieved and and the widget hand by the initial view argument is destroyed. """ self.disconnect_a...
Recursively destroy all Controllers The method remove all controllers, which calls the destroy method of the child controllers. Then, all registered models are relieved and and the widget hand by the initial view argument is destroyed.
def symlink_exists(self, symlink): """Checks whether a symbolic link exists in the guest. in symlink of type str Path to the alleged symbolic link. Guest path style. return exists of type bool Returns @c true if the symbolic link exists. Returns @c false if it ...
Checks whether a symbolic link exists in the guest. in symlink of type str Path to the alleged symbolic link. Guest path style. return exists of type bool Returns @c true if the symbolic link exists. Returns @c false if it does not exist, if the file system object...
def add_to_message(data, indent_level=0) -> list: """Adds data to the message object""" message = [] if isinstance(data, str): message.append(indent( dedent(data.strip('\n')).strip(), indent_level * ' ' )) return message for line in data: offset...
Adds data to the message object
def rss_create(channel, articles): """Create RSS xml feed. :param channel: channel info [title, link, description, language] :type channel: dict(str, str) :param articles: list of articles, an article is a dictionary with some \ required fields [title, description, link] and any optional, which wil...
Create RSS xml feed. :param channel: channel info [title, link, description, language] :type channel: dict(str, str) :param articles: list of articles, an article is a dictionary with some \ required fields [title, description, link] and any optional, which will \ result to `<dict_key>dict_value</d...
def confirm(self, tid, out_sid, session): '''taobao.logistics.online.confirm 确认发货通知接口 确认发货的目的是让交易流程继承走下去,确认发货后交易状态会由【买家已付款】变为【卖家已发货】,然后买家才可以确认收货,货款打入卖家账号。货到付款的订单除外''' request = TOPRequest('taobao.logistics.online.confirm') request['tid'] = tid request['out_sid'] = out_si...
taobao.logistics.online.confirm 确认发货通知接口 确认发货的目的是让交易流程继承走下去,确认发货后交易状态会由【买家已付款】变为【卖家已发货】,然后买家才可以确认收货,货款打入卖家账号。货到付款的订单除外
def datacenters(gandi, id): """List available datacenters.""" output_keys = ['iso', 'name', 'country', 'dc_code', 'status'] if id: output_keys.append('id') result = gandi.datacenter.list() for num, dc in enumerate(result): if num: gandi.separator_line() output_da...
List available datacenters.
def set_file_encoding(self, path, encoding): """ Cache encoding for the specified file path. :param path: path of the file to cache :param encoding: encoding to cache """ try: map = json.loads(self._settings.value('cachedFileEncodings')) except TypeEr...
Cache encoding for the specified file path. :param path: path of the file to cache :param encoding: encoding to cache
def set_permutation_symmetry(force_constants): """Enforce permutation symmetry to force cosntants by Phi_ij_ab = Phi_ji_ba i, j: atom index a, b: Cartesian axis index This is not necessary for harmonic phonon calculation because this condition is imposed when making dynamical matrix Hermite i...
Enforce permutation symmetry to force cosntants by Phi_ij_ab = Phi_ji_ba i, j: atom index a, b: Cartesian axis index This is not necessary for harmonic phonon calculation because this condition is imposed when making dynamical matrix Hermite in dynamical_matrix.py.
def _file_read(path): ''' Read a file and return content ''' content = False if os.path.exists(path): with salt.utils.files.fopen(path, 'r+') as fp_: content = salt.utils.stringutils.to_unicode(fp_.read()) fp_.close() return content
Read a file and return content
def process_raw(self, raw: dict) -> None: """Pre-process raw dict. Prepare parameters to work with APIItems. """ raw_ports = {} for param in raw: port_index = REGEX_PORT_INDEX.search(param).group(0) if port_index not in raw_ports: raw_po...
Pre-process raw dict. Prepare parameters to work with APIItems.
def _definition_from_example(example): """Generates a swagger definition json from a given example Works only for simple types in the dict Args: example: The example for which we want a definition Type is DICT Returns: A dict that is the ...
Generates a swagger definition json from a given example Works only for simple types in the dict Args: example: The example for which we want a definition Type is DICT Returns: A dict that is the swagger definition json
def _save_current(self, settings, axes_active=True): ''' Sets the current in Amperes (A) by axis. Currents are limited to be between 0.0-2.0 amps per axis motor. Note: this method does not send gcode commands, but instead stores the desired current setting. A seperate call to _g...
Sets the current in Amperes (A) by axis. Currents are limited to be between 0.0-2.0 amps per axis motor. Note: this method does not send gcode commands, but instead stores the desired current setting. A seperate call to _generate_current_command() will return a gcode command that can be...