code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def _ProcessFileEntry(self, mediator, file_entry):
display_name = mediator.GetDisplayName()
logger.debug(
'[ProcessFileEntry] processing file entry: {0:s}'.format(display_name))
reference_count = mediator.resolver_context.GetFileObjectReferenceCount(
file_entry.path_spec)
try:
... | Processes a file entry.
Args:
mediator (ParserMediator): mediates the interactions between
parsers and other components, such as storage and abort signals.
file_entry (dfvfs.FileEntry): file entry. | juraj-google-style |
def wait_for_batches(self, batch_ids, timeout=None):
self._batch_tracker.watch_statuses(self, batch_ids)
timeout = timeout or DEFAULT_TIMEOUT
start_time = time()
with self._wait_condition:
while True:
if self._statuses is not None:
... | Locks until a list of batch ids is committed to the block chain
or a timeout is exceeded. Returns the statuses of those batches.
Args:
batch_ids (list of str): The ids of the batches to wait for
timeout(int): Maximum time in seconds to wait for
Returns:
list of BatchStatus: BatchStatuses to send back to client | juraj-google-style |
def ParseCmd(self, cmd_input, attributes=None, templates=None):
self.raw = cmd_input
if not templates:
row_idx = self.index.GetRowMatch(attributes)
if row_idx:
templates = self.index.index[row_idx]["Template"]
else:
... | Creates a TextTable table of values from cmd_input string.
Parses command output with template/s. If more than one template is found
subsequent tables are merged if keys match (dropped otherwise).
Args:
cmd_input: String, Device/command response.
attributes: Dict, attribute that further refine matching template.
templa... | juraj-google-style |
def is_global(self):
return ((not ((self.network_address in IPv4Network('100.64.0.0/10')) and (self.broadcast_address in IPv4Network('100.64.0.0/10')))) and (not self.is_private)) | Test if this address is allocated for public networks.
Returns:
A boolean, True if the address is not reserved per
iana-ipv4-special-registry. | codesearchnet |
def _query(self, query_type, query_str, verbose=False):
cached = self.query_cache.get(query_str)
if cached:
if verbose:
print('Returning Cached VT Query Results')
return cached
if query_type == 'file':
response = req... | Internal query method for the VirusTotal Service
Args:
query_type(str): The type of query (either 'file' or 'url')
query_str (str): The file hash or domain/url to be queried | juraj-google-style |
def zeros(shape, dtype=None, **kwargs):
data = np.zeros(shape, dtype)
return dc.array(data, **kwargs) | Create an array of given shape and type, filled with zeros.
Args:
shape (sequence of ints): 2D shape of the array.
dtype (data-type, optional): Desired data-type for the array.
kwargs (optional): Other arguments of the array (*coords, attrs, and name).
Returns:
array (decode.array): Decode array filled with zeros. | juraj-google-style |
def GetCredential(self, path_spec, identifier):
credentials = self._credentials_per_path_spec.get(path_spec.comparable, {})
return credentials.get(identifier, None) | Retrieves a specific credential from the key chain.
Args:
path_spec (PathSpec): path specification.
identifier (str): credential identifier.
Returns:
object: credential or None if the credential for the path specification
is not set. | codesearchnet |
def init_cache(self, batch_size, max_length):
input_ids = jnp.ones((batch_size, max_length), dtype='i4')
attention_mask = jnp.ones_like(input_ids, dtype='i4')
position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_ids.shape)
init_variables = self.module.init(jax.random.PR... | Args:
batch_size (`int`):
batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
max_length (`int`):
maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized
cache. | github-repos |
def update(self, domain, type_name, search_command, body):
return self._request(domain, type_name, search_command, 'PUT', body) | Update entry in ThreatConnect Data Store
Args:
domain (string): One of 'local', 'organization', or 'system'.
type_name (string): This is a free form index type name. The ThreatConnect API will use
this resource verbatim.
search_command (string): Search command to pass to ES.
body (str): JSON body | juraj-google-style |
def key_validation_check(tweet_keys_list, superset_keys, minset_keys):
tweet_keys = set(tweet_keys_list)
minset_overlap = (tweet_keys & minset_keys)
if (minset_overlap != minset_keys):
raise UnexpectedFormatError('keys ({}) missing from Tweet (Public API data is not supported)'.format((minset_keys -... | Validates the keys present in a Tweet.
Args:
tweet_keys_list (list): the keys present in a tweet
superset_keys (set): the set of all possible keys for a tweet
minset_keys (set): the set of minimal keys expected in a tweet.
Returns:
0 if no errors
Raises:
UnexpectedFormatError on any mismatch of keys. | codesearchnet |
def add(self, coro, *args, **kw):
if asyncio.iscoroutinefunction(coro):
coro = coro(*args, **kw)
if (not asyncio.iscoroutine(coro)):
raise TypeError('paco: coro must be a coroutine object')
index = max(len(self.pool), 0)
task = Task(index, coro)
self.pool.append(task)
return coro | Adds a new coroutine function with optional variadic argumetns.
Arguments:
coro (coroutine function): coroutine to execute.
*args (mixed): optional variadic arguments
Raises:
TypeError: if the coro object is not a valid coroutine
Returns:
future: coroutine wrapped future | codesearchnet |
def charge_balance(model):
compound_charge = {}
for compound in model.compounds:
if compound.charge is not None:
compound_charge[compound.id] = compound.charge
for reaction in model.reactions:
charge = reaction_charge(reaction.equation, compound_charge)
yield react... | Calculate the overall charge for all reactions in the model.
Yield (reaction, charge) pairs.
Args:
model: :class:`psamm.datasource.native.NativeModel`. | juraj-google-style |
def clip_range(nodes1, nodes2):
(coeff_a, coeff_b, coeff_c, d_min, d_max) = compute_fat_line(nodes1)
(_, num_nodes2) = nodes2.shape
polynomial = np.empty((2, num_nodes2), order='F')
denominator = float((num_nodes2 - 1))
for index in six.moves.xrange(num_nodes2):
polynomial[(0, index)] = (ind... | r"""Reduce the parameter range where two curves can intersect.
Does so by using the "fat line" for ``nodes1`` and computing the
distance polynomial against ``nodes2``.
.. note::
This assumes, but does not check that the curves being considered
will only have one intersection in the parameter ranges
:math:`s \in \lef... | codesearchnet |
def from_file(cls, filename, *, strict=True):
config = cls()
config.load_from_file(filename, strict=strict)
return config | Create a new Config object from a configuration file.
Args:
filename (str): The location and name of the configuration file.
strict (bool): If true raises a ConfigLoadError when the configuration
cannot be found.
Returns:
An instance of the Config class.
Raises:
ConfigLoadError: If the configuration cannot be found. | codesearchnet |
def MakeSimpleProtoClass(fields, full_name=None, pool=None):
factory = message_factory.MessageFactory(pool=pool)
if full_name is not None:
try:
proto_cls = _GetMessageFromFactory(factory, full_name)
return proto_cls
except KeyError:
pass
field_items = fields.items()
... | Create a Protobuf class whose fields are basic types.
Note: this doesn't validate field names!
Args:
fields: dict of {name: field_type} mappings for each field in the proto. If
this is an OrderedDict the order will be maintained, otherwise the
fields will be sorted by name.
full_name: optional str, the fully-qualifie... | juraj-google-style |
def _get_example_from_properties(self, spec):
local_spec = deepcopy(spec)
additional_property = False
if ('additionalProperties' in local_spec):
additional_property = True
if ('properties' not in local_spec):
local_spec['properties'] = {}
local_spec['properties'].update({... | Get example from the properties of an object defined inline.
Args:
prop_spec: property specification you want an example of.
Returns:
An example for the given spec
A boolean, whether we had additionalProperties in the spec, or not | codesearchnet |
def _get_suffix(path):
suffix = os.path.basename(path).split('.')[(- 1)]
if ('/' in suffix):
raise UserWarning(("Filename can't contain '/' in suffix (%s)!" % path))
return suffix | Return suffix from `path`.
``/home/xex/somefile.txt`` --> ``txt``.
Args:
path (str): Full file path.
Returns:
str: Suffix.
Raises:
UserWarning: When ``/`` is detected in suffix. | codesearchnet |
def write_string_to_file(filename, file_content):
with FileIO(filename, mode='w') as f:
f.write(file_content) | Writes a string to a given file.
Args:
filename: string, path to a file
file_content: string, contents that need to be written to the file
Raises:
errors.OpError: If there are errors during the operation. | github-repos |
def baredoc(obj):
doc = getdoc(obj)
if not doc:
return ''
doc = doc.splitlines()[0]
return doc.rstrip(' .').lstrip() | Return the first line of the docstring of an object.
Trailing periods and spaces as well as leading spaces are removed from the
output.
Args:
obj: any Python object.
Returns:
str: the first line of the docstring of obj. | juraj-google-style |
def add_field(self, fieldname, fieldspec=whoosh_module_fields.TEXT):
self._whoosh.add_field(fieldname, fieldspec)
return self._whoosh.schema | Add a field in the index of the model.
Args:
fieldname (Text): This parameters register a new field in specified model.
fieldspec (Name, optional): This option adds various options as were described before.
Returns:
TYPE: The new schema after deleted is returned. | codesearchnet |
def create_projection(self, fov: float = 75.0, near: float = 1.0, far: float = 100.0, aspect_ratio: float = None):
return matrix44.create_perspective_projection_matrix(
fov,
aspect_ratio or self.window.aspect_ratio,
near,
far,
dtype='f4',
... | Create a projection matrix with the following parameters.
When ``aspect_ratio`` is not provided the configured aspect
ratio for the window will be used.
Args:
fov (float): Field of view (float)
near (float): Camera near value
far (float): Camrea far value
Keyword Args:
aspect_ratio (float): Aspect ratio of the viewpo... | juraj-google-style |
def _randomized_roundoff_to_bfloat16(x, noise, cand1, cand2):
cand1_f = tf.to_float(cand1)
cand2_f = tf.to_float(cand2)
step_size = (cand2_f - cand1_f)
fpart = ((x - cand1_f) / step_size)
ret = tf.where(tf.greater(fpart, noise), cand2, cand1)
return ret | Round-off x to cand1 or to cand2 in an unbiased way.
Cand1 and cand2 are the same shape as x.
For every element of x, the corresponding elements of cand1 and cand2 should
be the two closest bfloat16 values to x. Order does not matter.
cand1 and cand2 must differ from each other.
Args:
x: A float32 Tensor.
noise: A T... | codesearchnet |
def protorpc_to_endpoints_error(self, status, body):
try:
rpc_error = self.__PROTOJSON.decode_message(remote.RpcStatus, body)
except (ValueError, messages.ValidationError):
rpc_error = remote.RpcStatus()
if (rpc_error.state == remote.RpcStatus.State.APPLICATION_ERROR):
error_class = ... | Convert a ProtoRPC error to the format expected by Google Endpoints.
If the body does not contain an ProtoRPC message in state APPLICATION_ERROR
the status and body will be returned unchanged.
Args:
status: HTTP status of the response from the backend
body: JSON-encoded error in format expected by Endpoints frontend.... | codesearchnet |
def optimize(objective_function, domain,
stopping_condition, parameters=None,
position_update=functions.std_position,
velocity_update=functions.std_velocity,
parameter_update=functions.std_parameter_update,
measurements=(),
measurer=dictionar... | Perform particle swarm optimization of the given fitness function.
Args:
objective_function: the cost function to optimize.
stopping_condition: function specifying the stopping condition.
parameters: dictionary: parameter dictionary for the PSO.
Returns:
cipy.algorithms.pso.Particle: The global best particle. | juraj-google-style |
def get_metric_by_name(self, metric_name, **kwargs):
return self._get_object_by_name(self._METRIC_ENDPOINT_SUFFIX, metric_name, **kwargs) | get a metric by name
Args:
metric_name (string): name of metric
Returns:
dictionary of response | codesearchnet |
def load(self, response):
self._response = response
if self.next_location(raw=True):
self._num_redirects += 1 | Load the response and increment the counter.
Args:
response (:class:`.http.request.Response`): The response from
a previous request. | codesearchnet |
def load_delivery_report(adapter: MongoAdapter, report_path: str, case_id: str, update: bool=False):
case_obj = adapter.case(case_id=case_id)
if (case_obj is None):
raise DataNotFoundError('no case found')
if (not case_obj.get('delivery_report')):
_put_report_in_case_root(case_obj, report_pa... | Load a delivery report into a case in the database
If the report already exists the function will exit.
If the user want to load a report that is already in the database
'update' has to be 'True'
Args:
adapter (MongoAdapter): Connection to the database
report_path (string): Path to delivery report
case_id ... | codesearchnet |
def save_forensic_reports_to_kafka(self, forensic_reports, forensic_topic):
if type(forensic_reports) == dict:
forensic_reports = [forensic_reports]
if len(forensic_reports) < 1:
return
try:
logger.debug("Saving forensic reports to Kafka")
... | Saves forensic DMARC reports to Kafka, sends individual
records (slices) since Kafka requires messages to be <= 1MB
by default.
Args:
forensic_reports (list): A list of forensic report dicts
to save to Kafka
forensic_topic (str): The name of the Kafka topic | juraj-google-style |
def WriteStatEntries(stat_entries, client_id, mutation_pool, token=None):
for stat_response in stat_entries:
if stat_response.pathspec.last.stream_name:
stat_response.st_mode &= (~ stat_type_mask)
stat_response.st_mode |= stat.S_IFREG
if data_store.AFF4Enabled():
for stat... | Persists information about stat entries.
Args:
stat_entries: A list of `StatEntry` instances.
client_id: An id of a client the stat entries come from.
mutation_pool: A mutation pool used for writing into the AFF4 data store.
token: A token used for writing into the AFF4 data store. | codesearchnet |
def get_session(db_url):
engine = create_engine(db_url, poolclass=NullPool, echo=False)
Session = sessionmaker(bind=engine)
Base.metadata.create_all(engine)
return Session() | Gets SQLAlchemy session given url. Your tables must inherit
from Base in hdx.utilities.database.
Args:
db_url (str): SQLAlchemy url
Returns:
sqlalchemy.orm.session.Session: SQLAlchemy session | juraj-google-style |
def get_ip_prefixes_from_config(config, services, ip_version):
ip_prefixes = set()
for service in services:
ip_prefix = ipaddress.ip_network(config.get(service, 'ip_prefix'))
if (ip_prefix.version == ip_version):
ip_prefixes.add(ip_prefix.with_prefixlen)
return ip_prefixes | Build a set of IP prefixes found in service configuration files.
Arguments:
config (obg): A configparser object which holds our configuration.
services (list): A list of section names which are the name of the
service checks.
ip_version (int): IP protocol version
Returns:
A set of IP prefixes. | codesearchnet |
def as_graph(self, depth=0):
if depth in self._graph_cache:
return self._graph_cache[depth]
self._graph_cache[depth] = graph = Graph(self, depth=depth)
return graph | Create a graph with self as node, cache it, return it.
Args:
depth (int): depth of the graph.
Returns:
Graph: an instance of Graph. | juraj-google-style |
def _launch_cli(self):
self._register_this_run_info(self._run_cli)
response = self._run_cli.run_ui(init_command=self._init_command, title=self._title, title_color=self._title_color)
return response | Launch the interactive command-line interface.
Returns:
The OnRunStartResponse specified by the user using the "run" command. | github-repos |
def _wait_after(provider, job_ids, poll_interval, stop_on_failure):
job_ids_to_check = {j for j in job_ids if (j != dsub_util.NO_JOB)}
error_messages = []
while (job_ids_to_check and ((not error_messages) or (not stop_on_failure))):
print(('Waiting for: %s.' % ', '.join(job_ids_to_check)))
j... | Print status info as we wait for those jobs.
Blocks until either all of the listed jobs succeed,
or one of them fails.
Args:
provider: job service provider
job_ids: a set of job IDs (string) to wait for
poll_interval: integer seconds to wait between iterations
stop_on_failure: whether to stop waiting if one of the ta... | codesearchnet |
def last_updated(self, path):
return self._gcsIO().last_updated(path) | Get UNIX Epoch time in seconds on the FileSystem.
Args:
path: string path of file.
Returns: float UNIX Epoch time
Raises:
``BeamIOError``: if path doesn't exist. | github-repos |
def _HasDuplicateRegistryKeyPaths(
self, filename, artifact_definition, source):
result = False
intersection = self._artifact_registry_key_paths.intersection(
set(source.keys))
if intersection:
duplicate_key_paths = '\n'.join(intersection)
logging.warning((
'Artifact... | Checks if Registry key paths are not already defined by other artifacts.
Note that at the moment this function will only find exact duplicate
Registry key paths.
Args:
filename (str): name of the artifacts definition file.
artifact_definition (ArtifactDefinition): artifact definition.
source (SourceType): source defi... | juraj-google-style |
def scored_to_phenotype(self,phenotypes):
def _apply_score(scored_calls,phenotypes):
present = sorted(list(set(phenotypes)&set(scored_calls.keys())))
total = sum([scored_calls[x] for x in present])
if total > 1:
raise ValueError("You cant extract phe... | Convert binary pehnotypes to mutually exclusive phenotypes.
If none of the phenotypes are set, then phenotype_label becomes nan
If any of the phenotypes are multiply set then it throws a fatal error.
Args:
phenotypes (list): a list of scored_names to convert to phenotypes
Returns:
CellDataFrame | juraj-google-style |
def export(self, name=None):
with tf.name_scope(name or '%s_lookup_table_export' % self._name):
keys, values = gen_simple_hash_table_op.examples_simple_hash_table_export(self.resource_handle, key_dtype=self._key_dtype, value_dtype=self._value_dtype)
return (keys, values) | Export all `key` and `value` pairs.
Args:
name: A name for the operation (optional).
Returns:
A tuple of two tensors, the first with the `keys` and the second with
the `values`. | github-repos |
def transform_content(tags, content_transformer):
if type(tags) not in [tuple, list]:
tags = [tags]
for tag in tags:
new_child = dhtmlparser.HTMLElement(content_transformer(tag))
if hasattr(tag, "parent"):
new_child.parent = tag
tag.childs = [new_chil... | Transform content in all `tags` using result of `content_transformer(tag)`
call.
Args:
tags (obj/list): HTMLElement instance, or list of HTMLElement
instances.
content_transformer (function): Function which is called as
``content_transformer(tag)``. | juraj-google-style |
def _parse_hextet(self, hextet_str):
if not self._HEX_DIGITS.issuperset(hextet_str):
raise ValueError
if len(hextet_str) > 4:
raise ValueError
hextet_int = int(hextet_str, 16)
if hextet_int > 0xFFFF:
raise ValueError
return hext... | Convert an IPv6 hextet string into an integer.
Args:
hextet_str: A string, the number to parse.
Returns:
The hextet as an integer.
Raises:
ValueError: if the input isn't strictly a hex number from [0..FFFF]. | juraj-google-style |
def AsDict(self, dt=True):
data = {}
if self.sharekey:
data['sharekey'] = self.sharekey
if self.name:
data['name'] = self.name
if self.user:
data['user'] = self.user.AsDict()
if self.title:
data['title'] = self.title
... | A dict representation of this Shake instance.
The return value uses the same key names as the JSON representation.
Args:
dt (bool): If True, return dates as python datetime objects. If
False, return dates as ISO strings.
Return:
A dict representing this Shake instance | juraj-google-style |
def from_json_str(cls, json_str: str, primitive_cls: Type[message.Message], context: Context) -> 'PrimitiveWrapper': | Serializes json_str into an instance of primitive_cls and wraps.
Args:
json_str: The string-representation of the raw json_value to serialize
into primitive_cls and wrap.
primitive_cls: The FHIR primitive class to serialize into and wrap.
context: Related primitive information to use for printing/parsing a
wrapped pri... | github-repos |
def does_attribute_meet_condition(self, attribute, conditions):
if conditions is None or len(conditions) == 0:
return True
for attribute_name, attribute_value in conditions.items():
value = getattr(attribute, attribute_name, False)
if value != attribute_valu... | Check if the attribute meet all the given conditions
Args:
attribute: the attribute information
conditions: a dictionary of condition to match
Returns:
True if the attribute match all conditions. False otherwise | juraj-google-style |
def _repr_to_list(value: torch.Tensor):
torch.set_printoptions(sci_mode=True, linewidth=120)
with StringIO() as buf, redirect_stdout(buf):
print(value)
raw = buf.getvalue()
return _sanitize_repr_for_diff(raw).splitlines() | Converts a tensor into a sanitized multi-line string representation.
Args:
value (`torch.Tensor`): The tensor to represent.
Returns:
`List[str]`: List of string lines representing the tensor. | github-repos |
def open_if_needed(self, mode=None):
was_open = self.is_open()
if not was_open:
self.open(mode=mode)
try:
yield self
finally:
if not was_open:
self.close() | Convenience context-manager for the use with ``with``.
Opens the container if not already done.
Only closes the container if it was opened within this context.
Args:
mode (str): Either 'r' for read-only, 'w' for truncate and write or
'a' for append. (default: 'a').
If ``None``, uses ``self.mode``. | juraj-google-style |
def get_field(proto: message.Message, fields: FieldTypes) -> tuple[Any, Optional[descriptor.FieldDescriptor]]:
field_proto = proto
field_desc = None
for field_proto, field_desc, _, _ in _walk_fields(proto, fields):
pass
return (field_proto, field_desc) | Returns the field and field descriptor from the proto.
Args:
proto: Parent proto of any message type.
fields: List of string/int/map key fields, e.g. ["nodes", "attr", "value"]
can represent `proto.nodes.attr["value"]`.
Returns:
Tuple of (
Field in the proto or `None` if none are found,
Field descriptor
) | github-repos |
def get(cls, blob_key, **ctx_options):
fut = cls.get_async(blob_key, **ctx_options)
return fut.get_result() | Retrieve a BlobInfo by key.
Args:
blob_key: A blob key. This may be a str, unicode or BlobKey instance.
**ctx_options: Context options for Model().get_by_id().
Returns:
A BlobInfo entity associated with the provided key, If there was
no such entity, returns None. | juraj-google-style |
def mark_experimental(fn):
@wraps(fn)
def wrapper(*args, **kw):
from peltak.core import shell
if shell.is_tty:
warnings.warn('This command is has experimental status. The interface is not yet stable and might change without notice within with a patch version update. Use at your own ... | Mark function as experimental.
Args:
fn (FunctionType):
The command function to decorate. | codesearchnet |
def _create_record_internal(self, rtype, name, content, identifier=None):
name = (self._relative_name(name) if (name is not None) else name)
LOGGER.debug('Creating record with name %s', name)
if self._is_duplicate_record(rtype, name, content):
return True
data = self._get_post_data_to_create_dns... | Create a new DNS entry in the domain zone if it does not already exist.
Args:
rtype (str): The DNS type (e.g. A, TXT, MX, etc) of the new entry.
name (str): The name of the new DNS entry, e.g the domain for which a
MX entry shall be valid.
content (str): The content of the new DNS entry, e.g. the mail server
hostname ... | codesearchnet |
def create_output(self, key, value, variable_type=None):
results = None
if key is not None:
key = key.strip()
key_type = '{}-{}'.format(key, variable_type)
if self.out_variables_type.get(key_type) is not None:
v = self.out_var... | Wrapper for Create method of CRUD operation for working with KeyValue DB.
This method will automatically check to see if provided variable was requested by
a downstream app and if so create the data in the KeyValue DB.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
vari... | juraj-google-style |
def port_tag_details(cls, tags):
for tag in tags:
match = port_tag_re.match(tag)
if match:
source_sink, port, extra = match.groups()
return source_sink == "source", cls(port), extra | Search tags for port info, returning it
Args:
tags: A list of tags to check
Returns:
None or (is_source, port, connected_value|disconnected_value)
where port is one of the Enum entries of Port | juraj-google-style |
def topological_sort(data):
def check_self_dependencies(input_data):
for k, v in input_data.items():
if k in v:
raise ValueError('Self-dependency, {} depends on itself.'.format(k))
def prepare_input_data(input_data):
return {k: set(v) for k, v... | Topological sort the given dictionary structure.
Args:
data (dict); dictionary structure where the value is a list of dependencies for that given key.
For example: ``{'a': (), 'b': ('a',)}``, where ``a`` depends on nothing and ``b`` depends on ``a``.
Returns:
tuple: the dependencies in constructor order | juraj-google-style |
async def get_tournaments(self, subdomain: str = None, force_update: bool = False) -> list:
if self.tournaments is None:
force_update = True
self._subdomains_searched.append('' if subdomain is None else subdomain)
elif subdomain is None and '' not in self._subdomains_sea... | gets all user's tournaments
|methcoro|
Args:
subdomain: *optional* subdomain needs to be given explicitely to get tournaments in a subdomain
force_update: *optional* set to True to force the data update from Challonge
Returns:
list[Tournament]: list of all the user tournaments
Raises:
APIException | juraj-google-style |
def set_hostname(self, value=None, default=False, disable=False):
cmd = self.command_builder('hostname', value=value, default=default,
disable=disable)
return self.configure(cmd) | Configures the global system hostname setting
EosVersion:
4.13.7M
Args:
value (str): The hostname value
default (bool): Controls use of the default keyword
disable (bool): Controls the use of the no keyword
Returns:
bool: True if the commands are completed successfully | juraj-google-style |
def _insert(self, item, feed_item):
return self._api().insert(profileId=self.profile_id, body=item).execute() | Inserts a new item into CM.
Args:
item: The CM object to insert.
feed_item: The feed item from the Bulkdozer feed representing the item to
insert.
Returns:
The CM object representing the item inserted. | github-repos |
def pull(self, project, run=None, entity=None):
(project, run) = self.parse_slug(project, run=run)
urls = self.download_urls(project, run, entity)
responses = []
for fileName in urls:
(_, response) = self.download_write_file(urls[fileName])
if response:
responses.append(respo... | Download files from W&B
Args:
project (str): The project to download
run (str, optional): The run to upload to
entity (str, optional): The entity to scope this project to. Defaults to wandb models
Returns:
The requests library response object | codesearchnet |
def _GetPathSegmentSeparator(self, path):
if path.startswith('\\') or path[1:].startswith(':\\'):
return '\\'
if path.startswith('/'):
return '/'
if '/' and '\\' in path:
forward_count = len(path.split('/'))
backward_count = len(path.split('\\'))
if forward_count... | Given a path give back the path separator as a best guess.
Args:
path (str): path.
Returns:
str: path segment separator. | juraj-google-style |
def forward(self, hidden_states: List[torch.Tensor], patch_height, patch_width) -> List[torch.Tensor]:
if not isinstance(hidden_states, (tuple, list)):
raise TypeError('hidden_states should be a tuple or list of tensors')
if len(hidden_states) != len(self.config.neck_hidden_sizes):
raise ValueEr... | Args:
hidden_states (`List[torch.FloatTensor]`, each of shape `(batch_size, sequence_length, hidden_size)` or `(batch_size, hidden_size, height, width)`):
List of hidden states from the backbone. | github-repos |
def __init__(self, profile_id: str, profile_location: Optional[str]=None, log_results: bool=False, file_copy_fn: Optional[Callable[[str, str], None]]=None, time_prefix: str='%Y-%m-%d_%H_%M_%S-', enable_cpu_profiling: bool=False, enable_memory_profiling: bool=False):
self.profile_id = str(profile_id)
self.profil... | Creates a Profile object.
Args:
profile_id: Unique id of the profiling session.
profile_location: The file location where the profiling results will be
stored.
log_results: Log the result to console if true.
file_copy_fn: Lambda function for copying files.
time_prefix: Format of the timestamp prefix in profiling resul... | github-repos |
def materialize(self, ref, table_name=None, index_columns=None, logger=None):
from ambry.library import Library
assert isinstance(self._library, Library)
logger.debug('Materializing warehouse partition.\n partition: {}'.format(ref))
partition = self._library.partition(ref)
connection = self._back... | Creates materialized table for given partition reference.
Args:
ref (str): id, vid, name or vname of the partition.
Returns:
str: name of the partition table in the database. | codesearchnet |
def thermal_conductivity(self, temperature, volume):
gamma = self.gruneisen_parameter(temperature, volume)
theta_d = self.debye_temperature(volume)
theta_a = theta_d * self.natoms**(-1./3.)
prefactor = (0.849 * 3 * 4**(1./3.)) / (20. * np.pi**3)
prefactor = ... | Eq(17) in 10.1103/PhysRevB.90.174107
Args:
temperature (float): temperature in K
volume (float): in Ang^3
Returns:
float: thermal conductivity in W/K/m | juraj-google-style |
def visit_invoke_reference(self, identifier: InvokeReferenceNode) -> Any:
return self.visit_invoke_expression(identifier) | Allows visitors to implement custom Reference logic.
By default, calls `visit_invoke_expression`. Subclasses may override this
method to introduce custom logic for handling references.
This function is called when the 'reference' identifier is invoked against a
FHIR Reference resource. The visit_invoke_expression fun... | github-repos |
def verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATION_CERTS):
_require_crypto_or_die()
if (http is None):
http = transport.get_cached_http()
(resp, content) = transport.request(http, cert_uri)
if (resp.status == http_client.OK):
certs = json.loads(_helpers._fr... | Verifies a signed JWT id_token.
This function requires PyOpenSSL and because of that it does not work on
App Engine.
Args:
id_token: string, A Signed JWT.
audience: string, The audience 'aud' that the token should be for.
http: httplib2.Http, instance to use to make the HTTP request. Callers
should supply an instance... | codesearchnet |
def _get_single_variable(self, name, shape=None, dtype=dtypes.float32, initializer=None, regularizer=None, partition_info=None, reuse=None, trainable=None, collections=None, caching_device=None, validate_shape=True, use_resource=None, constraint=None, synchronization=VariableSynchronization.AUTO, aggregation=VariableAg... | Get or create a single Variable (e.g.
a shard or entire variable).
See the documentation of get_variable above (ignore partitioning components)
for details.
Args:
name: see get_variable.
shape: see get_variable.
dtype: see get_variable.
initializer: see get_variable.
regularizer: see get_variable.
partition_info: _P... | github-repos |
def generate_lars_path(weighted_data, weighted_labels):
x_vector = weighted_data
(alphas, _, coefs) = lars_path(x_vector, weighted_labels, method='lasso', verbose=False)
return (alphas, coefs) | Generates the lars path for weighted data.
Args:
weighted_data: data that has been weighted by kernel
weighted_label: labels, weighted by kernel
Returns:
(alphas, coefs), both are arrays corresponding to the
regularization parameter and coefficients, respectively | codesearchnet |
def snr(*args, **kwargs):
squeeze = False
max_length = 0
for arg in args:
try:
length = len(arg)
if (length > max_length):
max_length = length
except TypeError:
pass
if (max_length == 0):
squeeze = True
kwargs['length'] = ma... | Compute the SNR of binaries.
snr is a function that takes binary parameters and sensitivity curves as inputs,
and returns snr for chosen phases.
Warning: All binary parameters must be either scalar, len-1 arrays,
or arrays of the same length. All of these can be used at once. However,
you cannot input multiple arrays... | codesearchnet |
def _get_showcase_dataset_dict(self, dataset):
if isinstance(dataset, hdx.data.dataset.Dataset) or isinstance(dataset, dict):
if 'id' not in dataset:
dataset = hdx.data.dataset.Dataset.read_from_hdx(dataset['name'])
dataset = dataset['id']
elif n... | Get showcase dataset dict
Args:
showcase (Union[Showcase,Dict,str]): Either a showcase id or Showcase metadata from a Showcase object or dictionary
Returns:
Dict: showcase dataset dict | juraj-google-style |
def _CheckIsDevice(self, file_entry):
if definitions.FILE_ENTRY_TYPE_DEVICE not in self._file_entry_types:
return False
return file_entry.IsDevice() | Checks the is_device find specification.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if not. | juraj-google-style |
def clean_args(self, args, keys):
for k in keys:
if getattr(args, k) is None:
delattr(args, k) | Clean None values out of the arg namespace.
This lets us check for a config file arg based on whether the None default
was overwritten.
Args:
args: an argparse.Namespace.
keys: Keys to clean if None | github-repos |
def transform(self, col):
out = pd.DataFrame(index=col.index)
out[self.col_name] = col.fillna(self.default_value)
out[self.new_name] = (pd.notnull(col) * 1).astype(int)
return out | Prepare the transformer to convert data and return the processed table.
Args:
col(pandas.DataFrame): Data to transform.
Returns:
pandas.DataFrame | juraj-google-style |
def bdp(tickers, flds, **kwargs):
logger = logs.get_logger(bdp, level=kwargs.pop('log', logs.LOG_LEVEL))
con, _ = create_connection()
ovrds = assist.proc_ovrds(**kwargs)
logger.info(
f'loading reference data from Bloomberg:\n'
f'{assist.info_qry(tickers=tickers, flds=flds)}'
)
... | Bloomberg reference data
Args:
tickers: tickers
flds: fields to query
**kwargs: bbg overrides
Returns:
pd.DataFrame
Examples:
>>> bdp('IQ US Equity', 'Crncy', raw=True)
ticker field value
0 IQ US Equity Crncy USD
>>> bdp('IQ US Equity', 'Crncy').reset_index()
ticker crncy
0 IQ US Equity USD | juraj-google-style |
def load_subclasses(klass, modules=None):
if modules:
if isinstance(modules, six.string_types):
modules = [modules]
loader = Loader()
loader.load(*modules)
return klass.__subclasses__() | Load recursively all all subclasses from a module.
Args:
klass (str or list of str): Class whose subclasses we want to load.
modules: List of additional modules or module names that should be
recursively imported in order to find all the subclasses of the
desired class. Default: None
FIXME: This function is kept only... | codesearchnet |
def relative_humidity(self, value=999):
if value is not None:
try:
value = int(value)
except ValueError:
raise ValueError('value {} need to be of type int '
'for field `relative_humidity`'.format(value))
... | Corresponds to IDD Field `relative_humidity`
Args:
value (int): value for IDD Field `relative_humidity`
value >= 0
value <= 110
Missing value: 999
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises:
ValueError: if `value` is not a valid value | juraj-google-style |
def to_tensor_list(element_spec, element):
return _to_tensor_list_helper(lambda state, spec, component: state + spec._to_tensor_list(component), element_spec, element) | Returns a tensor list representation of the element.
Args:
element_spec: A nested structure of `tf.TypeSpec` objects representing to
element type specification.
element: The element to convert to tensor list representation.
Returns:
A tensor list representation of `element`.
Raises:
ValueError: If `element_spec` and... | github-repos |
def write_tarball(voevents, filepath):
tuple_gen = ( (v.ivorn, v.xml) for v in voevents)
return write_tarball_from_ivorn_xml_tuples(tuple_gen,
filepath) | Iterate over voevent models / dbrows and write to bz'd tarball.
Args:
voevents (iterable): An iterable (e.g. list) of e.g. Voevent db-rows,
with access to the 'ivorn' and 'xml' attributes.
filepath (string): Path to the new tarball to create. Typically of form
'/path/to/foo.tar.bz2'
Returns
packet_count (int): Number ... | juraj-google-style |
def AcceptableMimeType(accept_patterns, mime_type):
if ('/' not in mime_type):
raise exceptions.InvalidUserInputError(('Invalid MIME type: "%s"' % mime_type))
unsupported_patterns = [p for p in accept_patterns if (';' in p)]
if unsupported_patterns:
raise exceptions.GeneratedClientError(('MI... | Return True iff mime_type is acceptable for one of accept_patterns.
Note that this function assumes that all patterns in accept_patterns
will be simple types of the form "type/subtype", where one or both
of these can be "*". We do not support parameters (i.e. "; q=") in
patterns.
Args:
accept_patterns: list of accept... | codesearchnet |
def get_item_concept_mapping(self, lang):
concepts = self.filter(active=True, lang=lang)
return group_keys_by_value_lists(Concept.objects.get_concept_item_mapping(concepts, lang)) | Get mapping of items_ids to concepts containing these items
Args:
lang (str): language of concepts
Returns:
dict: item (int) -> set of concepts (int) | juraj-google-style |
def get_lonlatalts(self):
band = self.filehandle
((xpoints, ypoints), (gcp_lons, gcp_lats, gcp_alts), (gcps, crs)) = self.get_gcps()
longitudes = interpolate_xarray(xpoints, ypoints, gcp_lons, band.shape)
latitudes = interpolate_xarray(xpoints, ypoints, gcp_lats, band.shape)
altitudes = interpolate_... | Obtain GCPs and construct latitude and longitude arrays.
Args:
band (gdal band): Measurement band which comes with GCP's
array_shape (tuple) : The size of the data array
Returns:
coordinates (tuple): A tuple with longitude and latitude arrays | codesearchnet |
def get(self):
chunk_size = self._smallest_buffer()
all_full = self._all_full()
if all_full:
right_context = 0
num_frames = (chunk_size - self.current_left_context)
else:
right_context = self.right_context
num_frames = self.min_frames
chunk_size_needed = ((num_frames ... | Get a new chunk if available.
Returns:
Chunk or list: If enough frames are available a chunk is returned. Otherwise None.
If ``self.num_buffer >= 1`` a list instead of single chunk is returned. | codesearchnet |
def MapFile(self, key_path_prefix, registry_file):
self._registry_files[key_path_prefix.upper()] = registry_file
registry_file.SetKeyPathPrefix(key_path_prefix) | Maps the Windows Registry file to a specific key path prefix.
Args:
key_path_prefix (str): key path prefix.
registry_file (WinRegistryFile): Windows Registry file. | juraj-google-style |
def milliseconds(value: Union[int, float]) -> Duration:
return float(value / 1000) | Converts input value from milliseconds to a `Duration` in seconds.
Example:
```python
>>> duration = tp.duration.milliseconds(250)
>>> duration
0.25
>>> # Usage in a window operation
>>> a = tp.event_set(
... timestamps=[0.5, 1.0, 1.2],
... features={"f1": [1, 5, -5]}
... )
>>> a.moving_sum(window_length=dura... | github-repos |
def assert_visible(self, selector, testid=None, **kwargs):
self.info_log(('Assert visible selector(%s) testid(%s)' % (selector, testid)))
highlight = kwargs.get('highlight', BROME_CONFIG['highlight']['highlight_on_assertion_success'])
self.debug_log(('effective highlight: %s' % highlight))
wait_until_vi... | Assert that the element is visible in the dom
Args:
selector (str): the selector used to find the element
testid (str): the test_id or a str
Kwargs:
wait_until_visible (bool)
highlight (bool)
Returns:
bool: True is the assertion succeed; False otherwise. | codesearchnet |
def price(self, valuation_date, market, model=None, pricing_context=None, name=None):
del model, pricing_context
name = name or self._name + '_price'
with tf.name_scope(name):
discount_curve = market.discount_curve
discount_factors = discount_curve.get_discount_factor(self._payment_dates)
... | Returns the present value of the stream on the valuation date.
Args:
valuation_date: A scalar `DateTensor` specifying the date on which
valuation is being desired.
market: A namedtuple of type `InterestRateMarket` which contains the
necessary information for pricing the cashflow stream.
model: Reserved for future use.... | github-repos |
def find_equivalent_sites(self, site):
for sites in self.equivalent_sites:
if site in sites:
return sites
raise ValueError("Site not in structure") | Finds all symmetrically equivalent sites for a particular site
Args:
site (PeriodicSite): A site in the structure
Returns:
([PeriodicSite]): List of all symmetrically equivalent sites. | juraj-google-style |
def watch(self, enable=True, gpsd_protocol=PROTOCOL, devicepath=None):
command = '?WATCH={{"enable":true,"{0}":true}}'.format(gpsd_protocol)
if gpsd_protocol == 'rare':
command = command.replace('"rare":true', '"raw":1')
if gpsd_protocol == 'raw':
c... | watch gpsd in various gpsd_protocols or devices.
Arguments:
enable: (bool) stream data to socket
gpsd_protocol: (str) 'json' | 'nmea' | 'rare' | 'raw' | 'scaled' | 'split24' | 'pps'
devicepath: (str) device path - '/dev/ttyUSBn' for some number n or '/dev/whatever_works'
Returns:
command: (str) e.g., '?WATCH={"enable":... | juraj-google-style |
def _start_profiler(self, logdir):
if self._profiler_started:
return
try:
profiler.start(logdir=logdir)
self._profiler_started = True
except errors.AlreadyExistsError as e:
logging.error('Failed to start profiler: %s', e.message) | Starts the profiler if currently inactive.
Args:
logdir: Directory where profiler results will be saved. | github-repos |
def get_internal_urls(self):
internal_urls = self.get_subfields('856', 'u', i1='4', i2='0')
internal_urls.extend(self.get_subfields('998', 'a'))
internal_urls.extend(self.get_subfields('URL', 'u'))
return map((lambda x: x.replace('&', '&')), internal_urls) | URL's, which may point to edeposit, aleph, kramerius and so on.
Fields ``856u40``, ``998a`` and ``URLu``.
Returns:
list: List of internal URLs. | codesearchnet |
def kill_raylet(self, check_alive=True):
self._kill_process_type(ray_constants.PROCESS_TYPE_RAYLET, check_alive=check_alive) | Kill the raylet.
Args:
check_alive (bool): Raise an exception if the process was already
dead. | codesearchnet |
def _extract_inner_match(self, candidate, offset):
for possible_inner_match in _INNER_MATCHES:
group_match = possible_inner_match.search(candidate)
is_first_match = True
while group_match and self._max_tries > 0:
if is_first_match:
... | Attempts to extract a match from candidate if the whole candidate
does not qualify as a match.
Arguments:
candidate -- The candidate text that might contain a phone number
offset -- The current offset of candidate within text
Returns the match found, None if none can be found | juraj-google-style |
def _ImportAll(self, module):
aliases = []
getattrs = set()
ast = self._module_map[module]
type_param_names = set()
if module == 'http.client':
exports = None
else:
exports = [x for x in ast.constants if x.name.endswith('.__all__')]
if exports:
exports = expor... | Get the new members that would result from a star import of the module.
Args:
module: The module name.
Returns:
A tuple of:
- a list of new aliases,
- a set of new __getattr__ functions. | github-repos |
def visit_and_get_function_nodes(self, definition, first_node):
len_before_visiting_func = len(self.nodes)
previous_node = self.nodes[(- 1)]
entry_node = self.append_node(EntryOrExitNode(('Function Entry ' + definition.name)))
if (not first_node):
first_node = entry_node
self.connect_if_allo... | Visits the nodes of a user defined function.
Args:
definition(LocalModuleDefinition): Definition of the function being added.
first_node(EntryOrExitNode or None or RestoreNode): Used to connect previous statements to this function.
Returns:
the_new_nodes(list[Node]): The nodes added while visiting the function.
first... | codesearchnet |
def save_driver_logs(driver, prefix):
browser_name = os.environ.get('SELENIUM_BROWSER', 'firefox')
log_dir = os.environ.get('SELENIUM_DRIVER_LOG_DIR')
if not log_dir:
LOGGER.warning('The SELENIUM_DRIVER_LOG_DIR environment variable was not set; not saving logs')
return
elif not os.p... | Save the selenium driver logs.
The location of the driver log files can be configured
by the environment variable `SELENIUM_DRIVER_LOG_DIR`. If not set,
this defaults to the current working directory.
Args:
driver (selenium.webdriver): The Selenium-controlled browser.
prefix (str): A prefix which will be used in the... | juraj-google-style |
def _scalar(tf_fn, x, promote_to_float=False):
x = np_array_ops.asarray(x)
if promote_to_float and (not np.issubdtype(x.dtype.as_numpy_dtype, np.inexact)):
x = x.astype(np_utils.result_type(float))
return tf_fn(x) | Computes the tf_fn(x) for each element in `x`.
Args:
tf_fn: function that takes a single Tensor argument.
x: array_like. Could be an ndarray, a Tensor or any object that can be
converted to a Tensor using `ops.convert_to_tensor`.
promote_to_float: whether to cast the argument to a float dtype if it is not
already.
Re... | github-repos |
def gates_to_idx(gates, qregs):
sizes = [qr.size for qr in qregs.values()]
reg_idx = np.cumsum(([0] + sizes))
regint = {}
for (ind, qreg) in enumerate(qregs.values()):
regint[qreg] = ind
out = np.zeros((2 * len(gates)), dtype=np.int32)
for (idx, gate) in enumerate(gates):
out[(2 ... | Converts gate tuples into a nested list of integers.
Args:
gates (list): List of (QuantumRegister, int) pairs
representing gates.
qregs (dict): List of )QuantumRegister, int) tuples.
Returns:
list: Nested list of integers for gates. | codesearchnet |
def to_sql(cls, qc, **kwargs):
empty_df = qc.head(1).to_pandas().head(0)
empty_df.to_sql(**kwargs)
kwargs["if_exists"] = "append"
columns = qc.columns
def func(df, **kwargs):
df.columns = columns
... | Write records stored in a DataFrame to a SQL database.
Args:
qc: the query compiler of the DF that we want to run to_sql on
kwargs: parameters for pandas.to_sql(**kwargs) | juraj-google-style |
def from_keras_log(csv_path, output_dir_path, **kwargs):
data = pd.read_csv(csv_path, sep=None, engine='python')
_from_keras_log_format(data, output_dir_path=output_dir_path, **kwargs) | Plot accuracy and loss from a Keras CSV log.
Args:
csv_path: The path to the CSV log with the actual data.
output_dir_path: The path to the directory where the resultings plots
should end up. | juraj-google-style |
def series_with_slh(self, other):
new_S = self.S * other.S
new_L = self.S * other.L + self.L
def ImAdjoint(m):
return (m.H - m) * (I / 2)
delta = ImAdjoint(self.L.adjoint() * self.S * other.L)
if isinstance(delta, Matrix):
new_H = self.H + othe... | Series product with another :class:`SLH` object
Args:
other (SLH): An upstream SLH circuit.
Returns:
SLH: The combined system. | juraj-google-style |
def _sequence_search(self, start: GridQubit, current: List[GridQubit]) -> List[GridQubit]:
used = set(current)
seq = []
n = start
while (n is not None):
seq.append(n)
used.add(n)
n = self._choose_next_qubit(n, used)
return seq | Search for the continuous linear sequence from the given qubit.
This method is called twice for the same starting qubit, so that
sequences that begin and end on this qubit are searched for.
Args:
start: The first qubit, where search should be trigerred from.
current: Previously found linear sequence, which qubits are... | codesearchnet |
def set_heat_pump_mode(self, device_label, mode):
response = None
try:
response = requests.put(
urls.set_heatpump_state(self._giid, device_label),
headers={
'Accept': 'application/json',
'Content-Type': 'applica... | Set heatpump mode
Args:
mode (str): 'HEAT', 'COOL', 'FAN' or 'AUTO' | juraj-google-style |
def __call__(self, fn):
def completion(app, *args, **kwargs):
app.exit_message = self.msg
return fn(app, *args, **kwargs)
return completion | Implement __call__ function for decorator.
Args:
fn (function): The decorated function.
Returns:
function: The custom decorator function. | juraj-google-style |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.