code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def usergroups_users_update(self, *, usergroup: str, users: List[str], **kwargs) -> SlackResponse:
self._validate_xoxp_token()
kwargs.update({'usergroup': usergroup, 'users': users})
return self.api_call('usergroups.users.update', json=kwargs) | Update the list of users for a User Group
Args:
usergroup (str): The encoded ID of the User Group to update.
e.g. 'S0604QSJC'
users (list): A list user IDs that represent the entire list of
users for the User Group. e.g. ['U060R4BJ4', 'U060RNRCZ'] | codesearchnet |
def create(self, specify_uri=False, ignore_tombstone=False, serialization_format=None, stream=False, auto_refresh=None):
if self.exists:
raise Exception('resource exists attribute True, aborting')
else:
if specify_uri:
verb = 'PUT'
else:
verb = 'POST'
logg... | Primary method to create resources.
Args:
specify_uri (bool): If True, uses PUT verb and sets the URI during creation. If False, uses POST and gets repository minted URI
ignore_tombstone (bool): If True, will attempt creation, if tombstone exists (409), will delete tombstone and retry
serialization_format(str): Conte... | codesearchnet |
def single_qubit_state_tomography(sampler: sim.Sampler, qubit: devices.GridQubit, circuit: circuits.Circuit, repetitions: int=1000) -> TomographyResult:
circuit_z = (circuit + circuits.Circuit.from_ops(ops.measure(qubit, key='z')))
results = sampler.run(circuit_z, repetitions=repetitions)
rho_11 = np.mean(r... | Single-qubit state tomography.
The density matrix of the output state of a circuit is measured by first
doing projective measurements in the z-basis, which determine the
diagonal elements of the matrix. A X/2 or Y/2 rotation is then added before
the z-basis measurement, which determines the imaginary and real parts of... | codesearchnet |
def ParseZeitgeistEventRow(self, parser_mediator, query, row, **unused_kwargs):
query_hash = hash(query)
event_data = ZeitgeistActivityEventData()
event_data.offset = self._GetRowValue(query_hash, row, 'id')
event_data.query = query
event_data.subject_uri = self._GetRowValue(query_hash, row, 'subj_u... | Parses a zeitgeist event row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row. | codesearchnet |
def from_file(cls, jss, filename):
tree = ElementTree.parse(filename)
root = tree.getroot()
return cls(jss, root) | Create a new JSSObject from an external XML file.
Args:
jss: A JSS object.
filename: String path to an XML file. | juraj-google-style |
def _copy_delpoy_scripts(self, scripts):
if (not os.path.exists(self.paths.scripts())):
os.makedirs(self.paths.scripts())
new_scripts = []
for script in scripts:
script = os.path.expandvars(script)
if (not os.path.exists(script)):
raise RuntimeError(('Script %s does not e... | Copy the given deploy scripts to the scripts dir in the prefix
Args:
scripts(list of str): list of paths of the scripts to copy to the
prefix
Returns:
list of str: list with the paths to the copied scripts, with a
prefixed with $LAGO_PREFIX_PATH so the full path is not
hardcoded | codesearchnet |
def setup(template, version=None):
temple.check.is_git_ssh_path(template)
temple.check.not_in_git_repo()
repo_path = temple.utils.get_repo_path(template)
msg = 'You will be prompted for the parameters of your new project. Please read the docs at https:
print(msg)
(cc_repo_dir, config) = temple.u... | Sets up a new project from a template
Note that the `temple.constants.TEMPLE_ENV_VAR` is set to 'setup' during the duration
of this function.
Args:
template (str): The git SSH path to a template
version (str, optional): The version of the template to use when updating. Defaults
to the latest version | codesearchnet |
def create_bird_config_files(bird_configuration):
for ip_version in bird_configuration:
config_file = bird_configuration[ip_version]['config_file']
try:
touch(config_file)
except OSError as exc:
raise ValueError("failed to create {f}:{e}"
... | Create bird configuration files per IP version.
Creates bird configuration files if they don't exist. It also creates the
directories where we store the history of changes, if this functionality is
enabled.
Arguments:
bird_configuration (dict): A dictionary with settings for bird.
Returns:
None
Raises:
ValueError i... | juraj-google-style |
def get_videos_for_course(course_id, sort_field=None, sort_dir=SortDirection.asc, pagination_conf=None):
return _get_videos_for_filter(
{'courses__course_id': six.text_type(course_id), 'courses__is_hidden': False},
sort_field,
sort_dir,
pagination_conf,
) | Returns an iterator of videos for the given course id.
Args:
course_id (String)
sort_field (VideoSortField)
sort_dir (SortDirection)
Returns:
A generator expression that contains the videos found, sorted by the
given field and direction, with ties broken by edx_video_id to ensure a
total order. | juraj-google-style |
def call(self, inputs, state):
original_shape = inputs.shape
if (len(original_shape) < 2):
inputs = tf.reshape(inputs, [1, (- 1)])
(out, state) = self.lstm_cell(inputs, state)
out = self.output_layer(out)
correct_shape = tf.concat((original_shape[:(- 1)], tf.shape(input=out)[(- 1):]), 0)
... | Runs the model to generate a distribution for a single timestep.
This generates a batched MultivariateNormalDiag distribution using
the output of the recurrent model at the current timestep to
parameterize the distribution.
Args:
inputs: The sampled value of `z` at the previous timestep, i.e.,
`z_{t-1}`, of shape [..... | codesearchnet |
def __init__(self, *rows, **kwargs):
if not all([isinstance(r, Row) for r in rows]):
raise TypeError('All elements of Grid must be Row instances')
self.type = 'grid'
self.rows = rows | Init method.
Args:
*rows (): the instances of Row.
**kwargs (): not used. | juraj-google-style |
def get(self, url, params={}, headers={}, auth=(), certificate_path=None):
certificate_path = (certificate_path if certificate_path else False)
return self.session.get(url, params=params, headers=headers, verify=certificate_path, auth=auth, timeout=self.timeout) | Returns the response payload from the request to the given URL.
Args:
url (str): The URL for the WEB API that the request is being made too.
params (dict): Dictionary containing the query string parameters.
headers (dict): HTTP Headers that may be needed for the request.
auth (tuple): User ID and password for Basic Au... | codesearchnet |
def from_csv(input_csv, headers=None, schema_file=None):
if (headers is not None):
names = headers
elif (schema_file is not None):
with _util.open_local_or_gcs(schema_file, mode='r') as f:
schema = json.load(f)
names = [x['name'] for x in schema]
else:
raise Value... | Create a ConfusionMatrix from a csv file.
Args:
input_csv: Path to a Csv file (with no header). Can be local or GCS path.
headers: Csv headers. If present, it must include 'target' and 'predicted'.
schema_file: Path to a JSON file containing BigQuery schema. Used if "headers" is None.
If present, it must include 'targ... | codesearchnet |
def create_ingress_rule(self, app, rule):
if isinstance(rule, dict):
start_port = rule.get('start_port')
end_port = rule.get('end_port')
protocol = rule.get('protocol', 'tcp')
requested_cross_account = rule.get('env', self.env)
if (self.env == requested_cross_account):
... | Create a normalized ingress rule.
Args:
app (str): Application name
rule (dict or int): Allowed Security Group ports and protocols.
Returns:
dict: Contains app, start_port, end_port, protocol, cross_account_env and cross_account_vpc_id | codesearchnet |
def GetUsername(self, event, default_username='-'):
username = getattr(event, 'username', None)
if (username and (username != '-')):
return username
session_identifier = event.GetSessionIdentifier()
if (session_identifier is None):
return default_username
user_sid = getattr(event, 'u... | Retrieves the username related to the event.
Args:
event (EventObject): event.
default_username (Optional[str]): default username.
Returns:
str: username. | codesearchnet |
def GetScripts(self, dest_dir):
metadata_dict = self.watcher.GetMetadata() or {}
try:
instance_data = metadata_dict['instance']['attributes']
except KeyError:
instance_data = None
self.logger.warning('Instance attributes were not found.')
try:
project_data = metadata_dict[... | Retrieve the scripts to execute.
Args:
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
dict, a dictionary mapping set metadata keys with associated scripts. | juraj-google-style |
def _build(self, inputs):
if nest.is_sequence(inputs):
merged_tensors = [self._merge(tensor) for tensor in nest.flatten(inputs)]
return nest.pack_sequence_as(inputs, merged_tensors)
return self._merge(inputs) | Connects the MergeDims module into the graph.
Args:
inputs: Tensor or a nested list of Tensors to merge. Its rank must be
greater than or equal to `start` + `size`.
Returns:
The merged Tensor or a nested list of merged Tensors.
Raises:
ValueError: If any of the `inputs` tensors has insufficient rank. | codesearchnet |
def __init__(self, asynchronous_correlation_value=None):
super(PollRequestPayload, self).__init__(
enums.Tags.REQUEST_PAYLOAD
)
self._asynchronous_correlation_value = None
self.asynchronous_correlation_value = asynchronous_correlation_value | Construct a Poll request payload struct.
Args:
asynchronous_correlation_value (bytes): The ID of a pending
operation to poll the status of, in bytes. Optional, defaults
to None. | juraj-google-style |
def unpackVersion(ver):
major = ((ver >> (20 * 2)) & mask20)
minor = ((ver >> 20) & mask20)
patch = (ver & mask20)
return (major, minor, patch) | Unpack a system normalized integer representing a softare version into its component parts.
Args:
ver (int): System normalized integer value to unpack into a tuple.
Returns:
(int, int, int): A tuple containing the major, minor and patch values shifted out of the integer. | codesearchnet |
def __init__(self, cache_folder, genome_build):
self.cache = EnsemblCache(cache_folder, genome_build)
self.prior_time = time.time() - 1
self.rate_limit = 0.067
server_dict = {"grch37": "grch37.", "grch38": ""}
self.server = "http:
... | obtain the sequence for a transcript from ensembl
Args:
cache_folder: path to folder for caching data requested from Ensembl
genome_build: string indicating the genome build ("grch37" or "grch38") | juraj-google-style |
def parse_cytoband(lines):
cytobands = {}
for line in lines:
line = line.rstrip()
splitted_line = line.split('\t')
chrom = splitted_line[0].lstrip('chr')
start = int(splitted_line[1])
stop = int(splitted_line[2])
name = splitted_line[3]
if chrom in cy... | Parse iterable with cytoband coordinates
Args:
lines(iterable): Strings on format "chr1\t2300000\t5400000\tp36.32\tgpos25"
Returns:
cytobands(dict): Dictionary with chromosome names as keys and
interval trees as values | juraj-google-style |
def check_phonefy(self, query, kwargs={}):
data = self.launchQueryForMode(query=query, mode="phonefy")
if self._somethingFound(data, mode="phonefy"):
return data
return None | Verifying a mailfy query in this platform.
This might be redefined in any class inheriting from Platform. The only
condition is that any of this should return a dictionary as defined.
Args:
-----
query: The element to be searched.
kwargs: Dictionary with extra parameters. Just in case.
Return:
-------
Returns the co... | juraj-google-style |
def _VerifyValues(self, image, kernel, strides, rates, padding, out, use_gpu):
strides = [1] + strides + [1]
rates = [1] + rates + [1]
with self.cached_session(use_gpu=use_gpu):
out_tensor = nn_ops.erosion2d(constant_op.constant(image), constant_op.constant(kernel), strides=strides, rates=rates, pad... | Verifies the output values of the erosion function.
Args:
image: Input tensor with shape: [batch, in_height, in_width, channels].
kernel: Filter tensor with shape: [filter_height, filter_width, channels].
strides: Output strides, specified as [stride_height, stride_width].
rates: Atrous rates, specified as [rate_heigh... | github-repos |
def export_as_file(self, file_path, cv_source):
if os.path.exists(file_path):
raise exceptions.UserError('{} already exists'.format(file_path))
with open(file_path, 'wb') as f:
f.write(self.export_as_code(cv_source).encode('utf8')) | Export the ensemble as a single Python file and saves it to `file_path`.
This is EXPERIMENTAL as putting different modules together would probably wreak havoc
especially on modules that make heavy use of global variables.
Args:
file_path (str, unicode): Absolute/local path of place to save file in
cv_source (str, un... | juraj-google-style |
def iter_package_families(paths=None):
for path in (paths or config.packages_path):
repo = package_repository_manager.get_repository(path)
for resource in repo.iter_package_families():
(yield PackageFamily(resource)) | Iterate over package families, in no particular order.
Note that multiple package families with the same name can be returned.
Unlike packages, families later in the searchpath are not hidden by earlier
families.
Args:
paths (list of str, optional): paths to search for package families,
defaults to `config.packages_p... | codesearchnet |
def add_table(self, table):
import astropy
table_array = table.__array__()
self.table_keys= table.keys()
table_columns= []
for i in range(0,len(table.columns[0])):
row_data = []
for item in ta... | load a VOTable -already accessible on the python side- into the widget
Args:
table: votable object | juraj-google-style |
def generate(self, model_len=None, model_width=None):
if model_len is None:
model_len = Constant.MODEL_LEN
if model_width is None:
model_width = Constant.MODEL_WIDTH
if isinstance(model_width, list) and not len(model_width) == model_len:
raise ValueEr... | Generates a Multi-Layer Perceptron.
Args:
model_len: An integer. Number of hidden layers.
model_width: An integer or a list of integers of length `model_len`. If it is a list, it represents the
number of nodes in each hidden layer. If it is an integer, all hidden layers have nodes equal to this
value.
Returns:
An insta... | juraj-google-style |
def delete_course_completion(self, user_id, payload):
return self._delete(urljoin(self.enterprise_configuration.degreed_base_url, self.global_degreed_config.completion_status_api_path), payload, self.COMPLETION_PROVIDER_SCOPE) | Delete a completion status previously sent to the Degreed Completion Status endpoint
Args:
user_id: Unused.
payload: JSON encoded object (serialized from DegreedLearnerDataTransmissionAudit)
containing the required completion status fields for deletion per Degreed documentation.
Returns:
A tuple containing the status... | codesearchnet |
def _list_all_concrete_functions_for_serialization(self):
seen_signatures = []
if self.input_signature is not None:
seen_signatures.append((self.input_signature, {}))
else:
concrete_functions = self._list_all_concrete_functions()
for concrete_function in concrete_functions:
... | Returns all concrete functions for serialization.
Returns:
A list of instances of `ConcreteFunction`. | github-repos |
def whoami(self) -> dict:
if not self.access_token:
return {}
self._try_refresh_access_token()
return self.session.get(self.WHOAMI_URL).json() | Returns the basic information about the authenticated character.
Obviously doesn't do anything if this Preston instance is not
authenticated, so it returns an empty dict.
Args:
None
Returns:
character info if authenticated, otherwise an empty dict | juraj-google-style |
def clean(self, force: bool=False):
with (yield from self._lock):
for connection in tuple(self.ready):
if force or connection.closed():
connection.close()
self.ready.remove(connection) | Clean closed connections.
Args:
force: Clean connected and idle connections too.
Coroutine. | juraj-google-style |
def markdown_to_safe_html(markdown_string):
warning = ''
if isinstance(markdown_string, six.binary_type):
markdown_string_decoded = markdown_string.decode('utf-8')
markdown_string = markdown_string_decoded.replace(u'\x00', u'')
num_null_bytes = (len(markdown_string_decoded) - len(markdow... | Convert Markdown to HTML that's safe to splice into the DOM.
Arguments:
markdown_string: A Unicode string or UTF-8--encoded bytestring
containing Markdown source. Markdown tables are supported.
Returns:
A string containing safe HTML. | codesearchnet |
def __intervals_from_tops(self,
tops,
values,
basis,
components,
field=None,
ignore_nan=True):
length = float(basi... | Private method. Take a sequence of tops in an arbitrary dimension,
and provide a list of intervals from which a striplog can be made.
This is only intended to be used by ``from_image()``.
Args:
tops (iterable). A list of floats.
values (iterable). A list of values to look up.
basis (iterable). A list of components.
c... | juraj-google-style |
def __str__(self):
name = self.__class__.__name__
return '%s(Handle %d, Address %d)' % (name, self.Handle, self.Addr) | Returns a formatted string describing the breakpoint.
Args:
self (JLinkBreakpointInfo): the ``JLinkBreakpointInfo`` instance
Returns:
Stirng representation of the breakpoint. | juraj-google-style |
def put(self, rid, data, raise_on_error=True):
response_data = None
headers = {'Content-Type': 'application/json', 'DB-Method': 'PUT'}
url = '/v2/exchange/db/{}/{}/{}'.format(self.domain, self.data_type, rid)
r = self.tcex.session.post(url, json=data, headers=headers)
se... | Update the data for the provided Id.
Args:
rid (str): The record identifier.
data (dict): A search query
raise_on_error (bool): If True and not r.ok this method will raise a RunTimeError.
Returns:
object : Python request response. | juraj-google-style |
def sunrise(self, date=None, zenith=None):
return (segment.sunrise(date, zenith) for segment in self) | Calculate sunrise times for locations.
Args:
date (datetime.date): Calculate rise or set for given date
zenith (str): Calculate sunrise events, or end of twilight
Returns:
list of list of datetime.datetime: The time for the sunrise for
each point in each segment | codesearchnet |
def clean_df(df, header=None, **read_csv_kwargs):
df = read_csv(df, header=header, **read_csv_kwargs)
df = df.fillna(' ')
for col in df.columns:
df[col] = df[col].apply(unicode2ascii)
return df | Convert UTF8 characters in a CSV file or dataframe into ASCII
Args:
df (DataFrame or str): DataFrame or path or url to CSV | juraj-google-style |
def register_handler(self, handler, event_name, args):
if self.started:
raise IllegalStateError("Can't register service after polling is started")
self.lock.acquire()
try:
if (event_name in self.handlers):
raise DuplicateError('A handler for {} already exists'.format(event_name))... | Registers an event handler.
One type of event can only have one event handler associated with it.
Args:
handler: The event handler function to be registered.
event_name: Name of the event the handler is for.
args: User arguments to be passed to the handler when it's called.
Raises:
IllegalStateError: Raised if attem... | codesearchnet |
def change_extension(self, filepath, new_extension):
(filename, ext) = os.path.splitext(filepath)
return '.'.join([filename, new_extension]) | Change final filename extension.
Args:
filepath (str): A file path (relative or absolute).
new_extension (str): New extension name (without leading dot) to
apply.
Returns:
str: Filepath with new extension. | codesearchnet |
def from_json(data):
memfiles = InMemoryFiles()
memfiles.files = json.loads(data)
return memfiles | Convert JSON into a in memory file storage.
Args:
data (str): valid JSON with path and filenames and
the base64 encoding of the file content.
Returns:
InMemoryFiles: in memory file storage | juraj-google-style |
def write(self, name, **data):
data['name'] = name
if (not ('timestamp' in data)):
data['timestamp'] = datetime.utcnow()
try:
self.producer.send(topic=self.topic, value=data)
self.producer.flush()
except (KafkaTimeoutError, NoBrokersAvailable) as exc:
logger.warning('writ... | Write the metric to kafka
Args:
name (str): The name of the metric to write
data (dict): Additional data to store with the metric | codesearchnet |
def tap(self, locator, x_offset=None, y_offset=None, count=1):
driver = self._current_application()
el = self._element_find(locator, True, True)
action = TouchAction(driver)
action.tap(el,x_offset,y_offset, count).perform() | Tap element identified by ``locator``.
Args:
- ``x_offset`` - (optional) x coordinate to tap, relative to the top left corner of the element.
- ``y_offset`` - (optional) y coordinate. If y is used, x must also be set, and vice versa
- ``count`` - can be used for multiple times of tap on that element | juraj-google-style |
def subscribe_registration_ids_to_topic(self, registration_ids, topic_name):
url = 'https:
payload = {'to': ('/topics/' + topic_name), 'registration_tokens': registration_ids}
response = self.requests_session.post(url, json=payload)
if (response.status_code == 200):
return True
elif (respons... | Subscribes a list of registration ids to a topic
Args:
registration_ids (list): ids to be subscribed
topic_name (str): name of topic
Returns:
True: if operation succeeded
Raises:
InvalidDataError: data sent to server was incorrectly formatted
FCMError: an error occured on the server | codesearchnet |
def to_dataframe(self, start_row=0, max_rows=None):
fetcher = self._get_row_fetcher(start_row=start_row, max_rows=max_rows)
count = 0
page_token = None
df = None
while True:
page_rows, page_token = fetcher(page_token, count)
if len(page_rows):
count += len(page_rows)
... | Exports the table to a Pandas dataframe.
Args:
start_row: the row of the table at which to start the export (default 0)
max_rows: an upper limit on the number of rows to export (default None)
Returns:
A Pandas dataframe containing the table data. | juraj-google-style |
def is_value_type_valid_for_exact_conditions(self, value):
if (isinstance(value, string_types) or isinstance(value, (numbers.Integral, float))):
return True
return False | Method to validate if the value is valid for exact match type evaluation.
Args:
value: Value to validate.
Returns:
Boolean: True if value is a string, boolean, or number. Otherwise False. | codesearchnet |
def get_end_time_metric(result: PipelineResult, namespace: str, name: str) -> int:
distributions = result.metrics().query(MetricsFilter().with_namespace(namespace).with_name(name))['distributions']
max_list = list(map(lambda m: m.result.max, distributions))
return max(max_list) if len(max_list) > 0 else -1 | get the end time out of all times recorded by the specified distribution
metric
Args:
result: the PipelineResult which metrics are read from
namespace: a string representing the namespace of wanted metric
name: a string representing the name of the wanted metric
Returns:
the largest time in the metric or -1 if it do... | github-repos |
def as_tuning_range(self, name):
return {'Name': name,
'MinValue': to_str(self.min_value),
'MaxValue': to_str(self.max_value),
'ScalingType': self.scaling_type} | Represent the parameter range as a dicionary suitable for a request to
create an Amazon SageMaker hyperparameter tuning job.
Args:
name (str): The name of the hyperparameter.
Returns:
dict[str, str]: A dictionary that contains the name and values of the hyperparameter. | juraj-google-style |
def clean_channel_worker_username(self):
channel_worker_username = self.cleaned_data['channel_worker_username'].strip()
try:
User.objects.get(username=channel_worker_username)
except User.DoesNotExist:
raise ValidationError(ValidationMessages.INVALID_CHANNEL_WORKER.format(channel_worker_user... | Clean enterprise channel worker user form field
Returns:
str: the cleaned value of channel user username for transmitting courses metadata. | codesearchnet |
def _build_trial_meta(cls, expr_dir):
meta_file = os.path.join(expr_dir, EXPR_META_FILE)
meta = parse_json(meta_file)
if not meta:
job_id = expr_dir.split("/")[-2]
trial_id = expr_dir[-8:]
params = parse_json(os.path.join(expr_dir, EXPR_PARARM_FILE))... | Build meta file for trial.
Args:
expr_dir (str): Directory path of the experiment.
Return:
A dict of trial meta info. | juraj-google-style |
def parse_expression(src):
src = STANDARD_PREAMBLE + src.strip()
node = parse(src, preamble_len=STANDARD_PREAMBLE_LEN, single_node=True)
if __debug__:
if not isinstance(node, gast.Expr):
raise ValueError('expected exactly one node of type Expr, got {}'.format(node))
return node.value | Returns the AST of given identifier.
Args:
src: A piece of code that represents a single Python expression
Returns:
A gast.AST object.
Raises:
ValueError: if src does not consist of a single Expression. | github-repos |
def transpose(vari):
if isinstance(vari, Poly):
core = vari.A.copy()
for key in vari.keys:
core[key] = transpose(core[key])
return Poly(core, vari.dim, vari.shape[::-1], vari.dtype)
return numpy.transpose(vari) | Transpose a shapeable quantety.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Quantety of interest.
Returns:
(chaospy.poly.base.Poly, numpy.ndarray):
Same type as ``vari``.
Examples:
>>> P = chaospy.reshape(chaospy.prange(4), (2,2))
>>> print(P)
[[1, q0], [q0^2, q0^3]]
>>> print(chaospy.transpose(P))
[[1, q0^2... | juraj-google-style |
def read_nose(in_file):
suites = {}
doc_xml = minidom.parse(in_file)
suite_xml = doc_xml.getElementsByTagName('testsuite')[0]
for case_xml in suite_xml.getElementsByTagName('testcase'):
classname = case_xml.getAttribute('classname')
if (classname not in suites):
suites[classn... | Parse nose-style test reports into a `dict`
Args:
in_file (:obj:`str`): path to nose-style test report
Returns:
:obj:`dict`: dictionary of test suites | codesearchnet |
def add(self, index):
if ((index - self.flush_at) < self.interval):
return
now = time.time()
elapsed = (now - self.lap)
elapsed_total = (now - self.start)
it = (index - self.flush_at)
self.lap = now
if self.verbose:
logger.info('iter={} {{{}}}={}[sec/{}iter] {}[sec]'.format(i... | Calculate time elapsed from the point previously called
this method or this object is created to this is called.
Args:
index (int): Index to be displayed, and be used to take intervals. | codesearchnet |
def _convert_and_export_metrics(self, convert_func, *args, **kwargs):
self._increase_conversion_attempt_metric()
self._save_conversion_params_metric()
start_time = time.process_time()
result = convert_func(self, *args, **kwargs)
elapsed_time_ms = (time.process_time() - start_time) * 1000
if resu... | Wraps around convert function to export metrics.
Args:
convert_func: The convert function to wrap.
*args: Positional arguments of the convert function.
**kwargs: The keyword arguments of the convert function.
Returns:
The decorator to wrap the convert function. | github-repos |
def values(self, *args):
return [dict(zip(args, values_list))
for values_list in self.values_list(flatten=False, *args)] | Returns list of dicts (field names as keys) for given fields.
Args:
\*args: List of fields to be returned as dict.
Returns:
list of dicts for given fields.
Example:
>>> Person.objects.filter(age__gte=16, name__startswith='jo').values('name', 'lastname') | juraj-google-style |
def _get_path_for_op_id(self, id: str) -> Optional[str]:
for path_key, path_value in self._get_spec()['paths'].items():
for method in self.METHODS:
if method in path_value:
if self.OPERATION_ID_KEY in path_value[method]:
if path_va... | Searches the spec for a path matching the operation id.
Args:
id: operation id
Returns:
path to the endpoint, or None if not found | juraj-google-style |
def guid(valu=None):
if valu is None:
return binascii.hexlify(os.urandom(16)).decode('utf8')
byts = s_msgpack.en(valu)
return hashlib.md5(byts).hexdigest() | Get a 16 byte guid value.
By default, this is a random guid value.
Args:
valu: Object used to construct the guid valu from. This must be able
to be msgpack'd.
Returns:
str: 32 character, lowercase ascii string. | juraj-google-style |
def get_preprocessor(model_name: str) -> Optional[Union['AutoTokenizer', 'AutoFeatureExtractor', 'AutoProcessor']]:
from .. import AutoFeatureExtractor, AutoProcessor, AutoTokenizer
try:
return AutoProcessor.from_pretrained(model_name)
except (ValueError, OSError, KeyError):
tokenizer, featu... | Gets a preprocessor (tokenizer, feature extractor or processor) that is available for `model_name`.
Args:
model_name (`str`): Name of the model for which a preprocessor are loaded.
Returns:
`Optional[Union[AutoTokenizer, AutoFeatureExtractor, AutoProcessor]]`:
If a processor is found, it is returned. Otherwise, if a ... | github-repos |
def _maybe_repeat(self, x):
if isinstance(x, list):
assert len(x) == self.n
return x
else:
return [x] * self.n | Utility function for processing arguments that are singletons or lists.
Args:
x: either a list of self.n elements, or not a list.
Returns:
a list of self.n elements. | juraj-google-style |
def __set_unkown_effect(self, hgvs_string):
unknown_effect_list = ['?', '(=)', '=']
if hgvs_string in unknown_effect_list:
self.unknown_effect = True
elif "(" in hgvs_string:
self.unknown_effect = True
else:
self.unknow... | Sets a flag for unkown effect according to HGVS syntax. The
COSMIC database also uses unconventional questionmarks to denote
missing information.
Args:
hgvs_string (str): hgvs syntax with "p." removed | juraj-google-style |
def CreateKey(self, private_key=None):
if (private_key is None):
private_key = bytes(Random.get_random_bytes(32))
key = KeyPair(priv_key=private_key)
self._keys[key.PublicKeyHash.ToBytes()] = key
return key | Create a KeyPair
Args:
private_key (iterable_of_ints): (optional) 32 byte private key
Returns:
KeyPair: a KeyPair instance | codesearchnet |
def transform_tensor(self, tensor):
dim = tensor.shape
rank = len(dim)
assert all([i == 3 for i in dim])
lc = string.ascii_lowercase
indices = lc[:rank], lc[rank:2 * rank]
einsum_string = ','.join([a + i for a, i in zip(*indices)])
einsum_string ... | Applies rotation portion to a tensor. Note that tensor has to be in
full form, not the Voigt form.
Args:
tensor (numpy array): a rank n tensor
Returns:
Transformed tensor. | juraj-google-style |
def createResourceMapFromStream(in_stream, base_url=d1_common.const.URL_DATAONE_ROOT):
pids = []
for line in in_stream:
pid = line.strip()
if ((pid == '
continue
if (len(pids) < 2):
raise ValueError('Insufficient numbers of identifiers provided.')
logging.info('Read {... | Create a simple OAI-ORE Resource Map with one Science Metadata document and any
number of Science Data objects, using a stream of PIDs.
Args:
in_stream:
The first non-blank line is the PID of the resource map itself. Second line is
the science metadata PID and remaining lines are science data PIDs.
Example stream con... | codesearchnet |
def from_rotation_and_translation_and_time_reversal(rotation_matrix=((1, 0, 0), (0, 1, 0), (0, 0, 1)), translation_vec=(0, 0, 0), time_reversal=1, tol=0.1):
symmop = SymmOp.from_rotation_and_translation(rotation_matrix=rotation_matrix, translation_vec=translation_vec, tol=tol)
return MagSymmOp.from_symmop(symmo... | Creates a symmetry operation from a rotation matrix, translation
vector and time reversal operator.
Args:
rotation_matrix (3x3 array): Rotation matrix.
translation_vec (3x1 array): Translation vector.
time_reversal (int): Time reversal operator, +1 or -1.
tol (float): Tolerance to determine if rotation matrix is valid... | codesearchnet |
def _ParsePropertiesXMLFile(self, xml_data):
xml_root = ElementTree.fromstring(xml_data)
properties = {}
for xml_element in xml_root.iter():
if (not xml_element.text):
continue
(_, _, name) = xml_element.tag.partition('}')
if (name == 'lpstr'):
continue
... | Parses a properties XML file.
Args:
xml_data (bytes): data of a _rels/.rels XML file.
Returns:
dict[str, object]: properties.
Raises:
zipfile.BadZipfile: if the properties XML file cannot be read. | codesearchnet |
def __eq__(self, rhs):
return (isinstance(rhs, MockMethod) and
self._name == rhs._name and
self._params == rhs._params and
self._named_params == rhs._named_params) | Test whether this MockMethod is equivalent to another MockMethod.
Args:
# rhs: the right hand side of the test
rhs: MockMethod | juraj-google-style |
def load_glossary(file_path: str, read_json=False) -> List[str]:
if read_json:
if file_path.endswith('.gz'):
return json.load(gzip.open(file_path))
return json.load(open(file_path))
return open(file_path).read().splitlines() | A glossary is a text file, one entry per line.
Args:
file_path (str): path to a text file containing a glossary.
read_json (bool): set True if the glossary is in json format
Returns: List of the strings in the glossary. | codesearchnet |
def wait(fs, timeout=None, return_when=ALL_COMPLETED):
with _AcquireFutures(fs):
done = set((f for f in fs if (f._state in [CANCELLED_AND_NOTIFIED, FINISHED])))
not_done = (set(fs) - done)
if ((return_when == FIRST_COMPLETED) and done):
return DoneAndNotDoneFutures(done, not_done... | Wait for the futures in the given sequence to complete.
Args:
fs: The sequence of Futures (possibly created by different Executors) to
wait upon.
timeout: The maximum number of seconds to wait. If None, then there
is no limit on the wait time.
return_when: Indicates when this function should return. The options
are:
... | codesearchnet |
def ellipse_distance(item_a, time_a, item_b, time_b, max_value):
ts = np.array([0, np.pi])
ell_a = item_a.get_ellipse_model(time_a)
ell_b = item_b.get_ellipse_model(time_b)
ends_a = ell_a.predict_xy(ts)
ends_b = ell_b.predict_xy(ts)
distances = np.sqrt((((ends_a[(:, 0:1)] - ends_b[(:, 0:1)].T) *... | Calculate differences in the properties of ellipses fitted to each object.
Args:
item_a: STObject from the first set in ObjectMatcher
time_a: Time integer being evaluated
item_b: STObject from the second set in ObjectMatcher
time_b: Time integer being evaluated
max_value: Maximum distance value used as scaling value a... | codesearchnet |
def get_subscribers(object_type: str) -> List[str]:
return DB.get_list(_keys.subscribers(object_type)) | Get the list of subscribers to events of the object type.
Args:
object_type (str): Type of object.
Returns:
List[str], list of subscriber names. | codesearchnet |
def expand_recurring(number, repeat=5):
if "[" in number:
pattern_index = number.index("[")
pattern = number[pattern_index + 1:-1]
number = number[:pattern_index]
number = number + pattern * (repeat + 1)
return number | Expands a recurring pattern within a number.
Args:
number(tuple): the number to process in the form:
(int, int, int, ... ".", ... , int int int)
repeat: the number of times to expand the pattern.
Returns:
The original number with recurring pattern expanded.
Example:
>>> expand_recurring((1, ".", 0, "[", 9, "]"), rep... | juraj-google-style |
def result_code(self, value):
if value == self._defaults['resultCode'] and 'resultCode' in self._values:
del self._values['resultCode']
else:
self._values['resultCode'] = value | The result_code property.
Args:
value (string). the property value. | juraj-google-style |
def __init__(self, name, number, aliases=None, description=None):
super(EnumerationValue, self).__init__()
self.aliases = aliases or []
self.description = description
self.name = name
self.number = number | Initializes an enumeration value.
Args:
name (str): name.
number (int): number.
aliases (Optional[list[str]]): aliases.
description (Optional[str]): description. | juraj-google-style |
def __delitem__(self, obj, sync=True):
if self._is_item:
raise TypeError("This an item of the parent ListNode")
list(self._generate_instances())
_lnk_key = None
if isinstance(obj, six.string_types):
_lnk_key = obj
_obj = self.node_dict[obj]
... | Allow usage of "del" statement on ListNodes with bracket notation.
Args:
obj: ListNode item or relation key.
Raises:
TypeError: If it's called on a ListNode item (intstead of ListNode's itself) | juraj-google-style |
def parse_rfc3339_utc_string(rfc3339_utc_string):
m = re.match('(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2}).?(\\d*)Z', rfc3339_utc_string)
if (not m):
return None
groups = m.groups()
if (len(groups[6]) not in (0, 3, 6, 9)):
return None
g = [int(val) for val in groups[:6]]
... | Converts a datestamp from RFC3339 UTC to a datetime.
Args:
rfc3339_utc_string: a datetime string in RFC3339 UTC "Zulu" format
Returns:
A datetime. | codesearchnet |
def output(self, filename):
info = 'Inheritance\n'
if (not self.contracts):
return
info += (blue('Child_Contract -> ') + green('Immediate_Base_Contracts'))
info += green(' [Not_Immediate_Base_Contracts]')
for child in self.contracts:
info += blue(f)
if child.inheritance:
... | Output the inheritance relation
_filename is not used
Args:
_filename(string) | codesearchnet |
def build_sanitiser_node_dict(
cfg,
sinks_in_file
):
sanitisers = list()
for sink in sinks_in_file:
sanitisers.extend(sink.sanitisers)
sanitisers_in_file = list()
for sanitiser in sanitisers:
for cfg_node in cfg.nodes:
if sanitiser in cfg_node.label:
... | Build a dict of string -> TriggerNode pairs, where the string
is the sanitiser and the TriggerNode is a TriggerNode of the sanitiser.
Args:
cfg(CFG): cfg to traverse.
sinks_in_file(list[TriggerNode]): list of TriggerNodes containing
the sinks in the file.
Returns:
A string -> TriggerNode dict. | juraj-google-style |
def most_exposes(python_type):
_exposes = set()
try:
do_not_expose = set((python_type.__dir__(object) + ['__slots__', '__module__', '__weakref__']))
empty = python_type.__new__(python_type)
except AttributeError:
try:
_exposes = python_type.__slots__
except Attrib... | Core engine for the automatic generation of storable instances.
Finds the attributes exposed by the objects of a given type.
Mostly Python3-only.
Does not handle types which `__new__` method requires extra arguments either.
Arguments:
python_type (type): object type.
Returns:
list: attributes exposed. | codesearchnet |
def InspectZipFile(self, parser_mediator, zip_file):
try:
xml_data = zip_file.read('_rels/.rels')
property_files = self._ParseRelationshipsXMLFile(xml_data)
except (IndexError, IOError, KeyError, OverflowError, ValueError,
zipfile.BadZipfile) as exception:
parser_mediator.Prod... | Parses an OXML file-like object.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
zip_file (zipfile.ZipFile): the zip file containing OXML content. It is
not be closed in this method, but will be closed by the parser logic
in czip.py.
Raise... | juraj-google-style |
def GetUserByEmail(self, email):
user = self.rpc_helper.GetAccountInfoByEmail(email)
return GitkitUser.FromApiResponse(user) | Gets user info by email.
Args:
email: string, the user email.
Returns:
GitkitUser, containing the user info. | juraj-google-style |
def deserialize_subject_info(subject_info_xml):
try:
return d1_common.xml.deserialize(subject_info_xml)
except ValueError as e:
raise d1_common.types.exceptions.InvalidToken(0, 'Could not deserialize SubjectInfo. subject_info="{}", error="{}"'.format(subject_info_xml, str(e))) | Deserialize SubjectInfo XML doc to native object.
Args:
subject_info_xml: str
SubjectInfo XML doc
Returns:
SubjectInfo PyXB object | codesearchnet |
def url_is_project(url, default='not_a_func'):
try:
u = resolve(url)
if u and u.func != default:
return True
except Resolver404:
static_url = settings.STATIC_URL
static_url_wd = static_url.lstrip('/')
if url.startswith(static_url):
url = url[l... | Check if URL is part of the current project's URLs.
Args:
url (str): URL to check.
default (callable): used to filter out some URLs attached to function.
Returns: | juraj-google-style |
def ParseLSQuarantineRow(
self, parser_mediator, query, row, **unused_kwargs):
query_hash = hash(query)
event_data = LsQuarantineEventData()
event_data.agent = self._GetRowValue(query_hash, row, 'Agent')
event_data.data = self._GetRowValue(query_hash, row, 'Data')
event_data.query = quer... | Parses a launch services quarantine event row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row. | juraj-google-style |
def get_tracks_for_album(self, artist, album, full_album_art_uri=False):
subcategories = [artist, album]
result = self.get_album_artists(full_album_art_uri=full_album_art_uri, subcategories=subcategories, complete_result=True)
result._metadata['search_type'] = 'tracks_for_album'
return result | Get the tracks of an artist's album.
Args:
artist (str): an artist's name.
album (str): an album name.
full_album_art_uri: whether the album art URI should be
absolute (i.e. including the IP address). Default `False`.
Returns:
A `SearchResult` instance. | codesearchnet |
def port(self, value):
self._port = value
if value is None:
try:
del self._connectionXML.attrib['port']
except KeyError:
pass
else:
self._connectionXML.set('port', value) | Set the connection's port property.
Args:
value: New port value. String.
Returns:
Nothing. | juraj-google-style |
def _parse_query_key(self, key, val, is_escaped):
if key.endswith('__contains'):
key = key[:(- 10)]
val = self._parse_query_modifier('contains', val, is_escaped)
elif key.endswith('__range'):
key = key[:(- 7)]
val = self._parse_query_modifier('range', val, is_escaped)
elif ke... | Strips query modifier from key and call's the appropriate value modifier.
Args:
key (str): Query key
val: Query value
Returns:
Parsed query key and value. | codesearchnet |
def run(self):
while self.should_run:
try:
self.logger.debug(('Sending heartbeat, seq ' + last_sequence))
self.ws.send(json.dumps({'op': 1, 'd': last_sequence}))
except Exception as e:
self.logger.error(f'Got error in heartbeat: {str(e)}')
finally:
... | Runs the thread
This method handles sending the heartbeat to the Discord websocket server, so the connection
can remain open and the bot remain online for those commands that require it to be.
Args:
None | codesearchnet |
def Erase(self, partition, timeout_ms=None):
self._SimpleCommand(b'erase', arg=partition, timeout_ms=timeout_ms) | Erases the given partition.
Args:
partition: Partition to clear. | juraj-google-style |
def stage_tc_batch_xid(xid_type, xid_value, owner):
xid_string = '{}-{}-{}'.format(xid_type, xid_value, owner)
hash_object = hashlib.sha256(xid_string.encode('utf-8'))
return hash_object.hexdigest() | Create an xid for a batch job.
Args:
xid_type (str): [description]
xid_value (str): [description]
owner (str): [description]
Returns:
[type]: [description] | juraj-google-style |
def set_save_handler(save_handler: Optional[Callable[..., Any]]) -> Optional[Callable[..., Any]]:
if save_handler and (not callable(save_handler)):
raise ValueError('`save_handler` must be callable.')
global _SAVE_HANDLER
old_handler = _SAVE_HANDLER
_SAVE_HANDLER = save_handler
return old_ha... | Sets global save handler.
Args:
save_handler: A callable object that takes at least one argument as value to
save. `symbolic.save` method will pass through all arguments to this
handler and return its return value.
Returns:
Previous global save handler. | github-repos |
def _SetHeader(self, new_values):
row = self.row_class()
row.row = 0
for v in new_values:
row[v] = v
self._table[0] = row | Sets header of table to the given tuple.
Args:
new_values: Tuple of new header values. | juraj-google-style |
def estimate_motion(self, time, intensity_grid, max_u, max_v):
ti = np.where((time == self.times))[0][0]
mask_vals = np.where((self.masks[ti].ravel() == 1))
i_vals = self.i[ti].ravel()[mask_vals]
j_vals = self.j[ti].ravel()[mask_vals]
obj_vals = self.timesteps[ti].ravel()[mask_vals]
u_shifts = n... | Estimate the motion of the object with cross-correlation on the intensity values from the previous time step.
Args:
time: time being evaluated.
intensity_grid: 2D array of intensities used in cross correlation.
max_u: Maximum x-component of motion. Used to limit search area.
max_v: Maximum y-component of motion. Used ... | codesearchnet |
def ipv4_is_defined(address):
query_ip = IPv4Address(str(address))
results = namedtuple('ipv4_is_defined_results', 'is_defined, ietf_name, '
'ietf_rfc')
if query_ip in IPv4Network('0.0.0.0/8'):
return results(True, 'This Net... | The function for checking if an IPv4 address is defined (does not need to
be resolved).
Args:
address (:obj:`str`): An IPv4 address.
Returns:
namedtuple:
:is_defined (bool): True if given address is defined, otherwise
False
:ietf_name (str): IETF assignment name if given address is
defined, otherwise ''
:ietf_rfc (s... | juraj-google-style |
def fit_gaussian(samples, ddof=0):
if (len(samples.shape) == 1):
return (np.mean(samples), np.std(samples, ddof=ddof))
return (np.mean(samples, axis=1), np.std(samples, axis=1, ddof=ddof)) | Calculates the mean and the standard deviation of the given samples.
Args:
samples (ndarray): a one or two dimensional array. If one dimensional we calculate the fit using all
values. If two dimensional, we fit the Gaussian for every set of samples over the first dimension.
ddof (int): the difference degrees of freedo... | codesearchnet |
def timestamp(value, fmt=None):
if fmt:
return _timestamp_formats.get(fmt, (lambda v: timestamp_fmt(v, fmt)))(value)
l = len(value)
if ((19 <= l <= 24) and (value[3] == ' ')):
try:
return timestamp_d_b_Y_H_M_S(value)
except (KeyError, ValueError, OverflowError):
... | Parse a datetime to a unix timestamp.
Uses fast custom parsing for common datetime formats or the slow dateutil
parser for other formats. This is a trade off between ease of use and speed
and is very useful for fast parsing of timestamp strings whose format may
standard but varied or unknown prior to parsing.
Common ... | codesearchnet |
def has_relationship(self, left_id, left_type, right_id, right_type,
rel_type='Related To'):
data = self.get_object(left_id, left_type)
if not data:
raise CRITsOperationalError('Crits Object not found with id {}'
'and ... | Checks if the two objects are related
Args:
left_id: The CRITs ID of the first indicator
left_type: The CRITs TLO type of the first indicator
right_id: The CRITs ID of the second indicator
right_type: The CRITs TLO type of the second indicator
rel_type: The relationships type ("Related To", etc)
Returns:
True or False... | juraj-google-style |
def __init__(self, identifier):
super(FormatSpecification, self).__init__()
self.identifier = identifier
self.signatures = [] | Initializes a specification.
Args:
identifier (str): unique name for the format. | juraj-google-style |
class Mean(Metric):
def __init__(self, name='mean', dtype=None):
super().__init__(name=name, dtype=dtype)
self.total = self.add_variable(shape=(), initializer=initializers.Zeros(), dtype=self.dtype, name='total')
self.count = self.add_variable(shape=(), initializer=initializers.Zeros(), dty... | Compute the (weighted) mean of the given values.
For example, if values is `[1, 3, 5, 7]` then the mean is 4.
If `sample_weight` was specified as `[1, 1, 0, 0]` then the mean would be 2.
This metric creates two variables, `total` and `count`.
The mean value returned is simply `total` divided by `count`.
Args:
name: ... | github-repos |
def end_before(self, document_fields):
return self._cursor_helper(document_fields, before=True, start=False) | End query results before a particular document value.
The result set will **exclude** the document specified by
``document_fields``.
If the current query already has specified an end cursor -- either
via this method or
:meth:`~.firestore_v1beta1.query.Query.end_at` -- this will
overwrite it.
When the query is sent t... | codesearchnet |
def request(self, request):
url = "{}{}".format(self._base_url, request.path)
timeout = self.poll_timeout
if request.stream is True:
timeout = self.stream_timeout
try:
http_response = self._session.request(
request.method,
... | Perform an HTTP request through the context
Args:
request: A v20.request.Request object
Returns:
A v20.response.Response object | juraj-google-style |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.