code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def pull(self): """This action does some state checking (adds a object in the session that will identify this chat participant and adds a coroutine to manage it's state) and gets new messages or bail out in 10 seconds if there are no messages.""" if not 'client' in session o...
This action does some state checking (adds a object in the session that will identify this chat participant and adds a coroutine to manage it's state) and gets new messages or bail out in 10 seconds if there are no messages.
def GetKeyByPath(self, key_path): """Retrieves the key for a specific path. Args: key_path (str): Windows Registry key path. Returns: WinRegistryKey: Registry key or None if not available. """ key_path_upper = key_path.upper() if key_path_upper.startswith(self._key_path_prefix_uppe...
Retrieves the key for a specific path. Args: key_path (str): Windows Registry key path. Returns: WinRegistryKey: Registry key or None if not available.
def add_class(self, cssclass): """Adds a css class to this element.""" if self.has_class(cssclass): return self return self.toggle_class(cssclass)
Adds a css class to this element.
def fetchmany(self, size=None): """Returns the next set of rows of a query result, returning a list of tuples. When no more rows are available, it returns an empty list. The number of rows returned can be specified using the size argument, which defaults to one :param s...
Returns the next set of rows of a query result, returning a list of tuples. When no more rows are available, it returns an empty list. The number of rows returned can be specified using the size argument, which defaults to one :param size: ``int`` number of rows to return ...
def _immediate_dominators(self, node, target_graph=None, reverse_graph=False): """ Get all immediate dominators of sub graph from given node upwards. :param str node: id of the node to navigate forwards from. :param networkx.classes.digraph.DiGraph target_graph: graph to analyse, defaul...
Get all immediate dominators of sub graph from given node upwards. :param str node: id of the node to navigate forwards from. :param networkx.classes.digraph.DiGraph target_graph: graph to analyse, default is self.graph. :param bool reverse_graph: Whether the target graph should be reversed bef...
def _nested_unary_mul(nested_a, p): """Multiply `Tensors` in arbitrarily nested `Tensor` `nested_a` with `p`.""" def mul_with_broadcast(tensor): ndims = tensor.shape.ndims if ndims != 2: p_reshaped = tf.reshape(p, [-1] + [1] * (ndims - 1)) return p_reshaped * tensor else: return p * te...
Multiply `Tensors` in arbitrarily nested `Tensor` `nested_a` with `p`.
def borrow_readwrite_instance(cls, working_dir, block_number, expected_snapshots={}): """ Get a read/write database handle to the blockstack db. At most one such handle can exist within the program. When the caller is done with the handle, it should call release_readwrite_instance() ...
Get a read/write database handle to the blockstack db. At most one such handle can exist within the program. When the caller is done with the handle, it should call release_readwrite_instance() Returns the handle on success Returns None if we can't set up the db. Aborts if ther...
def update(self, app_id, data): """Update app identified by app_id with data :params: * app_id (int) id in the marketplace received with :method:`create` * data (dict) some keys are required: * *name*: the title of the app. Maximum length 127 ch...
Update app identified by app_id with data :params: * app_id (int) id in the marketplace received with :method:`create` * data (dict) some keys are required: * *name*: the title of the app. Maximum length 127 characters. * *summary*: the ...
def where(cls, **kwargs): """ where(scope=None, **kwargs) Like :py:meth:`.PanoptesObject.where`, but also allows setting the query scope. - **scope** can be any of the values given in the `Classification Collection API documentation <http://docs.panoptes.apiary.io/#re...
where(scope=None, **kwargs) Like :py:meth:`.PanoptesObject.where`, but also allows setting the query scope. - **scope** can be any of the values given in the `Classification Collection API documentation <http://docs.panoptes.apiary.io/#reference/classification/classification/list-all...
def login(self, username=None, password=None, token=None): # type: (Optional[str], Optional[str], Optional[str]) -> None """Login into KE-chain with either username/password or token. :param basestring username: username for your user from KE-chain :param basestring password: password f...
Login into KE-chain with either username/password or token. :param basestring username: username for your user from KE-chain :param basestring password: password for your user from KE-chain :param basestring token: user authentication token retrieved from KE-chain Examples ----...
def p_statement_randomize_expr(p): """ statement : RANDOMIZE expr """ p[0] = make_sentence('RANDOMIZE', make_typecast(TYPE.ulong, p[2], p.lineno(1)))
statement : RANDOMIZE expr
def _make_tagdict(self, sentences): '''Make a tag dictionary for single-tag words.''' counts = defaultdict(lambda: defaultdict(int)) for words, tags in sentences: for word, tag in zip(words, tags): counts[word][tag] += 1 self.classes.add(tag) f...
Make a tag dictionary for single-tag words.
def create_feature_vectorizer(input_features, output_feature_name, known_size_map = {}): """ Creates a feature vectorizer from input features, return the spec for a feature vectorizer that puts everything into a single array of length equal to the total size of all the inpu...
Creates a feature vectorizer from input features, return the spec for a feature vectorizer that puts everything into a single array of length equal to the total size of all the input features. Returns a 2-tuple `(spec, num_dimension)` Parameters ---------- input_features: [list of 2-tuples] ...
def get(self, name): """ Return component by category name """ for c in self.comps: if c.category == name: return c return None
Return component by category name
def eclean_pkg(destructive=False, package_names=False, time_limit=0, exclude_file='/etc/eclean/packages.exclude'): ''' Clean obsolete binary packages destructive Only keep minimum for reinstallation package_names Protect all versions of installed packages. Only meaningfu...
Clean obsolete binary packages destructive Only keep minimum for reinstallation package_names Protect all versions of installed packages. Only meaningful if used with destructive=True time_limit <time> Don't delete distfiles files modified since <time> <time> is an...
def __find_star_in_col(self, col): """ Find the first starred element in the specified row. Returns the row index, or -1 if no starred element was found. """ row = -1 for i in range(self.n): if self.marked[i][col] == 1: row = i ...
Find the first starred element in the specified row. Returns the row index, or -1 if no starred element was found.
def __parse_fc_data(fc_data): """Parse the forecast data from the xml section.""" from buienradar.buienradar import condition_from_code fc = [] for daycnt in range(1, 6): daysection = __BRDAYFC % daycnt if daysection in fc_data: tmpsect = fc_data[daysection] fcdat...
Parse the forecast data from the xml section.
def start_aikif(): """ starts the web interface and possibly other processes """ if sys.platform[0:3] == 'win': os.system("start go_web_aikif.bat") else: os.system("../aikif/web_app/web_aikif.py") import webbrowser import time time.sleep(1) webbrowser...
starts the web interface and possibly other processes
def filefind(self, names): """Return first found file matching name (case-insensitive). Some packages have docs/HISTORY.txt and package/name/HISTORY.txt. We make sure we only return the one in the docs directory if no other can be found. 'names' can be a string or a list of st...
Return first found file matching name (case-insensitive). Some packages have docs/HISTORY.txt and package/name/HISTORY.txt. We make sure we only return the one in the docs directory if no other can be found. 'names' can be a string or a list of strings; if you have both a CHAN...
def similarity(ctx, app_id, json_flag, query_pair, request_id): # type: (Context, unicode, bool, List[unicode], unicode) -> None """ Scoring the similarity of two words. """ app_id = clean_app_id(app_id) api = GoolabsAPI(app_id) ret = api.similarity( query_pair=query_pair, request_...
Scoring the similarity of two words.
def split_path(path_): """ Split the requested path into (locale, path). locale will be empty if it isn't found. """ path = path_.lstrip('/') # Use partitition instead of split since it always returns 3 parts first, _, rest = path.partition('/') lang = first.lower() if lang in set...
Split the requested path into (locale, path). locale will be empty if it isn't found.
def reshape_range(tensor, i, j, shape): """Reshapes a tensor between dimensions i and j.""" t_shape = common_layers.shape_list(tensor) target_shape = t_shape[:i] + shape + t_shape[j:] return tf.reshape(tensor, target_shape)
Reshapes a tensor between dimensions i and j.
def cmd_fence_move(self, args): '''handle fencepoint move''' if len(args) < 1: print("Usage: fence move FENCEPOINTNUM") return if not self.have_list: print("Please list fence points first") return idx = int(args[0]) if idx <= 0 or ...
handle fencepoint move
def parses(self, words, S='S'): """Return a list of parses; words can be a list or string. >>> chart = Chart(E_NP_) >>> chart.parses('happy man', 'NP') [[0, 2, 'NP', [('Adj', 'happy'), [1, 2, 'NP', [('N', 'man')], []]], []]] """ if isinstance(words, str): word...
Return a list of parses; words can be a list or string. >>> chart = Chart(E_NP_) >>> chart.parses('happy man', 'NP') [[0, 2, 'NP', [('Adj', 'happy'), [1, 2, 'NP', [('N', 'man')], []]], []]]
def run_step(self): """Write in to out, replacing strings per the replace_pairs.""" formatted_replacements = self.context.get_formatted_iterable( self.replace_pairs) iter = StreamReplacePairsRewriterStep.iter_replace_strings( formatted_replacements) rewriter = St...
Write in to out, replacing strings per the replace_pairs.
def publocus(args): """ %prog publocus idsfile > idsfiles.publocus Given a list of model identifiers, convert each into a GenBank approved pub_locus. Example output: Medtr1g007020.1 MTR_1g007020 Medtr1g007030.1 MTR_1g007030 Medtr1g007060.1 MTR_1g007060A Medtr1g007060.2 MTR_1g00...
%prog publocus idsfile > idsfiles.publocus Given a list of model identifiers, convert each into a GenBank approved pub_locus. Example output: Medtr1g007020.1 MTR_1g007020 Medtr1g007030.1 MTR_1g007030 Medtr1g007060.1 MTR_1g007060A Medtr1g007060.2 MTR_1g007060B
def make_empty(self, axes=None): """ return an empty BlockManager with the items axis of len 0 """ if axes is None: axes = [ensure_index([])] + [ensure_index(a) for a in self.axes[1:]] # preserve dtype if possible if self.ndim == 1: ...
return an empty BlockManager with the items axis of len 0
def ionic_radius(self): """ Ionic radius of specie. Returns None if data is not present. """ if self._oxi_state in self.ionic_radii: return self.ionic_radii[self._oxi_state] d = self._el.data oxstr = str(int(self._oxi_state)) if oxstr in d.get("Ionic ...
Ionic radius of specie. Returns None if data is not present.
def get_language(): """ Wrapper around Django's `get_language` utility. For Django >= 1.8, `get_language` returns None in case no translation is activate. Here we patch this behavior e.g. for back-end functionality requiring access to translated fields """ from parler import appsettings lang...
Wrapper around Django's `get_language` utility. For Django >= 1.8, `get_language` returns None in case no translation is activate. Here we patch this behavior e.g. for back-end functionality requiring access to translated fields
def _determine_profiles(self): """ Determine the WBEM management profiles advertised by the WBEM server, by communicating with it and enumerating the instances of `CIM_RegisteredProfile`. If the profiles could be determined, this method sets the :attr:`profiles` property...
Determine the WBEM management profiles advertised by the WBEM server, by communicating with it and enumerating the instances of `CIM_RegisteredProfile`. If the profiles could be determined, this method sets the :attr:`profiles` property of this object to the list of `CIM_Registe...
def dependencies_satisfied(self, plugin): """ Checks whether a plugin's dependencies are satisfied. Logs an error if there is an unsatisfied dependencies Returns: Bool """ for depends in plugin.dependencies: if depends not in self.config['plugins']: ...
Checks whether a plugin's dependencies are satisfied. Logs an error if there is an unsatisfied dependencies Returns: Bool
def setRGB(self, pixel, r, g, b): """Set single pixel using individual RGB values instead of tuple""" self.set(pixel, (r, g, b))
Set single pixel using individual RGB values instead of tuple
def _run_aws(cmd, region, opts, user, **kwargs): ''' Runs the given command against AWS. cmd Command to run region Region to execute cmd in opts Pass in from salt user Pass in from salt kwargs Key-value arguments to pass to the command ''' # Th...
Runs the given command against AWS. cmd Command to run region Region to execute cmd in opts Pass in from salt user Pass in from salt kwargs Key-value arguments to pass to the command
def israw(self): """ Returns True if the PTY should operate in raw mode. If the container was not started with tty=True, this will return False. """ if self.raw is None: info = self.container_info() self.raw = self.stdout.isatty() and info['Config']['Tty...
Returns True if the PTY should operate in raw mode. If the container was not started with tty=True, this will return False.
def create_search_url(self): """ Generates (urlencoded) query string from stored key-values tuples :returns: A string containing all arguments in a url-encoded format """ url = '?' for key, value in self.arguments.items(): url += '%s=%s&' % (quote_plus(key), quote_p...
Generates (urlencoded) query string from stored key-values tuples :returns: A string containing all arguments in a url-encoded format
def e(self, eid): """Get an Entity """ ta = datetime.datetime.now() rs = self.rest('GET', self.uri_db + '-/entity', data={'e':int(eid)}, parse=True) tb = datetime.datetime.now() - ta print cl('<<< fetched entity %s in %sms' % (eid, tb.microseconds/1000.0), 'cyan') return rs
Get an Entity
def summarize_notices(self, notices_json): """ The function for summarizing RDAP notices in to a unique list. https://tools.ietf.org/html/rfc7483#section-4.3 Args: notices_json (:obj:`dict`): A json mapping of notices from RDAP results. Returns: ...
The function for summarizing RDAP notices in to a unique list. https://tools.ietf.org/html/rfc7483#section-4.3 Args: notices_json (:obj:`dict`): A json mapping of notices from RDAP results. Returns: list of dict: Unique RDAP notices information: ...
def __update_state(self): """Fetches most up to date state from db.""" # Only if the job was not in a terminal state. if self._state.active: self._state = self.__get_state_by_id(self.job_config.job_id)
Fetches most up to date state from db.
def cardinal_groupby(self): """ Group this object on it cardinal dimension (_cardinal). Returns: grpby: Pandas groupby object (grouped on _cardinal) """ g, t = self._cardinal self[g] = self[g].astype(t) grpby = self.groupby(g) self[g] = self[g...
Group this object on it cardinal dimension (_cardinal). Returns: grpby: Pandas groupby object (grouped on _cardinal)
def serialisable(cls, key, obj): '''Determines what can be serialised and what shouldn't ''' # ignore class method names if key.startswith('_Serialisable'.format(cls.__name__)): return False if key in obj.__whitelist: return True # class variables ...
Determines what can be serialised and what shouldn't
def send(self, **kwargs): """Create and send a specific request, and return the response. For example: send(ping=sc_pb.RequestPing()) => sc_pb.ResponsePing Args: **kwargs: A single kwarg with the name and value to fill in to Request. Returns: The Response corresponding to your request. ...
Create and send a specific request, and return the response. For example: send(ping=sc_pb.RequestPing()) => sc_pb.ResponsePing Args: **kwargs: A single kwarg with the name and value to fill in to Request. Returns: The Response corresponding to your request.
def save_dash(self, dashboard_id): """Save a dashboard's metadata""" session = db.session() dash = (session .query(models.Dashboard) .filter_by(id=dashboard_id).first()) check_ownership(dash, raise_if_false=True) data = json.loads(request.form.get(...
Save a dashboard's metadata
def exists(self): """Check if a target exists This function is called by :mod:`luigi` to check if a task output exists. By default, :mod:`luigi` considers a task as complete if all it targets (outputs) exist. Returns: bool: ``True`` if target exists, ``False`` otherwise ...
Check if a target exists This function is called by :mod:`luigi` to check if a task output exists. By default, :mod:`luigi` considers a task as complete if all it targets (outputs) exist. Returns: bool: ``True`` if target exists, ``False`` otherwise
def threshold_monitor_hidden_threshold_monitor_security_policy_area_timebase(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") threshold_monitor_hidden = ET.SubElement(config, "threshold-monitor-hidden", xmlns="urn:brocade.com:mgmt:brocade-threshold-monitor") ...
Auto Generated Code
async def createWorkerType(self, *args, **kwargs): """ Create new Worker Type Create a worker type. A worker type contains all the configuration needed for the provisioner to manage the instances. Each worker type knows which regions and which instance types are allowed for th...
Create new Worker Type Create a worker type. A worker type contains all the configuration needed for the provisioner to manage the instances. Each worker type knows which regions and which instance types are allowed for that worker type. Remember that Capacity is the number of concur...
def update(self, batch_webhook_id, data): """ Update a webhook that will fire whenever any batch request completes processing. :param batch_webhook_id: The unique id for the batch webhook. :type batch_webhook_id: :py:class:`str` :param data: The request body parameters ...
Update a webhook that will fire whenever any batch request completes processing. :param batch_webhook_id: The unique id for the batch webhook. :type batch_webhook_id: :py:class:`str` :param data: The request body parameters :type data: :py:class:`dict` data = { ...
def fresh_working_set(): """return a pkg_resources "working set", representing the *currently* installed packages""" class WorkingSetPlusEditableInstalls(pkg_resources.WorkingSet): def __init__(self, *args, **kwargs): self._normalized_name_mapping = {} super(WorkingSetPlusEditab...
return a pkg_resources "working set", representing the *currently* installed packages
def display_matrix(self, matrix, interval=2.0, brightness=1.0, fading=False, ignore_duplicates=False): """ Displays an LED matrix on Nuimo's LED matrix display. :param matrix: the matrix to display :param interval: interval in seconds until the matrix disappears again :param bri...
Displays an LED matrix on Nuimo's LED matrix display. :param matrix: the matrix to display :param interval: interval in seconds until the matrix disappears again :param brightness: led brightness between 0..1 :param fading: if True, the previous matrix fades into the new matrix ...
def GetTZInfo(tzname='UTC', utcOffset=None, dst=None): """ Get / Add timezone info """ key = (tzname, utcOffset, dst) tzInfo = TZManager._tzInfos.get(key) if not tzInfo: tzInfo = TZInfo(tzname, utcOffset, dst) TZManager._tzInfos[key] = tzInfo return tzInfo
Get / Add timezone info
async def psetex(self, name, time_ms, value): """ Set the value of key ``name`` to ``value`` that expires in ``time_ms`` milliseconds. ``time_ms`` can be represented by an integer or a Python timedelta object """ if isinstance(time_ms, datetime.timedelta): ms ...
Set the value of key ``name`` to ``value`` that expires in ``time_ms`` milliseconds. ``time_ms`` can be represented by an integer or a Python timedelta object
def create(self, size): """ Creates and return a thumbnail of a given size. """ thumbnail = images.create(self.source_image.name, size, self.metadata_backend, self.storage) return thumbnail
Creates and return a thumbnail of a given size.
def remove_entry_listener(self, registration_id): """ Removes the specified entry listener. Returns silently if there is no such listener added before. :param registration_id: (str), id of registered listener. :return: (bool), ``true`` if registration is removed, ``false`` otherwise. ...
Removes the specified entry listener. Returns silently if there is no such listener added before. :param registration_id: (str), id of registered listener. :return: (bool), ``true`` if registration is removed, ``false`` otherwise.
def createZone(self, zone, zoneFile=None, callback=None, errback=None, **kwargs): """ Create a new zone, and return an associated high level Zone object. Several optional keyword arguments are available to configure the SOA record. If zoneFile is specified, up...
Create a new zone, and return an associated high level Zone object. Several optional keyword arguments are available to configure the SOA record. If zoneFile is specified, upload the specific zone definition file to populate the zone with. :param str zone: zone name, like 'exam...
def dimensionNames(self): """ Returns a list with the dimension names of the underlying NCDF variable """ nSubDims = len(self._subArrayShape) subArrayDims = ['SubDim{}'.format(dimNr) for dimNr in range(nSubDims)] return list(self._ncVar.dimensions + tuple(subArrayDims))
Returns a list with the dimension names of the underlying NCDF variable
def random_str(Nchars=6, randstrbase='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'): """Return a random string of <Nchars> characters. Characters are sampled uniformly from <randstrbase>. """ return ''.join([randstrbase[random.randint(0, len(randstrbase) - 1)] for i in range(Nchars)])
Return a random string of <Nchars> characters. Characters are sampled uniformly from <randstrbase>.
def create_lazy_user(self): """ Create a lazy user. Returns a 2-tuple of the underlying User object (which may be of a custom class), and the username. """ user_class = self.model.get_user_class() username = self.generate_username(user_class) user = user_class.objects.cre...
Create a lazy user. Returns a 2-tuple of the underlying User object (which may be of a custom class), and the username.
def listify(*args): """ Convert args to a list, unless there's one arg and it's a function, then acts a decorator. """ if (len(args) == 1) and callable(args[0]): func = args[0] @wraps(func) def _inner(*args, **kwargs): return list(func(*args, **kwargs)) r...
Convert args to a list, unless there's one arg and it's a function, then acts a decorator.
def _create_window_function(name, doc=''): """ Create a window function by name """ def _(): sc = SparkContext._active_spark_context jc = getattr(sc._jvm.functions, name)() return Column(jc) _.__name__ = name _.__doc__ = 'Window function: ' + doc return _
Create a window function by name
def timeseries(self): """ Time series of storage operation Parameters ---------- ts : :pandas:`pandas.DataFrame<dataframe>` DataFrame containing active power the storage is charged (negative) and discharged (positive) with (on the grid side) in kW in colu...
Time series of storage operation Parameters ---------- ts : :pandas:`pandas.DataFrame<dataframe>` DataFrame containing active power the storage is charged (negative) and discharged (positive) with (on the grid side) in kW in column 'p' and reactive power in ...
def publish_scene_name(self, scene_id, name): """publish a changed scene name""" self.sequence_number += 1 self.publisher.send_multipart(msgs.MessageBuilder.scene_name(self.sequence_number, scene_id, name)) return self.sequence_number
publish a changed scene name
def camelify(self): """turn a string to CamelCase, omitting non-word characters""" outstring = self.titleify(allwords=True) outstring = re.sub(r"&[^;]+;", " ", outstring) outstring = re.sub(r"\W+", "", outstring) return String(outstring)
turn a string to CamelCase, omitting non-word characters
def open(filename, frame='unspecified'): """Create a Direction from data saved in a file. Parameters ---------- filename : :obj:`str` The file to load data from. frame : :obj:`str` The frame to apply to the created Direction. Returns ---...
Create a Direction from data saved in a file. Parameters ---------- filename : :obj:`str` The file to load data from. frame : :obj:`str` The frame to apply to the created Direction. Returns ------- :obj:`Direction` A Directio...
def update_process_behavior(self, behavior_data, process_id, behavior_ref_name): """UpdateProcessBehavior. [Preview API] Replaces a behavior in the process. :param :class:`<ProcessBehaviorUpdateRequest> <azure.devops.v5_0.work_item_tracking_process.models.ProcessBehaviorUpdateRequest>` behavior_...
UpdateProcessBehavior. [Preview API] Replaces a behavior in the process. :param :class:`<ProcessBehaviorUpdateRequest> <azure.devops.v5_0.work_item_tracking_process.models.ProcessBehaviorUpdateRequest>` behavior_data: :param str process_id: The ID of the process :param str behavior_ref_n...
def batch_delete_intents(self, parent, intents, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ ...
Deletes intents in the specified agent. Operation <response: ``google.protobuf.Empty``> Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.IntentsClient() >>> >>> parent = client.project_agent_path('[PROJECT]') >>> ...
def list_local(): ''' List the locally installed overlays. Return a list of installed overlays: CLI Example: .. code-block:: bash salt '*' layman.list_local ''' cmd = 'layman --quietness=1 --list-local --nocolor' out = __salt__['cmd.run'](cmd, python_shell=False).split('\n') ...
List the locally installed overlays. Return a list of installed overlays: CLI Example: .. code-block:: bash salt '*' layman.list_local
def volumes(self): """This property prepares the list of volumes :return a list of volumes. """ return sys_volumes.VolumeCollection( self._conn, utils.get_subresource_path_by(self, 'Volumes'), redfish_version=self.redfish_version)
This property prepares the list of volumes :return a list of volumes.
def where(self, **kwargs): """Return a new Dataset refined using the given condition :param kwargs: a map of `dimension` => `condition` to filter the elements of the dataset. `condition` can either be an exact value or a callable returning a boolean value. If `condition` is a va...
Return a new Dataset refined using the given condition :param kwargs: a map of `dimension` => `condition` to filter the elements of the dataset. `condition` can either be an exact value or a callable returning a boolean value. If `condition` is a value, it is converted to a ...
def createEditor(self, parent, option, index): """Create editor widget""" model = index.model() value = model.get_value(index) if model._data.dtype.name == "bool": value = not value model.setData(index, to_qvariant(value)) return elif v...
Create editor widget
def from_pycbc(cls, pycbcseries, copy=True): """Convert a `pycbc.types.timeseries.TimeSeries` into a `TimeSeries` Parameters ---------- pycbcseries : `pycbc.types.timeseries.TimeSeries` the input PyCBC `~pycbc.types.timeseries.TimeSeries` array copy : `bool`, option...
Convert a `pycbc.types.timeseries.TimeSeries` into a `TimeSeries` Parameters ---------- pycbcseries : `pycbc.types.timeseries.TimeSeries` the input PyCBC `~pycbc.types.timeseries.TimeSeries` array copy : `bool`, optional, default: `True` if `True`, copy these da...
def proc_check_guard(self, instance, sql): """ check to see if the guard SQL returns a single column containing 0 or 1 We return true if 1, else False """ self.open_db_connections(instance, self.PROC_GUARD_DB_KEY) cursor = self.get_cursor(instance, self.PROC_GUARD_DB_KEY)...
check to see if the guard SQL returns a single column containing 0 or 1 We return true if 1, else False
def fire_event(self, event_name, service_name, default=None): """ Fire a data_ready, data_lost, start, or stop event on a given service. """ service = self.get_service(service_name) callbacks = service.get(event_name, default) if not callbacks: return ...
Fire a data_ready, data_lost, start, or stop event on a given service.
def parent(self): """ Parent of current object :rtype: Collection """ parent = list(self.graph.objects(self.asNode(), RDF_NAMESPACES.DTS.parent)) if parent: return self.parent_class(parent[0]) return None
Parent of current object :rtype: Collection
def update_usage_plan(plan_id, throttle=None, quota=None, region=None, key=None, keyid=None, profile=None): ''' Updates an existing usage plan with throttling and quotas .. versionadded:: 2017.7.0 plan_id Id of the created usage plan throttle A dictionary consisting of the followi...
Updates an existing usage plan with throttling and quotas .. versionadded:: 2017.7.0 plan_id Id of the created usage plan throttle A dictionary consisting of the following keys: rateLimit requests per second at steady rate, float burstLimit maximu...
def update(self, obj, size): '''Update this profile. ''' self.number += 1 self.total += size if self.high < size: # largest self.high = size try: # prefer using weak ref self.objref, self.weak = Weakref.ref(obj), True except Type...
Update this profile.
def interfaces(root): ''' Generate a dictionary with all available interfaces relative to root. Symlinks are not followed. CLI example: .. code-block:: bash salt '*' sysfs.interfaces block/bcache0/bcache Output example: .. code-block:: json { "r": [ ...
Generate a dictionary with all available interfaces relative to root. Symlinks are not followed. CLI example: .. code-block:: bash salt '*' sysfs.interfaces block/bcache0/bcache Output example: .. code-block:: json { "r": [ "state", "partial_str...
def smoothMLS1D(actor, f=0.2, showNLines=0): """ Smooth actor or points with a `Moving Least Squares` variant. The list ``actor.info['variances']`` contain the residue calculated for each point. Input actor's polydata is modified. :param float f: smoothing factor - typical range is [0,2]. :para...
Smooth actor or points with a `Moving Least Squares` variant. The list ``actor.info['variances']`` contain the residue calculated for each point. Input actor's polydata is modified. :param float f: smoothing factor - typical range is [0,2]. :param int showNLines: build an actor showing the fitting line...
def create_database(): """ creates database if necessary """ db = get_db() response = db.query('SHOW DATABASES') items = list(response.get_points('databases')) databases = [database['name'] for database in items] # if database does not exists, create it if settings.INFLUXDB_DATABASE not in d...
creates database if necessary
def evaluate_model(filepath, train_start=0, train_end=60000, test_start=0, test_end=10000, batch_size=128, testing=False, num_threads=None): """ Run evaluation on a saved model :param filepath: path to model to evaluate :param train_start: index of first ...
Run evaluation on a saved model :param filepath: path to model to evaluate :param train_start: index of first training set example :param train_end: index of last training set example :param test_start: index of first test set example :param test_end: index of last test set example :param batch_size: size o...
def epubcheck_help(): """Return epubcheck.jar commandline help text. :return unicode: helptext from epubcheck.jar """ # tc = locale.getdefaultlocale()[1] with open(os.devnull, "w") as devnull: p = subprocess.Popen( [c.JAVA, '-Duser.language=en', '-jar', c.EPUBCHECK, '-h'], ...
Return epubcheck.jar commandline help text. :return unicode: helptext from epubcheck.jar
def restore(name, run_path=None, replace=False, root="."): """ Downloads the specified file from cloud storage into the current run directory if it doesn exist. name: the name of the file run_path: optional path to a different run to pull files from replace: whether to download the file even if it ...
Downloads the specified file from cloud storage into the current run directory if it doesn exist. name: the name of the file run_path: optional path to a different run to pull files from replace: whether to download the file even if it already exists locally root: the directory to download the file...
def random_split(self, weights): """ Random split imageframes according to weights :param weights: weights for each ImageFrame :return: """ jvalues = self.image_frame.random_split(weights) return [ImageFrame(jvalue) for jvalue in jvalues]
Random split imageframes according to weights :param weights: weights for each ImageFrame :return:
def _match_errors_queues(self, query): """Tries to match in error queues :param query: message tuple :type query: Tuple[bytes] :return: response if found or None :rtype: Tuple[bytes] | None """ if query in self._error_queues: queue = self._error_queue...
Tries to match in error queues :param query: message tuple :type query: Tuple[bytes] :return: response if found or None :rtype: Tuple[bytes] | None
def env(*_vars, **kwargs): """Search for the first defined of possibly many env vars. Returns the first environment variable defined in vars, or returns the default defined in kwargs. """ for v in _vars: value = os.environ.get(v, None) if value: return value return ...
Search for the first defined of possibly many env vars. Returns the first environment variable defined in vars, or returns the default defined in kwargs.
def set_blocks(self, list=None, dict=None, fill_air=False): """ Sets all blocks in this chunk, using either a list or dictionary. Blocks not explicitly set can be filled to air by setting fill_air to True. """ if list: # Inputting a list like self.blocksList ...
Sets all blocks in this chunk, using either a list or dictionary. Blocks not explicitly set can be filled to air by setting fill_air to True.
def visitPrefixDecl(self, ctx: ShExDocParser.PrefixDeclContext): """ prefixDecl: KW_PREFIX PNAME_NS IRIREF """ iri = self.context.iriref_to_shexj_iriref(ctx.IRIREF()) prefix = ctx.PNAME_NS().getText() if iri not in self.context.ld_prefixes: self.context.prefixes.setdefault(pr...
prefixDecl: KW_PREFIX PNAME_NS IRIREF
def get_methods(self): """ Returns a list of `MethodClassAnalysis` objects """ for c in self.classes.values(): for m in c.get_methods(): yield m
Returns a list of `MethodClassAnalysis` objects
def convert(self, input_path=None, output_path=None, markup=None, break_lines=False, divide_works=False, latin=False, extra_args=None): """ :param input_path: TLG filepath to convert. :param output_path: filepath of new converted text. :param markup: Speci...
:param input_path: TLG filepath to convert. :param output_path: filepath of new converted text. :param markup: Specificity of inline markup. Default None removes all numerical markup; 'full' gives most detailed, with reference numbers included before each text line. :param break_...
def _validate_rule(self, rule): # type: (Type[Rule]) -> None """ Validate rule. Valid rule must inherit from Rule and have valid syntax. :param rule: Rule to validate. :raise NotRuleException: If the parameter doesn't inherit from Rule. """ if not inspect.isclass(...
Validate rule. Valid rule must inherit from Rule and have valid syntax. :param rule: Rule to validate. :raise NotRuleException: If the parameter doesn't inherit from Rule.
def read_stream(stream, output, prebuffer, chunk_size=8192): """Reads data from stream and then writes it to the output.""" is_player = isinstance(output, PlayerOutput) is_http = isinstance(output, HTTPServer) is_fifo = is_player and output.namedpipe show_progress = isinstance(output, FileOutput) an...
Reads data from stream and then writes it to the output.
def finalise_same_chip_constraints(substitutions, placements): """Given a set of placements containing the supplied :py:class:`MergedVertex`, remove the merged vertices replacing them with their constituent vertices (changing the placements inplace). """ for merged_vertex in reversed(substitutions):...
Given a set of placements containing the supplied :py:class:`MergedVertex`, remove the merged vertices replacing them with their constituent vertices (changing the placements inplace).
def load_secrets(self, secret_path): """render secrets into config object""" self._config = p_config.render_secrets(self.config_path, secret_path)
render secrets into config object
def clear(self, *resource_types): """Clear cache for each provided APIResource class, or all resources if no classes are provided""" resource_types = resource_types or tuple(self.__caches.keys()) for cls in resource_types: # Clear and delete cache instances to guarantee no lingering...
Clear cache for each provided APIResource class, or all resources if no classes are provided
def _get_fault_type_dummy_variables(self, rup): """ Fault type (Strike-slip, Normal, Thrust/reverse) is derived from rake angle. Rakes angles within 30 of horizontal are strike-slip, angles from 30 to 150 are reverse, and angles from -30 to -150 are normal. Note t...
Fault type (Strike-slip, Normal, Thrust/reverse) is derived from rake angle. Rakes angles within 30 of horizontal are strike-slip, angles from 30 to 150 are reverse, and angles from -30 to -150 are normal. Note that the 'Unspecified' case is not considered, because rake i...
def parse_cidr (addr, infer=True, allow_host=False): """ Takes a CIDR address or plain dotted-quad, and returns a tuple of address and count-of-network-bits. Can infer the network bits based on network classes if infer=True. Can also take a string in the form 'address/netmask', as long as the netmask is rep...
Takes a CIDR address or plain dotted-quad, and returns a tuple of address and count-of-network-bits. Can infer the network bits based on network classes if infer=True. Can also take a string in the form 'address/netmask', as long as the netmask is representable in CIDR. FIXME: This function is badly named.
def compute_loss_curves_maps(filename, builder, rlzi, monitor): """ :param filename: path to the datastore :param builder: LossCurvesMapsBuilder instance :param rlzi: realization index :param monitor: Monitor instance :returns: rlzi, (curves, maps) """ with datastore.read(filename) as ds...
:param filename: path to the datastore :param builder: LossCurvesMapsBuilder instance :param rlzi: realization index :param monitor: Monitor instance :returns: rlzi, (curves, maps)
def Focus(self): """Brings the client window into focus. """ self._Skype._Api.allow_focus(self._Skype.Timeout) self._Skype._DoCommand('FOCUS')
Brings the client window into focus.
def get_client(self, request=None): """Return the client from the OAuth parameters.""" if not isinstance(request, oauth.Request): request = self.get_oauth_request() client_key = request.get_parameter('oauth_consumer_key') if not client_key: raise Exception('Missi...
Return the client from the OAuth parameters.
def compat_kwargs(kwargs): """To keep backwards compat change the kwargs to new names""" warn_deprecations(kwargs) for old, new in RENAMED_VARS.items(): if old in kwargs: kwargs[new] = kwargs[old] # update cross references for c_old, c_new in RENAMED_VARS.items():...
To keep backwards compat change the kwargs to new names
def plot_predict(self, h=5, past_values=20, intervals=True,**kwargs): """ Plots forecast with the estimated model Parameters ---------- h : int (default : 5) How many steps ahead would you like to forecast? past_values : int (default : 20) ...
Plots forecast with the estimated model Parameters ---------- h : int (default : 5) How many steps ahead would you like to forecast? past_values : int (default : 20) How many past observations to show on the forecast graph? inter...
def docx_process_table(table: DOCX_TABLE_TYPE, config: TextProcessingConfig) -> str: """ Converts a DOCX table to text. Structure representing a DOCX table: .. code-block:: none table .rows[] .cells[] .paragraphs[] ...
Converts a DOCX table to text. Structure representing a DOCX table: .. code-block:: none table .rows[] .cells[] .paragraphs[] .text That's the structure of a :class:`docx.table.Table` object, but also of our homebrew cre...