code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def close_position(self, repay_only):
params = {'repay_only': repay_only}
return self._send_message('post', '/position/close',
data=json.dumps(params)) | Close position.
Args:
repay_only (bool): Undocumented by cbpro.
Returns:
Undocumented | juraj-google-style |
def colored(text: str, color: Optional[str]=None, background: Optional[str]=None, styles: Optional[List[str]]=None) -> str:
if not termcolor:
return text
return termcolor.colored(text, color=color, on_color='on_' + background if background else None, attrs=styles) | Returns the colored text with ANSI color characters.
Args:
text: A string that may or may not already has ANSI color characters.
color: A string for text colors. Applicable values are:
'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'.
background: A string for background colors. Applicable values are:
'red'... | github-repos |
def InterpolatePath(path, knowledge_base, users=None, path_args=None, depth=0):
sys_formatters = {'systemroot': 'c:\\Windows'}
if path_args:
sys_formatters.update(path_args)
if users:
results = []
for user in users:
user = GetUserInfo(knowledge_base, user)
if ... | Take a string as a path on a client and interpolate with client data.
Args:
path: A single string/unicode to be interpolated.
knowledge_base: An rdf_client.KnowledgeBase object.
users: A list of string usernames, or None.
path_args: A dict of additional args to use in interpolation. These take
precedence over any syst... | codesearchnet |
def get_tensor_shape(self, tensor_name):
tensor = self._name_to_tensor(tensor_name)
if isinstance(tensor, mtf.Tensor):
return tf.TensorShape(tensor.shape.to_integer_list)
else:
return tensor.shape | The tf.TensorShape of a tensor.
Args:
tensor_name: string, the name of a tensor in the graph.
Returns:
a tf.TensorShape | juraj-google-style |
def create(self, data=None, uri=None, timeout=-1, custom_headers=None, force=False):
if not uri:
uri = self._base_uri
if force:
uri += '?force={}'.format(force)
logger.debug('Create (uri = %s, resource = %s)' % (uri, str(data)))
return self.do_post(uri... | Makes a POST request to create a resource when a request body is required.
Args:
data: Additional fields can be passed to create the resource.
uri: Resouce uri
timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
in OneView; it just stops waiting for its completion... | juraj-google-style |
def ConvertCloudMetadataResponsesToCloudInstance(metadata_responses):
if (metadata_responses.instance_type == 'GOOGLE'):
cloud_instance = GoogleCloudInstance()
result = CloudInstance(cloud_type='GOOGLE', google=cloud_instance)
elif (metadata_responses.instance_type == 'AMAZON'):
cloud_in... | Convert CloudMetadataResponses to CloudInstance proto.
Ideally we'd just get the client to fill out a CloudInstance proto, but we
need to keep the flexibility of collecting new metadata and creating new
fields without a client push. So instead we bring back essentially a dict of
results and fill the proto on the serve... | codesearchnet |
def set_room_alias(self, room_id, room_alias):
data = {'room_id': room_id}
return self._send('PUT', '/directory/room/{}'.format(quote(room_alias)), content=data) | Set alias to room id
Args:
room_id (str): The room id.
room_alias (str): The room wanted alias name. | codesearchnet |
def filter_distributed_callbacks(callbacks_list, model):
if not model._in_multi_worker_mode():
raise ValueError('filter_distributed_callbacks() should only be called when Keras is in multi worker mode.')
callbacks_list = callbacks_list or []
if not [c for c in callbacks_list if isinstance(c, callbac... | Filter Callbacks based on the worker context when running multi-worker.
Args:
callbacks_list: A list of `Callback` instances.
model: Keras model instance.
Returns:
The list of `Callback` instances that should be run on this worker. | github-repos |
def _validate_aud(claims, audience=None):
if ('aud' not in claims):
return
audience_claims = claims['aud']
if isinstance(audience_claims, string_types):
audience_claims = [audience_claims]
if (not isinstance(audience_claims, list)):
raise JWTClaimsError('Invalid claim format in t... | Validates that the 'aud' claim is valid.
The "aud" (audience) claim identifies the recipients that the JWT is
intended for. Each principal intended to process the JWT MUST
identify itself with a value in the audience claim. If the principal
processing the claim does not identify itself with a value in the
"aud" clai... | codesearchnet |
def from_string(cls, public_key):
public_key_data = _helpers.to_bytes(public_key)
if _CERTIFICATE_MARKER in public_key_data:
cert = cryptography.x509.load_pem_x509_certificate(
public_key_data, _BACKEND)
pubkey = cert.public_key()
else:
... | Construct an Verifier instance from a public key or public
certificate string.
Args:
public_key (Union[str, bytes]): The public key in PEM format or the
x509 public key certificate.
Returns:
Verifier: The constructed verifier.
Raises:
ValueError: If the public key can't be parsed. | juraj-google-style |
def output(ret, **kwargs):
if ('opts' in kwargs):
global __opts__
__opts__ = kwargs.pop('opts')
base_indent = (kwargs.get('nested_indent', 0) or __opts__.get('out.table.nested_indent', 0))
rows_key = (kwargs.get('rows_key') or __opts__.get('out.table.rows_key'))
labels_key = (kwargs.get(... | Display the output as table.
Args:
* nested_indent: integer, specify the left alignment.
* has_header: boolean specifying if header should be displayed. Default: True.
* row_delimiter: character to separate rows. Default: ``_``.
* delim: character to separate columns. Default: ``" | "``.
* justify: text alignment. De... | codesearchnet |
def to_matrix(self):
(w, x, y, z) = self.normalize().data
mat = np.array([[((1 - (2 * (y ** 2))) - (2 * (z ** 2))), (((2 * x) * y) - ((2 * z) * w)), (((2 * x) * z) + ((2 * y) * w))], [(((2 * x) * y) + ((2 * z) * w)), ((1 - (2 * (x ** 2))) - (2 * (z ** 2))), (((2 * y) * z) - ((2 * x) * w))], [(((2 * x) * z) - ((... | Converts a unit-length quaternion to a rotation matrix.
Returns:
ndarray: Rotation matrix. | codesearchnet |
def terminate_ec2_instance(client, resource):
instance = EC2Instance.get(resource.id)
if instance.state == 'terminated':
return ActionStatus.IGNORED, {}
client.terminate_instances(InstanceIds=[resource.id])
return ActionStatus.SUCCEED, {'instance_type': resource.instance_type, 'public_... | Terminate an EC2 Instance
This function will terminate an EC2 Instance.
Args:
client (:obj:`boto3.session.Session.client`): A boto3 client object
resource (:obj:`Resource`): The resource object to terminate
Returns:
`ActionStatus` | juraj-google-style |
def _copy_and_clean_up_expectation(self, expectation, discard_result_format_kwargs=True, discard_include_configs_kwargs=True, discard_catch_exceptions_kwargs=True):
new_expectation = copy.deepcopy(expectation)
if ('success_on_last_run' in new_expectation):
del new_expectation['success_on_last_run']
... | Returns copy of `expectation` without `success_on_last_run` and other specified key-value pairs removed
Returns a copy of specified expectation will not have `success_on_last_run` key-value. The other key-value \
pairs will be removed by default but will remain in the copy if specified.
Args:
expectation (json): \
Th... | codesearchnet |
def __init__(self, subject_hash, hash_information):
self.hash_information = hash_information
self.subject_hash = subject_hash | Initializes analysis information about a hash.
Args:
subject_hash (str): hash that the hash_information relates to.
hash_information (object): information about the hash. This object will be
used by the GenerateLabels method in the HashTaggingAnalysisPlugin
to tag events that relate to the hash. | juraj-google-style |
def _should_unpack(arg):
return type(arg) is tuple | Determines whether the caller needs to unpack the argument from a tuple.
Args:
arg: argument to check
Returns:
Indication of whether the caller needs to unpack the argument from a tuple. | github-repos |
def get_dim_index(js_dict, dim):
try:
dim_index = js_dict['dimension'][dim]['category']['index']
except KeyError:
dim_label = get_dim_label(js_dict, dim)
dim_index = pd.DataFrame(list(zip([dim_label['id'][0]], [0])), index=[0], columns=['id', 'index'])
else:
if (type(dim_inde... | Get index from a given dimension.
Args:
js_dict (dict): dictionary containing dataset data and metadata.
dim (string): dimension name obtained from JSON file.
Returns:
dim_index (pandas.DataFrame): DataFrame with index-based dimension data. | codesearchnet |
def get_opt_attr(obj_pyxb, attr_str, default_val=None):
v = getattr(obj_pyxb, attr_str, default_val)
return (v if (v is not None) else default_val) | Get an optional attribute value from a PyXB element.
The attributes for elements that are optional according to the schema and
not set in the PyXB object are present and set to None.
PyXB validation will fail if required elements are missing.
Args:
obj_pyxb: PyXB object
attr_str: str
Name of an attribute that the Py... | codesearchnet |
def parse_fs_url(fs_url):
match = _RE_FS_URL.match(fs_url)
if (match is None):
raise ParseError('{!r} is not a fs2 url'.format(fs_url))
(fs_name, credentials, url1, url2, path) = match.groups()
if (not credentials):
username = None
password = None
url = url2
else:
... | Parse a Filesystem URL and return a `ParseResult`.
Arguments:
fs_url (str): A filesystem URL.
Returns:
~fs.opener.parse.ParseResult: a parse result instance.
Raises:
~fs.errors.ParseError: if the FS URL is not valid. | codesearchnet |
def _compute_sequence_length_from_mask(mask, time_major):
timestep_index = 0 if time_major else 1
return tf.reduce_sum(tf.cast(mask, tf.int32), axis=timestep_index) | Calculate the sequence length tensor (1-D) based on the masking tensor.
The masking tensor is a 2D boolean tensor with shape [batch, timestep]. For
any timestep that should be masked, the corresponding field will be False.
Consider the following example:
a = [[True, True, False, False],
[True, True, True, False]]
It i... | github-repos |
def _checkResponseWriteData(payload, writedata):
_checkString(payload, minlength=4, description='payload')
_checkString(writedata, minlength=2, maxlength=2, description='writedata')
BYTERANGE_FOR_WRITEDATA = slice(2, 4)
receivedWritedata = payload[BYTERANGE_FOR_WRITEDATA]
if (receivedWritedata != wr... | Check that the write data as given in the response is correct.
The bytes 2 and 3 (zero based counting) in the payload holds the write data.
Args:
* payload (string): The payload
* writedata (string): The data to write, length should be 2 bytes.
Raises:
TypeError, ValueError | codesearchnet |
def AddWatchOnly(self, script_hash):
if (script_hash in self._contracts):
logger.error('Address already in contracts')
return
self._watch_only.append(script_hash) | Add a watch only address to the wallet.
Args:
script_hash (UInt160): a bytearray (len 20) representing the public key.
Note:
Prints a warning to the console if the address already exists in the wallet. | codesearchnet |
def view(location, browser=None, new='same', autoraise=True):
try:
new = {'same': 0, 'window': 1, 'tab': 2}[new]
except KeyError:
raise RuntimeError(("invalid 'new' value passed to view: %r, valid values are: 'same', 'window', or 'tab'" % new))
if location.startswith('http'):
url = l... | Open a browser to view the specified location.
Args:
location (str) : Location to open
If location does not begin with "http:" it is assumed
to be a file path on the local filesystem.
browser (str or None) : what browser to use (default: None)
If ``None``, use the system default browser.
new (str) : How to open the lo... | codesearchnet |
def get_key_delivery_url(access_token, ck_id, key_type):
path = '/ContentKeys'
full_path = ''.join([path, "('", ck_id, "')", '/GetKeyDeliveryUrl'])
endpoint = ''.join([ams_rest_endpoint, full_path])
body = (('{"keyDeliveryType": "' + key_type) + '"}')
return do_ams_post(endpoint, full_path, body, ac... | Get Media Services Key Delivery URL.
Args:
access_token (str): A valid Azure authentication token.
ck_id (str): A Media Service Content Key ID.
key_type (str): A Media Service key Type.
Returns:
HTTP response. JSON body. | codesearchnet |
def in_same_dir(as_file, target_file):
return os.path.abspath(os.path.join(os.path.dirname(as_file), target_file)) | Return an absolute path to a target file that is located in the same directory as as_file
Args:
as_file: File name (including __file__)
Use the directory path of this file
target_file: Name of the target file | codesearchnet |
def add_report(self, specification_name, report):
self._reports[specification_name] = report
self._total = (self._total + report.testsRun)
self._failures = (self._failures + len(report.failures))
self._errors = (self._errors + len(report.errors))
self._success = ((self._total - self._failures) - sel... | Adds a given report with the given specification_name as key
to the reports list and computes the number of success, failures
and errors
Args:
specification_name: string representing the specification (with ".spec")
report: The | codesearchnet |
def VerifyStructure(self, parser_mediator, line):
try:
structure = self._HEADER.parseString(line)
except pyparsing.ParseException:
logger.debug('Not a XChat log file')
return False
_, month, day, hours, minutes, seconds, year = structure.date_time
month = timelib.MONTH_DICT.get(... | Verify that this file is a XChat log file.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
line (str): line from a text file.
Returns:
bool: True if the line is in the expected format, False if not. | juraj-google-style |
def scatter_max(self, sparse_delta, use_locking=False, name=None):
raise NotImplementedError | Updates this variable with the max of `tf.IndexedSlices` and itself.
Args:
sparse_delta: `tf.IndexedSlices` to use as an argument of max with this
variable.
use_locking: If `True`, use locking during the operation.
name: the name of the operation.
Returns:
The updated variable.
Raises:
TypeError: if `sparse_delta` i... | github-repos |
def update_restore_inputs(self, checkpoint_key, shape_and_slice_spec) -> tuple[List[str], List[str]]:
return ([checkpoint_key], [shape_and_slice_spec]) | Updates the specs to restore op.
Override this method if the arguments to restore op need to be updated as
per the resharding required.
Args:
checkpoint_key: The checkpoint key as requested by the caller
shape_and_slice_spec: The shape and slice spec as requested by caller
Returns:
Tuple of list of checkpoint_keys an... | github-repos |
def gzip_uncompress(data, truncated=False):
decompressor = SimpleGzipDecompressor()
inflated_data = decompressor.decompress(data)
if (not truncated):
inflated_data += decompressor.flush()
return inflated_data | Uncompress gzip data.
Args:
data (bytes): The gzip data.
truncated (bool): If True, the decompressor is not flushed.
This is a convenience function.
Returns:
bytes: The inflated data.
Raises:
zlib.error | codesearchnet |
def get_slot_names(self):
return sorted(self._slots.keys()) | Return a list of the names of slots created by the `Optimizer`.
See `get_slot()`.
Returns:
A list of strings. | github-repos |
def __init__(self, build_tree=True):
self._target_cache = {}
self._item_cache = {}
self._contains_cache = {}
self._matrix_cache = {}
self._graph_cache = {}
self._treemap_cache = None
self.modules = []
self.packages = []
if build_tree:
... | Initialization method.
Args:
build_tree (bool): whether to immediately build the tree or not. | juraj-google-style |
def _update_seek(self, offset, whence):
with self._seek_lock:
if (whence == SEEK_SET):
self._seek = offset
elif (whence == SEEK_CUR):
self._seek += offset
elif (whence == SEEK_END):
self._seek = (offset + self._size)
else:
raise ValueEr... | Update seek value.
Args:
offset (int): Offset.
whence (int): Whence.
Returns:
int: Seek position. | codesearchnet |
def get_image_data(self, ids=None, voxels=None, dense=True):
if (dense and (ids is None) and (voxels is None)):
logger.warning('Warning: get_image_data() is being called without specifying a subset of studies or voxels to retrieve. This may result in a very large amount of data (several GB) being read into ... | Slices and returns a subset of image data.
Args:
ids (list, array): A list or 1D numpy array of study ids to
return. If None, returns data for all studies.
voxels (list, array): A list or 1D numpy array of voxel indices
(i.e., rows) to return. If None, returns data for all voxels.
dense (bool): Optional boolean. When ... | codesearchnet |
def plot_scatter_matrix(self, freq=None, title=None, figsize=(10, 10), **kwargs):
if (title is None):
title = self._get_default_plot_title(freq, 'Return Scatter Matrix')
plt.figure()
ser = self._get_series(freq).to_returns().dropna()
pd.scatter_matrix(ser, figsize=figsize, **kwargs)
return p... | Wrapper around pandas' scatter_matrix.
Args:
* freq (str): Data frequency used for display purposes.
Refer to pandas docs for valid freq strings.
* figsize ((x,y)): figure size
* title (str): Title if default not appropriate
* kwargs: passed to pandas' scatter_matrix method | codesearchnet |
def setup(pin, mode, pullup=None, initial=False):
if pullup is not None:
raise ValueError("sysfs does not support pullups")
if mode not in (IN, OUT, LOW, HIGH):
raise ValueError(mode)
log.debug("Setup {0}: {1}".format(pin, mode))
f = _open[pin].direction
_write(f, mode)
if... | Setup pin with mode IN or OUT.
Args:
pin (int):
mode (str): use either gpio.OUT or gpio.IN
pullup (None): rpio compatibility. If anything but None, raises
value Error
pullup (bool, optional): Initial pin value. Default is False | juraj-google-style |
def _ParseComment(self, structure):
if (structure[1] == 'Date:'):
(self._year, self._month, self._day_of_month, _, _, _) = structure.date_time
elif (structure[1] == 'Fields:'):
self._ParseFieldsMetadata(structure) | Parses a comment.
Args:
structure (pyparsing.ParseResults): structure parsed from the log file. | codesearchnet |
def merge_lines(top, bot, icod="top"):
ret = ""
for topc, botc in zip(top, bot):
if topc == botc:
ret += topc
elif topc in '┼╪' and botc == " ":
ret += "│"
elif topc == " ":
ret += botc
elif topc in ... | Merges two lines (top and bot) in the way that the overlapping make senses.
Args:
top (str): the top line
bot (str): the bottom line
icod (top or bot): in case of doubt, which line should have priority? Default: "top".
Returns:
str: The merge of both lines. | juraj-google-style |
def get_room_id(self, room_alias):
content = self._send("GET", "/directory/room/{}".format(quote(room_alias)))
return content.get("room_id", None) | Get room id from its alias.
Args:
room_alias (str): The room alias name.
Returns:
Wanted room's id. | juraj-google-style |
def list(self):
request = requests.Request('GET', 'https:
pattern = re.compile('<([^>]*)>; rel="([^"]*)"')
gists = []
while True:
try:
response = self.send(request).json()
except Exception:
break
for gist in response:
try:
gists... | Returns a list of the users gists as GistInfo objects
Returns:
a list of GistInfo objects | codesearchnet |
def _ParseUpdateKeyValue(self, parser_mediator, registry_value, key_path):
if (not registry_value.DataIsString()):
parser_mediator.ProduceExtractionWarning('unsupported UpdateKey value data type: {0:s}'.format(registry_value.data_type_string))
return
date_time_string = registry_value.GetDataAsOb... | Parses the UpdateKey value.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_value (dfwinreg.WinRegistryValue): Windows Registry value.
key_path (str): Windows Registry key path. | codesearchnet |
def check_docstrings(overwrite: bool=False, check_all: bool=False):
module_diff_files = None
if not check_all:
module_diff_files = set()
repo = Repo(PATH_TO_REPO)
for modified_file_diff in repo.index.diff(None):
if modified_file_diff.a_path.startswith('src/transformers'):
... | Check docstrings of all public objects that are callables and are documented. By default, only checks the diff.
Args:
overwrite (`bool`, *optional*, defaults to `False`):
Whether to fix inconsistencies or not.
check_all (`bool`, *optional*, defaults to `False`):
Whether to check all files. | github-repos |
def update_table(self, table, fields, retry=DEFAULT_RETRY):
partial = table._build_resource(fields)
if (table.etag is not None):
headers = {'If-Match': table.etag}
else:
headers = None
api_response = self._call_api(retry, method='PATCH', path=table.path, data=partial, headers=headers)
... | Change some fields of a table.
Use ``fields`` to specify which fields to update. At least one field
must be provided. If a field is listed in ``fields`` and is ``None``
in ``table``, it will be deleted.
If ``table.etag`` is not ``None``, the update will only succeed if
the table on the server has the same ETag. Thus ... | codesearchnet |
def cache_penalty_model(penalty_model, database=None):
if (not _is_index_labelled(penalty_model.graph)):
(mapping, __) = _graph_canonicalization(penalty_model.graph)
penalty_model = penalty_model.relabel_variables(mapping, inplace=False)
if (database is None):
conn = cache_connect()
... | Caching function for penaltymodel_cache.
Args:
penalty_model (:class:`penaltymodel.PenaltyModel`): Penalty model to
be cached.
database (str, optional): The path to the desired sqlite database
file. If None, will use the default. | codesearchnet |
def do_load(self, design, init=False):
if design:
filename = self._validated_config_filename(design)
with open(filename, 'r') as f:
text = f.read()
structure = json_decode(text)
else:
structure = {}
attributes = structure.get('attributes', structure)
children ... | Load a design name, running the child LoadHooks.
Args:
design: Name of the design json file, without extension
init: Passed to the LoadHook to tell the children if this is being
run at Init or not | codesearchnet |
def _imputeMissing(X, center=True, unit=True, betaNotUnitVariance=False, betaA=1.0, betaB=1.0):
typeX = X.dtype
if (typeX != SP.int8):
iNanX = (X != X)
else:
iNanX = (X == (- 9))
if (iNanX.any() or betaNotUnitVariance):
if cparser:
print('using C-based imputer')
... | fill in missing values in the SNP matrix by the mean value
optionally center the data and unit-variance it
Args:
X: scipy.array of SNP values. If dtype=='int8' the missing values are -9,
otherwise the missing values are scipy.nan
center: Boolean indicator if data should be mean centered
Not supported in C-based p... | codesearchnet |
def dot_distance(t1, t2, name=None):
with tf.name_scope(name, 'dot_distance', [t1, t2]) as scope:
return (- dot_product(t1, t2, name=scope)) | dot "distance" between t1 and t2.
Args:
t1: A tensor.
t2: A tensor that is the same size as t1.
name: Optional name for this op.
Returns:
The dot distance between t1 and t2. | codesearchnet |
def _get_base_converter_args(self):
args = {'input_format': constants.TENSORFLOW_GRAPHDEF, 'allow_custom_ops': self.allow_custom_ops, 'debug_info': self._debug_info, 'target_ops': self.target_spec.supported_ops, 'select_user_tf_ops': self.target_spec.experimental_select_user_tf_ops, 'supported_backends': self.targe... | Returns the base converter args.
Returns:
{key str: val} | github-repos |
def NewRow(self, value=""):
newrow = self.row_class()
newrow.row = self.size + 1
newrow.table = self
headers = self._Header()
for header in headers:
newrow[header] = value
return newrow | Fetches a new, empty row, with headers populated.
Args:
value: Initial value to set each row entry to.
Returns:
A Row() object. | juraj-google-style |
def fit3d(samples, e_x, e_y, e_z, remove_zeros=False, **kw):
(height, width, depth) = ((len(e_y) - 1), (len(e_x) - 1), (len(e_z) - 1))
(p_est, _) = np.histogramdd(samples, (e_x, e_y, e_z))
p_est = (p_est / sum(p_est.flat))
p_est = p_est.flatten()
if remove_zeros:
non_zero = (~ (p_est == 0))
... | Fits a 3D distribution with splines.
Input:
samples: Array
Array of samples from a probability distribution
e_x: Array
Edges that define the events in the probability
distribution along the x direction. For example,
e_x[0] < samples[0] <= e_x[1] picks out all
samples that are associated with the first event.
e_y: Arra... | codesearchnet |
def construct_error_message(driver_id, error_type, message, timestamp):
builder = flatbuffers.Builder(0)
driver_offset = builder.CreateString(driver_id.binary())
error_type_offset = builder.CreateString(error_type)
message_offset = builder.CreateString(message)
ray.core.generated.ErrorTableDat... | Construct a serialized ErrorTableData object.
Args:
driver_id: The ID of the driver that the error should go to. If this is
nil, then the error will go to all drivers.
error_type: The type of the error.
message: The error message.
timestamp: The time of the error.
Returns:
The serialized object. | juraj-google-style |
def from_year_month_day(year, month, day, validate=True):
year = tf.convert_to_tensor(year, tf.int32)
month = tf.convert_to_tensor(month, tf.int32)
day = tf.convert_to_tensor(day, tf.int32)
control_deps = []
if validate:
control_deps.append(tf.debugging.assert_positive(year, message='Year mu... | Creates DateTensor from tensors of years, months and days.
Args:
year: Tensor of int32 type. Elements should be positive.
month: Tensor of int32 type of same shape as `year`. Elements should be in
range `[1, 12]`.
day: Tensor of int32 type of same shape as `year`. Elements should be in
range `[1, 31]` and represent va... | github-repos |
def write_to_text(pcoll, path: str):
try:
field_names = [name for name, _ in schemas.named_fields_from_element_type(pcoll.element_type)]
except Exception as exn:
raise ValueError('WriteToText requires an input schema with exactly one field.') from exn
if len(field_names) != 1:
raise ... | Writes a PCollection to a (set of) text files(s).
The input must be a PCollection whose schema has exactly one field.
Args:
path (str): The file path to write to. The files written will
begin with this prefix, followed by a shard identifier. | github-repos |
def json(cls, message):
if type(message) is OrderedDict:
pprint(dict(message))
else:
pprint(message) | Print a nice JSON output
Args:
message: the message to print | juraj-google-style |
def SetCTypesForLibrary(libname, fn_table):
libpath = ctypes.util.find_library(libname)
if (not libpath):
raise ErrorLibNotFound(('Library %s not found' % libname))
lib = ctypes.cdll.LoadLibrary(libpath)
for (function, args, result) in fn_table:
f = getattr(lib, function)
f.argty... | Set function argument types and return types for an ObjC library.
Args:
libname: Library name string
fn_table: List of (function, [arg types], return types) tuples
Returns:
ctypes.CDLL with types set according to fn_table
Raises:
ErrorLibNotFound: Can't find specified lib | codesearchnet |
def from_dictionary(cls, options):
flags = []
for k, v in options.items():
if isinstance(v, bool):
if v:
flags.append('--%s' % k)
elif k in _FLAG_THAT_SETS_FALSE_VALUE:
flag_that_disables_the_option = _FLAG_THAT_SETS_FALSE_VALUE[k]
... | Returns a PipelineOptions from a dictionary of arguments.
Args:
options: Dictionary of argument value pairs.
Returns:
A PipelineOptions object representing the given arguments. | github-repos |
def abspath(self, path):
if ((not path.startswith(os.path.sep)) or path.startswith('~')):
path = os.path.expanduser(os.path.join(self.base_path, path))
return path | Transform the path to an absolute path
Args:
path (string): The path to transform to an absolute path
Returns:
string: The absolute path to the file | codesearchnet |
def DeregisterHelper(cls, resolver_helper):
if resolver_helper.type_indicator not in cls._resolver_helpers:
raise KeyError(
'Resolver helper object not set for type indicator: {0:s}.'.format(
resolver_helper.type_indicator))
del cls._resolver_helpers[resolver_helper.type_indi... | Deregisters a path specification resolver helper.
Args:
resolver_helper (ResolverHelper): resolver helper.
Raises:
KeyError: if resolver helper object is not set for the corresponding
type indicator. | juraj-google-style |
def _restore_slice(file_pattern, tensor_name, shape_and_slice, tensor_type, name='restore_slice', preferred_shard=-1):
base_type = dtypes.as_dtype(tensor_type).base_dtype
return gen_io_ops.restore_slice(file_pattern, tensor_name, shape_and_slice, base_type, preferred_shard, name=name) | Restore a tensor slice from a set of files with a given pattern.
Example usage:
RestoreSlice("/foo/bar-?????-of-?????", "w", "10 10 0,2:-", DT_FLOAT)
Args:
file_pattern: the file pattern used to match a set of checkpoint files.
tensor_name: the name of the tensor to restore.
shape_and_slice: the shape-and-slice spec ... | github-repos |
def process(self, element):
import collections
import apache_beam as beam
num_in_batch = 0
try:
assert self._session is not None
feed_dict = collections.defaultdict(list)
for line in element:
if line.endswith('\n'):
line = line[:-1]
feed_dict... | Run batch prediciton on a TF graph.
Args:
element: list of strings, representing one batch input to the TF graph. | juraj-google-style |
def num_lineages_at(self, distance):
if not isinstance(distance, float) and not isinstance(distance, int):
raise TypeError("distance must be an int or a float")
if distance < 0:
raise RuntimeError("distance cannot be negative")
d = dict(); q = deque(); q.append(s... | Returns the number of lineages of this ``Tree`` that exist ``distance`` away from the root
Args:
``distance`` (``float``): The distance away from the root
Returns:
``int``: The number of lineages that exist ``distance`` away from the root | juraj-google-style |
def cellsiter_to_dataframe(cellsiter, args, drop_allna=True):
from modelx.core.cells import shareable_parameters
if len(args):
indexes = shareable_parameters(cellsiter)
else:
indexes = get_all_params(cellsiter.values())
result = None
for cells in cellsiter.values():
d... | Convert multiple cells to a frame.
If args is an empty sequence, all values are included.
If args is specified, cellsiter must have shareable parameters.
Args:
cellsiter: A mapping from cells names to CellsImpl objects.
args: A sequence of arguments | juraj-google-style |
def __init__(self, range_str='', make_token=AlphanumericVersionToken,
invalid_bound_error=True):
self._str = None
self.bounds = []
if range_str is None:
return
try:
parser = _VersionRangeParser(range_str, make_token,
... | Create a VersionRange object.
Args:
range_str: Range string, such as "3", "3+<4.5", "2|6+". The range
will be optimised, so the string representation of this instance
may not match range_str. For example, "3+<6|4+<8" == "3+<8".
make_token: Version token class to use.
invalid_bound_error (bool): If True, raise an excep... | juraj-google-style |
def DeserializeExclusiveData(self, reader):
if self.Version > 1:
logger.error("format exception...")
self.Code = FunctionCode()
self.Code.Deserialize(reader)
if self.Version >= 1:
self.NeedStorage = reader.ReadBool()
else:
self.NeedS... | Deserialize full object.
Args:
reader (neo.IO.BinaryReader): | juraj-google-style |
def is_unitary(matrix: np.ndarray, *, rtol: float=1e-05, atol: float=1e-08) -> bool:
return ((matrix.shape[0] == matrix.shape[1]) and np.allclose(matrix.dot(np.conj(matrix.T)), np.eye(matrix.shape[0]), rtol=rtol, atol=atol)) | Determines if a matrix is approximately unitary.
A matrix is unitary if it's square and its adjoint is its inverse.
Args:
matrix: The matrix to check.
rtol: The per-matrix-entry relative tolerance on equality.
atol: The per-matrix-entry absolute tolerance on equality.
Returns:
Whether the matrix is unitary within th... | codesearchnet |
def _batch_prepare_for_model(self, batch_ids_pairs: list[Union[PreTokenizedInputPair, tuple[list[int], None]]], add_special_tokens: bool=True, padding_strategy: PaddingStrategy=PaddingStrategy.DO_NOT_PAD, truncation_strategy: TruncationStrategy=TruncationStrategy.DO_NOT_TRUNCATE, max_length: Optional[int]=None, stride:... | Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by the model. It
adds special tokens, truncates sequences if overflowing while taking into account the special tokens and
manages a moving window (with user defined stride) for overflowing tokens
Args:
batch_ids_pairs: list of... | github-repos |
def stop(self, block=True):
self._stop = True
self.empty_queue()
for _ in range(self.threads_active()):
self._queue.put(SetPrio(target=DoNothing))
if block:
self.join()
... | Stops all active threads and rejects new tasks to be added
Args:
block (bool): If True, block until all threads are closed | juraj-google-style |
def notify(self, method, params=None):
log.debug('Sending notification: %s %s', method, params)
message = {'jsonrpc': JSONRPC_VERSION, 'method': method}
if (params is not None):
message['params'] = params
self._consumer(message) | Send a JSON RPC notification to the client.
Args:
method (str): The method name of the notification to send
params (any): The payload of the notification | codesearchnet |
def _process_req_body(self, body):
try:
return json.loads(body)
except ValueError:
return urlparse.parse_qs(body, keep_blank_values=True) | Process the body of the HTTP request.
If the body is valid JSON, return the JSON as a dict.
Else, convert the key=value format to a dict and return that.
Args:
body: The body of the HTTP request. | juraj-google-style |
def process_document_events(events, use_buffers=True):
json_events = []
references = set()
buffers = ([] if use_buffers else None)
for event in events:
json_events.append(event.generate(references, buffers))
json = {'events': json_events, 'references': references_json(references)}
return... | Create a JSON string describing a patch to be applied as well as
any optional buffers.
Args:
events : list of events to be translated into patches
Returns:
str, list :
JSON string which can be applied to make the given updates to obj
as well as any optional buffers | codesearchnet |
def update(self, iterable):
for pair in pairwise_longest(iterable, fillvalue=_FILL):
self._edges.append(pair)
self._results = None | Update with an ordered iterable of items.
Args:
iterable: An ordered iterable of items. The relative
order of the items in this iterable will be respected
in the TopoSet (in the absence of cycles). | codesearchnet |
def __init__(self,
max_entity_count=MAX_ENTITY_COUNT,
mapreduce_spec=None):
self.max_entity_count = max_entity_count
params = mapreduce_spec.params if mapreduce_spec is not None else {}
self.force_writes = bool(params.get("force_ops_writes", False))
self.puts = _ItemLi... | Constructor.
Args:
max_entity_count: maximum number of entities before flushing it to db.
mapreduce_spec: An optional instance of MapperSpec. | juraj-google-style |
def delete_project(self, project):
if not is_valid_uuid(project):
raise StorageArgumentException(
'Invalid UUID for project: {0}'.format(project))
self._authenticated_request \
.to_endpoint('project/{}/'.format(project)) \
.delete() | Delete a project. It will recursively delete all the content.
Args:
project (str): The UUID of the project to be deleted.
Returns:
None
Raises:
StorageArgumentException: Invalid arguments
StorageForbiddenException: 403
StorageNotFoundException: 404
HTTPError: other non-20x error codes | juraj-google-style |
def buckets_delete(self, bucket):
url = (Api._ENDPOINT + (Api._BUCKET_PATH % bucket))
google.datalab.utils.Http.request(url, method='DELETE', credentials=self._credentials, raw_response=True) | Issues a request to delete a bucket.
Args:
bucket: the name of the bucket.
Raises:
Exception if there is an error performing the operation. | codesearchnet |
def _bisect(self, begin, end, listener):
step = (end.date - begin.date) / 2
while abs(step) >= self._eps_bisect:
date = begin.date + step
if self.SPEAKER_MODE == "global":
orb = self.propagate(date)
else:
orb = begin.propagat... | This method search for the zero-crossing of the watched parameter
Args:
begin (Orbit):
end (Orbit)
listener (Listener)
Return
Return | juraj-google-style |
def index(self, ref, columns):
from ambry.orm.exc import NotFoundError
logger.debug('Creating index for partition.\n ref: {}, columns: {}'.format(ref, columns))
connection = self._backend._get_connection()
try:
table_or_partition = self._library.partition(ref)
... | Create an index on the columns.
Args:
ref (str): id, vid, name or versioned name of the partition.
columns (list of str): names of the columns needed indexes. | juraj-google-style |
def update(self, item):
if item.matrix not in self.data:
self.data[item.matrix] = []
result = Select(self.data[item.matrix]).where(
lambda entry: entry.stage == item.stage).build()
if len(result) > 0:
stage = result[0]
stage.status = ite... | Add a collector item.
Args:
item (CollectorUpdate): event data like stage, timestampe and status. | juraj-google-style |
def __init__(self, key_dtype, value_dtype):
self._key_dtype = key_dtype
self._value_dtype = value_dtype | Construct a table initializer object.
Args:
key_dtype: Type of the table keys.
value_dtype: Type of the table values. | github-repos |
def set(self, key, val):
self._create_file_if_none_exists()
with open(self.filename, 'r+b') as file_object:
cache_pickle = pickle.load(file_object)
cache_pickle[key] = val
file_object.seek(0)
pickle.dump(cache_pickle, file_object) | Sets a value in a key.
Args:
key (str): Key for the value.
val: Value to set.
Returns:
Retrieved value. | juraj-google-style |
def _FindStmtParent(node):
if pytree_utils.NodeName(node) in _STATEMENT_NODES:
return node
else:
return _FindStmtParent(node.parent) | Find the nearest parent of node that is a statement node.
Arguments:
node: node to start from
Returns:
Nearest parent (or node itself, if suitable). | github-repos |
def add_mutex_switch(parser, dest, arguments=set(), default=None,
single_arg=False, required=False):
if default is not None:
assert default in arguments
if isinstance(arguments, set):
arguments = {k: None for k in arguments}
if not sin... | Adds mutually exclusive switch arguments.
Args:
arguments: a dictionary that maps switch name to helper text. Use
sets to skip help texts. | juraj-google-style |
def save_def_args_in_temp(self, call_args, def_args, line_number, saved_function_call_index, first_node):
args_mapping = dict()
last_return_value_of_nested_call = None
for (i, call_arg) in enumerate(call_args):
def_arg_temp_name = ((('temp_' + str(saved_function_call_index)) + '_') + def_args[i])
... | Save the arguments of the definition being called. Visit the arguments if they're calls.
Args:
call_args(list[ast.Name]): Of the call being made.
def_args(ast_helper.Arguments): Of the definition being called.
line_number(int): Of the call being made.
saved_function_call_index(int): Unique number for each call.
first_... | codesearchnet |
def add_batch_parser(subparsers, parent_parser):
parser = subparsers.add_parser('batch', help='Displays information about batches and submit new batches', description='Provides subcommands to display Batch information and submit Batches to the validator via the REST API.')
grand_parsers = parser.add_subparsers(... | Adds arguments parsers for the batch list, batch show and batch status
commands
Args:
subparsers: Add parsers to this subparser object
parent_parser: The parent argparse.ArgumentParser object | codesearchnet |
def applicable_decision_points(self, dna_spec: pg.geno.DNASpec, global_state: pg.geno.AttributeDict, step: int) -> List[pg.geno.DecisionPoint]:
applicable_points = []
for dp in dna_spec.decision_points:
if isinstance(dp, pg.geno.Choices) and dp.is_subchoice:
if dp.subchoice_index == 0:
... | Returns applicable decision points for this recombinator.
The default behavior is to return all decision points in the search space,
with multi-choice subchoices folded into a single decision point. Subclasses
can override this method to select applicable points according to their
semantics.
Args:
dna_spec: The root ... | github-repos |
def calculate_focus(self, reading):
middle_index = (len(self.source.get_readings())
middle_reading = self.source.get_reading(middle_index)
return self.convert_source_location(middle_reading, reading) | Determines what the focal point of the downloaded image should be.
Returns:
focal_point: (x, y)
The location of the source in the middle observation, in the
coordinate system of the current source reading. | codesearchnet |
def ZerosLikeForExit(self, val):
val_shape = val.get_shape()
forward_ctxt = val.op._get_control_flow_context()
outer_forward_ctxt = forward_ctxt.outer_context
if outer_forward_ctxt:
outer_forward_ctxt = outer_forward_ctxt.GetWhileContext()
outer_grad_state = None
if outer_forward_ctxt:
... | Create zeros_like gradient for a loop exit.
If the result of a loop variable is not used but is involved in
computing the result of some needed loop variable, we create a
zero-valued tensor that is fed as gradient for the Exit node of that
loop variable. Note that val.op is an Exit, and this method must be
called in t... | github-repos |
def stop(self, accountID, **kwargs):
return self.create(
accountID,
order=StopOrderRequest(**kwargs)
) | Shortcut to create a Stop Order in an Account
Args:
accountID : The ID of the Account
kwargs : The arguments to create a StopOrderRequest
Returns:
v20.response.Response containing the results from submitting
the request | juraj-google-style |
def _piecewise_learning_rate(step, boundaries, values):
values = ([1.0] + values)
boundaries = [float(x) for x in boundaries]
return tf.train.piecewise_constant(step, boundaries, values, name='piecewise_lr') | Scale learning rate according to the given schedule.
Multipliers are not cumulative.
Args:
step: global step
boundaries: List of steps to transition on.
values: Multiplier to apply at each boundary transition.
Returns:
Scaled value for the learning rate. | codesearchnet |
def get_json_type(obj):
if hasattr(obj, 'get_config'):
return {'class_name': obj.__class__.__name__, 'config': obj.get_config()}
if type(obj).__module__ == np.__name__:
if isinstance(obj, np.ndarray):
return obj.tolist()
else:
return obj.item()
if callable(obj... | Serializes any object to a JSON-serializable structure.
Args:
obj: the object to serialize
Returns:
JSON-serializable structure representing `obj`.
Raises:
TypeError: if `obj` cannot be serialized. | github-repos |
def db_get(table, record, column, if_exists=False):
cmd = ['ovs-vsctl', '--format=json', '--columns={0}'.format(column)]
if if_exists:
cmd += ['--if-exists']
cmd += ['list', table, record]
result = __salt__['cmd.run_all'](cmd)
if result['retcode'] != 0:
raise CommandExecutionErr... | Gets a column's value for a specific record.
Args:
table: A string - name of the database table.
record: A string - identifier of the record.
column: A string - name of the column.
if_exists: A boolean - if True, it is not an error if the record does
not exist.
Returns:
The column's value.
CLI Example:
.. code-block... | juraj-google-style |
def _process_scalar_value(name, parse_fn, var_type, m_dict, values, results_dictionary):
try:
parsed_value = parse_fn(m_dict['val'])
except ValueError:
_parse_fail(name, var_type, m_dict['val'], values)
if (not m_dict['index']):
if (name in results_dictionary):
_reuse_fai... | Update results_dictionary with a scalar value.
Used to update the results_dictionary to be returned by parse_values when
encountering a clause with a scalar RHS (e.g. "s=5" or "arr[0]=5".)
Mutates results_dictionary.
Args:
name: Name of variable in assignment ("s" or "arr").
parse_fn: Function for parsing the actua... | codesearchnet |
def _item_to_document_ref(iterator, item):
document_id = item.name.split(_helpers.DOCUMENT_PATH_DELIMITER)[-1]
return iterator.collection.document(document_id) | Convert Document resource to document ref.
Args:
iterator (google.api_core.page_iterator.GRPCIterator):
iterator response
item (dict): document resource | juraj-google-style |
def get_cuda_visible_devices():
gpu_ids_str = os.environ.get('CUDA_VISIBLE_DEVICES', None)
if (gpu_ids_str is None):
return None
if (gpu_ids_str == ''):
return []
return [int(i) for i in gpu_ids_str.split(',')] | Get the device IDs in the CUDA_VISIBLE_DEVICES environment variable.
Returns:
if CUDA_VISIBLE_DEVICES is set, this returns a list of integers with
the IDs of the GPUs. If it is not set, this returns None. | codesearchnet |
def __call__(self, w):
return w | Applies the constraint to the input weight variable.
By default, the inputs weight variable is not modified.
Users should override this method to implement their own projection
function.
Args:
w: Input weight variable.
Returns:
Projected variable (by default, returns unmodified inputs). | github-repos |
def market_exact(self, session, start_time: str, end_time: str) -> Session:
if (session not in self.exch):
return SessNA
ss = self.exch[session]
same_day = (ss[0] < ss[(- 1)])
if (not start_time):
s_time = ss[0]
else:
s_time = param.to_hour(start_time)
if same_day:
... | Explicitly specify start time and end time
Args:
session: predefined session
start_time: start time in terms of HHMM string
end_time: end time in terms of HHMM string
Returns:
Session of start_time and end_time | codesearchnet |
def acc_difference(points):
data = [0]
for before, after in pairwise(points):
data.append(before.acc - after.acc)
return data | Computes the accelaration difference between each adjacent point
Args:
points (:obj:`Point`)
Returns:
:obj:`list` of int: Indexes of changepoints | juraj-google-style |
def list_street_poi_parking(self, **kwargs):
url_args = {'language': util.language_code(kwargs.get('lang')), 'address': kwargs.get('address', '')}
result = self.make_request('list_street_poi_parking', url_args)
if (not util.check_result(result)):
return (False, result.get('message', 'UNKNOWN ERROR')... | Obtain a list of addresses and POIs.
This endpoint uses an address to perform the search
Args:
lang (str): Language code (*es* or *en*).
address (str): Address in which to perform the search.
Returns:
Status boolean and parsed response (list[ParkingPoi]), or message
string in case of error. | codesearchnet |
def extract_value_from_output(canary, split_offset, kal_out):
retval = ''
while (retval == ''):
for line in kal_out.splitlines():
if (canary in line):
retval = str(line.split()[split_offset])
if (retval == ''):
retval = None
return retval | Return value parsed from output.
Args:
canary(str): This string must exist in the target line.
split_offset(int): Split offset for target value in string.
kal_out(int): Output from kal. | codesearchnet |
def transform(self, transform, desc=None):
if desc is None:
desc = u'transform({})'.format(getattr(transform, '__name__', ''))
return self.replace(
transforms=self.transforms + [transform],
desc_stack=self.desc_stack + [desc]
) | Create a copy of this query, transformed by `transform`.
Args:
transform (callable): Callable that takes an iterable of values and
returns an iterable of transformed values.
Keyword Args:
desc (str): A description of the transform, to use in log messages.
Defaults to the name of the `transform` function.
Returns:
Qu... | juraj-google-style |
def on_each(self, *targets: raw_types.Qid) -> op_tree.OP_TREE:
return [self.on(target) for target in targets] | Returns a list of operations apply this gate to each of the targets.
Args:
*targets: The qubits to apply this gate to.
Returns:
Operations applying this gate to the target qubits.
Raises:
ValueError if targets are not instances of Qid. | codesearchnet |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.