code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def connection_made(self, transport): """Called when reader thread is started""" self.port = transport.serial.port logger.debug('connection_made: `%s` `%s`', self.port, transport) self.transport = transport self.connected.set() self.disconnected.clear()
Called when reader thread is started
def load_file_as_yaml(path): """ Given a filepath, loads the file as a dictionary from YAML :param path: The path to a YAML file """ with open(path, "r") as f: raw_yaml = f.read() parsed_dict = yaml.load(raw_yaml) return parsed_dict
Given a filepath, loads the file as a dictionary from YAML :param path: The path to a YAML file
def filterAll(self, **kwargs): ''' filterAll aka filterAllAnd - Perform a filter operation on ALL nodes in this collection and all their children. Results must match ALL the filter criteria. for ANY, use the *Or methods For just the nodes in this collection, use "filter" or...
filterAll aka filterAllAnd - Perform a filter operation on ALL nodes in this collection and all their children. Results must match ALL the filter criteria. for ANY, use the *Or methods For just the nodes in this collection, use "filter" or "filterAnd" on a TagCollection For specia...
def volume(self): """ Mesh volume Returns ------- volume : float Total volume of the mesh. """ sizes = self.compute_cell_sizes(length=False, area=False, volume=True) return np.sum(sizes.cell_arrays['Volume'])
Mesh volume Returns ------- volume : float Total volume of the mesh.
def append(self, passes, ignore_requires=None, ignore_preserves=None, max_iteration=None, **flow_controller_conditions): """ Args: passes (list[BasePass] or BasePass): pass(es) to be added to schedule ignore_preserves (bool): ignore the preserves claim of passes. D...
Args: passes (list[BasePass] or BasePass): pass(es) to be added to schedule ignore_preserves (bool): ignore the preserves claim of passes. Default: False ignore_requires (bool): ignore the requires need of passes. Default: False max_iteration (int): max number of iteratio...
def compute_checksum(stream, algo, message_digest, chunk_size=None, progress_callback=None): """Get helper method to compute checksum from a stream. :param stream: File-like object. :param algo: Identifier for checksum algorithm. :param messsage_digest: A message digest instance. ...
Get helper method to compute checksum from a stream. :param stream: File-like object. :param algo: Identifier for checksum algorithm. :param messsage_digest: A message digest instance. :param chunk_size: Read at most size bytes from the file at a time. :param progress_callback: Function accepting o...
def from_dict(input_dict): """ Instantiate an object of a derived class using the information in input_dict (built by the to_dict method of the derived class). More specifically, after reading the derived class from input_dict, it calls the method _build_from_input_dict of the de...
Instantiate an object of a derived class using the information in input_dict (built by the to_dict method of the derived class). More specifically, after reading the derived class from input_dict, it calls the method _build_from_input_dict of the derived class. Note: This method should n...
def ConvertSupportedOSToConditions(src_object): """Turn supported_os into a condition.""" if src_object.supported_os: conditions = " OR ".join("os == '%s'" % o for o in src_object.supported_os) return conditions
Turn supported_os into a condition.
def get_by_start_id(self, start_id): """ :yield: Log entries starting from :start_id: and ending 200 entries after. In most cases easier to call than the paginate one because there is no need to keep track of the already read entries in a specific page. ...
:yield: Log entries starting from :start_id: and ending 200 entries after. In most cases easier to call than the paginate one because there is no need to keep track of the already read entries in a specific page.
def wave(self, wave_first=True, thread_id=None, thread_type=None): """ Says hello with a wave to a thread! :param wave_first: Whether to wave first or wave back :param thread_id: User/Group ID to send to. See :ref:`intro_threads` :param thread_type: See :ref:`intro_threads` ...
Says hello with a wave to a thread! :param wave_first: Whether to wave first or wave back :param thread_id: User/Group ID to send to. See :ref:`intro_threads` :param thread_type: See :ref:`intro_threads` :type thread_type: models.ThreadType :return: :ref:`Message ID <intro_messa...
def from_data(cls, data): """Create a list of Messages from deserialized epubcheck json output. :param dict data: Decoded epubcheck json data :return list[Message]: List of messages """ messages = [] filename = data['checker']['filename'] for m in data['messages'...
Create a list of Messages from deserialized epubcheck json output. :param dict data: Decoded epubcheck json data :return list[Message]: List of messages
def sqlwhere(criteria=None): """Generates SQL where clause. Returns (sql, values). Criteria is a dictionary of {field: value}. >>> sqlwhere() ('', []) >>> sqlwhere({'id': 5}) ('id=%s', [5]) >>> sqlwhere({'id': 3, 'name': 'toto'}) ('id=%s and name=%s', [3, 'toto']) >>> sqlwhere({'id'...
Generates SQL where clause. Returns (sql, values). Criteria is a dictionary of {field: value}. >>> sqlwhere() ('', []) >>> sqlwhere({'id': 5}) ('id=%s', [5]) >>> sqlwhere({'id': 3, 'name': 'toto'}) ('id=%s and name=%s', [3, 'toto']) >>> sqlwhere({'id': 3, 'name': 'toto', 'createdon': '2...
def initiate(self, mechanism, payload=None): """ Initiate the SASL handshake and advertise the use of the given `mechanism`. If `payload` is not :data:`None`, it will be base64 encoded and sent as initial client response along with the ``<auth />`` element. Return the ne...
Initiate the SASL handshake and advertise the use of the given `mechanism`. If `payload` is not :data:`None`, it will be base64 encoded and sent as initial client response along with the ``<auth />`` element. Return the next state of the state machine as tuple (see :class:`SASLS...
def get_variants(self, ref_sequence_name, allowed_ctg_coords, allowed_ref_coords, nucmer_matches=None): '''Nucmr coords = dict. Key=contig name. Value = list of intervals of ref coords that match the contig. Made by assembly_compare.AssemblyCompare.nucmer_hits_to_ref_coords Returns diction...
Nucmr coords = dict. Key=contig name. Value = list of intervals of ref coords that match the contig. Made by assembly_compare.AssemblyCompare.nucmer_hits_to_ref_coords Returns dictionary. Key=contig name. Value = list of variants. Each variant is a tuple: ( 0 = position, ...
def user_info(self, verbose=False): ''' Get information about the currently authenticated user http://docs.opsview.com/doku.php?id=opsview4.6:restapi#user_information ''' url = '{}/{}'.format(self.rest_url, 'user') return self.__auth_req_get(url, verbose=verbose)
Get information about the currently authenticated user http://docs.opsview.com/doku.php?id=opsview4.6:restapi#user_information
def bbox_from_point(point, distance=1000, project_utm=False, return_crs=False): """ Create a bounding box some distance in each direction (north, south, east, and west) from some (lat, lng) point. Parameters ---------- point : tuple the (lat, lon) point to create the bounding box around...
Create a bounding box some distance in each direction (north, south, east, and west) from some (lat, lng) point. Parameters ---------- point : tuple the (lat, lon) point to create the bounding box around distance : int how many meters the north, south, east, and west sides of the bo...
def add_new_peers( self, count, new_peers, current_peers, con=None, path=None, peer_table=None ): """ Ping up to @count new peers from @new_peers that aren't already known to us. If they respond, then add them to the peer set. Return the (list of peers added, the list of peers...
Ping up to @count new peers from @new_peers that aren't already known to us. If they respond, then add them to the peer set. Return the (list of peers added, the list of peers already known, list of peers ignored)
def config_(cls, key, default=None): """ Shortcut to access the config in your class :param key: The key to access :param default: The default value when None :returns mixed: """ return cls._app.config.get(key, default)
Shortcut to access the config in your class :param key: The key to access :param default: The default value when None :returns mixed:
def delete(self): """Remove the statement from a ProcmailRC structure, raise a RuntimeError if the statement is not inside a ProcmailRC structure return the parent id""" if self.parent is None: raise RuntimeError( "Current statement has no parent, so it cannot...
Remove the statement from a ProcmailRC structure, raise a RuntimeError if the statement is not inside a ProcmailRC structure return the parent id
def get_series_as_of_date(self, series_id, as_of_date): """ Get latest data for a Fred series id as known on a particular date. This includes any revision to the data series before or on as_of_date, but ignores any revision on dates after as_of_date. Parameters ---------- ...
Get latest data for a Fred series id as known on a particular date. This includes any revision to the data series before or on as_of_date, but ignores any revision on dates after as_of_date. Parameters ---------- series_id : str Fred series id such as 'GDP' as_of_dat...
def activate(locale): """ Override django's utils.translation.activate(). Django forces files to be named django.mo (http://code.djangoproject.com/ticket/6376). Since that's dumb and we want to be able to load different files depending on what part of the site the user is in, we'll make our own fu...
Override django's utils.translation.activate(). Django forces files to be named django.mo (http://code.djangoproject.com/ticket/6376). Since that's dumb and we want to be able to load different files depending on what part of the site the user is in, we'll make our own function here.
def get_special_inds(sample, label_store, aux_note): """ Get the indices of annotations that hold definition information about the entire annotation file, and other empty annotations to be removed. Note: There is no need to deal with SKIP annotations (label_store=59) which were already dealt ...
Get the indices of annotations that hold definition information about the entire annotation file, and other empty annotations to be removed. Note: There is no need to deal with SKIP annotations (label_store=59) which were already dealt with in proc_core_fields and hence not included here.
def add_dyn(system, model, data): """helper function to elem_add a device element to system""" if model == 'GENCLS': bus = data[0] data = data[3:] if bus in system.PV.bus: dev = 'PV' gen_idx = system.PV.idx[system.PV.bus.index(bus)] elif bus in system.SW.b...
helper function to elem_add a device element to system
def fromcolumns(cols, header=None, missing=None): """View a sequence of columns as a table, e.g.:: >>> import petl as etl >>> cols = [[0, 1, 2], ['a', 'b', 'c']] >>> tbl = etl.fromcolumns(cols) >>> tbl +----+-----+ | f0 | f1 | +====+=====+ | 0 | 'a'...
View a sequence of columns as a table, e.g.:: >>> import petl as etl >>> cols = [[0, 1, 2], ['a', 'b', 'c']] >>> tbl = etl.fromcolumns(cols) >>> tbl +----+-----+ | f0 | f1 | +====+=====+ | 0 | 'a' | +----+-----+ | 1 | 'b' | +---...
def angular_distance_fast(ra1, dec1, ra2, dec2): """ Compute angular distance using the Haversine formula. Use this one when you know you will never ask for points at their antipodes. If this is not the case, use the angular_distance function which is slower, but works also for antipodes. :param lo...
Compute angular distance using the Haversine formula. Use this one when you know you will never ask for points at their antipodes. If this is not the case, use the angular_distance function which is slower, but works also for antipodes. :param lon1: :param lat1: :param lon2: :param lat2: :r...
def ssh_key_info_from_key_data(key_id, priv_key=None): """Get/load SSH key info necessary for signing. @param key_id {str} Either a private ssh key fingerprint, e.g. 'b3:f0:a1:6c:18:3b:42:63:fd:6e:57:42:74:17:d4:bc', or the path to an ssh private key file (like ssh's IdentityFile config option)...
Get/load SSH key info necessary for signing. @param key_id {str} Either a private ssh key fingerprint, e.g. 'b3:f0:a1:6c:18:3b:42:63:fd:6e:57:42:74:17:d4:bc', or the path to an ssh private key file (like ssh's IdentityFile config option). @param priv_key {str} Optional. SSH private key file dat...
def down_the_wabbit_hole(session, class_name): """ Authenticate on class.coursera.org """ auth_redirector_url = AUTH_REDIRECT_URL.format(class_name=class_name) r = session.get(auth_redirector_url) logging.debug('Following %s to authenticate on class.coursera.org.', auth_redir...
Authenticate on class.coursera.org
def get_pull_request(project, num, auth=False): """get pull request info by number """ url = "https://api.github.com/repos/{project}/pulls/{num}".format(project=project, num=num) if auth: header = make_auth_header() else: header = None response = requests.get(url, headers=header...
get pull request info by number
def get_current_waypoints(boatd=None): ''' Get the current set of waypoints active from boatd. :returns: The current waypoints :rtype: List of Points ''' if boatd is None: boatd = Boatd() content = boatd.get('/waypoints') return [Point(*coords) for coords in content.get('waypo...
Get the current set of waypoints active from boatd. :returns: The current waypoints :rtype: List of Points
def GetElementNSdict(self, elt): '''Get a dictionary of all the namespace attributes for the indicated element. The dictionaries are cached, and we recurse up the tree as necessary. ''' d = self.ns_cache.get(id(elt)) if not d: if elt != self.dom: d = self.Get...
Get a dictionary of all the namespace attributes for the indicated element. The dictionaries are cached, and we recurse up the tree as necessary.
def _init_header(self, string): """ Extracts header part from TAF/METAR string and populates header dict Args: TAF/METAR report string Raises: MalformedTAF: An error parsing the report Returns: Header dictionary """ taf_header_patte...
Extracts header part from TAF/METAR string and populates header dict Args: TAF/METAR report string Raises: MalformedTAF: An error parsing the report Returns: Header dictionary
def build(self): """ Builds the query string, which can be used for a search query :return: the query string """ if self.es_version == '1': if len(self.filters) > 0: return { 'filtered': { 'query': self.quer...
Builds the query string, which can be used for a search query :return: the query string
def zadd(self, key, *members, **kwargs): """Adds all the specified members with the specified scores to the sorted set stored at key. It is possible to specify multiple score / member pairs. If a specified member is already a member of the sorted set, the score is updated and the element...
Adds all the specified members with the specified scores to the sorted set stored at key. It is possible to specify multiple score / member pairs. If a specified member is already a member of the sorted set, the score is updated and the element reinserted at the right position to ensure ...
async def handle_client_kill_job(self, client_addr, message: ClientKillJob): """ Handle an ClientKillJob message. Remove a job from the waiting list or send the kill message to the right agent. """ # Check if the job is not in the queue if (client_addr, message.job_id) in self._waiting_jobs: ...
Handle an ClientKillJob message. Remove a job from the waiting list or send the kill message to the right agent.
def _parse_scheme_file(self): """ Initialize redundant data structures for lookup optimization """ schemes = json.loads(self.scheme_file.read(), object_pairs_hook=OrderedDict) scheme_list = [] scheme_dict = defaultdict(list) for scheme_len, scheme_group in schemes...
Initialize redundant data structures for lookup optimization
def satisfiable(self, extra_constraints=(), exact=None): """ This function does a constraint check and checks if the solver is in a sat state. :param extra_constraints: Extra constraints (as ASTs) to add to s for this solve :param exact: If False, return approximate solu...
This function does a constraint check and checks if the solver is in a sat state. :param extra_constraints: Extra constraints (as ASTs) to add to s for this solve :param exact: If False, return approximate solutions. :return: True if sat, otherwise false
def conflicted(path_to_file): """Whether there are any conflict markers in that file""" for line in open(path_to_file, 'r'): for marker in '>="<': if line.startswith(marker * 8): return True return False
Whether there are any conflict markers in that file
def parse(readDataInstance): """ Returns a new L{DosHeader} object. @type readDataInstance: L{ReadData} @param readDataInstance: A L{ReadData} object with data to be parsed as a L{DosHeader} object. @rtype: L{DosHeader} @return: A new L{DosHeader} object...
Returns a new L{DosHeader} object. @type readDataInstance: L{ReadData} @param readDataInstance: A L{ReadData} object with data to be parsed as a L{DosHeader} object. @rtype: L{DosHeader} @return: A new L{DosHeader} object.
def getWindowByTitle(self, wildcard, order=0): """ Returns a handle for the first window that matches the provided "wildcard" regex """ for w in self._get_window_list(): if "kCGWindowName" in w and re.search(wildcard, w["kCGWindowName"], flags=re.I): # Matches - make sure we ...
Returns a handle for the first window that matches the provided "wildcard" regex
def _attribute_definition(self, attrid): """ Returns the attribute definition dict of a given attribute ID, can be the name or the integer ID """ attrs = self._schema["attributes"] try: # Make a new dict to avoid side effects return dict(attrs[attrid]) ex...
Returns the attribute definition dict of a given attribute ID, can be the name or the integer ID
def __init(self): """ initializes the service """ params = { "f" : "json", } json_dict = self._get(self._url, params, securityHandler=self._securityHandler, proxy_port=self._proxy_port, ...
initializes the service
def is_directed(self): r"""Check if the graph has directed edges (cached). In this framework, we consider that a graph is directed if and only if its weight matrix is not symmetric. Returns ------- directed : bool True if the graph is directed, False otherwi...
r"""Check if the graph has directed edges (cached). In this framework, we consider that a graph is directed if and only if its weight matrix is not symmetric. Returns ------- directed : bool True if the graph is directed, False otherwise. Examples -...
def __get_form_data(self, soup): """Build a form data dict from the given form. Args: soup (obj): The BeautifulSoup form. Returns: obj: The form data (key/value). """ elements = self.__get_valid_form_data_elements(soup) form_data = self.__get_d...
Build a form data dict from the given form. Args: soup (obj): The BeautifulSoup form. Returns: obj: The form data (key/value).
def forward(self, x): """Passing data through the network. :param x: 2d tensor containing both (x,y) Variables :return: output of the net """ features = self.conv(x).mean(dim=2) return self.dense(features)
Passing data through the network. :param x: 2d tensor containing both (x,y) Variables :return: output of the net
def x_grid(self, grid=None): """The horizontal lines that run accross the chart from the x-ticks. If a boolean value is given, these gridlines will be turned on or off. Otherwise, the method will return their current state. :param bool grid: Turns the gridlines on or off. :rtyp...
The horizontal lines that run accross the chart from the x-ticks. If a boolean value is given, these gridlines will be turned on or off. Otherwise, the method will return their current state. :param bool grid: Turns the gridlines on or off. :rtype: ``bool``
async def get_name_endpoint(request: web.Request) -> web.Response: """ Get the name of the robot. This information is also accessible in /server/update/health, but this endpoint provides symmetry with POST /server/name. GET /server/name -> 200 OK, {'name': robot name} """ return web.json_respo...
Get the name of the robot. This information is also accessible in /server/update/health, but this endpoint provides symmetry with POST /server/name. GET /server/name -> 200 OK, {'name': robot name}
def split_pdb_residue(s): '''Splits a PDB residue into the numeric and insertion code components.''' if s.isdigit(): return (int(s), ' ') else: assert(s[:-1].isdigit()) return ((s[:-1], s[-1]))
Splits a PDB residue into the numeric and insertion code components.
def notify(self, method, params=None): """Send a JSON RPC notification to the client. Args: method (str): The method name of the notification to send params (any): The payload of the notification """ log.debug('Sending notification: %s %s', method, params) ...
Send a JSON RPC notification to the client. Args: method (str): The method name of the notification to send params (any): The payload of the notification
def Emulation_setPageScaleFactor(self, pageScaleFactor): """ Function path: Emulation.setPageScaleFactor Domain: Emulation Method name: setPageScaleFactor WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'pageScaleFactor' (type: number) -> Page scale factor...
Function path: Emulation.setPageScaleFactor Domain: Emulation Method name: setPageScaleFactor WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'pageScaleFactor' (type: number) -> Page scale factor. No return value. Description: Sets a specified page sc...
def alpha2(self, code): """ Return the two letter country code when passed any type of ISO 3166-1 country code. If no match is found, returns an empty string. """ code = force_text(code).upper() if code.isdigit(): lookup_code = int(code) ...
Return the two letter country code when passed any type of ISO 3166-1 country code. If no match is found, returns an empty string.
def _dataset_create_resources(self): # type: () -> None """Creates resource objects in dataset """ if 'resources' in self.data: self.old_data['resources'] = self._copy_hdxobjects(self.resources, hdx.data.resource.Resource, 'file_to_upload') self.init_resources() ...
Creates resource objects in dataset
def fixed_point(is_zero, plus, minus, f, x): """ Get the least fixed point when it can be computed piecewise. .. testsetup:: from proso.func import fixed_point .. doctest:: >>> sorted(fixed_point( ... is_zero=lambda xs: len(xs) == 0, ... plus=lambda xs, ys: xs +...
Get the least fixed point when it can be computed piecewise. .. testsetup:: from proso.func import fixed_point .. doctest:: >>> sorted(fixed_point( ... is_zero=lambda xs: len(xs) == 0, ... plus=lambda xs, ys: xs + ys, ... minus=lambda xs, ys: [x for x in xs i...
def list_container_objects(self, container, limit=None, marker=None, prefix=None, delimiter=None, end_marker=None, full_listing=False): """ Return a list of StorageObjects representing the objects in the container. You can use the marker, end_marker, and limit params to handl...
Return a list of StorageObjects representing the objects in the container. You can use the marker, end_marker, and limit params to handle pagination, and the prefix and delimiter params to filter the objects returned. Also, by default only the first 10,000 objects are returned; if you s...
def from_list(cls, database, key, data, clear=False): """ Create and populate a List object from a data list. """ lst = cls(database, key) if clear: lst.clear() lst.extend(data) return lst
Create and populate a List object from a data list.
def learn(*, network, env, total_timesteps, timesteps_per_batch=1024, # what to train on max_kl=0.001, cg_iters=10, gamma=0.99, lam=1.0, # advantage estimation seed=None, ent_coef=0.0, cg_damping=1e-2, vf_stepsize=3e-4, ...
learn a policy function with TRPO algorithm Parameters: ---------- network neural network to learn. Can be either string ('mlp', 'cnn', 'lstm', 'lnlstm' for basic types) or function that takes input placeholder and returns tuple (output, None) for feedforward ne...
def _coltype_to_typeengine(coltype: Union[TypeEngine, VisitableType]) -> TypeEngine: """ An example is simplest: if you pass in ``Integer()`` (an instance of :class:`TypeEngine`), you'll get ``Integer()`` back. If you pass in ``Integer`` (an instance of :class:`...
An example is simplest: if you pass in ``Integer()`` (an instance of :class:`TypeEngine`), you'll get ``Integer()`` back. If you pass in ``Integer`` (an instance of :class:`VisitableType`), you'll also get ``Integer()`` back. The function asserts that its return type is an instance of :class:`TypeEngine...
def cmp(cls, v1: 'VersionBase', v2: 'VersionBase') -> int: """ Compares two instances. """ # TODO types checking if v1._version > v2._version: return 1 elif v1._version == v2._version: return 0 else: return -1
Compares two instances.
def is_attribute_deprecated(self, attribute): """ Check if the attribute is deprecated by the current KMIP version. Args: attribute (string): The name of the attribute (e.g., 'Unique Identifier'). Required. """ rule_set = self._attribute_rule_sets.get...
Check if the attribute is deprecated by the current KMIP version. Args: attribute (string): The name of the attribute (e.g., 'Unique Identifier'). Required.
def make_posix(path): # type: (str) -> str """ Convert a path with possible windows-style separators to a posix-style path (with **/** separators instead of **\\** separators). :param Text path: A path to convert. :return: A converted posix-style path :rtype: Text >>> make_posix("c:/us...
Convert a path with possible windows-style separators to a posix-style path (with **/** separators instead of **\\** separators). :param Text path: A path to convert. :return: A converted posix-style path :rtype: Text >>> make_posix("c:/users/user/venvs/some_venv\\Lib\\site-packages") "c:/user...
def plot_lines_to(self, other, index=None, **kwds): """Plot lines from samples shared between this projection and another dataset. Args: other (:py:class:`pymds.Projection` or :py:class:`pandas.DataFrame` or `array-like`): The other da...
Plot lines from samples shared between this projection and another dataset. Args: other (:py:class:`pymds.Projection` or :py:class:`pandas.DataFrame` or `array-like`): The other dataset to plot lines to. If other is an instance of ...
def fold_path(path, width=30): """ Fold a string form of a path so that each element is on separate line """ assert isinstance(path, six.string_types) if len(path) > width: path.replace(".", ".\n ") return path
Fold a string form of a path so that each element is on separate line
async def update_api(request: web.Request) -> web.Response: """ This handler accepts a POST request with Content-Type: multipart/form-data and file fields in the body named "whl", "serverlib", and "fw". The "whl" and "serverlib" files should be valid Python wheels to be installed ("whl" is expected ...
This handler accepts a POST request with Content-Type: multipart/form-data and file fields in the body named "whl", "serverlib", and "fw". The "whl" and "serverlib" files should be valid Python wheels to be installed ("whl" is expected generally to be the API server wheel, and "serverlib" is expected to...
def as_crispy_errors(form, template_pack=TEMPLATE_PACK): """ Renders only form errors the same way as django-crispy-forms:: {% load crispy_forms_tags %} {{ form|as_crispy_errors }} or:: {{ form|as_crispy_errors:"bootstrap" }} """ if isinstance(form, BaseFormSet): t...
Renders only form errors the same way as django-crispy-forms:: {% load crispy_forms_tags %} {{ form|as_crispy_errors }} or:: {{ form|as_crispy_errors:"bootstrap" }}
def newton_refine_solve(jac_both, x_val, surf_x, y_val, surf_y): r"""Helper for :func:`newton_refine`. We have a system: .. code-block:: rest [A C][ds] = [E] [B D][dt] [F] This is not a typo, ``A->B->C->D`` matches the data in ``jac_both``. We solve directly rather than using a l...
r"""Helper for :func:`newton_refine`. We have a system: .. code-block:: rest [A C][ds] = [E] [B D][dt] [F] This is not a typo, ``A->B->C->D`` matches the data in ``jac_both``. We solve directly rather than using a linear algebra utility: .. code-block:: rest ds = (D E - ...
def _get_creds(self, req): """ Get the username & password from the Authorization header If the header is actually malformed where Basic Auth was indicated by the request then an InvalidAuthSyntax exception is raised. Otherwise an AuthRequired exception since it's unclear in thi...
Get the username & password from the Authorization header If the header is actually malformed where Basic Auth was indicated by the request then an InvalidAuthSyntax exception is raised. Otherwise an AuthRequired exception since it's unclear in this scenario if the requestor was even aw...
def interface_options(score=False, raw=False, features=None, rgb=None): """Get an InterfaceOptions for the config.""" interface = sc_pb.InterfaceOptions() interface.score = score interface.raw = raw if features: interface.feature_layer.width = 24 interface.feature_layer.resolution.x = features int...
Get an InterfaceOptions for the config.
def maxStmId(proc): """ get max statement id, used for sorting of processes in architecture """ maxId = 0 for stm in proc.statements: maxId = max(maxId, getMaxStmIdForStm(stm)) return maxId
get max statement id, used for sorting of processes in architecture
def get_house_detail(self, html): """Get bedroom, bathroom, sqft and more information. Example: http://www.zillow.com/homedetails/8510-Whittier-Blvd-Bethesda-MD-20817/37183103_zpid/ """ if "I'm not a robot" in html: raise exc.CaptchaError(url) data = {"errors": dict...
Get bedroom, bathroom, sqft and more information. Example: http://www.zillow.com/homedetails/8510-Whittier-Blvd-Bethesda-MD-20817/37183103_zpid/
def get(self, label, default=None): """ Returns value occupying requested label, default to specified missing value if not present. Analogous to dict.get Parameters ---------- label : object Label value looking for default : object, optional ...
Returns value occupying requested label, default to specified missing value if not present. Analogous to dict.get Parameters ---------- label : object Label value looking for default : object, optional Value to return if label not in index Return...
def accounts(self): """Property to provide instance of HPEAccountCollection""" return account.HPEAccountCollection( self._conn, utils.get_subresource_path_by(self, 'Accounts'), redfish_version=self.redfish_version)
Property to provide instance of HPEAccountCollection
def collection_updated_percolator(mapper, connection, target): """Create percolator when collection is created. :param mapper: Not used. It keeps the function signature. :param connection: Not used. It keeps the function signature. :param target: Collection where the percolator should be updated. "...
Create percolator when collection is created. :param mapper: Not used. It keeps the function signature. :param connection: Not used. It keeps the function signature. :param target: Collection where the percolator should be updated.
def base_install(): """Generates configuration setting for required functionality of ISAMBARD.""" # scwrl scwrl = {} print('{BOLD}{HEADER}Generating configuration files for ISAMBARD.{END_C}\n' 'All required input can use tab completion for paths.\n' '{BOLD}Setting up SCWRL 4.0 (Recom...
Generates configuration setting for required functionality of ISAMBARD.
def get_version(): """Get single-source __version__.""" pkg_dir = get_package_dir() with open(os.path.join(pkg_dir, 'nestcheck/_version.py')) as ver_file: string = ver_file.read() return string.strip().replace('__version__ = ', '').replace('\'', '')
Get single-source __version__.
async def create_conversation(self, create_conversation_request): """Create a new conversation.""" response = hangouts_pb2.CreateConversationResponse() await self._pb_request('conversations/createconversation', create_conversation_request, response) return ...
Create a new conversation.
def save_species_count(self, delimiter=' ', filename='speciation.csv'): """ Log speciation throughout evolution. """ with open(filename, 'w') as f: w = csv.writer(f, delimiter=delimiter) for s in self.get_species_sizes(): w.writerow(s)
Log speciation throughout evolution.
def find_tendril(cls, proto, addr): """ Finds the tendril corresponding to the protocol and address tuple. Returns the Tendril object, or raises KeyError if the tendril is not tracked. The address tuple is the tuple of the local address and the remote address for the te...
Finds the tendril corresponding to the protocol and address tuple. Returns the Tendril object, or raises KeyError if the tendril is not tracked. The address tuple is the tuple of the local address and the remote address for the tendril.
def _check_rev_dict(tree, ebt): """Verifyies that `ebt` is the inverse of the `edgeBySourceId` data member of `tree`""" ebs = defaultdict(dict) for edge in ebt.values(): source_id = edge['@source'] edge_id = edge['@id'] ebs[source_id][edge_id] = edge assert ebs == tree['edgeBySou...
Verifyies that `ebt` is the inverse of the `edgeBySourceId` data member of `tree`
def connect_to_database_odbc_sqlserver(self, odbc_connection_string: str = None, dsn: str = None, database: str = None, user: str = None, ...
Connects to an SQL Server database via ODBC.
def get_X_slice(self, rmind): '''get X with slicing''' if self.forest.optimize_memory_use: return self.forest.X[:, rmind][self.subsample] else: return self.X[:, rmind]
get X with slicing
def from_Z(z: int): """ Get an element from an atomic number. Args: z (int): Atomic number Returns: Element with atomic number z. """ for sym, data in _pt_data.items(): if data["Atomic no"] == z: return Element(sym) ...
Get an element from an atomic number. Args: z (int): Atomic number Returns: Element with atomic number z.
def search_clans(self, **params: clansearch): """Search for a clan. At least one of the filters must be present Parameters ---------- name: Optional[str] The name of a clan (has to be at least 3 characters long) locationId: Optional[int] ...
Search for a clan. At least one of the filters must be present Parameters ---------- name: Optional[str] The name of a clan (has to be at least 3 characters long) locationId: Optional[int] A location ID minMembers: Optional[int] ...
def verify_permitted_to_read(gs_path): """Check if the user has permissions to read from the given path. Args: gs_path: the GCS path to check if user is permitted to read. Raises: Exception if user has no permissions to read. """ # TODO(qimingj): Storage APIs need to be modified to allo...
Check if the user has permissions to read from the given path. Args: gs_path: the GCS path to check if user is permitted to read. Raises: Exception if user has no permissions to read.
def verify(token, public_key, validate_nonce=None, algorithms=[DEFAULT_ALGORITHM]): """ Verify the validity of the given JWT using the given public key. :param token: JWM claim :param public_key: Public key to use when verifying the claim's signature. :param validate_nonce: Callable to use to valid...
Verify the validity of the given JWT using the given public key. :param token: JWM claim :param public_key: Public key to use when verifying the claim's signature. :param validate_nonce: Callable to use to validate the claim's nonce. :param algorithms: Allowable signing algorithms. Defaults to ['RS512'...
def _from_binary_volname(cls, binary_stream): """See base class.""" name = binary_stream.tobytes().decode("utf_16_le") _MOD_LOGGER.debug("Attempted to unpack VOLUME_NAME Entry from \"%s\"\nResult: %s", binary_stream.tobytes(), name) return cls(name)
See base class.
def check_input(self, token): """ Performs checks on the input token. Raises an exception if unsupported. :param token: the token to check :type token: Token """ if isinstance(token.payload, Instance): return raise Exception(self.full_name + ": Unhand...
Performs checks on the input token. Raises an exception if unsupported. :param token: the token to check :type token: Token
def can_handle(self, input_dict): """ Validates that the input dictionary contains only one key and is of the given intrinsic_name :param input_dict: Input dictionary representing the intrinsic function :return: True if it matches expected structure, False otherwise """ ...
Validates that the input dictionary contains only one key and is of the given intrinsic_name :param input_dict: Input dictionary representing the intrinsic function :return: True if it matches expected structure, False otherwise
def _get_total_read_size(self): """How much event data to process at once.""" if self.read_size: read_size = EVENT_SIZE * self.read_size else: read_size = EVENT_SIZE return read_size
How much event data to process at once.
def _GetIntersectingRanges(self, partition_key): """Gets the intersecting ranges based on the partition key. """ partitionkey_ranges = set() intersecting_ranges = set() if partition_key is None: return list(self.partition_map.keys()) if isinstance(partition_...
Gets the intersecting ranges based on the partition key.
def _required_segments(self, sampfrom, sampto): """ Determine the segments and the samples within each segment in a multi-segment record, that lie within a sample range. Parameters ---------- sampfrom : int The starting sample number to read for each channel....
Determine the segments and the samples within each segment in a multi-segment record, that lie within a sample range. Parameters ---------- sampfrom : int The starting sample number to read for each channel. sampto : int The sample number at which to stop...
def rollback(self): """ .. seealso:: :py:meth:`sqlite3.Connection.rollback` """ try: self.check_connection() except NullDatabaseConnectionError: return logger.debug("rollback: path='{}'".format(self.database_path)) self.connection.rollba...
.. seealso:: :py:meth:`sqlite3.Connection.rollback`
def format_cmdline(args, maxwidth=80): '''Format args into a shell-quoted command line. The result will be wrapped to maxwidth characters where possible, not breaking a single long argument. ''' # Leave room for the space and backslash at the end of each line maxwidth -= 2 def lines(): ...
Format args into a shell-quoted command line. The result will be wrapped to maxwidth characters where possible, not breaking a single long argument.
def _readable_flags(transport): """Method that turns bit flags into a human readable list Args: transport (dict): transport info, specifically needs a 'flags' key with bit_flags Returns: list: a list of human readable flags (e.g. ['syn_ack', 'fin', 'rst', ......
Method that turns bit flags into a human readable list Args: transport (dict): transport info, specifically needs a 'flags' key with bit_flags Returns: list: a list of human readable flags (e.g. ['syn_ack', 'fin', 'rst', ...]
def filter_data(self, min_len, max_len): """ Preserves only samples which satisfy the following inequality: min_len <= sample sequence length <= max_len :param min_len: minimum sequence length :param max_len: maximum sequence length """ logging.info(f'Filteri...
Preserves only samples which satisfy the following inequality: min_len <= sample sequence length <= max_len :param min_len: minimum sequence length :param max_len: maximum sequence length
def usage(self, subcommand): """ Returns *how to use command* text. """ usage = ' '.join(['%prog', subcommand, '[options]']) if self.args: usage = '%s %s' % (usage, str(self.args)) return usage
Returns *how to use command* text.
def date_convert(string, match, ymd=None, mdy=None, dmy=None, d_m_y=None, hms=None, am=None, tz=None, mm=None, dd=None): '''Convert the incoming string containing some date / time info into a datetime instance. ''' groups = match.groups() time_only = False if mm and dd: y=datetim...
Convert the incoming string containing some date / time info into a datetime instance.
def validate(cls, value): """ Raise |ValueError| if *value* is not an assignable value. """ if value not in cls._valid_settings: raise ValueError( "%s not a member of %s enumeration" % (value, cls.__name__) )
Raise |ValueError| if *value* is not an assignable value.
def update_caseid(self, case_obj, family_id): """Update case id for a case across the database. This function is used when a case is a rerun or updated for another reason. Args: case_obj(dict) family_id(str): The new family id Returns: new_case(dict...
Update case id for a case across the database. This function is used when a case is a rerun or updated for another reason. Args: case_obj(dict) family_id(str): The new family id Returns: new_case(dict): The updated case object
def multinomial(data, shape=_Null, get_prob=False, out=None, dtype='int32', **kwargs): """Concurrent sampling from multiple multinomial distributions. .. note:: The input distribution must be normalized, i.e. `data` must sum to 1 along its last dimension. Parameters ---------- data :...
Concurrent sampling from multiple multinomial distributions. .. note:: The input distribution must be normalized, i.e. `data` must sum to 1 along its last dimension. Parameters ---------- data : NDArray An *n* dimensional array whose last dimension has length `k`, where `...
def _read_opt_pdm(self, code, *, desc): """Read HOPOPT PDM option. Structure of HOPOPT PDM option [RFC 8250]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+...
Read HOPOPT PDM option. Structure of HOPOPT PDM option [RFC 8250]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | ...
def handle_readable(client): """ Return True: The client is re-registered to the selector object. Return False: The server disconnects the client. """ data = client.recv(1028) if data == b'': return False client.sendall(b'SERVER: ' + data) print(threading.active_count()) ret...
Return True: The client is re-registered to the selector object. Return False: The server disconnects the client.