code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def on_yaml_imported(self, yaml): """ The `pyyaml <https://pypi.org/project/pyyaml/>`_ import hook. :param module yaml: The ``yaml`` module """ def represent_ordereddict(dumper, data): """ A custom data representer for ``OrderedDict`` instances. .. note:: Credi...
The `pyyaml <https://pypi.org/project/pyyaml/>`_ import hook. :param module yaml: The ``yaml`` module
def extract_tree_with(self, labels, suppress_unifurcations=True): '''Extract a copy of this ``Tree`` with only the leaves labeled by the strings in ``labels`` Args: ``leaves`` (``set``): Set of leaf labels to include. ``suppress_unifurcations`` (``bool``): ``True`` to suppress ...
Extract a copy of this ``Tree`` with only the leaves labeled by the strings in ``labels`` Args: ``leaves`` (``set``): Set of leaf labels to include. ``suppress_unifurcations`` (``bool``): ``True`` to suppress unifurcations, otherwise ``False`` Returns: Tree: Copy o...
def Parse(self, cmd, args, stdout, stderr, return_val, time_taken, knowledge_base): """Parse the system profiler output. We get it in the form of a plist.""" _ = stderr, time_taken, args, knowledge_base # Unused self.CheckReturn(cmd, return_val) plist = biplist.readPlist(io.BytesIO(stdout)...
Parse the system profiler output. We get it in the form of a plist.
def _get_struct_shapewithstyle(self, shape_number): """Get the values for the SHAPEWITHSTYLE record.""" obj = _make_object("ShapeWithStyle") obj.FillStyles = self._get_struct_fillstylearray(shape_number) obj.LineStyles = self._get_struct_linestylearray(shape_number) bc = BitConsu...
Get the values for the SHAPEWITHSTYLE record.
def on_message(self, msg): ''' When a message with an already known traversal_id is received, we try to build a duplication message and send it in to a protocol dependent recipient. This is used in contracts traversing the graph, when the contract has reached again the same shard...
When a message with an already known traversal_id is received, we try to build a duplication message and send it in to a protocol dependent recipient. This is used in contracts traversing the graph, when the contract has reached again the same shard. This message is necessary, as silentl...
def is_valid_state(self): """A bool value that indicates whether the object's state is a valid state code.""" return self.is_valid_country and self.country.upper() in STATES and \ self.state is not None and \ self.state.upper() in STATES[self.country.upper()]
A bool value that indicates whether the object's state is a valid state code.
def infix(tokens, operator_table): """Match an infix of an operator.""" operator, matched_tokens = operator_table.infix.match(tokens) if operator: return TokenMatch(operator, None, matched_tokens)
Match an infix of an operator.
def refresh(self): """ Refresh/Obtain an account's data from the API server """ import re if re.match(r"^1\.2\.[0-9]*$", self.identifier): account = self.blockchain.rpc.get_objects([self.identifier])[0] else: account = self.blockchain.rpc.lookup_account_n...
Refresh/Obtain an account's data from the API server
def get_bounding_box_list(input_doc_fname, input_doc, full_page_box_list, set_of_page_nums_to_crop, argparse_args, chosen_PdfFileWriter): """Calculate a bounding box for each page in the document. The first argument is the filename of the document's original PDF file, the second is t...
Calculate a bounding box for each page in the document. The first argument is the filename of the document's original PDF file, the second is the PdfFileReader for the document. The argument full_page_box_list is a list of the full-page-size boxes (which is used to correct for any nonzero origins in t...
def username_enable(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") username = ET.SubElement(config, "username", xmlns="urn:brocade.com:mgmt:brocade-aaa") name_key = ET.SubElement(username, "name") name_key.text = kwargs.pop('name') enabl...
Auto Generated Code
def set_shipping(self, *args, **kwargs): ''' Define os atributos do frete Args: type (int): (opcional) Tipo de frete. Os valores válidos são: 1 para 'Encomenda normal (PAC).', 2 para 'SEDEX' e 3 para 'Tipo de frete não especificado.' cost (float): (opcional) Valo...
Define os atributos do frete Args: type (int): (opcional) Tipo de frete. Os valores válidos são: 1 para 'Encomenda normal (PAC).', 2 para 'SEDEX' e 3 para 'Tipo de frete não especificado.' cost (float): (opcional) Valor total do frete. Deve ser maior que 0.00 e menor ou ...
def assert_partial_link_text(self, partial_link_text, timeout=settings.SMALL_TIMEOUT): """ Similar to wait_for_partial_link_text(), but returns nothing. As above, will raise an exception if nothing can be found. Returns True if successful. Default timeout...
Similar to wait_for_partial_link_text(), but returns nothing. As above, will raise an exception if nothing can be found. Returns True if successful. Default timeout = SMALL_TIMEOUT.
def connect(self): """ Connects to the redis database. """ self._connection = StrictRedis( host=self._host, port=self._port, db=self._database, password=self._password)
Connects to the redis database.
def positional(max_positional_args): """A decorator to declare that only the first N arguments my be positional. This decorator makes it easy to support Python 3 style keyword-only parameters. For example, in Python 3 it is possible to write:: def fn(pos1, *, kwonly1=None, kwonly1=None): ...
A decorator to declare that only the first N arguments my be positional. This decorator makes it easy to support Python 3 style keyword-only parameters. For example, in Python 3 it is possible to write:: def fn(pos1, *, kwonly1=None, kwonly1=None): ... All named parameters after ``*``...
def get_property(self, filename): """Opens the file and reads the value""" with open(self.filepath(filename)) as f: return f.read().strip()
Opens the file and reads the value
def _canonical_dir(self, morf): """Return the canonical directory of the module or file `morf`.""" return os.path.split(CodeUnit(morf, self.file_locator).filename)[0]
Return the canonical directory of the module or file `morf`.
def _get_call_params(self, method, **kwargs): """ Returns the prepared call parameters. Mind, these will be keyword arguments to ``requests.post``. ``method`` the NVP method ``kwargs`` the actual call parameters """ payload = {'METHOD': method, ...
Returns the prepared call parameters. Mind, these will be keyword arguments to ``requests.post``. ``method`` the NVP method ``kwargs`` the actual call parameters
def dir_empty(d): '''Return True if given directory is empty, false otherwise.''' flist = glob.glob(os.path.join(d,'*')) return (len(flist) == 0)
Return True if given directory is empty, false otherwise.
def logical_definitions(self, nid): """ Retrieves logical definitions for a class id Arguments --------- nid : str Node identifier for entity to be queried Returns ------- LogicalDefinition """ ldefs = self.all_logical_definit...
Retrieves logical definitions for a class id Arguments --------- nid : str Node identifier for entity to be queried Returns ------- LogicalDefinition
def create_pull_from_issue(self, issue, base, head): """Create a pull request from issue #``issue``. :param int issue: (required), issue number :param str base: (required), e.g., 'master' :param str head: (required), e.g., 'username:branch' :returns: :class:`PullRequest <github3...
Create a pull request from issue #``issue``. :param int issue: (required), issue number :param str base: (required), e.g., 'master' :param str head: (required), e.g., 'username:branch' :returns: :class:`PullRequest <github3.pulls.PullRequest>` if successful, else None
def checkIPFromAlias(alias=None): ''' Method that checks if the given alias is currently connected to Skype and returns its IP address. :param alias: Alias to be searched. :return: Python structure for the Json received. It has the following structure: { "type": "i3visio.ip", ...
Method that checks if the given alias is currently connected to Skype and returns its IP address. :param alias: Alias to be searched. :return: Python structure for the Json received. It has the following structure: { "type": "i3visio.ip", "value": "1.1.1.1", "at...
def numdiff2(f, x0, dv=1e-8): '''Returns the derivative of f w.r.t. to multidimensional vector x0 If x0 is of dimension R1 x ... x Rd dimension of f is assumed to be in the form S1 x ... x Sf x Rn. The last dimension corresponds to various observations. The value returned is of dimension : S1 x ... x Sf x R1 x ... ...
Returns the derivative of f w.r.t. to multidimensional vector x0 If x0 is of dimension R1 x ... x Rd dimension of f is assumed to be in the form S1 x ... x Sf x Rn. The last dimension corresponds to various observations. The value returned is of dimension : S1 x ... x Sf x R1 x ... x Rd x Rn
def _create_B_direct(self): """ Creates OLS coefficient matrix (calculates Y within - for OLS fitting) Returns ---------- The coefficient matrix B """ Y = np.array([reg[self.lags:reg.shape[0]] for reg in self.data]) Z = self._create_Z(Y) ...
Creates OLS coefficient matrix (calculates Y within - for OLS fitting) Returns ---------- The coefficient matrix B
def use_gdbs(self, gdbs=True, port=2345): """ Set gdbs use for process. :param gdbs: Boolean, default is True :param port: Port number for gdbserver """ self.gdbs = gdbs self.gdbs_port = port
Set gdbs use for process. :param gdbs: Boolean, default is True :param port: Port number for gdbserver
def ReadList(self, *branches, **kwargs): """ Same as `phi.dsl.Expression.List` but any string argument `x` is translated to `Read(x)`. """ branches = map(lambda x: E.Read(x) if isinstance(x, str) else x, branches) return self.List(*branches, **kwargs)
Same as `phi.dsl.Expression.List` but any string argument `x` is translated to `Read(x)`.
def PrepareMergeTaskStorage(self, task): """Prepares a task storage for merging. Moves the task storage file from the processed directory to the merge directory. Args: task (Task): task. Raises: IOError: if the storage type is not supported or if the storage file cannot be r...
Prepares a task storage for merging. Moves the task storage file from the processed directory to the merge directory. Args: task (Task): task. Raises: IOError: if the storage type is not supported or if the storage file cannot be renamed. OSError: if the storage type is no...
def parse(self, string, parent): """Parses all the value code elements from the specified string.""" result = {} for member in self.RE_MEMBERS.finditer(string): mems = self._process_member(member, parent, string) #The regex match could contain multiple members that were d...
Parses all the value code elements from the specified string.
def _stat(self, path): '''IMPORTANT: expects `path`'s parent to already be deref()'erenced.''' if path not in self.entries: return OverlayStat(*self.originals['os:stat'](path)[:10], st_overlay=0) st = self.entries[path].stat if stat.S_ISLNK(st.st_mode): return self._stat(self.deref(path)) ...
IMPORTANT: expects `path`'s parent to already be deref()'erenced.
def reply(self, msg, router=None, **kwargs): """ Compose a reply to this message and send it using :attr:`router`, or `router` is :attr:`router` is :data:`None`. :param obj: Either a :class:`Message`, or an object to be serialized in order to construct a new mess...
Compose a reply to this message and send it using :attr:`router`, or `router` is :attr:`router` is :data:`None`. :param obj: Either a :class:`Message`, or an object to be serialized in order to construct a new message. :param router: Optional router to use if...
def npm(package_json, output_file, pinned_file): """Generate a package.json file.""" amd_build_deprecation_warning() try: version = get_distribution(current_app.name).version except DistributionNotFound: version = '' output = { 'name': current_app.name, 'version': ma...
Generate a package.json file.
def auth_aws_iam(self, access_key, secret_key, session_token=None, header_value=None, mount_point='aws', role='', use_token=True, region='us-east-1'): """POST /auth/<mount point>/login :param access_key: AWS IAM access key ID :type access_key: str :param secret_key: AWS IAM secret acces...
POST /auth/<mount point>/login :param access_key: AWS IAM access key ID :type access_key: str :param secret_key: AWS IAM secret access key :type secret_key: str :param session_token: Optional AWS IAM session token retrieved via a GetSessionToken AWS API request. see:...
def extract_vars(template): """ Extract variables from template. Variables are enclosed in double curly braces. """ keys = set() for match in re.finditer(r"\{\{ (?P<key>\w+) \}\}", template.getvalue()): keys.add(match.groups()[0]) return sorted(list(keys))
Extract variables from template. Variables are enclosed in double curly braces.
def _SetPath(self, path): """Sets the current path to watch for new events. This also records the size of the old path, if any. If the size can't be found, an error is logged. Args: path: The full path of the file to watch. """ old_path = self._path if old_path and not io_wrapper.IsC...
Sets the current path to watch for new events. This also records the size of the old path, if any. If the size can't be found, an error is logged. Args: path: The full path of the file to watch.
def statsd_metric(name, count, elapsed): """Metric that records to statsd & graphite""" with statsd.pipeline() as pipe: pipe.incr(name, count) pipe.timing(name, int(round(1000 * elapsed)))
Metric that records to statsd & graphite
def _render_full_resource(self, instance, include, fields): """ Generate a representation of a full resource to match JSON API spec. :param instance: The instance to serialize :param include: Dictionary of relationships to include :param fields: Dictionary of fields to filter ...
Generate a representation of a full resource to match JSON API spec. :param instance: The instance to serialize :param include: Dictionary of relationships to include :param fields: Dictionary of fields to filter
def caches(self, options={}): """Query the server for a list of caches, parse the JSON response, and return the result. Keyword arguments: options -- a dict of arguments to send with the request. See http://dev.iron.io/cache/reference/api/#list_caches for more ...
Query the server for a list of caches, parse the JSON response, and return the result. Keyword arguments: options -- a dict of arguments to send with the request. See http://dev.iron.io/cache/reference/api/#list_caches for more information on defaults and p...
def _processLostJobs(self): """Process jobs that have gone awry""" # In the case that there is nothing happening (no updated jobs to # gather for rescueJobsFrequency seconds) check if there are any jobs # that have run too long (see self.reissueOverLongJobs) or which have # gone ...
Process jobs that have gone awry
def clean(self, value): """Cleans and returns the given value, or raises a ParameterNotValidError exception""" if isinstance(value, numpy.ndarray): return value elif isinstance(value, (list, tuple)): return numpy.array(value) raise ParameterNotValidError
Cleans and returns the given value, or raises a ParameterNotValidError exception
def set_geometry(self, geom): """A convenience function to set the geometry variables. Args: geom: A tuple containing (thet0, thet, phi0, phi, alpha, beta). See the Scatterer class documentation for a description of these angles. """ (self.thet0, self...
A convenience function to set the geometry variables. Args: geom: A tuple containing (thet0, thet, phi0, phi, alpha, beta). See the Scatterer class documentation for a description of these angles.
def inheritance_diagram_directive(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): """ Run when the inheritance_diagram directive is first encountered. """ node = inheritance_diagram() c...
Run when the inheritance_diagram directive is first encountered.
def postorder(self): """ iterator for nodes: left, right, root """ if not self: return if self.left: for x in self.left.postorder(): yield x if self.right: for x in self.right.postorder(): yield x yield self
iterator for nodes: left, right, root
def wait_for_ssh(ip): """Wait for SSH to be available at given IP address.""" for _ in range(12): with safe_socket() as s: try: s.connect((ip, 22)) return True except socket.timeout: pass time.sleep(10) return False
Wait for SSH to be available at given IP address.
def add_prop_descriptor_to_class(self, class_name, new_class_attrs, names_with_refs, container_names, dataspecs): ''' ``MetaHasProps`` calls this during class creation as it iterates over properties to add, to update its registry of new properties. The parameters passed in are mutable and this ...
``MetaHasProps`` calls this during class creation as it iterates over properties to add, to update its registry of new properties. The parameters passed in are mutable and this function is expected to update them accordingly. Args: class_name (str) : name of...
def get_supported_versions(self): """ Gets a list of supported U2F versions from the device. """ if not hasattr(self, '_versions'): try: self._versions = [self.send_apdu(INS_GET_VERSION).decode()] except exc.APDUError as e: # v0 did...
Gets a list of supported U2F versions from the device.
def list_public_images(self, guid=None, name=None, **kwargs): """List all public images. :param string guid: filter based on GUID :param string name: filter based on name :param dict \\*\\*kwargs: response-level options (mask, limit, etc.) """ if 'mask' not in kwargs: ...
List all public images. :param string guid: filter based on GUID :param string name: filter based on name :param dict \\*\\*kwargs: response-level options (mask, limit, etc.)
def attribute_is_public(self, permission): """ Checks if attribute is visible to public (regardless of admins status) """ try: parent = getattr(self, "parent_{}".format(permission)) student = getattr(self, "self_{}".format(permission)) return (parent and stude...
Checks if attribute is visible to public (regardless of admins status)
def reverse_dictionary(d): """ Reverses the key value pairs for a given dictionary. Parameters ---------- d : :obj:`dict` dictionary to reverse Returns ------- :obj:`dict` dictionary with keys and values swapped """ rev_d = {} [rev_d.update({v:k}) for k, v in d....
Reverses the key value pairs for a given dictionary. Parameters ---------- d : :obj:`dict` dictionary to reverse Returns ------- :obj:`dict` dictionary with keys and values swapped
def media_new_callbacks(self, open_cb, read_cb, seek_cb, close_cb, opaque): '''Create a media with custom callbacks to read the data from. @param open_cb: callback to open the custom bitstream input media. @param read_cb: callback to read data (must not be NULL). @param seek_cb: callback...
Create a media with custom callbacks to read the data from. @param open_cb: callback to open the custom bitstream input media. @param read_cb: callback to read data (must not be NULL). @param seek_cb: callback to seek, or NULL if seeking is not supported. @param close_cb: callback to clo...
def open(self): """initialize visit variables and statistics """ self._tryfinallys = [] self.stats = self.linter.add_stats(module=0, function=0, method=0, class_=0)
initialize visit variables and statistics
def _wrapped_signed_div(a, b): """ Perform wrapped unsigned division on two StridedIntervals. :param a: The dividend (StridedInterval) :param b: The divisor (StridedInterval) :return: The quotient """ bits = max(a.bits, b.bits) # Make sure the divisor i...
Perform wrapped unsigned division on two StridedIntervals. :param a: The dividend (StridedInterval) :param b: The divisor (StridedInterval) :return: The quotient
def tpot_driver(args): """Perform a TPOT run.""" if args.VERBOSITY >= 2: _print_args(args) input_data = _read_data_file(args) features = input_data.drop(args.TARGET_NAME, axis=1) training_features, testing_features, training_target, testing_target = \ train_test_split(features, inp...
Perform a TPOT run.
def compile(definition, handlers={}): """ Generates validation function for validating JSON schema passed in ``definition``. Example: .. code-block:: python import fastjsonschema validate = fastjsonschema.compile({'type': 'string'}) validate('hello') This implementation s...
Generates validation function for validating JSON schema passed in ``definition``. Example: .. code-block:: python import fastjsonschema validate = fastjsonschema.compile({'type': 'string'}) validate('hello') This implementation support keyword ``default``: .. code-block:: p...
def payload(self, value): """ Sets the payload of the message and eventually the Content-Type :param value: the payload """ if isinstance(value, tuple): content_type, payload = value self.content_type = content_type self._payload = payload ...
Sets the payload of the message and eventually the Content-Type :param value: the payload
def addRecord(self, record): """ Adds the inputed record to this logger tree widget. :param record | <logging.LogRecord> """ if self._destroyed: return if not self.uiRecordBTN.isChecked(): return ...
Adds the inputed record to this logger tree widget. :param record | <logging.LogRecord>
def start(self): """Start the sensor. """ if rospy.get_name() == '/unnamed': raise ValueError('PhoXi sensor must be run inside a ros node!') # Connect to the cameras if not self._connect_to_sensor(): self._running = False return False ...
Start the sensor.
def put(self, uri_relative, request_bytes, custom_headers): """ :type uri_relative: str :type request_bytes: bytes :type custom_headers: dict[str, str] :rtype: BunqResponseRaw """ return self._request( self._METHOD_PUT, uri_relative, ...
:type uri_relative: str :type request_bytes: bytes :type custom_headers: dict[str, str] :rtype: BunqResponseRaw
def googleRetryPredicate(e): """ necessary because under heavy load google may throw TooManyRequests: 429 The project exceeded the rate limit for creating and deleting buckets. or numerous other server errors which need to be retried. """ if isinstance(e, GoogleAPICallError) and e.c...
necessary because under heavy load google may throw TooManyRequests: 429 The project exceeded the rate limit for creating and deleting buckets. or numerous other server errors which need to be retried.
def to_scales(val): """Parse *val* to return an array of scale factors. """ res = [] for i in val: if len(i) == 3: res.append((i[0], type(i[2]))) else: try: res.append((i[0], i[3].dtype, i[2])) except AttributeError: res...
Parse *val* to return an array of scale factors.
def ellipsoid_phantom(space, ellipsoids, min_pt=None, max_pt=None): """Return a phantom given by ellipsoids. Parameters ---------- space : `DiscreteLp` Space in which the phantom should be created, must be 2- or 3-dimensional. If ``space.shape`` is 1 in an axis, a corresponding ...
Return a phantom given by ellipsoids. Parameters ---------- space : `DiscreteLp` Space in which the phantom should be created, must be 2- or 3-dimensional. If ``space.shape`` is 1 in an axis, a corresponding slice of the phantom is created (instead of squashing the whole pha...
def single(window, config): """Single theme ===== Header ===== = items = ================== """ cordx = round(config.get('cordx', 0)) color = config.get('color', red) icon = config.get('icon', '=') align = config.get('align', 'left') term = window.term width = roun...
Single theme ===== Header ===== = items = ==================
def get_gain(self, attr_name): """ Calculates the information gain from splitting on the given attribute. """ subset_entropy = 0.0 for value in iterkeys(self._attr_value_counts[attr_name]): value_prob = self.get_value_prob(attr_name, value) e = self.get_en...
Calculates the information gain from splitting on the given attribute.
def regress(self, method = 'lstsq'): """regress performs linear least squares regression of the designmatrix on the data. :param method: method, or backend to be used for the regression analysis. :type method: string, one of ['lstsq', 'sm_ols'] :returns: instance variables ...
regress performs linear least squares regression of the designmatrix on the data. :param method: method, or backend to be used for the regression analysis. :type method: string, one of ['lstsq', 'sm_ols'] :returns: instance variables 'betas' (nr_betas x nr_signals) and 'residuals' ...
def get_relaxation_options(self): """ Returns possible generalizations for the upper values in the taxonomy """ domain = self.get_domain() for upper_value in self.upper: for suc in domain.predecessors(upper_value): yield suc
Returns possible generalizations for the upper values in the taxonomy
def _Viscosity(rho, T, fase=None, drho=None): """Equation for the Viscosity Parameters ---------- rho : float Density, [kg/m³] T : float Temperature, [K] fase: dict, optional for calculate critical enhancement phase properties drho: float, optional for calculate crit...
Equation for the Viscosity Parameters ---------- rho : float Density, [kg/m³] T : float Temperature, [K] fase: dict, optional for calculate critical enhancement phase properties drho: float, optional for calculate critical enhancement [∂ρ/∂P]T at reference state,...
def remove_ignore(path, use_sudo=False, force=False): """ Recursively removes a file or directory, ignoring any errors that may occur. Should only be used for temporary files that can be assumed to be cleaned up at a later point. :param path: Path to file or directory to remove. :type path: unicode...
Recursively removes a file or directory, ignoring any errors that may occur. Should only be used for temporary files that can be assumed to be cleaned up at a later point. :param path: Path to file or directory to remove. :type path: unicode :param use_sudo: Use the `sudo` command. :type use_sudo: ...
def _build_path(self): ''' Constructs the actual request URL with accompanying query if any. Returns: None: But does modify self.path, which contains the final request path sent to the server. ''' if not self.path: self.path = '/' ...
Constructs the actual request URL with accompanying query if any. Returns: None: But does modify self.path, which contains the final request path sent to the server.
def _globals(self): """ Returns the globals needed for eval() statements. """ # start with numpy globbies = dict(_n.__dict__) globbies.update(_special.__dict__) # update with required stuff globbies.update({'h':self.h, 'c':self.c, 'd':self, 'self':self})...
Returns the globals needed for eval() statements.
def value_error(self, key, bad_value): """Reports a value error using ERROR_MESSAGES dict. key - key to use for ERROR_MESSAGES. bad_value - is passed to format which is called on what key maps to in ERROR_MESSAGES. """ msg = ERROR_MESSAGES[key].format(bad_value) s...
Reports a value error using ERROR_MESSAGES dict. key - key to use for ERROR_MESSAGES. bad_value - is passed to format which is called on what key maps to in ERROR_MESSAGES.
def _check_auth(self, username: str, password: str) -> bool: """Check if a username/password combination is valid.""" try: return self.credentials[username] == password except KeyError: return False
Check if a username/password combination is valid.
def get_queryset(self): """ Returns a queryset of all bodies holding an election on a date. """ try: date = ElectionDay.objects.get(date=self.kwargs['date']) except Exception: raise APIException( 'No elections on {}.'.format(self.kwargs['da...
Returns a queryset of all bodies holding an election on a date.
def multipart_to_singleparts(geom): """ Yield single part geometries if geom is multipart, otherwise yield geom. Parameters: ----------- geom : shapely geometry Returns: -------- shapely single part geometries """ if isinstance(geom, base.BaseGeometry): if hasattr(geom,...
Yield single part geometries if geom is multipart, otherwise yield geom. Parameters: ----------- geom : shapely geometry Returns: -------- shapely single part geometries
def code(self): """the http status code to return to the client, by default, 200 if a body is present otherwise 204""" code = getattr(self, '_code', None) if not code: if self.has_body(): code = 200 else: code = 204 return code
the http status code to return to the client, by default, 200 if a body is present otherwise 204
def provisioning_configuration( self, body, custom_headers=None, raw=False, **operation_config): """ProvisioningConfiguration. :param body: :type body: :class:`ContinuousDeploymentConfiguration <vsts_info_provider.models.ContinuousDeploymentConfiguration>` :param di...
ProvisioningConfiguration. :param body: :type body: :class:`ContinuousDeploymentConfiguration <vsts_info_provider.models.ContinuousDeploymentConfiguration>` :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongs...
def create_namespace(self, name, ignore_errors=False): """creates a namespace if it does not exist args: name: the name of the namespace ignore_errors(bool): Will ignore if a namespace already exists or there is an error creating the namespace ...
creates a namespace if it does not exist args: name: the name of the namespace ignore_errors(bool): Will ignore if a namespace already exists or there is an error creating the namespace returns: True if created False if not c...
def to_dir_path_url(url_info: URLInfo) -> str: '''Return URL string with the path replaced with directory only.''' dir_name = posixpath.dirname(url_info.path) if not dir_name.endswith('/'): url_template = 'ftp://{}{}/' else: url_template = 'ftp://{}{}' return url_template.format(ur...
Return URL string with the path replaced with directory only.
def _init_special(self): """Initial the dispatch tables for special handling of special construction variables.""" self._special_del = {} self._special_del['SCANNERS'] = _del_SCANNERS self._special_set = {} for key in reserved_construction_var_names: self._sp...
Initial the dispatch tables for special handling of special construction variables.
def closeContentsWidget( self ): """ Closes the current contents widget. """ widget = self.currentContentsWidget() if ( not widget ): return widget.close() widget.setParent(None) widget.deleteLater()
Closes the current contents widget.
def normalized(self, document, schema=None, always_return_document=False): """ Returns the document normalized according to the specified rules of a schema. :param document: The document to normalize. :type document: any :term:`mapping` :param schema: The validation schema. Defa...
Returns the document normalized according to the specified rules of a schema. :param document: The document to normalize. :type document: any :term:`mapping` :param schema: The validation schema. Defaults to :obj:`None`. If not provided here, the schema must have ...
def put(self, x): """Assign input `x` to an available worker and invoke `parallizable.forward_backward` with x. """ if self._num_serial > 0 or len(self._threads) == 0: self._num_serial -= 1 out = self._parallizable.forward_backward(x) self._out_queue.put(out) ...
Assign input `x` to an available worker and invoke `parallizable.forward_backward` with x.
def guild_details(guild_id=None, name=None): """This resource returns details about a guild. :param guild_id: The guild id to query for. :param name: The guild name to query for. *Note: Only one parameter is required; if both are set, the guild Id takes precedence and a warning will be logged.* ...
This resource returns details about a guild. :param guild_id: The guild id to query for. :param name: The guild name to query for. *Note: Only one parameter is required; if both are set, the guild Id takes precedence and a warning will be logged.* The response is a dictionary with the following k...
def upload_panel(store, institute_id, case_name, stream): """Parse out HGNC symbols from a stream.""" institute_obj, case_obj = institute_and_case(store, institute_id, case_name) raw_symbols = [line.strip().split('\t')[0] for line in stream if line and not line.startswith('#')] # chec...
Parse out HGNC symbols from a stream.
def scaleToBoxParam(quad, shape): ''' so, you have a [quad] ((x0,y0),,,) inside a box [shape](width,height) this function gives you center [x,y], and scale factor [x,y] you would need to apply to [quad] in order to scale it to the same shape as the box !quad corners needs to be sorted...
so, you have a [quad] ((x0,y0),,,) inside a box [shape](width,height) this function gives you center [x,y], and scale factor [x,y] you would need to apply to [quad] in order to scale it to the same shape as the box !quad corners needs to be sorted like in example
def _format_unhashed_feature(name, hl_spaces, sep=' | '): # type: (List, bool, str) -> str """ Format feature name for hashed features. """ return sep.join( format_signed(n, _format_single_feature, hl_spaces=hl_spaces) for n in name)
Format feature name for hashed features.
def continuous_periods(self): """ Return a list of continuous data periods by removing the data gaps from the overall record. """ result = [] # For the first period start_date = self.start_date for gap in self.pot_data_gaps: end_date = gap.start_date ...
Return a list of continuous data periods by removing the data gaps from the overall record.
def validate_sort_fields(sort_fields): """ Make sure the fields in the given list exist, and return sorting key. If field names are prefixed with '-', sort order is reversed for that field (descending). """ # Allow descending order per field by prefixing with '-' descending = set() def sort...
Make sure the fields in the given list exist, and return sorting key. If field names are prefixed with '-', sort order is reversed for that field (descending).
def matrixToMathTransform(matrix): """ Take a 6-tuple and return a ShallowTransform object.""" if isinstance(matrix, ShallowTransform): return matrix off, scl, rot = MathTransform(matrix).decompose() return ShallowTransform(off, scl, rot)
Take a 6-tuple and return a ShallowTransform object.
def file_find(self, load): ''' Convenience function for calls made using the LocalClient ''' path = load.get('path') if not path: return {'path': '', 'rel': ''} tgt_env = load.get('saltenv', 'base') return self.find_file(path, tgt_e...
Convenience function for calls made using the LocalClient
def query_radecl(ra, decl, filtersystem='sloan_2mass', field_deg2=1.0, usebinaries=True, extinction_sigma=0.1, magnitude_limit=26.0, maglim_filtercol=4, trilegal_version=1.6, ...
This runs the TRILEGAL query for decimal equatorial coordinates. Parameters ---------- ra,decl : float These are the center equatorial coordinates in decimal degrees filtersystem : str This is a key in the TRILEGAL_FILTER_SYSTEMS dict. Use the function :py:func:`astrobase.serv...
def clean_start_time(self): """ Make sure that the start time doesn't come before the active entry """ start = self.cleaned_data.get('start_time') if not start: return start active_entries = self.user.timepiece_entries.filter( start_time__gte=start...
Make sure that the start time doesn't come before the active entry
def tunnel_to_kernel(connection_info, sshserver, sshkey=None): """tunnel connections to a kernel via ssh This will open four SSH tunnels from localhost on this machine to the ports associated with the kernel. They can be either direct localhost-localhost tunnels, or if an intermediate server is ne...
tunnel connections to a kernel via ssh This will open four SSH tunnels from localhost on this machine to the ports associated with the kernel. They can be either direct localhost-localhost tunnels, or if an intermediate server is necessary, the kernel must be listening on a public IP. Par...
def write(self, filename='same'): """ write object to an ENVI header file """ if filename == 'same': filename = self.filename if not filename.endswith('.hdr'): filename += '.hdr' with open(filename, 'w') as out: out.write(self.__str__()...
write object to an ENVI header file
def compute_node_colors(self): """Compute the node colors. Also computes the colorbar.""" data = [self.graph.node[n][self.node_color] for n in self.nodes] if self.group_order == "alphabetically": data_reduced = sorted(list(set(data))) elif self.group_order == "default": ...
Compute the node colors. Also computes the colorbar.
def allsplit(self, x, mesh_axis, split_axis, which=None): """Inverse of allconcat - split each slice and keep only one piece of it. The number of ways to split is the number of processors in the group. The part that is kept corresponds to the processor's index in the group. Args: x: LaidOutTenso...
Inverse of allconcat - split each slice and keep only one piece of it. The number of ways to split is the number of processors in the group. The part that is kept corresponds to the processor's index in the group. Args: x: LaidOutTensor. mesh_axis: int, the mesh axis along which to split. ...
def _get_rar_version(xfile): """Check quickly whether file is rar archive. """ buf = xfile.read(len(RAR5_ID)) if buf.startswith(RAR_ID): return 3 elif buf.startswith(RAR5_ID): xfile.read(1) return 5 return 0
Check quickly whether file is rar archive.
def populateFromFile(self, dataUrl, indexFile=None): """ Populates the instance variables of this ReadGroupSet from the specified dataUrl and indexFile. If indexFile is not specified guess usual form. """ self._dataUrl = dataUrl self._indexFile = indexFile ...
Populates the instance variables of this ReadGroupSet from the specified dataUrl and indexFile. If indexFile is not specified guess usual form.
def _generate_id_maps(self, unique_stmts, poolsize=None, size_cutoff=100, split_idx=None): """Connect statements using their refinement relationships.""" # Check arguments relating to multiprocessing if poolsize is None: logger.debug('combine_related: poolsi...
Connect statements using their refinement relationships.
def addStormCmd(self, ctor): ''' Add a synapse.lib.storm.Cmd class to the cortex. ''' if not s_syntax.isCmdName(ctor.name): raise s_exc.BadCmdName(name=ctor.name) self.stormcmds[ctor.name] = ctor
Add a synapse.lib.storm.Cmd class to the cortex.
def inception_v3_arg_scope(weight_decay=0.00004, stddev=0.1, batch_norm_var_collection='moving_vars'): """Defines the default InceptionV3 arg scope. Args: weight_decay: The weight decay to use for regularizing the model. stddev: The standard deviation o...
Defines the default InceptionV3 arg scope. Args: weight_decay: The weight decay to use for regularizing the model. stddev: The standard deviation of the trunctated normal weight initializer. batch_norm_var_collection: The name of the collection for the batch norm variables. Returns: An `arg_...
def make_link_node(rawtext, app, type, slug, options): """Create a link to a github resource. :param rawtext: Text being replaced with link node. :param app: Sphinx application context :param type: Link type (issues, changeset, etc.) :param slug: ID of the thing to link to :param options: Optio...
Create a link to a github resource. :param rawtext: Text being replaced with link node. :param app: Sphinx application context :param type: Link type (issues, changeset, etc.) :param slug: ID of the thing to link to :param options: Options dictionary passed to role func.
def read_archive(archive, fname): """Return an iterator of unique rows from a zip archive. * archive - path to the zip archive. * fname - name of the compressed file within the archive. """ # Note that deduplication here is equivalent to an upsert/ignore, # but avoids requirement for a databa...
Return an iterator of unique rows from a zip archive. * archive - path to the zip archive. * fname - name of the compressed file within the archive.