positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def pad_width(model, table_padding=0.85, tabs_padding=1.2): """ Computes the width of a model and sets up appropriate padding for Tabs and DataTable types. """ if isinstance(model, Row): vals = [pad_width(child) for child in model.children] width = np.max([v for v in vals if v is not...
Computes the width of a model and sets up appropriate padding for Tabs and DataTable types.
def services(self): """ returns all the service objects in the admin service's page """ self._services = [] params = {"f": "json"} if not self._url.endswith('/services'): uURL = self._url + "/services" else: uURL = self._url res = self._get(url=uUR...
returns all the service objects in the admin service's page
def find(self, board: Union[chess.Board, int], *, minimum_weight: int = 1, exclude_moves: Container[chess.Move] = ()) -> Entry: """ Finds the main entry for the given position or Zobrist hash. The main entry is the (first) entry with the highest weight. By default, entries with weight ...
Finds the main entry for the given position or Zobrist hash. The main entry is the (first) entry with the highest weight. By default, entries with weight ``0`` are excluded. This is a common way to delete entries from an opening book without compacting it. Pass *minimum_weight* ``0`` t...
def find_credentials(): ''' Cycle through all the possible credentials and return the first one that works. ''' # if the username and password were already found don't fo though the # connection process again if 'username' in DETAILS and 'password' in DETAILS: return DETAILS['userna...
Cycle through all the possible credentials and return the first one that works.
def cumulative_statistics(self): """ Access the cumulative_statistics :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsList :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQ...
Access the cumulative_statistics :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsList :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsList
def get_unicode_str(obj): """Makes sure obj is a unicode string.""" if isinstance(obj, six.text_type): return obj if isinstance(obj, six.binary_type): return obj.decode("utf-8", errors="ignore") return six.text_type(obj)
Makes sure obj is a unicode string.
def get_events(self, user_id, start_date=None): """Gets the event log for a specific user, default start_date is 30 days ago :param int id: User id to view :param string start_date: "%Y-%m-%dT%H:%M:%s.0000-06:00" is the full formatted string. The Timezone part ...
Gets the event log for a specific user, default start_date is 30 days ago :param int id: User id to view :param string start_date: "%Y-%m-%dT%H:%M:%s.0000-06:00" is the full formatted string. The Timezone part has to be HH:MM, notice the : there. :returns: http...
def get_utm_zone(longitude): """Return utm zone.""" zone = int((math.floor((longitude + 180.0) / 6.0) + 1) % 60) if zone == 0: zone = 60 return zone
Return utm zone.
def start(self): ''' start display :rtype: self ''' if self.use_xauth: self._setup_xauth() EasyProcess.start(self) # https://github.com/ponty/PyVirtualDisplay/issues/2 # https://github.com/ponty/PyVirtualDisplay/issues/14 self.old_dis...
start display :rtype: self
def open_file(infile, verbose=True): """ Open file and return a list of the file's lines. Try to use utf-8 encoding, and if that fails use Latin-1. Parameters ---------- infile : str full path to file Returns ---------- data: list all lines in the file """ t...
Open file and return a list of the file's lines. Try to use utf-8 encoding, and if that fails use Latin-1. Parameters ---------- infile : str full path to file Returns ---------- data: list all lines in the file
def _wrlog_details_illegal_gaf(self, fout_err, err_cnts): """Print details regarding illegal GAF lines seen to a log file.""" # fout_err = "{}.log".format(fin_gaf) gaf_base = os.path.basename(fout_err) with open(fout_err, 'w') as prt: prt.write("ILLEGAL GAF ERROR SUMMARY:\n\n...
Print details regarding illegal GAF lines seen to a log file.
def create_route_func(self, method): """ create_route_func """ def _route(resource, handler, schema=None): """ _route """ route = self.routes.get(resource, Route(resource)) route.__getattribute__(method)(handler, schema) ...
create_route_func
def aggregated_relevant_items(raw_df): """ Aggragation for calculate mean and std. """ df = ( raw_df[['idSegmento', 'idPlanilhaItens', 'VlUnitarioAprovado']] .groupby(by=['idSegmento', 'idPlanilhaItens']) .agg([np.mean, lambda x: np.std(x, ddof=0)]) ) df.columns = df.colu...
Aggragation for calculate mean and std.
def endline_repl(self, inputstring, reformatting=False, **kwargs): """Add end of line comments.""" out = [] ln = 1 # line number for line in inputstring.splitlines(): add_one_to_ln = False try: if line.endswith(lnwrapper): line...
Add end of line comments.
def getaddresses (addr): """Return list of email addresses from given field value.""" parsed = [mail for name, mail in AddressList(addr).addresslist if mail] if parsed: addresses = parsed elif addr: # we could not parse any mail addresses, so try with the raw string addresses = [...
Return list of email addresses from given field value.
def _generate_SAX_single(self, sections, value): """ Generate SAX representation(Symbolic Aggregate approXimation) for a single data point. Read more about it here: Assumption-Free Anomaly Detection in Time Series(http://alumni.cs.ucr.edu/~ratana/SSDBM05.pdf). :param dict sections: value...
Generate SAX representation(Symbolic Aggregate approXimation) for a single data point. Read more about it here: Assumption-Free Anomaly Detection in Time Series(http://alumni.cs.ucr.edu/~ratana/SSDBM05.pdf). :param dict sections: value sections. :param float value: value to be categorized. ...
def get_resource_value(self, device_id, resource_path, fix_path=True, timeout=None): """Get a resource value for a given device and resource path by blocking thread. Example usage: .. code-block:: python try: v = api.get_resource_value(device_id, path) ...
Get a resource value for a given device and resource path by blocking thread. Example usage: .. code-block:: python try: v = api.get_resource_value(device_id, path) print("Current value", v) except CloudAsyncError, e: print("Erro...
def _bird_core(X, scales, n_runs, Lambda_W, max_iter=100, stop_crit=np.mean, selection_rule=np.sum, n_jobs=1, indep=True, random_state=None, memory=Memory(None), verbose=False): """Automatically detect when noise zone has been reached and stop MP at th...
Automatically detect when noise zone has been reached and stop MP at this point Parameters ---------- X : array, shape (n_channels, n_times) The numpy n_channels-vy-N array to be denoised where n_channels is number of sensors and N the dimension scales : list The list of MDC...
def raise_412(instance, msg=None): """Abort the current request with a 412 (Precondition Failed) response code. If the message is given it's output as an error message in the response body (correctly converted to the requested MIME type). :param instance: Resource instance (used to access the response)...
Abort the current request with a 412 (Precondition Failed) response code. If the message is given it's output as an error message in the response body (correctly converted to the requested MIME type). :param instance: Resource instance (used to access the response) :type instance: :class:`webob.resourc...
def list_component_status(self, **kwargs): """ list objects of kind ComponentStatus This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_component_status(async_req=True) >>> result ...
list objects of kind ComponentStatus This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_component_status(async_req=True) >>> result = thread.get() :param async_req bool :param st...
def check_downloaded(self, path, maybe_downloaded): """Check if files downloaded and return downloaded packages """ downloaded = [] for pkg in maybe_downloaded: if os.path.isfile(path + pkg): downloaded.append(pkg) return downloaded
Check if files downloaded and return downloaded packages
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'pronunciation') and self.pronunciation is not None: _dict['pronunciation'] = self.pronunciation return _dict
Return a json dictionary representing this model.
def lotus_root_geometry(): """Tomographic geometry for the lotus root dataset. Notes ----- See the article `Tomographic X-ray data of a lotus root filled with attenuating objects`_ for further information. See Also -------- lotus_root_geometry References ---------- .. _Tom...
Tomographic geometry for the lotus root dataset. Notes ----- See the article `Tomographic X-ray data of a lotus root filled with attenuating objects`_ for further information. See Also -------- lotus_root_geometry References ---------- .. _Tomographic X-ray data of a lotus roo...
def import_mod_attr(path): """ Import string format module, e.g. 'uliweb.orm' or an object return module object and object """ import inspect if isinstance(path, (str, unicode)): v = path.split(':') if len(v) == 1: module, func = path.rsplit('.', 1) else: ...
Import string format module, e.g. 'uliweb.orm' or an object return module object and object
def add_federation(self, provider, federated_id): """ Add federated login to the current user :param provider: :param federated_id: :return: """ models.AuthUserFederation.new(user=self, provider=provider, ...
Add federated login to the current user :param provider: :param federated_id: :return:
def get_replacement_types(titles, reportnumbers, publishers): """Given the indices of the titles and reportnumbers that have been recognised within a reference line, create a dictionary keyed by the replacement position in the line, where the value for each key is a string describing the type o...
Given the indices of the titles and reportnumbers that have been recognised within a reference line, create a dictionary keyed by the replacement position in the line, where the value for each key is a string describing the type of item replaced at that position in the line. The descr...
def operators(self, ignore=0): """ Returns a list of operators for this plugin. :return <str> """ return [k for k, v in self._operatorMap.items() if not v.flags & ignore]
Returns a list of operators for this plugin. :return <str>
def add_badge(self, kind): '''Perform an atomic prepend for a new badge''' badge = self.get_badge(kind) if badge: return badge if kind not in getattr(self, '__badges__', {}): msg = 'Unknown badge type for {model}: {kind}' raise db.ValidationError(msg.f...
Perform an atomic prepend for a new badge
def utm_to_pixel(east, north, transform, truncate=True): """ Convert UTM coordinate to image coordinate given a transform :param east: east coordinate of point :type east: float :param north: north coordinate of point :type north: float :param transform: georeferencing transform of the image, e...
Convert UTM coordinate to image coordinate given a transform :param east: east coordinate of point :type east: float :param north: north coordinate of point :type north: float :param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)` :type...
def add_block_widget(self, top=False): """ Return a select widget for blocks which can be added to this column. """ widget = AddBlockSelect(attrs={ 'class': 'glitter-add-block-select', }, choices=self.add_block_options(top=top)) return widget.render(name='', ...
Return a select widget for blocks which can be added to this column.
def resources_of_config(config): """ Returns all resources and models from config. """ return set( # unique values sum([ # join lists to flat list list(value) # if value is iter (ex: list of resources) if hasattr(value, '__iter__') el...
Returns all resources and models from config.
def _element_keywords(cls, backend, elements=None): "Returns a dictionary of element names to allowed keywords" if backend not in Store.loaded_backends(): return {} mapping = {} backend_options = Store.options(backend) elements = elements if elements is not None else...
Returns a dictionary of element names to allowed keywords
def set_mode_px4(self, mode, custom_mode, custom_sub_mode): '''enter arbitrary mode''' if isinstance(mode, str): mode_map = self.mode_mapping() if mode_map is None or mode not in mode_map: print("Unknown mode '%s'" % mode) return # PX4 ...
enter arbitrary mode
def crypt_salt_is_valid(salt): """ Validate a salt as crypt salt :param str salt: a password salt :return: ``True`` if ``salt`` is a valid crypt salt on this system, ``False`` otherwise :rtype: bool """ if len(salt) < 2: return False else: if salt[0] == '...
Validate a salt as crypt salt :param str salt: a password salt :return: ``True`` if ``salt`` is a valid crypt salt on this system, ``False`` otherwise :rtype: bool
def von_neumann_entropy(self, t_max=100): """Calculate Von Neumann Entropy Determines the Von Neumann entropy of the diffusion affinities at varying levels of `t`. The user should select a value of `t` around the "knee" of the entropy curve. We require that 'fit' stores the val...
Calculate Von Neumann Entropy Determines the Von Neumann entropy of the diffusion affinities at varying levels of `t`. The user should select a value of `t` around the "knee" of the entropy curve. We require that 'fit' stores the value of `PHATE.diff_op` in order to calculate t...
def add_ip_address(list_name, item_name): ''' Add an IP address to an IP address list. list_name(str): The name of the specific policy IP address list to append to. item_name(str): The IP address to append to the list. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_ip_...
Add an IP address to an IP address list. list_name(str): The name of the specific policy IP address list to append to. item_name(str): The IP address to append to the list. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.add_ip_address MyIPAddressList 10.0.0.0/24
def get_alpha_or_number(number, template): """Returns an Alphanumber that represents the number passed in, expressed as defined in the template. Otherwise, returns the number """ match = re.match(r".*\{alpha:(\d+a\d+d)\}$", template.strip()) if match and match.groups(): format = match.groups...
Returns an Alphanumber that represents the number passed in, expressed as defined in the template. Otherwise, returns the number
def having(self, expr): """ Add a post-aggregation result filter (like the having argument in `aggregate`), for composability with the group_by API Parameters ---------- expr : ibis.expr.types.Expr Returns ------- grouped : GroupedTableExpr ...
Add a post-aggregation result filter (like the having argument in `aggregate`), for composability with the group_by API Parameters ---------- expr : ibis.expr.types.Expr Returns ------- grouped : GroupedTableExpr
def rsdl_sn(self, U): """Compute dual residual normalisation term. Overriding this method is required if methods :meth:`cnst_A`, :meth:`cnst_AT`, :meth:`cnst_B`, and :meth:`cnst_c` are not overridden. """ return self.rho * np.linalg.norm(self.cnst_AT(U))
Compute dual residual normalisation term. Overriding this method is required if methods :meth:`cnst_A`, :meth:`cnst_AT`, :meth:`cnst_B`, and :meth:`cnst_c` are not overridden.
def setVisible( self, state ): """ Sets whether or not this node is visible in the scene. :param state | <bool> """ self._visible = state super(XNode, self).setVisible(self.isVisible()) self.dispatch.visibilityChanged.emit(state) ...
Sets whether or not this node is visible in the scene. :param state | <bool>
def parse_xml_node(self, node): '''Parse an xml.dom Node object representing a participant into this object. ''' if node.getElementsByTagNameNS(RTS_NS, 'Participant').length != 1: raise InvalidParticipantNodeError self.target_component = TargetComponent().parse_xml_n...
Parse an xml.dom Node object representing a participant into this object.
def init_submodules(self, cache): """cache = path or bool""" self.cache = CacheService(cache, weakref.proxy(self)) self.mesh = PrecomputedMeshService(weakref.proxy(self)) self.skeleton = PrecomputedSkeletonService(weakref.proxy(self))
cache = path or bool
def save_file(self, path: str, file_id: int = None, file_part: int = 0, progress: callable = None, progress_args: tuple = ()): """Use this method to upload a file onto Telegram servers, without actually sending the message...
Use this method to upload a file onto Telegram servers, without actually sending the message to anyone. This is a utility method intended to be used **only** when working with Raw Functions (i.e: a Telegram API method you wish to use which is not available yet in the Client class as an easy-to-use meth...
def uniform(graph, vartype, low=0.0, high=1.0, cls=BinaryQuadraticModel, seed=None): """Generate a bqm with random biases and offset. Biases and offset are drawn from a uniform distribution range (low, high). Args: graph (int/tuple[nodes, edges]/:obj:`~networkx.Graph`): The...
Generate a bqm with random biases and offset. Biases and offset are drawn from a uniform distribution range (low, high). Args: graph (int/tuple[nodes, edges]/:obj:`~networkx.Graph`): The graph to build the bqm loops on. Either an integer n, interpreted as a complete graph of si...
def synthetic_grad(X, theta, sigma1, sigma2, sigmax, rescale_grad=1.0, grad=None): """Get synthetic gradient value""" if grad is None: grad = nd.empty(theta.shape, theta.context) theta1 = theta.asnumpy()[0] theta2 = theta.asnumpy()[1] v1 = sigma1 ** 2 v2 = sigma2 ** 2 vx = sigmax ** ...
Get synthetic gradient value
def find_packages(path): """ Find all java files matching the "*Package.java" pattern within the given enaml package directory relative to the java source path. """ matches = [] root = join(path, 'src', 'main', 'java') for folder, dirnames, filenames in os.walk(root): ...
Find all java files matching the "*Package.java" pattern within the given enaml package directory relative to the java source path.
def export(self, top=True): """Exports object to its string representation. Args: top (bool): if True appends `internal_name` before values. All non list objects should be exported with value top=True, all list objects, that are embedded in as fields inlist ...
Exports object to its string representation. Args: top (bool): if True appends `internal_name` before values. All non list objects should be exported with value top=True, all list objects, that are embedded in as fields inlist objects should be expor...
def dump(self, ret): """ Dumps the return value :param ret: :return: """ if self.args.flatten: ret = drop_none(flatten(ret)) logger.info('Dump: \n' + json.dumps(ret, cls=AutoJSONEncoder, indent=2 if self.args.indent else None))
Dumps the return value :param ret: :return:
def remove_html_tag(input_str='', tag=None): """ Returns a string with the html tag and all its contents from a string """ result = input_str if tag is not None: pattern = re.compile('<{tag}[\s\S]+?/{tag}>'.format(tag=tag)) result = re.sub(pattern, '', str(input_str)) return res...
Returns a string with the html tag and all its contents from a string
def _to_ctfile_counts_line(self, key): """Create counts line in ``CTfile`` format. :param str key: Counts line key. :return: Counts line string. :rtype: :py:class:`str` """ counter = OrderedCounter(self.counts_line_format) self[key]['number_of_atoms'] = str(len(...
Create counts line in ``CTfile`` format. :param str key: Counts line key. :return: Counts line string. :rtype: :py:class:`str`
def _make_request(self, params, translation_url, headers): """ This is the final step, where the request is made, the data is retrieved and returned. """ resp = requests.get(translation_url, params=params, headers=headers) resp.encoding = "UTF-8-sig" ...
This is the final step, where the request is made, the data is retrieved and returned.
def update_user_entitlement(self, document, user_id): """UpdateUserEntitlement. [Preview API] Edit the entitlements (License, Extensions, Projects, Teams etc) for a user. :param :class:`<[JsonPatchOperation]> <azure.devops.v5_0.member_entitlement_management.models.[JsonPatchOperation]>` document...
UpdateUserEntitlement. [Preview API] Edit the entitlements (License, Extensions, Projects, Teams etc) for a user. :param :class:`<[JsonPatchOperation]> <azure.devops.v5_0.member_entitlement_management.models.[JsonPatchOperation]>` document: JsonPatchDocument containing the operations to perform on the u...
def write_task_metadata( self, declaration_datetime=None, flight_date=None, task_number=None, turnpoints=None, text=None): """ Write the task declaration metadata record:: writer.write_task_metadata( datetime.datetime(2014, 4, 13, 12, 53, 02), ...
Write the task declaration metadata record:: writer.write_task_metadata( datetime.datetime(2014, 4, 13, 12, 53, 02), task_number=42, turnpoints=3, ) # -> C140413125302000000004203 There are sensible defaults in place for all p...
def insert(conn, qualified_name: str, column_names, records): """Insert a collection of namedtuple records.""" query = create_insert_statement(qualified_name, column_names) with conn: with conn.cursor(cursor_factory=NamedTupleCursor) as cursor: for record in records: cu...
Insert a collection of namedtuple records.
def quit(self,verbose=False): """ This command causes Cytoscape to exit. It is typically used at the end of a script file. :param verbose: print more """ response=api(url=self.__url+"/quit", verbose=verbose) return response
This command causes Cytoscape to exit. It is typically used at the end of a script file. :param verbose: print more
def env(self, **kw): ''' Allows adding/overriding env vars in the execution context. :param kw: Key-value pairs :return: self ''' self._original_env = kw if self._env is None: self._env = dict(os.environ) self._env.update({k: unicode(v) for k, ...
Allows adding/overriding env vars in the execution context. :param kw: Key-value pairs :return: self
def has_intercept(estimator): # type: (Any) -> bool """ Return True if an estimator has intercept fit. """ if hasattr(estimator, 'fit_intercept'): return estimator.fit_intercept if hasattr(estimator, 'intercept_'): if estimator.intercept_ is None: return False # sciki...
Return True if an estimator has intercept fit.
def get(self, roleId): """Get a specific role information""" role = db.Role.find_one(Role.role_id == roleId) if not role: return self.make_response('No such role found', HTTP.NOT_FOUND) return self.make_response({'role': role})
Get a specific role information
def _paramf(ins): """ Pushes 40bit (float) param into the stack """ output = _float_oper(ins.quad[1]) output.extend(_fpush()) return output
Pushes 40bit (float) param into the stack
def which(filename): '''This takes a given filename; tries to find it in the environment path; then checks if it is executable. This returns the full path to the filename if found and executable. Otherwise this returns None. Note ---- This function is taken from the pexpect module, see module d...
This takes a given filename; tries to find it in the environment path; then checks if it is executable. This returns the full path to the filename if found and executable. Otherwise this returns None. Note ---- This function is taken from the pexpect module, see module doc-string for license.
def add_path(self, nodes, t=None): """Add a path at time t. Parameters ---------- nodes : iterable container A container of nodes. t : snapshot id (default=None) See Also -------- add_path, add_cycle Examples -------- ...
Add a path at time t. Parameters ---------- nodes : iterable container A container of nodes. t : snapshot id (default=None) See Also -------- add_path, add_cycle Examples -------- >>> G = dn.DynGraph() >>> G.add_path(...
def split_qname(qname): """Split `qname` into namespace URI and local name Return namespace and local name as a tuple. This is a static method.""" res = qname.split(YinParser.ns_sep) if len(res) == 1: # no namespace return None, res[0] else: ...
Split `qname` into namespace URI and local name Return namespace and local name as a tuple. This is a static method.
def filter_geoquiet(sat, maxKp=None, filterTime=None, kpData=None, kp_inst=None): """Filters pysat.Instrument data for given time after Kp drops below gate. Loads Kp data for the same timeframe covered by sat and sets sat.data to NaN for times when Kp > maxKp and for filterTime after Kp drops below max...
Filters pysat.Instrument data for given time after Kp drops below gate. Loads Kp data for the same timeframe covered by sat and sets sat.data to NaN for times when Kp > maxKp and for filterTime after Kp drops below maxKp. Parameters ---------- sat : pysat.Instrument Instrument to b...
def ufloatDict_nominal(self, ufloat_dict): 'This gives us a dictionary of nominal values from a dictionary of uncertainties' return OrderedDict(izip(ufloat_dict.keys(), map(lambda x: x.nominal_value, ufloat_dict.values())))
This gives us a dictionary of nominal values from a dictionary of uncertainties
def setup( cls, app_version: str, app_name: str, config_file_path: str, config_sep_str: str, root_path: typing.Optional[typing.List[str]] = None, ): """ Configures elib_config in one fell swoop :param app_version: versi...
Configures elib_config in one fell swoop :param app_version: version of the application :param app_name:name of the application :param config_file_path: path to the config file to use :param config_sep_str: separator for config values paths :param root_path: list of strings that...
def convert_basis(basis_dict, fmt, header=None): ''' Returns the basis set data as a string representing the data in the specified output format ''' # make converters case insensitive fmt = fmt.lower() if fmt not in _converter_map: raise RuntimeError('Unknown basis set format "{}"'....
Returns the basis set data as a string representing the data in the specified output format
def menu(self, choices, prompt='Please choose from the provided options:', error='Invalid choice', intro=None, strict=True, default=None, numerator=lambda x: [i + 1 for i in range(x)], formatter=lambda x, y: '{0:>3}) {1}'.format(x, y), clean=utils.safeint): ""...
Print a menu The choices must be an iterable of two-tuples where the first value is the value of the menu item, and the second is the label for that matches the value. The menu will be printed with numeric choices. For example:: 1) foo 2) bar Formattin...
def __output_see(self, see): """ Convert the argument to a @see tag to rest """ if see.startswith('<a href'): # HTML link -- <a href="...">...</a> return self.__html_to_rst(see) elif '"' in see: # Plain text return see else: # ...
Convert the argument to a @see tag to rest
def _retrieve_all_teams(self, year): """ Find and create Team instances for all teams in the given season. For a given season, parses the specified NCAAB stats table and finds all requested stats. Each team then has a Team instance created which includes all requested stats and ...
Find and create Team instances for all teams in the given season. For a given season, parses the specified NCAAB stats table and finds all requested stats. Each team then has a Team instance created which includes all requested stats and a few identifiers, such as the team's name and ab...
def module(command, *args): """Run the modulecmd tool and use its Python-formatted output to set the environment variables.""" if 'MODULESHOME' not in os.environ: print('payu: warning: No Environment Modules found; skipping {0} call.' ''.format(command)) return modulecmd ...
Run the modulecmd tool and use its Python-formatted output to set the environment variables.
def edit_securitygroup_rule(self, group_id, rule_id, remote_ip=None, remote_group=None, direction=None, ethertype=None, port_max=None, port_min=None, protocol=None): """Edit a security group rule. :param int...
Edit a security group rule. :param int group_id: The ID of the security group the rule belongs to :param int rule_id: The ID of the rule to edit :param str remote_ip: The remote IP or CIDR to enforce the rule on :param int remote_group: The remote security group ID to enforce ...
def get_ga_query_dict(self): """ Adds user agent and IP to the default hit parameters """ query_dict = super(GARequestErrorReportingMixin, self).get_ga_query_dict() request = self.get_ga_request() if not request: return query_dict user_ip = request.MET...
Adds user agent and IP to the default hit parameters
def checker(func: Callable) -> Callable: """ A decorator that will convert AssertionErrors into CiVerificationError. :param func: A function that will raise AssertionError :return: The given function wrapped to raise a CiVerificationError on AssertionError """ def func_wrapper(*args, **kwa...
A decorator that will convert AssertionErrors into CiVerificationError. :param func: A function that will raise AssertionError :return: The given function wrapped to raise a CiVerificationError on AssertionError
def is_valid(self, tree): """ returns true, iff the order of the tokens in the graph are the same as in the Conano file (converted to plain text). """ conano_plaintext = etree.tostring(tree, encoding='utf8', method='text') token_str_list = conano_plaintext.split() ...
returns true, iff the order of the tokens in the graph are the same as in the Conano file (converted to plain text).
def correct_means(means, opt_t0s, combs): """Applies optimal t0s to gaussians means. Should be around zero afterwards. Parameters ---------- means: numpy array of means of gaussians of all PMT combinations opt_t0s: numpy array of optimal t0 values for all PMTs combs: pmt combinations used ...
Applies optimal t0s to gaussians means. Should be around zero afterwards. Parameters ---------- means: numpy array of means of gaussians of all PMT combinations opt_t0s: numpy array of optimal t0 values for all PMTs combs: pmt combinations used to correct Returns ------- corrected...
def has_quantity(self, quantity, include_native=True): """ Check if *quantity* is available in this catalog Parameters ---------- quantity : str a quantity name to check include_native : bool, optional whether or not to include native quantity na...
Check if *quantity* is available in this catalog Parameters ---------- quantity : str a quantity name to check include_native : bool, optional whether or not to include native quantity names when checking Returns ------- has_quantity : b...
def _af_filter(data, in_file, out_file): """Soft-filter variants with AF below min_allele_fraction (appends "MinAF" to FILTER) """ min_freq = float(utils.get_in(data["config"], ("algorithm", "min_allele_fraction"), 10)) / 100.0 logger.debug("Filtering MuTect2 calls with allele fraction threshold of %s" ...
Soft-filter variants with AF below min_allele_fraction (appends "MinAF" to FILTER)
def _protobuf_value_type(value): """Returns the type of the google.protobuf.Value message as an api.DataType. Returns None if the type of 'value' is not one of the types supported in api_pb2.DataType. Args: value: google.protobuf.Value message. """ if value.HasField("number_value"): return api_pb2...
Returns the type of the google.protobuf.Value message as an api.DataType. Returns None if the type of 'value' is not one of the types supported in api_pb2.DataType. Args: value: google.protobuf.Value message.
def run_checks(self): """ Iterates over the configured ports and runs the checks on each one. Returns a two-element tuple: the first is the set of ports that transitioned from down to up, the second is the set of ports that transitioned from up to down. Also handles the...
Iterates over the configured ports and runs the checks on each one. Returns a two-element tuple: the first is the set of ports that transitioned from down to up, the second is the set of ports that transitioned from up to down. Also handles the case where a check for a since-removed po...
def input_data_ports(self, input_data_ports): """Property for the _input_data_ports field See Property. :param dict input_data_ports: Dictionary that maps :class:`int` data_port_ids onto values of type :class:`rafcon.core.state_elements.data_port.InputData...
Property for the _input_data_ports field See Property. :param dict input_data_ports: Dictionary that maps :class:`int` data_port_ids onto values of type :class:`rafcon.core.state_elements.data_port.InputDataPort` :raises exceptions.TypeError: if the input_...
def delete_node(self, loadbalancer, node): """Removes the node from its load balancer.""" lb = node.parent if not lb: raise exc.UnattachedNode("No parent Load Balancer for this node " "could be determined.") resp, body = self.api.method_delete("/loadbalanc...
Removes the node from its load balancer.
def parameter_vector(self): """An array of all parameters (including frozen parameters)""" return np.array([getattr(self, k) for k in self.parameter_names])
An array of all parameters (including frozen parameters)
def _open(self): """ open input file, optionally with decompression """ if self.fileName.endswith(".gz"): return gzip.open(self.fileName) elif self.fileName.endswith(".bz2"): return bz2.BZ2File(self.fileName) else: return open(self.file...
open input file, optionally with decompression
def extract_params(raw): """Extract parameters and return them as a list of 2-tuples. Will successfully extract parameters from urlencoded query strings, dicts, or lists of 2-tuples. Empty strings/dicts/lists will return an empty list of parameters. Any other input will result in a return value of ...
Extract parameters and return them as a list of 2-tuples. Will successfully extract parameters from urlencoded query strings, dicts, or lists of 2-tuples. Empty strings/dicts/lists will return an empty list of parameters. Any other input will result in a return value of None.
def low(data, **kwargs): ''' Execute a single low data call This function is mostly intended for testing the state system CLI Example: .. code-block:: bash salt '*' state.low '{"state": "pkg", "fun": "installed", "name": "vi"}' ''' st_kwargs = __salt__.kwargs __opts__['grains'...
Execute a single low data call This function is mostly intended for testing the state system CLI Example: .. code-block:: bash salt '*' state.low '{"state": "pkg", "fun": "installed", "name": "vi"}'
def fire_metric(metric_name, metric_value): """ Fires a metric using the MetricsApiClient """ metric_value = float(metric_value) metric = {metric_name: metric_value} metric_client.fire_metrics(**metric) return "Fired metric <{}> with value <{}>".format(metric_name, metric_value)
Fires a metric using the MetricsApiClient
def _get(self, obj): ''' Internal implementation of instance attribute access for the ``BasicPropertyDescriptor`` getter. If the value has not been explicitly set by a user, return that value. Otherwise, return the default. Args: obj (HasProps) : the instance to get...
Internal implementation of instance attribute access for the ``BasicPropertyDescriptor`` getter. If the value has not been explicitly set by a user, return that value. Otherwise, return the default. Args: obj (HasProps) : the instance to get a value of this property for ...
async def get_models(self, all_=False, username=None): """ .. deprecated:: 0.7.0 Use :meth:`.list_models` instead. """ controller_facade = client.ControllerFacade.from_connection( self.connection()) for attempt in (1, 2, 3): try: ...
.. deprecated:: 0.7.0 Use :meth:`.list_models` instead.
def receive(self): """ :rtype: bytes """ try: return self.socket.recv(self.__recv_bytes) except socket.error: _, e, _ = sys.exc_info() if get_errno(e) in (errno.EAGAIN, errno.EINTR): log.debug("socket read interrupted, restartin...
:rtype: bytes
def import_module(path): """ Import a module given a dotted *path* in the form of ``.name(.name)*``, and returns the last module (unlike ``__import__`` which just returns the first module). :param path: The dotted path to the module. """ mod = __import__(path, locals={}, globals={}) ...
Import a module given a dotted *path* in the form of ``.name(.name)*``, and returns the last module (unlike ``__import__`` which just returns the first module). :param path: The dotted path to the module.
def modify_agent(self, agent_id, **kwargs): ''' modify_agent(self, agent_id, **kwargs) | Modifies agent information (like name) :Parameters: * *agent_id* (`string`) -- Identifier of an existing agent :Example: .. code-block:: python opereto_client ...
modify_agent(self, agent_id, **kwargs) | Modifies agent information (like name) :Parameters: * *agent_id* (`string`) -- Identifier of an existing agent :Example: .. code-block:: python opereto_client = OperetoClient() opereto_client.modify_agent('agentI...
def beautify_date(inasafe_time, feature, parent): """Given an InaSAFE analysis time, it will convert it to a date with year-month-date format. For instance: * beautify_date( @start_datetime ) -> will convert datetime provided by qgis_variable. """ _ = feature, parent # NOQA datet...
Given an InaSAFE analysis time, it will convert it to a date with year-month-date format. For instance: * beautify_date( @start_datetime ) -> will convert datetime provided by qgis_variable.
def smartfields_get_field_status(self, field_name): """A way to find out a status of a filed.""" manager = self._smartfields_managers.get(field_name, None) if manager is not None: return manager.get_status(self) return {'state': 'ready'}
A way to find out a status of a filed.
def _regex_strings(self): """ A property to link into IntentEngine's _regex_strings. Warning: this is only for backwards compatiblility and should not be used if you intend on using domains. Returns: the domains _regex_strings from its IntentEngine """ domai...
A property to link into IntentEngine's _regex_strings. Warning: this is only for backwards compatiblility and should not be used if you intend on using domains. Returns: the domains _regex_strings from its IntentEngine
def main(argv=None): """ Make a confidence report and save it to disk. """ try: _name_of_script, filepath = argv except ValueError: raise ValueError(argv) print(filepath) make_confidence_report_bundled(filepath=filepath, test_start=FLAGS.test_start, ...
Make a confidence report and save it to disk.
def get_atlas_peers(hostport, timeout=30, my_hostport=None, proxy=None): """ Get an atlas peer's neighbors. Return {'status': True, 'peers': [peers]} on success. Return {'error': ...} on error """ assert hostport or proxy, 'need either hostport or proxy' peers_schema = { 'type': 'o...
Get an atlas peer's neighbors. Return {'status': True, 'peers': [peers]} on success. Return {'error': ...} on error
def QA_fetch_get_hkindex_list(ip=None, port=None): """[summary] Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) # 港股 HKMARKET 27 5 香港指数 FH 31 2 香港主板 KH 48 2...
[summary] Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) # 港股 HKMARKET 27 5 香港指数 FH 31 2 香港主板 KH 48 2 香港创业板 KG 49 2 香港基金 ...
def _servicegroup_get_servers(sg_name, **connection_args): ''' Returns a list of members of a servicegroup or None ''' nitro = _connect(**connection_args) if nitro is None: return None sg = NSServiceGroup() sg.set_servicegroupname(sg_name) try: sg = NSServiceGroup.get_ser...
Returns a list of members of a servicegroup or None
def _setup_logging(self): """ This is done in the :class:`Router` constructor for historical reasons. It must be called before ExternalContext logs its first messages, but after logging has been setup. It must also be called when any router is constructed for a consumer app. ...
This is done in the :class:`Router` constructor for historical reasons. It must be called before ExternalContext logs its first messages, but after logging has been setup. It must also be called when any router is constructed for a consumer app.
def join(self, file): """Find the named object in this tree's contents :return: ``git.Blob`` or ``git.Tree`` or ``git.Submodule`` :raise KeyError: if given file or tree does not exist in tree""" msg = "Blob or Tree named %r not found" if '/' in file: tree = self ...
Find the named object in this tree's contents :return: ``git.Blob`` or ``git.Tree`` or ``git.Submodule`` :raise KeyError: if given file or tree does not exist in tree