text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def strict_dependencies(self, dep_context):
"""
:param dep_context: A DependencyContext with configuration for the request.
:return: targets that this target "strictly" depends on. This set of dependencies contains
only directly declared dependencies, with two exceptions:
1) aliases are expand... | 0.010505 |
def kill_process(self):
"""Stop the process"""
if self.process.poll() is not None:
return
try:
if hasattr(self.process, 'terminate'):
self.process.terminate()
elif os.name != 'nt':
os.kill(self.process.pid, 9)
else:
... | 0.003929 |
def search(query, stats):
""" Perform issue search for given stats instance """
log.debug("Search query: {0}".format(query))
issues = []
# Fetch data from the server in batches of MAX_RESULTS issues
for batch in range(MAX_BATCHES):
response = stats.parent.session.get(... | 0.001815 |
def change_exteditor(self):
"""Change external editor path"""
path, valid = QInputDialog.getText(self, _('External editor'),
_('External editor executable path:'),
QLineEdit.Normal,
self.get_option('external_editor/path')... | 0.007229 |
def add(self, *args, **kwargs):
"""Add the instance tied to the field for the given "value" (via `args`) to the index
For the parameters, see ``BaseIndex.add``
"""
check_uniqueness = kwargs.get('check_uniqueness', True)
key = self.get_storage_key(*args)
if self.field.... | 0.004405 |
def execute_get(self, resource, **kwargs):
"""
Execute an HTTP GET request against the API endpoints.
This method is meant for internal use.
:param resource: The last part of the URI
:param kwargs: Additional query parameters (and optionally headers)
:return: The HTTP re... | 0.002621 |
def bind_type(python_value):
"""Return a Gibica type derived from a Python type."""
binding_table = {'bool': Bool, 'int': Int, 'float': Float}
if python_value is None:
return NoneType()
python_type = type(python_value)
gibica_type = binding_table.get(python_type.__name__)
if gibica_t... | 0.002288 |
def setInputFormatText( self, text ):
"""
Sets the input format text for this widget to the given value.
:param text | <str>
"""
try:
self._inputFormat = XLineEdit.InputFormat[nativestring(text)]
except KeyError:
pass | 0.016502 |
def _print_unique_links_with_status_codes(page_url, soup):
""" Finds all unique links in the html of the page source
and then prints out those links with their status codes.
Format: ["link" -> "status_code"] (per line)
Page links include those obtained from:
"a"->"href", "img"->"... | 0.001887 |
def chain_split(*splits: Iterable[Callable[..., Any]]) -> Callable[[BaseChain], Iterable[BaseChain]]: # noqa: E501
"""
Construct and execute multiple concurrent forks of the chain.
Any number of forks may be executed. For each fork, provide an iterable of
commands.
Returns the resulting chain o... | 0.002887 |
def split(self):
"""
Split the graph into sub-graphs. Only connected objects belong to the
same graph. `split` yields copies of the Graph object. Shallow copies
are used that only replicate the meta-information, but share the same
object list ``self.objects``.
>>> from p... | 0.001914 |
def copy_snapshot(kwargs=None, call=None):
'''
Copy a snapshot
'''
if call != 'function':
log.error(
'The copy_snapshot function must be called with -f or --function.'
)
return False
if 'source_region' not in kwargs:
log.error('A source_region must be spe... | 0.000847 |
def get_ip_interface_input_request_type_get_request_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
input = ET.SubElement(get_ip_interface, "input")
... | 0.004559 |
def set_table(self, schema, **kwargs):
"""
add the table to the db
schema -- Schema() -- contains all the information about the table
"""
with self.connection(**kwargs) as connection:
kwargs['connection'] = connection
if self.has_table(str(schema), **kwar... | 0.003784 |
def resolve_url(self, catalog_url):
"""Resolve the url of the dataset when reading latest.xml.
Parameters
----------
catalog_url : str
The catalog url to be resolved
"""
if catalog_url != '':
resolver_base = catalog_url.split('catalog.xml')[0]
... | 0.001599 |
def embed_ising(source_h, source_J, embedding, target_adjacency, chain_strength=1.0):
"""Embed an Ising problem onto a target graph.
Args:
source_h (dict[variable, bias]/list[bias]):
Linear biases of the Ising problem. If a list, the list's indices are used as
variable labels.
... | 0.004586 |
def trajectory(self,
horizon: int,
initial_state: Optional[StateTensor] = None) -> TrajectoryOutput:
'''Returns the ops for the trajectory generation with given `horizon`
and `initial_state`.
The simulation returns states, actions and interms as a
sequence of ten... | 0.004535 |
def show_raslog_output_show_all_raslog_raslog_entries_index(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_raslog = ET.Element("show_raslog")
config = show_raslog
output = ET.SubElement(show_raslog, "output")
show_all_raslog = ET.Su... | 0.003247 |
def old_roles_manager(self):
'''Return old roles, grouped first by term, then by chamber,
then by type.'''
wrapper = self._old_role_wrapper
chamber_getter = operator.methodcaller('get', 'chamber')
for term, roles in self.get('old_roles', {}).items():
chamber_roles = d... | 0.002928 |
def gen_min(cachedir, extra_mods='', overwrite=False, so_mods='',
python2_bin='python2', python3_bin='python3'):
'''
Generate the salt-min tarball and print the location of the tarball
Optional additional mods to include (e.g. mako) can be supplied as a comma
delimited string. Permits forci... | 0.002147 |
def _calculate_conversion(hdr):
"""Calculate the conversion factor.
Returns
-------
conv_factor : numpy.ndarray
channel-long vector with the channel-specific conversion factor
Notes
-----
Final units are microvolts
It should include all the headbox versions apart from 5 becaus... | 0.00091 |
def display_assignment_changes(plan_details, to_log=True):
"""Display current and proposed changes in
topic-partition to replica layout over brokers.
"""
curr_plan_list, new_plan_list, total_changes = plan_details
action_cnt = '\n[INFO] Total actions required {0}'.format(total_changes)
_log_or_d... | 0.001075 |
def _read_color_image(self):
""" Reads a color image from the device """
# read raw buffer
im_arr = self._color_stream.read_frame()
raw_buf = im_arr.get_buffer_as_triplet()
r_array = np.array([raw_buf[i][0] for i in range(PrimesenseSensor.COLOR_IM_WIDTH * PrimesenseSensor.COLOR_I... | 0.010338 |
def plotly(
data: typing.Union[dict, list] = None,
layout: dict = None,
scale: float = 0.5,
figure: dict = None,
static: bool = False
):
"""
Creates a Plotly plot in the display with the specified data and
layout.
:param data:
The Plotly trace data to be ... | 0.000676 |
def CreateMenuBar(self):
"""Create our menu-bar for triggering operations"""
menubar = wx.MenuBar()
menu = wx.Menu()
menu.Append(ID_OPEN, _('&Open Profile'), _('Open a cProfile file'))
menu.Append(ID_OPEN_MEMORY, _('Open &Memory'), _('Open a Meliae memory-dump file'))
men... | 0.003698 |
def post_flag_list(self, creator_id=None, creator_name=None, post_id=None,
reason_matches=None, is_resolved=None, category=None):
"""Function to flag a post (Requires login).
Parameters:
creator_id (int): The user id of the flag's creator.
creator_name (st... | 0.004608 |
def get_available_user_FIELD_transitions(instance, user, field):
"""
List of transitions available in current model state
with all conditions met and user have rights on it
"""
for transition in get_available_FIELD_transitions(instance, field):
if transition.has_perm(instance, user):
... | 0.002933 |
def save(self, filename_or_handle):
'''Save the state of this network to a pickle file on disk.
Parameters
----------
filename_or_handle : str or file handle
Save the state of this network to a pickle file. If this parameter
is a string, it names the file where t... | 0.004061 |
def netconf_config_change_edit_operation(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
netconf_config_change = ET.SubElement(config, "netconf-config-change", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-notifications")
edit = ET.SubElement(netconf_c... | 0.005618 |
def interface(self):
"""
Public method for handling service command argument.
"""
# Possible control arguments
controls = {
'start': self.do_start,
'stop': self.do_stop,
'status': self.do_status,
'restart': self.do_restart,... | 0.009804 |
def _handle_response(self, response):
"""Internal helper for handling API responses from the Coinbase server.
Raises the appropriate exceptions when necessary; otherwise, returns the
response.
"""
if not str(response.status_code).startswith('2'):
raise build_api_erro... | 0.008451 |
def _get_team_results(self, away_name, away_abbr, away_score, home_name,
home_abbr, home_score):
"""
Determine the winner and loser of the game.
If the game has been completed and sports-reference has been updated
with the score, determine the winner and loser ... | 0.001856 |
def _process_bulk_chunk(client, bulk_actions, raise_on_exception=True, raise_on_error=True, **kwargs):
"""
Send a bulk request to elasticsearch and process the output.
"""
# if raise on error is set, we need to collect errors per chunk before raising them
errors = []
try:
# send the act... | 0.003082 |
def percentage(self):
"""Returns the progress as a percentage."""
if self.currval >= self.maxval:
return 100.0
return self.currval * 100.0 / self.maxval | 0.010638 |
def _get_source_snapshots(self, snapshot, fallback_self=False):
"""
Get list of source snapshot names of given snapshot
TODO: we have to decide by description at the moment
"""
if not snapshot:
return []
source_snapshots = re.findall(r"'([\w\d\.-]+)'", snaps... | 0.005941 |
def complete_tree(self, text, line, begidx, endidx):
"""completion for ls command"""
options = self.TREE_OPTS
if not text:
completions = options
else:
completions = [f
for f in options
if f.startswith(text)
... | 0.005348 |
def check_entry(self, entries, *args, **kwargs):
"""
With a list of entries, check each entry against every other
"""
verbosity = kwargs.get('verbosity', 1)
user_total_overlaps = 0
user = ''
for index_a, entry_a in enumerate(entries):
# Show the name t... | 0.001656 |
def validar(self, id_vlan):
"""Validates ACL - IPv4 of VLAN from its identifier.
Assigns 1 to 'acl_valida'.
:param id_vlan: Identifier of the Vlan. Integer value and greater than zero.
:return: None
:raise InvalidParameterError: Vlan identifier is null and invalid.
:r... | 0.003509 |
def _AddInitMethod(message_descriptor, cls):
"""Adds an __init__ method to cls."""
def _GetIntegerEnumValue(enum_type, value):
"""Convert a string or integer enum value to an integer.
If the value is a string, it is converted to the enum value in
enum_type with the same name. If the value is not a st... | 0.008793 |
def create_submission(self, token, **kwargs):
"""
Associate a result item with a particular scalar value.
:param token: A valid token for the user in question.
:type token: string
:param uuid (optional) The uuid of the submission (must be unique)
:type uuid: string
... | 0.002577 |
def privtohex(key):
'''
Used for getting unknown input type into a private key.
For example, if you ask a user to input a private key, and they
may input hex, WIF, integer, etc. Run it through this function to
get a standardized format.
Function either outputs private key hex string or raises ... | 0.004181 |
def custom_build_class_rule(self, opname, i, token, tokens, customize):
'''
# Should the first rule be somehow folded into the 2nd one?
build_class ::= LOAD_BUILD_CLASS mkfunc
LOAD_CLASSNAME {expr}^n-1 CALL_FUNCTION_n
LOAD_CONST CALL_FUNCTION_n
... | 0.004587 |
def __view_remove_actions(self):
"""
Removes the View actions.
"""
trace_modules_action = "Actions|Umbra|Components|addons.trace_ui|Trace Module(s)"
untrace_modules_action = "Actions|Umbra|Components|addons.trace_ui|Untrace Module(s)"
for action in (trace_modules_action... | 0.00998 |
def add_kb_mapping(kb_name, key, value=""):
"""Add a new mapping to given kb.
:param kb_name: the name of the kb where to insert the new value
:param key: the key of the mapping
:param value: the value of the mapping
"""
kb = get_kb_by_name(kb_name)
if key in kb.kbrvals:
# update
... | 0.002217 |
def format_and_annualise(self, raw_cov_array):
"""
Helper method which annualises the output of shrinkage calculations,
and formats the result into a dataframe
:param raw_cov_array: raw covariance matrix of daily returns
:type raw_cov_array: np.ndarray
:return: annualise... | 0.005703 |
def get_user_log(self, language='da'):
"""Get the controller state"""
payload = """<getUserLog1 xmlns="utcs" />
<getUserLog2 xmlns="utcs">0</getUserLog2>
<getUserLog3 xmlns="utcs">{language}</getUserLog3>
""".format(language=language)
... | 0.00266 |
def requires_swimlane_version(min_version=None, max_version=None):
"""Decorator for SwimlaneResolver methods verifying Swimlane server build version is within a given inclusive range
Raises:
InvalidVersion: Raised before decorated method call if Swimlane server version is out of provided range
... | 0.008076 |
def OnUpdate(self, event):
"""Updates the toolbar states"""
attributes = event.attr
self._update_buttoncell(attributes["button_cell"])
self.Refresh()
event.Skip() | 0.009709 |
def _accumulate(data_list, no_concat=()):
"""Concatenate a list of dicts `(name, array)`.
You can specify some names which arrays should not be concatenated.
This is necessary with lists of plots with different sizes.
"""
acc = Accumulator()
for data in data_list:
for name, val in data... | 0.001431 |
def _load_type_counts(self):
"""Load the table of frequency counts of word forms."""
rel_path = os.path.join(CLTK_DATA_DIR,
'old_english',
'model',
'old_english_models_cltk',
'data... | 0.023102 |
def create(self, data):
"""
Add a new store to your MailChimp account.
Error checking on the currency code verifies that it is in the correct
three-letter, all-caps format as specified by ISO 4217 but does not
check that it is a valid code as the list of valid codes changes over... | 0.002235 |
def nextClass(self, classuri):
"""Returns the next class in the list of classes. If it's the last one, returns the first one."""
if classuri == self.classes[-1].uri:
return self.classes[0]
flag = False
for x in self.classes:
if flag == True:
return... | 0.009901 |
def longitude(self):
"""
This method gets a dict of routes listed in Daft.
:return:
"""
try:
scripts = self._ad_page_content.find_all('script')
for script in scripts:
if 'longitude' in script.text:
find_list = re.findall... | 0.002861 |
def str_rstrip(x, to_strip=None):
"""Remove trailing characters from a string sample.
:param str to_strip: The string to be removed
:returns: an expression containing the modified string column.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>... | 0.003 |
def remove(self, email):
"""Remove a Collaborator.
Args:
str : Collaborator email address.
"""
if email in self._collaborators:
if self._collaborators[email] == ShareRequestValue.Add:
del self._collaborators[email]
else:
... | 0.004975 |
def ICM(input_dim, num_outputs, kernel, W_rank=1,W=None,kappa=None,name='ICM'):
"""
Builds a kernel for an Intrinsic Coregionalization Model
:input_dim: Input dimensionality (does not include dimension of indices)
:num_outputs: Number of outputs
:param kernel: kernel that will be multiplied by the ... | 0.013699 |
def verify_integrity(self, session=None):
"""
Verifies the DagRun by checking for removed tasks or tasks that are not in the
database yet. It will set state to removed or add the task if required.
"""
from airflow.models.taskinstance import TaskInstance # Avoid circular import
... | 0.001926 |
def hardware_connector_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:brocade-hardware")
connector = ET.SubElement(hardware, "connector")
name = ET.SubElement(connecto... | 0.006522 |
def get_file_versions(self, secure_data_path, limit=None, offset=None):
"""
Get versions of a particular file
This is just a shim to get_secret_versions
secure_data_path -- full path to the file in the safety deposit box
limit -- Default(100), limits how many records to be retur... | 0.00759 |
async def parse_form(self, req: Request, name: str, field: Field) -> typing.Any:
"""Pull a form value from the request."""
post_data = self._cache.get("post")
if post_data is None:
self._cache["post"] = await req.post()
return core.get_value(self._cache["post"], name, field) | 0.009404 |
def autocorr_coeff(x, t, tau1, tau2):
"""Calculate the autocorrelation coefficient."""
return corr_coeff(x, x, t, tau1, tau2) | 0.007407 |
def clone_to_path(https_authenticated_url, folder, branch_or_commit=None):
"""Clone the given URL to the folder.
:param str branch_or_commit: If specified, switch to this branch. Branch must exist.
"""
_LOGGER.info("Cloning repo")
repo = Repo.clone_from(https_authenticated_url, str(folder))
# D... | 0.004942 |
def mouseMoveEvent(self, event):
"""
Detect mouser over indicator and highlight the current scope in the
editor (up and down decoration arround the foldable text when the mouse
is over an indicator).
:param event: event
"""
super(FoldingPanel, self).mouseMoveEven... | 0.001132 |
def options(self, url: StrOrURL, *, allow_redirects: bool=True,
**kwargs: Any) -> '_RequestContextManager':
"""Perform HTTP OPTIONS request."""
return _RequestContextManager(
self._request(hdrs.METH_OPTIONS, url,
allow_redirects=allow_redirects,
... | 0.014205 |
def atleast_1d(*arrs):
r"""Convert inputs to arrays with at least one dimension.
Scalars are converted to 1-dimensional arrays, whilst other
higher-dimensional inputs are preserved. This is a thin wrapper
around `numpy.atleast_1d` to preserve units.
Parameters
----------
arrs : arbitrary p... | 0.003171 |
def get_common_course_modes(self, course_run_ids):
"""
Find common course modes for a set of course runs.
This function essentially returns an intersection of types of seats available
for each course run.
Arguments:
course_run_ids(Iterable[str]): Target Course run I... | 0.003127 |
def blastnprep(self):
"""Setup blastn analyses"""
# Populate threads for each gene, genome combination
for sample in self.metadata:
if sample.general.bestassemblyfile != 'NA':
#
# sample[self.analysistype].alleleresults = GenObject()
sa... | 0.002712 |
def AppMoVCopeland(profile, alpha=0.5):
"""
Returns an integer that is equal to the margin of victory of the election profile, that is,
the smallest number k such that changing k votes can change the winners.
:ivar Profile profile: A Profile object that represents an election profile.
"""
# Cu... | 0.003898 |
def pformat_xml(xml):
"""Return pretty formatted XML."""
try:
from lxml import etree # delayed import
if not isinstance(xml, bytes):
xml = xml.encode('utf-8')
xml = etree.parse(io.BytesIO(xml))
xml = etree.tostring(xml, pretty_print=True, xml_declaration=True,
... | 0.001709 |
def hset(self, hashroot, key, value):
""" hashed set """
hroot = self.root / hashroot
if not hroot.isdir():
hroot.makedirs()
hfile = hroot / gethashfile(key)
d = self.get(hfile, {})
d.update( {key : value})
self[hfile] = d | 0.013793 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'tones') and self.tones is not None:
_dict['tones'] = [x._to_dict() for x in self.tones]
if hasattr(self, 'category_id') and self.category_id is not None:
_dict... | 0.003929 |
def teardown(self):
'''
Clean up the target once all tests are completed
'''
if self.controller:
self.controller.teardown()
for monitor in self.monitors:
monitor.teardown() | 0.008475 |
def _set_relay(self, v, load=False):
"""
Setter method for relay, mapped from YANG variable /rbridge_id/maps/relay (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_relay is considered as a private
method. Backends looking to populate this variable should
do... | 0.003827 |
def truncate(self, before=None, after=None, axis=None, copy=True):
"""
Truncate a Series or DataFrame before and after some index value.
This is a useful shorthand for boolean indexing based on index
values above or below certain thresholds.
Parameters
----------
... | 0.00041 |
def stats(self, columns):
"""Compute the stats for each column provided in columns.
Parameters
----------
columns : list of str, contains all columns to compute stats on.
"""
assert (not isinstance(columns, basestring)), "columns should be a " \
... | 0.002466 |
def _remove_hdxobject(self, objlist, obj, matchon='id', delete=False):
# type: (List[Union[HDXObjectUpperBound,Dict]], Union[HDXObjectUpperBound,Dict,str], str, bool) -> bool
"""Remove an HDX object from a list within the parent HDX object
Args:
objlist (List[Union[T <= HDXObject,Di... | 0.003698 |
def validate_count_api(rule_payload, endpoint):
"""
Ensures that the counts api is set correctly in a payload.
"""
rule = (rule_payload if isinstance(rule_payload, dict)
else json.loads(rule_payload))
bucket = rule.get('bucket')
counts = set(endpoint.split("/")) & {"counts.json"}
... | 0.001587 |
def property_cache_once_per_frame(f):
""" This decorator caches the return value for one game loop, then clears it if it is accessed in a different game loop
Only works on properties of the bot object because it requires access to self.state.game_loop """
f.frame = -1
f.cache = None
@wraps(f)
d... | 0.005376 |
def _check_bad_exception_context(self, node):
"""Verify that the exception context is properly set.
An exception context can be only `None` or an exception.
"""
cause = utils.safe_infer(node.cause)
if cause in (astroid.Uninferable, None):
return
if isinstanc... | 0.004724 |
def delete(self, item):
"""Deletes the specified item."""
uri = "/%s/%s" % (self.uri_base, utils.get_id(item))
return self._delete(uri) | 0.012579 |
def to_data(self, value):
'''
Coerce python data type to simple form for serialization.
If default value was defined returns the default value if None was passed.
Throw exception is value is ``None`` is ``required`` is set to ``True``
'''
try:
if value is None... | 0.005025 |
def write_lammps_inputs(output_dir, script_template, settings=None,
data=None, script_filename="in.lammps",
make_dir_if_not_present=True, **kwargs):
"""
Writes input files for a LAMMPS run. Input script is constructed
from a str template with placeholders to b... | 0.000528 |
def __copyfile(source, destination):
"""Copy data and mode bits ("cp source destination").
The destination may be a directory.
Args:
source (str): Source file (file to copy).
destination (str): Destination file or directory (where to copy).
Returns:
bool: True if the operation... | 0.00146 |
async def get_non_secret(
self,
typ: str,
filt: Union[dict, str] = None,
canon_wql: Callable[[dict], dict] = None,
limit: int = None) -> dict:
"""
Return dict mapping each non-secret storage record of interest by identifier or,
for no f... | 0.00385 |
def _make_embedded_from(self, doc):
'''Creates embedded navigators from a HAL response doc'''
ld = utils.CurieDict(self._core.default_curie, {})
for rel, doc in doc.get('_embedded', {}).items():
if isinstance(doc, list):
ld[rel] = [self._recursively_embed(d) for d in ... | 0.004819 |
def _format_command(name, envvars, base=None):
''' Creates a list-table directive
for a set of defined environment variables
Parameters:
name (str):
The name of the config section
envvars (dict):
A dictionary of the environment variable definitions from the config
... | 0.002086 |
def init_input_obj(self):
"""Section 4 - Create uwg objects from input parameters
self.simTime # simulation time parameter obj
self.weather # weather obj for simulation time period
self.forcIP # Forcing obj
self.forc ... | 0.0045 |
def label_field(self, f):
"""
Select one field as the label field.
Note that this field will be exclude from feature fields.
:param f: Selected label field
:type f: str
:rtype: DataFrame
"""
if f is None:
raise ValueError("Label field name ca... | 0.006263 |
def map_values2(self, func):
"""
:param func:
:type func: (K, T) -> U
:rtype: TDict[U]
Usage:
>>> TDict(k1=1, k2=2, k3=3).map_values2(lambda k, v: f'{k} -> {v*2}') == {
... "k1": "k1 -> 2",
... "k2": "k2 -> 4",
... "k3... | 0.006787 |
def getextensibleindex(bunchdt, data, commdct, key, objname):
"""get the index of the first extensible item"""
theobject = getobject(bunchdt, key, objname)
if theobject == None:
return None
theidd = iddofobject(data, commdct, key)
extensible_i = [
i for i in range(len(theidd)) if 'be... | 0.004494 |
def send_simple(self, address, timestamp, value):
"""Queue a simple datapoint (ie. a 64-bit word), return True/False for success.
Arguments:
address -- uint64_t representing a unique metric.
timestamp -- uint64_t representing number of nanoseconds (10^-9) since epoch.
value -- u... | 0.005618 |
def find_prepositions(chunked):
""" The input is a list of [token, tag, chunk]-items.
The output is a list of [token, tag, chunk, preposition]-items.
PP-chunks followed by NP-chunks make up a PNP-chunk.
"""
# Tokens that are not part of a preposition just get the O-tag.
for ch in chunked... | 0.003524 |
def issn(self, mask: str = '####-####') -> str:
"""Generate a random ISSN.
:param mask: Mask of ISSN.
:return: ISSN.
"""
return self.random.custom_code(mask=mask) | 0.009852 |
def _count_dollars_before_index(self, s, i):
"""Returns the number of '$' characters right in front of s[i]."""
dollar_count = 0
dollar_index = i - 1
while dollar_index > 0 and s[dollar_index] == '$':
dollar_count += 1
dollar_index -= 1
return dollar_count | 0.00625 |
def fromMessage(klass, message, op_endpoint):
"""Construct me from an OpenID message.
@raises ProtocolError: When not all required parameters are present
in the message.
@raises MalformedReturnURL: When the C{return_to} URL is not a URL.
@raises UntrustedReturnURL: When th... | 0.000752 |
def get_results(self, client_id, msg):
"""Get the result of 1 or more messages."""
content = msg['content']
msg_ids = sorted(set(content['msg_ids']))
statusonly = content.get('status_only', False)
pending = []
completed = []
content = dict(status='ok')
con... | 0.00471 |
def list_slack():
"""List channels & users in slack."""
try:
token = os.environ['SLACK_TOKEN']
slack = Slacker(token)
# Get channel list
response = slack.channels.list()
channels = response.body['channels']
for channel in channels:
print(channel['id']... | 0.001211 |
def check_spelling(spelling_lang, txt):
"""
Check the spelling in the text, and compute a score. The score is the
number of words correctly (or almost correctly) spelled, minus the number
of mispelled words. Words "almost" correct remains neutral (-> are not
included in the score)
Returns:
... | 0.000454 |
def shadows(self, data=None, t=None, dt=None, latitude=None,
init='empty', resolution='mid'):
'''
Initializes a ShadowManager object for this ``pyny.Space``
instance.
The 'empty' initialization accepts ``data`` and ``t`` and ``dt``
but the Shadows... | 0.009104 |
def _rshift_arithmetic(self, shift_amount):
"""
Arithmetic shift right with a concrete shift amount
:param int shift_amount: Number of bits to shift right.
:return: The new StridedInterval after right shifting
:rtype: StridedInterval
"""
if self.is_empty:
... | 0.004831 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.