code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def take_profit(self, accountID, **kwargs):
return self.create(
accountID,
order=TakeProfitOrderRequest(**kwargs)
) | Shortcut to create a Take Profit Order in an Account
Args:
accountID : The ID of the Account
kwargs : The arguments to create a TakeProfitOrderRequest
Returns:
v20.response.Response containing the results from submitting
the request | juraj-google-style |
def run(self, shell=False, ignore_errors=False, stdin=False, check_output=False):
previous_directory = os.getcwd()
os.chdir(self.directory)
try:
kwargs = {'stderr': sys.stderr, 'stdin': (sys.stdin if stdin else None), 'env': self.env_vars, 'shell': shell}
if check_output:
return ... | Run subcommand.
Args:
shell (Optional[bool]): Run command using shell (default False)
ignore_errors (Optional[bool]): If the command has a non-zero return code, don't raise an exception (default False)
stdin (Optional[bool]): Plug input from stdin when running command (default False)
check_output (Optional[bool]): Ret... | codesearchnet |
def sg_input(shape=None, dtype=sg_floatx, name=None):
r
if shape is None:
return tf.placeholder(dtype, shape=None, name=name)
else:
if not isinstance(shape, (list, tuple)):
shape = [shape]
return tf.placeholder(dtype, shape=[None] + list(shape), name=name) | r"""Creates a placeholder.
Args:
shape: A tuple/list of integers. If an integers is given, it will turn to a list.
dtype: A data type. Default is float32.
name: A name for the placeholder.
Returns:
A wrapped placeholder `Tensor`. | juraj-google-style |
def sample(self, n):
total = bq.Query(('select count(*) from %s' % self._get_source())).execute().result()[0].values()[0]
if (n > total):
raise ValueError('sample larger than population')
sampling = bq.Sampling.random(percent=((n * 100.0) / float(total)))
if (self._query is not None):
so... | Samples data into a Pandas DataFrame. Note that it calls BigQuery so it will
incur cost.
Args:
n: number of sampled counts. Note that the number of counts returned is approximated.
Returns:
A dataframe containing sampled data.
Raises:
Exception if n is larger than number of rows. | codesearchnet |
def save_attributes_to_hdf5_group(group, name, data):
HDF5_OBJECT_HEADER_LIMIT = 64512
bad_attributes = [x for x in data if len(x) > HDF5_OBJECT_HEADER_LIMIT]
if bad_attributes:
raise RuntimeError(f'The following attributes cannot be saved to HDF5 file because they are larger than {HDF5_OBJECT_HEADE... | Saves attributes (data) of the specified name into the HDF5 group.
This method deals with an inherent problem of HDF5 file which is not able to store data larger than
HDF5_OBJECT_HEADER_LIMIT bytes.
Args:
group: A pointer to a HDF5 group.
name: A name of the attributes to save.
data: Attributes data to store.
Raises... | github-repos |
def _check_dims_and_partition_or_replicate_on_host(self, tensor, dims):
self._check_input_partition_dims(tensor, dims)
return partition_or_replicate_on_host(tensor, dims) | Checks dims and partitions or replicates the input tensor.
The ops inside this function are placed on the host side.
Args:
tensor: The input tensor which will be partitioned or replicated.
dims: A list of integer describes how to partition the input tensor.
Returns:
An iterator of `Tensor`s or a list of partitioned ... | github-repos |
def ask_when_work_is_populated(self, work):
work.read_all_from_datastore()
if work.work:
print('Work is already written to datastore.\n'
'If you continue these data will be overwritten and '
'possible corrupted.')
inp = input_str('Do you want to continue? '
... | When work is already populated asks whether we should continue.
This method prints warning message that work is populated and asks
whether user wants to continue or not.
Args:
work: instance of WorkPiecesBase
Returns:
True if we should continue and populate datastore, False if we should stop | juraj-google-style |
def summary(self, stdout=True, plot=False):
if stdout:
print('Collinearity summary:')
print(pd.concat([self.results['Eigenvalues'], self.results['ConditionIndices'], self.results['VIFs'], self.results['CorrelationMatrix']], axis=1))
print('Outlier summary:')
print(self.results['RowMa... | Displays diagnostics to the user
Args:
stdout (bool): print results to the console
plot (bool): use Seaborn to plot results | codesearchnet |
def _check_audience(payload_dict, audience):
if (audience is None):
return
audience_in_payload = payload_dict.get('aud')
if (audience_in_payload is None):
raise AppIdentityError('No aud field in token: {0}'.format(payload_dict))
if (audience_in_payload != audience):
raise AppIden... | Checks audience field from a JWT payload.
Does nothing if the passed in ``audience`` is null.
Args:
payload_dict: dict, A dictionary containing a JWT payload.
audience: string or NoneType, an audience to check for in
the JWT payload.
Raises:
AppIdentityError: If there is no ``'aud'`` field in the payload
dictionary ... | codesearchnet |
def resolve(phrases: typing.List[str], html: str, separator: str='\u200b') -> str:
resolver = HTMLChunkResolver(phrases, separator)
resolver.feed(html)
result = '<span style="%s">%s</span>' % (PARENT_CSS_STYLE, resolver.output)
return result | Wraps phrases in the HTML string with non-breaking markup.
Args:
phrases (List[str]): The phrases included in the HTML string.
html (str): The HTML string to resolve.
separator (str, optional): The separator string.
Returns:
The HTML string with phrases wrapped in non-breaking markup. | github-repos |
def save_weights_to_hdf5_group(f, model):
from keras.src import __version__ as keras_version
save_attributes_to_hdf5_group(f, 'layer_names', [layer.name.encode('utf8') for layer in model.layers])
f.attrs['backend'] = backend.backend().encode('utf8')
f.attrs['keras_version'] = str(keras_version).encode('... | Saves the weights of a list of layers to a HDF5 group.
Args:
f: HDF5 group.
model: Model instance. | github-repos |
def format_auth_params(params):
parts = []
for (key, value) in params.items():
if value:
parts.append('{}="{}"'.format(key, value))
return ", ".join(parts) | Generate the format expected by HTTP Headers from parameters.
Args:
params (dict): {key: value} to convert to key=value
Returns:
A formatted header string. | juraj-google-style |
def imshow(img, win_name='', wait_time=0):
cv2.imshow(win_name, imread(img))
cv2.waitKey(wait_time) | Show an image.
Args:
img (str or ndarray): The image to be displayed.
win_name (str): The window name.
wait_time (int): Value of waitKey param. | juraj-google-style |
def unpack(self, buff, offset=0):
super().unpack(buff, offset)
if not self.is_valid():
raise UnpackException("Unsupported protocols in ARP packet") | Unpack a binary struct into this object's attributes.
Return the values instead of the lib's basic types.
Check if the protocols involved are Ethernet and IPv4. Other protocols
are currently not supported.
Args:
buff (bytes): Binary buffer.
offset (int): Where to begin unpacking.
Raises:
:exc:`~.exceptions.UnpackExc... | juraj-google-style |
def load_own_variables(self, store):
all_vars = self._trainable_variables + self._non_trainable_variables
if len(store.keys()) != len(all_vars):
if len(all_vars) == 0 and (not self.built):
raise ValueError(f"Layer '{self.name}' was never built and thus it doesn't have any variables. However ... | Loads the state of the layer.
You can override this method to take full control of how the state of
the layer is loaded upon calling `keras.models.load_model()`.
Args:
store: Dict from which the state of the model will be loaded. | github-repos |
def ts_to_dt(jwt_dict):
d = jwt_dict.copy()
for k, v in [v[:2] for v in CLAIM_LIST if v[2]]:
if k in jwt_dict:
d[k] = d1_common.date_time.dt_from_ts(jwt_dict[k])
return d | Convert timestamps in JWT to datetime objects.
Args:
jwt_dict: dict
JWT with some keys containing timestamps.
Returns:
dict: Copy of input dict where timestamps have been replaced with
datetime.datetime() objects. | juraj-google-style |
def dispatch_event(self, event: "Event") -> None:
if event.target is None:
event.set_target(self)
listeners: dict[types.MethodType, bool] = self._registered_listeners.get(event.type)
if listeners is None:
return
for listener in listene... | Dispatches the given event.
It is the duty of this method to set the target of the dispatched event by calling
`event.set_target(self)`.
Args:
event (Event): The event to dispatch. Must not be `None`.
Raises:
TypeError: If the event is `None` or its type is incorrect. | juraj-google-style |
def has_full_stack(self, value):
if value == self._defaults['hasFullStack'] and 'hasFullStack' in self._values:
del self._values['hasFullStack']
else:
self._values['hasFullStack'] = value | The has_full_stack property.
Args:
value (bool). the property value. | juraj-google-style |
def identify_triggers(cfg, sources, sinks, lattice, nosec_lines):
assignment_nodes = filter_cfg_nodes(cfg, AssignmentNode)
tainted_nodes = filter_cfg_nodes(cfg, TaintedNode)
tainted_trigger_nodes = [TriggerNode(Source('Framework function URL parameter'), cfg_node=node) for node in tainted_nodes]
sources... | Identify sources, sinks and sanitisers in a CFG.
Args:
cfg(CFG): CFG to find sources, sinks and sanitisers in.
sources(tuple): list of sources, a source is a (source, sanitiser) tuple.
sinks(tuple): list of sources, a sink is a (sink, sanitiser) tuple.
nosec_lines(set): lines with # nosec whitelisting
Returns:
Trigge... | codesearchnet |
def take_bug_report(self,
test_name,
begin_time,
timeout=300,
destination=None):
new_br = True
try:
stdout = self.adb.shell('bugreportz -v').decode('utf-8')
... | Takes a bug report on the device and stores it in a file.
Args:
test_name: Name of the test method that triggered this bug report.
begin_time: Timestamp of when the test started.
timeout: float, the number of seconds to wait for bugreport to
complete, default is 5min.
destination: string, path to the directory where t... | juraj-google-style |
def DeserializeExclusiveData(self, reader):
if self.Version is not 0:
raise Exception('Invalid format')
self.PublicKey = ECDSA.Deserialize_Secp256r1(reader) | Deserialize full object.
Args:
reader (neo.IO.BinaryReader):
Raises:
Exception: If the version read is incorrect. | juraj-google-style |
def insert_tile(self, tile_info):
for i, tile in enumerate(self.registered_tiles):
if tile.slot == tile_info.slot:
self.registered_tiles[i] = tile_info
return
self.registered_tiles.append(tile_info) | Add or replace an entry in the tile cache.
Args:
tile_info (TileInfo): The newly registered tile. | juraj-google-style |
def event_shape(self):
return tensor_shape.as_shape(self._event_shape()) | Shape of a single sample from a single batch as a `TensorShape`.
May be partially defined or unknown.
Returns:
event_shape: `TensorShape`, possibly unknown. | github-repos |
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0):
super(QueryRequestPayload, self).read(input_buffer, kmip_version=kmip_version)
local_buffer = utils.BytearrayStream(input_buffer.read(self.length))
query_functions = []
while self.is_tag_next(enums.Tags.QUERY_FUNCTION, local_buffer):... | Read the data encoding the QueryRequestPayload object and decode it
into its constituent parts.
Args:
input_buffer (Stream): A data stream containing encoded object
data, supporting a read method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the obje... | codesearchnet |
def to(self, new_unit):
return self.__class__(
np.array(self) * self.unit.get_conversion_factor(new_unit),
unit_type=self.unit_type, unit=new_unit) | Conversion to a new_unit.
Args:
new_unit:
New unit type.
Returns:
A ArrayWithFloatWithUnit object in the new units.
Example usage:
>>> e = EnergyArray([1, 1.1], "Ha")
>>> e.to("eV")
array([ 27.21138386, 29.93252225]) eV | juraj-google-style |
def merge(metric_kind, prior, latest):
(prior_type, _) = _detect_value(prior)
(latest_type, _) = _detect_value(latest)
if (prior_type != latest_type):
_logger.warn(u'Metric values are not compatible: %s, %s', prior, latest)
raise ValueError(u'Incompatible delta metric values')
if (prior_... | Merges `prior` and `latest`
Args:
metric_kind (:class:`MetricKind`): indicates the kind of metrics
being merged
prior (:class:`MetricValue`): an prior instance of the metric
latest (:class:`MetricValue`: the latest instance of the metric | codesearchnet |
def parse_dtype_info(flags):
if flags.dtype in (i[0] for i in DTYPE_MAP.values()):
return
try:
flags.dtype, default_loss_scale = DTYPE_MAP[flags.dtype]
except KeyError:
raise ValueError("Invalid dtype: {}".format(flags.dtype))
flags.loss_scale = flags.loss_scale or default_loss_scale | Convert dtype string to tf dtype, and set loss_scale default as needed.
Args:
flags: namespace object returned by arg parser.
Raises:
ValueError: If an invalid dtype is provided. | juraj-google-style |
def _parse_graph(self):
if self.exists:
self.rdf.graph = self.repo.api.parse_rdf_payload(self.rdf.data, self.headers)
else:
self.rdf.graph = rdflib.Graph()
self.rdf.namespace_manager = rdflib.namespace.NamespaceManager(self.rdf.graph)
for ns_prefix, ns_uri in self.rdf.prefixes.__dict__.ite... | use Content-Type from headers to determine parsing method
Args:
None
Return:
None: sets self.rdf by parsing data from GET request, or setting blank graph of resource does not yet exist | juraj-google-style |
def GetParserObjects(cls, parser_filter_expression=None):
(includes, excludes) = cls._GetParserFilters(parser_filter_expression)
parser_objects = {}
for (parser_name, parser_class) in iter(cls._parser_classes.items()):
if ((not includes) and (parser_name in excludes)):
continue
i... | Retrieves the parser objects.
Args:
parser_filter_expression (Optional[str]): parser filter expression,
where None represents all parsers and plugins.
Returns:
dict[str, BaseParser]: parsers per name. | codesearchnet |
def to_dlpack(tf_tensor):
return pywrap_tfe.TFE_ToDlpackCapsule(tf_tensor) | Returns the dlpack capsule representing the tensor.
This operation ensures the underlying data memory is ready when returns.
```python
a = tf.tensor([1, 10])
dlcapsule = tf.experimental.dlpack.to_dlpack(a)
# dlcapsule represents the dlpack data structure
```
Args:
tf_tensor: Tensorflow eager tensor, to be converted ... | github-repos |
def _ContinueReportCompilation(self):
analyzer_alive = self._analyzer.is_alive()
hash_queue_has_tasks = (self.hash_queue.unfinished_tasks > 0)
analysis_queue = (not self.hash_analysis_queue.empty())
return ((analyzer_alive and hash_queue_has_tasks) or analysis_queue) | Determines if the plugin should continue trying to compile the report.
Returns:
bool: True if the plugin should continue, False otherwise. | codesearchnet |
def docx_text_from_xml(xml: str, config: TextProcessingConfig) -> str:
root = ElementTree.fromstring(xml)
return docx_text_from_xml_node(root, 0, config) | Converts an XML tree of a DOCX file to string contents.
Args:
xml: raw XML text
config: :class:`TextProcessingConfig` control object
Returns:
contents as a string | codesearchnet |
def ParseRow(header,
row):
precondition.AssertDictType(row, Text, Text)
result = rdf_osquery.OsqueryRow()
for column in header.columns:
result.values.append(row[column.name])
return result | Parses a single row of osquery output.
Args:
header: A parsed header describing the row format.
row: A row in a "parsed JSON" representation.
Returns:
A parsed `rdf_osquery.OsqueryRow` instance. | juraj-google-style |
class SamplePatchTSMixerRegressionOutput(ModelOutput):
sequences: Optional[torch.FloatTensor] = None | Base class for time series model's predictions outputs that contains the sampled values from the chosen
distribution.
Args:
sequences (`torch.FloatTensor` of shape `(batch_size, num_samples, num_targets)`
Sampled values from the chosen distribution. | github-repos |
def __init__(self, pattern):
super(Interpolator, self).__init__()
self._pattern = pattern
if isinstance(pattern, bytes):
var_regex = re.compile(self._VAR_PLACEHOLDER_PATTERN.encode("ascii"))
scope_regex = re.compile(self._SCOPE_PLACEHOLDER_PATTERN.encode("ascii"))
decoder = lambda _:... | Initializes the interpolator.
Args:
pattern: A string (either of unicode or byte characters) with placeholders
to format. | juraj-google-style |
def default(self, name, action, seqno):
return self.configure(('default route-map %s %s %s' % (name, action, seqno))) | Defaults the routemap on the node
Note:
This method will attempt to default the routemap from the nodes
operational config. Since routemaps do not exist by default,
the default action is essentially a negation and the result will
be the removal of the routemap clause.
If the routemap does not exist then this
method wi... | codesearchnet |
async def updateCronJob(self, iden, query):
cron = self.cell.agenda.appts.get(iden)
if cron is None:
raise s_exc.NoSuchIden()
self._trig_auth_check(cron.useriden)
await self.cell.agenda.mod(iden, query) | Change an existing cron job's query
Args:
iden (bytes): The iden of the cron job to be changed | juraj-google-style |
def __init__(self, name, formatter=None):
if formatter is not None:
name = formatter(name)
self._tag_data = {'name': name}
self._valid = True
if not name:
self._valid = False | Initialize Class Properties.
Args:
name (str): The value for this tag.
formatter (method, optional): A method that take a tag value and returns a
formatted tag. | juraj-google-style |
def set_item(target, i, x):
if isinstance(target, tensor_array_ops.TensorArray):
return _tf_tensorarray_set_item(target, i, x)
elif tensor_util.is_tf_type(target):
if target.dtype == dtypes.variant:
return _tf_tensor_list_set_item(target, i, x)
else:
return _tf_te... | The slice write operator (i.e. __setitem__).
Note: it is unspecified whether target will be mutated or not. In general,
if target is mutable (like Python lists), it will be mutated.
Args:
target: An entity that supports setitem semantics.
i: Index to modify.
x: The new element value.
Returns:
Same as target, after t... | github-repos |
def ami_lookup(region='us-east-1', name='tomcat8'):
if AMI_JSON_URL:
ami_dict = _get_ami_dict(AMI_JSON_URL)
ami_id = ami_dict[region][name]
elif GITLAB_TOKEN:
warn_user('Use AMI_JSON_URL feature instead.')
ami_contents = _get_ami_file(region=region)
ami_dict = json.l... | Look up AMI ID.
Use _name_ to find AMI ID. If no ami_base_url or gitlab_token is provided,
_name_ is returned as the ami id.
Args:
region (str): AWS Region to find AMI ID.
name (str): Simple AMI base name to lookup.
Returns:
str: AMI ID for _name_ in _region_. | juraj-google-style |
def define_saver(exclude=None):
variables = []
exclude = exclude or []
exclude = [re.compile(regex) for regex in exclude]
for variable in tf.global_variables():
if any(regex.match(variable.name) for regex in exclude):
continue
variables.append(variable)
saver = tf.train.Saver(variables, keep_... | Create a saver for the variables we want to checkpoint.
Args:
exclude: List of regexes to match variable names to exclude.
Returns:
Saver object. | juraj-google-style |
def set_query(self, value):
if (isinstance(value, basestring) or (value is None)):
self._content['query'] = value
elif hasattr(value, 'keys'):
self._content['query'] = query.terms_from_dict(value)
else:
raise TypeError((('Query must be a string or dict. Got: ' + type(value)) + ' inst... | Convert a dict form of query in a string of needed and store the query string.
Args:
value -- A query string or a dict with query xpaths as keys and text or
nested query dicts as values. | codesearchnet |
def lookup(self, keys, name=None):
if keys.dtype.base_dtype != self._key_dtype:
raise TypeError(f'Dtype of argument `keys` must be {self._key_dtype}, received: {keys.dtype}')
values = keys
if isinstance(keys, (sparse_tensor.SparseTensor, internal.RaggedTensor)):
values = keys.values
if s... | Looks up `keys` in the table, outputs the corresponding values.
It assigns out-of-vocabulary keys to buckets based in their hashes.
Args:
keys: Keys to look up. May be either a `SparseTensor` or dense `Tensor`.
name: Optional name for the op.
Returns:
A `SparseTensor` if keys are sparse, a `RaggedTensor` if keys are... | github-repos |
def parse_json(self, values_json):
values_map = json.loads(values_json)
return self.override_from_dict(values_map) | Override existing hyperparameter values, parsing new values from a json object.
Args:
values_json: String containing a json object of name:value pairs.
Returns:
The `HParams` instance.
Raises:
KeyError: If a hyperparameter in `values_json` doesn't exist.
ValueError: If `values_json` cannot be parsed. | codesearchnet |
def variants(self, case_id, skip=0, count=1000, filters=None):
filters = (filters or {})
logger.debug('Looking for variants in {0}'.format(case_id))
limit = (count + skip)
gemini_query = (filters.get('gemini_query') or 'SELECT * from variants v')
any_filter = False
if filters.get('frequency'):
... | Return count variants for a case.
This function needs to have different behaviours based on what is asked
for. It should allways try to give minimal information back to improve
on speed. For example, if consequences are not asked for we will not
build all transcripts. If not sv variants we will not build sv
coordinate... | codesearchnet |
def compile_state_cpfs(self, scope: Dict[(str, TensorFluent)], batch_size: Optional[int]=None, noise: Optional[Noise]=None) -> List[CPFPair]:
next_state_fluents = []
with self.graph.as_default():
with tf.name_scope('state_cpfs'):
for cpf in self.rddl.domain.state_cpfs:
cpf_no... | Compiles the next state fluent CPFs given the current `state` and `action` scope.
Args:
scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): The fluent scope for CPF evaluation.
batch_size (Optional[int]): The batch size.
Returns:
A list of state fluent CPFs compiled to :obj:`rddl2tf.fluent.TensorFluent`. | codesearchnet |
def PushEvent(self, timestamp, event_data):
heap_values = (timestamp, event_data)
heapq.heappush(self._heap, heap_values)
self.data_size += len(event_data) | Pushes a serialized event onto the heap.
Args:
timestamp (int): event timestamp, which contains the number of
micro seconds since January 1, 1970, 00:00:00 UTC.
event_data (bytes): serialized event. | codesearchnet |
def convert_version_to_int(version):
version = version.split('-')[0]
version_segments = version.split('.')
if len(version_segments) == 2:
version_segments.append('0')
for seg in version_segments:
if not seg.isdigit():
return None
version_str = ''.join(['%03d' % int(seg) f... | Convert a version number to a integer that can be used to compare.
Version strings of the form X.YZ and X.Y.Z-xxxxx are supported. The
'xxxxx' part, for instance 'homebrew' on OS/X, is ignored.
Args:
version: a version to be converted
Returns:
An integer if converted successfully, otherwise return None. | github-repos |
def __version_capture_slp(self, pkg_id, version_binary, version_display, display_name):
if (self.__pkg_obj and hasattr(self.__pkg_obj, 'version_capture')):
(version_str, src, version_user_str) = self.__pkg_obj.version_capture(pkg_id, version_binary, version_display, display_name)
if ((src != 'use-de... | This returns the version and where the version string came from, based on instructions
under ``version_capture``, if ``version_capture`` is missing, it defaults to
value of display-version.
Args:
pkg_id (str): Publisher of the software/component.
version_binary (str): Name of the software.
version_display (str): True ... | codesearchnet |
def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error):
line = clean_lines.elided[linenum]
fncall = line
for pattern in (r'\bif\s*\((.*)\)\s*{',
r'\bfor\s*\((.*)\)\s*{',
r'\bwhile\s*\((.*)\)\s*[{;]',
r'\bswitch\s*\((.*)\)\s*... | Checks for the correctness of various spacing around function calls.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | juraj-google-style |
def CheckForNewlineAtEOF(filename, lines, error):
if len(lines) < 3 or lines[-2]:
error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
'Could not find a newline character at the end of the file.') | Logs an error if there is no newline char at the end of the file.
Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found. | juraj-google-style |
def in_range(self, ver, req):
if req.exclude is not None:
for v in ver:
if v in req.exclude:
return False
include_checked = False
if req.include is not None:
for v in ver:
if v in req.include:
return True
include_checked = True
... | Checks if a version satisfies a version and/or compatibility requirement.
Args:
ver: List whose first item is a config version that needs to be checked
for support status and version compatibility.
e.g. ver = [`1.0`]
req: `_Reqs` class instance that represents a configuration version and
compatibility specifications.
... | github-repos |
def get_attribute_id(self, attribute_key):
attribute = self.attribute_key_map.get(attribute_key)
has_reserved_prefix = attribute_key.startswith(RESERVED_ATTRIBUTE_PREFIX)
if attribute:
if has_reserved_prefix:
self.logger.warning(('Attribute %s unexpectedly has reserved prefix %s; using ... | Get attribute ID for the provided attribute key.
Args:
attribute_key: Attribute key for which attribute is to be fetched.
Returns:
Attribute ID corresponding to the provided attribute key. | juraj-google-style |
def num_parameters(self, only_trainable: bool=False) -> int:
if only_trainable:
return int(sum((np.prod(w.shape.as_list()) for w in self.trainable_variables)))
else:
return self.count_params() | Get the number of (optionally, trainable) parameters in the model.
Args:
only_trainable (`bool`, *optional*, defaults to `False`):
Whether or not to return only the number of trainable parameters
Returns:
`int`: The number of parameters. | github-repos |
def make_trace_api(client):
generated = trace_service_client.TraceServiceClient(
credentials=client._credentials, client_info=_CLIENT_INFO
)
return _TraceAPI(generated, client) | Create an instance of the gapic Trace API.
Args:
client (~google.cloud.trace.client.Client): The client that holds
configuration details.
Returns:
A :class:`~google.cloud.trace._gapic._TraceAPI` instance with the
proper configurations. | juraj-google-style |
def skip_summary():
replica_context = distribute_lib.get_replica_context()
if not replica_context:
return False
replica_id = replica_context.replica_id_in_sync_group
if isinstance(replica_id, tensor.Tensor):
replica_id = tensor_util.constant_value(replica_id)
return replica_id and re... | Determines if summary should be skipped.
If using multiple replicas in distributed strategy, skip summaries on all
replicas except the first one (replica_id=0).
Returns:
True if the summary is skipped; False otherwise. | github-repos |
async def leader(self):
response = (await self._api.get('/v1/status/leader'))
if (response.status == 200):
return response.body | Returns the current Raft leader
Returns:
str: address of leader such as ``10.1.10.12:8300`` | codesearchnet |
def add_rel(self, source_node_id, target_node_id, rel):
n1_ref = self.graph_db.get_indexed_node('Node', 'node_id', source_node_id)
n2_ref = self.graph_db.get_indexed_node('Node', 'node_id', target_node_id)
if not n1_ref or not n2_ref:
print 'Cannot add re... | Add a relationship between nodes.
Args:
source_node_id: Node Id for the source node.
target_node_id: Node Id for the target node.
rel: Name of the relationship 'contains' | juraj-google-style |
def get_absorbing_atom_symbol_index(absorbing_atom, structure):
if isinstance(absorbing_atom, str):
return (absorbing_atom, structure.indices_from_symbol(absorbing_atom)[0])
elif isinstance(absorbing_atom, int):
return (str(structure[absorbing_atom].specie), absorbing_atom)
else:
rai... | Return the absorbing atom symboll and site index in the given structure.
Args:
absorbing_atom (str/int): symbol or site index
structure (Structure)
Returns:
str, int: symbol and site index | codesearchnet |
def segment(self, text):
files = {'text': text}
(res, status_code) = self.post(self.segmentation_service, files=files)
if (status_code != 200):
logger.debug('Segmentation failed.')
return (self.decode(res), status_code) | Call the segmenter in order to split text in sentences.
Args:
text (str): Text to be segmented.
Returns:
dict, int: A dict containing a list of dicts with the offsets of
each sentence; an integer representing the response code. | codesearchnet |
def controller_factory(cls, passes, options, **partial_controller):
if (None in partial_controller.values()):
raise TranspilerError('The controller needs a condition.')
if partial_controller:
for registered_controller in cls.registered_controllers.keys():
if (registered_controller in... | Constructs a flow controller based on the partially evaluated controller arguments.
Args:
passes (list[BasePass]): passes to add to the flow controller.
options (dict): PassManager options.
**partial_controller (dict): Partially evaluated controller arguments in the form
`{name:partial}`
Raises:
TranspilerError: When... | codesearchnet |
def lin_moma2(self, objective, wt_obj):
reactions = set(self._adjustment_reactions())
z_diff = self._z_diff
v = self._v
v_wt = self._v_wt
with self.constraints() as constr:
for f_reaction in reactions:
constr.add((z_diff[f_reaction] >= (v_wt[f_reaction] - v[f_reaction])), ((v_wt[... | Find the smallest redistribution vector using a linear objective.
The change in flux distribution is mimimized by minimizing the sum
of the absolute values of the differences of wild type FBA solution
and the knockout strain flux solution.
Creates the constraint that the we select the optimal flux vector that
is clos... | codesearchnet |
def _combine_sparse_successor(parent_indices, parent_shape, child_indices, child_values, child_shape, name=None):
with ops.name_scope(name, 'CombineSparseSuccessor', [parent_indices, parent_shape, child_indices, child_values, child_shape]):
(indices, values, shape) = ops_module.combine_sparse_successor(pare... | Combines two string `SparseTensor`s, where second `SparseTensor` is the result of expanding
first `SparseTensor`'s values.
Args:
parent_indices: 2D int64 `Tensor` with parent `SparseTensor` indices
parent_shape: 1D int64 `Tensor` with parent `SparseTensor` dense_shape
child_indices: 2D int64 `Tensor` with child `Spars... | codesearchnet |
def circuits_to_qobj(circuits, qobj_header=None, qobj_id=None, backend_name=None, config=None, shots=None, max_credits=None, basis_gates=None, coupling_map=None, seed=None, memory=None):
warnings.warn('circuits_to_qobj is deprecated and will be removed in Qiskit Terra 0.9. Use qiskit.compiler.assemble() to serializ... | Convert a list of circuits into a qobj.
Args:
circuits (list[QuantumCircuits] or QuantumCircuit): circuits to compile
qobj_header (QobjHeader): header to pass to the results
qobj_id (int): TODO: delete after qiskit-terra 0.8
backend_name (str): TODO: delete after qiskit-terra 0.8
config (dict): TODO: delete after qisk... | codesearchnet |
def _take_screenshot(self, screenshot=False, name_prefix='unknown'):
if isinstance(screenshot, bool):
if not screenshot:
return
return self._save_screenshot(name_prefix=name_prefix)
if isinstance(screenshot, Image.Image):
return self._save_scr... | This is different from _save_screenshot.
The return value maybe None or the screenshot path
Args:
screenshot: bool or PIL image | juraj-google-style |
def require_representation(self, req):
try:
type_, subtype, _ = parse_mime_type(req.content_type)
content_type = '/'.join((type_, subtype))
except:
raise falcon.HTTPUnsupportedMediaType(
description="Invalid Content-Type header: {}".format(
... | Require raw representation dictionary from falcon request object.
This does not perform any field parsing or validation but only uses
allowed content-encoding handler to decode content body.
Note:
Currently only JSON is allowed as content type.
Args:
req (falcon.Request): request object
Returns:
dict: raw dictionar... | juraj-google-style |
def execute_before(self, sensor_graph, scope_stack):
sensor_graph.add_constant(self.stream, 0)
new_scope = GatedClockScope(sensor_graph, scope_stack, (self.stream, self.trigger))
scope_stack.append(new_scope) | Execute statement before children are executed.
Args:
sensor_graph (SensorGraph): The sensor graph that we are building or
modifying
scope_stack (list(Scope)): A stack of nested scopes that may influence
how this statement allocates clocks or other stream resources. | juraj-google-style |
def SendReply(self, response, tag=None):
if not isinstance(response, rdfvalue.RDFValue):
raise ValueError("SendReply can only send RDFValues")
if self.rdf_flow.parent_flow_id:
response = rdf_flow_objects.FlowResponse(
client_id=self.rdf_flow.client_id,
request_id=self.rdf_f... | Allows this flow to send a message to its parent flow.
If this flow does not have a parent, the message is ignored.
Args:
response: An RDFValue() instance to be sent to the parent.
tag: If specified, tag the result with this tag.
Raises:
ValueError: If responses is not of the correct type. | juraj-google-style |
def is_stateful(self) -> bool:
return True | Indicates whether this ThresholdFn is stateful.
Returns:
bool: Always True for `QuantileThreshold` as it is stateful. | github-repos |
def read_video_opencv(video_path: str, sample_indices_fn: Callable, **kwargs):
requires_backends(read_video_opencv, ['cv2'])
import cv2
video = cv2.VideoCapture(video_path)
total_num_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
video_fps = video.get(cv2.CAP_PROP_FPS)
duration = total_num_fr... | Decode a video using the OpenCV backend.
Args:
video_path (`str`):
Path to the video file.
sample_indices_fn (`Callable`):
A callable function that will return indices at which the video should be sampled. If the video has to be loaded using
by a different sampling technique than provided by `num_frames` or `fps` argu... | github-repos |
def parse_flags_with_usage(args):
try:
return FLAGS(args)
except flags.Error as error:
sys.stderr.write(('FATAL Flags parsing error: %s\n' % error))
sys.stderr.write('Pass --helpshort or --helpfull to see help on flags.\n')
sys.exit(1) | Tries to parse the flags, print usage, and exit if unparseable.
Args:
args: [str], a non-empty list of the command line arguments including
program name.
Returns:
[str], a non-empty list of remaining command line arguments after parsing
flags, including program name. | codesearchnet |
def hist_axis_func(axis_type: enum.Enum) -> Callable[([Hist], Axis)]:
def axis_func(hist: Hist) -> Axis:
' Retrieve the axis associated with the ``HistAxisRange`` object for a given hist.\n\n Args:\n hist: Histogram from which the selected axis should be retrieved.\n axis_type:... | Wrapper to retrieve the axis of a given histogram.
This can be convenient outside of just projections, so it's made available in the API.
Args:
axis_type: The type of axis to retrieve.
Returns:
Callable to retrieve the specified axis when given a hist. | codesearchnet |
def window(self, begin, end=None):
if (self._name_parts.decorator != ''):
raise Exception('Cannot use window() on an already decorated table')
start = Table._convert_decorator_time(begin)
if (end is None):
if isinstance(begin, datetime.timedelta):
end = datetime.timedelta(0)
... | Return a new Table limited to the rows added to this Table during the specified time range.
Args:
begin: the start time of the window. This can be a Python datetime (absolute) or timedelta
(relative to current time). The result must be after the table was created and no more
than seven days in the past.
Note that usi... | codesearchnet |
def to_proto(self, export_scope=None):
raise NotImplementedError | Converts a `Variable` to a `VariableDef` protocol buffer.
Args:
export_scope: Optional `string`. Name scope to remove.
Returns:
A `VariableDef` protocol buffer, or `None` if the `Variable` is not
in the specified name scope. | github-repos |
def bounded_uniform(cls, lowest, highest, weight_interval=None):
if (weight_interval is None):
weights = [(lowest, 1), (highest, 1)]
else:
i = lowest
weights = []
while (i < highest):
weights.append((i, 1))
i += weight_interval
weights.append((high... | Initialize with a uniform distribution between two values.
If no ``weight_interval`` is passed, this weight distribution
will just consist of ``[(lowest, 1), (highest, 1)]``. If specified,
weights (still with uniform weight distribution) will be added every
``weight_interval``. Use this if you intend to modify the wei... | codesearchnet |
def __user_location(__pkg: str, type_) -> str:
if ALLOW_DARWIN and sys.platform == 'darwin':
user_dir = '~/Library/{}'.format(__LOCATIONS[type_][0])
else:
user_dir = getenv('XDG_{}_HOME'.format(type_.upper()),
path.sep.join([getenv('HOME', ''),
... | Utility function to look up XDG basedir locations
Args:
__pkg: Package name
__type: Location type | juraj-google-style |
def __get_conn(self, flag_force_new=False, filename=None):
flag_open_new = (flag_force_new or (not self._conn_is_open()))
if flag_open_new:
if (filename is None):
filename = self.filename
conn = self._get_conn(filename)
self._conn = conn
else:
conn = self._conn
... | Returns connection to database. Tries to return existing connection, unless flag_force_new
Args:
flag_force_new:
filename:
Returns: sqlite3.Connection object
**Note** this is a private method because you can get a connection to any file, so it has to
be used in the right moment | codesearchnet |
def save_target_classes_for_batch(self, filename, image_batches, batch_id):
images = image_batches.data[batch_id]['images']
with open(filename, 'w') as f:
for (image_id, image_val) in iteritems(images):
target_class = self.get_target_class(image_val['dataset_image_id'])
f.write('... | Saves file with target class for given dataset batch.
Args:
filename: output filename
image_batches: instance of ImageBatchesBase with dataset batches
batch_id: dataset batch ID | codesearchnet |
def matmul(self, input_tensor: core.Tensor) -> Mapping[str, core.Tensor]:
out = math_ops.matmul(input_tensor, self.filters, name='sample/matmul')
if bias_fn is not None:
out = bias_fn(out, self.bias)
if activation_fn is not None:
out = activation_fn(out)
return {'output': out} | Performs a matrix multiplication.
Depending on self.bias_fn and self.activation_fn, it may add a bias
term or go through the activaction function.
Args:
input_tensor: Input tensor to matmul with the filter.
Returns:
A map of: output key -> output result. | github-repos |
def diff(self, container):
return self._result(self._get(self._url('/containers/{0}/changes', container)), True) | Inspect changes on a container's filesystem.
Args:
container (str): The container to diff
Returns:
(str)
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error. | codesearchnet |
def __init__(self, indices, num_segments, batch_dims=0):
self.indices = torch.as_tensor(indices, device=indices.device)
self.num_segments = torch.as_tensor(num_segments, device=indices.device)
self.batch_dims = batch_dims | Creates an index
Args:
indices (`torch.LongTensor`, same shape as a *values* Tensor to which the indices refer):
Tensor containing the indices.
num_segments (`torch.LongTensor`):
Scalar tensor, the number of segments. All elements in a batched segmented tensor must have the same
number of segments (although many segme... | github-repos |
def read_tree_newick(newick):
if (not isinstance(newick, str)):
try:
newick = str(newick)
except:
raise TypeError('newick must be a str')
if newick.lower().endswith('.gz'):
f = gopen(expanduser(newick))
ts = f.read().decode().strip()
f.close()
... | Read a tree from a Newick string or file
Args:
``newick`` (``str``): Either a Newick string or the path to a Newick file (plain-text or gzipped)
Returns:
``Tree``: The tree represented by ``newick``. If the Newick file has multiple trees (one per line), a ``list`` of ``Tree`` objects will be returned | codesearchnet |
def parse_query(self, query, index, stop_current, shuffle):
if index is not None and len(self.queue) > 0:
if index < 0 or index >= len(self.queue):
if len(self.queue) == 1:
self.statuslog.error("Play index must be 1 (1 song in queue)")
... | Parses a query and adds it to the queue
Args:
query (str): Either a search term or a link
index (int): The index to enqueue at (None for end)
stop_current (bool): Whether to stop the current song after the songs are queued
shuffle (bool): Whether to shuffle the added songs | juraj-google-style |
def clamp(value, maximum=None):
value = max(value, 0)
if maximum is not None:
return min(value, maximum)
else:
return value | Clamp numeric values to be non-negative, an optionally, less than a
given maximum.
Args:
value (float) :
A number to clamp.
maximum (float, optional) :
A max bound to to clamp to. If None, there is no upper bound,
and values are only clamped to be non-negative. (default: None)
Returns:
float | juraj-google-style |
def _AsTensorList(x, p):
if not isinstance(x, (list, _basetuple)):
x = [x]
l = []
for v in x:
if isinstance(v, ops.Operation):
v = with_dependencies([v], p)
v = ops.convert_to_tensor_or_composite(v)
if isinstance(v, tensor_lib.Tensor):
l.append(array_o... | Return x as a list of Tensors or IndexedSlices.
For entries of `x` that are Operations, this returns an Identity of `p`
with a dependency on the operation.
Args:
x: A Tensor/IndexedSlices/Operation or a list or tuple of them.
p: A Tensor to return for entries in `x` that are Operations.
Returns:
A list of Tensors or... | github-repos |
def Append(self, value, timestamp):
timestamp = self._NormalizeTime(timestamp)
if self.data and timestamp < self.data[-1][1]:
raise RuntimeError("Next timestamp must be larger.")
self.data.append([value, timestamp]) | Adds value at timestamp.
Values must be added in order of increasing timestamp.
Args:
value: An observed value.
timestamp: The timestamp at which value was observed.
Raises:
RuntimeError: If timestamp is smaller than the previous timstamp. | juraj-google-style |
def SaveGDAL(filename, rda):
if type(rda) is not rdarray:
raise Exception("A richdem.rdarray or numpy.ndarray is required!")
if not GDAL_AVAILABLE:
raise Exception("richdem.SaveGDAL() requires GDAL.")
driver = gdal.GetDriverByName('GTiff')
data_type = gdal.GDT_Float32
data_set = driver.Creat... | Save a GDAL file.
Saves a RichDEM array to a data file in GeoTIFF format.
If you need to do something more complicated, look at the source of this
function.
Args:
filename (str): Name of the raster file to be created
rda (rdarray): Data to save.
Returns:
No Return | juraj-google-style |
def terminate(self, end):
if self.terminated:
raise TdlError('Cannot terminate a closed list.')
if (end == LIST_TYPE):
self.terminated = False
elif (end == EMPTY_LIST_TYPE):
if self._last_path:
self[self._last_path] = None
else:
self._avm = None
... | Set the value of the tail of the list.
Adding values via :meth:`append` places them on the `FIRST`
feature of some level of the feature structure (e.g.,
`REST.FIRST`), while :meth:`terminate` places them on the
final `REST` feature (e.g., `REST.REST`). If *end* is a
:class:`Conjunction` or :class:`Term`, it is typical... | codesearchnet |
def __init__(self, mh_map: dict[str, ModelHandler]):
self._max_models = None
self._mh_map: dict[str, ModelHandler] = mh_map
self._key_to_last_update: dict[str, str] = defaultdict(str)
self._tag_map: dict[str, str] = OrderedDict()
self._proxy_map: dict[str, multi_process_shared.MultiProcessShared] = ... | Args:
mh_map: A map from keys to model handlers which can be used to load a
model. | github-repos |
def match_opcodes(opcode_traces, lineno, op_match_list):
out = []
for trace in opcode_traces[lineno]:
for match_op, match_symbol in op_match_list:
if trace.op == match_op and match_symbol in [None, trace.symbol]:
out.append((trace.op, trace.symbol, trace.types))
return ou... | Get all opcodes matching op_match_list on a given line.
Args:
opcode_traces: traces
lineno: line number to get ops from.
op_match_list: [(opcode_name, symbol|None), ...]; None matches any symbol.
Returns:
A list of matching opcodes. | github-repos |
def __tomo_linear_inv(freqs, ops, weights=None, trace=None):
if (weights is not None):
W = np.array(weights)
if (W.ndim == 1):
W = np.diag(W)
S = np.array([vectorize(m).conj() for m in ops]).reshape(len(ops), ops[0].size)
if (weights is not None):
S = np.dot(W, S)
v =... | Reconstruct a matrix through linear inversion.
Args:
freqs (list[float]): list of observed frequences.
ops (list[np.array]): list of corresponding projectors.
weights (list[float] or array_like):
weights to be used for weighted fitting.
trace (float or None): trace of returned operator.
Returns:
numpy.array: A numpy ... | codesearchnet |
def output_sector_csv(self,csv_path,file_dict_key,out_path):
csv_file = csv_path + "{0}_{1}_{2}_{3}.csv".format(
file_dict_key,
self.ensemble_name,
... | Segment forecast tracks to only output data contined within a
region in the CONUS, as defined by the mapfile.
Args:
csv_path(str): Path to the full CONUS csv file.
file_dict_key(str): Dictionary key for the csv files,
currently either 'track_step' or 'track_total'
out_path (str): Path to output new segmented csv files... | juraj-google-style |
def verify_fully_used_iterator(self, ds_fn, num_outputs, sparse_tensors=False, assert_items_equal=False):
self.verify_run_with_breaks(ds_fn, [num_outputs], num_outputs, sparse_tensors=sparse_tensors, assert_items_equal=assert_items_equal) | Verifies that saving and restoring a fully used iterator works.
Note that this only checks saving and restoring an iterator from which
`num_outputs` items have been produced but does not check for an
exhausted iterator, i.e., one from which an OutOfRange error has been
returned.
Args:
ds_fn: 0-argument function that ... | github-repos |
def get_cpu_vendor(cls, family, arch='x86'):
props = cls.get_cpu_props(family, arch)
vendor = 'generic'
try:
vendor = props.xpath('vendor/@name')[0]
except IndexError:
pass
return vendor | Get CPU vendor, if vendor is not available will return 'generic'
Args:
family(str): CPU family
arch(str): CPU arch
Returns:
str: CPU vendor if found otherwise 'generic' | juraj-google-style |
def concat(self, second_iterable):
if self.closed():
raise ValueError('Attempt to call concat() on a closed Queryable.')
if (not is_iterable(second_iterable)):
raise TypeError('Cannot compute concat() with second_iterable of non-iterable {0}'.format(str(type(second_iterable))[7:(- 1)]))
retu... | Concatenates two sequences.
Note: This method uses deferred execution.
Args:
second_iterable: The sequence to concatenate on to the sequence.
Returns:
A Queryable over the concatenated sequences.
Raises:
ValueError: If the Queryable is closed().
TypeError: If second_iterable is not in fact iterable. | codesearchnet |
def Process(self, parser_mediator, zip_file, archive_members):
if (not self.REQUIRED_PATHS):
raise ValueError('REQUIRED_PATHS not specified')
if (not set(archive_members).issuperset(self.REQUIRED_PATHS)):
raise errors.WrongCompoundZIPPlugin(self.NAME)
logger.debug('Compound ZIP Plugin used: ... | Determines if this is the correct plugin; if so proceed with processing.
This method checks if the zip file being contains the paths specified in
REQUIRED_PATHS. If all paths are present, the plugin logic processing
continues in InspectZipFile.
Args:
parser_mediator (ParserMediator): mediates interactions between par... | codesearchnet |
def get_config_file(basename):
locations = [
os.path.join(os.curdir, basename),
os.path.join(
os.path.expanduser("~"),
".config",
"scriptabit",
basename),
resource_filename(
Requirement.parse("scriptabit"),
os.path.... | Looks for a configuration file in 3 locations:
- the current directory
- the user config directory (~/.config/scriptabit)
- the version installed with the package (using setuptools resource API)
Args:
basename (str): The base filename.
Returns:
str: The full path to the configuration file. | juraj-google-style |
def DisjoinCalendars(self, cutoff):
def TruncatePeriod(service_period, start, end):
service_period.start_date = max(service_period.start_date, start)
service_period.end_date = min(service_period.end_date, end)
dates_to_delete = []
for k in service_period.date_exceptions:
... | Forces the old and new calendars to be disjoint about a cutoff date.
This truncates the service periods of the old schedule so that service
stops one day before the given cutoff date and truncates the new schedule
so that service only begins on the cutoff date.
Args:
cutoff: The cutoff date as a string in YYYYMMDD fo... | juraj-google-style |
def _parse_format_pages_isbn(html_chunk):
ppi = get_first_content(
html_chunk.find("div", {"class": "price-overflow"})
)
if not ppi:
return None, None, None
ppi = filter(lambda x: x.strip(), ppi.split("<br />"))[0]
isbn = dhtmlparser.parseString(ppi)
isbn = isbn... | Parse format, number of pages and ISBN.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
tuple: (format, pages, isbn), all as string. | juraj-google-style |
def table(name=None, mode='create', use_cache=True, priority='interactive', allow_large_results=False):
output = QueryOutput()
output._output_type = 'table'
output._table_name = name
output._table_mode = mode
output._use_cache = use_cache
output._priority = priority
output._allow_large_resul... | Construct a query output object where the result is a table
Args:
name: the result table name as a string or TableName; if None (the default), then a
temporary table will be used.
table_mode: one of 'create', 'overwrite' or 'append'. If 'create' (the default), the request
will fail if the table exists.
use_cache: whet... | codesearchnet |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.