code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def calculate_size(name, id): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += calculate_size_str(id) return data_size
Calculates the request payload size
def clear_list_value(self, value): """ Clean the argument value to eliminate None or Falsy values if needed. """ # Don't go any further: this value is empty. if not value: return self.empty_value # Clean empty items if wanted if self.clean_empty: ...
Clean the argument value to eliminate None or Falsy values if needed.
def _evaluate(self,*args,**kwargs): """ NAME: __call__ (_evaluate) PURPOSE: evaluate the actions (jr,lz,jz) INPUT: Either: a) R,vR,vT,z,vz[,phi]: 1) floats: phase-space value for single object (phi is optional) (each can be ...
NAME: __call__ (_evaluate) PURPOSE: evaluate the actions (jr,lz,jz) INPUT: Either: a) R,vR,vT,z,vz[,phi]: 1) floats: phase-space value for single object (phi is optional) (each can be a Quantity) 2) numpy.ndarray: [N] phase...
def post(method, hmc, uri, uri_parms, body, logon_required, wait_for_completion): """Operation: Mount ISO Image (requires DPM mode).""" assert wait_for_completion is True # synchronous operation partition_oid = uri_parms[0] partition_uri = '/api/partitions/' + partition_oid...
Operation: Mount ISO Image (requires DPM mode).
def kill_zombies(self, zombies, session=None): """ Fail given zombie tasks, which are tasks that haven't had a heartbeat for too long, in the current DagBag. :param zombies: zombie task instances to kill. :type zombies: airflow.utils.dag_processing.SimpleTaskInstance :pa...
Fail given zombie tasks, which are tasks that haven't had a heartbeat for too long, in the current DagBag. :param zombies: zombie task instances to kill. :type zombies: airflow.utils.dag_processing.SimpleTaskInstance :param session: DB session. :type session: sqlalchemy.orm.sess...
def iri_to_uri(value, normalize=False): """ Encodes a unicode IRI into an ASCII byte string URI :param value: A unicode string of an IRI :param normalize: A bool that controls URI normalization :return: A byte string of the ASCII-encoded URI """ if not isinstance(...
Encodes a unicode IRI into an ASCII byte string URI :param value: A unicode string of an IRI :param normalize: A bool that controls URI normalization :return: A byte string of the ASCII-encoded URI
def get_directories_re( self, directory_re, full_path=False, ignorecase=False): """Same as get_files_re, but for directories""" if ignorecase: compiled_re = re.compile(directory_re, re.I) else: compiled_re = re.compile(direc...
Same as get_files_re, but for directories
def reset(self): """Reset the current animation generator.""" animation_gen = self._frame_function(*self._animation_args, **self._animation_kwargs) self._current_generator = itertools.cycle( util.concatechain(animation_gen, self._back_up_g...
Reset the current animation generator.
def main(): """Main loop.""" parser = optparse.OptionParser() parser.add_option( '-s', '--server', help='Index Server Name', metavar='SERVER') parser.add_option( '-r', '--repository', help='Repository URL', metavar='URL') parser.add_option( '-u', '--username', help='User Name...
Main loop.
def monthdayscalendar(cls, year, month): """Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven day numbers.""" weeks = [] week = [] for day in NepCal.itermonthdays(year, month): week.append(day) if len(week) =...
Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven day numbers.
def abort_io(self, iocb, err): """Forward the abort downstream.""" if _debug: IOChainMixIn._debug("abort_io %r %r", iocb, err) # make sure we're being notified of an abort request from # the iocb we are chained from if iocb is not self.ioChain: raise RuntimeError("br...
Forward the abort downstream.
def list_resource_record_sets(self, max_results=None, page_token=None, client=None): """List resource record sets for this zone. See https://cloud.google.com/dns/api/v1/resourceRecordSets/list :type max_results: int :param max_results: Optional. The maximum number of resource r...
List resource record sets for this zone. See https://cloud.google.com/dns/api/v1/resourceRecordSets/list :type max_results: int :param max_results: Optional. The maximum number of resource record sets to return. Defaults to a sensible value ...
def _check_ipcidr_minions(self, expr, greedy): ''' Return the minions found by looking via ipcidr ''' cache_enabled = self.opts.get('minion_data_cache', False) if greedy: minions = self._pki_minions() elif cache_enabled: minions = self.cache.list(...
Return the minions found by looking via ipcidr
def get_section_metrics(cls): """ Get the mapping between metrics and sections in Manuscripts report :return: a dict with the mapping between metrics and sections in Manuscripts report """ return { "overview": { "activity_metrics": [Closed, Submitted]...
Get the mapping between metrics and sections in Manuscripts report :return: a dict with the mapping between metrics and sections in Manuscripts report
def get_device(self): """ Returns a reference to the device that is represented by this node. Returns None if no such device can be determined. """ addr = self.address servers = [server for server in pyrax.cloudservers.list() if addr in server.networks.get...
Returns a reference to the device that is represented by this node. Returns None if no such device can be determined.
def get_impala_queries(self, start_time, end_time, filter_str="", limit=100, offset=0): """ Returns a list of queries that satisfy the filter @type start_time: datetime.datetime. Note that the datetime must either be time zone aware or specified in the server time zone. See ...
Returns a list of queries that satisfy the filter @type start_time: datetime.datetime. Note that the datetime must either be time zone aware or specified in the server time zone. See the python datetime documentation for more details about python's ...
def post(self, request, key): """ Process notitication hooks: 1. Obtain Hook 2. Check Auth 3. Delay processing to a task 4. Respond requester """ try: hook = Hook.objects.get(key=key, enabled=True) except Hook.DoesNotExi...
Process notitication hooks: 1. Obtain Hook 2. Check Auth 3. Delay processing to a task 4. Respond requester
def bind(self, **config): """ Bind all unbound types to the engine. Bind each unbound typedef to the engine, passing in the engine and :attr:`config`. The resulting ``load`` and ``dump`` functions can be found under ``self.bound_types[typedef]["load"]`` and ``self.bound...
Bind all unbound types to the engine. Bind each unbound typedef to the engine, passing in the engine and :attr:`config`. The resulting ``load`` and ``dump`` functions can be found under ``self.bound_types[typedef]["load"]`` and ``self.bound_types[typedef]["dump"], respectively. ...
def delete(self, primary_key): ''' a method to delete a record in the table :param primary_key: string with primary key of record :return: string with status message ''' title = '%s.delete' % self.__class__.__name__ # delete obje...
a method to delete a record in the table :param primary_key: string with primary key of record :return: string with status message
def copy_ssh_keys_to_hosts(self, hosts, known_hosts=DEFAULT_KNOWN_HOSTS, dry=False): """ Copy the SSH keys to the given hosts. :param hosts: the list of `Host` objects to copy the SSH keys to. :param known_hosts: the `known_hosts` file to store the SSH public keys. :param dry: p...
Copy the SSH keys to the given hosts. :param hosts: the list of `Host` objects to copy the SSH keys to. :param known_hosts: the `known_hosts` file to store the SSH public keys. :param dry: perform a dry run. :raise msshcopyid.errors.CopySSHKeysError:
def alterar(self, id_user_group, name, read, write, edit, remove): """Edit user group data from its identifier. :param id_user_group: User group id. :param name: User group name. :param read: If user group has read permission ('S' ou 'N'). :param write: If user group has write p...
Edit user group data from its identifier. :param id_user_group: User group id. :param name: User group name. :param read: If user group has read permission ('S' ou 'N'). :param write: If user group has write permission ('S' ou 'N'). :param edit: If user group has edit permission...
def exit_success(jid, ext_source=None): ''' Check if a job has been executed and exit successfully jid The jid to look up. ext_source The external job cache to use. Default: `None`. CLI Example: .. code-block:: bash salt-run jobs.exit_success 20160520145827701627 ...
Check if a job has been executed and exit successfully jid The jid to look up. ext_source The external job cache to use. Default: `None`. CLI Example: .. code-block:: bash salt-run jobs.exit_success 20160520145827701627
def list_nodes_full(**kwargs): ''' Return all data on nodes ''' nodes = _query('server/list') ret = {} for node in nodes: name = nodes[node]['label'] ret[name] = nodes[node].copy() ret[name]['id'] = node ret[name]['image'] = nodes[node]['os'] ret[name]['s...
Return all data on nodes
def gen_sponsor_schedule(user, sponsor=None, num_blocks=6, surrounding_blocks=None, given_date=None): r"""Return a list of :class:`EighthScheduledActivity`\s in which the given user is sponsoring. Returns: Dictionary with: activities no_attendance_today num_acts ...
r"""Return a list of :class:`EighthScheduledActivity`\s in which the given user is sponsoring. Returns: Dictionary with: activities no_attendance_today num_acts
def get_localhost(): ''' Should return 127.0.0.1 in ipv4 and ::1 in ipv6 localhost is not used because on windows vista/windows 7, there can be issues where the resolving doesn't work properly and takes a lot of time (had this issue on the pyunit server). Using the IP directly solves the problem. ...
Should return 127.0.0.1 in ipv4 and ::1 in ipv6 localhost is not used because on windows vista/windows 7, there can be issues where the resolving doesn't work properly and takes a lot of time (had this issue on the pyunit server). Using the IP directly solves the problem.
def _table_sort_by(table, sort_exprs): """ Sort table by the indicated column expressions and sort orders (ascending/descending) Parameters ---------- sort_exprs : sorting expressions Must be one of: - Column name or expression - Sort key, e.g. desc(col) - (column ...
Sort table by the indicated column expressions and sort orders (ascending/descending) Parameters ---------- sort_exprs : sorting expressions Must be one of: - Column name or expression - Sort key, e.g. desc(col) - (column name, True (ascending) / False (descending)) E...
def set_language(self): """Parses feed language and set value""" try: self.language = self.soup.find('language').string except AttributeError: self.language = None
Parses feed language and set value
def output_results(results, mvdelim = '\n', output = sys.stdout): """Given a list of dictionaries, each representing a single result, and an optional list of fields, output those results to stdout for consumption by the Splunk pipeline""" # We collect all the unique field names, as well as # c...
Given a list of dictionaries, each representing a single result, and an optional list of fields, output those results to stdout for consumption by the Splunk pipeline
def dump( state, host, remote_filename, database=None, # Details for speaking to PostgreSQL via `psql` CLI postgresql_user=None, postgresql_password=None, postgresql_host=None, postgresql_port=None, ): ''' Dump a PostgreSQL database into a ``.sql`` file. Requires ``mysqldump``. + databa...
Dump a PostgreSQL database into a ``.sql`` file. Requires ``mysqldump``. + database: name of the database to dump + remote_filename: name of the file to dump the SQL to + postgresql_*: global module arguments, see above
def clean(self: 'TSelf', *, atol: float=1e-9) -> 'TSelf': """Remove terms with coefficients of absolute value atol or less.""" negligible = [v for v, c in self._terms.items() if abs(c) <= atol] for v in negligible: del self._terms[v] return self
Remove terms with coefficients of absolute value atol or less.
def safe_filename(self, otype, oid): """Santize obj name into fname and verify doesn't already exist""" permitted = set(['_', '-', '(', ')']) oid = ''.join([c for c in oid if c.isalnum() or c in permitted]) while oid.find('--') != -1: oid = oid.replace('--', '-') ext ...
Santize obj name into fname and verify doesn't already exist
def _resetID(self): """Reset all ID fields.""" # Dirty.. .=)) self._setID((None,) * len(self._sqlPrimary)) self._new = True
Reset all ID fields.
def load_from_cache(path=user_path): ''' Try to load category ranges from userlevel cache file. :param path: path to userlevel cache file :type path: str :returns: category ranges dict or None :rtype: None or dict of RangeGroup ''' if not path: return try: with open(...
Try to load category ranges from userlevel cache file. :param path: path to userlevel cache file :type path: str :returns: category ranges dict or None :rtype: None or dict of RangeGroup
def evaluate(self, sequence, transformations): """ Execute the sequence of transformations in parallel :param sequence: Sequence to evaluation :param transformations: Transformations to apply :return: Resulting sequence or value """ result = sequence paral...
Execute the sequence of transformations in parallel :param sequence: Sequence to evaluation :param transformations: Transformations to apply :return: Resulting sequence or value
def support_jsonp(api_instance, callback_name_source='callback'): """Let API instance can respond jsonp request automatically. `callback_name_source` can be a string or a callback. If it is a string, the system will find the argument that named by this string in `query string`. If found, deter...
Let API instance can respond jsonp request automatically. `callback_name_source` can be a string or a callback. If it is a string, the system will find the argument that named by this string in `query string`. If found, determine this request to be a jsonp request, and use the argument's value as ...
def text(self): """Return the string to render.""" if callable(self._text): return str(self._text()) return str(self._text)
Return the string to render.
def get_processes(self): """ Grab a shuffled list of all currently running process names """ procs = set() try: # POSIX ps, so it should work in most environments where doge would p = sp.Popen(['ps', '-A', '-o', 'comm='], stdout=sp.PIPE) out...
Grab a shuffled list of all currently running process names
def decode(self, encoded): """ Decodes ``encoded`` label. Args: encoded (torch.Tensor): Encoded label. Returns: object: Label decoded from ``encoded``. """ encoded = super().decode(encoded) if encoded.numel() > 1: raise ValueError( ...
Decodes ``encoded`` label. Args: encoded (torch.Tensor): Encoded label. Returns: object: Label decoded from ``encoded``.
def _validate(self, all_valid_addresses): """Validate that all of the dependencies in the graph exist in the given addresses set.""" for dependency, dependents in iteritems(self._dependent_address_map): if dependency not in all_valid_addresses: raise AddressLookupError( 'Dependent grap...
Validate that all of the dependencies in the graph exist in the given addresses set.
def plot_gos(fout_png, goids, obo_dag, *args, **kws): """Given GO ids and the obo_dag, create a plot of paths from GO ids.""" engine = kws['engine'] if 'engine' in kws else 'pydot' godagsmall = OboToGoDagSmall(goids=goids, obodag=obo_dag).godag godagplot = GODagSmallPlot(godagsmall, *args, **kws) go...
Given GO ids and the obo_dag, create a plot of paths from GO ids.
def format_header_cell(val): """ Formats given header column. This involves changing '_Px_' to '(', '_xP_' to ')' and all other '_' to spaces. """ return re.sub('_', ' ', re.sub(r'(_Px_)', '(', re.sub(r'(_xP_)', ')', str(val) )))
Formats given header column. This involves changing '_Px_' to '(', '_xP_' to ')' and all other '_' to spaces.
def get_stops(records, group_dist): """ Group records arounds stop locations and returns a list of dict(location, records) for each stop. Parameters ---------- records : list A list of Record objects ordered by non-decreasing datetime group_dist : float Minimum distance (in ...
Group records arounds stop locations and returns a list of dict(location, records) for each stop. Parameters ---------- records : list A list of Record objects ordered by non-decreasing datetime group_dist : float Minimum distance (in meters) to switch to a new stop.
def round(self, multiple=1): """ Rounds the kerning values to increments of **multiple**, which will be an ``int``. The default behavior is to round to increments of 1. """ if not isinstance(multiple, int): raise TypeError("The round multiple must be an int n...
Rounds the kerning values to increments of **multiple**, which will be an ``int``. The default behavior is to round to increments of 1.
def popitem(self): """Remove and return the `(key, value)` pair least recently used that has not already expired. """ with self.__timer as time: self.expire(time) try: key = next(iter(self.__links)) except StopIteration: ...
Remove and return the `(key, value)` pair least recently used that has not already expired.
def methods(self, methods): """Setter method; for a description see the getter method.""" # We make sure that the dictionary is a NocaseDict object, and that the # property values are CIMMethod objects: # pylint: disable=attribute-defined-outside-init self._methods = NocaseDict()...
Setter method; for a description see the getter method.
def runner(self): """ Run the necessary methods in the correct order """ printtime('Starting mashsippr analysis pipeline', self.starttime) if not self.pipeline: # Create the objects to be used in the analyses objects = Objectprep(self) objects....
Run the necessary methods in the correct order
def GpsSecondsFromPyUTC( pyUTC, leapSecs=14 ): """converts the python epoch to gps seconds pyEpoch = the python epoch from time.time() """ t = t=gpsFromUTC(*ymdhmsFromPyUTC( pyUTC )) return int(t[0] * 60 * 60 * 24 * 7 + t[1])
converts the python epoch to gps seconds pyEpoch = the python epoch from time.time()
def _combine(self, other, conn='and'): """ OR and AND will create a new F, with the filters from both F objects combined with the connector `conn`. """ f = F() self_filters = copy.deepcopy(self.filters) other_filters = copy.deepcopy(other.filters) if not...
OR and AND will create a new F, with the filters from both F objects combined with the connector `conn`.
def init_app(self, app): """Configures the specified Flask app to enforce SSL.""" app.config.setdefault('SSLIFY_AGE', self.defaults['age']) app.config.setdefault('SSLIFY_SUBDOMAINS', self.defaults['subdomains']) app.config.setdefault('SSLIFY_PERMANENT', self.defaults['permanent']) ...
Configures the specified Flask app to enforce SSL.
def getlist(self, section, option, *, raw=False, vars=None, fallback=None): """Return the [section] option values as a list. The list items must be delimited with commas and/or newlines. """ val = self.get(section, option, raw=raw, vars=vars, fallback=fallback) va...
Return the [section] option values as a list. The list items must be delimited with commas and/or newlines.
def get_search_engine(index=None): """ Returns the desired implementor (defined in settings) """ search_engine_class = _load_class(getattr(settings, "SEARCH_ENGINE", None), None) return search_engine_class(index=index) if search_engine_class else None
Returns the desired implementor (defined in settings)
def IsDirectory(self): """Determines if the file entry is a directory. Returns: bool: True if the file entry is a directory. """ if self._stat_object is None: self._stat_object = self._GetStat() if self._stat_object is not None: self.entry_type = self._stat_object.type return ...
Determines if the file entry is a directory. Returns: bool: True if the file entry is a directory.
def _create_download_failed_message(exception, url): """ Creates message describing why download has failed :param exception: Exception raised during download :type exception: Exception :param url: An URL from where download was attempted :type url: str :return: Error message :rtype: str ...
Creates message describing why download has failed :param exception: Exception raised during download :type exception: Exception :param url: An URL from where download was attempted :type url: str :return: Error message :rtype: str
def set_args(self, args, unknown_args=None): """ Configure job, based on the arguments provided. """ if unknown_args is None: unknown_args = [] self.logger.setLevel(getattr(logging, args.log_level)) parent = hdfs.path.dirname(hdfs.path.abspath(args.output.rst...
Configure job, based on the arguments provided.
def execute( mapchete_files, zoom=None, bounds=None, point=None, wkt_geometry=None, tile=None, overwrite=False, multi=None, input_file=None, logfile=None, verbose=False, no_pbar=False, debug=False, max_chunksize=None, vrt=False, idx_out_dir=None ): """...
Execute a Mapchete process.
def write_text_files(args, infilenames, outfilename): """Write text file(s) to disk. Keyword arguments: args -- program arguments (dict) infilenames -- names of user-inputted and/or downloaded files (list) outfilename -- name of output text file (str) """ if not outfilename.endswith('.txt')...
Write text file(s) to disk. Keyword arguments: args -- program arguments (dict) infilenames -- names of user-inputted and/or downloaded files (list) outfilename -- name of output text file (str)
def _write_superbox(self, fptr, box_id): """Write a superbox. Parameters ---------- fptr : file or file object Superbox (box of boxes) to be written to this file. box_id : bytes 4-byte sequence that identifies the superbox. """ # Write the...
Write a superbox. Parameters ---------- fptr : file or file object Superbox (box of boxes) to be written to this file. box_id : bytes 4-byte sequence that identifies the superbox.
def _raise_glfw_errors_as_exceptions(error_code, description): """ Default error callback that raises GLFWError exceptions for glfw errors. Set an alternative error callback or set glfw.ERROR_REPORTING to False to disable this behavior. """ global ERROR_REPORTING if ERROR_REPORTING: ...
Default error callback that raises GLFWError exceptions for glfw errors. Set an alternative error callback or set glfw.ERROR_REPORTING to False to disable this behavior.
def json_schema_type(schema_file: str, **kwargs) -> typing.Type: """Create a :class:`~doctor.types.JsonSchema` type. This function will automatically load the schema and set it as an attribute of the class along with the description and example. :param schema_file: The full path to the json schema fil...
Create a :class:`~doctor.types.JsonSchema` type. This function will automatically load the schema and set it as an attribute of the class along with the description and example. :param schema_file: The full path to the json schema file to load. :param kwargs: Can include any attribute defined in ...
def closedopen(lower_value, upper_value): """Helper function to construct an interval object with a closed lower and open upper. For example: >>> closedopen(100.2, 800.9) [100.2, 800.9) """ return Interval(Interval.CLOSED, lower_value, upper_value, Interval.OPEN)
Helper function to construct an interval object with a closed lower and open upper. For example: >>> closedopen(100.2, 800.9) [100.2, 800.9)
def detect_pattern_format(pattern_filename, encoding, on_word_boundaries): ''' Automatically detects the pattern file format, and determines whether the Aho-Corasick string matching should pay attention to word boundaries or not. Arguments: - `pattern_filename`: - `encoding`: - `on_word...
Automatically detects the pattern file format, and determines whether the Aho-Corasick string matching should pay attention to word boundaries or not. Arguments: - `pattern_filename`: - `encoding`: - `on_word_boundaries`:
def get_couchdb_admins(): ''' Return the actual CouchDB admins ''' user_list = [] req = curl_couchdb('/_config/admins/') for user in req.json().keys(): user_list.append(user) return user_list
Return the actual CouchDB admins
def calc_effective_conductivity(self, inlets=None, outlets=None, domain_area=None, domain_length=None): r""" This calculates the effective electrical conductivity. Parameters ---------- inlets : array_like The pores where the inlet...
r""" This calculates the effective electrical conductivity. Parameters ---------- inlets : array_like The pores where the inlet voltage boundary conditions were applied. If not given an attempt is made to infer them from the algorithm. outle...
def iris(display=False): """ Return the classic iris data in a nice package. """ d = sklearn.datasets.load_iris() df = pd.DataFrame(data=d.data, columns=d.feature_names) # pylint: disable=E1101 if display: return df, [d.target_names[v] for v in d.target] # pylint: disable=E1101 else: ...
Return the classic iris data in a nice package.
def check_physical(self, line): """Run all physical checks on a raw input line.""" self.physical_line = line for name, check, argument_names in self._physical_checks: self.init_checker_state(name, argument_names) result = self.run_check(check, argument_names) ...
Run all physical checks on a raw input line.
def get_resources_by_search(self, resource_query, resource_search): """Gets the search results matching the given search query using the given search. arg: resource_query (osid.resource.ResourceQuery): the resource query arg: resource_search (osid.resource.ResourceSearch):...
Gets the search results matching the given search query using the given search. arg: resource_query (osid.resource.ResourceQuery): the resource query arg: resource_search (osid.resource.ResourceSearch): the resource search return: (osid.resource.ResourceSea...
def __replace_capitalise(sentence): """here we replace all instances of #CAPITALISE and cap the next word. ############ #NOTE: Buggy as hell, as it doesn't account for words that are already #capitalized ############ :param _sentence: """ if sentence is not None: while senten...
here we replace all instances of #CAPITALISE and cap the next word. ############ #NOTE: Buggy as hell, as it doesn't account for words that are already #capitalized ############ :param _sentence:
def _inject_cookie_message(self, msg): """Inject the first message, which is the document cookie, for authentication.""" if isinstance(msg, unicode): # Cookie can't constructor doesn't accept unicode strings for some reason msg = msg.encode('utf8', 'replace') try:...
Inject the first message, which is the document cookie, for authentication.
def find_family(self, pattern=r".*", flags=0, node=None): """ Returns the Nodes from given family. :param pattern: Matching pattern. :type pattern: unicode :param flags: Matching regex flags. :type flags: int :param node: Node to start walking from. :type...
Returns the Nodes from given family. :param pattern: Matching pattern. :type pattern: unicode :param flags: Matching regex flags. :type flags: int :param node: Node to start walking from. :type node: AbstractNode or AbstractCompositeNode or Object :return: Family...
def rest_put(url, data, timeout, show_error=False): '''Call rest put method''' try: response = requests.put(url, headers={'Accept': 'application/json', 'Content-Type': 'application/json'},\ data=data, timeout=timeout) return response except Exception as except...
Call rest put method
def _gen_shuffles(self): ''' Used internally to build a list for mapping between a random number and a song index. ''' # The current metasong index si = 0 # The shuffle mapper list self.shuffles = [] # Go through all our songs... for song...
Used internally to build a list for mapping between a random number and a song index.
def write_string(self, s, codec): """ Write string encoding it with codec into stream """ for i in range(0, len(s), self.bufsize): chunk = s[i:i + self.bufsize] buf, consumed = codec.encode(chunk) assert consumed == len(chunk) self.write(buf)
Write string encoding it with codec into stream
def bbox(self, out_crs=None): """ Return data bounding box. Parameters ---------- out_crs : ``rasterio.crs.CRS`` rasterio CRS object (default: CRS of process pyramid) Returns ------- bounding box : geometry Shapely geometry object...
Return data bounding box. Parameters ---------- out_crs : ``rasterio.crs.CRS`` rasterio CRS object (default: CRS of process pyramid) Returns ------- bounding box : geometry Shapely geometry object
def query(self, sql, timeout=10): """ Submit a query and return results. :param sql: string :param timeout: int :return: pydrill.client.ResultQuery """ if not sql: raise QueryError('No query passed to drill.') result = ResultQuery(*self.perfo...
Submit a query and return results. :param sql: string :param timeout: int :return: pydrill.client.ResultQuery
def stop(self): """Send signal to stop the current stream playback""" self._response['shouldEndSession'] = True self._response['action']['audio']['interface'] = 'stop' self._response['action']['audio']['sources'] = [] return self
Send signal to stop the current stream playback
def members(self): """获取小组所有成员的信息列表""" all_members = [] for page in range(1, self.max_page() + 1): all_members.extend(self.single_page_members(page)) return all_members
获取小组所有成员的信息列表
def get_cards(self, **query_params): ''' Get all cards this member is attached to. Return a list of Card objects. Returns: list(Card): Return all cards this member is attached to ''' cards = self.get_cards_json(self.base_uri, query_params=query_params) ...
Get all cards this member is attached to. Return a list of Card objects. Returns: list(Card): Return all cards this member is attached to
def Main(): """The main program function. Returns: bool: True if successful or False if not. """ argument_parser = argparse.ArgumentParser(description=( 'Calculates a message digest hash for every file in a directory or ' 'storage media image.')) argument_parser.add_argument( '--output...
The main program function. Returns: bool: True if successful or False if not.
def format_attributes_json(self): """Convert the Attributes object to json format.""" attributes_json = {} for key, value in self.attributes.items(): key = utils.check_str_length(key)[0] value = _format_attribute_value(value) if value is not None: ...
Convert the Attributes object to json format.
def check(self): """ Run inadyn from the commandline to test the configuration. To be run like: fab role inadyn.check """ self._validate_settings() r = self.local_renderer r.env.alias = r.env.aliases[0] r.sudo(r.env.check_command_template)
Run inadyn from the commandline to test the configuration. To be run like: fab role inadyn.check
def execute(self, input_data): ''' Execute the ViewMemoryDeep worker ''' # Aggregate the output from all the memory workers, clearly this could be kewler output = input_data['view_memory'] output['tables'] = {} for data in [input_data[key] for key in ViewMemoryDeep.dependencies]...
Execute the ViewMemoryDeep worker
def load_and_preprocess_imdb_data(n_gram=None): """Load IMDb data and augment with hashed n-gram features.""" X_train, y_train, X_test, y_test = tl.files.load_imdb_dataset(nb_words=VOCAB_SIZE) if n_gram is not None: X_train = np.array([augment_with_ngrams(x, VOCAB_SIZE, N_BUCKETS, n=n_gram) for x i...
Load IMDb data and augment with hashed n-gram features.
def available(name): ''' Returns ``True`` if the specified service is available, otherwise returns ``False``. We look up the name with the svcs command to get back the FMRI This allows users to use simpler service names CLI Example: .. code-block:: bash salt '*' service.available...
Returns ``True`` if the specified service is available, otherwise returns ``False``. We look up the name with the svcs command to get back the FMRI This allows users to use simpler service names CLI Example: .. code-block:: bash salt '*' service.available net-snmp
def drag_and_drop_by_offset(self, source, xoffset, yoffset): """ Holds down the left mouse button on the source element, then moves to the target offset and releases the mouse button. :Args: - source: The element to mouse down. - xoffset: X offset to move to. ...
Holds down the left mouse button on the source element, then moves to the target offset and releases the mouse button. :Args: - source: The element to mouse down. - xoffset: X offset to move to. - yoffset: Y offset to move to.
def _parse_configs(self, config): """Builds a dict with information to connect to Clusters. Parses the list of configuration dictionaries passed by the user and builds an internal dict (_clusters) that holds information for creating Clients connecting to Clusters and matching database n...
Builds a dict with information to connect to Clusters. Parses the list of configuration dictionaries passed by the user and builds an internal dict (_clusters) that holds information for creating Clients connecting to Clusters and matching database names. Args: config: A li...
def _get_ema(cls, df, column, windows): """ get exponential moving average :param df: data :param column: column to calculate :param windows: collection of window of exponential moving average :return: None """ window = cls.get_only_one_positive_int(windo...
get exponential moving average :param df: data :param column: column to calculate :param windows: collection of window of exponential moving average :return: None
def update_port_statuses_cfg(self, context, port_ids, status): """Update the operational statuses of a list of router ports. This is called by the Cisco cfg agent to update the status of a list of ports. :param context: contains user information :param port_ids: list of ids of ...
Update the operational statuses of a list of router ports. This is called by the Cisco cfg agent to update the status of a list of ports. :param context: contains user information :param port_ids: list of ids of all the ports for the given status :param status: PORT_STATUS_ACTI...
def create(): """Create a new database with information about the films in the specified directory or directories.""" if not all(map(os.path.isdir, ARGS.directory)): exit('Error: One or more of the specified directories does not exist.') with sqlite3.connect(ARGS.database) as connection: ...
Create a new database with information about the films in the specified directory or directories.
def convert(word): """This method converts given `word` to UTF-8 encoding and `bytes` type for the SWIG wrapper.""" if six.PY2: if isinstance(word, unicode): return word.encode('utf-8') else: return word.decode('utf-8').encode('utf-8') # make sure it is real utf8, ...
This method converts given `word` to UTF-8 encoding and `bytes` type for the SWIG wrapper.
def begin(self): """Load variables from checkpoint. New model variables have the following name foramt: new_model_scope/old_model_scope/xxx/xxx:0 To find the map of name to variable, need to strip the new_model_scope and then match the old_model_scope and remove the suffix :0. """ variable...
Load variables from checkpoint. New model variables have the following name foramt: new_model_scope/old_model_scope/xxx/xxx:0 To find the map of name to variable, need to strip the new_model_scope and then match the old_model_scope and remove the suffix :0.
def has_entities(status): """ Returns true if a Status object has entities. Args: status: either a tweepy.Status object or a dict returned from Twitter API """ try: if sum(len(v) for v in status.entities.values()) > 0: return True except AttributeError: if s...
Returns true if a Status object has entities. Args: status: either a tweepy.Status object or a dict returned from Twitter API
def token_is_correct(self, token): """ Подходит ли токен, для генерации текста. Допускаются русские слова, знаки препинания и символы начала и конца. """ if self.is_rus_word(token): return True elif self.ONLY_MARKS.search(token): return True ...
Подходит ли токен, для генерации текста. Допускаются русские слова, знаки препинания и символы начала и конца.
def _get_bound_pressure_height(pressure, bound, heights=None, interpolate=True): """Calculate the bounding pressure and height in a layer. Given pressure, optional heights, and a bound, return either the closest pressure/height or interpolated pressure/height. If no heights are provided, a standard atmosph...
Calculate the bounding pressure and height in a layer. Given pressure, optional heights, and a bound, return either the closest pressure/height or interpolated pressure/height. If no heights are provided, a standard atmosphere is assumed. Parameters ---------- pressure : `pint.Quantity` ...
def within_radians(self, key, point, max_distance, min_distance=None): """ 增加查询条件,限制返回结果指定字段值的位置在某点的一段距离之内。 :param key: 查询条件字段名 :param point: 查询地理位置 :param max_distance: 最大距离限定(弧度) :param min_distance: 最小距离限定(弧度) :rtype: Query """ self.near(key, p...
增加查询条件,限制返回结果指定字段值的位置在某点的一段距离之内。 :param key: 查询条件字段名 :param point: 查询地理位置 :param max_distance: 最大距离限定(弧度) :param min_distance: 最小距离限定(弧度) :rtype: Query
def mean_imls(self): """ Compute the mean IMLs (Intensity Measure Level) for the given vulnerability function. :param vulnerability_function: the vulnerability function where the IMLs (Intensity Measure Level) are taken from. :type vuln_function: :py:class...
Compute the mean IMLs (Intensity Measure Level) for the given vulnerability function. :param vulnerability_function: the vulnerability function where the IMLs (Intensity Measure Level) are taken from. :type vuln_function: :py:class:`openquake.risklib.vulnerability_functio...
def compute_checksum(self): """ Calculates checksums for a given file. """ if self._filename.startswith("s3://"): print("Warning: Did not perform client-side checksumming for file in S3. To be implemented.") pass else: checksumCalculator = self.ChecksumCalcula...
Calculates checksums for a given file.
def mode_run_common_obs(args, extra_args): """Observing mode processing mode of numina.""" # Loading observation result if exists loaded_obs = [] sessions = [] if args.session: for obfile in args.obsresult: _logger.info("session file from %r", obfile) with open(obfi...
Observing mode processing mode of numina.
def _invert(color, **kwargs): """ Returns the inverse (negative) of a color. The red, green, and blue values are inverted, while the opacity is left alone. """ col = ColorValue(color) args = [ 255.0 - col.value[0], 255.0 - col.value[1], 255.0 - col.value[2], col.v...
Returns the inverse (negative) of a color. The red, green, and blue values are inverted, while the opacity is left alone.
def list_types_poi(self, **kwargs): """Obtain a list of families, types and categories of POI. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[ParkingPoiType]), or message string in case of error. """...
Obtain a list of families, types and categories of POI. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[ParkingPoiType]), or message string in case of error.
def force_process_ordered(self): """ Take any messages from replica that have been ordered and process them, this should be done rarely, like before catchup starts so a more current LedgerStatus can be sent. can be called either 1. when node is participating, this happens...
Take any messages from replica that have been ordered and process them, this should be done rarely, like before catchup starts so a more current LedgerStatus can be sent. can be called either 1. when node is participating, this happens just before catchup starts so the node can h...