code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def item_to_mrc(code, val):
if isinstance(val, basestring):
return [val_to_mrc(code, val)]
if isinstance(val, dict):
val = [val]
return dicts_to_mrc(code, val) | Convert `val` to MRC, whether it is dict or string.
Args:
code (str): Code of the field.
val (str or dict): Value of the field.
Returns:
list: MRC lines for output template. | codesearchnet |
def from_hising(cls, h, J, offset=None):
poly = {(k,): v for (k, v) in h.items()}
poly.update(J)
if (offset is not None):
poly[frozenset([])] = offset
return cls(poly, Vartype.SPIN) | Construct a binary polynomial from a higher-order Ising problem.
Args:
h (dict):
The linear biases.
J (dict):
The higher-order biases.
offset (optional, default=0.0):
Constant offset applied to the model.
Returns:
:obj:`.BinaryPolynomial`
Examples:
>>> poly = dimod.BinaryPolynomial.from_hising({'a': 2}, {'ab': -1}... | codesearchnet |
def auto_batch_size(sequence_length,
mesh_shape,
layout_rules,
tokens_per_split=2048):
num_splits = mtf.tensor_dim_to_mesh_dim_size(
layout_rules, mesh_shape, mtf.Dimension("batch", 0))
ret = max(1, tokens_per_split
tf.logging.info(
"AUTO... | Automatically compute batch size.
Args:
sequence_length: an integer
mesh_shape: an input to mtf.convert_to_shape()
layout_rules: an input to mtf.convert_to_layout_rules()
tokens_per_split: an integer
Returns:
an integer | juraj-google-style |
def get_global_vars(func):
closure = getclosurevars(func)
if closure['nonlocal']:
raise TypeError("Can't launch a job with closure variables: %s" %
closure['nonlocals'].keys())
globalvars = dict(modules={},
functions={},
vars={... | Store any methods or variables bound from the function's closure
Args:
func (function): function to inspect
Returns:
dict: mapping of variable names to globally bound VARIABLES | juraj-google-style |
def usufyToGmlExport(d, fPath):
try:
oldData = nx.read_gml(fPath)
except UnicodeDecodeError as e:
print(('UnicodeDecodeError:\t' + str(e)))
print('Something went wrong when reading the .gml file relating to the decoding of UNICODE.')
import time as time
fPath += ('_' + st... | Workaround to export data to a .gml file.
Args:
-----
d: Data to export.
fPath: File path for the output file. | codesearchnet |
def unflatten1(flat_list, reverse_list):
unflat_list2 = [[flat_list[index] for index in tup]
for tup in reverse_list]
return unflat_list2 | Rebuilds unflat list from invertible_flatten1
Args:
flat_list (list): the flattened list
reverse_list (list): the list which undoes flattenting
Returns:
unflat_list2: original nested list
SeeAlso:
invertible_flatten1
invertible_flatten2
unflatten2 | juraj-google-style |
def connect(self, host='localhost'):
get_logger().info("Connecting to RabbitMQ server...")
self._conn = pika.BlockingConnection(
pika.ConnectionParameters(host=host))
self._channel = self._conn.channel()
get_logger().info("Declaring topic excha... | Connect to the server and set everything up.
Args:
host: hostname to connect to | juraj-google-style |
def is_valid(self, tol: float = DISTANCE_TOLERANCE) -> bool:
if len(self.sites) == 1:
return True
all_dists = self.distance_matrix[np.triu_indices(len(self), 1)]
return bool(np.min(all_dists) > tol) | True if SiteCollection does not contain atoms that are too close
together. Note that the distance definition is based on type of
SiteCollection. Cartesian distances are used for non-periodic
Molecules, while PBC is taken into account for periodic structures.
Args:
tol (float): Distance tolerance. Default is 0.5A.
Ret... | juraj-google-style |
def relaxed_value_for_var(value, var):
assert isinstance(var, tf.Variable)
name = var.op.name
varshape = tuple(var.get_shape().as_list())
if varshape != value.shape:
if np.prod(varshape) != np.prod(value.shape):
raise ValueError... | Returns a relaxed (possibly reshaped/upcast-ed) version of value,
to be loaded to the given variable.
Args:
value (ndarray): an numpy array to be loaded to var
var (tf.Variable):
Returns:
ndarray: a possibly reshaped or casted version of value | juraj-google-style |
def _CheckStorageFile(self, storage_file_path):
if os.path.exists(storage_file_path):
if (not os.path.isfile(storage_file_path)):
raise errors.BadConfigOption('Storage file: {0:s} already exists and is not a file.'.format(storage_file_path))
logger.warning('Appending to an already existi... | Checks if the storage file path is valid.
Args:
storage_file_path (str): path of the storage file.
Raises:
BadConfigOption: if the storage file path is invalid. | codesearchnet |
def listdir(*paths, glob=None):
path = genpath(*paths)
names = os.listdir(path)
if glob is not None:
names = fnmatch.filter(names, glob)
retn = [os.path.join(path, name) for name in names]
return retn | List the (optionally glob filtered) full paths from a dir.
Args:
*paths ([str,...]): A list of path elements
glob (str): An optional fnmatch glob str | juraj-google-style |
def __getitem__(self, thing: Any) -> np.ndarray:
if type(thing) is slice or type(thing) is np.ndarray or type(thing) is int:
am = AttributeManager(None, axis=self.axis)
for key, val in self.items():
am[key] = val[thing]
return am
elif type(thing) is tuple:
result: np.ndarray = None
for t i... | Return a named attribute, or a slice through all the attributes
Args:
thing: if string, return the named attribute
if slice, np.ndarray or int, return a slice through all the attributes | juraj-google-style |
def fit(self, X, y):
self.X = X
self.y = y | Fit
Args:
X (np.array): Array of hyperparameter values with shape (n_samples, len(tunables))
y (np.array): Array of scores with shape (n_samples, ) | juraj-google-style |
def Delete(self, request, global_params=None):
config = self.GetMethodConfig('Delete')
return self._RunMethod(config, request, global_params=global_params) | Deletes the model specified by modelId from the dataset.
Args:
request: (BigqueryModelsDeleteRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(BigqueryModelsDeleteResponse) The response message. | github-repos |
def is_flash_attention_enabled():
from keras.src.backend.common import global_state
return global_state.get_global_attribute('flash_attention', default=None) | Checks whether flash attention is globally enabled in Keras.
Flash attention is a performance-optimized method for computing attention
in large models, such as transformers, allowing for faster and more
memory-efficient operations. This function checks the global Keras
configuration to determine if flash attention is ... | github-repos |
def cancel_all(self, product_id=None):
if (product_id is not None):
params = {'product_id': product_id}
else:
params = None
return self._send_message('delete', '/orders', params=params) | With best effort, cancel all open orders.
Args:
product_id (Optional[str]): Only cancel orders for this
product_id
Returns:
list: A list of ids of the canceled orders. Example::
[
"144c6f8e-713f-4682-8435-5280fbe8b2b4",
"debe4907-95dc-442f-af3b-cec12f42ebda",
"cf7aceee-7b08-4227-a76c-3858144323ab",
"dfc5ae27-cadb-4c0... | codesearchnet |
def add_import(self, symbol, source_module_name, source_name, dest_module_name, dest_name):
if source_module_name.endswith('python.modules_with_exports'):
source_module_name = symbol.__module__
import_str = self.format_import(source_module_name, source_name, dest_name)
full_api_name = dest_name
... | Adds this import to module_imports.
Args:
symbol: TensorFlow Python symbol.
source_module_name: (string) Module to import from.
source_name: (string) Name of the symbol to import.
dest_module_name: (string) Module name to add import to.
dest_name: (string) Import the symbol using this name.
Raises:
SymbolExposedTwice... | github-repos |
def get_list(self, **query_params):
list_json = self.get_list_json(self.base_uri, query_params=query_params)
return self.create_list(list_json) | Get list information for this card. Returns a List object.
Returns:
List: The list this card is attached to | codesearchnet |
def get_sonos_playlist_by_attr(self, attr_name, match):
for sonos_playlist in self.get_sonos_playlists():
if (getattr(sonos_playlist, attr_name) == match):
return sonos_playlist
raise ValueError('No match on "{0}" for value "{1}"'.format(attr_name, match)) | Return the first Sonos Playlist DidlPlaylistContainer that
matches the attribute specified.
Args:
attr_name (str): DidlPlaylistContainer attribute to compare. The
most useful being: 'title' and 'item_id'.
match (str): Value to match.
Returns:
(:class:`~.soco.data_structures.DidlPlaylistContainer`): The
first matching... | codesearchnet |
def _ParseCacheEntries(self, parser_mediator, index_table, data_block_files):
for cache_address in index_table:
cache_address_chain_length = 0
while cache_address.value != 0:
if cache_address_chain_length >= 64:
parser_mediator.ProduceExtractionWarning(
'Maximum... | Parses Chrome Cache file entries.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
index_table (list[CacheAddress]): the cache addresses which are stored in
the index file.
data_block_files (dict[str: file]): look up table for the data block... | juraj-google-style |
def get_storage(request):
storage_model = oauth2_settings.storage_model
user_property = oauth2_settings.storage_model_user_property
credentials_property = oauth2_settings.storage_model_credentials_property
if storage_model:
module_name, class_name = storage_model.rsplit('.', 1)
mod... | Gets a Credentials storage object provided by the Django OAuth2 Helper
object.
Args:
request: Reference to the current request object.
Returns:
An :class:`oauth2.client.Storage` object. | juraj-google-style |
def save(self, resource):
resource_type = None
xid = None
if isinstance(resource, dict):
resource_type = resource.get('type')
xid = resource.get('xid')
else:
resource_type = resource.type
xid = resource.xid
if resource_typ... | Save group|indicator dict or object to shelve.
Best effort to save group/indicator data to disk. If for any reason the save fails
the data will still be accessible from list in memory.
Args:
resource (dict|obj): The Group or Indicator dict or object. | juraj-google-style |
def _ConvertMessageDescriptor(self, desc_proto, package=None, file_desc=None,
scope=None, syntax=None):
if package:
desc_name = '.'.join((package, desc_proto.name))
else:
desc_name = desc_proto.name
if file_desc is None:
file_name = None
else:
... | Adds the proto to the pool in the specified package.
Args:
desc_proto: The descriptor_pb2.DescriptorProto protobuf message.
package: The package the proto should be located in.
file_desc: The file containing this message.
scope: Dict mapping short and full symbols to message and enum types.
syntax: string indicating s... | juraj-google-style |
def build_url(self):
url = '{protocol}/{url}/{rest}/{version}/{restapi}/{rscpath}/{query}'.format(protocol=self.schema.protocol, url=self.schema.main_url, rest=self.schema.rest, version=self.schema.version, restapi=self.schema.restApi, rscpath=self.schema.resourcePath, query=self.schema.query)
return url.replac... | Builds the URL for elevations API services based on the data given
by the user.
Returns:
url (str): URL for the elevations API services | codesearchnet |
def _check_sleep(self, op):
delay = 0.3
start_t = time.time()
func = tf.function(lambda: op(delay))
results = self.evaluate(func())
end_t = time.time()
delta_t = end_t - start_t
self.assertEqual(results.shape, tuple())
self.assertGreater(delta_t, 0.9 * delay) | Check that one sleep op works in isolation.
See sleep_bin.py for an example of how the synchronous and asynchronous
sleep ops differ in behavior.
Args:
op: The sleep op, either sleep_op.SyncSleep or sleep_op.AsyncSleep. | github-repos |
def setOutBoundLinkQuality(self, LinkQuality):
print '%s call setOutBoundLinkQuality' % self.port
print LinkQuality
try:
cmd = 'macfilter rss add-lqi * %s' % str(LinkQuality)
print cmd
return self.__sendCommand(cmd)[0] == 'Done'
except Excepti... | set custom LinkQualityIn for all receiving messages from the any address
Args:
LinkQuality: a given custom link quality
link quality/link margin mapping table
3: 21 - 255 (dB)
2: 11 - 20 (dB)
1: 3 - 9 (dB)
0: 0 - 2 (dB)
Returns:
True: successful to set the link quality
False: fail to set the link quality | juraj-google-style |
def get_processed_events(self) -> List[Event]:
event_ids = DB.get_list(self._processed_key)
events = []
for event_id in event_ids:
event_str = DB.get_hash_value(self._data_key, event_id)
event_dict = ast.literal_eval(event_str)
event_dict['id'] = event_id
event_dict['subscrib... | Get all processed events.
This method is intended to be used to recover events stuck in the
processed state which could happen if an event handling processing
an processed event goes down before completing the event processing.
Returns:
list[Events], list of event objects. | codesearchnet |
def read_xyz(cls, buf, start_index=0, get_bonds=True,
nrows=None, engine=None):
frame = pd.read_table(buf, skiprows=2, comment='
nrows=nrows,
delim_whitespace=True,
names=['atom', 'x', 'y', 'z'], ... | Read a file of coordinate information.
Reads xyz-files.
Args:
inputfile (str):
start_index (int):
get_bonds (bool):
nrows (int): Number of rows of file to read.
Note that the first two rows are implicitly excluded.
engine (str): Wrapper for argument of :func:`pandas.read_csv`.
Returns:
Cartesian: | juraj-google-style |
def read_windows_environ():
res = winapi.GetEnvironmentStringsW()
if (not res):
raise ctypes.WinError()
res = ctypes.cast(res, ctypes.POINTER(ctypes.c_wchar))
done = []
current = u''
i = 0
while 1:
c = res[i]
i += 1
if (c == u'\x00'):
if (not curre... | Returns a unicode dict of the Windows environment.
Raises:
WindowsEnvironError | codesearchnet |
def convert_upsample(params, w_name, scope_name, inputs, layers, weights, names):
print('Converting upsample...')
if params['mode'] != 'nearest':
raise AssertionError('Cannot convert non-nearest upsampling')
if names == 'short':
tf_name = 'UPSL' + random_string(4)
elif names == 'k... | Convert nearest upsampling layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras layers | juraj-google-style |
def GetMessages(self, formatter_mediator, event):
if self.DATA_TYPE != event.data_type:
raise errors.WrongFormatter('Unsupported data type: {0:s}.'.format(
event.data_type))
event_values = event.CopyToDict()
login_type = event_values.get('type', None)
if login_type is None:
... | Determines the formatted message strings for an event object.
Args:
formatter_mediator (FormatterMediator): mediates the interactions
between formatters and other components, such as storage and Windows
EventLog resources.
event (EventObject): event.
Returns:
tuple(str, str): formatted message string and short messag... | juraj-google-style |
def average(numbers, numtype='float'):
if type == 'decimal':
return Decimal(sum(numbers)) / len(numbers)
else:
return float(sum(numbers)) / len(numbers) | Calculates the average or mean of a list of numbers
Args:
numbers: a list of integers or floating point numbers.
numtype: string, 'decimal' or 'float'; the type of number to return.
Returns:
The average (mean) of the numbers as a floating point number
or a Decimal object.
Requires:
The math module | juraj-google-style |
def _compile_pvariable_expression(self, expr: Expression, scope: Dict[(str, TensorFluent)], batch_size: Optional[int]=None, noise: Optional[List[tf.Tensor]]=None) -> TensorFluent:
etype = expr.etype
args = expr.args
name = expr._pvar_to_name(args)
if (name not in scope):
raise ValueError('Variab... | Compile a pvariable expression `expr` into a TensorFluent
in the given `scope` with optional batch size.
Args:
expr (:obj:`rddl2tf.expr.Expression`): A RDDL pvariable expression.
scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope.
batch_size (Optional[size]): The batch size.
Returns:
:obj:`rddl2tf.... | codesearchnet |
def preview(self, n=10, k='items', kheader='displayLink', klink='link', kdescription='snippet'):
if 'searchType' in self.cseargs:
searchType = self.cseargs['searchType']
else:
searchType = None
items = self.metadata[k]
for i, kv in enumerate(items[:n]):
if 'start' in self.... | Print a preview of the search results.
Args:
n (int):
Maximum number of search results to preview
k (str):
Key in :class:`api.results`.metadata to preview
kheader (str):
Key in :class:`api.results`.metadata[``k``] to use as the header
klink (str):
Key in :class:`api.results`.metadata[``k``] to use as the link if image... | juraj-google-style |
def _full_shape_filter(t: List, shapes: List) -> bool:
if shapes:
for a_token in t:
if a_token._.full_shape not in shapes:
return False
return True | Shape filter
Args:
t: List, list of tokens
shapes: List
Returns: bool | juraj-google-style |
def isbase(path1, path2):
_path1 = forcedir(abspath(path1))
_path2 = forcedir(abspath(path2))
return _path2.startswith(_path1) | Check if ``path1`` is a base of ``path2``.
Arguments:
path1 (str): A PyFilesytem path.
path2 (str): A PyFilesytem path.
Returns:
bool: `True` if ``path2`` starts with ``path1``
Example:
>>> isbase('foo/bar', 'foo/bar/baz/egg.txt')
True | codesearchnet |
def _is_quantized_input_stats_required(conversion_flags: _conversion_flags_pb2.ConverterFlags) -> bool:
quantized_inference_types = [_types_pb2.QUANTIZED_UINT8, _types_pb2.QUANTIZED_INT8]
return (conversion_flags.inference_type in quantized_inference_types or conversion_flags.inference_input_type in quantized_i... | Checks if the `quantized_input_stats` flag is required for conversion.
Args:
conversion_flags: A protocol buffer describing the conversion process.
Returns:
True, if the `inference_type` or the `inference_input_type` is a quantized
type and it is not post training quantization, else False. | github-repos |
def set_default(self, default: Any, use_default_apply: bool=True, root_path: Optional[utils.KeyPath]=None) -> 'ValueSpec': | Sets the default value and returns `self`.
Args:
default: Default value.
use_default_apply: If True, invoke `apply` to the value, otherwise use
default value as is.
root_path: (Optional) The path of the field.
Returns:
ValueSpec itself.
Raises:
ValueError: If default value cannot be applied when use_default_apply
is... | github-repos |
def load_data(self, data, datatype='ttl', namespace=None, graph=None, is_file=False, **kwargs):
log.setLevel(kwargs.get('log_level', self.log_level))
time_start = datetime.datetime.now()
datatype_map = {'ttl': 'text/turtle', 'xml': 'application/rdf+xml', 'rdf': 'application/rdf+xml', 'nt': 'text/plain'}
... | Loads data via file stream from python to triplestore
Args:
-----
data: The data or filepath to load
datatype(['ttl', 'xml', 'rdf']): the type of data to load
namespace: the namespace to use
graph: the graph to load the data to.
is_file(False): If true python will read the data argument as a
filepath, determine the da... | codesearchnet |
def group(text, size):
if (size <= 0):
raise ValueError('n must be a positive integer')
return [text[i:(i + size)] for i in range(0, len(text), size)] | Group ``text`` into blocks of ``size``.
Example:
>>> group("test", 2)
['te', 'st']
Args:
text (str): text to separate
size (int): size of groups to split the text into
Returns:
List of n-sized groups of text
Raises:
ValueError: If n is non positive | codesearchnet |
def coupling(self, source_y, target_y, weight):
return ((np.ones_like(target_y) * np.mean(source_y)) * weight) | How to couple the output of one subsystem to the input of another.
This is a fallback default coupling function that should usually be
replaced with your own.
This example coupling function takes the mean of all variables of the
source subsystem and uses that value weighted by the connection
strength to drive all var... | codesearchnet |
def coalescence_waiting_times(self, backward=True):
if not isinstance(backward, bool):
raise TypeError("backward must be a bool")
times = list(); lowest_leaf_dist = float('-inf')
for n,d in self.distances_from_root():
if len(n.children) > 1:
times... | Generator over the waiting times of successive coalescence events
Args:
``backward`` (``bool``): ``True`` to go backward in time (i.e., leaves to root), otherwise ``False`` | juraj-google-style |
def decode_payload(cls, request):
if (request.headers.get(cls.PAYLOAD_VERSION_HEADER) != cls.PAYLOAD_VERSION):
raise DeprecationWarning('Task is generated by an older incompatible version of mapreduce. Please kill this job manually')
return cls._decode_payload(request.body) | Decode task payload.
HugeTask controls its own payload entirely including urlencoding.
It doesn't depend on any particular web framework.
Args:
request: a webapp Request instance.
Returns:
A dict of str to str. The same as the params argument to __init__.
Raises:
DeprecationWarning: When task payload constructed fr... | codesearchnet |
def _transform_indices(self, key):
ndims = self.ndims
if all(not (isinstance(el, slice) or callable(el)) for el in key):
dim_inds = []
for dim in self.kdims:
dim_type = self.get_dimension_type(dim)
if isinstance(dim_type, type) and issubcl... | Snaps indices into the GridSpace to the closest coordinate.
Args:
key: Tuple index into the GridSpace
Returns:
Transformed key snapped to closest numeric coordinates | juraj-google-style |
def serialize_to_list(self, name, datas):
items = datas.get('items', None)
splitter = datas.get('splitter', self._DEFAULT_SPLITTER)
if (items is None):
msg = "List reference '{}' lacks of required 'items' variable or is empty"
raise SerializerError(msg.format(name))
else:
items =... | Serialize given datas to a list structure.
List structure is very simple and only require a variable ``--items``
which is a string of values separated with an empty space. Every other
properties are ignored.
Arguments:
name (string): Name only used inside possible exception message.
datas (dict): Datas to serialize.
... | codesearchnet |
def get_load_balancer(self, id):
return LoadBalancer.get_object(api_token=self.token, id=id) | Returns a Load Balancer object by its ID.
Args:
id (str): Load Balancer ID | codesearchnet |
def from_sub_model_configs(cls, text_config: ClvpEncoderConfig, speech_config: ClvpEncoderConfig, decoder_config: ClvpDecoderConfig, **kwargs):
return cls(text_config=text_config.to_dict(), speech_config=speech_config.to_dict(), decoder_config=decoder_config.to_dict(), **kwargs) | Instantiate a [`ClvpConfig`] (or a derived class) from CLVP text model configuration, CLVP speech model
configuration and CLVP decoder model configuration.
Args:
text_config (`ClvpEncoderConfig`):
Text model configuration of type [`ClvpEncoderConfig`].
speech_config (`ClvpEncoderConfig`):
Speech model configuration of... | github-repos |
def pop(stack, op_id):
if __debug__:
pushed_value, pushed_op_id = stack.pop()
assert pushed_op_id == op_id, 'Wanted %s, got %s' % (op_id, pushed_op_id)
else:
pushed_value = stack.pop()
return pushed_value | Pop a value from the stack (i.e. read it from the tape).
Args:
stack: The stack to pop from.
op_id: A unique variable that is also passed into the matching push.
Allows optimization passes to track pairs of pushes and pops.
Returns:
The last value. | juraj-google-style |
def __init__(self, graph, canonical_device=None):
self._graph = graph
self.canonical_device = canonical_device
self._operations = self._initialize_operations()
self._operation_name_to_id = self._initialize_operation_name_to_id()
self._tensor_name_to_ids = self._initialize_tensor_name_to_ids()
... | Initializer.
Args:
graph: either a tf.Graph or mtf.Graph.
canonical_device: optional string, the name of the canonical device for
IsTensoronCanonicalDevice. | juraj-google-style |
def ExtractEvents(self, parser_mediator, registry_key, **kwargs):
for subkey in registry_key.GetSubkeys():
values_dict = {}
values_dict['subkey_name'] = subkey.name
vendor_identification = None
product_identification = None
try:
subkey_name_parts = subkey.name.split('&')
... | Extracts events from a Windows Registry key.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_key (dfwinreg.WinRegistryKey): Windows Registry key. | juraj-google-style |
def remove(path, force=False):
path = os.path.expanduser(path)
if (not os.path.isabs(path)):
raise SaltInvocationError('File path must be absolute: {0}'.format(path))
if ((not os.path.exists(path)) and (not is_link(path))):
raise CommandExecutionError('Path not found: {0}'.format(path))
... | Remove the named file or directory
Args:
path (str): The path to the file or directory to remove.
force (bool): Remove even if marked Read-Only. Default is False
Returns:
bool: True if successful, False if unsuccessful
CLI Example:
.. code-block:: bash
salt '*' file.remove C:\\Temp | codesearchnet |
def to_proto(self, export_scope=None):
if export_scope is None or self.name.startswith(export_scope):
context_def = control_flow_pb2.WhileContextDef()
context_def.context_name = ops.strip_name_scope(self.name, export_scope)
context_def.parallel_iterations = self._parallel_iterations
... | Converts a `WhileContext` to a `WhileContextDef` protocol buffer.
Args:
export_scope: Optional `string`. Name scope to remove.
Returns:
A `WhileContextDef` protocol buffer. | github-repos |
def __init__(self, scope, parent, id, name, result):
CodeEntity.__init__(self, scope, parent)
self.id = id
self.name = name
self.result = result
self.value = None
self.member_of = None
self.references = []
self.writes = [] | Constructor for variables.
Args:
scope (CodeEntity): The program scope where this object belongs.
parent (CodeEntity): This object's parent in the program tree.
id: An unique identifier for this variable.
name (str): The name of the variable in the program.
result (str): The type of the variable in the program. | juraj-google-style |
def InsertAll(self, request, global_params=None):
config = self.GetMethodConfig('InsertAll')
return self._RunMethod(config, request, global_params=global_params) | Streams data into BigQuery one record at a time without needing to run a load job. Requires the WRITER dataset role.
Args:
request: (BigqueryTabledataInsertAllRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(TableDataInsertAllResponse) The response message. | github-repos |
def refactor_tree(self, tree, name):
for fixer in chain(self.pre_order, self.post_order):
fixer.start_tree(tree, name)
self.traverse_by(self.bmi_pre_order_heads, tree.pre_order())
self.traverse_by(self.bmi_post_order_heads, tree.post_order())
mat... | Refactors a parse tree (modifying the tree in place).
For compatible patterns the bottom matcher module is
used. Otherwise the tree is traversed node-to-node for
matches.
Args:
tree: a pytree.Node instance representing the root of the tree
to be refactored.
name: a human-readable name for this tree.
Returns:
True if... | juraj-google-style |
def Append(self, new_values):
newrow = self.NewRow()
newrow.values = new_values
self._table.append(newrow) | Adds a new row (list) to the table.
Args:
new_values: Tuple, dict, or Row() of new values to append as a row.
Raises:
TableError: Supplied tuple not equal to table width. | juraj-google-style |
def _signal_handler(self, signal_interupt, frame):
if self.container is not None:
print('{}{}Stopping docker container.'.format(c.Style.BRIGHT, c.Fore.YELLOW))
self.container.stop()
print('{}{}Interrupt signal received.'.format(c.Style.BRIGHT, c.Fore.RED))
self... | Handle singal interrupt.
Args:
signal_interupt ([type]): [Description]
frame ([type]): [Description] | juraj-google-style |
def open_sequence(path: Union[str, os.PathLike[str]], mode: str='r', *, perms: Optional[int]=436, serializer: Optional[Callable[[Any], Union[bytes, str]]]=None, deserializer: Optional[Callable[[Union[bytes, str]], Any]]=None, make_dirs_if_not_exist: bool=True) -> Sequence:
if 'w' in mode or 'a' in mode:
par... | Open sequence for reading or writing.
Args:
path: The path to the sequence.
mode: The mode of the sequence.
perms: (Optional) The permissions of the sequence.
serializer: (Optional) A serializer function for converting a structured
object to a string or bytes.
deserializer: (Optional) A deserializer function for conve... | github-repos |
def build_input_pipeline(x, y, batch_size):
training_dataset = tf.data.Dataset.from_tensor_slices((x, y))
training_batches = training_dataset.repeat().batch(batch_size)
training_iterator = tf.compat.v1.data.make_one_shot_iterator(training_batches)
(batch_features, batch_labels) = training_iterator.get_n... | Build a Dataset iterator for supervised classification.
Args:
x: Numpy `array` of features, indexed by the first dimension.
y: Numpy `array` of labels, with the same first dimension as `x`.
batch_size: Number of elements in each training batch.
Returns:
batch_features: `Tensor` feed features, of shape
`[batch_size] ... | codesearchnet |
def gene_by_alias(self, symbol, build='37'):
res = self.hgnc_collection.find({'hgnc_symbol': symbol, 'build':build})
if res.count() == 0:
res = self.hgnc_collection.find({'aliases': symbol, 'build':build})
return res | Return a iterable with hgnc_genes.
If the gene symbol is listed as primary the iterable will only have
one result. If not the iterable will include all hgnc genes that have
the symbol as an alias.
Args:
symbol(str)
build(str)
Returns:
res(pymongo.Cursor(dict)) | juraj-google-style |
def read(url, encoding=None, cache=None, mode='rb'):
with read_handle(url, cache, mode=mode) as handle:
data = handle.read()
if encoding:
data = data.decode(encoding)
return data | Read from any URL.
Internally differentiates between URLs supported by tf.gfile, such as URLs
with the Google Cloud Storage scheme ('gs://...') or local paths, and HTTP
URLs. This way users don't need to know about the underlying fetch mechanism.
Args:
url: a URL including scheme or a local path
mode: mode in which t... | codesearchnet |
def unmanaged_devices(self):
if (not self.__unmanaged_devices):
self.__unmanaged_devices = UnmanagedDevices(self.__connection)
return self.__unmanaged_devices | Gets the Unmanaged Devices API client.
Returns:
UnmanagedDevices: | codesearchnet |
def percentile_nearest(self, percentile):
if self._input_csv_files:
df = self._get_data_from_csv_files()
if 'target' not in df or 'predicted' not in df:
raise ValueError('Cannot find "target" or "predicted" column')
df = df[['target', 'predicted']].apply(pd.to_numeric)
abs_err... | Get nearest percentile from regression model evaluation results.
Args:
percentile: a 0~100 float number.
Returns:
the percentile float number.
Raises:
Exception if the CSV headers do not include 'target' or 'predicted', or BigQuery
does not return 'target' or 'predicted' column, or if target or predicted is not
numb... | juraj-google-style |
def get_duration_h_m(start: Union[str, DateTime],
end: Union[str, DateTime],
default: str = "N/A") -> str:
start = coerce_to_pendulum(start)
end = coerce_to_pendulum(end)
if start is None or end is None:
return default
duration = end - start
min... | Calculate the time between two dates/times expressed as strings.
Args:
start: start date/time
end: end date/time
default: string value to return in case either of the inputs is
``None``
Returns:
a string that is one of
.. code-block:
'hh:mm'
'-hh:mm'
default | juraj-google-style |
def kmip_version(self, value):
if isinstance(value, enums.KMIPVersion):
self.proxy.kmip_version = value
else:
raise ValueError("KMIP version must be a KMIPVersion enumeration") | Set the KMIP version for the client.
Args:
value (KMIPVersion): A KMIPVersion enumeration
Return:
None
Raises:
ValueError: if value is not a KMIPVersion enumeration
Example:
>>> client.kmip_version = enums.KMIPVersion.KMIP_1_1
>>> | juraj-google-style |
def createCategoryFilter(self, filterName, positiveExamples, negativeExamples=[]):
samples = {"positiveExamples": [{"text": s} for s in positiveExamples],
"negativeExamples": [{"text": s} for s in negativeExamples]}
body = json.dumps(samples)
return self._classify.cre... | Get a classifier filter (fingerprint) for positive and negative text samples
Args:
filterName, str: A unique name for the filter. (required)
positiveExamples, list(str): The list of positive example texts. (required)
negativeExamples, list(str): The list of negative example texts. (optional)
Returns:
CategoryFilter
Rai... | juraj-google-style |
def expand_abbreviations(self, text):
if not self.abbreviations:
raise LexiconError("No abbreviations in lexicon.")
def chunks(data, SIZE=25):
it = iter(data)
for i in range(0, len(data), SIZE):
yield {k: data[k] for k in islice(... | Parse a piece of text and replace any abbreviations with their full
word equivalents. Uses the lexicon.abbreviations dictionary to find
abbreviations.
Args:
text (str): The text to parse.
Returns:
str: The text with abbreviations replaced. | juraj-google-style |
def pubsub_pop_message(self, deadline=None):
if (not self.subscribed):
excep = ClientError('you must subscribe before using pubsub_pop_message')
raise tornado.gen.Return(excep)
reply = None
try:
reply = self._reply_list.pop(0)
raise tornado.gen.Return(reply)
except IndexE... | Pops a message for a subscribed client.
Args:
deadline (int): max number of seconds to wait (None => no timeout)
Returns:
Future with the popped message as result (or None if timeout
or ConnectionError object in case of connection errors
or ClientError object if you are not subscribed) | codesearchnet |
def get_orbital_resolved_cohp(self, label, orbitals):
if (self.orb_res_cohp is None):
return None
elif (isinstance(orbitals, list) or isinstance(orbitals, tuple)):
cohp_orbs = [d['orbitals'] for d in self.orb_res_cohp[label].values()]
orbs = []
for orbital in orbitals:
... | Get orbital-resolved COHP.
Args:
label: bond label (Lobster: labels as in ICOHPLIST/ICOOPLIST.lobster).
orbitals: The orbitals as a label, or list or tuple of the form
[(n1, orbital1), (n2, orbital2)]. Orbitals can either be str,
int, or Orbital.
Returns:
A Cohp object if CompleteCohp contains orbital-resolved cohp,... | codesearchnet |
def subscribe(self, requested_timeout=None, auto_renew=False, event_queue=None):
subscription = Subscription(self, event_queue)
subscription.subscribe(requested_timeout=requested_timeout, auto_renew=auto_renew)
return subscription | Subscribe to the service's events.
Args:
requested_timeout (int, optional): If requested_timeout is
provided, a subscription valid for that
number of seconds will be requested, but not guaranteed. Check
`Subscription.timeout` on return to find out what period of
validity is actually allocated.
auto_renew (bool): If au... | codesearchnet |
def _process_update(self, item, feed_item):
item['name'] = feed_item.get(FieldMap.CAMPAIGN_LANDING_PAGE_NAME, None)
item['url'] = feed_item.get(FieldMap.CAMPAIGN_LANDING_PAGE_URL, None) | Updates an landing page based on the values from the feed.
Args:
item: Object representing the landing page to be updated, this object is
updated directly.
feed_item: Feed item representing landing page values from the Bulkdozer
feed. | github-repos |
def list(self, resource):
return self.service.list(
resource, self.url_prefix, self.auth, self.session,
self.session_send_opts) | List metadata keys associated with the given resource.
Args:
resource (intern.resource.boss.BossResource): List keys associated with this resource.
Returns:
(list): List of key names.
Raises:
requests.HTTPError on failure. | juraj-google-style |
def find_first(self, *args, **kwargs):
if capybara.wait_on_first_by_default:
kwargs.setdefault('minimum', 1)
try:
result = self.find_all(*args, **kwargs)
return (result[0] if (len(result) > 0) else None)
except ExpectationNotMet:
return None | Find the first element on the page matching the given selector and options, or None if no
element matches.
By default, no waiting behavior occurs. However, if ``capybara.wait_on_first_by_default``
is set to true, it will trigger Capybara's waiting behavior for a minimum of 1 matching
element to be found.
Args:
*args:... | codesearchnet |
def known(self, words):
tmp = [w.lower() for w in words]
return set((w for w in tmp if ((w in self._word_frequency.dictionary) or (not self._check_if_should_check(w))))) | The subset of `words` that appear in the dictionary of words
Args:
words (list): List of words to determine which are in the \
corpus
Returns:
set: The set of those words from the input that are in the \
corpus | codesearchnet |
def matching_args(fn, dictionary):
arg_spec = getargspec(fn)
if arg_spec.keywords:
return dictionary
return _mapping.split_by_criteria(dictionary, arg_spec.args).included | Given a function fn and a dict dictionary, returns the function arguments that match the dict keys.
Example:
def train(channel_dirs, model_dir): pass
dictionary = {'channel_dirs': {}, 'model_dir': '/opt/ml/model', 'other_args': None}
args = functions.matching_args(train, dictionary) # {'channel_dirs': {}, 'model_di... | codesearchnet |
def check_codes_match(observed_code: str, theoretical_code: str) -> Optional[int]:
observed_code_header = observed_code.split('\n')[0]
theoretical_code_header = theoretical_code.split('\n')[0]
_re_class_match = re.compile('class\\s+([^\\(:]+)(?:\\(|:)')
_re_func_match = re.compile('def\\s+([^\\(]+)\\(')... | Checks if two version of a code match with the exception of the class/function name.
Args:
observed_code (`str`): The code found.
theoretical_code (`str`): The code to match.
Returns:
`Optional[int]`: The index of the first line where there is a difference (if any) and `None` if the codes
match. | github-repos |
def swo_enable(self, cpu_speed, swo_speed=9600, port_mask=1):
if self.swo_enabled():
self.swo_stop()
res = self._dll.JLINKARM_SWO_EnableTarget(cpu_speed, swo_speed, enums.JLinkSWOInterfaces.UART, port_mask)
if (res != 0):
raise errors.JLinkException(res)
self._swo_enabled = True
retu... | Enables SWO output on the target device.
Configures the output protocol, the SWO output speed, and enables any
ITM & stimulus ports.
This is equivalent to calling ``.swo_start()``.
Note:
If SWO is already enabled, it will first stop SWO before enabling it
again.
Args:
self (JLink): the ``JLink`` instance
cpu_speed ... | codesearchnet |
def allreduce(self, x, mesh_axes, reduction_fn_string):
return self._collective_with_groups(
x, mesh_axes, functools.partial(
allreduce_ring, reduction_fn_string=reduction_fn_string)) | Grouped allreduce, (across the given dimensions).
Args:
x: a LaidOutTensor
mesh_axes: a list of integers - the mesh dimensions to be reduced
reduction_fn_string: "SUM" or "MAX"
Returns:
a LaidOutTensor | juraj-google-style |
def replace_characters(self, text, characters, replacement=''):
if not characters:
return text
characters = ''.join(sorted(characters))
if characters in self._characters_regexes:
characters_regex = self._characters_regexes[characters]
else:
c... | Remove characters from text.
Removes custom characters from input text or replaces them
with a string if specified.
Args:
text: The text to be processed.
characters: Characters that will be replaced.
replacement: New text that will replace the custom characters.
Returns:
The text without the given characters. | juraj-google-style |
def __init__(self, project: str, location: str, api_endpoint: str, feature_store_name: str, feature_view_name: str, row_key: str, *, exception_level: ExceptionLevel=ExceptionLevel.WARN, **kwargs):
self.project = project
self.location = location
self.api_endpoint = api_endpoint
self.feature_store_name = ... | Initializes an instance of `VertexAIFeatureStoreEnrichmentHandler`.
Args:
project (str): The GCP project-id for the Vertex AI Feature Store.
location (str): The region for the Vertex AI Feature Store.
api_endpoint (str): The API endpoint for the Vertex AI Feature Store.
feature_store_name (str): The name of the Vertex... | github-repos |
def __init__(self, details):
if not isinstance(details, dict):
raise ValueError('details in ' + self.__class__.__name__ + '.' + sys._getframe().f_code.co_name + ' must be a dict')
if '__name__' not in details:
raise KeyError('__name__')
if not _standardField.match(details['__name__']):
rai... | Constructor
Initialises the instance
Arguments:
details {dict} -- Details describing the type of values allowed for
the node
Raises:
KeyError
ValueError
Returns:
Tree | juraj-google-style |
def initial_value_of_masked_time_series(time_series_tensor, broadcast_mask):
num_timesteps = tf.shape(input=time_series_tensor)[-1]
unmasked_negindices = (
tf.cast(~broadcast_mask, tf.int32) *
tf.range(num_timesteps, 0, -1))
first_unmasked_indices = num_timesteps - tf.reduce_max(
input_t... | Get the first unmasked entry of each time series in the batch.
Args:
time_series_tensor: float `Tensor` of shape [..., num_timesteps].
broadcast_mask: bool `Tensor` of same shape as `time_series`. | juraj-google-style |
def put(self, data): | Write data to file sequentially.
Args:
data: (memoryview) Data to write. | github-repos |
def certificate_authority(self):
if (not self.__certificate_authority):
self.__certificate_authority = CertificateAuthority(self.__connection)
return self.__certificate_authority | Gets the Certificate Authority API client.
Returns:
CertificateAuthority: | codesearchnet |
def fromTFExample(iter, binary_features=[]):
def _get_value(k, v):
if v.int64_list.value:
result = v.int64_list.value
elif v.float_list.value:
result = v.float_list.value
elif (k in binary_features):
return bytearray(v.bytes_list.value[0])
else:
... | mapPartition function to convert an RDD of serialized tf.train.Example bytestring into an RDD of Row.
Note: TensorFlow represents both strings and binary types as tf.train.BytesList, and we need to
disambiguate these types for Spark DataFrames DTypes (StringType and BinaryType), so we require a "hint"
from the caller ... | codesearchnet |
def get_symbol_list(rank, dim=6):
indices = list(itertools.combinations_with_replacement(range(dim), r=rank))
c_vec = np.zeros(len(indices), dtype=object)
c_arr = np.zeros(([dim] * rank), dtype=object)
for (n, idx) in enumerate(indices):
c_vec[n] = sp.Symbol(('c_' + ''.join([str(i) for i in idx]... | Returns a symbolic representation of the voigt-notation
tensor that places identical symbols for entries related
by index transposition, i. e. C_1121 = C_1211 etc.
Args:
dim (int): dimension of matrix/tensor, e. g. 6 for
voigt notation and 3 for standard
rank (int): rank of tensor, e. g. 3 for third-order ECs
Returns... | codesearchnet |
def aggregate_repo(repo, args, sem, err_queue):
try:
logger.debug('%s' % repo)
dirmatch = args.dirmatch
if not match_dir(repo.cwd, dirmatch):
logger.info("Skip %s", repo.cwd)
return
if args.command == 'aggregate':
repo.aggregate()
... | Aggregate one repo according to the args.
Args:
repo (Repo): The repository to aggregate.
args (argparse.Namespace): CLI arguments. | juraj-google-style |
def intersection(L1, L2):
D = ((L1[0] * L2[1]) - (L1[1] * L2[0]))
Dx = ((L1[2] * L2[1]) - (L1[1] * L2[2]))
Dy = ((L1[0] * L2[2]) - (L1[2] * L2[0]))
if (D != 0):
x = (Dx / D)
y = (Dy / D)
return (x, y)
else:
return False | Intersects two line segments
Args:
L1 ([float, float]): x and y coordinates
L2 ([float, float]): x and y coordinates
Returns:
bool: if they intersect
(float, float): x and y of intersection, if they do | codesearchnet |
def __init__(self, filename, mode='a', encoding='utf-8'):
if 't' not in mode and encoding and py2to3.PY_3:
mode = '{0:s}t'.format(mode)
super(CompressedFileHandler, self).__init__(
filename, mode=mode, encoding=encoding, delay=True) | Initializes a compressed file logging handler.
Args:
filename (str): name of the log file.
mode (Optional[str]): file access mode.
encoding (Optional[str]): encoding of the log lines. | juraj-google-style |
def get_control_outputs(self, op):
if op.graph not in self.cache:
control_outputs = self.calc_control_outputs(op.graph)
self.cache[op.graph] = control_outputs
else:
control_outputs = self.cache[op.graph]
return control_outputs.get(op, []) | Return the control outputs for a given op.
Args:
op: The op to fetch control outputs for.
Returns:
Iterable of control output ops. | github-repos |
def create_writer_of_type(type_name):
writers = available_writers()
if (type_name not in writers.keys()):
raise UnknownWriterException(('Unknown writer: %s' % (type_name,)))
return writers[type_name]() | Create an instance of the writer with the given name.
Args:
type_name: The name of a writer.
Returns:
An instance of the writer with the given type. | codesearchnet |
def get_top_coins(tsym, limit=20):
url = build_url('volumes', tsym=tsym, limit=limit)
data = load_data(url)
return data['Data'] | Get top coins by 24 hour trading volume value in the requested currency.
Args:
tsym: TO symbol.
limit: Number of results. Default value returns top 20 coins.
Returns:
Function returns a list containing a dictionary for each result:
[{'SUPPLY': ..., 'SYMBOL': ..., 'VOLUME24HOURTO': ...},
{...},
...]
The list is orde... | juraj-google-style |
def validate(self, ticket, client_ip=None, now=None, encoding='utf-8'):
parts = self.parse(ticket)
new_ticket = self.new(*parts[1:], client_ip=client_ip, encoding=encoding)
if (new_ticket[:(self._hash.digest_size * 2)] != parts.digest):
raise TicketDigestError(ticket)
if (now is None):
n... | Validates the passed ticket, , raises a TicketError
on failure
Args:
ticket: String value (possibly generated by new function)
client_ip: Optional IPAddress of client, should be passed if the
ip address was passed on ticket creation.
now: Optional (defaults to time.time()) time to use when
validating ticket date
Retu... | codesearchnet |
def set_authentication_profile(profile=None, deploy=False):
if (not profile):
raise CommandExecutionError('Profile name option must not be none.')
ret = {}
query = {'type': 'config', 'action': 'set', 'xpath': "/config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/authentication-pr... | Set the authentication profile of the Palo Alto proxy minion. A commit will be required before this is processed.
CLI Example:
Args:
profile (str): The name of the authentication profile to set.
deploy (bool): If true then commit the full candidate configuration, if false only set pending change.
.. code-block:: ba... | codesearchnet |
def get_file(self, file_name, local_destination=None, **kwargs):
if (not local_destination):
local_destination = file_name
return SubprocessTask((self._rsync_cmd() + ['-ut', ('%s:%s' % (self.hostname, file_name)), local_destination]), **kwargs) | Get a file from a remote host with rsync.
Args:
file_name (str): The relative location of the file on the remote
host.
local_destination (str): The destination for the file on the local
host. If `None`, will be assumed to be the same as
**file_name**. Default `None`.
**kwargs: Passed to ``SubprocessTask``'s init met... | codesearchnet |
def _decode_crop_and_flip(image_buffer, num_channels):
min_object_covered = 0.1
aspect_ratio_range = [0.75, 1.33]
area_range = [0.05, 1.0]
max_attempts = 100
mlperf_log.resnet_print(key=mlperf_log.INPUT_DISTORTED_CROP_MIN_OBJ_COV, value=min_object_covered)
mlperf_log.resnet_print(key=mlperf_log.... | Crops the given image to a random part of the image, and randomly flips.
We use the fused decode_and_crop op, which performs better than the two ops
used separately in series, but note that this requires that the image be
passed in as an un-decoded string Tensor.
Args:
image_buffer: scalar string Tensor representing ... | codesearchnet |
def create_policy(self, account, client, document, name, arn=None):
if ((not arn) and (not name)):
raise ValueError('create_policy must be called with either arn or name in the argument list')
if arn:
response = client.list_policy_versions(PolicyArn=arn)
if (len(response['Versions']) >= ... | Create a new IAM policy.
If the policy already exists, a new version will be added and if needed the oldest policy version not in use
will be removed. Returns a dictionary containing the policy or version information
Args:
account (:obj:`Account`): Account to create the policy on
client (:obj:`boto3.client`): A boto3... | codesearchnet |
def model(self, inputs, mode='train'):
training = (mode == 'train')
with tf.variable_scope('conv1') as scope:
conv = tf.layers.conv2d(inputs=inputs, filters=16, kernel_size=[3, 3], padding='SAME')
bn = tf.layers.batch_normalization(inputs=conv, training=training... | Build a simple convnet (BN before ReLU).
Args:
inputs: a tensor of size [batch_size, height, width, channels]
mode: string in ['train', 'test']
Returns:
the last op containing the predictions
Note:
Best score
Step: 7015 - Epoch: 18/20 - best batch acc: 0.8984 - loss: 1.5656
Worst score
Step: 7523 - Epoch: 20/20 - bes... | juraj-google-style |
def is_initialized(self, name=None):
return gen_resource_variable_ops.var_is_initialized_op(self.handle, name) | Checks whether a resource variable has been initialized.
Outputs boolean scalar indicating whether the tensor has been initialized.
Args:
name: A name for the operation (optional).
Returns:
A `Tensor` of type `bool`. | github-repos |
def ascii2h5(dat_fname, h5_fname):
table = np.loadtxt(dat_fname, skiprows=1, dtype='f4')
filter_kwargs = dict(
chunks=True,
compression='gzip',
compression_opts=3)
idx = ~np.all(table[:,2:32] < 1.e-5, axis=1)
with h5py.File(h5_fname, 'w') as f:
d = np.arange(... | Converts from the original ASCII format of the Chen+ (2014) 3D dust map to
the HDF5 format.
Args:
dat_fname (:obj:`str`): Filename of the original ASCII .dat file.
h5_fname (:obj:`str`): Output filename to write the resulting HDF5 file to. | juraj-google-style |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.