code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def parse_command_line(self, argv=None): """Parse the jhubctl command line arguments. This overwrites traitlets' default `parse_command_line` method and tailors it to jhubctl's needs. """ argv = sys.argv[1:] if argv is None else argv self.argv = [py3compat.cast_u...
Parse the jhubctl command line arguments. This overwrites traitlets' default `parse_command_line` method and tailors it to jhubctl's needs.
def length_of_overlap(first_start, first_end, second_start, second_end): """ Find the length of the overlapping part of two segments. Args: first_start (float): Start of the first segment. first_end (float): End of the first segment. second_start (float): Start of the second segment...
Find the length of the overlapping part of two segments. Args: first_start (float): Start of the first segment. first_end (float): End of the first segment. second_start (float): Start of the second segment. second_end (float): End of the second segment. Return: float: ...
def _createAssociateRequest(self, endpoint, assoc_type, session_type): """Create an association request for the given assoc_type and session_type. @param endpoint: The endpoint whose server_url will be queried. The important bit about the endpoint is whether it's in comp...
Create an association request for the given assoc_type and session_type. @param endpoint: The endpoint whose server_url will be queried. The important bit about the endpoint is whether it's in compatiblity mode (OpenID 1.1) @param assoc_type: The association type that t...
def install_new_pipeline(): """ Install above transformer into the existing pipeline creator. """ def new_create_pipeline(context, *args, **kwargs): result = old_create_pipeline(context, *args, **kwargs) result.insert(1, DAAPObjectTransformer(context)) return result old_cr...
Install above transformer into the existing pipeline creator.
def cms_identify(self, url, timeout=15, headers={}): """ Function called when attempting to determine if a URL is identified as being this particular CMS. @param url: the URL to attempt to identify. @param timeout: number of seconds before a timeout occurs on a http c...
Function called when attempting to determine if a URL is identified as being this particular CMS. @param url: the URL to attempt to identify. @param timeout: number of seconds before a timeout occurs on a http connection. @param headers: custom HTTP headers as expected by req...
def double_percent_options_to_metadata(options): """Parse double percent options""" matches = _PERCENT_CELL.findall('# %%' + options) # Fail safe when regexp matching fails #116 # (occurs e.g. if square brackets are found in the title) if not matches: return {'title': options.strip()} ...
Parse double percent options
def com_google_fonts_check_name_typographicsubfamilyname(ttFont, style_with_spaces): """ Check name table: TYPOGRAPHIC_SUBFAMILY_NAME entries. """ from fontbakery.utils import name_entry_id failed = False if style_with_spaces in ['Regular', 'Italic', 'Bold'...
Check name table: TYPOGRAPHIC_SUBFAMILY_NAME entries.
def convertToBool(): """ Convert a byte value to boolean (0 or 1) if the global flag strictBool is True """ if not OPTIONS.strictBool.value: return [] REQUIRES.add('strictbool.asm') result = [] result.append('pop af') result.append('call __NORMALIZE_BOOLEAN') result.append(...
Convert a byte value to boolean (0 or 1) if the global flag strictBool is True
def string(self, writesize=None): ''' Looks like a file handle ''' if not self.finished: self.finished = True return self.content return ''
Looks like a file handle
def getCollectorPath(self): """ Returns collector path servers.host.cpu.total.idle return "cpu" """ # If we don't have a host name, assume it's just the third part of the # metric path if self.host is None: return self.path.split('....
Returns collector path servers.host.cpu.total.idle return "cpu"
def upload_nginx_site_conf(site_name, template_name=None, context=None, enable=True): """Upload Nginx site configuration from a template.""" template_name = template_name or [u'nginx/%s.conf' % site_name, u'nginx/site.conf'] site_available = u'/etc/nginx/sites-available/%s' % site_name upload_templ...
Upload Nginx site configuration from a template.
def ingest(event): '''Ingest a finished recording to the Opencast server. ''' # Update status set_service_status(Service.INGEST, ServiceStatus.BUSY) notify.notify('STATUS=Uploading') recording_state(event.uid, 'uploading') update_event_status(event, Status.UPLOADING) # Select ingest ser...
Ingest a finished recording to the Opencast server.
def load_transform(fname): """Load affine transform from file Parameters ---------- fname : str or None Filename of an LTA or FSL-style MAT transform file. If ``None``, return an identity transform Returns ------- affine : (4, 4) numpy.ndarray """ if fname is None: ...
Load affine transform from file Parameters ---------- fname : str or None Filename of an LTA or FSL-style MAT transform file. If ``None``, return an identity transform Returns ------- affine : (4, 4) numpy.ndarray
def select_month(self, month): """ 选择月份 @2018/06/03 pandas 的索引问题导致 https://github.com/pandas-dev/pandas/issues/21299 因此先用set_index去重做一次index 影响的有selects,select_time,select_month,get_bar @2018/06/04 当选择的时间越界/股票不存在,raise ValueError @2018/06/04 pa...
选择月份 @2018/06/03 pandas 的索引问题导致 https://github.com/pandas-dev/pandas/issues/21299 因此先用set_index去重做一次index 影响的有selects,select_time,select_month,get_bar @2018/06/04 当选择的时间越界/股票不存在,raise ValueError @2018/06/04 pandas索引问题已经解决 全部恢复
def make_df_from_batch(batch_name, batch_col="b01", reader=None, reader_label=None): """Create a pandas DataFrame with the info needed for ``cellpy`` to load the runs. Args: batch_name (str): Name of the batch. batch_col (str): The column where the batch name is in the db. reader (m...
Create a pandas DataFrame with the info needed for ``cellpy`` to load the runs. Args: batch_name (str): Name of the batch. batch_col (str): The column where the batch name is in the db. reader (method): the db-loader method. reader_label (str): the label for the db-loader (if db...
def color(string, name, style='normal', when='auto'): """ Change the color of the given string. """ if name not in colors: from .text import oxford_comma raise ValueError("unknown color '{}'.\nknown colors are: {}".format( name, oxford_comma(["'{}'".format(x) for x in sorted(colors)]...
Change the color of the given string.
def first_solar_spectral_loss(self, pw, airmass_absolute): """ Use the :py:func:`first_solar_spectral_correction` function to calculate the spectral loss modifier. The model coefficients are specific to the module's cell type, and are determined by searching for one of the follo...
Use the :py:func:`first_solar_spectral_correction` function to calculate the spectral loss modifier. The model coefficients are specific to the module's cell type, and are determined by searching for one of the following keys in self.module_parameters (in order): 'first_solar_spectra...
def putParamset(self, paramset, data={}): """ Some devices act upon changes to paramsets. A "putted" paramset must not contain all keys available in the specified paramset, just the ones which are writable and should be changed. """ try: if paramset in self._P...
Some devices act upon changes to paramsets. A "putted" paramset must not contain all keys available in the specified paramset, just the ones which are writable and should be changed.
def motif3struct_bin(A): ''' Structural motifs are patterns of local connectivity. Motif frequency is the frequency of occurrence of motifs around a node. Parameters ---------- A : NxN np.ndarray binary directed connection matrix Returns ------- F : 13xN np.ndarray ...
Structural motifs are patterns of local connectivity. Motif frequency is the frequency of occurrence of motifs around a node. Parameters ---------- A : NxN np.ndarray binary directed connection matrix Returns ------- F : 13xN np.ndarray motif frequency matrix f : 13x1 n...
def on_push(self, device): """Press button. Check DEFAULT_DELAY. :param scapy.packet.Packet device: Scapy packet :return: None """ src = device.src.lower() if last_execution[src] + self.settings.get('delay', DEFAULT_DELAY) > time.time(): return last_e...
Press button. Check DEFAULT_DELAY. :param scapy.packet.Packet device: Scapy packet :return: None
def present(name=None, start_addr=None, end_addr=None, data=None, **api_opts): ''' Ensure range record is present. infoblox_range.present: start_addr: '129.97.150.160', end_addr: '129.97.150.170', Verbose state example: .. code-block:: yaml infoblox_range.present: ...
Ensure range record is present. infoblox_range.present: start_addr: '129.97.150.160', end_addr: '129.97.150.170', Verbose state example: .. code-block:: yaml infoblox_range.present: data: { 'always_update_dns': False, 'authority': False...
def parse_hostname(hostname, default_port): ''' Parse hostname string and return a tuple of (host, port) If port missing in hostname string then use default_port If anything is not a valid then return None hostname should contain a host and an option space delimited port host port As an at...
Parse hostname string and return a tuple of (host, port) If port missing in hostname string then use default_port If anything is not a valid then return None hostname should contain a host and an option space delimited port host port As an attempt to prevent foolish mistakes the parser also tries ...
def find(*_, **kwargs): """ Find user by id/email""" click.echo(green('\nFind user:')) click.echo(green('-' * 40)) with get_app().app_context(): user = find_user(kwargs) if not user: click.echo(red('Not found\n')) return click.echo(str(user) + '\n') return
Find user by id/email
def create_entity(self, workspace_id, entity, description=None, metadata=None, fuzzy_match=None, values=None, **kwargs): """ Create entity. C...
Create entity. Create a new entity, or enable a system entity. This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. This st...
def winning_name(self): """ Returns a ``string`` of the winning team's name, such as 'Purdue Boilermakers'. """ if self.winner == HOME: if 'cbb/schools' not in str(self._home_name): return str(self._home_name) return self._home_name.text() ...
Returns a ``string`` of the winning team's name, such as 'Purdue Boilermakers'.
def dumps(): """Returns a string representation of the FILTERS dictionary.""" d = {} for k, v in FILTERS.items(): d[dr.get_name(k)] = list(v) return _dumps(d)
Returns a string representation of the FILTERS dictionary.
def _enum_from_direction(direction): """Convert a string representation of a direction to an enum. Args: direction (str): A direction to order by. Must be one of :attr:`~.firestore.Query.ASCENDING` or :attr:`~.firestore.Query.DESCENDING`. Returns: int: The enum corr...
Convert a string representation of a direction to an enum. Args: direction (str): A direction to order by. Must be one of :attr:`~.firestore.Query.ASCENDING` or :attr:`~.firestore.Query.DESCENDING`. Returns: int: The enum corresponding to ``direction``. Raises: ...
def parseFilename(filename): """ Parse out filename from any specified extensions. Returns rootname and string version of extension name. Modified from 'pydrizzle.fileutil' to allow this module to be independent of PyDrizzle/MultiDrizzle. """ # Parse out any extension speci...
Parse out filename from any specified extensions. Returns rootname and string version of extension name. Modified from 'pydrizzle.fileutil' to allow this module to be independent of PyDrizzle/MultiDrizzle.
def _parse_common_paths_file(project_path): """ Parses a common_paths.xml file and returns a dictionary of paths, a dictionary of annotation level descriptions and the filename of the style file. Parameters ---------- project_path : str path to the ro...
Parses a common_paths.xml file and returns a dictionary of paths, a dictionary of annotation level descriptions and the filename of the style file. Parameters ---------- project_path : str path to the root directory of the MMAX project Returns ------...
def put(self, resource): """ Edits an existing resource Args: resource - gophish.models.Model - The resource instance """ endpoint = self.endpoint if resource.id: endpoint = self._build_url(endpoint, resource.id) response = self.api.execute("PU...
Edits an existing resource Args: resource - gophish.models.Model - The resource instance
def get_module_names(p): '''Accepts a path to search for modules. The method will filter on files that end in .pyc or files that start with __. Arguments: p (string): The path to search Returns: list of file names ''' mods = list() mods = [f.split('.')[0] for f in listdir(p)...
Accepts a path to search for modules. The method will filter on files that end in .pyc or files that start with __. Arguments: p (string): The path to search Returns: list of file names
def parse_at_element( self, element, # type: ET.Element state # type: _ProcessorState ): # type: (...) -> Any """Parse the given element.""" xml_value = self._processor.parse_at_element(element, state) return _hooks_apply_after_parse(self._hooks,...
Parse the given element.
def delete_certificate_issuer_config_by_id(self, certificate_issuer_configuration_id, **kwargs): # noqa: E501 """Delete certificate issuer configuration. # noqa: E501 Delete the configured certificate issuer configuration. You can only delete the configurations of custom certificates. # noqa: E501 ...
Delete certificate issuer configuration. # noqa: E501 Delete the configured certificate issuer configuration. You can only delete the configurations of custom certificates. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass...
def _start_monitoring(self): """ Internal method that monitors the directory for changes """ # Grab all the timestamp info before = self._file_timestamp_info(self.path) while True: gevent.sleep(1) after = self._file_timestamp_info(self.path) ...
Internal method that monitors the directory for changes
def check_constraints(self, instance): ''' Return fieldnames which need recalculation. ''' recalc_fields = [] for constraint in self.constraints: try: constraint(self.model, instance) except constraints.InvalidConstraint as e: ...
Return fieldnames which need recalculation.
def survey(self, pk=None, **kwargs): """Get the survey_spec for the job template. To write a survey, use the modify command with the --survey-spec parameter. =====API DOCS===== Get the survey specification of a resource object. :param pk: Primary key of the resource to retrieve...
Get the survey_spec for the job template. To write a survey, use the modify command with the --survey-spec parameter. =====API DOCS===== Get the survey specification of a resource object. :param pk: Primary key of the resource to retrieve survey from. Tower CLI will only attempt to ...
def maybe(func): """Calls `f` in a try/except block, returning a `Fail` object if the call fails in any way. If any of the arguments to the call are Fail objects, the call is not attempted.""" name = object_name(func) @wraps(func) def maybe_wrapped(*args, **kwargs): """@maybe wrapped v...
Calls `f` in a try/except block, returning a `Fail` object if the call fails in any way. If any of the arguments to the call are Fail objects, the call is not attempted.
def user(self, message): """ Creates a user log (if user logging is turned on) Uses the log path defined by ``Debug.setUserLogFile()``. If no log file is defined, sends to STDOUT Note: Does *not* use Java string formatting like Sikuli. Format your message with Python ``basestri...
Creates a user log (if user logging is turned on) Uses the log path defined by ``Debug.setUserLogFile()``. If no log file is defined, sends to STDOUT Note: Does *not* use Java string formatting like Sikuli. Format your message with Python ``basestring.format()`` instead.
def num_tasks(self, work_spec_name): '''Get the total number of work units for some work spec.''' return self.num_finished(work_spec_name) + \ self.num_failed(work_spec_name) + \ self.registry.len(WORK_UNITS_ + work_spec_name)
Get the total number of work units for some work spec.
def _data(self): """A simpler version of data to avoid infinite recursion in some cases. Don't use this. """ if self.is_caching: return self.cache with open(self.path, "r") as f: return json.load(f)
A simpler version of data to avoid infinite recursion in some cases. Don't use this.
def sorted_proposals(proposals, scopepref=None, typepref=None): """Sort a list of proposals Return a sorted list of the given `CodeAssistProposal`\s. `scopepref` can be a list of proposal scopes. Defaults to ``['parameter_keyword', 'local', 'global', 'imported', 'attribute', 'builtin', 'keyword']...
Sort a list of proposals Return a sorted list of the given `CodeAssistProposal`\s. `scopepref` can be a list of proposal scopes. Defaults to ``['parameter_keyword', 'local', 'global', 'imported', 'attribute', 'builtin', 'keyword']``. `typepref` can be a list of proposal types. Defaults to `...
def set_storage_controller_bootable(self, name, bootable): """Sets the bootable flag of the storage controller with the given name. in name of type str in bootable of type bool raises :class:`VBoxErrorObjectNotFound` A storage controller with given name doesn't exist. ...
Sets the bootable flag of the storage controller with the given name. in name of type str in bootable of type bool raises :class:`VBoxErrorObjectNotFound` A storage controller with given name doesn't exist. raises :class:`VBoxErrorObjectInUse` Another ...
def assortativity_wei(CIJ, flag=0): ''' The assortativity coefficient is a correlation coefficient between the strengths (weighted degrees) of all nodes on two opposite ends of a link. A positive assortativity coefficient indicates that nodes tend to link to other nodes with the same or similar stre...
The assortativity coefficient is a correlation coefficient between the strengths (weighted degrees) of all nodes on two opposite ends of a link. A positive assortativity coefficient indicates that nodes tend to link to other nodes with the same or similar strength. Parameters ---------- CIJ : N...
def append(self, other): """ Append a Printable Image at the end of the current instance. :param other: another PrintableImage :return: PrintableImage containing data from both self and other """ self.data.extend(other.data) self.height = self.height + other.heigh...
Append a Printable Image at the end of the current instance. :param other: another PrintableImage :return: PrintableImage containing data from both self and other
def wgs84_to_utm(lng, lat, utm_crs=None): """ Convert WGS84 coordinates to UTM. If UTM CRS is not set it will be calculated automatically. :param lng: longitude in WGS84 system :type lng: float :param lat: latitude in WGS84 system :type lat: float :param utm_crs: UTM coordinate reference system...
Convert WGS84 coordinates to UTM. If UTM CRS is not set it will be calculated automatically. :param lng: longitude in WGS84 system :type lng: float :param lat: latitude in WGS84 system :type lat: float :param utm_crs: UTM coordinate reference system enum constants :type utm_crs: constants.CRS o...
def get_consumed_read_units_percent( table_name, gsi_name, lookback_window_start=15, lookback_period=5): """ Returns the number of consumed read units in percent :type table_name: str :param table_name: Name of the DynamoDB table :type gsi_name: str :param gsi_name: Name of the GSI :typ...
Returns the number of consumed read units in percent :type table_name: str :param table_name: Name of the DynamoDB table :type gsi_name: str :param gsi_name: Name of the GSI :type lookback_window_start: int :param lookback_window_start: Relative start time for the CloudWatch metric :type lo...
def get_queryset(self): """ Return queryset limited to not removed entries. """ kwargs = {'model': self.model, 'using': self._db} if hasattr(self, '_hints'): kwargs['hints'] = self._hints return self._queryset_class(**kwargs).filter(is_removed=False)
Return queryset limited to not removed entries.
def update_name( self, name ): """ Rename the current checklist item. Returns a new ChecklistItem object. """ checklistitem_json = self.fetch_json( uri_path = self.base_uri + '/name', http_method = 'PUT', query_params = {'value': name} ) ...
Rename the current checklist item. Returns a new ChecklistItem object.
def remove_child(self, *sprites): """Remove one or several :class:`Sprite` sprites from scene """ # first drop focus scene = self.get_scene() if scene: child_sprites = list(self.all_child_sprites()) if scene._focus_sprite in child_sprites: scene....
Remove one or several :class:`Sprite` sprites from scene
def slice(self, start_time, end_time, strict=False): ''' Slice every annotation contained in the annotation array using `Annotation.slice` and return as a new AnnotationArray See `Annotation.slice` for details about slicing. This function does not modify the annotations ...
Slice every annotation contained in the annotation array using `Annotation.slice` and return as a new AnnotationArray See `Annotation.slice` for details about slicing. This function does not modify the annotations in the original annotation array. Parameters ---------- ...
def evaluate(x, amplitude, mean, stddev): """ GaussianAbsorption1D model function. """ return 1.0 - Gaussian1D.evaluate(x, amplitude, mean, stddev)
GaussianAbsorption1D model function.
def load_deploy_config(deploy_filename, config=None): ''' Loads any local config overrides in the deploy file. ''' if not config: config = Config() if not deploy_filename: return if path.exists(deploy_filename): extract_file_config(deploy_filename, config) return ...
Loads any local config overrides in the deploy file.
def removed(name, ruby=None, user=None, gem_bin=None): ''' Make sure that a gem is not installed. name The name of the gem to uninstall gem_bin : None Full path to ``gem`` binary to use. ruby : None If RVM or rbenv are installed, the ruby version and gemset to use. ...
Make sure that a gem is not installed. name The name of the gem to uninstall gem_bin : None Full path to ``gem`` binary to use. ruby : None If RVM or rbenv are installed, the ruby version and gemset to use. Ignored if ``gem_bin`` is specified. user: None The u...
def sb_filter(fastq, bc, cores, nedit): ''' Filters reads with non-matching sample barcodes Expects formatted fastq files. ''' barcodes = set(sb.strip() for sb in bc) if nedit == 0: filter_sb = partial(exact_sample_filter2, barcodes=barcodes) else: barcodehash = MutationHash(barc...
Filters reads with non-matching sample barcodes Expects formatted fastq files.
def paramnames(co): """ Get the parameter names from a pycode object. Returns a 4-tuple of (args, kwonlyargs, varargs, varkwargs). varargs and varkwargs will be None if the function doesn't take *args or **kwargs, respectively. """ flags = co.co_flags varnames = co.co_varnames argc...
Get the parameter names from a pycode object. Returns a 4-tuple of (args, kwonlyargs, varargs, varkwargs). varargs and varkwargs will be None if the function doesn't take *args or **kwargs, respectively.
def set_manip(self, manip, ovs_sm=None, ovs_lg=None, name='A manipulatable'): """stub""" o3d_manip_id = self.create_o3d_asset(manip, small_ov_set=ovs_sm, large_ov_set=ovs_lg, ...
stub
def cluster(points, radius): """ Clustering of points in space. `radius` is the radius of local search. Individual subsets can be accessed through ``actor.clusters``. .. hint:: |clustering| |clustering.py|_ """ if isinstance(points, vtk.vtkActor): poly = points.GetMapper().GetInput...
Clustering of points in space. `radius` is the radius of local search. Individual subsets can be accessed through ``actor.clusters``. .. hint:: |clustering| |clustering.py|_
def multipublish(self, topic, messages, block=True, timeout=None, raise_error=True): """Publish an iterable of messages to the given topic. :param topic: the topic to publish to :param messages: iterable of bytestrings to publish :param block: wait for a connectio...
Publish an iterable of messages to the given topic. :param topic: the topic to publish to :param messages: iterable of bytestrings to publish :param block: wait for a connection to become available before publishing the message. If block is `False` and no connections a...
def execute_cross_join(op, left, right, **kwargs): """Execute a cross join in pandas. Notes ----- We create a dummy column of all :data:`True` instances and use that as the join key. This results in the desired Cartesian product behavior guaranteed by cross join. """ # generate a uniqu...
Execute a cross join in pandas. Notes ----- We create a dummy column of all :data:`True` instances and use that as the join key. This results in the desired Cartesian product behavior guaranteed by cross join.
def diff(local_path, remote_path): """Return true if local and remote paths differ in contents""" with hide('commands'): if isinstance(local_path, basestring): with open(local_path) as stream: local_content = stream.read() else: pos = local_path.tell() ...
Return true if local and remote paths differ in contents
def _le_from_lt(self, other): """Return a <= b. Computed by @total_ordering from (a < b) or (a == b).""" op_result = self.__lt__(other) return op_result or self == other
Return a <= b. Computed by @total_ordering from (a < b) or (a == b).
def polish(commit_indexes=None, urls=None): ''' Apply certain behaviors to commits or URLs that need polishing before they are ready for screenshots For example, if you have 10 commits in a row where static file links were broken, you could re-write the html in memory as it is interpreted. Keyword...
Apply certain behaviors to commits or URLs that need polishing before they are ready for screenshots For example, if you have 10 commits in a row where static file links were broken, you could re-write the html in memory as it is interpreted. Keyword arguments: commit_indexes -- A list of indexes to a...
def subclass_exception(name, parents, module, attached_to=None): """ Create exception subclass. If 'attached_to' is supplied, the exception will be created in a way that allows it to be pickled, assuming the returned exception class will be added as an attribute to the 'attached_to' class. """ ...
Create exception subclass. If 'attached_to' is supplied, the exception will be created in a way that allows it to be pickled, assuming the returned exception class will be added as an attribute to the 'attached_to' class.
def set_monitor(self, monitor): """Set the monitor config. This module assumes that users will connect to the roaster and get reading information _before_ they want to begin collecting roast details. This method is critical to enabling the collection of roast information and ens...
Set the monitor config. This module assumes that users will connect to the roaster and get reading information _before_ they want to begin collecting roast details. This method is critical to enabling the collection of roast information and ensuring it gets saved in memory. :pa...
def has_src_builder(self): """Return whether this Node has a source builder or not. If this Node doesn't have an explicit source code builder, this is where we figure out, on the fly, if there's a transparent source code builder for it. Note that if we found a source builder, w...
Return whether this Node has a source builder or not. If this Node doesn't have an explicit source code builder, this is where we figure out, on the fly, if there's a transparent source code builder for it. Note that if we found a source builder, we also set the self.builder at...
def _WorkerCommand_launcher(self): """Return list commands to start the bootstrap process""" return [ self.workersArguments.pythonExecutable, '-m', 'scoop.launch.__main__', str(self.workerAmount), str(self.workersArguments.verbose), ]
Return list commands to start the bootstrap process
def compute(self, x, yerr=0.0, **kwargs): """ Pre-compute the covariance matrix and factorize it for a set of times and uncertainties. :param x: ``(nsamples,)`` or ``(nsamples, ndim)`` The independent coordinates of the data points. :param yerr: (optional) ``(nsampl...
Pre-compute the covariance matrix and factorize it for a set of times and uncertainties. :param x: ``(nsamples,)`` or ``(nsamples, ndim)`` The independent coordinates of the data points. :param yerr: (optional) ``(nsamples,)`` or scalar The Gaussian uncertainties on the...
def write_electrodes(self, filename): """ Write X Y coordinates of electrodes """ fid = open(filename, 'w') for i in self.Electrodes: fid.write('{0} {1}\n'.format(self.Points[i][0], self.Points[i][1])) fid.close()
Write X Y coordinates of electrodes
def _ensure_initialized(cls, instance=None, gateway=None, conf=None): """ Checks whether a SparkContext is initialized or not. Throws error if a SparkContext is already running. """ with SparkContext._lock: if not SparkContext._gateway: SparkContext._g...
Checks whether a SparkContext is initialized or not. Throws error if a SparkContext is already running.
def tag_add(self, *tags): """ Return a view with the specified tags added """ return View({**self.spec, 'tag': list(set(self.tags) | set(tags))})
Return a view with the specified tags added
def list_upgrades(refresh=True, backtrack=3, **kwargs): # pylint: disable=W0613 ''' List all available package upgrades. refresh Whether or not to sync the portage tree before checking for upgrades. backtrack Specifies an integer number of times to backtrack if dependency calc...
List all available package upgrades. refresh Whether or not to sync the portage tree before checking for upgrades. backtrack Specifies an integer number of times to backtrack if dependency calculation fails due to a conflict or an unsatisfied dependency (default: ´3´). ...
def load_card(self, code, cache=True): """ Load a card with the given code from the database. This calls each save event hook on the save string before commiting it to the database. Will cache each resulting card for faster future lookups with this method while respecting the li...
Load a card with the given code from the database. This calls each save event hook on the save string before commiting it to the database. Will cache each resulting card for faster future lookups with this method while respecting the libraries cache limit. However only if the cache argu...
def get_metadata(address=None, tx_hash=None, block_hash=None, api_key=None, private=True, coin_symbol='btc'): ''' Get metadata using blockcypher's API. This is data on blockcypher's servers and not embedded into the bitcoin (or other) blockchain. ''' assert is_valid_coin_symbol(coin_symbol), coin_s...
Get metadata using blockcypher's API. This is data on blockcypher's servers and not embedded into the bitcoin (or other) blockchain.
def sort_seeds(uhandle, usort): """ sort seeds from cluster results""" cmd = ["sort", "-k", "2", uhandle, "-o", usort] proc = sps.Popen(cmd, close_fds=True) proc.communicate()
sort seeds from cluster results
def get_dependency_graph(self): """Generate the dependency graph. The dependency graph is a simpler subset of the resolve graph. It contains package name nodes connected directly to their dependencies. Weak references and conflict requests are not included in the graph. The depe...
Generate the dependency graph. The dependency graph is a simpler subset of the resolve graph. It contains package name nodes connected directly to their dependencies. Weak references and conflict requests are not included in the graph. The dependency graph does not show conflicts. ...
def do_cleanup(self, subcmd, opts, *args): """Recursively clean up the working copy, removing locks, resuming unfinished operations, etc. usage: cleanup [PATH...] ${cmd_option_list} """ print "'svn %s' opts: %s" % (subcmd, opts) print "'svn %...
Recursively clean up the working copy, removing locks, resuming unfinished operations, etc. usage: cleanup [PATH...] ${cmd_option_list}
def getEffort(self, vehID, time, edgeID): """getEffort(string, double, string) -> double . """ self._connection._beginMessage(tc.CMD_GET_VEHICLE_VARIABLE, tc.VAR_EDGE_EFFORT, vehID, 1 + 4 + 1 + 4 + 1 + 4 + len(edgeID)) self._connection._str...
getEffort(string, double, string) -> double .
def register_command(self, name: str, f: Callable): """Registers an existing callable object as a command callback This method can be used instead of the ``@command`` decorator. Both do the same thing, but this method is useful for registering callbacks for methods defined before or out...
Registers an existing callable object as a command callback This method can be used instead of the ``@command`` decorator. Both do the same thing, but this method is useful for registering callbacks for methods defined before or outside the scope of your bot object, allowing you to defi...
def clear(self): """Clears this instance's cache.""" if self._cache is not None: with self._cache as c, self._out as out: self.in_flush_all = True c.clear() out.clear() # pylint: disable=no-member self.in_flush_all = False
Clears this instance's cache.
def get_element_attribute(elem_to_parse, attrib_name, default_value=u''): """ :return: an attribute from the parsed element if it has the attribute, otherwise the default value """ element = get_element(elem_to_parse) if element is None: return default_value return element.attrib....
:return: an attribute from the parsed element if it has the attribute, otherwise the default value
def _build_basic_context(self): """ Return a standard dict used in django as a template context """ # printDebug(str(self.ontospy_graph.toplayer_classes)) topclasses = self.ontospy_graph.toplayer_classes[:] if len(topclasses) < 3: # massage the toplayer! for ...
Return a standard dict used in django as a template context
def realpath(self, spec, key): """ Resolve and update the path key in the spec with its realpath, based on the working directory. """ if key not in spec: # do nothing for now return if not spec[key]: logger.warning( "c...
Resolve and update the path key in the spec with its realpath, based on the working directory.
def unpackVersion(ver): ''' Unpack a system normalized integer representing a softare version into its component parts. Args: ver (int): System normalized integer value to unpack into a tuple. Returns: (int, int, int): A tuple containing the major, minor and patch values shifted out of...
Unpack a system normalized integer representing a softare version into its component parts. Args: ver (int): System normalized integer value to unpack into a tuple. Returns: (int, int, int): A tuple containing the major, minor and patch values shifted out of the integer.
def getRecommendedRenderTargetSize(self): """Suggested size for the intermediate render target that the distortion pulls from.""" fn = self.function_table.getRecommendedRenderTargetSize pnWidth = c_uint32() pnHeight = c_uint32() fn(byref(pnWidth), byref(pnHeight)) return...
Suggested size for the intermediate render target that the distortion pulls from.
def _init_metadata(self): """stub""" super(PDFPreviewFormRecord, self)._init_metadata() self._preview_metadata = { 'element_id': Id(self.my_osid_object_form._authority, self.my_osid_object_form._namespace, 'file'), ...
stub
def filename_add_custom_url_params(filename, request): """ Adds custom url parameters to filename string :param filename: Initial filename :type filename: str :param request: OGC-type request with specified bounding box, cloud coverage for specific product. :type request: OgcReq...
Adds custom url parameters to filename string :param filename: Initial filename :type filename: str :param request: OGC-type request with specified bounding box, cloud coverage for specific product. :type request: OgcRequest or GeopediaRequest :return: Filename with custom url p...
def last_blank(src): """Determine if the input source ends in a blank. A blank is either a newline or a line consisting of whitespace. Parameters ---------- src : string A single or multiline string. """ if not src: return False ll = src.splitlines()[-1] return (ll == '') or...
Determine if the input source ends in a blank. A blank is either a newline or a line consisting of whitespace. Parameters ---------- src : string A single or multiline string.
def mkdirs(remote_dir, use_sudo=False): """ Wrapper around mkdir -pv Returns a list of directories created """ func = use_sudo and sudo or run result = func(' '.join(['mkdir -pv',remote_dir])).split('\n') #extract dir list from ["mkdir: created directory `example.com/some/dir'"] if ...
Wrapper around mkdir -pv Returns a list of directories created
def render_binary(self, context, result): """Return binary responses unmodified.""" context.response.app_iter = iter((result, )) # This wraps the binary string in a WSGI body iterable. return True
Return binary responses unmodified.
def map_pixel(point_x, point_y, cellx, celly, xmin, ymax): ''' Usage: map_pixel(xcoord, ycoord, x_cell_size, y_cell_size, xmin, ymax) where: xmin is leftmost X coordinate in system ymax is topmost Y coordinate in system Example: raster = HMISea.tif ndv...
Usage: map_pixel(xcoord, ycoord, x_cell_size, y_cell_size, xmin, ymax) where: xmin is leftmost X coordinate in system ymax is topmost Y coordinate in system Example: raster = HMISea.tif ndv, xsize, ysize, geot, projection, datatype = get_geo_info(raster) ...
def element_to_object(elem_to_parse, element_path=None): """ :return: the root key, and a dict with all the XML data, but without preserving structure, for instance: <elem val="attribute"><val>nested text</val><val prop="attr">nested dict text</val>nested dict tail</elem> {'elem': { 'val': [ ...
:return: the root key, and a dict with all the XML data, but without preserving structure, for instance: <elem val="attribute"><val>nested text</val><val prop="attr">nested dict text</val>nested dict tail</elem> {'elem': { 'val': [ u'nested text', {'prop': u'attr', 'value': [u'n...
def open_state_machine(path=None, recent_opened_notification=False): """ Open a state machine from respective file system path :param str path: file system path to the state machine :param bool recent_opened_notification: flags that indicates that this call also should update recently open :rtype rafc...
Open a state machine from respective file system path :param str path: file system path to the state machine :param bool recent_opened_notification: flags that indicates that this call also should update recently open :rtype rafcon.core.state_machine.StateMachine :return: opened state machine
def validate_cookies(session, class_name): """ Checks whether we have all the required cookies to authenticate on class.coursera.org. Also check for and remove stale session. """ if not do_we_have_enough_cookies(session.cookies, class_name): return False url = CLASS_URL.format(class...
Checks whether we have all the required cookies to authenticate on class.coursera.org. Also check for and remove stale session.
def create_lbaas_member(self, lbaas_pool, body=None): """Creates a lbaas_member.""" return self.post(self.lbaas_members_path % lbaas_pool, body=body)
Creates a lbaas_member.
def process_presence(self, stanza): """Process presence stanza. Pass it to a handler of the stanza's type and payload namespace. :Parameters: - `stanza`: presence stanza to be handled """ stanza_type = stanza.stanza_type return self.__try_handlers(self._pre...
Process presence stanza. Pass it to a handler of the stanza's type and payload namespace. :Parameters: - `stanza`: presence stanza to be handled
def call_status(*args, **kwargs): ''' Return the status of the lamps. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.status salt '*' hue.status id=1 salt '*' hue.status id=1,2...
Return the status of the lamps. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.status salt '*' hue.status id=1 salt '*' hue.status id=1,2,3
def get_arg_parse_arguments(self): """ During the element declaration, all configuration file requirements and all cli requirements have been described once. This method will build a dict containing all argparse options. It can be used to feed argparse.ArgumentParser. You...
During the element declaration, all configuration file requirements and all cli requirements have been described once. This method will build a dict containing all argparse options. It can be used to feed argparse.ArgumentParser. You does not need to have multiple declarations.
def techport(Id): ''' In order to use this capability, queries can be issued to the system with the following URI format: GET /xml-api/id_parameter Parameter Required? Value Description id_parameter Yes Type: String Default: None The id value of the TechPort record. TechPort values r...
In order to use this capability, queries can be issued to the system with the following URI format: GET /xml-api/id_parameter Parameter Required? Value Description id_parameter Yes Type: String Default: None The id value of the TechPort record. TechPort values range from 0-20000. Not all...
def validate(self, generator, axesToMove=None, **kwargs): # type: (AGenerator, AAxesToMove, **Any) -> AConfigureParams """Validate configuration parameters and return validated parameters. Doesn't take device state into account so can be run in any state """ iterations = 10 ...
Validate configuration parameters and return validated parameters. Doesn't take device state into account so can be run in any state
def _watchdog_queue(self): """ 从queue里取出字符执行命令 """ while not self.quit: k = self.queue.get() if k == self.keys['QUIT']: # 退出 self.quit = True self.switch_queue.put('main') elif k == self.keys['BYE']: sel...
从queue里取出字符执行命令