positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def unicode_escape_sequence_fix(self, value): """ It is possible to define unicode characters in the config either as the actual utf-8 character or using escape sequences the following all will show the Greek delta character. Δ \N{GREEK CAPITAL LETTER DELTA} \U00000394 \u0394 ...
It is possible to define unicode characters in the config either as the actual utf-8 character or using escape sequences the following all will show the Greek delta character. Δ \N{GREEK CAPITAL LETTER DELTA} \U00000394 \u0394
def _from_binary_idx_root(cls, binary_stream): """See base class.""" ''' Attribute type - 4 Collation rule - 4 Bytes per index record - 4 Clusters per index record - 1 Padding - 3 ''' attr_type, collation_rule, b_per_idx_r, c_per_idx_r = cls._REPR.unpack(binary_stream[:cl...
See base class.
def write_content(self, content, destination): """ Write given content to destination path. It will create needed directory structure first if it contain some directories that does not allready exists. Args: content (str): Content to write to target file. ...
Write given content to destination path. It will create needed directory structure first if it contain some directories that does not allready exists. Args: content (str): Content to write to target file. destination (str): Destination path for target file. Ret...
def create_sitemap(app, exception): """Generates the sitemap.xml from the collected HTML page links""" if (not app.config['html_theme_options'].get('base_url', '') or exception is not None or not app.sitemap_links): return filename = app.outdir + "/sitemap.xml" print("Gene...
Generates the sitemap.xml from the collected HTML page links
def any2unicode(text, encoding='utf8', errors='strict'): """Convert a string (bytestring in `encoding` or unicode), to unicode.""" if isinstance(text, unicode): return text return unicode(text, encoding, errors=errors)
Convert a string (bytestring in `encoding` or unicode), to unicode.
def _scan(self, type): """ Returns the matched text, and moves to the next token """ tok = self._scanner.token(self._pos, frozenset([type])) if tok[2] != type: err = SyntaxError("SyntaxError[@ char %s: %s]" % (repr(tok[0]), "Trying to find " + type)) err.p...
Returns the matched text, and moves to the next token
def plot_state_histogram(result: trial_result.TrialResult) -> np.ndarray: """Plot the state histogram from a single result with repetitions. States is a bitstring representation of all the qubit states in a single result. Currently this function assumes each measurement gate applies to only a singl...
Plot the state histogram from a single result with repetitions. States is a bitstring representation of all the qubit states in a single result. Currently this function assumes each measurement gate applies to only a single qubit. Args: result: The trial results to plot. Returns: ...
def block_quote(node): """ A block quote """ o = nodes.block_quote() o.line = node.sourcepos[0][0] for n in MarkDown(node): o += n return o
A block quote
def get(self): """Reloads the check with its current values.""" new = self.manager.get(self) if new: self._add_details(new._info)
Reloads the check with its current values.
def get_degenerate_statements(self): """Get all degenerate BEL statements. Stores the results of the query in self.degenerate_stmts. """ logger.info("Checking for 'degenerate' statements...\n") # Get rules of type protein X -> activity Y q_stmts = prefixes + """ ...
Get all degenerate BEL statements. Stores the results of the query in self.degenerate_stmts.
def get_entry_url(entry, blog_page, root_page): """ Get the entry url given and entry page a blog page instances. It will use an url or another depending if blog_page is the root page. """ if root_page == blog_page: return reverse('entry_page_serve', kwargs={ 'year': entry.date.s...
Get the entry url given and entry page a blog page instances. It will use an url or another depending if blog_page is the root page.
def run(self): """ Append version number to vegas/__init__.py """ with open('src/vegas/__init__.py', 'a') as vfile: vfile.write("\n__version__ = '%s'\n" % VEGAS_VERSION) _build_py.run(self)
Append version number to vegas/__init__.py
def _preallocate_samples(self): """Preallocate samples for faster adaptive sampling. """ self.prealloc_samples_ = [] for i in range(self.num_prealloc_samples_): self.prealloc_samples_.append(self.sample())
Preallocate samples for faster adaptive sampling.
def OnTextColor(self, event): """Text color choice event handler""" color = event.GetValue().GetRGB() post_command_event(self, self.TextColorMsg, color=color)
Text color choice event handler
def stats_list(self, list=None, date=None, headers=None): """ Retrieve information about your subscriber counts on a particular list, on a particular day. http://docs.sailthru.com/api/stat """ data = {'stat': 'list'} if list is not None: data['list'] = list ...
Retrieve information about your subscriber counts on a particular list, on a particular day. http://docs.sailthru.com/api/stat
def identify_filepath(arg, real_path=None, show_directory=None, find_source=None, hide_init=None): """Discover and return the disk file path of the Python module named in `arg` by importing the module and returning its ``__file__`` attribute. If `find_source` is `True`, the named module is a ``pyc`` or...
Discover and return the disk file path of the Python module named in `arg` by importing the module and returning its ``__file__`` attribute. If `find_source` is `True`, the named module is a ``pyc`` or ``pyo`` file, and a corresponding ``.py`` file exists on disk, the path to the ``.py`` file is return...
def _kput(url, data): ''' put any object in kubernetes based on URL ''' # Prepare headers headers = {"Content-Type": "application/json"} # Make request ret = http.query(url, method='PUT', header_dict=headers, data=salt.utils.json.dumps(...
put any object in kubernetes based on URL
def enabled(name, runas=None): ''' Check if the specified service is enabled :param str name: The name of the service to look up :param str runas: User to run launchctl commands :return: True if the specified service enabled, otherwise False :rtype: bool CLI Example: .. code-block::...
Check if the specified service is enabled :param str name: The name of the service to look up :param str runas: User to run launchctl commands :return: True if the specified service enabled, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' service.enabled org...
def build_route_timetable( feed: "Feed", route_id: str, dates: List[str] ) -> DataFrame: """ Return a timetable for the given route and dates. Parameters ---------- feed : Feed route_id : string ID of a route in ``feed.routes`` dates : string or list A YYYYMMDD date stri...
Return a timetable for the given route and dates. Parameters ---------- feed : Feed route_id : string ID of a route in ``feed.routes`` dates : string or list A YYYYMMDD date string or list thereof Returns ------- DataFrame The columns are all those in ``feed.tri...
def setup_db(session, botconfig, confdir): """Sets up the database.""" Base.metadata.create_all(session.connection()) # If we're creating a fresh db, we don't need to worry about migrations. if not session.get_bind().has_table('alembic_version'): conf_obj = config.Config() conf_obj.set_m...
Sets up the database.
def extend_with_default(validator_class: Any) -> Any: """Append defaults from schema to instance need to be validated. :param validator_class: Apply the change for given validator class. """ validate_properties = validator_class.VALIDATORS['properties'] def set_defaults(validator: Any, ...
Append defaults from schema to instance need to be validated. :param validator_class: Apply the change for given validator class.
def _adjust_bin_edges(datetime_bins, offset, closed, index, labels): """This is required for determining the bin edges resampling with daily frequencies greater than one day, month end, and year end frequencies. Consider the following example. Let's say you want to downsample the time series with ...
This is required for determining the bin edges resampling with daily frequencies greater than one day, month end, and year end frequencies. Consider the following example. Let's say you want to downsample the time series with the following coordinates to month end frequency: CFTimeIndex([2000-01-...
def mark_job_as_errored(job_id, error_object): """Mark a job as failed with an error. :param job_id: the job_id of the job to be updated :type job_id: unicode :param error_object: the error returned by the job :type error_object: either a string or a dict with a "message" key whose value i...
Mark a job as failed with an error. :param job_id: the job_id of the job to be updated :type job_id: unicode :param error_object: the error returned by the job :type error_object: either a string or a dict with a "message" key whose value is a string
def _session(self): """Provide a transactional scope around a series of operations.""" # Taken from the session docs. session = self._session_maker() try: yield session session.commit() except: session.rollback() raise final...
Provide a transactional scope around a series of operations.
def is_serializable(obj): """Return `True` if the given object conforms to the Serializable protocol. :rtype: bool """ if inspect.isclass(obj): return Serializable.is_serializable_type(obj) return isinstance(obj, Serializable) or hasattr(obj, '_asdict')
Return `True` if the given object conforms to the Serializable protocol. :rtype: bool
def update(self, **kwargs): """We need to implement the custom exclusive parameter check.""" self._check_exclusive_parameters(**kwargs) return super(Rule, self)._update(**kwargs)
We need to implement the custom exclusive parameter check.
def verify(self, public_pair, val, sig): """ :param: public_pair: a :class:`Point <pycoin.ecdsa.Point.Point>` on the curve :param: val: an integer value :param: sig: a pair of integers ``(r, s)`` representing an ecdsa signature :returns: True if and only if the signature ``sig``...
:param: public_pair: a :class:`Point <pycoin.ecdsa.Point.Point>` on the curve :param: val: an integer value :param: sig: a pair of integers ``(r, s)`` representing an ecdsa signature :returns: True if and only if the signature ``sig`` is a valid signature of ``val`` using ``public_p...
def file_content(self, value): """The Base64 encoded content of the attachment :param value: The Base64 encoded content of the attachment :type value: FileContent, string """ if isinstance(value, FileContent): self._file_content = value else: self...
The Base64 encoded content of the attachment :param value: The Base64 encoded content of the attachment :type value: FileContent, string
def _add_recent(self, doc, logged_id): "Keep a tab on the most recent message for each channel" spec = dict(channel=doc['channel']) doc['ref'] = logged_id doc.pop('_id') self._recent.replace_one(spec, doc, upsert=True)
Keep a tab on the most recent message for each channel
def copytree(src, dst, symlinks=False, ignore=None): """ Function recursively copies from directory to directory. Args ---- src (string): the full path of source directory dst (string): the full path of destination directory symlinks (boolean): the switch for tracking symlinks ignore (l...
Function recursively copies from directory to directory. Args ---- src (string): the full path of source directory dst (string): the full path of destination directory symlinks (boolean): the switch for tracking symlinks ignore (list): the ignore list
def update_host(self, url: URL) -> None: """Update destination host, port and connection type (ssl).""" # get host/port if not url.host: raise InvalidURL(url) # basic auth info username, password = url.user, url.password if username: self.auth = h...
Update destination host, port and connection type (ssl).
def _unicode(ctx, text): """ Returns a numeric code for the first character in a text string """ text = conversions.to_string(text, ctx) if len(text) == 0: raise ValueError("Text can't be empty") return ord(text[0])
Returns a numeric code for the first character in a text string
def get_html(url, headers=None, timeout=None, errors="strict", wait_time=None, driver=None, zillow_only=False, cache_only=False, zillow_first=False, cache_first=False, random=False, ...
Use Google Cached Url. :param cache_only: if True, then real zillow site will never be used. :param driver: selenium browser driver。
def update_flags(self, idlist, flags): """ A thin back compat wrapper around build_update(flags=X) """ return self.update_bugs(idlist, self.build_update(flags=flags))
A thin back compat wrapper around build_update(flags=X)
def on_message(self, message): """Listens for a "websocket client ready" message. Once that message is received an asynchronous job is stated that yields messages to the client. These messages make up salt's "real time" event stream. """ log.debug('Got websocket m...
Listens for a "websocket client ready" message. Once that message is received an asynchronous job is stated that yields messages to the client. These messages make up salt's "real time" event stream.
def get_all_subdomains(self, offset=None, count=None, min_sequence=None, cur=None): """ Get and all subdomain names, optionally over a range """ get_cmd = 'SELECT DISTINCT fully_qualified_subdomain FROM {}'.format(self.subdomain_table) args = () if min_sequence is not No...
Get and all subdomain names, optionally over a range
def available_dtypes(): """Return the set of data types available in this implementation. Notes ----- This is all dtypes available in Numpy. See ``numpy.sctypes`` for more information. The available dtypes may depend on the specific system used. """ all_...
Return the set of data types available in this implementation. Notes ----- This is all dtypes available in Numpy. See ``numpy.sctypes`` for more information. The available dtypes may depend on the specific system used.
def valid_hotp( token, secret, last=1, trials=1000, digest_method=hashlib.sha1, token_length=6, ): """Check if given token is valid for given secret. Return interval number that was successful, or False if not found. :param token: token being checked :typ...
Check if given token is valid for given secret. Return interval number that was successful, or False if not found. :param token: token being checked :type token: int or str :param secret: secret for which token is checked :type secret: str :param last: last used interval (start checking with ne...
def create_configuration(self, node, ports): """Create RAID configuration on the bare metal. This method creates the desired RAID configuration as read from node['target_raid_config']. :param node: A dictionary of the node object :param ports: A list of dictionaries containing ...
Create RAID configuration on the bare metal. This method creates the desired RAID configuration as read from node['target_raid_config']. :param node: A dictionary of the node object :param ports: A list of dictionaries containing information of ports for the node :r...
def get_display(self): """ returns information about the display, including brightness, screensaver etc. """ log.debug("getting display information...") cmd, url = DEVICE_URLS["get_display"] return self._exec(cmd, url)
returns information about the display, including brightness, screensaver etc.
def get_groups(self, **kwargs): """Obtain line types and details. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[GeoGroupItem]), or message string in case of error. """ # Endpoint parameters ...
Obtain line types and details. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[GeoGroupItem]), or message string in case of error.
def _get_range(self, endpoint, *args, method='GET', **kwargs): """ Helper that returns another range""" if args: url = self.build_url(self._endpoints.get(endpoint).format(*args)) else: url = self.build_url(self._endpoints.get(endpoint)) if not kwargs: ...
Helper that returns another range
def destroy(self, stream=False): """ Run a 'terraform destroy' :param stream: whether or not to stream TF output in realtime :type stream: bool """ self._setup_tf(stream=stream) args = ['-refresh=true', '-force', '.'] logger.warning('Running terraform des...
Run a 'terraform destroy' :param stream: whether or not to stream TF output in realtime :type stream: bool
def _cache_index(self, dbname, collection, index, cache_for): """Add an index to the index cache for ensure_index operations.""" now = datetime.datetime.utcnow() expire = datetime.timedelta(seconds=cache_for) + now with self.__index_cache_lock: if dbname not in self.__index_...
Add an index to the index cache for ensure_index operations.
def score(self, periods=None): """Compute the periodogram for the given period or periods Parameters ---------- periods : float or array_like Array of periods at which to compute the periodogram. Returns ------- scores : np.ndarray Array ...
Compute the periodogram for the given period or periods Parameters ---------- periods : float or array_like Array of periods at which to compute the periodogram. Returns ------- scores : np.ndarray Array of normalized powers (between 0 and 1) for...
def main(prog: str = None, subcommand_overrides: Dict[str, Subcommand] = {}) -> None: """ The :mod:`~allennlp.run` command only knows about the registered classes in the ``allennlp`` codebase. In particular, once you start creating your own ``Model`` s and so forth, it won't work for them, unle...
The :mod:`~allennlp.run` command only knows about the registered classes in the ``allennlp`` codebase. In particular, once you start creating your own ``Model`` s and so forth, it won't work for them, unless you use the ``--include-package`` flag.
def handle_nested_relation(self, line: str, position: int, tokens: ParseResults): """Handle nested statements. If :code:`allow_nested` is False, raises a ``NestedRelationWarning``. :raises: NestedRelationWarning """ if not self.allow_nested: raise NestedRelationWarn...
Handle nested statements. If :code:`allow_nested` is False, raises a ``NestedRelationWarning``. :raises: NestedRelationWarning
def _findSegment(self, x): ''' :param x: x value to place in segment defined by the xData (instantiation) :return: The lower index in the segment ''' iLeft = 0 iRight = len(self.xData) - 1 while True: if iRight - iLeft <= 1: return iLef...
:param x: x value to place in segment defined by the xData (instantiation) :return: The lower index in the segment
def do_types_conflict(type1: GraphQLOutputType, type2: GraphQLOutputType) -> bool: """Check whether two types conflict Two types conflict if both types could not apply to a value simultaneously. Composite types are ignored as their individual field types will be compared later recursively. However List...
Check whether two types conflict Two types conflict if both types could not apply to a value simultaneously. Composite types are ignored as their individual field types will be compared later recursively. However List and Non-Null types must match.
def update(self, dict): """Set all field values from a dictionary. For any key in `dict` that is also a field to store tags the method retrieves the corresponding value from `dict` and updates the `MediaFile`. If a key has the value `None`, the corresponding property is deleted ...
Set all field values from a dictionary. For any key in `dict` that is also a field to store tags the method retrieves the corresponding value from `dict` and updates the `MediaFile`. If a key has the value `None`, the corresponding property is deleted from the `MediaFile`.
def parse_csr(): """ Parse certificate signing request for domains """ LOGGER.info("Parsing CSR...") cmd = [ 'openssl', 'req', '-in', os.path.join(gettempdir(), 'domain.csr'), '-noout', '-text' ] devnull = open(os.devnull, 'wb') out = subprocess.check_outp...
Parse certificate signing request for domains
def OnDestroy(self, event): """Called on panel destruction.""" # deregister observers if hasattr(self, 'cardmonitor'): self.cardmonitor.deleteObserver(self.cardtreecardobserver) if hasattr(self, 'readermonitor'): self.readermonitor.deleteObserver(self.readertreere...
Called on panel destruction.
def get_user(self, user_id, expand=False): """Returns Hacker News `User` object. Fetches data from the url: https://hacker-news.firebaseio.com/v0/user/<user_id>.json e.g. https://hacker-news.firebaseio.com/v0/user/pg.json Args: user_id (string): unique user id ...
Returns Hacker News `User` object. Fetches data from the url: https://hacker-news.firebaseio.com/v0/user/<user_id>.json e.g. https://hacker-news.firebaseio.com/v0/user/pg.json Args: user_id (string): unique user id of a Hacker News user. expand (bool): Flag...
def gprmc_to_degdec(lat, latDirn, lng, lngDirn): """Converts GPRMC formats (Decimal Minutes) to Degrees Decimal.""" x = float(lat[0:2]) + float(lat[2:]) / 60 y = float(lng[0:3]) + float(lng[3:]) / 60 if latDirn == 'S': x = -x if lngDirn == 'W': y = -y return x, y
Converts GPRMC formats (Decimal Minutes) to Degrees Decimal.
def import_from_json(self, data): """ Replace the current roster with the :meth:`export_as_json`-compatible dictionary in `data`. No events are fired during this activity. After this method completes, the whole roster contents are exchanged with the contents from `data`. ...
Replace the current roster with the :meth:`export_as_json`-compatible dictionary in `data`. No events are fired during this activity. After this method completes, the whole roster contents are exchanged with the contents from `data`. Also, no data is transferred to the server; this met...
def create_process(daemon, name, callback, *callbackParams): """创建进程 :param daemon: True主进程关闭而关闭, False主进程必须等待子进程结束 :param name: 进程名称 :param callback: 回调函数 :param callbackParams: 回调函数参数 :return: 返回一个进程对象 """ bp = Process(daemon=daemon, name=name, target=callback, args=callbackParams) ...
创建进程 :param daemon: True主进程关闭而关闭, False主进程必须等待子进程结束 :param name: 进程名称 :param callback: 回调函数 :param callbackParams: 回调函数参数 :return: 返回一个进程对象
def encode_dict(data, encoding=None, errors='strict', keep=False, preserve_dict_class=False, preserve_tuples=False): ''' Encode all string values to bytes ''' rv = data.__class__() if preserve_dict_class else {} for key, value in six.iteritems(data): if isinstance(key, tuple)...
Encode all string values to bytes
def _get_configs_path(): """Get a list of possible configuration files, from the following sources: 1. All files that exists in constants.CONFS_PATH. 2. All XDG standard config files for "lago.conf", in reversed order of importance. Returns: list(str): list of files """ paths...
Get a list of possible configuration files, from the following sources: 1. All files that exists in constants.CONFS_PATH. 2. All XDG standard config files for "lago.conf", in reversed order of importance. Returns: list(str): list of files
def pad_with_fill_value(self, pad_widths=None, fill_value=dtypes.NA, **pad_widths_kwargs): """ Return a new Variable with paddings. Parameters ---------- pad_width: Mapping of the form {dim: (before, after)} Number of values padded to the ...
Return a new Variable with paddings. Parameters ---------- pad_width: Mapping of the form {dim: (before, after)} Number of values padded to the edges of each dimension. **pad_widths_kwargs: Keyword argument for pad_widths
def list_contacts(self, **kwargs): """ List all contacts, optionally filtered by a query. Specify filters as query keyword argument, such as: query= email is abc@xyz.com, query= mobile is 1234567890, query= phone is 1234567890, contacts can be filtered ...
List all contacts, optionally filtered by a query. Specify filters as query keyword argument, such as: query= email is abc@xyz.com, query= mobile is 1234567890, query= phone is 1234567890, contacts can be filtered by name such as; letter=Prenit ...
def org_find_projects(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /org-xxxx/findProjects API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Organizations#API-method%3A-%2Forg-xxxx%2FfindProjects """ return DXHTTPRequest('/%s/findProjects...
Invokes the /org-xxxx/findProjects API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Organizations#API-method%3A-%2Forg-xxxx%2FfindProjects
def copy_data(self, project, logstore, from_time, to_time=None, to_client=None, to_project=None, to_logstore=None, shard_list=None, batch_size=None, compress=None, new_topic=None, new_source=None): """ copy data from one logstore to another one ...
copy data from one logstore to another one (could be the same or in different region), the time is log received time on server side. :type project: string :param project: project name :type logstore: string :param logstore: logstore name :type from_time: string/int ...
def hash(buf, encoding="utf-8"): """ Compute the fuzzy hash of a buffer :param String|Bytes buf: The data to be fuzzy hashed :return: The fuzzy hash :rtype: String :raises InternalError: If lib returns an internal error :raises TypeError: If buf is not String or Bytes """ if isins...
Compute the fuzzy hash of a buffer :param String|Bytes buf: The data to be fuzzy hashed :return: The fuzzy hash :rtype: String :raises InternalError: If lib returns an internal error :raises TypeError: If buf is not String or Bytes
def printImportedNames(self): """Produce a report of imported names.""" for module in self.listModules(): print("%s:" % module.modname) print(" %s" % "\n ".join(imp.name for imp in module.imported_names))
Produce a report of imported names.
def setup_logger(): # type: () -> logging.Logger """Setup the root logger. Return the logger instance for possible further setting and use. To be used from CLI scripts only. """ formatter = logging.Formatter( fmt='%(levelname)s - %(module)s - %(message)s') handler = logging.StreamHandler(...
Setup the root logger. Return the logger instance for possible further setting and use. To be used from CLI scripts only.
def get_content(request, page_id, content_id): """Get the content for a particular page""" content = Content.objects.get(pk=content_id) return HttpResponse(content.body)
Get the content for a particular page
def fprint(self, file, indent): """ Print contents of directory to open stream """ return lib.zdir_fprint(self._as_parameter_, coerce_py_file(file), indent)
Print contents of directory to open stream
def reset(): """ Unmount and remove the sqlite database (used in robot reset) """ if os.path.exists(database_path): os.remove(database_path) # Not an os.path.join because it is a suffix to the full filename journal_path = database_path + '-journal' if os.path.exists(journal_path): os...
Unmount and remove the sqlite database (used in robot reset)
def _is_qrs(self, peak_num, backsearch=False): """ Check whether a peak is a qrs complex. It is classified as qrs if it: - Comes after the refractory period - Passes qrs threshold - Is not a t-wave (check it if the peak is close to the previous qrs). Pa...
Check whether a peak is a qrs complex. It is classified as qrs if it: - Comes after the refractory period - Passes qrs threshold - Is not a t-wave (check it if the peak is close to the previous qrs). Parameters ---------- peak_num : int The ...
def _chunk_actions(actions, chunk_size, max_chunk_bytes, serializer): """ Split actions into chunks by number or size, serialize them into strings in the process. """ bulk_actions = [] size, action_count = 0, 0 for action, data in actions: action = serializer.dumps(action) cu...
Split actions into chunks by number or size, serialize them into strings in the process.
def forward(self, x, boxes): """ Arguments: x (tuple[tensor, tensor]): x contains the class logits and the box_regression from the model. boxes (list[BoxList]): bounding boxes that are used as reference, one for ech image Returns: ...
Arguments: x (tuple[tensor, tensor]): x contains the class logits and the box_regression from the model. boxes (list[BoxList]): bounding boxes that are used as reference, one for ech image Returns: results (list[BoxList]): one BoxList for each...
def name(self): # pylint: disable=no-self-use """ Name returns user's name or user's email or user_id :return: best guess of name to use to greet user """ if 'lis_person_sourcedid' in self.session: return self.session['lis_person_sourcedid'] elif 'lis_person_...
Name returns user's name or user's email or user_id :return: best guess of name to use to greet user
def exists(self, path_or_index): """ Checks if a path exists in the document. This is meant to be used for a corresponding :meth:`~couchbase.subdocument.exists` request. :param path_or_index: The path (or index) to check :return: `True` if the path exists, `False` if the path do...
Checks if a path exists in the document. This is meant to be used for a corresponding :meth:`~couchbase.subdocument.exists` request. :param path_or_index: The path (or index) to check :return: `True` if the path exists, `False` if the path does not exist :raise: An exception if the serv...
async def open(self) -> 'HolderProver': """ Explicit entry. Perform ancestor opening operations, then parse cache from archive if so configured, and synchronize revocation registry to tails tree content. :return: current object """ LOGGER.debug('HolderProver.ope...
Explicit entry. Perform ancestor opening operations, then parse cache from archive if so configured, and synchronize revocation registry to tails tree content. :return: current object
def insert(self, document): """ Insert a new document into the table. :param document: the document to insert :returns: the inserted document's ID """ doc_id = self._get_doc_id(document) data = self._read() data[doc_id] = dict(document) self._wri...
Insert a new document into the table. :param document: the document to insert :returns: the inserted document's ID
def create_symlinks(d): """Create new symbolic links in output directory.""" data = loadJson(d) outDir = prepare_output(d) unseen = data["pages"].keys() while len(unseen) > 0: latest = work = unseen[0] while work in unseen: unseen.remove(work) if "prev" in da...
Create new symbolic links in output directory.
def filter_paths(pathnames, patterns=None, ignore_patterns=None): """Filters from a set of paths based on acceptable patterns and ignorable patterns.""" result = [] if patterns is None: patterns = ['*'] if ignore_patterns is None: ignore_patterns = [] for pathname in pathnames: ...
Filters from a set of paths based on acceptable patterns and ignorable patterns.
def check_contract_allowed(func): """Check if Contract is allowed by token """ @wraps(func) def decorator(*args, **kwargs): contract = kwargs.get('contract') if (contract and current_user.is_authenticated() and not current_user.allowed(contract)): return curre...
Check if Contract is allowed by token
def start(self, stdout=subprocess.PIPE, stderr=subprocess.PIPE): """ Merged copy paste from the inheritance chain with modified stdout/err behaviour """ if self.pre_start_check(): # Some other executor (or process) is running with same config: raise AlreadyRunning(self) ...
Merged copy paste from the inheritance chain with modified stdout/err behaviour
def get_type_of_fields(fields, table): """ Return data types of `fields` that are in `table`. If a given parameter is empty return primary key. :param fields: list - list of fields that need to be returned :param table: sa.Table - the current table :return: list - list o...
Return data types of `fields` that are in `table`. If a given parameter is empty return primary key. :param fields: list - list of fields that need to be returned :param table: sa.Table - the current table :return: list - list of the tuples `(field_name, fields_type)`
def Description(self): """Returns searchable data as Description""" descr = " ".join((self.getId(), self.aq_parent.Title())) return safe_unicode(descr).encode('utf-8')
Returns searchable data as Description
def selectnone(table, field, complement=False): """Select rows where the given field is `None`.""" return select(table, field, lambda v: v is None, complement=complement)
Select rows where the given field is `None`.
def __process_sentence(sentence_tuple, counts): """pull the actual sentence from the tuple (tuple contains additional data such as ID) :param _sentence_tuple: :param counts: """ sentence = sentence_tuple[2] # now we start replacing words one type at a time... sentence = __replace_verbs(sen...
pull the actual sentence from the tuple (tuple contains additional data such as ID) :param _sentence_tuple: :param counts:
def list(self): """ :rtype: list(setting_name, value, default_value, is_set, is_supported) """ settings = [] for setting in _SETTINGS: value = self.get(setting) is_set = self.is_set(setting) default_value = self.get_default_value(setting) ...
:rtype: list(setting_name, value, default_value, is_set, is_supported)
def remove(mode_id: str) -> bool: """ Removes the specified mode identifier from the active modes and returns whether or not a remove operation was carried out. If the mode identifier is not in the currently active modes, it does need to be removed. """ had_mode = has(mode_id) if had_mode:...
Removes the specified mode identifier from the active modes and returns whether or not a remove operation was carried out. If the mode identifier is not in the currently active modes, it does need to be removed.
def combineblocks(blks, imgsz, stpsz=None, fn=np.median): """Combine blocks from an ndarray to reconstruct ndarray signal. Parameters ---------- blks : ndarray nd array of blocks of a signal imgsz : tuple tuple of the signal size stpsz : tuple, optional (default None, corresponds to...
Combine blocks from an ndarray to reconstruct ndarray signal. Parameters ---------- blks : ndarray nd array of blocks of a signal imgsz : tuple tuple of the signal size stpsz : tuple, optional (default None, corresponds to steps of 1) tuple of step sizes between neighboring blocks...
def softmax_average_pooling_class_label_top(body_output, targets, model_hparams, vocab_size): """Loss for class label.""" del targets # unused arg with tf.variable_scope( "sof...
Loss for class label.
def namespace_map(self, target): """Returns the namespace_map used for Thrift generation. :param target: The target to extract the namespace_map from. :type target: :class:`pants.backend.codegen.targets.java_thrift_library.JavaThriftLibrary` :returns: The namespaces to remap (old to new). :rtype: d...
Returns the namespace_map used for Thrift generation. :param target: The target to extract the namespace_map from. :type target: :class:`pants.backend.codegen.targets.java_thrift_library.JavaThriftLibrary` :returns: The namespaces to remap (old to new). :rtype: dictionary
def element_height_should_be(self, locator, expected): """Verifies the element identified by `locator` has the expected height. Expected height should be in pixels. | *Argument* | *Description* | *Example* | | locator | Selenium 2 element locator | id=my_id | | expected | expected height | 600 |""" self._...
Verifies the element identified by `locator` has the expected height. Expected height should be in pixels. | *Argument* | *Description* | *Example* | | locator | Selenium 2 element locator | id=my_id | | expected | expected height | 600 |
def _next(self, request, application, roles, next_config): """ Continue the state machine at given state. """ # we only support state changes for POST requests if request.method == "POST": key = None # If next state is a transition, process it while True: ...
Continue the state machine at given state.
def category_helper(form_tag=True): """ Category's form layout helper """ helper = FormHelper() helper.form_action = '.' helper.attrs = {'data_abide': ''} helper.form_tag = form_tag helper.layout = Layout( Row( Column( 'title', css...
Category's form layout helper
def password_length_needed(entropybits: Union[int, float], chars: str) -> int: """Calculate the length of a password for a given entropy and chars.""" if not isinstance(entropybits, (int, float)): raise TypeError('entropybits can only be int or float') if entropybits < 0: raise ValueError('e...
Calculate the length of a password for a given entropy and chars.
def list(self, **kwds): """ Endpoint: /albums/list.json Returns a list of Album objects. """ albums = self._client.get("/albums/list.json", **kwds)["result"] albums = self._result_to_list(albums) return [Album(self._client, album) for album in albums]
Endpoint: /albums/list.json Returns a list of Album objects.
def do_list_modules(self, long_output=None,sort_order=None): """Display a list of loaded modules. Config items: - shutit.list_modules['long'] If set, also print each module's run order value - shutit.list_modules['sort'] Select the column by which the list is ordered: - id: sort the list by mo...
Display a list of loaded modules. Config items: - shutit.list_modules['long'] If set, also print each module's run order value - shutit.list_modules['sort'] Select the column by which the list is ordered: - id: sort the list by module id - run_order: sort the list by module run order The ...
def _on_rpc_done(self, future): """Triggered whenever the underlying RPC terminates without recovery. This is typically triggered from one of two threads: the background consumer thread (when calling ``recv()`` produces a non-recoverable error) or the grpc management thread (when cancel...
Triggered whenever the underlying RPC terminates without recovery. This is typically triggered from one of two threads: the background consumer thread (when calling ``recv()`` produces a non-recoverable error) or the grpc management thread (when cancelling the RPC). This method is *non...
def _create_adapter_type(network_adapter, adapter_type, network_adapter_label=''): ''' Returns a vim.vm.device.VirtualEthernetCard object specifying a virtual ethernet card information network_adapter None or VirtualEthernet object adapter_type String, type...
Returns a vim.vm.device.VirtualEthernetCard object specifying a virtual ethernet card information network_adapter None or VirtualEthernet object adapter_type String, type of adapter network_adapter_label string, network adapter name
def run(self): """Process the work unit, or wait for sentinel to exit""" while True: self.running = True workunit = self._workq.get() if is_sentinel(workunit): # Got sentinel break # Run the job / sequence worku...
Process the work unit, or wait for sentinel to exit
def onSiliconCheckList(ra_deg, dec_deg, FovObj, padding_pix=DEFAULT_PADDING): """Check a list of positions.""" dist = angSepVincenty(FovObj.ra0_deg, FovObj.dec0_deg, ra_deg, dec_deg) mask = (dist < 90.) out = np.zeros(len(dist), dtype=bool) out[mask] = FovObj.isOnSiliconList(ra_deg[mask], dec_deg[ma...
Check a list of positions.
def set_bin_window(self, bin_size=None, window_size=None): """Set the bin and window sizes.""" bin_size = bin_size or self.bin_size window_size = window_size or self.window_size assert 1e-6 < bin_size < 1e3 assert 1e-6 < window_size < 1e3 assert bin_size < window_size ...
Set the bin and window sizes.
def join(cls, diffs: Iterable['DBDiff']) -> 'DBDiff': """ Join several DBDiff objects into a single DBDiff object. In case of a conflict, changes in diffs that come later in ``diffs`` will overwrite changes from earlier changes. """ tracker = DBDiffTracker() for ...
Join several DBDiff objects into a single DBDiff object. In case of a conflict, changes in diffs that come later in ``diffs`` will overwrite changes from earlier changes.