code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _registrant_publication(reg_pub, rules): """ Separate the registration from the publication in a given string. :param reg_pub: A string of digits representing a registration and publication. :param rules: A list of RegistrantRules which designate where to sepa...
Separate the registration from the publication in a given string. :param reg_pub: A string of digits representing a registration and publication. :param rules: A list of RegistrantRules which designate where to separate the values in the string. :returns: A (regis...
def Pack(self): """Returns this message in an over-the-wire format.""" return struct.pack(self.format, self.command, self.arg0, self.arg1, len(self.data), self.checksum, self.magic)
Returns this message in an over-the-wire format.
def use_isolated_vault_view(self): """Pass through to provider AuthorizationLookupSession.use_isolated_vault_view""" self._vault_view = ISOLATED # self._get_provider_session('authorization_lookup_session') # To make sure the session is tracked for session in self._get_provider_sessions()...
Pass through to provider AuthorizationLookupSession.use_isolated_vault_view
def parse_data_line(self, line): """ Parses the data line into a dictionary for the importer """ it = self._generate(line) reader = csv.DictReader(it, fieldnames=self.headers) values = reader.next() values['DefaultResult'] = 'ResidualError' ...
Parses the data line into a dictionary for the importer
def apply_changes(self, other, with_buffer=False): """Applies updates from the buffer of another filter. Params: other (MeanStdFilter): Other filter to apply info from with_buffer (bool): Flag for specifying if the buffer should be copied from other. Exa...
Applies updates from the buffer of another filter. Params: other (MeanStdFilter): Other filter to apply info from with_buffer (bool): Flag for specifying if the buffer should be copied from other. Examples: >>> a = MeanStdFilter(()) >>> a...
def push_results(self, kill_event): """ Listens on the pending_result_queue and sends out results via 0mq Parameters: ----------- kill_event : threading.Event Event to let the thread know when it is time to die. """ logger.debug("[RESULT_PUSH_THREAD] Start...
Listens on the pending_result_queue and sends out results via 0mq Parameters: ----------- kill_event : threading.Event Event to let the thread know when it is time to die.
def setup_icons(self, ): """Set all icons on buttons :returns: None :rtype: None :raises: None """ folder_icon = get_icon('glyphicons_144_folder_open.png', asicon=True) self.asset_open_path_tb.setIcon(folder_icon) self.shot_open_path_tb.setIcon(folder_ico...
Set all icons on buttons :returns: None :rtype: None :raises: None
def key_value(minion_id, pillar, # pylint: disable=W0613 pillar_key='redis_pillar'): ''' Looks for key in redis matching minion_id, returns a structure based on the data type of the redis key. String for string type, dict for hash type and lists for lists, sets and sorted se...
Looks for key in redis matching minion_id, returns a structure based on the data type of the redis key. String for string type, dict for hash type and lists for lists, sets and sorted sets. pillar_key Pillar key to return data into
def iter_chunks(chunk_size, iterator): "Yield from an iterator in chunks of chunk_size." iterator = iter(iterator) while True: next_chunk = _take_n(chunk_size, iterator) # If len(iterable) % chunk_size == 0, don't return an empty chunk. if next_chunk: yield next_chunk ...
Yield from an iterator in chunks of chunk_size.
def get_pid_from_tid(self, dwThreadId): """ Retrieves the global ID of the process that owns the thread. @type dwThreadId: int @param dwThreadId: Thread global ID. @rtype: int @return: Process global ID. @raise KeyError: The thread does not exist. """...
Retrieves the global ID of the process that owns the thread. @type dwThreadId: int @param dwThreadId: Thread global ID. @rtype: int @return: Process global ID. @raise KeyError: The thread does not exist.
def create_session(user): """ Create the login session :param user: UserModel :return: """ def cb(): if user: if __options__.get("require_email_verification") and not user.email_verified: raise exceptions.VerifyEmailError() if flask_login.login_u...
Create the login session :param user: UserModel :return:
def AddEvent(self, event): """Adds an event. Args: event (EventObject): event. Raises: IOError: when the storage file is closed or read-only or if the event data identifier type is not supported. OSError: when the storage file is closed or read-only or if the event da...
Adds an event. Args: event (EventObject): event. Raises: IOError: when the storage file is closed or read-only or if the event data identifier type is not supported. OSError: when the storage file is closed or read-only or if the event data identifier type is not supporte...
def catFiles(filesToCat, catFile): """Cats a bunch of files into one file. Ensures a no more than maxCat files are concatenated at each step. """ if len(filesToCat) == 0: #We must handle this case or the cat call will hang waiting for input open(catFile, 'w').close() return maxCat = ...
Cats a bunch of files into one file. Ensures a no more than maxCat files are concatenated at each step.
def qos_map_cos_mutation_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos") map = ET.SubElement(qos, "map") cos_mutation = ET.SubElement(map, "cos-mutation") n...
Auto Generated Code
def InterpretWaveform(raw, integersOnly=False, headersOnly=False, noTimeArray=False): """ Take the raw binary from a file saved from the LeCroy, read from a file using the 2 lines: with open(filename, "rb") as file: raw = file.read() And extracts various properties of th...
Take the raw binary from a file saved from the LeCroy, read from a file using the 2 lines: with open(filename, "rb") as file: raw = file.read() And extracts various properties of the saved time trace. Parameters ---------- raw : bytes Bytes o...
def speed(self): """ Returns the current motor speed in tacho counts per second. Note, this is not necessarily degrees (although it is for LEGO motors). Use the `count_per_rot` attribute to convert this value to RPM or deg/sec. """ self._speed, value = self.get_attr_int(s...
Returns the current motor speed in tacho counts per second. Note, this is not necessarily degrees (although it is for LEGO motors). Use the `count_per_rot` attribute to convert this value to RPM or deg/sec.
def copy_config_input_source_config_source_candidate_candidate(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") copy_config = ET.Element("copy_config") config = copy_config input = ET.SubElement(copy_config, "input") source = ET.SubElement...
Auto Generated Code
def turn_physical_on(self,ro=None,vo=None): """ NAME: turn_physical_on PURPOSE: turn on automatic returning of outputs in physical units INPUT: ro= reference distance (kpc; can be Quantity) vo= reference velocity (km/s; can be Quantity) ...
NAME: turn_physical_on PURPOSE: turn on automatic returning of outputs in physical units INPUT: ro= reference distance (kpc; can be Quantity) vo= reference velocity (km/s; can be Quantity) OUTPUT: (none) HISTORY: ...
def list_blobs( self, max_results=None, page_token=None, prefix=None, delimiter=None, versions=None, projection="noAcl", fields=None, client=None, ): """Return an iterator used to find blobs in the bucket. If :attr:`user_projec...
Return an iterator used to find blobs in the bucket. If :attr:`user_project` is set, bills the API request to that project. :type max_results: int :param max_results: (Optional) The maximum number of blobs in each page of results from this request. Non-positive values a...
def _get_rows(self, options): """Return only those data rows that should be printed, based on slicing and sorting. Arguments: options - dictionary of option settings.""" if options["oldsortslice"]: rows = copy.deepcopy(self._rows[options["start"]:options["end"]]) e...
Return only those data rows that should be printed, based on slicing and sorting. Arguments: options - dictionary of option settings.
def salt_extend(extension, name, description, salt_dir, merge): ''' Quickstart for developing on the saltstack installation .. versionadded:: 2016.11.0 ''' import salt.utils.extend salt.utils.extend.run(extension=extension, name=name, descript...
Quickstart for developing on the saltstack installation .. versionadded:: 2016.11.0
def _check_with_label(self, selector, checked, locator=None, allow_label_click=None, visible=None, wait=None, **kwargs): """ Args: selector (str): The selector for the type of element that should be checked/unchecked. checked (bool): Whether the element ...
Args: selector (str): The selector for the type of element that should be checked/unchecked. checked (bool): Whether the element should be checked. locator (str, optional): Which element to check. allow_label_click (bool, optional): Attempt to click the label to toggle st...
def _escape(s): """Escape commas, tabs, newlines and dashes in a string Commas are encoded as tabs """ assert isinstance(s, str), \ "expected %s but got %s; value=%s" % (type(str), type(s), s) s = s.replace("\\", "\\\\") s = s.replace("\n", "\\n") s = s.replace("\t", "\\t") s = s.replace(",", "...
Escape commas, tabs, newlines and dashes in a string Commas are encoded as tabs
def get_queryset(self, request): """Limit to TenantGroups that this user can access.""" qs = super(TenantGroupAdmin, self).get_queryset(request) if not request.user.is_superuser: qs = qs.filter(tenantrole__user=request.user, tenantrole__role=TenantRole.ROLE...
Limit to TenantGroups that this user can access.
def _tarjan(self, function, order, stack, data): """Tarjan's strongly connected components algorithm. See also: - http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm """ try: func_data = data[function.id] return order ex...
Tarjan's strongly connected components algorithm. See also: - http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm
def reverted(name, snapshot=None, cleanup=False): # pylint: disable=redefined-outer-name ''' .. deprecated:: 2016.3.0 Reverts to the particular snapshot. .. versionadded:: 2016.3.0 .. code-block:: yaml domain_name: virt.reverted: - cleanup: True domain_nam...
.. deprecated:: 2016.3.0 Reverts to the particular snapshot. .. versionadded:: 2016.3.0 .. code-block:: yaml domain_name: virt.reverted: - cleanup: True domain_name_1: virt.reverted: - snapshot: snapshot_name - cleanup: False
def _get_sortgo(self): """Get function for sorting GO terms in a list of namedtuples.""" if 'sortgo' in self.datobj.kws: return self.datobj.kws['sortgo'] return self.datobj.grprdflt.gosubdag.prt_attr['sort'] + "\n"
Get function for sorting GO terms in a list of namedtuples.
async def reply(self, *args, **kwargs): """ Replies to the message (as a reply). Shorthand for `telethon.client.messages.MessageMethods.send_message` with both ``entity`` and ``reply_to`` already set. """ kwargs['reply_to'] = self.id return await self._client.send...
Replies to the message (as a reply). Shorthand for `telethon.client.messages.MessageMethods.send_message` with both ``entity`` and ``reply_to`` already set.
def extract_flash(prihdr, scihdu): """Extract postflash data from ``FLSHFILE``. Parameters ---------- prihdr : obj FITS primary header HDU. scihdu : obj Extension HDU of the science image. This is only used to extract subarray data. Returns ------- flash : ndar...
Extract postflash data from ``FLSHFILE``. Parameters ---------- prihdr : obj FITS primary header HDU. scihdu : obj Extension HDU of the science image. This is only used to extract subarray data. Returns ------- flash : ndarray or `None` Postflash, if any. S...
def validate(self, validator, preserve_errors=False, copy=False, section=None): """ Test the ConfigObj against a configspec. It uses the ``validator`` object from *validate.py*. To run ``validate`` on the current ConfigObj, call: :: test = config.validate(...
Test the ConfigObj against a configspec. It uses the ``validator`` object from *validate.py*. To run ``validate`` on the current ConfigObj, call: :: test = config.validate(validator) (Normally having previously passed in the configspec when the ConfigObj was created - you...
def prepare_metadata_for_build_wheel(metadata_directory, config_settings): """Invoke optional prepare_metadata_for_build_wheel Implements a fallback by building a wheel if the hook isn't defined. """ backend = _build_backend() try: hook = backend.prepare_metadata_for_build_wheel except ...
Invoke optional prepare_metadata_for_build_wheel Implements a fallback by building a wheel if the hook isn't defined.
def gen_min(cachedir, extra_mods='', overwrite=False, so_mods='', python2_bin='python2', python3_bin='python3'): ''' Generate the salt-min tarball and print the location of the tarball Optional additional mods to include (e.g. mako) can be supplied as a comma delimited string. Permits forci...
Generate the salt-min tarball and print the location of the tarball Optional additional mods to include (e.g. mako) can be supplied as a comma delimited string. Permits forcing an overwrite of the output file as well. CLI Example: .. code-block:: bash salt-run min.generate salt-run m...
def get_remote_peer_list(self): ''' listPeer 返回列表 { "rtn":0, "peerList": [{ "category": "", "status": 0, "name": "GUNNER_HOME", "vodPort": 43566, "company": "XUNLEI_MIPS_BE_MIPS32", ...
listPeer 返回列表 { "rtn":0, "peerList": [{ "category": "", "status": 0, "name": "GUNNER_HOME", "vodPort": 43566, "company": "XUNLEI_MIPS_BE_MIPS32", "pid": "8498352EB4F5208X0001", ...
def get_grade_entries(self): """Gets the package list resulting from the search. return: (osid.grading.GradeEntryList) - the grade entry list raise: IllegalState - list already retrieved *compliance: mandatory -- This method must be implemented.* """ if self.retrieved:...
Gets the package list resulting from the search. return: (osid.grading.GradeEntryList) - the grade entry list raise: IllegalState - list already retrieved *compliance: mandatory -- This method must be implemented.*
def _set_child_joined_alias_using_join_map(child, join_map, alias_map): """ Set the joined alias on the child, for Django <= 1.7.x. :param child: :param join_map: :param alias_map: """ for lhs, table, join_cols in join_map: if lhs is None: ...
Set the joined alias on the child, for Django <= 1.7.x. :param child: :param join_map: :param alias_map:
def expire_token(self, token): """ Given a token, makes a request to the authentication server to expire it immediately. This is considered a responsible way to log out a user. If you simply remove the session your application has for the user without expiring their token, the ...
Given a token, makes a request to the authentication server to expire it immediately. This is considered a responsible way to log out a user. If you simply remove the session your application has for the user without expiring their token, the user is not _really_ logged out. :param to...
def process_text(self, text, format='json'): """Return a mentions JSON object given text. Parameters ---------- text : str Text to be processed. format : str The format of the output to produce, one of "json" or "json_ld". Default: "json" ...
Return a mentions JSON object given text. Parameters ---------- text : str Text to be processed. format : str The format of the output to produce, one of "json" or "json_ld". Default: "json" Returns ------- json_dict : dict ...
def print_details(self): """Print torrent details""" print("Title:", self.title) print("Category:", self.category) print("Page: ", self.page) print("Size: ", self.size) print("Files: ", self.files) print("Age: ", self.age) print("Seeds:", self.seeders) print("Leechers: ", self.leechers) print("Magne...
Print torrent details
def integrate(self, coord, datetime_unit=None): """ integrate the array with the trapezoidal rule. .. note:: This feature is limited to simple cartesian geometry, i.e. coord must be one dimensional. Parameters ---------- dim: str, or a sequence of str ...
integrate the array with the trapezoidal rule. .. note:: This feature is limited to simple cartesian geometry, i.e. coord must be one dimensional. Parameters ---------- dim: str, or a sequence of str Coordinate(s) used for the integration. da...
def d2Ibr_dV2(Ybr, V, lam): """ Computes 2nd derivatives of complex branch current w.r.t. voltage. """ nb = len(V) diaginvVm = spdiag(div(matrix(1.0, (nb, 1)), abs(V))) Haa = spdiag(mul(-(Ybr.T * lam), V)) Hva = -1j * Haa * diaginvVm Hav = Hva Hvv = spmatrix([], [], [], (nb, nb)) r...
Computes 2nd derivatives of complex branch current w.r.t. voltage.
def piece_size(model_file=None, model_proto=None, name=None): """Returns the piece size (vocabulary size). Args: model_file: The sentencepiece model file path. model_proto: The sentencepiece model serialized proto. Either `model_file` or `model_proto` must be set. name: The name argume...
Returns the piece size (vocabulary size). Args: model_file: The sentencepiece model file path. model_proto: The sentencepiece model serialized proto. Either `model_file` or `model_proto` must be set. name: The name argument that is passed to the op function. Returns: A scalar repre...
def clear_thumbnails(self): '''clear all thumbnails from the map''' state = self.state for l in state.layers: keys = state.layers[l].keys()[:] for key in keys: if (isinstance(state.layers[l][key], SlipThumbnail) and not isinstance(state...
clear all thumbnails from the map
def patText(s0): '''make text pattern''' arr = np.zeros((s0,s0), dtype=np.uint8) s = int(round(s0/100.)) p1 = 0 pp1 = int(round(s0/10.)) for pos0 in np.linspace(0,s0,10): cv2.putText(arr, 'helloworld', (p1,int(round(pos0))), cv2.FONT_HERSHEY_COMPLEX_SMALL, fo...
make text pattern
def render(template, context, partials={}, state=None): """ Renders a given mustache template, with sane defaults. """ # Create a new state by default state = state or State() # Add context to the state dict if isinstance(context, Context): state.context = context else: state.co...
Renders a given mustache template, with sane defaults.
def is_not_none(self, a, message=None): "Check if a value is not None" if a is None: self.log_error("{} is None".format(str(a)), message) return False return True
Check if a value is not None
def sync_one(self, aws_syncr, amazon, bucket): """Make sure this bucket exists and has only attributes we want it to have""" if bucket.permission.statements: permission_document = bucket.permission.document else: permission_document = "" bucket_info = amazon.s3.b...
Make sure this bucket exists and has only attributes we want it to have
def apply_network(network, x, chunksize=None): """ Apply a pytorch network, potentially in chunks """ network_is_cuda = next(network.parameters()).is_cuda x = torch.from_numpy(x) with torch.no_grad(): if network_is_cuda: x = x.cuda() if chunksize is None: ...
Apply a pytorch network, potentially in chunks
def get_assessment_part_item_design_session(self, *args, **kwargs): """Gets the ``OsidSession`` associated with the assessment part item design service. return: (osid.assessment.authoring.AssessmentPartItemDesignSession) - an ``AssessmentPartItemDesignSession`` raise: Operation...
Gets the ``OsidSession`` associated with the assessment part item design service. return: (osid.assessment.authoring.AssessmentPartItemDesignSession) - an ``AssessmentPartItemDesignSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_...
def UrlGet(url, timeout=10, retries=0): """ Retrieve content from the given URL. """ # in Python 2.6 we can pass timeout to urllib2.urlopen socket.setdefaulttimeout(timeout) attempts = 0 content = None while not content: try: content = urllib2.urlopen(url).read() except urllib2.URLErr...
Retrieve content from the given URL.
def load_filter_plugins(entrypoint_group: str) -> Iterable[Filter]: """ Load all blacklist plugins that are registered with pkg_resources Parameters ========== entrypoint_group: str The entrypoint group name to load plugins from Returns ======= List of Blacklist: A list...
Load all blacklist plugins that are registered with pkg_resources Parameters ========== entrypoint_group: str The entrypoint group name to load plugins from Returns ======= List of Blacklist: A list of objects derived from the Blacklist class
def get_withdrawal_quotas(self, currency): """Get withdrawal quotas for a currency https://docs.kucoin.com/#get-withdrawal-quotas :param currency: Name of currency :type currency: string .. code:: python quotas = client.get_withdrawal_quotas('ETH') :retur...
Get withdrawal quotas for a currency https://docs.kucoin.com/#get-withdrawal-quotas :param currency: Name of currency :type currency: string .. code:: python quotas = client.get_withdrawal_quotas('ETH') :returns: ApiResponse .. code:: python ...
def token(self, i, restrict=None): """ Get the i'th token, and if i is one past the end, then scan for another token; restrict is a list of tokens that are allowed, or 0 for any token. """ tokens_len = len(self.tokens) if i == tokens_len: # We are at the end, ge ...
Get the i'th token, and if i is one past the end, then scan for another token; restrict is a list of tokens that are allowed, or 0 for any token.
def save_object(collection, obj): """Save an object ``obj`` to the given ``collection``. ``obj.id`` must be unique across all other existing objects in the given collection. If ``id`` is not present in the object, a *UUID* is assigned as the object's ``id``. Indexes already defined on the ``colle...
Save an object ``obj`` to the given ``collection``. ``obj.id`` must be unique across all other existing objects in the given collection. If ``id`` is not present in the object, a *UUID* is assigned as the object's ``id``. Indexes already defined on the ``collection`` are updated after the object ...
def set_uri(self, uri): ''' Sets the uri to the public object @param uri: a uri @type uri: string ''' publicObj = self.get_public() if publicObj is not None: publicObj.set_uri(uri) else: publicObj = Cpublic() publicObj.s...
Sets the uri to the public object @param uri: a uri @type uri: string
def t_NUMBER(self, t): r'\d+\.?\d*' if t.value.find(".") != -1: t.value = float(t.value) else: t.value = int(t.value) return t
r'\d+\.?\d*
def enable_category(self, category: str) -> None: """ Enable an entire category of commands :param category: the category to enable """ for cmd_name in list(self.disabled_commands): func = self.disabled_commands[cmd_name].command_function if hasattr(func, ...
Enable an entire category of commands :param category: the category to enable
def meanApprox(self, timeout, confidence=0.95): """ .. note:: Experimental Approximate operation to return the mean within a timeout or meet the confidence. >>> rdd = sc.parallelize(range(1000), 10) >>> r = sum(range(1000)) / 1000.0 >>> abs(rdd.meanApprox(1000) ...
.. note:: Experimental Approximate operation to return the mean within a timeout or meet the confidence. >>> rdd = sc.parallelize(range(1000), 10) >>> r = sum(range(1000)) / 1000.0 >>> abs(rdd.meanApprox(1000) - r) / r < 0.05 True
def add_get(self, *args, **kwargs): """ Shortcut for add_route with method GET """ return self.add_route(hdrs.METH_GET, *args, **kwargs)
Shortcut for add_route with method GET
def save_csv(self, csv_location): # type: (str) -> None """ Save the csv to a file """ with open(csv_location, 'w') as csv_handle: writer = csv.writer(csv_handle) for row in self.csv_data: writer.writerow(row)
Save the csv to a file
def remove_ticks(ax, x=False, y=False): """ Remove ticks from axis. Parameters: ax: axes to work on x: if True, remove xticks. Default False. y: if True, remove yticks. Default False. Examples: removeticks(ax, x=True) removeticks(ax, x=True, y=True) """ if x: ...
Remove ticks from axis. Parameters: ax: axes to work on x: if True, remove xticks. Default False. y: if True, remove yticks. Default False. Examples: removeticks(ax, x=True) removeticks(ax, x=True, y=True)
def neighbor_graph(X, metric='euclidean', k=None, epsilon=None, weighting='none', precomputed=False): '''Build a neighbor graph from pairwise distance information. X : two-dimensional array-like Shape must either be (num_pts, num_dims) or (num_pts, num_pts). k : int, maximum number...
Build a neighbor graph from pairwise distance information. X : two-dimensional array-like Shape must either be (num_pts, num_dims) or (num_pts, num_pts). k : int, maximum number of nearest neighbors epsilon : float, maximum distance to a neighbor metric : str, type of distance metric (see sklearn.m...
def update_profiles(self): """List all profiles in the ipython_dir and cwd. """ for path in [get_ipython_dir(), os.getcwdu()]: for profile in list_profiles_in(path): pd = self.get_profile_dir(profile, path) if profile not in self.profiles: ...
List all profiles in the ipython_dir and cwd.
def gps2_raw_send(self, time_usec, fix_type, lat, lon, alt, eph, epv, vel, cog, satellites_visible, dgps_numch, dgps_age, force_mavlink1=False): ''' Second GPS data. Coordinate frame is right-handed, Z-axis up (GPS frame). time_usec : Time...
Second GPS data. Coordinate frame is right-handed, Z-axis up (GPS frame). time_usec : Timestamp (microseconds since UNIX epoch or microseconds since system boot) (uint64_t) fix_type : See the GPS_FIX_TYPE enum. (uint8_t) l...
def build_js(): ''' Build BokehJS files (CSS, JS, etc) under the ``bokehjs`` source subdirectory. Also prints a table of statistics about the generated assets (file sizes, etc.) or any error messages if the build fails. Note this function only builds BokehJS assets, it does not install them in...
Build BokehJS files (CSS, JS, etc) under the ``bokehjs`` source subdirectory. Also prints a table of statistics about the generated assets (file sizes, etc.) or any error messages if the build fails. Note this function only builds BokehJS assets, it does not install them into the python source tre...
def get_playcount(self): """Returns the user's playcount so far.""" doc = self._request(self.ws_prefix + ".getInfo", True) return _number(_extract(doc, "playcount"))
Returns the user's playcount so far.
def _read_file(self, filename): """Return the lines from the given file, ignoring lines that start with comments""" result = [] with open(filename, 'r') as f: lines = f.read().split('\n') for line in lines: nocomment = line.strip().split('#')[0].st...
Return the lines from the given file, ignoring lines that start with comments
def initialize(self, request): """Store the data we'll need to make the postback from the request object.""" if request.method == 'GET': # PDT only - this data is currently unused self.query = request.META.get('QUERY_STRING', '') elif request.method == 'POST': ...
Store the data we'll need to make the postback from the request object.
def capture_insert(self, *, exclude_fields=()): """Apply :meth:`.TriggerLogAbstract.capture_insert_from_model` for this log.""" return self.capture_insert_from_model(self.table_name, self.record_id, exclude_fields=exclude_fields)
Apply :meth:`.TriggerLogAbstract.capture_insert_from_model` for this log.
def _progress(bytes_received, bytes_total, worker): """Return download progress.""" worker.sig_download_progress.emit( worker.url, worker.path, bytes_received, bytes_total)
Return download progress.
def save(self, to_save, manipulate=True, check_keys=True, **kwargs): """Save a document in this collection. **DEPRECATED** - Use :meth:`insert_one` or :meth:`replace_one` instead. .. versionchanged:: 3.0 Removed the `safe` parameter. Pass ``w=0`` for unacknowledged write ...
Save a document in this collection. **DEPRECATED** - Use :meth:`insert_one` or :meth:`replace_one` instead. .. versionchanged:: 3.0 Removed the `safe` parameter. Pass ``w=0`` for unacknowledged write operations.
def urlfetch_async(self, url, method='GET', headers=None, payload=None, deadline=None, callback=None, follow_redirects=False): """Make an async urlfetch() call. This is an async wrapper around urlfetch(). It adds an authentication header. Args: url: the ...
Make an async urlfetch() call. This is an async wrapper around urlfetch(). It adds an authentication header. Args: url: the url to fetch. method: the method in which to fetch. headers: the http headers. payload: the data to submit in the fetch. deadline: the deadline in which...
def select_peer(peer_addrs, service, routing_id, method): '''Choose a target from the available peers for a singular message :param peer_addrs: the ``(host, port)``s of the peers eligible to handle the RPC, and possibly a ``None`` entry if this hub can handle it locally :type peer_addrs: li...
Choose a target from the available peers for a singular message :param peer_addrs: the ``(host, port)``s of the peers eligible to handle the RPC, and possibly a ``None`` entry if this hub can handle it locally :type peer_addrs: list :param service: the service of the message :type servi...
def find_minimum_spanning_forest(graph): """Calculates the minimum spanning forest of a disconnected graph. Returns a list of lists, each containing the edges that define that tree. Returns an empty list for an empty graph. """ msf = [] if graph.num_nodes() == 0: return msf if graph...
Calculates the minimum spanning forest of a disconnected graph. Returns a list of lists, each containing the edges that define that tree. Returns an empty list for an empty graph.
def list_models(self, limit=-1, offset=-1): """List models in the database. Takes optional parameters limit and offset for pagination. Parameters ---------- limit : int Limit number of models in the result set offset : int Set offset in list (orde...
List models in the database. Takes optional parameters limit and offset for pagination. Parameters ---------- limit : int Limit number of models in the result set offset : int Set offset in list (order as defined by object store) Returns ...
def unwrap_arguments(xml_response): """Extract arguments and their values from a SOAP response. Args: xml_response (str): SOAP/xml response text (unicode, not utf-8). Returns: dict: a dict of ``{argument_name: value}`` items. """ # A UP...
Extract arguments and their values from a SOAP response. Args: xml_response (str): SOAP/xml response text (unicode, not utf-8). Returns: dict: a dict of ``{argument_name: value}`` items.
def delete_handle_value(self, handle, key): ''' Delete a key-value pair from a handle record. If the key exists more than once, all key-value pairs with this key are deleted. :param handle: Handle from whose record the entry should be deleted. :param key: Key to be deleted. Also...
Delete a key-value pair from a handle record. If the key exists more than once, all key-value pairs with this key are deleted. :param handle: Handle from whose record the entry should be deleted. :param key: Key to be deleted. Also accepts a list of keys. :raises: :exc:`~b2handle.handle...
async def api_call(self, endpoint): """Call the API.""" data = None if self.session is None: self.session = aiohttp.ClientSession() try: async with async_timeout.timeout(5, loop=self.loop): response = await self.session.get(endpoint, headers=HEADER...
Call the API.
def growSynapses(self, segments, activeInputsBySource, initialPermanence): """ Grow synapses to each of the specified inputs on each specified segment. @param segments (numpy array) The segments that should add synapses @param activeInputsBySource (dict) The active cells in each source. Exampl...
Grow synapses to each of the specified inputs on each specified segment. @param segments (numpy array) The segments that should add synapses @param activeInputsBySource (dict) The active cells in each source. Example: {"customInputName1": np.array([42, 69])} @param initialPermanence (float)
def place(vertices_resources, nets, machine, constraints, breadth_first=True): """Places vertices in breadth-first order along a hilbert-curve path through the chips in the machine. This is a thin wrapper around the :py:func:`sequential <rig.place_and_route.place.sequential.place>` placement algorithm ...
Places vertices in breadth-first order along a hilbert-curve path through the chips in the machine. This is a thin wrapper around the :py:func:`sequential <rig.place_and_route.place.sequential.place>` placement algorithm which optionally uses the :py:func:`breadth_first_vertex_order` vertex ordering ...
def render(self): """ Returns the rendered release notes from all parsers as a string """ release_notes = [] for parser in self.parsers: parser_content = parser.render() if parser_content is not None: release_notes.append(parser_content) return u"\...
Returns the rendered release notes from all parsers as a string
def parameter_names_flat(self, include_fixed=False): """ Return the flattened parameter names for all subsequent parameters of this parameter. We do not include the name for self here! If you want the names for fixed parameters as well in this list, set include_fixed to True. ...
Return the flattened parameter names for all subsequent parameters of this parameter. We do not include the name for self here! If you want the names for fixed parameters as well in this list, set include_fixed to True. if not hasattr(obj, 'cache'): obj.cache = Funct...
def route(self, path=None, method='GET', callback=None, name=None, apply=None, skip=None, **config): """ A decorator to bind a function to a request URL. Example:: @app.route('/hello/:name') def hello(name): return 'Hello %s' % name ...
A decorator to bind a function to a request URL. Example:: @app.route('/hello/:name') def hello(name): return 'Hello %s' % name The ``:name`` part is a wildcard. See :class:`Router` for syntax details. :param path: Request path o...
def get_consistent_edges(graph: BELGraph) -> Iterable[Tuple[BaseEntity, BaseEntity]]: """Yield pairs of (source node, target node) for which all of their edges have the same type of relation. :return: An iterator over (source, target) node pairs corresponding to edges with many inconsistent relations """ ...
Yield pairs of (source node, target node) for which all of their edges have the same type of relation. :return: An iterator over (source, target) node pairs corresponding to edges with many inconsistent relations
def get_cumulative_data(self): """Get the data as it will be charted. The first set will be the actual first data set. The second will be the sum of the first and the second, etc.""" sets = map(itemgetter('data'), self.data) if not sets: return sum = sets.pop(0) yield sum while sets: sum = map(a...
Get the data as it will be charted. The first set will be the actual first data set. The second will be the sum of the first and the second, etc.
def _findRedundantProteins(protToPeps, pepToProts, proteins=None): """Returns a set of proteins with redundant peptide evidence. After removing the redundant proteins from the "protToPeps" and "pepToProts" mapping, all remaining proteins have at least one unique peptide. The remaining proteins are a "m...
Returns a set of proteins with redundant peptide evidence. After removing the redundant proteins from the "protToPeps" and "pepToProts" mapping, all remaining proteins have at least one unique peptide. The remaining proteins are a "minimal" set of proteins that are able to explain all peptides. However...
def _mb_model(self, beta, mini_batch): """ Creates the structure of the model Parameters ---------- beta : np.array Contains untransformed starting values for latent variables mini_batch : int Mini batch size for the data sampling Returns ...
Creates the structure of the model Parameters ---------- beta : np.array Contains untransformed starting values for latent variables mini_batch : int Mini batch size for the data sampling Returns ---------- lambda : np.array ...
def enable_zones(self, zones): """ Enable availability zones to this Access Point. All zones must be in the same region as the Access Point. :type zones: string or List of strings :param zones: The name of the zone(s) to add. """ if isinstance(zones, str) or isi...
Enable availability zones to this Access Point. All zones must be in the same region as the Access Point. :type zones: string or List of strings :param zones: The name of the zone(s) to add.
def _psi(self, x, y, q, s): """ expression after equation (8) in Keeton&Kochanek 1998 :param x: :param y: :param q: :param s: :return: """ return np.sqrt(q**2 * (s**2 + x**2) + y**2)
expression after equation (8) in Keeton&Kochanek 1998 :param x: :param y: :param q: :param s: :return:
def modflow_read_hydmod_file(hydmod_file, hydmod_outfile=None): """ read in a binary hydmod file and return a dataframe of the results Parameters ---------- hydmod_file : str modflow hydmod binary file hydmod_outfile : str output file to write. If None, use <hydmod_file>.dat. ...
read in a binary hydmod file and return a dataframe of the results Parameters ---------- hydmod_file : str modflow hydmod binary file hydmod_outfile : str output file to write. If None, use <hydmod_file>.dat. Default is None Returns ------- df : pandas.DataFrame ...
def makeSubDir(dirName): """Makes a given subdirectory if it doesn't already exist, making sure it us public. """ if not os.path.exists(dirName): os.mkdir(dirName) os.chmod(dirName, 0777) return dirName
Makes a given subdirectory if it doesn't already exist, making sure it us public.
def integrate_auto_switch(odes, kw, x, y0, params=(), **kwargs): """ Auto-switching between formulations of ODE system. In case one has a formulation of a system of ODEs which is preferential in the beginning of the integration, this function allows the user to run the integration with this system wher...
Auto-switching between formulations of ODE system. In case one has a formulation of a system of ODEs which is preferential in the beginning of the integration, this function allows the user to run the integration with this system where it takes a user-specified maximum number of steps before switching ...
def _initialize(self, *args, **kwargs): """Initiaize the mapping matcher with constructor arguments.""" self.items = None self.keys = None self.values = None if args: if len(args) != 2: raise TypeError("expected exactly two positional arguments, " ...
Initiaize the mapping matcher with constructor arguments.
def get_stack_frame(self, max_size = None): """ Reads the contents of the current stack frame. Only works for functions with standard prologue and epilogue. @type max_size: int @param max_size: (Optional) Maximum amount of bytes to read. @rtype: str @return: S...
Reads the contents of the current stack frame. Only works for functions with standard prologue and epilogue. @type max_size: int @param max_size: (Optional) Maximum amount of bytes to read. @rtype: str @return: Stack frame data. May not be accurate, depending on t...
def initialize_memory(basic_block): """ Initializes global memory array with the given one """ global MEMORY MEMORY = basic_block.mem get_labels(MEMORY, basic_block) basic_block.mem = MEMORY
Initializes global memory array with the given one
def create_where(): """ Create a grammar for the 'where' clause used by 'select' """ conjunction = Forward().setResultsName("conjunction") nested = Group(Suppress("(") + conjunction + Suppress(")")).setResultsName( "conjunction" ) maybe_nested = nested | constraint inverted = Group(not_...
Create a grammar for the 'where' clause used by 'select'
async def jsk_vc_youtube_dl(self, ctx: commands.Context, *, url: str): """ Plays audio from youtube_dl-compatible sources. """ if not youtube_dl: return await ctx.send("youtube_dl is not installed.") voice = ctx.guild.voice_client if voice.is_playing(): ...
Plays audio from youtube_dl-compatible sources.
def show_updates(self): """ Check installed packages for available updates on PyPI @param project_name: optional package name to check; checks every installed pacakge if none specified @type project_name: string @returns: None """ di...
Check installed packages for available updates on PyPI @param project_name: optional package name to check; checks every installed pacakge if none specified @type project_name: string @returns: None
async def set_volume(self, volume: int, *, device: Optional[SomeDevice] = None): """Set the volume for the user’s current playback device. Parameters ---------- volume : int The volume to set. Must be a value from 0 to 100 inclusive. device : Optional[:obj:`SomeDevic...
Set the volume for the user’s current playback device. Parameters ---------- volume : int The volume to set. Must be a value from 0 to 100 inclusive. device : Optional[:obj:`SomeDevice`] The Device object or id of the device this command is targeting. ...
def save_feature(self, cat, img, feature, data): """Saves a new feature.""" filename = self.path(cat, img, feature) mkdir(filename) savemat(filename, {'output':data})
Saves a new feature.
def cmd_cammsg(self, args): '''cammsg''' print("Sent DIGICAM_CONTROL CMD_LONG") self.master.mav.command_long_send( self.settings.target_system, # target_system 0, # target_component mavutil.mavlink.MAV_CMD_DO_DIGICAM_CONTROL, # command 0, # confi...
cammsg