code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def _from_tensor_shape(cls, shape: Any, num_row_partitions: int, dtype: dtypes.DType) -> 'DynamicRaggedShape.Spec':
if dtype != dtypes.int32 and dtype != dtypes.int64:
raise ValueError('dtype must be tf.int32 or tf.int64')
shape = tensor_shape.as_shape(shape)
if shape.rank is None:
row_parti... | Creates a `DynamicRaggedShape.Spec` corresponding to a `tf.TensorShape`.
It is assumed that this is a `tf.TensorShape` coming from a
`tf.TensorSpec`, not from `RaggedTensor.shape`.
In addition to the shape, we need to know the number of row partitions,
and the dtype used in the shape (tf.int32 or tf.int64).
Within t... | github-repos |
def get_cost_per_mol(self, comp):
comp = comp if isinstance(comp, Composition) else Composition(comp)
decomp = self.get_lowest_decomposition(comp)
return sum(k.energy_per_atom * v * comp.num_atoms for k, v in
decomp.items()) | Get best estimate of minimum cost/mol based on known data
Args:
comp:
Composition as a pymatgen.core.structure.Composition
Returns:
float of cost/mol | juraj-google-style |
def error(message):
fail = '\033[91m'
end = '\033[0m'
sys.exit(fail + "Error: {}".format(message) + end) | Throw an error with the given message and immediately quit.
Args:
message(str): The message to display. | juraj-google-style |
def parse_ranges(range_string):
range_string = range_string.strip()
if not range_string:
return []
if 'inf' in range_string:
range_string = re.sub('inf', repr(sys.float_info.max), range_string)
ranges = ast.literal_eval(range_string)
if isinstance(ranges, list) and (not isinstance(ra... | Parse a string representing numerical range(s).
Args:
range_string: (str) A string representing a numerical range or a list of
them. For example:
"[-1.0,1.0]", "[-inf, 0]", "[[-inf, -1.0], [1.0, inf]]"
Returns:
(list of list of float) A list of numerical ranges parsed from the input
string.
Raises:
ValueError: If th... | github-repos |
def _get_class(self):
class_parts = [self._prefix, self._known_keys[_InstrumentationKnownStatusKeys.CLASS]]
return '.'.join(filter(None, class_parts)) | Gets the class name of the test method for the instrumentation
method block.
Returns:
A string containing the class name of the instrumentation test
method's test or empty string if no name was parsed. If a prefix
was specified, then the prefix will be prepended to the class
name. | github-repos |
def abort_class(reason, extras=None):
raise signals.TestAbortClass(reason, extras) | Abort all subsequent tests within the same test class in one iteration.
If one test class is requested multiple times in a test run, this can
only abort one of the requested executions, NOT all.
Args:
reason: The reason to abort.
extras: An optional field for extra information to be included in
test result.
Raises:
... | github-repos |
def aes_decrypt(base64_encryption_key, base64_data):
data = from_base64(base64_data)
(aes_key_bytes, hmac_key_bytes) = _extract_keys(base64_encryption_key)
(data, hmac_signature) = (data[:(- HMAC_SIG_SIZE)], data[(- HMAC_SIG_SIZE):])
if (hmac.new(hmac_key_bytes, data, hashlib.sha256).digest() != hmac_si... | Verify HMAC-SHA256 signature and decrypt data with AES-CBC
Arguments:
encryption_key (str): a base64-encoded string containing an AES encryption key and HMAC
signing key as generated by generate_encryption_key()
data (str): a byte string containing the data decrypted with an HMAC signing key
appended to the end
Retur... | codesearchnet |
def human_timestamp_to_datetime(human_timestamp, to_utc=False):
settings = {}
if to_utc:
settings = {"TO_TIMEZONE": "UTC"}
return dateparser.parse(human_timestamp, settings=settings) | Converts a human-readable timestamp into a Python ``DateTime`` object
Args:
human_timestamp (str): A timestamp string
to_utc (bool): Convert the timestamp to UTC
Returns:
DateTime: The converted timestamp | juraj-google-style |
def _get_default_initializer(self, name, shape=None, dtype=dtypes.float32):
del shape
if dtype.is_floating:
initializer = init_ops.glorot_uniform_initializer()
initializing_from_value = False
elif dtype.is_integer or dtype.is_unsigned or dtype.is_bool or (dtype == dtypes.string):
ini... | Provide a default initializer and a corresponding value.
Args:
name: see get_variable.
shape: see get_variable.
dtype: see get_variable.
Returns:
initializer and initializing_from_value. See get_variable above.
Raises:
ValueError: When giving unsupported dtype. | github-repos |
def Create(conf):
global _source_implementations
if not _source_implementations:
raise RuntimeError('no source implementations exist')
source_name = conf['name']
if source_name not in list(_source_implementations.keys()):
raise RuntimeError('source not implemented: %r' % (source_name,))
... | Source creation factory method.
Args:
conf: a dictionary of configuration key/value pairs, including one
required attribute 'name'.
Returns:
A Source instance.
Raises:
RuntimeError: no sources are registered with RegisterImplementation | github-repos |
def swap_tensor_content_in_graph_function(graph_def, from_endiness, to_endiness):
if isinstance(graph_def, meta_graph_pb2.MetaGraphDef):
functions = graph_def.graph_def.library.function
elif isinstance(graph_def, graph_pb2.GraphDef):
functions = graph_def.library.function
else:
retur... | Fix endiness of tensor contents.
Args:
graph_def: Target graph_def to change endiness.
from_endiness: The original endianness format. "big" or "little"
to_endiness: The target endianness format. "big" or "little" | github-repos |
def get_help_data(filepath):
try:
with open(filepath, 'r') as file:
return _json.load(file, object_pairs_hook=OrderedDict)
except Exception as e:
logger.error("Could not load file {}".format(filepath))
logger.exception(e)
return {} | Get the json data from a help file
Args:
filepath (str): The file path for the help file
Returns:
data: The json data from a help file | juraj-google-style |
def HasTable(self, table_name):
if not self._connection:
raise IOError('Not opened.')
if not table_name:
return False
if self._table_names is None:
self._table_names = []
self._cursor.execute(self._HAS_TABLE_QUERY)
for row in self._cursor.fetchall():
if not row[... | Determines if a specific table exists.
Args:
table_name (str): name of the table.
Returns:
bool: True if the column exists.
Raises:
IOError: if the database file is not opened.
OSError: if the database file is not opened. | juraj-google-style |
def add_severity(self, name, value):
logger.debug('Adding severity {0} with value {1} to variant {2}'.format(name, value, self['variant_id']))
self['severities'].append({name: value}) | Add a severity to the variant
Args:
name (str): The name of the severity
value : The value of the severity | codesearchnet |
def checksum(self, path):
if not self.exists(path):
raise BeamIOError('Path does not exist: %s' % path)
return str(os.path.getsize(path)) | Fetch checksum metadata of a file on the
:class:`~apache_beam.io.filesystem.FileSystem`.
Args:
path: string path of a file.
Returns: string containing file size.
Raises:
``BeamIOError``: if path isn't a file or doesn't exist. | github-repos |
def hex_is_dark(hexx, percent=50):
(r, g, b) = hex_to_rgb(hexx)
luma = ((((0.2126 * r) + (0.7152 * g)) + (0.0722 * b)) / 2.55)
return (luma < percent) | Function to decide if a hex colour is dark.
Args:
hexx (str): A hexadecimal colour, starting with '#'.
Returns:
bool: The colour's brightness is less than the given percent. | codesearchnet |
def _FlushCache(cls, format_categories):
if (definitions.FORMAT_CATEGORY_ARCHIVE in format_categories):
cls._archive_remainder_list = None
cls._archive_scanner = None
cls._archive_store = None
if (definitions.FORMAT_CATEGORY_COMPRESSED_STREAM in format_categories):
cls._compresse... | Flushes the cached objects for the specified format categories.
Args:
format_categories (set[str]): format categories. | codesearchnet |
def __init__(self, default_value, initializer):
super(InitializableLookupTableBase, self).__init__(initializer.key_dtype, initializer.value_dtype)
self._default_value = ops.convert_to_tensor(default_value, dtype=self._value_dtype)
self._default_value.get_shape().merge_with(tensor_shape.TensorShape([]))
... | Construct a table object from a table reference.
If requires a table initializer object (subclass of `TableInitializerBase`).
It provides the table key and value types, as well as the op to initialize
the table. The caller is responsible to execute the initialization op.
Args:
default_value: The value to use if a key... | github-repos |
def ensure_scheme(url, default_scheme='http'):
parsed = urlsplit(url, scheme=default_scheme)
if (not parsed.netloc):
parsed = SplitResult(scheme=parsed.scheme, netloc=parsed.path, path='', query=parsed.query, fragment=parsed.fragment)
return urlunsplit(parsed) | Adds a scheme to a url if not present.
Args:
url (string): a url, assumed to start with netloc
default_scheme (string): a scheme to be added
Returns:
string: URL with a scheme | codesearchnet |
def status(self, **kwargs):
path = ('/geo_nodes/%s/status' % self.get_id())
return self.manager.gitlab.http_get(path, **kwargs) | Get the status of the geo node.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the server failed to perform the request
Returns:
dict: The status of the geo node | codesearchnet |
def NewFromContent(cls, content, urn, chunk_size=1024, token=None, private_key=None, public_key=None):
aff4.FACTORY.Delete(urn, token=token)
with data_store.DB.GetMutationPool() as pool:
with aff4.FACTORY.Create(urn, cls, mode='w', mutation_pool=pool, token=token) as fd:
for start_of_chunk i... | Alternate constructor for GRRSignedBlob.
Creates a GRRSignedBlob from a content string by chunking it and signing
each chunk.
Args:
content: The data to stored in the GRRSignedBlob.
urn: The AFF4 URN to create.
chunk_size: Data will be chunked into this size (each chunk is
individually signed.
token: The ACL Token.
... | codesearchnet |
def _find_and_replace(text, start_string, end_string, replace_fn):
ret = u""
current_pos = 0
while True:
start_pos = text.find(start_string, current_pos)
if start_pos == -1:
ret += text[current_pos:]
break
ret += text[current_pos:start_pos]
end_pos = text.find(end_string, start_pos ... | Remove everything found between instances of start_string and end_string.
Replace each such instance with replace_fn(removed_text)
e.g. _find_and_replace(u"the [[fat]] cat [[sat]]", u"[[", u"]]", lambda x: x)
= u"the fat cat sat"
Args:
text: a unicode string
start_string: a unicode string
end_string: a unicode strin... | juraj-google-style |
def run_step(self, representer):
assert representer, ("ObjectRepresenter instance required to run "
"ObjectRewriterStep.")
rewriter = ObjectRewriter(self.context.get_formatted_iterable,
representer)
super().run_step(rewriter... | Do the object in-out rewrite.
Args:
representer: A pypyr.filesystem.ObjectRepresenter instance. | juraj-google-style |
def Next(self):
stacktop = self.stack[(- 1)]
if (stacktop.index == (- 1)):
stacktop = _Frame(None, index=0)
self.stack.append(stacktop)
context_array = self.stack[(- 2)].context
if (stacktop.index == len(context_array)):
self.stack.pop()
raise StopIteration
stacktop.c... | Advance to the next item in a repeated section.
Raises:
StopIteration if there are no more elements | codesearchnet |
class _ConvBlock(tf.keras.Model):
def __init__(self, kernel_size, filters, stage, block, data_format, strides=(2, 2)):
super(_ConvBlock, self).__init__(name='')
filters1, filters2, filters3 = filters
conv_name_base = 'res' + str(stage) + block + '_branch'
bn_name_base = 'bn' + str(s... | _ConvBlock is the block that has a conv layer at shortcut.
Args:
kernel_size: the kernel size of middle conv layer at main path
filters: list of integers, the filters of 3 conv layer at main path
stage: integer, current stage label, used for generating layer names
block: 'a','b'..., current block label, used for gener... | github-repos |
def cumulative_distribution(self, X):
self.check_fit()
def func(*args):
return self.probability_density(list(args))
lower_bound = self.get_lower_bound()
ranges = [[lower_bound, val] for val in X]
return integrate.nquad(func, ranges)[0] | Computes the cumulative distribution function for the copula
Args:
X: `numpy.ndarray` or `pandas.DataFrame`
Returns:
np.array: cumulative probability | codesearchnet |
def add_activation_summary(x, types=None, name=None, collections=None):
ndim = x.get_shape().ndims
if ndim < 2:
logger.warn("Cannot summarize scalar activation {}".format(x.name))
return
if types is None:
types = ['sparsity', 'rms', 'histogram']
with cached_name_scope('activ... | Call :func:`add_tensor_summary` under a reused 'activation-summary' name scope.
This function is a no-op if not calling from main training tower.
Args:
x (tf.Tensor): the tensor to summary.
types (list[str]): summary types, defaults to ``['sparsity', 'rms', 'histogram']``.
name (str): if is None, use x.name.
collectio... | juraj-google-style |
def get_size_with_aspect_ratio(image_size: Tuple[int, int], size: int, max_size: Optional[int]=None, mod_size: int=16) -> Tuple[int, int]:
height, width = image_size
raw_size = None
if max_size is not None:
min_original_size = float(min((height, width)))
max_original_size = float(max((height... | Computes the output image size given the input image size and the desired output size with multiple of divisible_size.
Args:
image_size (`Tuple[int, int]`):
The input image size.
size (`int`):
The desired output size.
max_size (`int`, *optional*):
The maximum allowed output size.
mod_size (`int`, *optional*):
The size... | github-repos |
def install_package(self, name, index=None, force=False, update=False):
cmd = 'install'
if force:
cmd = '{0} {1}'.format(cmd, '--force-reinstall')
if update:
cmd = '{0} {1}'.format(cmd, '--update')
if index:
cmd = '{0} {1}'.format(cmd, '--index-url {0}'.format(index))
self.pi... | Install a given package.
Args:
name (str): The package name to install. This can be any valid
pip package specification.
index (str): The URL for a pypi index to use.
force (bool): For the reinstall of packages during updates.
update (bool): Update the package if it is out of date. | codesearchnet |
def resource_path(package: Union[str, types.ModuleType]) -> abstract_path.Path:
try:
path = importlib_resources.files(package)
except AttributeError:
is_adhoc = True
else:
if isinstance(path, importlib_resources._adapters.CompatibilityFiles.SpecPath):
is_adhoc = True
... | Returns read-only root directory path of the module.
Used to access module resource files.
Usage:
```python
path = epath.resource_path('tensorflow_datasets') / 'README.md'
content = path.read_text()
```
This is compatible with everything, including zipapp (`.par`).
Resource files should be in the `data=` of the `p... | github-repos |
def valid_as_v2_0(voevent):
_return_to_standard_xml(voevent)
valid_bool = voevent_v2_0_schema.validate(voevent)
_remove_root_tag_prefix(voevent)
return valid_bool | Tests if a voevent conforms to the schema.
Args:
voevent(:class:`Voevent`): Root node of a VOEvent etree.
Returns:
bool: Whether VOEvent is valid | codesearchnet |
def options(self):
response = self.repo.api.http_request('OPTIONS', self.uri)
return response.headers | Small method to return headers of an OPTIONS request to self.uri
Args:
None
Return:
(dict) response headers from OPTIONS request | juraj-google-style |
def set_default_by_alias(self, alias):
if alias not in self._aliases:
raise DataInvalidAlias('A dataset with alias {} does not exist'.format(alias))
self._default_index = self._aliases[alias] | Set the default dataset by its alias.
After changing the default dataset, all calls without explicitly specifying the
dataset by index or alias will be redirected to this dataset.
Args:
alias (str): The alias of the dataset that should be made the default.
Raises:
DataInvalidAlias: If the alias does not represent a ... | juraj-google-style |
def cast_to_type(obj, out_type):
in_type = type(obj)
if out_type is in_type:
return obj
else:
return out_type(obj) | Cast obj to out_type if it's not out_type already.
If the obj happens to be out_type already, it just returns obj as is.
Args:
obj: input object
out_type: type.
Returns:
obj cast to out_type. Usual python conversion / casting rules apply. | juraj-google-style |
def from_api_repr(cls, api_repr):
api_repr = api_repr.strip()
if not api_repr:
raise ValueError("Field path API representation cannot be empty.")
return cls(*parse_field_path(api_repr)) | Factory: create a FieldPath from the string formatted per the API.
Args:
api_repr (str): a string path, with non-identifier elements quoted
It cannot exceed 1500 characters, and cannot be empty.
Returns:
(:class:`FieldPath`) An instance parsed from ``api_repr``.
Raises:
ValueError if the parsing fails | juraj-google-style |
def init(config, workdir=None, logfile=None, loglevel=logging.INFO, **kwargs):
setup_sdk_logging(logfile, loglevel)
defaults = lago_config.get_section('init')
if workdir is None:
workdir = os.path.abspath('.lago')
defaults['workdir'] = workdir
defaults['virt_config'] = config
defau... | Initialize the Lago environment
Args:
config(str): Path to LagoInitFile
workdir(str): Path to initalize the workdir, defaults to "$PWD/.lago"
**kwargs(dict): Pass arguments to :func:`~lago.cmd.do_init`
logfile(str): A path to setup a log file.
loglevel(int): :mod:`logging` log level.
Returns:
:class:`~lago.sdk.SDK`: ... | juraj-google-style |
def read_structs(fstream):
struct = read_struct(fstream)
while (struct is not None):
(yield struct)
struct = read_struct(fstream) | Read all structs from likwid's file stream.
Args:
fstream: Likwid's output file stream.
Returns:
A generator that can be used to iterate over all structs in the
fstream. | codesearchnet |
def unsafe_peek(init):
def peek(store, container, _stack=None):
return init(*[store.peek(attr, container, _stack=_stack) for attr in container])
return peek | Deserialize all the attributes available in the container and pass them in the same order
as they come in the container.
This is a factory function; returns the actual `peek` routine.
Arguments:
init: type constructor.
Returns:
callable: deserializer (`peek` routine). | codesearchnet |
def onTagAdd(self, name, func):
if ('*' in name):
self.ontagaddglobs.add(name, func)
else:
self.ontagadds[name].append(func) | Register a callback for tag addition.
Args:
name (str): The name of the tag or tag glob.
func (function): The callback func(node, tagname, tagval). | codesearchnet |
def save_images(images, filenames, output_dir):
for i, filename in enumerate(filenames):
with tf.gfile.Open(os.path.join(output_dir, filename), 'w') as f:
img = (((images[i, :, :, :] + 1.0) * 0.5) * 255.0).astype(np.uint8)
Image.fromarray(img).save(f, format='PNG') | Saves images to the output directory.
Args:
images: array with minibatch of images
filenames: list of filenames without path
If number of file names in this list less than number of images in
the minibatch then only first len(filenames) images will be saved.
output_dir: directory where to save images | juraj-google-style |
def __init__(self, shape, dtype=dtypes.float32, name=None):
self._shape = tensor_shape.TensorShape(shape)
try:
self._shape_tuple = tuple(self.shape.as_list())
except ValueError:
self._shape_tuple = None
self._dtype = dtypes.as_dtype(dtype)
self._name = name | Creates a TensorSpec.
Args:
shape: Value convertible to `tf.TensorShape`. The shape of the tensor.
dtype: Value convertible to `tf.DType`. The type of the tensor values.
name: Optional name for the Tensor.
Raises:
TypeError: If shape is not convertible to a `tf.TensorShape`, or dtype is
not convertible to a `tf.DType... | juraj-google-style |
def get_edgestore_handle(
client: arango.client.ArangoClient,
username=None,
password=None,
edgestore_db_name: str = edgestore_db_name,
edgestore_edges_name: str = edgestore_edges_name,
edgestore_nodes_name: str = edgestore_nodes_name,
edgestore_pipeline_name: str = edgestore_pipeline_name,
... | Get Edgestore arangodb database handle
Args:
client (arango.client.ArangoClient): Description
username (None, optional): Description
password (None, optional): Description
edgestore_db_name (str, optional): Description
edgestore_edges_name (str, optional): Description
edgestore_nodes_name (str, optional): Description
... | juraj-google-style |
def _check_response(response, expected):
response_code = response.status_code
if expected == response_code:
return
if response_code < 400:
raise ex.UnexpectedResponseCodeException(response.text)
elif response_code == 401:
raise ex.Unauthori... | Checks if the expected response code matches the actual response code.
If they're not equal, raises the appropriate exception
Args:
response: (int) Actual status code
expected: (int) Expected status code | juraj-google-style |
def store_container(self, container):
with self._store_lock:
self.store.setdefault(container.CONTAINER_TYPE, []).append(container) | Thread-safe method to store data in the state's store.
Args:
container (containers.interface.AttributeContainer): The data to store. | codesearchnet |
def rtt_get_num_up_buffers(self):
cmd = enums.JLinkRTTCommand.GETNUMBUF
dir = ctypes.c_int(enums.JLinkRTTDirection.UP)
return self.rtt_control(cmd, dir) | After starting RTT, get the current number of up buffers.
Args:
self (JLink): the ``JLink`` instance
Returns:
The number of configured up buffers on the target.
Raises:
JLinkRTTException if the underlying JLINK_RTTERMINAL_Control call fails. | juraj-google-style |
def get_text(revision, strip=True):
start_pos = revision.find('<text')
assert (start_pos != (- 1))
end_tag_pos = revision.find('>', start_pos)
assert (end_tag_pos != (- 1))
end_tag_pos += len('>')
end_pos = revision.find('</text>')
if (end_pos == (- 1)):
ret = ''
else:
re... | Extract the text from a revision.
Args:
revision: a string
strip: a boolean
Returns:
a string | codesearchnet |
def identity(x, name=None):
return array_ops.identity(x, name=name) | Returns a tensor with the same content as the input tensor.
Args:
x: The input tensor.
name: String, name for the variable to create.
Returns:
A tensor of the same shape, type and content. | github-repos |
def list_dir(root, prefix=False):
root = os.path.expanduser(root)
directories = list(
filter(
lambda p: os.path.isdir(os.path.join(root, p)),
os.listdir(root)
)
)
if prefix is True:
directories = [os.path.join(root, d) for d in directories]
retu... | List all directories at a given root
Args:
root (str): Path to directory whose folders need to be listed
prefix (bool, optional): If true, prepends the path to each result, otherwise
only returns the name of the directories found | juraj-google-style |
def memory_write(self, addr, data, zone=None, nbits=None):
buf_size = len(data)
buf = None
access = 0
if (nbits is None):
packed_data = map((lambda d: reversed(binpacker.pack(d))), data)
packed_data = list(itertools.chain(*packed_data))
buf_size = len(packed_data)
buf = (... | Writes memory to a target system or specific memory zone.
The optional ``zone`` specifies a memory zone to access to write to,
e.g. ``IDATA``, ``DDATA``, or ``CODE``.
The given number of bits, if provided, must be either ``8``, ``16``, or
``32``.
Args:
self (JLink): the ``JLink`` instance
addr (int): start address t... | codesearchnet |
def from_index_amount(cls, idx, amount):
if (np.array(idx).ndim == 0):
v = np.zeros(6)
v[idx] = amount
return cls.from_voigt(v)
elif (np.array(idx).ndim == 1):
v = np.zeros((3, 3))
for i in itertools.permutations(idx):
v[i] = amount
return cls(v)
e... | Like Deformation.from_index_amount, except generates
a strain from the zero 3x3 tensor or voigt vector with
the amount specified in the index location. Ensures
symmetric strain.
Args:
idx (tuple or integer): index to be perturbed, can be voigt or
full-tensor notation
amount (float): amount to perturb selected index | codesearchnet |
def noise_new(
dim: int,
h: float = NOISE_DEFAULT_HURST,
l: float = NOISE_DEFAULT_LACUNARITY,
random: Optional[tcod.random.Random] = None,
) -> tcod.noise.Noise:
return tcod.noise.Noise(dim, hurst=h, lacunarity=l, seed=random) | Return a new Noise instance.
Args:
dim (int): Number of dimensions. From 1 to 4.
h (float): The hurst exponent. Should be in the 0.0-1.0 range.
l (float): The noise lacunarity.
random (Optional[Random]): A Random instance, or None.
Returns:
Noise: The new Noise instance. | juraj-google-style |
def plot_cv(self, tmin, tmax, ntemp, ylim=None, **kwargs):
temperatures = np.linspace(tmin, tmax, ntemp)
if self.structure:
ylabel = '$C_v$ (J/K/mol)'
else:
ylabel = '$C_v$ (J/K/mol-c)'
fig = self._plot_thermo(self.dos.cv, temperatures, ylabel=ylabel, ylim=ylim, **kwargs)
return fig | Plots the constant volume specific heat C_v in a temperature range.
Args:
tmin: minimum temperature
tmax: maximum temperature
ntemp: number of steps
ylim: tuple specifying the y-axis limits.
kwargs: kwargs passed to the matplotlib function 'plot'.
Returns:
matplotlib figure | codesearchnet |
def _FormatServiceText(self, service):
string_segments = [service.name, '\tImage Path = {0:s}'.format(service.image_path), '\tService Type = {0:s}'.format(service.HumanReadableType()), '\tStart Type = {0:s}'.format(service.HumanReadableStartType()), '\tService Dll = {0:s}'.format(service.service_dll), '\tO... | Produces a human readable multi-line string representing the service.
Args:
service (WindowsService): service to format.
Returns:
str: human readable representation of a Windows Service. | codesearchnet |
def json_to_pybel(data, infer_bonds=False):
obmol = ob.OBMol()
obmol.BeginModify()
for atom in data['atoms']:
obatom = obmol.NewAtom()
obatom.SetAtomicNum(table.GetAtomicNum(str(atom['element'])))
obatom.SetVector(*atom['location'])
if ('label' in atom):
pd = ob.O... | Converts python data structure to pybel.Molecule.
This will infer bond data if not specified.
Args:
data: The loaded json data of a molecule, as a Python object
infer_bonds (Optional): If no bonds specified in input, infer them
Returns:
An instance of `pybel.Molecule` | codesearchnet |
async def start(self, name='websocket_client'):
self._con = (await websockets.connect(self.url))
self._connection_task = self._loop.add_task(self._manage_connection(), name=name) | Connect to the websocket server.
This method will spawn a background task in the designated event loop
that will run until stop() is called. You can control the name of the
background task for debugging purposes using the name parameter. The
name is not used in anyway except for debug logging statements.
Args:
name... | codesearchnet |
def add_time_dimension(padded_inputs, seq_lens):
padded_batch_size = tf.shape(padded_inputs)[0]
max_seq_len = padded_batch_size
new_batch_size = padded_batch_size
new_shape = ([new_batch_size, max_seq_len] +
padded_inputs.get_shape().as_list()[1:])
retur... | Adds a time dimension to padded inputs.
Arguments:
padded_inputs (Tensor): a padded batch of sequences. That is,
for seq_lens=[1, 2, 2], then inputs=[A, *, B, B, C, C], where
A, B, C are sequence elements and * denotes padding.
seq_lens (Tensor): the sequence lengths within the input batch,
suitable for passing to tf.... | juraj-google-style |
def insert_query_m(data, table, conn, columns=None, db_type='mysql'):
if len(data) > 10000:
_chunk_query(data, 10000, columns, conn, table, db_type)
else:
if db_type == 'sqlite':
type_sign = '?'
else:
type_sign = '%s'
type_... | Insert python list of tuples into SQL table
Args:
data (list): List of tuples
table (str): Name of database table
conn (connection object): database connection object
columns (str): String of column names to use if not assigned then all columns are presumed to be used [Optional]
db_type (str): If "sqlite" or "mysql" | juraj-google-style |
def get_additional_charge_by_identifier(self, recurring_billing_id):
fmt = 'recurringBillItems/{}'.format(recurring_billing_id)
return self.client._get((self.url + fmt), headers=self.get_headers()) | Query extra charge information of an invoice from its identifier.
Args:
recurring_billing_id: Identifier of the additional charge.
Returns: | codesearchnet |
def plot_bloch_multivector(rho, title='', figsize=None):
if not HAS_MATPLOTLIB:
raise ImportError('Must have Matplotlib installed.')
rho = _validate_input_state(rho)
num = int(np.log2(len(rho)))
width, height = plt.figaspect(1/num)
fig = plt.figure(figsize=(width, height))
for i in ... | Plot the Bloch sphere.
Plot a sphere, axes, the Bloch vector, and its projections onto each axis.
Args:
rho (ndarray): Numpy array for state vector or density matrix.
title (str): a string that represents the plot title
figsize (tuple): Has no effect, here for compatibility only.
Returns:
Figure: A matplotlib figure... | juraj-google-style |
def __init__(self, class_number, train_examples, test_examples, **kwargs):
super(EMNISTConfig, self).__init__(**kwargs)
self.class_number = class_number
self.train_examples = train_examples
self.test_examples = test_examples | BuilderConfig for EMNIST class number.
Args:
class_number: There are six different splits provided in this dataset. And
have different class numbers.
train_examples: number of train examples
test_examples: number of test examples
**kwargs: keyword arguments forwarded to super. | juraj-google-style |
def normalize(self, image: np.ndarray, data_format: Optional[Union[str, ChannelDimension]]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None) -> np.ndarray:
image = rescale(image=image, scale=1 / 127.5, data_format=data_format, input_data_format=input_data_format)
image = image - 1
return... | Normalizes an images' pixel values to between [-1, 1].
Args:
image (`np.ndarray`):
Image to normalize.
data_format (`str` or `ChannelDimension`, *optional*):
The channel dimension format of the image. If not provided, it will be the same as the input image.
input_data_format (`ChannelDimension` or `str`, *optional*):
... | github-repos |
def GetHelp(self, prefix='', include_special_flags=True):
helplist = []
flags_by_module = self.FlagsByModuleDict()
if flags_by_module:
modules = sorted(flags_by_module)
main_module = sys.argv[0]
if (main_module in modules):
modules.remove(main_module)
modules ... | Generates a help string for all known flags.
Args:
prefix: str, per-line output prefix.
include_special_flags: bool, whether to include description of
_SPECIAL_FLAGS, i.e. --flagfile and --undefok.
Returns:
str, formatted help message. | codesearchnet |
def download_software_file(filename=None, synch=False):
if not filename:
raise CommandExecutionError("Filename option must not be none.")
if not isinstance(synch, bool):
raise CommandExecutionError("Synch option must be boolean..")
if synch is True:
query = {'type': 'op',
... | Download software packages by filename.
Args:
filename(str): The filename of the PANOS file to download.
synch (bool): If true then the file will synch to the peer unit.
CLI Example:
.. code-block:: bash
salt '*' panos.download_software_file PanOS_5000-8.0.0
salt '*' panos.download_software_file PanOS_5000-8.0.0 T... | juraj-google-style |
def from_dict(cls, config_dict, **kwargs):
config = cls(**config_dict)
to_remove = []
for key, value in kwargs.items():
if hasattr(config, key):
setattr(config, key, value)
to_remove.append(key)
for key in to_remove:
kwargs.pop(key, None)
return config | Constructs a BaseWatermarkingConfig instance from a dictionary of parameters.
Args:
config_dict (Dict[str, Any]): Dictionary containing configuration parameters.
**kwargs: Additional keyword arguments to override dictionary values.
Returns:
BaseWatermarkingConfig: Instance of BaseWatermarkingConfig constructed from t... | github-repos |
def determine_opening_indent(indent_texts):
num_lines = len(indent_texts)
if num_lines < 1:
return 0
assert num_lines >= 1
first_line_indent = indent_texts[0][0]
if num_lines == 1:
return first_line_indent
assert num_lines >= 2
second_line_indent = indent_texts[1]... | Determine the opening indent level for a docstring.
The opening indent level is the indent level is the first non-zero indent
level of a non-empty line in the docstring.
Args:
indent_texts: The lines of the docstring as an iterable over 2-tuples
each containing an integer indent level as the first element and
the tex... | juraj-google-style |
def get_nearest_site(self, coords, site, r=None):
index = self.index(site)
if r is None:
r = np.linalg.norm(np.sum(self.lattice.matrix, axis=0))
ns = self.get_sites_in_sphere(coords, r, include_index=True)
ns = [n for n in ns if n[2] == index]
... | Given coords and a site, find closet site to coords.
Args:
coords (3x1 array): cartesian coords of center of sphere
site: site to find closest to coords
r: radius of sphere. Defaults to diagonal of unit cell
Returns:
Closest site and distance. | juraj-google-style |
def draw(vertexes, edges):
Xs = []
Ys = []
sug = _build_sugiyama_layout(vertexes, edges)
for vertex in sug.g.sV:
Xs.append((vertex.view.xy[0] - (vertex.view.w / 2.0)))
Xs.append((vertex.view.xy[0] + (vertex.view.w / 2.0)))
Ys.append(vertex.view.xy[1])
Ys.append((vertex.vi... | Build a DAG and draw it in ASCII.
Args:
vertexes (list): list of graph vertexes.
edges (list): list of graph edges. | codesearchnet |
def adaptive_gaussian_prior_builder(getter, name, *args, **kwargs):
kwargs['shape'] = ()
loc_var = getter((name + '_prior_loc'), *args, **kwargs)
kwargs['initializer'] = scale_variable_initializer(0.01)
scale_var = getter((name + '_prior_scale'), *args, **kwargs)
prior = tfp.distributions.Normal(loc... | A pre-canned builder for adaptive scalar gaussian prior distributions.
Given a true `getter` function and arguments forwarded from `tf.get_variable`,
return a distribution object for a scalar-valued adaptive gaussian prior
which will be broadcast over a variable of the requisite shape. This prior's
parameters (e.g `lo... | codesearchnet |
def merge_bindings(program: cfg.Program, node: cfg.CFGNode, bindings: Sequence[cfg.Binding]) -> cfg.Variable:
v = program.NewVariable()
for b in bindings:
v.PasteBinding(b, node)
return v | Create a combined Variable for a list of bindings.
Args:
program: A cfg.Program instance.
node: The current CFG node.
bindings: A list of cfg.Bindings.
Returns:
A cfg.Variable. | github-repos |
def _ParseIndex(self, preread, precompile):
self.index = texttable.TextTable()
self.index.CsvToTable(self._index_handle)
if preread:
for row in self.index:
for col in row.header:
row[col] = preread(col, row[col])
self.compiled = ... | Reads index file and stores entries in TextTable.
For optimisation reasons, a second table is created with compiled entries.
Args:
preread: func, Pre-processing, applied to each field as it is read.
precompile: func, Pre-compilation, applied to each field before compiling.
Raises:
IndexTableError: If the column headers... | juraj-google-style |
def create_test_method(pipeline_spec_file: str, custom_preprocessors: List[Callable[..., Union[Dict, List]]]):
@mock.patch('apache_beam.Pipeline', TestPipeline)
def test_yaml_example(self):
with open(pipeline_spec_file, encoding='utf-8') as f:
lines = f.readlines()
expected_key = '
... | Generates a test method for a given YAML pipeline specification file.
This function reads the YAML file, extracts the expected output (if present),
and creates a test function that uses `TestPipeline` to run the pipeline
defined in the YAML file. It also applies any custom preprocessors registered
for this test.
Args... | github-repos |
def get_likelihood(self, uni_matrix):
if (self.parents is None):
left_u = uni_matrix[(:, self.L)]
right_u = uni_matrix[(:, self.R)]
else:
left_ing = list((self.D - self.parents[0].D))[0]
right_ing = list((self.D - self.parents[1].D))[0]
left_u = uni_matrix[(self.L, left_i... | Compute likelihood given a U matrix.
Args:
uni_matrix(numpy.array): Matrix to compute the likelihood.
Return:
tuple(np.ndarray, np.ndarray, np.array): likelihood and conditional values. | codesearchnet |
def ec2_pipeline_setup(generated=None, project='', settings=None, env='', pipeline_type='', region='', region_subnets=None):
data = copy.deepcopy(settings)
user_data = generate_encoded_user_data(env=env, region=region, generated=generated, group_name=project, pipeline_type=pipeline_type)
instance_security_g... | Handles ec2 pipeline data setup
Args:
generated (gogoutils.Generator): Generated naming formats.
project (str): Group name of application
settings (dict): Environment settings from configurations.
env (str): Deploy environment name, e.g. dev, stage, prod.
pipeline_type (str): Type of Foremast Pipeline to configure.
re... | codesearchnet |
def get(self, block_id):
pool = current_app.config['bigchain_pool']
with pool() as bigchain:
block = bigchain.get_block(block_id=block_id)
if not block:
return make_error(404)
return block | API endpoint to get details about a block.
Args:
block_id (str): the id of the block.
Return:
A JSON string containing the data about the block. | juraj-google-style |
def delete(self, url, params=None, **kwargs):
return self.call_api(
"DELETE",
url,
params=params,
**kwargs
) | Call the API with a DELETE request.
Args:
url (str): Resource location relative to the base URL.
params (dict or None): Query-string parameters.
Returns:
ResultParser or ErrorParser. | juraj-google-style |
def submit_evaluation(self, variant_obj, user_obj, institute_obj, case_obj, link, criteria):
variant_specific = variant_obj['_id']
variant_id = variant_obj['variant_id']
user_id = user_obj['_id']
user_name = user_obj.get('name', user_obj['_id'])
institute_id = institute_obj['_id']
case_id = case... | Submit an evaluation to the database
Get all the relevant information, build a evaluation_obj
Args:
variant_obj(dict)
user_obj(dict)
institute_obj(dict)
case_obj(dict)
link(str): variant url
criteria(list(dict)):
[
{
'term': str,
'comment': str,
'links': list(str)
},
.
.
] | codesearchnet |
def match_from_mro(self, left, other_type, allow_compat_builtins=True):
for base in left.mro:
if isinstance(base, abstract.ParameterizedClass):
base_cls = base.base_cls
else:
base_cls = base
if isinstance(base_cls, abstract.Class):
if self._match_base_clas... | Checks a type's MRO for a match for a formal type.
Args:
left: The type.
other_type: The formal type.
allow_compat_builtins: Whether to allow compatible builtins to match -
e.g., int against float.
Returns:
The match, if any, None otherwise. | github-repos |
def get_result(self, timeout=None) -> Optional[GenerationOutput]:
if self._generation_thread is None and self.output_queue.empty():
return None
try:
result = self.output_queue.get(block=True, timeout=timeout)
logger.debug(f'Retrieved result for request {result.request_id}')
retur... | Retrieve one result from the output queue.
Args:
timeout: Maximum time to wait for a result
Returns:
Optional[Dict]: The result data or None if timeout | github-repos |
def configure_tests(tests, test_run_id):
print('UPDATE CONFIG')
os.makedirs(HARNESS_DIRECTORY, exist_ok=True)
for filename, script in tests:
script_fields = json_get_fields(script)
script_name = filename.split('.')[0]
harness_fields = {}
harness_path = HARNESS_DIRECTORY + scr... | Initialize the starthinker_assets/tests.json variable harness.
Read all existing tests from tests/*.json and create a harness file in
starthinker_assets/tests/*.json so developer can configure tests.
Args:
test: List of (filename, json) pairs containing all the tests.
Returns:
None | github-repos |
def __init__(
self,
base_url,
username=None,
api_key=None,
status_endpoint=None,
timeout=60
):
self.base_url = base_url
self.username = username
self.api_key = api_key
self.status_endpoint = urljoin(self... | Initialise client.
Args:
base_url (str): The base URL to the service being used.
username (str): The username to authenticate with.
api_key (str): The API key to authenticate with.
timeout (int): Maximum time before timing out. | juraj-google-style |
def _add_session_callback(self, callback_obj, callback, one_shot, originator):
if one_shot:
@wraps(callback)
def remove_then_invoke(*args, **kwargs):
if (callback_obj in self._session_callbacks):
self._remove_session_callback(callback_obj, originator)
return ... | Internal implementation for adding session callbacks.
Args:
callback_obj (SessionCallback) :
A session callback object that wraps a callable and is
passed to ``trigger_on_change``.
callback (callable) :
A callable to execute when session events happen.
one_shot (bool) :
Whether the callback should immediately auto-r... | codesearchnet |
def forward(self, hidden_states):
hidden_states = self.wi(hidden_states)
hidden_states = self.act(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.wo(hidden_states)
return hidden_states | Args:
hidden_states (`torch.Tensor`) :
[num_groups, tokens_per_group, hidden_dim] inputs to send to experts.
Returns:
torch.Tensor[num_groups, tokens_per_group, hidden_dim] | github-repos |
def _oai_to_xml(marc_oai):
record = MARCXMLRecord(marc_oai)
record.oai_marc = False
return record.to_XML() | Convert OAI to MARC XML.
Args:
marc_oai (str): String with either OAI or MARC XML.
Returns:
str: String with MARC XML. | juraj-google-style |
def sg_producer_func(func):
@wraps(func)
def wrapper(**kwargs):
'Manages arguments of `tf.sg_opt`.\n\n Args:\n **kwargs:\n source: A source queue list to enqueue\n dtypes: Input data types of each tensor\n out_dtypes: Output data types of each tensor ( I... | r"""Decorates a function `func` as sg_producer_func.
Args:
func: A function to decorate. | codesearchnet |
def __init__(self, excluded_sites=None, **kwargs):
super().__init__(**kwargs)
self.excluded_site = excluded_sites
if excluded_sites is None:
self.excluded_site = [] | Constructor.
Args:
excluded_sites(list): sites to forget about when reloading the
jobs. The primary use case was to exclude unreachable sites and
allow the program to go on. | juraj-google-style |
def read_as_base64(fn):
with open(fn) as unpacked_file:
with tempfile.TemporaryFile() as b64_file:
base64.encode(unpacked_file, b64_file)
b64_file.flush()
b64_file.seek(0)
return b64_file.read() | Convert given `fn` to base64 and return it. This method does the process
in not-so-much memory consuming way.
Args:
fn (str): Path to the file which should be converted.
Returns:
str: File encoded as base64. | juraj-google-style |
def parse_pv(header):
order_fit = parse_order_fit(header)
def parse_with_base(i):
key_base = "PV%d_" % i
pvi_x = [header[key_base + "0"]]
def parse_range(lower, upper):
for j in range(lower, upper + 1):
pvi_x.append(header[key_base + str(j)])
... | Parses the PV array from an astropy FITS header.
Args:
header: astropy.io.fits.header.Header
The header containing the PV values.
Returns:
cd: 2d array (list(list(float))
[[PV1_0, PV1_1, ... PV1_N], [PV2_0, PV2_1, ... PV2_N]]
Note that N depends on the order of the fit. For example, an
order 3 fit goes up to PV?_10. | juraj-google-style |
def strip_prefix_from_items(prefix, items):
items_no_prefix = []
for item in items:
if item.startswith(prefix):
items_no_prefix.append(item[len(prefix):])
else:
items_no_prefix.append(item)
return items_no_prefix | Strips out the prefix from each of the items if it is present.
Args:
prefix: the string for that you wish to strip from the beginning of each
of the items.
items: a list of strings that may or may not contain the prefix you want
to strip out.
Returns:
items_no_prefix: a copy of the list of items (same order) without ... | juraj-google-style |
def get_niggli_reduced_lattice(self, tol: float = 1e-5) -> "Lattice":
matrix = self.lll_matrix
a = matrix[0]
b = matrix[1]
c = matrix[2]
e = tol * self.volume ** (1 / 3)
G = [
[dot(a, a), dot(a, b), dot(a, c)],
[dot(a, b... | Get the Niggli reduced lattice using the numerically stable algo
proposed by R. W. Grosse-Kunstleve, N. K. Sauter, & P. D. Adams,
Acta Crystallographica Section A Foundations of Crystallography, 2003,
60(1), 1-6. doi:10.1107/S010876730302186X
Args:
tol (float): The numerical tolerance. The default of 1e-5 should
resul... | juraj-google-style |
def GetMountPoint(self, path=None):
path = os.path.abspath(client_utils.CanonicalPathToLocalPath((path or self.path)))
while (not os.path.ismount(path)):
path = os.path.dirname(path)
return path | Walk back from the path to find the mount point.
Args:
path: a Unicode string containing the path or None. If path is None the
value in self.path is used.
Returns:
path string of the mount point | codesearchnet |
def _args_to_val(func, args):
from .google_imports import gql
vals = []
for arg in args:
if isinstance(arg, (int, long, basestring)):
val = Parameter(arg)
elif isinstance(arg, gql.Literal):
val = arg.Get()
else:
raise TypeError(('Unexpected arg (%r... | Helper for GQL parsing to extract values from GQL expressions.
This can extract the value from a GQL literal, return a Parameter
for a GQL bound parameter (:1 or :foo), and interprets casts like
KEY(...) and plain lists of values like (1, 2, 3).
Args:
func: A string indicating what kind of thing this is.
args: One or... | codesearchnet |
def _minigui_report_search_status(self, leaves):
root = self._player.get_root()
msg = {'id': hex(id(root)), 'n': int(root.N), 'q': float(root.Q)}
msg['childQ'] = [int(round((q * 1000))) for q in root.child_Q]
msg['childN'] = [int(n) for n in root.child_N]
ranked_children = root.rank_children()
v... | Prints the current MCTS search status to stderr.
Reports the current search path, root node's child_Q, root node's
child_N, the most visited path in a format that can be parsed by
one of the STDERR_HANDLERS in minigui.ts.
Args:
leaves: list of leaf MCTSNodes returned by tree_search(). | codesearchnet |
def _remove_double_brackets(text):
def replacement_fn(s):
if ":" in s:
return ""
bar_pos = s.find("|")
if bar_pos == -1:
return s
return s[bar_pos + 1:]
return _find_and_replace(text, "[[", "]]", replacement_fn) | Remove double brackets, but leave the viewable text.
Args:
text: a string
Returns:
a string | juraj-google-style |
def checksum(self, path):
raise NotImplementedError | Fetch checksum metadata of a file on the
:class:`~apache_beam.io.filesystem.FileSystem`.
This operation returns checksum metadata as stored in the underlying
FileSystem. It should not need to read file data to obtain this value.
Checksum type and format are FileSystem dependent and are not compatible
between FileSyste... | github-repos |
def short_repr(obj, max_len=40):
obj_repr = repr(obj)
if (len(obj_repr) <= max_len):
return obj_repr
return '<{} of length {}>'.format(type(obj).__name__, len(obj_repr)) | Returns a short, term-friendly string representation of the object.
Args:
obj: An object for which to return a string representation.
max_len: Maximum length of the returned string. Longer reprs will be turned
into a brief descriptive string giving the type and length of obj. | codesearchnet |
def _validate_cidr(self, rule):
try:
network = ipaddress.IPv4Network(rule['app'])
except (ipaddress.NetmaskValueError, ValueError) as error:
raise SpinnakerSecurityGroupCreationFailed(error)
self.log.debug('Validating CIDR: %s', network.exploded)
return True | Validate the cidr block in a rule.
Returns:
True: Upon successful completion.
Raises:
SpinnakerSecurityGroupCreationFailed: CIDR definition is invalid or
the network range is too wide. | codesearchnet |
def build_shuffle_all_reduce(input_tensors, gather_devices, red_op, un_op=None):
input_tensors, shape = _flatten_tensors(input_tensors)
dst_devices = [t.device for t in input_tensors]
reduced_shards = _build_shuffle_gather(input_tensors, gather_devices, red_op, un_op)
output_tensors = _build_shuffle_sca... | Construct a subgraph for shuffle all-reduce.
Shuffle reduce is essentially the algorithm implemented when using
parameter servers. Suppose tensor length is n, there are d devices
and g gather shards. Each device sends a n/g length sub-tensor to
each gather shard. The gather shards perform a reduction across d
fragm... | github-repos |
def redraw(self, reset_camera=False):
self.ren.RemoveAllViewProps()
self.picker = None
self.add_picker_fixed()
self.helptxt_mapper = vtk.vtkTextMapper()
tprops = self.helptxt_mapper.GetTextProperty()
tprops.SetFontSize(14)
tprops.SetFontFamilyToTimes()
... | Redraw the render window.
Args:
reset_camera: Set to True to reset the camera to a
pre-determined default for each structure. Defaults to False. | juraj-google-style |
def from_pb(cls, policy_pb):
policy = cls(policy_pb.etag, policy_pb.version)
for binding in policy_pb.bindings:
policy[binding.role] = sorted(binding.members)
return policy | Factory: create a policy from a protobuf message.
Args:
policy_pb (google.iam.policy_pb2.Policy): message returned by
``get_iam_policy`` gRPC API.
Returns:
:class:`Policy`: the parsed policy | juraj-google-style |
def per_device_batch_size(batch_size, num_gpus):
if (num_gpus <= 1):
return batch_size
remainder = (batch_size % num_gpus)
if remainder:
err = 'When running with multiple GPUs, batch size must be a multiple of the number of available GPUs. Found {} GPUs with a batch size of {}; try --batch_s... | For multi-gpu, batch-size must be a multiple of the number of GPUs.
Note that this should eventually be handled by DistributionStrategies
directly. Multi-GPU support is currently experimental, however,
so doing the work here until that feature is in place.
Args:
batch_size: Global batch size to be divided among devic... | codesearchnet |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.