code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def __init__(self, model_file, input_arrays=None, input_shapes=None, output_arrays=None, custom_objects=None):
super(TFLiteKerasModelConverter, self).__init__(experimental_debug_info_func=None)
if context.executing_eagerly():
if input_arrays or output_arrays:
raise ValueError('`input_arrays`... | Constructor for TFLiteConverter.
Args:
model_file: Full filepath of HDF5 file containing the tf.keras model.
input_arrays: List of input tensors to freeze graph with. Uses input
arrays from SignatureDef when none are provided. (default None)
input_shapes: Dict of strings representing input tensor names to list of
inte... | github-repos |
def set_storage(self, storage):
if isinstance(storage, BaseStorage):
self.storage = storage
elif isinstance(storage, dict):
if 'backend' not in storage and 'root_dir' in storage:
storage['backend'] = 'FileSystem'
try:
backend_c... | Set storage backend for downloader
For full list of storage backend supported, please see :mod:`storage`.
Args:
storage (dict or BaseStorage): storage backend configuration or instance | juraj-google-style |
def _projected_entity_to_message(ent, message_type):
msg = message_type()
analyzed = _analyze_indexed_fields(ent._projection)
for name, sublist in analyzed.iteritems():
prop = ent._properties[name]
val = prop._get_value(ent)
assert isinstance(prop, model.StructuredProperty) == bool(sublist)
if ... | Recursive helper for _from_base_type() to convert an entity to a message.
Args:
ent: A Model instance.
message_type: A Message subclass.
Returns:
An instance of message_type. | juraj-google-style |
def call(self, hidden_states: tf.Tensor, attention_mask: Optional[tf.Tensor]=None, image_hidden_states: Optional[tf.Tensor]=None, image_attention_mask: Optional[tf.Tensor]=None, cross_attention_gate: Optional[tf.Tensor]=None, output_attentions: Optional[bool]=False, use_cache: Optional[bool]=False, past_key_value: Opti... | Args:
hidden_states (`tf.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
attention_mask (`tf.Tensor`, *optional*): attention mask of size
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
output_attentions (`bool`, *optional*):
Whether or not to retur... | github-repos |
def assertNotAllClose(self, a, b, rtol=1e-06, atol=1e-06, msg=None):
try:
self.assertAllClose(a, b, rtol=rtol, atol=atol, msg=msg)
except AssertionError:
return
msg = msg or ''
raise AssertionError('The two values are close at all elements. %s' % msg) | Assert that two numpy arrays, or Tensors, do not have near values.
Args:
a: The expected numpy `ndarray`, or anything that can be converted into a
numpy `ndarray` (including Tensor), or any arbitrarily nested of
structure of these.
b: The actual numpy `ndarray`, or anything that can be converted into a
numpy `ndarray`... | github-repos |
def iter(self, keyed=False, extended=False):
if self.closed:
message = 'Stream is closed. Please call "stream.open()" first.'
raise exceptions.TabulatorException(message)
iterator = chain(self.__sample_extended_rows, self.__parser.extended_rows)
iterator = self.__apply_processors(iterator)
... | Iterate over the rows.
Each row is returned in a format that depends on the arguments `keyed`
and `extended`. By default, each row is returned as list of their
values.
Args:
keyed (bool, optional): When True, each returned row will be a
`dict` mapping the header name to its value in the current row.
For example, `[{'... | codesearchnet |
def has_error(self):
return next((True for cr in self.component_results if cr.has_error()), False) | Returns whether there was a business logic error when fetching data
for any components for this property.
Returns:
boolean | codesearchnet |
def match(self, patterns, limits=None):
if limits is None:
limits = [None] * len(patterns)
else:
err_msg = 'Patterns and limits should be equal in length'
assert len(patterns) == len(limits), err_msg
def _match(pattern, limit):
if pattern.endswith('/') or pattern.en... | Find all matching paths to the patterns provided.
See Also:
:meth:`translate_pattern`
Patterns ending with '/' or '\' will be appended with '*'.
Args:
patterns: list of string for the file path pattern to match against
limits: list of maximum number of responses that need to be fetched
Returns: list of ``MatchResul... | github-repos |
def AddDateTimeRange(self, time_value, start_time_string=None, end_time_string=None):
if (not isinstance(time_value, py2to3.STRING_TYPES)):
raise ValueError('Filter type must be a string.')
if ((start_time_string is None) and (end_time_string is None)):
raise ValueError('Filter must have either ... | Adds a date time filter range.
The time strings are formatted as:
YYYY-MM-DD hh:mm:ss.######[+-]##:##
Where # are numeric digits ranging from 0 to 9 and the seconds
fraction can be either 3 or 6 digits. The time of day, seconds fraction
and timezone offset are optional. The default timezone is UTC.
Args:
time_value (... | codesearchnet |
def Unregister(self, name):
precondition.AssertType(name, Text)
try:
del self._constructors[name]
except KeyError:
raise ValueError("Constructor with name '%s' is not registered" % name) | Unregisters a constructor.
Args:
name: A name of the constructor to unregister.
Raises:
ValueError: If constructor with specified name has never been registered. | juraj-google-style |
def _construct_linebreak_token(self, d: Dict) -> List[Dict]:
result = []
num_break = int(d["length"][0]) if d["length"] else 1
if num_break:
s = ''
for i in range(num_break):
s += '\n'
this_token = {attrs.LOWER: s}
result.... | Construct a shape token
Args:
d: Dict
Returns: List[Dict] | juraj-google-style |
def frombase(path1, path2):
if (not isparent(path1, path2)):
raise ValueError('path1 must be a prefix of path2')
return path2[len(path1):] | Get the final path of ``path2`` that isn't in ``path1``.
Arguments:
path1 (str): A PyFilesytem path.
path2 (str): A PyFilesytem path.
Returns:
str: the final part of ``path2``.
Example:
>>> frombase('foo/bar/', 'foo/bar/baz/egg')
'baz/egg' | codesearchnet |
def singleOrPair(obj):
if len(list(obj.__class__.__mro__)) <= 2:
return 'Neither'
else:
if ancestorJr(obj) is Pair:
return 'Pair'
elif ancestor(obj) is Single:
return 'Single'
else:
return 'Neither' | Chech an object is single or pair or neither.
Of course,, all pairs are single, so what the function is really detecting is whether an object is only single or at the same time a pair.
Args:
obj (object): Literally anything.
Returns:
str: 'Single', or 'Pair', or 'Neither' | juraj-google-style |
def coarse_grain(G, ncg):
if (ncg <= 1):
return G
G = numpy.asarray(G)
(nbin, remainder) = divmod(G.shape[(- 1)], ncg)
if (remainder != 0):
nbin += 1
return numpy.transpose([(numpy.sum(G[(..., i:(i + ncg))], axis=(- 1)) / G[(..., i:(i + ncg))].shape[(- 1)]) for i in numpy.arange(0, (... | Coarse-grain last index of array ``G``.
Bin the last index of array ``G`` in bins of width ``ncg``, and
replace each bin by its average. Return the binned results.
Args:
G: Array to be coarse-grained.
ncg: Bin width for coarse-graining. | codesearchnet |
def match(self, request):
if (self._times <= 0):
raise PookExpiredMock('Mock expired')
for test in self.filters:
if (not test(request, self)):
return (False, [])
for mapper in self.mappers:
request = mapper(request, self)
if (not request):
raise ValueE... | Matches an outgoing HTTP request against the current mock matchers.
This method acts like a delegator to `pook.MatcherEngine`.
Arguments:
request (pook.Request): request instance to match.
Raises:
Exception: if the mock has an exception defined.
Returns:
tuple(bool, list[Exception]): ``True`` if the mock matches
th... | codesearchnet |
def get_content_field(self, name):
fields = self._content.findall(name)
if not fields:
return None
elif len(fields) == 1:
return etree_to_dict(fields[0])[name]
else:
return [etree_to_dict(field)[name] for field in fields] | Get the contents of a specific subtag from Clusterpoint Storage's response's content tag.
Args:
name -- A name string of the content's subtag to be returned.
Returns:
A dict representing the contents of the specified field or a list of dicts
if there are multiple fields with that tag name. Returns None if no field fo... | juraj-google-style |
def cs20(msg):
chars = '
d = hex2bin(data(msg))
cs = ''
cs += chars[bin2int(d[8:14])]
cs += chars[bin2int(d[14:20])]
cs += chars[bin2int(d[20:26])]
cs += chars[bin2int(d[26:32])]
cs += chars[bin2int(d[32:38])]
cs += chars[bin2int(d[38:44])]
cs += chars[bin2int(d[44:50])]
... | Aircraft callsign
Args:
msg (String): 28 bytes hexadecimal message (BDS40) string
Returns:
string: callsign, max. 8 chars | juraj-google-style |
def _DictToListOfStrings(self, data_dict):
ret_list = []
for (key, value) in iter(data_dict.items()):
if (key in ('body', 'datetime', 'type', 'room', 'rooms', 'id')):
continue
ret_list.append('{0:s} = {1!s}'.format(key, value))
return ret_list | Converts a dictionary into a list of strings.
Args:
data_dict (dict[str, object]): dictionary to convert.
Returns:
list[str]: list of strings. | codesearchnet |
def average_datetimes(dt_list):
if (sys.version_info < (3, 3)):
import time
def timestamp_func(dt):
return time.mktime(dt.timetuple())
else:
timestamp_func = datetime.timestamp
total = [timestamp_func(dt) for dt in dt_list]
return datetime.fromtimestamp((sum(total) /... | Average a series of datetime objects.
.. note::
This function assumes all datetime objects are naive and in the same
time zone (UTC).
Args:
dt_list (iterable): Datetime objects to average
Returns: Average datetime as a datetime object | codesearchnet |
def MapByteStream(
self, byte_stream, byte_offset=0, context=None, **unused_kwargs):
data_type_size = self._data_type_definition.GetByteSize()
self._CheckByteStreamSize(byte_stream, byte_offset, data_type_size)
try:
struct_tuple = self._operation.ReadFrom(byte_stream[byte_offset:])
m... | Maps the data type on a byte stream.
Args:
byte_stream (bytes): byte stream.
byte_offset (Optional[int]): offset into the byte stream where to start.
context (Optional[DataTypeMapContext]): data type map context.
Returns:
object: mapped value.
Raises:
MappingError: if the data type definition cannot be mapped on
the... | juraj-google-style |
def constant_time_string_compare(a, b):
try:
return hmac.compare_digest(a, b)
except AttributeError:
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= ord(x) ^ ord(y)
return result == 0 | Helper for comparing string in constant time, independent
of the python version being used.
Args:
a (str): A string to compare
b (str): A string to compare | juraj-google-style |
def show_history(self, status=None, nids=None, full_history=False, metadata=False):
(nrows, ncols) = get_terminal_size()
works_done = []
for task in self.iflat_tasks(status=status, nids=nids):
work = task.work
if (work not in works_done):
works_done.append(work)
if (w... | Print the history of the flow to stdout.
Args:
status: if not None, only the tasks with this status are select
full_history: Print full info set, including nodes with an empty history.
nids: optional list of node identifiers used to filter the tasks.
metadata: print history metadata (experimental) | codesearchnet |
def _extract_direct(self, *, stream):
def normal_dct_rgb():
DEFAULT_CT_RGB = 1
ct = self.filter_decodeparms[0][1].get('/ColorTransform', DEFAULT_CT_RGB)
return self.mode == 'RGB' and ct == DEFAULT_CT_R... | Attempt to extract the image directly to a usable image file
If there is no way to extract the image without decompressing or
transcoding then raise an exception. The type and format of image
generated will vary.
Args:
stream: Writable stream to write data to | juraj-google-style |
def estimate_tokens(self, input_dict: Dict[str, Union[torch.Tensor, Any]]) -> int:
if not hasattr(self, 'warnings_issued'):
self.warnings_issued = {}
if self.main_input_name in input_dict:
return input_dict[self.main_input_name].numel()
elif 'estimate_tokens' not in self.warnings_issued:
... | Helper function to estimate the total number of tokens from the model inputs.
Args:
inputs (`dict`): The model inputs.
Returns:
`int`: The total number of tokens. | github-repos |
def is_truthy(value, default=False):
if value is None:
return False
if isinstance(value, bool):
return value
if isinstance(value, int):
return value > 0
trues = ('1', 'true', 'y', 'yes', 'ok')
falses = ('', '0', 'false', 'n', 'none', 'no')
if value.lower().strip... | Evaluate a value for truthiness
>>> is_truthy('Yes')
True
>>> is_truthy('False')
False
>>> is_truthy(1)
True
Args:
value (Any): Value to evaluate
default (bool): Optional default value, if the input does not match the true or false values
Returns:
True if a truthy value is passed, else False | juraj-google-style |
def Verify(self, mempool):
if not super(ClaimTransaction, self).Verify(mempool):
return False
otherclaimTxs = [tx for tx in mempool if tx is ClaimTransaction and tx is not self]
for o... | Verify the transaction.
Args:
mempool:
Returns:
bool: True if verified. False otherwise. | juraj-google-style |
def __recv(self, size=4096):
data = self.socket.recv(size)
if (not data):
raise NNTPError('Failed to read from socket')
self.__buffer.write(data) | Reads data from the socket.
Raises:
NNTPError: When connection times out or read from socket fails. | codesearchnet |
def categorize(values, categories, default=None):
uniq_cats = list(unique_iterator(values))
cats = []
for c in values:
if isinstance(categories, list):
cat_ind = uniq_cats.index(c)
if cat_ind < len(categories):
cat = categories[cat_ind]
else:
... | Maps discrete values to supplied categories.
Replaces discrete values in input array with a fixed set of
categories defined either as a list or dictionary.
Args:
values: Array of values to be categorized
categories: List or dict of categories to map inputs to
default: Default value to assign if value not in categorie... | juraj-google-style |
def content(self, request, id):
gist = self.send(request, id).json()
def convert(data):
return base64.b64decode(data).decode('utf-8')
content = {}
for name, data in gist['files'].items():
content[name] = convert(data['content'])
return content | Returns the content of the gist
Arguments:
request: an initial request object
id: the gist identifier
Returns:
A dict containing the contents of each file in the gist | juraj-google-style |
def from_structure(cls, structure, ff_elements=None, atom_style="charge"):
s = structure.get_sorted_structure()
box, symmop = lattice_2_lmpbox(s.lattice)
coords = symmop.operate_multi(s.cart_coords)
site_properties = s.site_properties
if "velocities" in site_properties:
... | Simple constructor building LammpsData from a structure without
force field parameters and topologies.
Args:
structure (Structure): Input structure.
ff_elements ([str]): List of strings of elements that must
be present due to force field settings but not
necessarily in the structure. Default to None.
atom_style (str):... | juraj-google-style |
def _apply_credentials(auto_refresh=True, credentials=None,
headers=None):
token = credentials.get_credentials().access_token
if auto_refresh is True:
if token is None:
token = credentials.refresh(
access_token=None, tim... | Update Authorization header.
Update request headers with latest `access_token`. Perform token
`refresh` if token is ``None``.
Args:
auto_refresh (bool): Perform token refresh if access_token is ``None`` or expired. Defaults to ``True``.
credentials (class): Read-only credentials.
headers (class): Requests `CaseInsens... | juraj-google-style |
def strace_data_access_event(self, operation, address, data, data_mask=None, access_width=4, address_range=0):
cmd = enums.JLinkStraceCommand.TRACE_EVENT_SET
event_info = structs.JLinkStraceEventInfo()
event_info.Type = enums.JLinkStraceEvent.DATA_ACCESS
event_info.Op = operation
event_info.AccessSi... | Sets an event to trigger trace logic when data access is made.
Data access corresponds to either a read or write.
Args:
self (JLink): the ``JLink`` instance.
operation (int): one of the operations in ``JLinkStraceOperation``.
address (int): the address of the load/store data.
data (int): the data to be compared the e... | codesearchnet |
def sg_any(tensor, opt):
r
return tf.reduce_any(tensor, axis=opt.axis, keep_dims=opt.keep_dims, name=opt.name) | r"""Computes the "logical or" of elements across axis of a tensor.
See `tf.reduce_any()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
axis : A tuple/list of integers or an integer. The axis to reduce.
keep_dims: If true, retains reduced dimensions with length 1.
name: If provided, repl... | juraj-google-style |
def _multi_worker_session(kwargs):
strategy = None
for _, v in kwargs.items():
if isinstance(v, distribute_lib.StrategyBase):
if strategy is not None:
logging.warning('The test uses multiple strategies. Skipping entering a session that is configured for the strategy.')
... | Returns a context manager that enters a session that is configured for the MultiWorkerMirroredStrategy.
Args:
kwargs: a dict. Keyword arguments passed to the test.
Returns:
A context manager. If MultiWorkerMirroredStrategy is the one and only one
strategy in kwargs and it's in graph mode, it's the session that is
co... | github-repos |
def _parse_mtu(self, config):
match = re.search('mtu (\\d+)', config)
return dict(mtu=int(match.group(1))) | Parses the config block and returns the configured IP MTU value
The provided configuration block is scanned and the configured value
for the IP MTU is returned as a dict object. The IP MTU value is
expected to always be present in the provided config block
Args:
config (str): The interface configuration block to par... | codesearchnet |
def print_schema_results(results, level=0):
for error in results.errors:
print_level(logger.error, _RED + "[X] %s", level, error) | Print JSON Schema validation errors to stdout.
Args:
results: An instance of ObjectValidationResults.
level: The level at which to print the results. | juraj-google-style |
def get_id_transcripts(self, hgnc_id, build='37'):
transcripts = self.transcripts(build=build, hgnc_id=hgnc_id)
identifier_transcripts = set()
longest = None
nr = []
xm = []
for tx in transcripts:
enst_id = tx['transcript_id']
... | Return a set with identifier transcript(s)
Choose all refseq transcripts with NM symbols, if none where found choose ONE with NR,
if no NR choose ONE with XM. If there are no RefSeq transcripts identifiers choose the
longest ensembl transcript.
Args:
hgnc_id(int)
build(str)
Returns:
identifier_transcripts(set) | juraj-google-style |
def _is_univariate_marginal(self, index_points):
num_index_points = tf.compat.dimension_value(index_points.shape[(- (self.kernel.feature_ndims + 1))])
if (num_index_points is None):
warnings.warn('Unable to detect statically whether the number of index_points is 1. As a result, defaulting to treating th... | True if the given index_points would yield a univariate marginal.
Args:
index_points: the set of index set locations at which to compute the
marginal Gaussian distribution. If this set is of size 1, the marginal is
univariate.
Returns:
is_univariate: Boolean indicating whether the marginal is univariate or
multivaria... | codesearchnet |
def get_interface(self):
raise NotImplementedError('Base class should not be called directly!') | This function returns The interface used to configure the sniffer,
e.g. 'wlan0'.
Returns:
The interface (string) used to configure the sniffer. Corresponds to
the 'Interface' key of the sniffer configuration. | github-repos |
def update_parser(self, parser):
self._parser = parser
ini_str = argparse_to_ini(parser)
configp = configparser.ConfigParser(allow_no_value=True)
configp.read_dict(self._config)
configp.read_string(ini_str)
self._config.update({s: dict(configp.items(s)) for s in configp.sections()}) | Update config dictionary with declared arguments in an argparse.parser
New variables will be created, and existing ones overridden.
Args:
parser (argparse.ArgumentParser): parser to read variables from | codesearchnet |
def __init__(self, app, env, region, prop_path):
self.app_name = app
self.env = env
self.region = region
self.properties = get_properties(prop_path)
generated = get_details(app=self.app_name)
self.group = generated.data['project']
try:
self.p... | Lambda function object.
Args:
app (str): Application name
env (str): Environment/Account
region (str): AWS Region
prop_path (str): Path of environment property file | juraj-google-style |
def _parse_deploy(self, deploy_values: dict, service_config: dict):
mode = {}
for d_value in deploy_values:
if ('restart_policy' in d_value):
restart_spec = docker.types.RestartPolicy(**deploy_values[d_value])
service_config['restart_policy'] = restart_spec
if ('placement... | Parse deploy key.
Args:
deploy_values (dict): deploy configuration values
service_config (dict): Service configuration | codesearchnet |
def drop(self, index=None, columns=None):
if self._is_transposed:
return self.transpose().drop(index=columns, columns=index).transpose()
if (index is None):
new_data = self.data
new_index = self.index
else:
def delitem(df, internal_indices=[]):
return df.drop(ind... | Remove row data for target index and columns.
Args:
index: Target index to drop.
columns: Target columns to drop.
Returns:
A new QueryCompiler. | codesearchnet |
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. | codesearchnet |
def __init__(self, rate=None, burst_size=None, prec_level=None):
super().__init__(MeterBandType.OFPMBT_DSCP_REMARK, rate, burst_size)
self.prec_level = prec_level | Create a MeterBandDscpRemark with the optional parameters below.
Args:
rate (int): Rate for remarking packets.
burst_size (int): Size of bursts.
prec_level (int): Number of precendence level to substract. | juraj-google-style |
def _create_config_proto(self) -> tpu_embedding_configuration_pb2.TPUEmbeddingConfiguration:
config_proto = tpu_embedding_configuration_pb2.TPUEmbeddingConfiguration()
learning_rate_index = {r: i for i, r in enumerate(self._dynamic_learning_rates)}
for table in self._table_config:
table._set_table_d... | Creates the TPUEmbeddingConfiguration proto.
This proto is used to initialize the TPU embedding engine.
Returns:
A TPUEmbeddingConfiguration proto. | github-repos |
def load_dict_values(self, db_key: str, dict_keys: List[str], hierarchical: bool=False) -> List:
result = []
if (not hierarchical):
_values = self._db.hmget(db_key, *dict_keys)
result = [ast.literal_eval(_value) for _value in _values]
else:
db_keys = self._db.keys(pattern=(db_key + '... | Load values from a dictionary with the specified dict_keys.
Args:
db_key (str): Key where the dictionary is stored
dict_keys (List[str]): Keys within the dictionary to load.
hierarchical (bool): If True, expect the dictionary to have been
stored hierarchically. If False, expect the dictionary to have
been stored flat.... | codesearchnet |
def _range_along_dimension(range_dim, shape):
rank = len(shape)
if (range_dim >= rank):
raise ValueError('Cannot calculate range along non-existent index.')
indices = tf.range(start=0, limit=shape[range_dim])
indices = tf.reshape(indices, shape=[(1 if (i != range_dim) else shape[range_dim]) for ... | Construct a Tensor whose values are the index along a dimension.
Construct a Tensor that counts the distance along a single dimension. This is
useful, for example, when constructing an identity matrix,
>>> x = _range_along_dimension(0, [2, 2]).eval()
>>> x
array([[0, 0],
[1, 1]], dtype=int32)
>>> y = _range_along_di... | codesearchnet |
def write_to_hdf5(self, filename_out, *args, **kwargs):
t0 = time.time()
self.__update_header()
if self.container.isheavy():
self.__write_to_hdf5_heavy(filename_out)
else:
self.__write_to_hdf5_light(filename_out)
t1 = time.time()
logger.info(('Conversion time: %2.2fsec' % (t1 - t... | Write data to HDF5 file.
It check the file size then decides how to write the file.
Args:
filename_out (str): Name of output file | codesearchnet |
def create_tree(profile, tree):
resource = '/trees'
payload = {'tree': tree}
data = api.post_request(profile, resource, payload)
return prepare(data) | Create a new tree.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
tree
A list of blob objects (each with a path, mode, type, and
content or sha) to put in the tree.
Returns:
A dict... | codesearchnet |
def EnableNetworkInterfaces(
self, interfaces, logger, dhclient_script=None):
if os.path.exists(self.network_path):
self._DisableNetworkManager(interfaces, logger)
helpers.CallDhclient(interfaces, logger) | Enable the list of network interfaces.
Args:
interfaces: list of string, the output device names to enable.
logger: logger object, used to write to SysLog and serial port.
dhclient_script: string, the path to a dhclient script used by dhclient. | juraj-google-style |
def prefetch_users(persistent_course_grades):
users = User.objects.filter(id__in=[grade.user_id for grade in persistent_course_grades])
return {user.id: user for user in users} | Prefetch Users from the list of user_ids present in the persistent_course_grades.
Arguments:
persistent_course_grades (list): A list of PersistentCourseGrade.
Returns:
(dict): A dictionary containing user_id to user mapping. | codesearchnet |
def unique_array(arr):
if not len(arr):
return np.asarray(arr)
elif pd:
if isinstance(arr, np.ndarray) and arr.dtype.kind not in 'MO':
return pd.unique(arr)
values = []
for v in arr:
if (isinstance(v, datetime_types) and
... | Returns an array of unique values in the input order.
Args:
arr (np.ndarray or list): The array to compute unique values on
Returns:
A new array of unique values | juraj-google-style |
def _transform_binary_composition_to_expression(expression, node, context):
if (expression.operator not in constants.SUPPORTED_OPERATORS):
raise NotImplementedError(u'Filter operation "{}" is not supported by the SQL backend.'.format(expression.operator))
sql_operator = constants.SUPPORTED_OPERATORS[exp... | Transform a BinaryComposition compiler expression into a SQLAlchemy expression.
Recursively calls _expression_to_sql to convert its left and right sub-expressions.
Args:
expression: expression, BinaryComposition compiler expression.
node: SqlNode, the SqlNode the expression applies to.
context: CompilationContext, gl... | codesearchnet |
def split_raster(rs, split_shp, field_name, temp_dir):
UtilClass.rmmkdir(temp_dir)
ds = ogr_Open(split_shp)
lyr = ds.GetLayer(0)
lyr.ResetReading()
ft = lyr.GetNextFeature()
while ft:
cur_field_name = ft.GetFieldAsString(field_name)
for r ... | Split raster by given shapefile and field name.
Args:
rs: origin raster file.
split_shp: boundary (ESRI Shapefile) used to spilt raster.
field_name: field name identify the spilt value.
temp_dir: directory to store the spilt rasters. | juraj-google-style |
def _CreateRouteShapesFolder(self, schedule, parent, route, style_id=None, visible=True):
shape_id_to_trips = {}
for trip in route.trips:
if trip.shape_id:
shape_id_to_trips.setdefault(trip.shape_id, []).append(trip)
if (not shape_id_to_trips):
return None
shape_id_to_trips_i... | Create a KML Folder for the shapes of a route.
The folder contains a placemark for each shape referenced by a trip in the
route. If there are no such shapes, no folder is created and None is
returned.
Args:
schedule: The transitfeed.Schedule instance.
parent: The parent ElementTree.Element instance.
route: The transi... | codesearchnet |
def sendfrom(self, user_id, dest_address, amount, minconf=1):
amount = Decimal(amount).quantize(self.quantum, rounding=ROUND_HALF_EVEN)
txhash = self.rpc.call("sendfrom",
user_id, dest_address, float(str(amount)), minconf
)
self.logger.debug("Send %s %s from %s to %s... | Send coins from user's account.
Args:
user_id (str): this user's unique identifier
dest_address (str): address which is to receive coins
amount (str or Decimal): amount to send (eight decimal points)
minconf (int): ensure the account has a valid balance using this
many confirmations (default=1)
Returns:
str: transact... | juraj-google-style |
def garbage_collection(time_limit=YEAR/12.0):
expired_request_infos = (
ri for ri in DATABASE.values()
if ri.creation_ts + time_limit <= time.time()
)
for ri in expired_request_infos:
del DATABASE[ri.url] | Collect and remove all :class:`.RequestInfo` objects older than
`time_limit` (in seconds).
Args:
time_limit (float, default YEAR / 2): Collect objects older than
this limit. | juraj-google-style |
def padding_to_length(padding):
non_padding = (1.0 - padding)
return tf.to_int32(tf.reduce_sum(non_padding, axis=(- 1))) | Calculate the length of mask based on padding.
Args:
padding: a Tensor with shape [..., length].
Returns:
a Tensor with shape [...]. | codesearchnet |
def _init_request_logging(self, app):
enabled = not app.config.get(CONF_DISABLE_REQUEST_LOGGING, False)
if not enabled:
return
self._requests_middleware = WSGIApplication(
self._key, app.wsgi_app, telemetry_channel=self._channel)
app.wsgi_app = self._r... | Sets up request logging unless ``APPINSIGHTS_DISABLE_REQUEST_LOGGING``
is set in the Flask config.
Args:
app (flask.Flask). the Flask application for which to initialize the extension. | juraj-google-style |
def residual_block_layer(inputs, hparams):
kernel = (hparams.res_kernel_size, hparams.res_kernel_size)
x = inputs
for i in range(hparams.num_res_layers):
with tf.variable_scope(('res_conv_%d' % i)):
y = common_layers.conv_block(common_layers.layer_norm(x, hparams.hidden_size, name='lnorm... | Residual block over inputs.
Runs a residual block consisting of
conv: kernel_size x kernel_size
conv: 1x1
dropout, add and normalize according to hparams.layer_postprocess_sequence.
Args:
inputs: Tensor of shape [batch, height, width, hparams.hidden_size].
hparams: HParams.
Returns:
Tensor of shape [batch, height, w... | codesearchnet |
def NamedSelector(name, fields, description=None, type_attributes=DEFAULT_TYPE_ATTRIBUTES):
check.str_param(name, 'name')
check_user_facing_fields_dict(fields, 'NamedSelector named "{}"'.format(name))
class _NamedSelector(_ConfigSelector):
def __init__(self):
super(_NamedSelector, ... | A :py:class`Selector` with a name, allowing it to be referenced by that name.
Args:
name (str):
fields (Dict[str, Field]) | juraj-google-style |
def call_each(seq):
try:
reduce(lambda _, y: y(), seq)
except TypeError as e:
if text_type(e) != "reduce() of empty sequence with no initial value":
raise | Calls each element of sequence to invoke the side effect.
Args:
seq:
Returns: None | juraj-google-style |
def predict_features(self, df_features, df_target, nh=20, idx=0, dropout=0.0, activation_function=th.nn.ReLU, lr=0.01, l1=0.1, batch_size=(- 1), train_epochs=1000, test_epochs=1000, device=None, verbose=None, nb_runs=3):
(device, verbose) = SETTINGS.get_default(('device', device), ('verbose', verbose))
x = th.F... | For one variable, predict its neighbours.
Args:
df_features (pandas.DataFrame):
df_target (pandas.Series):
nh (int): number of hidden units
idx (int): (optional) for printing purposes
dropout (float): probability of dropout (between 0 and 1)
activation_function (torch.nn.Module): activation function of the NN
lr (floa... | codesearchnet |
def update_vlan(self, name, vid, vni):
cmd = ('vxlan vlan %s vni %s' % (vid, vni))
return self.configure_interface(name, cmd) | Adds a new vlan to vni mapping for the interface
EosVersion:
4.13.7M
Args:
vlan (str, int): The vlan id to map to the vni
vni (str, int): The vni value to use
Returns:
True if the command completes successfully | codesearchnet |
def delete_vnet(access_token, subscription_id, resource_group, name):
endpoint = ''.join([get_rm_endpoint(),
'/subscriptions/', subscription_id,
'/resourceGroups/', resource_group,
'/providers/Microsoft.Network/virtualNetworks/', name,
... | Delete a virtual network.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
name (str): Name of the VNet.
Returns:
HTTP response. VNet JSON body. | juraj-google-style |
def __init__(self, target='', graph=None, config=None):
_python_session_create_counter.get_cell().increase_by(1)
if graph is None:
self._graph = ops.get_default_graph()
else:
if not isinstance(graph, ops.Graph):
raise TypeError(f'Argument `graph` must be a tf.Graph, but got "{typ... | Constructs a new TensorFlow session.
Args:
target: (Optional) The TensorFlow execution engine to connect to.
graph: (Optional) The graph to be used. If this argument is None, the
default graph will be used.
config: (Optional) ConfigProto proto used to configure the session. If no
config is specified, the global defaul... | github-repos |
def from_pymatgen_molecule(cls, molecule):
new = cls(atoms=[el.value for el in molecule.species],
coords=molecule.cart_coords)
return new._to_numeric() | Create an instance of the own class from a pymatgen molecule
Args:
molecule (:class:`pymatgen.core.structure.Molecule`):
Returns:
Cartesian: | juraj-google-style |
def StatEntryFromPath(path, pathspec, ext_attrs=True):
try:
stat = filesystem.Stat.FromPath(path)
except (IOError, OSError) as error:
logging.error("Failed to obtain stat for '%s': %s", pathspec, error)
return rdf_client_fs.StatEntry(pathspec=pathspec)
return StatEntryFromStat(stat, ... | Builds a stat entry object from a given path.
Args:
path: A path (string value) to stat.
pathspec: A `PathSpec` corresponding to the `path`.
ext_attrs: Whether to include extended file attributes in the result.
Returns:
`StatEntry` object. | codesearchnet |
def queuify_logger(logger, queue_handler, queue_listener):
if isinstance(logger, str):
logger = logging.getLogger(logger)
handlers = [handler for handler in logger.handlers
if handler not in queue_listener.handlers]
if handlers:
queue_listener.handlers = ... | Replace logger's handlers with a queue handler while adding existing
handlers to a queue listener.
This is useful when you want to use a default logging config but then
optionally add a logger's handlers to a queue during runtime.
Args:
logger (mixed): Logger instance or string name of logger to queue-ify
handlers.
q... | juraj-google-style |
def Oem(self, command, timeout_ms=None, info_cb=DEFAULT_MESSAGE_CALLBACK):
if not isinstance(command, bytes):
command = command.encode('utf8')
return self._SimpleCommand(
b'oem %s' % command, timeout_ms=timeout_ms, info_cb=info_cb) | Executes an OEM command on the device.
Args:
command: Command to execute, such as 'poweroff' or 'bootconfig read'.
timeout_ms: Optional timeout in milliseconds to wait for a response.
info_cb: See Download. Messages vary based on command.
Returns:
The final response from the device. | juraj-google-style |
def Sample(self, tasks_status):
sample_time = time.time()
sample = '{0:f}\t{1:d}\t{2:d}\t{3:d}\t{4:d}\t{5:d}\n'.format(sample_time, tasks_status.number_of_queued_tasks, tasks_status.number_of_tasks_processing, tasks_status.number_of_tasks_pending_merge, tasks_status.number_of_abandoned_tasks, tasks_status.total... | Takes a sample of the status of queued tasks for profiling.
Args:
tasks_status (TasksStatus): status information about tasks. | codesearchnet |
def raster_reclassify(srcfile, v_dict, dstfile, gdaltype=GDT_Float32):
src_r = RasterUtilClass.read_raster(srcfile)
src_data = src_r.data
dst_data = numpy.copy(src_data)
if gdaltype == GDT_Float32 and src_r.dataType != GDT_Float32:
gdaltype = src_r.dataType
n... | Reclassify raster by given classifier dict.
Args:
srcfile: source raster file.
v_dict: classifier dict.
dstfile: destination file path.
gdaltype (:obj:`pygeoc.raster.GDALDataType`): GDT_Float32 as default. | juraj-google-style |
def _get_commands(dist
):
py_files = (f for f in setuptools.findall()
if os.path.splitext(f)[1].lower() == '.py')
pkg_files = (f for f in py_files if _get_package_name(f) in dist.packages)
commands = {}
for file_name in pkg_files:
with open(file_na... | Find all commands belonging to the given distribution.
Args:
dist: The Distribution to search for docopt-compatible docstrings that
can be used to generate command entry points.
Returns:
A dictionary containing a mapping of primary commands to sets of
subcommands. | juraj-google-style |
def _GetAnalysisPlugins(self, analysis_plugins_string):
if (not analysis_plugins_string):
return []
analysis_plugins_list = [name.strip() for name in analysis_plugins_string.split(',')]
analysis_plugins = self._analysis_manager.GetPluginObjects(analysis_plugins_list)
return analysis_plugins.valu... | Retrieves analysis plugins.
Args:
analysis_plugins_string (str): comma separated names of analysis plugins
to enable.
Returns:
list[AnalysisPlugin]: analysis plugins. | codesearchnet |
def getAll(self, event_name):
raw_events = self.callEventGetAllRpc(self._id, event_name)
return [callback_event.from_dict(msg) for msg in raw_events] | Gets all existing events in the server with the specified identifier.
This is a non-blocking call.
Args:
event_name: str, the name of the event to get.
Returns:
A list of CallbackEvent, each representing an event from the Server side. | github-repos |
def initialize_repository(path, spor_dir='.spor'):
path = pathlib.Path(path)
spor_path = (path / spor_dir)
if spor_path.exists():
raise ValueError('spor directory already exists: {}'.format(spor_path))
spor_path.mkdir()
return Repository(path, spor_dir) | Initialize a spor repository in `path` if one doesn't already exist.
Args:
path: Path to any file or directory within the repository.
spor_dir: The name of the directory containing spor data.
Returns: A `Repository` instance.
Raises:
ValueError: A repository already exists at `path`. | codesearchnet |
def ns(self, value):
if value == self._defaults['ns'] and 'ns' in self._values:
del self._values['ns']
else:
self._values['ns'] = value | The ns property.
Args:
value (string). the property value. | juraj-google-style |
def __init__(self, feed_merger):
self.feed_merger = feed_merger
self._num_merged = 0
self._num_not_merged_a = 0
self._num_not_merged_b = 0 | Initialise.
Args:
feed_merger: The FeedMerger. | juraj-google-style |
def AddLabel(self, label):
if (not isinstance(label, py2to3.STRING_TYPES)):
raise TypeError('label is not a string type. Is {0:s}'.format(type(label)))
if (not self._VALID_LABEL_REGEX.match(label)):
raise ValueError('Unsupported label: "{0:s}". A label must only consist of alphanumeric character... | Adds a label to the event tag.
Args:
label (str): label.
Raises:
TypeError: if the label provided is not a string.
ValueError: if a label is malformed. | codesearchnet |
def add_trial(self, trial):
trial.set_verbose(self._verbose)
self._trials.append(trial)
with warn_if_slow("scheduler.on_trial_add"):
self._scheduler_alg.on_trial_add(self, trial)
self.trial_executor.try_checkpoint_metadata(trial) | Adds a new trial to this TrialRunner.
Trials may be added at any time.
Args:
trial (Trial): Trial to queue. | juraj-google-style |
def lookup_subclass(cls, d):
try:
typeid = d['typeid']
except KeyError:
raise FieldError(('typeid not present in keys %s' % list(d)))
subclass = cls._subcls_lookup.get(typeid, None)
if (not subclass):
raise FieldError(("'%s' not a valid typeid" % typeid))
else:
return... | Look up a class based on a serialized dictionary containing a typeid
Args:
d (dict): Dictionary with key "typeid"
Returns:
Serializable subclass | codesearchnet |
def process_resource(self, req, resp, resource, uri_kwargs=None):
if 'user' in req.context:
return
identifier = self.identify(req, resp, resource, uri_kwargs)
user = self.try_storage(identifier, req, resp, resource, uri_kwargs)
if user is not None:
req.... | Process resource after routing to it.
This is basic falcon middleware handler.
Args:
req (falcon.Request): request object
resp (falcon.Response): response object
resource (object): resource object matched by falcon router
uri_kwargs (dict): additional keyword argument from uri template.
For ``falcon<1.0.0`` this is a... | juraj-google-style |
def __call__(self, index, s):
if self.colorize:
self._color_wrap(index, s)
else:
print(s) | Print the output, colorized or not, depending on the environment.
Args:
index (int): The instance number.
s (str): The string to print. | juraj-google-style |
def importGurobiSolution(self, grbmodel):
self.eval(''.join(
'let {} := {};'.format(var.VarName, var.X)
for var in grbmodel.getVars()
if '$' not in var.VarName
)) | Import the solution from a gurobipy.Model object.
Args:
grbmodel: A :class:`gurobipy.Model` object with the model solved. | juraj-google-style |
def DecoderLayer(feature_depth, feedforward_depth, num_heads, dropout, mode):
return layers.Serial(layers.Residual(layers.LayerNorm(), layers.Branch(), layers.Parallel(layers.Identity(), layers.CausalMask(axis=(- 2))), layers.MultiHeadedAttention(feature_depth, num_heads=num_heads, dropout=dropout, mode=mode), laye... | Transformer decoder layer.
Args:
feature_depth: int: depth of embedding
feedforward_depth: int: depth of feed-forward layer
num_heads: int: number of attention heads
dropout: float: dropout rate (how much to drop out)
mode: str: 'train' or 'eval'
Returns:
the layer. | codesearchnet |
def swo_stop(self):
res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.STOP, 0)
if res < 0:
raise errors.JLinkException(res)
return None | Stops collecting SWO data.
Args:
self (JLink): the ``JLink`` instance
Returns:
``None``
Raises:
JLinkException: on error | juraj-google-style |
def check_streamers(self, blacklist=None):
ready = []
selected = set()
for (i, streamer) in enumerate(self.streamers):
if ((blacklist is not None) and (i in blacklist)):
continue
if (i in selected):
continue
marked = False
if (i in self._manually_trigg... | Check if any streamers are ready to produce a report.
You can limit what streamers are checked by passing a set-like
object into blacklist.
This method is the primary way to see when you should poll a given
streamer for its next report.
Note, this function is not idempotent. If a streamer is marked as
manual and it... | codesearchnet |
def FindChecks(cls, artifact=None, os_name=None, cpe=None, labels=None, restrict_checks=None):
check_ids = set()
conditions = list(cls.Conditions(artifact, os_name, cpe, labels))
for (chk_id, chk) in iteritems(cls.checks):
if (restrict_checks and (chk_id not in restrict_checks)):
continu... | Takes targeting info, identifies relevant checks.
FindChecks will return results when a host has the conditions necessary for
a check to occur. Conditions with partial results are not returned. For
example, FindChecks will not return checks that if a check targets
os_name=["Linux"], labels=["foo"] and a host only has ... | codesearchnet |
def to_pytd_def(self, val: abstract.BaseValue) -> pytd.Node:
if isinstance(val, abstract.SimpleClass):
return self._class_to_pytd_def(val)
elif isinstance(val, abstract.BaseFunction):
return self._function_to_pytd_def(val)
else:
raise NotImplementedError(f'to_pytd_def() not implement... | Returns the pytd definition of the abstract value.
For example, if the abstract value is:
InterpreterClass(name='C', members={'x': PythonConstant(0)})
then to_pytd_def() produces:
pytd.Class(name='C',
constants=(pytd.Constant(name='x', type=pytd.NamedType(int)),))
Args:
val: The abstract value. | github-repos |
def _GetKeysDefaultEmpty(self, top_level, keys, depth=1):
keys = set(keys)
match = {}
if depth == 1:
for key in keys:
value = top_level.get(key, None)
if value is not None:
match[key] = value
else:
for _, parsed_key, parsed_value in plist_interface.RecurseKey(... | Retrieves plist keys, defaulting to empty values.
Args:
top_level (plistlib._InternalDict): top level plist object.
keys (set[str]): names of keys that should be returned.
depth (int): depth within the plist, where 1 is top level.
Returns:
dict[str, str]: values of the requested keys. | juraj-google-style |
def getValue(self, scalarExpression):
return lock_and_call((lambda : Utils.castVariant(self._impl.getValue(scalarExpression))), self._lock) | Get a scalar value from the underlying AMPL interpreter, as a double or
a string.
Args:
scalarExpression: An AMPL expression which evaluates to a scalar
value.
Returns:
The value of the expression. | codesearchnet |
def genUserCert(self, name, signas=None, outp=None, csr=None):
(pkey, cert) = self._genBasePkeyCert(name, pkey=csr)
cert.add_extensions([crypto.X509Extension(b'nsCertType', False, b'client'), crypto.X509Extension(b'keyUsage', False, b'digitalSignature'), crypto.X509Extension(b'extendedKeyUsage', False, b'client... | Generates a user keypair.
Args:
name (str): The name of the user keypair.
signas (str): The CA keypair to sign the new user keypair with.
outp (synapse.lib.output.Output): The output buffer.
csr (OpenSSL.crypto.PKey): The CSR public key when generating the keypair from a CSR.
Examples:
Generate a user cert for the us... | codesearchnet |
def getValue(self, scalarExpression):
return lock_and_call(
lambda: Utils.castVariant(self._impl.getValue(scalarExpression)),
self._lock
) | Get a scalar value from the underlying AMPL interpreter, as a double or
a string.
Args:
scalarExpression: An AMPL expression which evaluates to a scalar
value.
Returns:
The value of the expression. | juraj-google-style |
def _Open(self, path_spec=None, mode='rb'):
if not path_spec:
raise ValueError('Missing path specification.')
file_system = resolver.Resolver.OpenFileSystem(
path_spec, resolver_context=self._resolver_context)
file_entry = file_system.GetFileEntryByPathSpec(path_spec)
if not file_en... | Opens the file-like object defined by path specification.
Args:
path_spec (Optional[PathSpec]): path specification.
mode (Optional[str]): file access mode.
Raises:
AccessError: if the access to open the file was denied.
IOError: if the file-like object could not be opened.
OSError: if the file-like object could not b... | juraj-google-style |
def convert_rgb(self, image):
self._ensure_format_supported(image)
if not isinstance(image, PIL.Image.Image):
return image
return image.convert('RGB') | Converts `PIL.Image.Image` to RGB format.
Args:
image (`PIL.Image.Image`):
The image to convert. | github-repos |
def _format_variant(self, case_id, gemini_variant, individual_objs,
index=0, add_all_info=False):
chrom = gemini_variant['chrom']
if chrom.startswith('chr') or chrom.startswith('CHR'):
chrom = chrom[3:]
variant_dict = {
'CHROM':chrom,
... | Make a puzzle variant from a gemini variant
Args:
case_id (str): related case id
gemini_variant (GeminiQueryRow): The gemini variant
individual_objs (list(dict)): A list of Individuals
index(int): The index of the variant
Returns:
variant (dict): A Variant object | juraj-google-style |
def agg_wt_avg(mat, min_wt=0.01, corr_metric='spearman'):
assert (mat.shape[1] > 0), 'mat is empty! mat: {}'.format(mat)
if (mat.shape[1] == 1):
out_sig = mat
upper_tri_df = None
raw_weights = None
weights = None
else:
assert (corr_metric in ['spearman', 'pearson'])
... | Aggregate a set of replicate profiles into a single signature using
a weighted average.
Args:
mat (pandas df): a matrix of replicate profiles, where the columns are
samples and the rows are features; columns correspond to the
replicates of a single perturbagen
min_wt (float): Minimum raw weight when calculating weight... | codesearchnet |
def run_config(self, project, run=None, entity=None):
query = gql()
response = self.gql(query, variable_values={
'name': project, 'run': run, 'entity': entity
})
if response['model'] == None:
raise ValueError("Run {}/{}/{} not found".format(entity, proje... | Get the relevant configs for a run
Args:
project (str): The project to download, (can include bucket)
run (str, optional): The run to download
entity (str, optional): The entity to scope this project to. | juraj-google-style |
def read_proto(filename: str, proto_cls: Type[_T]) -> _T:
filepath = _fhir_filepath_from(filename)
proto = proto_cls()
raw_proto = ''
with open(filepath, 'r', encoding='utf-8') as f:
raw_proto = f.read()
text_format.Parse(raw_proto, proto)
return proto | Reads protobuf information from filename relative to the fhir/ root dir.
Data is serialized into an instance of `proto_cls`.
Args:
filename: The file to read from.
proto_cls: The type of protobuf message to look for and return.
Returns:
The protobuf message in the file. | github-repos |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.