code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def process(self, batch, *args, **kwargs): """ Process a list of examples to create a batch. Postprocess the batch with user-provided Pipeline. Args: batch (list(object)): A list of object from a batch of examples. Returns: object: Processed object given the inp...
Process a list of examples to create a batch. Postprocess the batch with user-provided Pipeline. Args: batch (list(object)): A list of object from a batch of examples. Returns: object: Processed object given the input and custom postprocessing Pipeline.
def bench(client, n): """ Benchmark n requests """ pairs = [(x, x + 1) for x in range(n)] started = time.time() for pair in pairs: res, err = client.call('add', *pair) # assert err is None duration = time.time() - started print('Client stats:') util.print_stats(n, duration)
Benchmark n requests
def rvs(self, size=1, **kwargs): """Returns random values for all of the parameters. """ size = int(size) dtype = [(p, float) for p in self.params] arr = numpy.zeros(size, dtype=dtype) remaining = size keepidx = 0 while remaining: draws = self....
Returns random values for all of the parameters.
def is_valid_pid_for_create(did): """Assert that ``did`` can be used as a PID for creating a new object with MNStorage.create() or MNStorage.update().""" if not d1_gmn.app.did.is_valid_pid_for_create(did): raise d1_common.types.exceptions.IdentifierNotUnique( 0, 'Identifier i...
Assert that ``did`` can be used as a PID for creating a new object with MNStorage.create() or MNStorage.update().
def maybe_convert_objects(values, convert_dates=True, convert_numeric=True, convert_timedeltas=True, copy=True): """ if we have an object dtype, try to coerce dates and/or numbers """ # if we have passed in a list or scalar if isinstance(values, (list, tuple)): values = np...
if we have an object dtype, try to coerce dates and/or numbers
def gps2_raw_encode(self, time_usec, fix_type, lat, lon, alt, eph, epv, vel, cog, satellites_visible, dgps_numch, dgps_age): ''' Second GPS data. Coordinate frame is right-handed, Z-axis up (GPS frame). time_usec : Timestamp (microseconds ...
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 _from_binary_ea_info(cls, binary_stream): """See base class.""" ''' Size of Extended Attribute entry - 2 Number of Extended Attributes which have NEED_EA set - 2 Size of extended attribute data - 4 ''' return cls(cls._REPR.unpack(binary_stream[:cls._REPR.size]))
See base class.
def update_cer(self, symbol, cer, account=None): """ Update the Core Exchange Rate (CER) of an asset :param str symbol: Symbol of the asset to publish feed for :param bitshares.price.Price cer: Core exchange Rate :param str account: (optional) the account to allow access ...
Update the Core Exchange Rate (CER) of an asset :param str symbol: Symbol of the asset to publish feed for :param bitshares.price.Price cer: Core exchange Rate :param str account: (optional) the account to allow access to (defaults to ``default_account``)
def has_tag(self, model): """Does the given port have this tag?""" for tag in model.tags: if self.is_tag(tag): return True return False
Does the given port have this tag?
def load_fasta_file_as_dict_of_seqrecords(filename): """Load a FASTA file and return the sequences as a dict of {ID: SeqRecord} Args: filename (str): Path to the FASTA file to load Returns: dict: Dictionary of IDs to their SeqRecords """ results = {} records = load_fasta_file...
Load a FASTA file and return the sequences as a dict of {ID: SeqRecord} Args: filename (str): Path to the FASTA file to load Returns: dict: Dictionary of IDs to their SeqRecords
def _create_buffer_control(self, editor_buffer): """ Create a new BufferControl for a given location. """ @Condition def preview_search(): return self.editor.incsearch input_processors = [ # Processor for visualising spaces. (should come before th...
Create a new BufferControl for a given location.
def overlap_summary(self): """ print summary of reconstruction overlaps """ olaps = self.compute_overlaps() # compute min, 25% 50% (median), mean, 75%, max table = [["5%: ",np.percentile(olaps,5)], ["25%: ",np.percentile(olaps,25)], ["50%: ",np.percent...
print summary of reconstruction overlaps
def get_names(file_dir, files): """ Get the annotator name list based on a list of files Args: file_dir: AMR file folder files: a list of AMR names, e.g. nw_wsj_0001_1 Returns: a list of user names who annotate all the files """ # for each user, check if they have files available ...
Get the annotator name list based on a list of files Args: file_dir: AMR file folder files: a list of AMR names, e.g. nw_wsj_0001_1 Returns: a list of user names who annotate all the files
def _get_depthsr(self, goobj): """Return DNN or RNN depending on if relationships are loaded.""" if 'reldepth' in self.gosubdag.prt_attr['flds']: return "R{R:02}".format(R=goobj.reldepth) return "D{D:02}".format(D=goobj.depth)
Return DNN or RNN depending on if relationships are loaded.
def read_from(self, provider, **options): """ All :class:`Pointer` fields in the `Sequence` read the necessary number of bytes from the data :class:`Provider` for their referenced :attr:`~Pointer.data` object. Null pointer are ignored. :param Provider provider: data :class:`Provider`. ...
All :class:`Pointer` fields in the `Sequence` read the necessary number of bytes from the data :class:`Provider` for their referenced :attr:`~Pointer.data` object. Null pointer are ignored. :param Provider provider: data :class:`Provider`. :keyword bool nested: if ``True`` all :class:`P...
def build_columns(self, X, verbose=False): """construct the model matrix columns for the term Parameters ---------- X : array-like Input dataset with n rows verbose : bool whether to show warnings Returns ------- scipy sparse arr...
construct the model matrix columns for the term Parameters ---------- X : array-like Input dataset with n rows verbose : bool whether to show warnings Returns ------- scipy sparse array with n rows
def cli(env, identifier, sortby, cpu, domain, hostname, memory, tag, columns): """List guests which are in a dedicated host server.""" mgr = SoftLayer.DedicatedHostManager(env.client) guests = mgr.list_guests(host_id=identifier, cpus=cpu, hostname=h...
List guests which are in a dedicated host server.
def _generate_struct_class_h(self, struct): """Defines an Obj C header file that represents a struct in Stone.""" self._generate_init_imports_h(struct) self._generate_imports_h(self._get_imports_h(struct)) self.emit() self.emit('NS_ASSUME_NONNULL_BEGIN') self.emit() ...
Defines an Obj C header file that represents a struct in Stone.
def next(self): """Return 'next' version. Eg, next(1.2) is 1.2_""" if self.tokens: other = self.copy() tok = other.tokens.pop() other.tokens.append(tok.next()) return other else: return Version.inf
Return 'next' version. Eg, next(1.2) is 1.2_
def split_once(self, horizontal: bool, position: int) -> None: """Split this partition into 2 sub-partitions. Args: horizontal (bool): position (int): """ cdata = self._as_cdata() lib.TCOD_bsp_split_once(cdata, horizontal, position) self._unpack_b...
Split this partition into 2 sub-partitions. Args: horizontal (bool): position (int):
def get_mor_by_property(service_instance, object_type, property_value, property_name='name', container_ref=None): ''' Returns the first managed object reference having the specified property value. service_instance The Service Instance from which to obtain managed object references. object_typ...
Returns the first managed object reference having the specified property value. service_instance The Service Instance from which to obtain managed object references. object_type The type of content for which to obtain managed object references. property_value The name of the prope...
def check_type_compatibility(type_1_id, type_2_id): """ When applying a type to a resource, it may be the case that the resource already has an attribute specified in the new type, but the template which defines this pre-existing attribute has a different unit specification to the new templa...
When applying a type to a resource, it may be the case that the resource already has an attribute specified in the new type, but the template which defines this pre-existing attribute has a different unit specification to the new template. This function checks for any situations where different...
def declareProvisioner(self, *args, **kwargs): """ Update a provisioner Declare a provisioner, supplying some details about it. `declareProvisioner` allows updating one or more properties of a provisioner as long as the required scopes are possessed. For example, a request to u...
Update a provisioner Declare a provisioner, supplying some details about it. `declareProvisioner` allows updating one or more properties of a provisioner as long as the required scopes are possessed. For example, a request to update the `aws-provisioner-v1` provisioner with a body `{de...
def compile( self, scss_string=None, scss_file=None, source_files=None, super_selector=None, filename=None, is_sass=None, line_numbers=True, import_static_css=False): """Compile Sass to CSS. Returns a single CSS string. This method is DEPRECATED; see :mod:`scss.comp...
Compile Sass to CSS. Returns a single CSS string. This method is DEPRECATED; see :mod:`scss.compiler` instead.
def save(self, directory_path): """ Save the material (the unencrypted PEM encoded RSA private key) of a newly created KeyPair to a local file. :type directory_path: string :param directory_path: The fully qualified path to the directory in...
Save the material (the unencrypted PEM encoded RSA private key) of a newly created KeyPair to a local file. :type directory_path: string :param directory_path: The fully qualified path to the directory in which the keypair will be saved. The ...
def setupFeatures(self): """ Make the features source. **This should not be called externally.** Subclasses may override this method to handle the file creation in a different way if desired. """ if self.featureWriters: featureFile = parseLayoutFeatur...
Make the features source. **This should not be called externally.** Subclasses may override this method to handle the file creation in a different way if desired.
def from_gff3(path, attributes=None, region=None, score_fill=-1, phase_fill=-1, attributes_fill='.', dtype=None): """Read a feature table from a GFF3 format file. Parameters ---------- path : string File path. attributes : list of strings, optional ...
Read a feature table from a GFF3 format file. Parameters ---------- path : string File path. attributes : list of strings, optional List of columns to extract from the "attributes" field. region : string, optional Genome region to extract. If ...
def get_platform_settings(): """ Returns the content of `settings.PLATFORMS` with a twist. The platforms settings was created to stay compatible with the old way of declaring the FB configuration, in order not to break production bots. This function will convert the legacy configuration into the ne...
Returns the content of `settings.PLATFORMS` with a twist. The platforms settings was created to stay compatible with the old way of declaring the FB configuration, in order not to break production bots. This function will convert the legacy configuration into the new configuration if required. As a res...
def colorbar(fig, ax, im, width=0.05, height=1.0, hoffset=0.01, voffset=0.0, orientation='vertical'): ''' draw colorbar without resizing the axes object to make room kwargs: :: fig : matplotlib.figure.Figure ...
draw colorbar without resizing the axes object to make room kwargs: :: fig : matplotlib.figure.Figure ax : matplotlib.axes.AxesSubplot im : matplotlib.image.AxesImage width : float, colorbar width in fraction of ax width height : float, colorbar height in fraction of ax ...
def GET(self): """ Show page """ todos = model.get_todos() form = self.form() return render.index(todos, form)
Show page
def insert_func(self, index, func, *args, **kwargs): ''' insert func with given arguments and keywords. ''' wraped_func = partial(func, *args, **kwargs) self.insert(index, wraped_func)
insert func with given arguments and keywords.
def _generate_response_head_bytes(status_code, headers): """ :type status_code: int :type headers: dict[str, str] :rtype: bytes """ head_string = str(status_code) + _DELIMITER_NEWLINE header_tuples = sorted((k, headers[k]) for k in headers) for name, value in header_tuples: na...
:type status_code: int :type headers: dict[str, str] :rtype: bytes
def add_properties(props, mol): """apply properties to the molecule object Returns: None (alter molecule object directly) """ if not props: return # The properties supersedes all charge and radical values in the atom block for _, atom in mol.atoms_iter(): atom.charge = 0...
apply properties to the molecule object Returns: None (alter molecule object directly)
def setedgeval(delta, is_multigraph, graph, orig, dest, idx, key, value): """Change a delta to say that an edge stat was set to a certain value""" if is_multigraph(graph): if ( graph in delta and 'edges' in delta[graph] and orig in delta[graph]['edges'] and dest in delta[graph]['...
Change a delta to say that an edge stat was set to a certain value
def retry(*r_args, **r_kwargs): """ Decorator wrapper for retry_call. Accepts arguments to retry_call except func and then returns a decorator for the decorated function. Ex: >>> @retry(retries=3) ... def my_func(a, b): ... "this is my funk" ... print(a, b) >>> my_func.__doc__ 'this is my funk' """...
Decorator wrapper for retry_call. Accepts arguments to retry_call except func and then returns a decorator for the decorated function. Ex: >>> @retry(retries=3) ... def my_func(a, b): ... "this is my funk" ... print(a, b) >>> my_func.__doc__ 'this is my funk'
def read_input_file(self, fn): """ This method may be overridden to implement a custom lookup mechanism when encountering ``\\input`` or ``\\include`` directives. The default implementation looks for a file of the given name relative to the directory set by :py:meth:`set_tex_inp...
This method may be overridden to implement a custom lookup mechanism when encountering ``\\input`` or ``\\include`` directives. The default implementation looks for a file of the given name relative to the directory set by :py:meth:`set_tex_input_directory()`. If `strict_input=True` wa...
def file_can_be_read(path): """ Return ``True`` if the file at the given ``path`` can be read. :param string path: the file path :rtype: bool .. versionadded:: 1.4.0 """ if path is None: return False try: with io.open(path, "rb") as test_file: pass r...
Return ``True`` if the file at the given ``path`` can be read. :param string path: the file path :rtype: bool .. versionadded:: 1.4.0
def visitLexerRuleSpec(self, ctx: jsgParser.LexerRuleSpecContext): """ lexerRuleSpec: LEXER_ID COLON lexerRuleBlock SEMI """ self._context.grammarelts[as_token(ctx)] = JSGLexerRuleBlock(self._context, ctx.lexerRuleBlock())
lexerRuleSpec: LEXER_ID COLON lexerRuleBlock SEMI
def translations_link(self): """ Print on admin change list the link to see all translations for this object @type text: string @param text: a string with the html to link to the translations admin interface """ translation_type = ContentType.objects.get_for_model(Transl...
Print on admin change list the link to see all translations for this object @type text: string @param text: a string with the html to link to the translations admin interface
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ # extracting dictionary of coefficients specific to required #...
See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.
def disabledColor(self): """ Returns the color this node should render when its disabled. :return <QColor> """ palette = self.palette() return palette.color(palette.Disabled, palette.NodeBackground)
Returns the color this node should render when its disabled. :return <QColor>
def is_sqlatype_text_of_length_at_least( coltype: Union[TypeEngine, VisitableType], min_length: int = 1000) -> bool: """ Is the SQLAlchemy column type a string type that's at least the specified length? """ coltype = _coltype_to_typeengine(coltype) if not isinstance(coltype, sqlt...
Is the SQLAlchemy column type a string type that's at least the specified length?
def add_bundle(name, scripts=[], files=[], scriptsdir=SCRIPTSDIR, filesdir=FILESDIR): """High level, simplified interface for creating a bundle which takes the bundle name, a list of script file names in a common scripts directory, and a list of absolute target file paths, of which the basename is also...
High level, simplified interface for creating a bundle which takes the bundle name, a list of script file names in a common scripts directory, and a list of absolute target file paths, of which the basename is also located in a common files directory. It converts those lists into maps and then calls new...
def path_completer(text, expected=None, classes=None, perm_level=None, include_current_proj=False, typespec=None, visibility=None): ''' :param text: String to tab-complete to a path matching the syntax project-name:folder/entity_or_folder_name :type text: string :param expected: "fold...
:param text: String to tab-complete to a path matching the syntax project-name:folder/entity_or_folder_name :type text: string :param expected: "folder", "entity", "project", or None (no restriction) as to the types of answers to look for :type expected: string :param classes: if expected="entity", the ...
def fromPattern(cls, datetime_string, datetime_pattern, time_zone, require_hour=True): ''' a method for constructing labDT from a strptime pattern in a string https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior iso_pattern: '%Y-%m-%dT%H:%M:%S....
a method for constructing labDT from a strptime pattern in a string https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior iso_pattern: '%Y-%m-%dT%H:%M:%S.%f%z' human_friendly_pattern: '%A, %B %d, %Y %I:%M:%S.%f%p' :param datetime_string: string wi...
def asDictionary(self): """returns the wkid id for use in json calls""" if self._wkid == None and self._wkt is not None: return {"wkt": self._wkt} else: return {"wkid": self._wkid}
returns the wkid id for use in json calls
def create_from_name_and_dictionary(self, name, datas): """Return a populated object Object from dictionary datas """ if "type" not in datas: str_type = "any" else: str_type = str(datas["type"]).lower() if str_type not in ObjectRaw.Types: type...
Return a populated object Object from dictionary datas
def _find_child(self, tag): """Find the child C{etree.Element} with the matching C{tag}. @raises L{WSDLParseError}: If more than one such elements are found. """ tag = self._get_namespace_tag(tag) children = self._root.findall(tag) if len(children) > 1: raise...
Find the child C{etree.Element} with the matching C{tag}. @raises L{WSDLParseError}: If more than one such elements are found.
def query(starttime, endtime, output=None, *filenames): '''Given a time range and input file, query creates a new file with only that subset of data. If no outfile name is given, the new file name is the old file name with the time range appended. Args: starttime: The datetime of th...
Given a time range and input file, query creates a new file with only that subset of data. If no outfile name is given, the new file name is the old file name with the time range appended. Args: starttime: The datetime of the beginning time range to be extracted from the files. ...
def get_features_all(self): """ Return all features with its names. Regardless of being used for train and prediction. Sorted by the names. Returns ------- all_features : OrderedDict Features dictionary. """ features = {} # Get all ...
Return all features with its names. Regardless of being used for train and prediction. Sorted by the names. Returns ------- all_features : OrderedDict Features dictionary.
def show_instance(name, call=None): ''' Show the details from AzureARM concerning an instance ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) try: node = list_nodes_full('function')[name] exc...
Show the details from AzureARM concerning an instance
def _deriv_logaddexp2(x1, x2): """The derivative of f(x, y) = log2(2^x + 2^y)""" y1 = np.exp2(x1) y2 = np.exp2(x2) df_dx1 = y1 / (y1 + y2) df_dx2 = y2 / (y1 + y2) return np.vstack([df_dx1, df_dx2]).T
The derivative of f(x, y) = log2(2^x + 2^y)
def velocity_graph(adata, basis=None, vkey='velocity', which_graph='velocity', n_neighbors=10, alpha=.8, perc=90, edge_width=.2, edge_color='grey', color=None, use_raw=None, layer=None, color_map=None, colorbar=True, palette=None, size=None, sort_order=True, groups=None, ...
\ Plot of the velocity graph. Arguments --------- adata: :class:`~anndata.AnnData` Annotated data matrix. vkey: `str` or `None` (default: `None`) Key for annotations of observations/cells or variables/genes. which_graph: `'velocity'` or `'neighbors'` (default: `'velocity'`) ...
def _register_custom_filters(self): """Register any custom filter modules.""" custom_filters = self.settings.get('CUSTOM_FILTERS', []) if not isinstance(custom_filters, list): raise KeyError("`CUSTOM_FILTERS` setting must be a list.") for filter_module_name in custom_filters...
Register any custom filter modules.
async def _download_photo(self, photo, file, date, thumb, progress_callback): """Specialized version of .download_media() for photos""" # Determine the photo and its largest size if isinstance(photo, types.MessageMediaPhoto): photo = photo.photo if not isinstance(photo, types...
Specialized version of .download_media() for photos
def absent(name, vname=None, use_32bit_registry=False): r''' Ensure a registry value is removed. To remove a key use key_absent. Args: name (str): A string value representing the full path of the key to include the HIVE, Key, and all Subkeys. For example: ``HKEY...
r''' Ensure a registry value is removed. To remove a key use key_absent. Args: name (str): A string value representing the full path of the key to include the HIVE, Key, and all Subkeys. For example: ``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` Valid hive val...
def tomask(self, pores=None, throats=None): r""" Convert a list of pore or throat indices into a boolean mask of the correct length Parameters ---------- pores or throats : array_like List of pore or throat indices. Only one of these can be specified ...
r""" Convert a list of pore or throat indices into a boolean mask of the correct length Parameters ---------- pores or throats : array_like List of pore or throat indices. Only one of these can be specified at a time, and the returned result will be of t...
def make_call_types(f, globals_d): # type: (Callable, Dict) -> Tuple[Dict[str, Anno], Anno] """Make a call_types dictionary that describes what arguments to pass to f Args: f: The function to inspect for argument names (without self) globals_d: A dictionary of globals to lookup annotation d...
Make a call_types dictionary that describes what arguments to pass to f Args: f: The function to inspect for argument names (without self) globals_d: A dictionary of globals to lookup annotation definitions in
def _ensure_device_active(self, device): '''Ensure a single device is in an active state :param device: ManagementRoot object -- device to inspect :raises: UnexpectedClusterState ''' act = device.tm.cm.devices.device.load( name=get_device_info(device).name, ...
Ensure a single device is in an active state :param device: ManagementRoot object -- device to inspect :raises: UnexpectedClusterState
def init(host='0.0.0.0', port=1338): """ Initialize PyMLGame. This creates a controller thread that listens for game controllers and events. :param host: Bind to this address :param port: Bind to this port :type host: str :type port: int """ CONTROLLER.host = host CONTROLLER.port = ...
Initialize PyMLGame. This creates a controller thread that listens for game controllers and events. :param host: Bind to this address :param port: Bind to this port :type host: str :type port: int
async def main(): """ Main code (asynchronous requests) You can send one millions request with aiohttp : https://pawelmhm.github.io/asyncio/python/aiohttp/2016/04/22/asyncio-aiohttp.html But don't do that on one server, it's DDOS ! """ # Create Client from endpoint string in Duniter form...
Main code (asynchronous requests) You can send one millions request with aiohttp : https://pawelmhm.github.io/asyncio/python/aiohttp/2016/04/22/asyncio-aiohttp.html But don't do that on one server, it's DDOS !
def dedent_description(pkg_info): """ Dedent and convert pkg_info['Description'] to Unicode. """ description = pkg_info['Description'] # Python 3 Unicode handling, sorta. surrogates = False if not isinstance(description, str): surrogates = True description = pkginfo_unicode(...
Dedent and convert pkg_info['Description'] to Unicode.
def improvise_step(oracle, i, lrs=0, weight=None, prune=False): """ Given the current time step, improvise (generate) the next time step based on the oracle structure. :param oracle: an indexed vmo object :param i: current improvisation time step :param lrs: the length of minimum longest repeated suffi...
Given the current time step, improvise (generate) the next time step based on the oracle structure. :param oracle: an indexed vmo object :param i: current improvisation time step :param lrs: the length of minimum longest repeated suffixes allowed to jump :param weight: if None, jump to possible candida...
def find_closing_parenthesis(sql, startpos): """Find the pair of opening and closing parentheses. Starts search at the position startpos. Returns tuple of positions (opening, closing) if search succeeds, otherwise None. """ pattern = re.compile(r'[()]') level = 0 opening = [] for match ...
Find the pair of opening and closing parentheses. Starts search at the position startpos. Returns tuple of positions (opening, closing) if search succeeds, otherwise None.
def initial(self, request, *args, **kwargs): """ Overrides DRF's `initial` in order to set the `_sorting_field` from corresponding property in view. Protected property is required in order to support overriding of `sorting_field` via `@property`, we do this after original `initial` has b...
Overrides DRF's `initial` in order to set the `_sorting_field` from corresponding property in view. Protected property is required in order to support overriding of `sorting_field` via `@property`, we do this after original `initial` has been ran in order to make sure that view has all its properties se...
def get_courses(self, **kwargs): """ Return a list of active courses for the current user. :calls: `GET /api/v1/courses \ <https://canvas.instructure.com/doc/api/courses.html#method.courses.index>`_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`...
Return a list of active courses for the current user. :calls: `GET /api/v1/courses \ <https://canvas.instructure.com/doc/api/courses.html#method.courses.index>`_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of :class:`canvasapi.course.Course`
def _add(self, name, *args, **kw): """ Add an argument to the underlying parser and grow the list .all_arguments and the set .names """ argname = list(self.argdict)[self._argno] if argname != name: raise NameError( 'Setting argument %s, but it ...
Add an argument to the underlying parser and grow the list .all_arguments and the set .names
def format_file_params(files): ''' Utility method for formatting file parameters for transmission ''' files_payload = {} if files: for idx, filename in enumerate(files): files_payload["file[" + str(idx) + "]"] = open(filename, 'rb') return ...
Utility method for formatting file parameters for transmission
def database(self, name=None): """Connect to a database called `name`. Parameters ---------- name : str, optional The name of the database to connect to. If ``None``, return the database named ``self.current_database``. Returns ------- db...
Connect to a database called `name`. Parameters ---------- name : str, optional The name of the database to connect to. If ``None``, return the database named ``self.current_database``. Returns ------- db : Database An :class:`ibis.cl...
def _load_libcrypto(): ''' Load OpenSSL libcrypto ''' if sys.platform.startswith('win'): # cdll.LoadLibrary on windows requires an 'str' argument return cdll.LoadLibrary(str('libeay32')) # future lint: disable=blacklisted-function elif getattr(sys, 'frozen', False) and salt.utils.pl...
Load OpenSSL libcrypto
def delete(self, eid, token): """ Delete a library entry. :param eid str: Entry ID :param token str: OAuth Token :return: True or ServerError :rtype: Bool or Exception """ final_headers = self.header final_headers['Authorization'] = "Bearer {}".fo...
Delete a library entry. :param eid str: Entry ID :param token str: OAuth Token :return: True or ServerError :rtype: Bool or Exception
def _available_services(): ''' Return a dictionary of all available services on the system ''' available_services = dict() for launch_dir in _launchd_paths(): for root, dirs, files in salt.utils.path.os_walk(launch_dir): for filename in files: file_path = os.path....
Return a dictionary of all available services on the system
def str2et(time): """ Convert a string representing an epoch to a double precision value representing the number of TDB seconds past the J2000 epoch corresponding to the input epoch. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/str2et_c.html :param time: A string representing an epo...
Convert a string representing an epoch to a double precision value representing the number of TDB seconds past the J2000 epoch corresponding to the input epoch. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/str2et_c.html :param time: A string representing an epoch. :type time: str :r...
def send_command_response(self, source: list, command: str, *args, **kwargs): """ Used in bot observer `on_next` method """ args = _json.dumps(args).encode('utf8') ...
Used in bot observer `on_next` method
def put_resource(self, resource): """ Adds a resource back to the pool or discards it if the pool is full. :param resource: A resource object. :raises UnknownResourceError: If resource was not made by the pool. """ rtracker = self...
Adds a resource back to the pool or discards it if the pool is full. :param resource: A resource object. :raises UnknownResourceError: If resource was not made by the pool.
def _setup_ipc(self): ''' Setup the listener ICP pusher. ''' log.debug('Setting up the listener IPC pusher') self.ctx = zmq.Context() self.pub = self.ctx.socket(zmq.PUSH) self.pub.connect(LST_IPC_URL) log.debug('Setting HWM for the listener: %d', self.opts...
Setup the listener ICP pusher.
def create_revert(self, revert_to_create, project, repository_id): """CreateRevert. [Preview API] Starts the operation to create a new branch which reverts changes introduced by either a specific commit or commits that are associated to a pull request. :param :class:`<GitAsyncRefOperationParamet...
CreateRevert. [Preview API] Starts the operation to create a new branch which reverts changes introduced by either a specific commit or commits that are associated to a pull request. :param :class:`<GitAsyncRefOperationParameters> <azure.devops.v5_1.git.models.GitAsyncRefOperationParameters>` revert_to_...
def fast_hash(self): """ Get a CRC32 or xxhash.xxh64 reflecting the DataStore. Returns ------------ hashed: int, checksum of data """ fast = sum(i.fast_hash() for i in self.data.values()) return fast
Get a CRC32 or xxhash.xxh64 reflecting the DataStore. Returns ------------ hashed: int, checksum of data
def train_batch(self, batch_info, data, target): """ Train single batch of data """ batch_info.optimizer.zero_grad() loss = self.feed_batch(batch_info, data, target) loss.backward() if self.max_grad_norm is not None: batch_info['grad_norm'] = torch.nn.utils.clip_grad...
Train single batch of data
def surface_normal(self, param): """Unit vector perpendicular to the detector surface at ``param``. The orientation is chosen as follows: - In 2D, the system ``(normal, tangent)`` should be right-handed. - In 3D, the system ``(tangent[0], tangent[1], normal)`` ...
Unit vector perpendicular to the detector surface at ``param``. The orientation is chosen as follows: - In 2D, the system ``(normal, tangent)`` should be right-handed. - In 3D, the system ``(tangent[0], tangent[1], normal)`` should be right-handed. ...
def get_tunnel_info_input_filter_type_filter_by_site_site_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_tunnel_info = ET.Element("get_tunnel_info") config = get_tunnel_info input = ET.SubElement(get_tunnel_info, "input") filter...
Auto Generated Code
def needsEncoding(self, s): """ Get whether string I{s} contains special characters. @param s: A string to check. @type s: str @return: True if needs encoding. @rtype: boolean """ if isinstance(s, str): for c in self.special: if...
Get whether string I{s} contains special characters. @param s: A string to check. @type s: str @return: True if needs encoding. @rtype: boolean
def dump_to_path(self, cnf, filepath, **kwargs): """ Dump config 'cnf' to a file 'filepath'. :param cnf: Configuration data to dump :param filepath: Config file path :param kwargs: optional keyword parameters to be sanitized :: dict """ with self.wopen(filepath) ...
Dump config 'cnf' to a file 'filepath'. :param cnf: Configuration data to dump :param filepath: Config file path :param kwargs: optional keyword parameters to be sanitized :: dict
def delete(self, file_, delete_file=True): """ Deletes file_ references in Key Value store and optionally the file_ it self. """ image_file = ImageFile(file_) if delete_file: image_file.delete() default.kvstore.delete(image_file)
Deletes file_ references in Key Value store and optionally the file_ it self.
def determine_types(self): """ Determine ES type names from request data. In particular `request.matchdict['collections']` is used to determine types names. Its value is comma-separated sequence of collection names under which views have been registered. """ from neferta...
Determine ES type names from request data. In particular `request.matchdict['collections']` is used to determine types names. Its value is comma-separated sequence of collection names under which views have been registered.
def calc_fft_with_PyCUDA(Signal): """ Calculates the FFT of the passed signal by using the scikit-cuda libary which relies on PyCUDA Parameters ---------- Signal : ndarray Signal to be transformed into Fourier space Returns ------- Signalfft : ndarray Array containi...
Calculates the FFT of the passed signal by using the scikit-cuda libary which relies on PyCUDA Parameters ---------- Signal : ndarray Signal to be transformed into Fourier space Returns ------- Signalfft : ndarray Array containing the signal's FFT
def makeStylesheetResource(self, path, registry): """ Return a resource for the css at the given path with its urls rewritten based on self.rootURL. """ return StylesheetRewritingResourceWrapper( File(path), self.installedOfferingNames, self.rootURL)
Return a resource for the css at the given path with its urls rewritten based on self.rootURL.
def update(self): """ Update this function. :return: None """ if self._owner_changed: self.update_owner(self.owner) self._resources = [res.name for res in self.resources] return self.parent.update(self)
Update this function. :return: None
def _add_task(self, tile_address, coroutine): """Add a task from within the event loop. All tasks are associated with a tile so that they can be cleanly stopped when that tile is reset. """ self.verify_calling_thread(True, "_add_task is not thread safe") if tile_addres...
Add a task from within the event loop. All tasks are associated with a tile so that they can be cleanly stopped when that tile is reset.
def check(self, line_info): """If the ifun is magic, and automagic is on, run it. Note: normal, non-auto magic would already have been triggered via '%' in check_esc_chars. This just checks for automagic. Also, before triggering the magic handler, make sure that there is nothing in the...
If the ifun is magic, and automagic is on, run it. Note: normal, non-auto magic would already have been triggered via '%' in check_esc_chars. This just checks for automagic. Also, before triggering the magic handler, make sure that there is nothing in the user namespace which could sha...
def restore(delta, which): r""" Generate one of the two sequences that generated a delta. Given a `delta` produced by `Differ.compare()` or `ndiff()`, extract lines originating from file 1 or 2 (parameter `which`), stripping off line prefixes. Examples: >>> diff = ndiff('one\ntwo\nthree\n...
r""" Generate one of the two sequences that generated a delta. Given a `delta` produced by `Differ.compare()` or `ndiff()`, extract lines originating from file 1 or 2 (parameter `which`), stripping off line prefixes. Examples: >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), ... ...
def process_mutect_vcf(job, mutect_vcf, work_dir, univ_options): """ Process the MuTect vcf for accepted calls. :param toil.fileStore.FileID mutect_vcf: fsID for a MuTect generated chromosome vcf :param str work_dir: Working directory :param dict univ_options: Dict of universal options used by almo...
Process the MuTect vcf for accepted calls. :param toil.fileStore.FileID mutect_vcf: fsID for a MuTect generated chromosome vcf :param str work_dir: Working directory :param dict univ_options: Dict of universal options used by almost all tools :return: Path to the processed vcf :rtype: str
def notebook_executed(pth): """Determine whether the notebook at `pth` has been executed.""" nb = nbformat.read(pth, as_version=4) for n in range(len(nb['cells'])): if nb['cells'][n].cell_type == 'code' and \ nb['cells'][n].execution_count is None: return False retur...
Determine whether the notebook at `pth` has been executed.
def get_instance(self, payload): """ Build an instance of ThisMonthInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthInstance :rtype: twilio.rest.api.v2010.account.usage.record.this_month.ThisMon...
Build an instance of ThisMonthInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthInstance :rtype: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthInstance
def add_child_bin(self, bin_id, child_id): """Adds a child to a bin. arg: bin_id (osid.id.Id): the ``Id`` of a bin arg: child_id (osid.id.Id): the ``Id`` of the new child raise: AlreadyExists - ``bin_id`` is already a parent of ``child_id`` raise: NotFoun...
Adds a child to a bin. arg: bin_id (osid.id.Id): the ``Id`` of a bin arg: child_id (osid.id.Id): the ``Id`` of the new child raise: AlreadyExists - ``bin_id`` is already a parent of ``child_id`` raise: NotFound - ``bin_id`` or ``child_id`` not found raise...
def _hosts_in_unenumerated_pattern(self, pattern): """ Get all host names matching the pattern """ hosts = {} # ignore any negative checks here, this is handled elsewhere pattern = pattern.replace("!","").replace("&", "") groups = self.get_groups() for group in groups: ...
Get all host names matching the pattern
def _set_notification(self, conn, char, enabled, timeout=1.0): """Enable/disable notifications on a GATT characteristic Args: conn (int): The connection handle for the device we should interact with char (dict): The characteristic we should modify enabled (bool): Sho...
Enable/disable notifications on a GATT characteristic Args: conn (int): The connection handle for the device we should interact with char (dict): The characteristic we should modify enabled (bool): Should we enable or disable notifications timeout (float): How lo...
def gmst(utc_time): """Greenwich mean sidereal utc_time, in radians. As defined in the AIAA 2006 implementation: http://www.celestrak.com/publications/AIAA/2006-6753/ """ ut1 = jdays2000(utc_time) / 36525.0 theta = 67310.54841 + ut1 * (876600 * 3600 + 8640184.812866 + ut1 * ...
Greenwich mean sidereal utc_time, in radians. As defined in the AIAA 2006 implementation: http://www.celestrak.com/publications/AIAA/2006-6753/
def set_connection(connection=defaults.sqlalchemy_connection_string_default): """Set the connection string for sqlalchemy and write it to the config file. .. code-block:: python import pyhgnc pyhgnc.set_connection('mysql+pymysql://{user}:{passwd}@{host}/{db}?charset={charset}') .. hint::...
Set the connection string for sqlalchemy and write it to the config file. .. code-block:: python import pyhgnc pyhgnc.set_connection('mysql+pymysql://{user}:{passwd}@{host}/{db}?charset={charset}') .. hint:: valid connection strings - mysql+pymysql://user:passwd@localhost/d...
def star(self) -> snug.Query[bool]: """star this repo""" req = snug.PUT(BASE + f'/user/starred/{self.owner}/{self.name}') return (yield req).status_code == 204
star this repo