code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def logdet(x):
if any_symbolic_tensors((x,)):
return Logdet().symbolic_call(x)
return backend.math.logdet(x) | Computes log of the determinant of a hermitian positive definite matrix.
Args:
x: Input matrix. It must 2D and square.
Returns:
The natural log of the determinant of matrix. | github-repos |
def _locate_elements_in_line(line, indices_list, ref_indices):
batch_size = len(indices_list)
offsets = [indices[-1] - ref_indices[-1] for indices in indices_list]
start_columns = [None] * batch_size
end_columns = [None] * batch_size
if _NUMPY_OMISSION in line:
ellipsis_index = line.find(_NU... | Determine the start and end indices of an element in a line.
Args:
line: (str) the line in which the element is to be sought.
indices_list: (list of list of int) list of indices of the element to
search for. Assumes that the indices in the batch are unique and sorted
in ascending order.
ref_indices: (list of int) refe... | github-repos |
def match_hail_size_step_distributions(self, model_tracks, obs_tracks, track_pairings):
label_columns = ["Matched", "Max_Hail_Size", "Num_Matches", "Shape", "Location", "Scale"]
s = 0
for m, model_track in enumerate(model_tracks):
model_track.observations = pd.DataFrame(inde... | Given a matching set of observed tracks for each model track,
Args:
model_tracks:
obs_tracks:
track_pairings:
Returns: | juraj-google-style |
def transpose(self):
graph = self.graph
transposed = DAG()
for (node, edges) in graph.items():
transposed.add_node(node)
for (node, edges) in graph.items():
for edge in edges:
transposed.add_edge(edge, node)
return transposed | Builds a new graph with the edges reversed.
Returns:
:class:`stacker.dag.DAG`: The transposed graph. | codesearchnet |
def get_memberships(self):
response = self._get_xml((self.rest_url + '/group/membership'))
if (not response.ok):
return None
xmltree = etree.fromstring(response.content)
memberships = {}
for mg in xmltree.findall('membership'):
group = u'{}'.format(mg.get('group'))
users = [u... | Fetches all group memberships.
Returns:
dict:
key: group name
value: (array of users, array of groups) | codesearchnet |
def distance_and_image_from_frac_coords(self, fcoords, jimage=None):
return self.lattice.get_distance_and_image(self.frac_coords, fcoords, jimage=jimage) | Gets distance between site and a fractional coordinate assuming
periodic boundary conditions. If the index jimage of two sites atom j
is not specified it selects the j image nearest to the i atom and
returns the distance and jimage indices in terms of lattice vector
translations. If the index jimage of atom j is specif... | codesearchnet |
def push(self, targets, jobs=None, remote=None, show_checksums=False):
return self.repo.cache.local.push(
targets,
jobs=jobs,
remote=self._get_cloud(remote, "push"),
show_checksums=show_checksums,
) | Push data items in a cloud-agnostic way.
Args:
targets (list): list of targets to push to the cloud.
jobs (int): number of jobs that can be running simultaneously.
remote (dvc.remote.base.RemoteBase): optional remote to push to.
By default remote from core.remote config option is used.
show_checksums (bool): show chec... | juraj-google-style |
def regression_signature_def(examples, predictions):
if examples is None:
raise ValueError('Regression `examples` cannot be None.')
if not isinstance(examples, tensor_lib.Tensor):
raise ValueError(f'Expected regression `examples` to be of type Tensor. Found `examples` of type {type(examples)}.')... | Creates regression signature from given examples and predictions.
This function produces signatures intended for use with the TensorFlow Serving
Regress API (tensorflow_serving/apis/prediction_service.proto), and so
constrains the input and output types to those allowed by TensorFlow Serving.
Args:
examples: A string... | github-repos |
def compute_one_decoding_video_metrics(iterator, feed_dict, num_videos):
output, target = iterator.get_next()
metrics = psnr_and_ssim(output, target)
with tf.Session() as sess:
sess.run(tf.local_variables_initializer())
initalizer = iterator._initializer
if initalizer is not None:
sess.run... | Computes the average of all the metric for one decoding.
Args:
iterator: dataset iterator.
feed_dict: feed dict to initialize iterator.
num_videos: number of videos.
Returns:
all_psnr: 2-D Numpy array, shape=(num_samples, num_frames)
all_ssim: 2-D Numpy array, shape=(num_samples, num_frames) | juraj-google-style |
def compute_mel_filterbank_features(waveforms, sample_rate=16000, dither=(1.0 / np.iinfo(np.int16).max), preemphasis=0.97, frame_length=25, frame_step=10, fft_length=None, window_fn=functools.partial(tf.contrib.signal.hann_window, periodic=True), lower_edge_hertz=80.0, upper_edge_hertz=7600.0, num_mel_bins=80, log_nois... | Implement mel-filterbank extraction using tf ops.
Args:
waveforms: float32 tensor with shape [batch_size, max_len]
sample_rate: sampling rate of the waveform
dither: stddev of Gaussian noise added to waveform to prevent quantization
artefacts
preemphasis: waveform high-pass filtering constant
frame_length: frame lengt... | codesearchnet |
def get_loss_reduction():
if not distribute_lib.get_strategy()._scale_loss_for_estimator:
return ReduceOp.SUM
last_reduction = ops.get_default_graph()._last_loss_reduction
if last_reduction == losses_impl.Reduction.SUM or last_reduction == 'sum':
return ReduceOp.SUM
return ReduceOp.MEAN | `tf.distribute.ReduceOp` corresponding to the last loss reduction.
Returns:
`tf.distribute.ReduceOp` corresponding to the last loss reduction for
estimator and v1 optimizer use case. `tf.distribute.ReduceOp.SUM` otherwise. | github-repos |
def call(command, collect_missing=False, silent=True):
return (_execCommand if silent else execCommand)(shlex.split(command), collect_missing) | r"""Calls a task, as if it were called from the command line.
Args:
command (str): A route followed by params (as if it were entered in the shell).
collect_missing (bool): Collects any missing argument for the command through the shell. Defaults to False.
Returns:
The return value of the called command. | codesearchnet |
def parse_numpy_printoption(kv_str):
k_v_str = kv_str.split('=', 1)
if len(k_v_str) != 2 or not k_v_str[0]:
raise argparse.ArgumentTypeError("'%s' is not in the form k=v." % kv_str)
k, v_str = k_v_str
printoptions = np.get_printoptions()
if k not in printoptions:
raise argparse.Argum... | Sets a single numpy printoption from a string of the form 'x=y'.
See documentation on numpy.set_printoptions() for details about what values
x and y can take. x can be any option listed there other than 'formatter'.
Args:
kv_str: A string of the form 'x=y', such as 'threshold=100000'
Raises:
argparse.ArgumentTypeErr... | github-repos |
def execute_code_block(elem, doc):
command = select_executor(elem, doc).split(' ')
code = elem.text
if (('plt' in elem.attributes) or ('plt' in elem.classes)):
code = save_plot(code, elem)
command.append(code)
if ('args' in elem.attributes):
for arg in elem.attributes['args'].split()... | Executes a code block by passing it to the executor.
Args:
elem The AST element.
doc The document.
Returns:
The output of the command. | codesearchnet |
async def do_upload(context, files):
status = 0
try:
(await upload_artifacts(context, files))
except ScriptWorkerException as e:
status = worst_level(status, e.exit_code)
log.error('Hit ScriptWorkerException: {}'.format(e))
except aiohttp.ClientError as e:
status = worst_... | Upload artifacts and return status.
Returns the integer status of the upload.
args:
context (scriptworker.context.Context): the scriptworker context.
files (list of str): list of files to be uploaded as artifacts
Raises:
Exception: on unexpected exception.
Returns:
int: exit status | codesearchnet |
def new(cls, access_token, environment='prod'):
api_client = ApiClient.new(access_token, environment)
return cls(api_client) | Create new storage service client.
Arguments:
environment(str): The service environment to be used for the client.
'prod' or 'dev'.
access_token(str): The access token used to authenticate with the
service
Returns:
A storage_service.Client instance | codesearchnet |
def set_status(self, status):
text = ''
colour = '
if (status == 0):
text = 'OFFLINE'
colour = '
elif (status == 1):
text = 'STARTING'
colour = '
elif (status == 2):
text = 'ONLINE'
colour = '
self.status.set(text)
self.statusbar.config(backgro... | Updates the status text
Args:
status (int): The offline/starting/online status of Modis
0: offline, 1: starting, 2: online | codesearchnet |
def scroll(self, direction='vertical', percent=0.6, duration=2.0):
if (direction not in ('vertical', 'horizontal')):
raise ValueError('Argument `direction` should be one of "vertical" or "horizontal". Got {}'.format(repr(direction)))
focus1 = (self._focus or [0.5, 0.5])
focus2 = list(focus1)
hal... | Simply touch down from point A and move to point B then release up finally. This action is performed within
specific motion range and duration.
Args:
direction (:py:obj:`str`): scrolling direction. "vertical" or "horizontal"
percent (:py:obj:`float`): scrolling distance percentage of selected UI height or width accord... | codesearchnet |
def _unicode_def_src_to_str(srclist: List[Union[str, int]]) -> str:
charlist = []
for src in srclist:
if isinstance(src, int):
charlist.append(chr(src))
else:
first, last = [int(x, 16) for x in src.split("-")]
charlist += [chr(x) for x in r... | Used to create :data:`UNICODE_CATEGORY_STRINGS`.
Args:
srclist: list of integers or hex range strings like ``"0061-007A"``
Returns:
a string with all characters described by ``srclist``: either the
character corresponding to the integer Unicode character number, or
all characters corresponding to the inclusive range ... | juraj-google-style |
def bytestring_to_tar_tuple(filename, bytes):
info = tarfile.TarInfo(filename)
info.size = len(bytes)
return info, BytesIO(bytes) | Take a string + filename, return a (tarinfo, stringbuf) tuple for insertion.
Args:
bytes (bstring): Bytestring representation of the filedata.
filename (string): Filepath relative to tarfile root.
Returns:
tuple: (tarfile.TarInfo,io.BytesIO).
This can be passed directly to TarFile.addfile(). | juraj-google-style |
def tar_add_bytes(tf, filename, bytestring):
if (not isinstance(bytestring, bytes)):
bytestring = bytestring.encode('ascii')
buff = io.BytesIO(bytestring)
tarinfo = tarfile.TarInfo(filename)
tarinfo.size = len(bytestring)
tf.addfile(tarinfo, buff) | Add a file to a tar archive
Args:
tf (tarfile.TarFile): tarfile to add the file to
filename (str): path within the tar file
bytestring (bytes or str): file contents. Must be :class:`bytes` or
ascii-encodable :class:`str` | codesearchnet |
def _lookup_in_all_namespaces(self, symbol):
namespace = self.namespaces
namespace_stack = []
for current in symbol.namespace_stack:
namespace = namespace.get(current)
if namespace is None or not isinstance(namespace, dict):
break
... | Helper for lookup_symbol that looks for symbols in all namespaces.
Args:
symbol: Symbol | juraj-google-style |
def CheckSupportedFormat(cls, path, check_readable_only=False):
try:
connection = sqlite3.connect(
path, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
cursor = connection.cursor()
query = 'SELECT * FROM metadata'
cursor.execute(query)
metadata_values = ... | Checks if the storage file format is supported.
Args:
path (str): path to the storage file.
check_readable_only (Optional[bool]): whether the store should only be
checked to see if it can be read. If False, the store will be checked
to see if it can be read and written to.
Returns:
bool: True if the format is support... | juraj-google-style |
def _GetStructureValue(self, structure, key):
value = structure.get(key)
return (value if (not isinstance(value, pyparsing.ParseResults)) else None) | Retrieves a value from a parsed log line, removing empty results.
Args:
structure (pyparsing.ParseResults): parsed log line.
key (str): results key to retrieve from the parsed log line.
Returns:
type or None: the value of the named key in the parsed log line, or None
if the value is a ParseResults object. | codesearchnet |
def objects(self, prefix=None, delimiter=None):
return _object.Objects(self._name, prefix, delimiter, context=self._context) | Get an iterator for the objects within this bucket.
Args:
prefix: an optional prefix to match objects.
delimiter: an optional string to simulate directory-like semantics. The returned objects
will be those whose names do not contain the delimiter after the prefix. For
the remaining objects, the names will be returned ... | codesearchnet |
def _check(self, check, radl):
if check[0] == float:
if not isinstance(self.value, int) and not isinstance(self.value, float):
raise RADLParseException("Invalid type; expected %s" % check[0],
line=self.line)
... | Check type, operator and unit in a feature.
Args:
- check(tuple):
- v[0]: expected type of the feature value.
- v[1]: can be a list of possible values or a function to test the value or None.
- v[2] (optional): can be a list of possible units; if None or not set the
unit valid is none.
- radl: second argument passed w... | juraj-google-style |
def setup_test_logger(log_path, prefix=None, filename=None):
utils.create_dir(log_path)
_setup_test_logger(log_path, prefix)
logging.info('Test output folder: "%s"', log_path)
create_latest_log_alias(log_path) | Customizes the root logger for a test run.
Args:
log_path: Location of the report file.
prefix: A prefix for each log line in terminal.
filename: Name of the files. The default is the time the objects
are requested. | juraj-google-style |
def _CreateDictReader(self, line_reader):
delimiter = self.DELIMITER
quotechar = self.QUOTE_CHAR
magic_test_string = self._MAGIC_TEST_STRING
if py2to3.PY_3:
delimiter = delimiter.decode(self._encoding)
quotechar = quotechar.decode(self._encoding)
magic_test_string = magic_tes... | Returns a reader that processes each row and yields dictionaries.
csv.DictReader does this job well for single-character delimiters; parsers
that need multi-character delimiters need to override this method.
Args:
line_reader (iter): yields lines from a file-like object.
Returns:
iter: a reader of dictionaries, as r... | juraj-google-style |
def run_example(example_cls: Example, args=None):
values = parse_args(args)
window_cls = get_window_cls(values.window)
window = window_cls(
title=example_cls.title,
size=example_cls.window_size,
fullscreen=values.fullscreen,
resizable=example_cls.resizable,
gl_v... | Run an example entering a blocking main loop
Args:
example_cls: The exmaple class to render
args: Override sys.args | juraj-google-style |
def _FormatSubjectOrProcessToken(self, token_data):
ip_address = self._FormatPackedIPv4Address(token_data.ip_address)
return {
'aid': token_data.audit_user_identifier,
'euid': token_data.effective_user_identifier,
'egid': token_data.effective_group_identifier,
'uid': token_d... | Formats a subject or process token as a dictionary of values.
Args:
token_data (bsm_token_data_subject32|bsm_token_data_subject64):
AUT_SUBJECT32, AUT_PROCESS32, AUT_SUBJECT64 or AUT_PROCESS64 token
data.
Returns:
dict[str, str]: token values. | juraj-google-style |
def add_residues_highlight_to_nglview(view, structure_resnums, chain, res_color='red'):
chain = ssbio.utils.force_list(chain)
if isinstance(structure_resnums, list):
structure_resnums = list(set(structure_resnums))
elif isinstance(structure_resnums, int):
structure_resnums = ssbio.util... | Add a residue number or numbers to an NGLWidget view object.
Args:
view (NGLWidget): NGLWidget view object
structure_resnums (int, list): Residue number(s) to highlight, structure numbering
chain (str, list): Chain ID or IDs of which residues are a part of. If not provided, all chains in the
mapped_chains attribute wi... | juraj-google-style |
def GetEntries(self, parser_mediator, match=None, **unused_kwargs):
devices = match.get('Devices', {})
for device_identifier, device_information in iter(devices.items()):
datetime_value = device_information.get('Connected', None)
if not datetime_value:
continue
event_data = IPodP... | Extract device information from the iPod plist.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
match (Optional[dict[str: object]]): keys extracted from PLIST_KEYS. | juraj-google-style |
def extract_random_video_patch(videos, num_frames=-1):
if num_frames == -1:
return videos
batch_size, num_total_frames, h, w, c = common_layers.shape_list(videos)
if num_total_frames < num_frames:
raise ValueError("Expected num_frames <= %d, got %d" %
(num_total_frames, num_frames)... | For every video, extract a random consecutive patch of num_frames.
Args:
videos: 5-D Tensor, (NTHWC)
num_frames: Integer, if -1 then the entire video is returned.
Returns:
video_patch: 5-D Tensor, (NTHWC) with T = num_frames.
Raises:
ValueError: If num_frames is greater than the number of total frames in
the video. | juraj-google-style |
def analogy_rank_score(analogies, word_vectors, no_threads=1):
input_vectors = ((word_vectors[analogies[(:, 1)]] + word_vectors[analogies[(:, 2)]]) - word_vectors[analogies[(:, 0)]])
word_vector_norms = np.linalg.norm(word_vectors, axis=1)
rank_violations = np.zeros(input_vectors.shape[0], dtype=np.int32)
... | Calculate the analogy rank score for the given set of analogies.
A rank of zero denotes a perfect score; with random word vectors
we would expect a rank of 0.5.
Arguments:
- analogies: a numpy array holding the ids of the words in the analogy tasks,
as constructed by `construct_analogy_test_set`.
- word_vectors: nump... | codesearchnet |
def find(pcoll, regex, group=0):
regex = Regex._regex_compile(regex)
def _process(element):
r = regex.search(element)
if r:
yield r.group(group)
return pcoll | FlatMap(_process) | Returns the matches if a portion of the line matches the Regex. Returns
the entire group (group 0 by default). Group can be integer value or a
string value.
Args:
regex: the regular expression string or (re.compile) pattern.
group: (optional) name of the group, it can be integer or a string value. | github-repos |
def get_drives(self, id_or_uri):
uri = (self._client.build_uri(id_or_uri=id_or_uri) + self.DRIVES_PATH)
return self._client.get(id_or_uri=uri) | Gets the list of drives allocated to this SAS logical JBOD.
Args:
id_or_uri: Can be either the SAS logical JBOD ID or the SAS logical JBOD URI.
Returns:
list: A list of Drives | codesearchnet |
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_resu... | 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. | juraj-google-style |
def save_json(obj, filename, **kwargs):
with open(filename, 'w', encoding='utf-8') as f:
json.dump(obj, f, **kwargs) | Save an object as a JSON file.
Args:
obj: The object to save. Must be JSON-serializable.
filename: Path to the output file.
**kwargs: Additional arguments to `json.dump`. | juraj-google-style |
def __init__(self, graph=None, op_log=None):
if not graph and (not context.executing_eagerly()):
graph = ops.get_default_graph()
self._coverage = 0.0
self._graph = graph
op_log = tfprof_logger.merge_default_with_oplog(self._graph, op_log=op_log)
print_mdl.NewProfiler(_graph_string(self._grap... | Constructor.
Args:
graph: tf.Graph. If None and eager execution is not enabled, use default
graph.
op_log: optional. tensorflow::tfprof::OpLogProto proto. Used to define
extra op types. | github-repos |
def __init__(self,
domain_mapper,
mode='classification',
class_names=None,
random_state=None):
self.random_state = random_state
self.mode = mode
self.domain_mapper = domain_mapper
self.local_exp = {}
sel... | Initializer.
Args:
domain_mapper: must inherit from DomainMapper class
type: "classification" or "regression"
class_names: list of class names (only used for classification)
random_state: an integer or numpy.RandomState that will be used to
generate random numbers. If None, the random state will be
initialized using t... | juraj-google-style |
def load(self, train=True, test=True, shuffle=True) -> tuple:
return self.__load(self.__load_files, train, test, shuffle=shuffle) | Load the vectorized representations of the stored data files
Args:
train: Whether to load train data
test: Whether to load test data | juraj-google-style |
def get_transcript_credentials_state_for_org(org, provider=None):
query_filter = {'org': org}
if provider:
query_filter['provider'] = provider
return {
credential.provider: credential.exists
for credential in ThirdPartyTranscriptCredentialsState.objects.filter(**query_filter)
... | Returns transcript credentials state for an org
Arguments:
org (unicode): course organization
provider (unicode): transcript provider
Returns:
dict: provider name and their credential existance map
{
u'Cielo24': True
}
{
u'3PlayMedia': False,
u'Cielo24': True
} | juraj-google-style |
def _init_from_bool(self, z, x):
if z is None:
raise QiskitError("z vector must not be None.")
if x is None:
raise QiskitError("x vector must not be None.")
if len(z) != len(x):
raise QiskitError("length of z and x vectors must be "
... | Construct pauli from boolean array.
Args:
z (numpy.ndarray): boolean, z vector
x (numpy.ndarray): boolean, x vector
Returns:
Pauli: self
Raises:
QiskitError: if z or x are None or the length of z and x are different. | juraj-google-style |
def set_smartplug_state(self, device_label, state):
response = None
try:
response = requests.post(urls.smartplug(self._giid), headers={'Content-Type': 'application/json', 'Cookie': 'vid={}'.format(self._vid)}, data=json.dumps([{'deviceLabel': device_label, 'state': state}]))
except requests.exceptio... | Turn on or off smartplug
Args:
device_label (str): Smartplug device label
state (boolean): new status, 'True' or 'False' | codesearchnet |
def lookup_zone_exception(self, callsign, timestamp=datetime.utcnow().replace(tzinfo=UTC)):
callsign = callsign.strip().upper()
if (self._lookuptype == 'clublogxml'):
return self._check_zone_exception_for_date(callsign, timestamp, self._zone_exceptions, self._zone_exceptions_index)
elif (self._looku... | Returns a CQ Zone if an exception exists for the given callsign
Args:
callsign (string): Amateur radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
int: Value of the the CQ Zone exception which exists for this callsign (at the given time)
Raises:
KeyError: No matching callsign ... | codesearchnet |
def get_special_tokens_mask(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None, already_has_special_tokens: bool=False) -> List[int]:
if already_has_special_tokens:
return super().get_special_tokens_mask(token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True)
... | Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
special tokens using the tokenizer `prepare_for_model` method.
Args:
token_ids_0 (`List[int]`):
List of IDs.
token_ids_1 (`List[int]`, *optional*):
Optional second list of IDs for sequence pairs.
already_has_spe... | github-repos |
def pairwise_iou(boxlist1, boxlist2):
intersections = pairwise_intersection(boxlist1, boxlist2)
areas1 = area(boxlist1)
areas2 = area(boxlist2)
unions = (
tf.expand_dims(areas1, 1) + tf.expand_dims(areas2, 0) - intersections)
return tf.where(
tf.equal(intersections, 0.0),
... | Computes pairwise intersection-over-union between box collections.
Args:
boxlist1: Nx4 floatbox
boxlist2: Mx4
Returns:
a tensor with shape [N, M] representing pairwise iou scores. | juraj-google-style |
def read_from_directory(self, dataset_info_dir):
if not dataset_info_dir:
raise ValueError(
"Calling read_from_directory with undefined dataset_info_dir.")
json_filename = self._dataset_info_filename(dataset_info_dir)
parsed_proto = read_from_json(json_filename)
self._s... | Update DatasetInfo from the JSON file in `dataset_info_dir`.
This function updates all the dynamically generated fields (num_examples,
hash, time of creation,...) of the DatasetInfo.
This will overwrite all previous metadata.
Args:
dataset_info_dir: `str` The directory containing the metadata file. This
should be th... | juraj-google-style |
def input_streams(self):
streams = []
for (walker, _trigger) in self.inputs:
if ((walker.selector is None) or (not walker.selector.singular)):
continue
streams.append(walker.selector.as_stream())
return streams | Return a list of DataStream objects for all singular input streams.
This function only returns individual streams, not the streams that would
be selected from a selector like 'all outputs' for example.
Returns:
list(DataStream): A list of all of the individual DataStreams that are inputs
of the node. Input selectors... | codesearchnet |
def webhook(self, webhook_url):
if not webhook_url:
raise Exception('Url can not be None')
matcher = re.match(self.__webhook_url_format, webhook_url)
if not matcher:
raise Exception('Invalid url format, looking for: ' + self.__webhook_url_format)
self.a... | Load object with webhook_url
Args:
webhook_url (str): full webhook url given by Discord 'create webhook' func | juraj-google-style |
def WriteRow(self, values):
precondition.AssertDictType(values, text, text)
row = []
for column in self._columns:
try:
value = values[column]
except KeyError:
raise ValueError("Row does not contain required column `%s`" % column)
row.append(value)
self._writer.W... | Writes a single row to the underlying buffer.
Args:
values: A dictionary mapping column names to values to be inserted into
the CSV output. | juraj-google-style |
def check_configuration(ctx, base_key, needed_keys):
if base_key not in ctx.keys():
exit("[{}ERROR{}] missing configuration for '{}'"
.format(ERROR_COLOR, RESET_COLOR, base_key))
if ctx.releaser is None:
exit("[{}ERROR{}] empty configuration for '{}' found"
... | Confrim a valid configuration.
Args:
ctx (invoke.context):
base_key (str): the base configuration key everything is under.
needed_keys (list): sub-keys of the base key that are checked to make
sure they exist. | juraj-google-style |
def __RenderOurModuleKeyFlags(self, module, output_lines, prefix=''):
key_flags = self._GetKeyFlagsForModule(module)
if key_flags:
self.__RenderModuleFlags(module, key_flags, output_lines, prefix) | Generates a help string for the key flags of a given module.
Args:
module: A module object or a module name (a string).
output_lines: A list of strings. The generated help message
lines will be appended to this list.
prefix: A string that is prepended to each generated help line. | codesearchnet |
def find_by(cls, payload, require=False):
if (not isinstance(payload, dict)):
raise ValueError("The 'payload' parameter must be provided a dictionary object.")
url = os.path.join(cls.URL, 'find_by')
payload = {'find_by': payload}
cls.debug_logger.debug('Searching Pulsar {} for {}'.format(cls.__n... | Searches the model in question by AND joining the query parameters.
Implements a Railsy way of looking for a record using a method by the same name and passing
in the query as a dict. as well. Only the first hit is returned, and there is no particular
ordering specified in the server-side API method.
Args:
payload: `... | codesearchnet |
def _GetTimeValues(self, number_of_seconds):
number_of_seconds = int(number_of_seconds)
number_of_minutes, seconds = divmod(number_of_seconds, 60)
number_of_hours, minutes = divmod(number_of_minutes, 60)
number_of_days, hours = divmod(number_of_hours, 24)
return number_of_days, hours, minutes, ... | Determines time values.
Args:
number_of_seconds (int|decimal.Decimal): number of seconds.
Returns:
tuple[int, int, int, int]: days, hours, minutes, seconds. | juraj-google-style |
class _BaseThresholdDoFn(beam.DoFn):
def __init__(self, threshold_fn_spec: Spec):
self._threshold_fn_spec = threshold_fn_spec
def _apply_threshold_to_predictions(self, result: AnomalyResult) -> AnomalyResult:
predictions = [dataclasses.replace(p, label=self._threshold_fn.apply(p.score... | Applies a ThresholdFn to anomaly detection results.
This abstract base class defines the structure for DoFns that use a
`ThresholdFn` to convert anomaly scores into anomaly labels (e.g., normal
or outlier). It handles the core logic of applying the threshold function
and updating the prediction labels within `AnomalyR... | github-repos |
def CreateDefaultPartition(client, ad_group_id):
ad_group_criterion_service = client.GetService('AdGroupCriterionService',
version='v201809')
operations = [{
'operator': 'ADD',
'operand': {
'xsi_type': 'BiddableAdGroupCriterion',
'... | Creates a default partition.
Args:
client: an AdWordsClient instance.
ad_group_id: an integer ID for an ad group. | juraj-google-style |
def subspace_index(self, little_endian_bits_int: int) -> Tuple[(Union[(slice, int, 'ellipsis')], ...)]:
return linalg.slice_for_qubits_equal_to(self.axes, little_endian_bits_int) | An index for the subspace where the target axes equal a value.
Args:
little_endian_bits_int: The desired value of the qubits at the
targeted `axes`, packed into an integer. The least significant
bit of the integer is the desired bit for the first axis, and
so forth in increasing order.
Returns:
A value that can be us... | codesearchnet |
def __strip_extra_attributes(self, node: yaml.Node,
known_attrs: List[str]) -> None:
known_keys = list(known_attrs)
known_keys.remove('self')
if 'yatiml_extra' in known_keys:
known_keys.remove('yatiml_extra')
for key_node, value_node... | Strips tags from extra attributes.
This prevents nodes under attributes that are not part of our \
data model from being converted to objects. They'll be plain \
CommentedMaps instead, which then get converted to OrderedDicts \
for the user.
Args:
node: The node to process
known_attrs: The attributes to not strip | juraj-google-style |
def rename_keys(d: Dict[(str, Any)], mapping: Dict[(str, str)]) -> Dict[(str, Any)]:
result = {}
for (k, v) in d.items():
if (k in mapping):
k = mapping[k]
result[k] = v
return result | Returns a copy of the dictionary ``d`` with its keys renamed according to
``mapping``.
Args:
d: the starting dictionary
mapping: a dictionary of the format ``{old_key_name: new_key_name}``
Returns:
a new dictionary
Keys that are not in ``mapping`` are left unchanged.
The input parameters are not modified. | codesearchnet |
def calc_checksum(sentence):
if sentence.startswith('$'):
sentence = sentence[1:]
sentence = sentence.split('*')[0]
return reduce(xor, map(ord, sentence)) | Calculate a NMEA 0183 checksum for the given sentence.
NMEA checksums are a simple XOR of all the characters in the sentence
between the leading "$" symbol, and the "*" checksum separator.
Args:
sentence (str): NMEA 0183 formatted sentence | juraj-google-style |
def reset_sequence(cls, value=None, force=False):
cls._meta.reset_sequence(value, force=force) | Reset the sequence counter.
Args:
value (int or None): the new 'next' sequence value; if None,
recompute the next value from _setup_next_sequence().
force (bool): whether to force-reset parent sequence counters
in a factory inheritance chain. | juraj-google-style |
def get_session_tensor(handle, dtype, name=None):
handle_device = TensorHandle._get_device_name(handle)
with ops.device(handle_device):
holder = array_ops.placeholder(dtypes.string)
_register_handle_feeder(holder.graph, holder, dtype)
tensor = gen_data_flow_ops.get_session_tensor(holder,... | Get the tensor of type `dtype` by feeding a tensor handle.
This is EXPERIMENTAL and subject to change.
Get the value of the tensor from a tensor handle. The tensor
is produced in a previous run() and stored in the state of the
session.
Args:
handle: The string representation of a persistent tensor handle.
dtype: The... | github-repos |
def tf_loss_per_instance(self, states, internals, actions, terminal, reward, next_states, next_internals, update, reference=None):
raise NotImplementedError | Creates the TensorFlow operations for calculating the loss per batch instance.
Args:
states: Dict of state tensors.
internals: Dict of prior internal state tensors.
actions: Dict of action tensors.
terminal: Terminal boolean tensor.
reward: Reward tensor.
next_states: Dict of successor state tensors.
next_internals: L... | codesearchnet |
def merge_from(self, dev):
self.job, self.replica, self.task, self.device_type, self.device_index = self._get_combined_properties(dev) | Merge the properties of "dev" into this `DeviceSpec`.
Note: Will be removed in TensorFlow 2.x since DeviceSpecs will become
immutable.
Args:
dev: a `DeviceSpec`. | github-repos |
def __init__(self, request_builder, upload_url, current_content_length=0,
is_last=False):
self._request_builder = request_builder
if current_content_length < 0:
raise googleads.errors.GoogleAdsValueError(
'Current content length %s is < 0.' % current_content_length)
self.... | Initializes the IncrementalUpload.
Args:
request_builder: an AbstractUploadRequestBuilder instance.
upload_url: a string url provided by the BatchJobService.
current_content_length: an integer identifying the current content length
of data uploaded to the Batch Job.
is_last: a boolean indicating whether this is the fi... | juraj-google-style |
def SetDayOfWeekHasService(self, dow, has_service=True):
assert(dow >= 0 and dow < 7)
self.day_of_week[dow] = has_service | Set service as running (or not) on a day of the week. By default the
service does not run on any days.
Args:
dow: 0 for Monday through 6 for Sunday
has_service: True if this service operates on dow, False if it does not.
Returns:
None | juraj-google-style |
def _get_shoulds(options):
if (options.version == '2.0'):
return shoulds20.list_shoulds(options)
else:
return shoulds21.list_shoulds(options) | Return the list of 'SHOULD' validators for the correct version of STIX.
Args:
options: ValidationOptions instance with validation options for this
validation run, including the STIX spec version. | codesearchnet |
def trivial_reward(example):
return example | Reward for the trivial search space.
The reward (i.e. fitness) is the value itself. The goal of the search,
therefore, is to find the value 1.
Args:
example: a materialized value.
Returns:
The corresponding reward. | github-repos |
def find_files(paths, file_predicate):
file_list = []
for path in paths:
p = abs_path(path)
for dirPath, _, fileList in os.walk(p):
for fname in fileList:
name, ext = os.path.splitext(fname)
if file_predicate(name, ext):
file_l... | Locate files whose names and extensions match the given predicate in
the specified directories.
Args:
paths: A list of directory paths where to find the files.
file_predicate: A function that returns True if the file name and
extension are desired.
Returns:
A list of files that match the predicate. | juraj-google-style |
def format_arguments(*args):
positional_args = []
kwargs = {}
split_key = None
for arg in args:
if arg.startswith('--'):
arg = arg[2:]
if ('=' in arg):
(key, value) = arg.split('=', 1)
kwargs[key.replace('-', '_')] = value
else:... | Converts a list of arguments from the command line into a list of
positional arguments and a dictionary of keyword arguments.
Handled formats for keyword arguments are:
* --argument=value
* --argument value
Args:
*args (list): a list of arguments
Returns:
([positional_args], {kwargs}) | codesearchnet |
def __add__(self, other):
sum_roc = DistributedROC(self.thresholds, self.obs_threshold)
sum_roc.contingency_tables = self.contingency_tables + other.contingency_tables
return sum_roc | Add two DistributedROC objects together and combine their contingency table values.
Args:
other: Another DistributedROC object. | juraj-google-style |
def maybe_download(self, filename, work_directory, source_url):
if not os.path.exists(work_directory):
os.makedirs(work_directory)
filepath = os.path.join(work_directory, filename)
if not os.path.exists(filepath):
temp_file_name, _ = urllib.request.urlretrieve(so... | Download the data from source url, unless it's already here.
Args:
filename: string, name of the file in the directory.
work_directory: string, path to working directory.
source_url: url to download from if file doesn't exist.
Returns:
Path to resulting file. | juraj-google-style |
def write_uint16(self, value, little_endian=True):
if little_endian:
endian = '<'
else:
endian = '>'
return self.pack(('%sH' % endian), value) | Pack the value as an unsigned integer and write 2 bytes to the stream.
Args:
value:
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
int: the number of bytes written. | codesearchnet |
def ConvertMessage(self, value, message):
message_descriptor = message.DESCRIPTOR
full_name = message_descriptor.full_name
if _IsWrapperMessage(message_descriptor):
self._ConvertWrapperMessage(value, message)
elif (full_name in _WKTJSONMETHODS):
methodcaller(_WKTJSONMETHODS[full_name][1]... | Convert a JSON object into a message.
Args:
value: A JSON object.
message: A WKT or regular protocol message to record the data.
Raises:
ParseError: In case of convert problems. | codesearchnet |
def parse_docs(docs, marks):
if docs is None:
return {}
indexs = []
for mark in marks:
i = docs.find(mark)
if i >= 0:
indexs.append(i)
if not indexs:
return {"$desc": textwrap.dedent(docs).strip()}
start = min(indexs)
start = docs.rfind("\n", 0, s... | Parse YAML syntax content from docs
If docs is None, return {}
If docs has no YAML content, return {"$desc": docs}
Else, parse YAML content, return {"$desc": docs, YAML}
Args:
docs (str): docs to be parsed
marks (list): list of which indicate YAML content starts
Returns:
A dict contains information of docs | juraj-google-style |
def RegisterHelper(cls, resolver_helper):
if resolver_helper.type_indicator in cls._resolver_helpers:
raise KeyError((
'Resolver helper object already set for type indicator: '
'{0!s}.').format(resolver_helper.type_indicator))
cls._resolver_helpers[resolver_helper.type_indicator]... | Registers a path specification resolver helper.
Args:
resolver_helper (ResolverHelper): resolver helper.
Raises:
KeyError: if resolver helper object is already set for the corresponding
type indicator. | juraj-google-style |
def GetFrequencyStopTimes(self, problems=None):
stoptimes_list = []
stoptime_pattern = self.GetStopTimes()
first_secs = stoptime_pattern[0].arrival_secs
stoptime_class = self.GetGtfsFactory().StopTime
for run_secs in self.GetFrequencyStartTimes():
stoptimes = []
for st in stoptime_pa... | Return a list of StopTime objects for each headway-based run.
Returns:
a list of list of StopTime objects. Each list of StopTime objects
represents one run. If this trip doesn't have headways returns an empty
list. | codesearchnet |
def dummy_inputs(self) -> Dict[str, tf.Tensor]:
dummies = {}
for key, spec in self.input_signature.items():
dummy_shape = [dim if dim is not None else 2 for dim in spec.shape]
if spec.shape[0] is None:
dummy_shape[0] = 1
dummies[key] = tf.ones(shape=dummy_shape, dtype=spec.dt... | Dummy inputs to build the network.
Returns:
`Dict[str, tf.Tensor]`: The dummy inputs. | github-repos |
def select_segments(self, jsonpath: str) -> List[Segment]:
path = self.etk.parse_json_path(jsonpath)
matches = path.find(self.cdr_document)
segments = list()
for a_match in matches:
this_segment = Segment(str(a_match.full_path), a_match.value, self)
segm... | Dereferences the json_path inside the document and returns the selected elements.
This method should compile and cache the compiled json_path in case the same path
is reused by multiple extractors.
Args:
jsonpath (str): a valid JSON path.
Returns: A list of Segments object that contains the elements selected by the j... | juraj-google-style |
def fetch(self, customer_id, data={}, **kwargs):
return super(Customer, self).fetch(customer_id, data, **kwargs) | Fetch Customer for given Id
Args:
customer_id : Id for which customer object has to be retrieved
Returns:
Order dict for given customer Id | codesearchnet |
def _get_single_variable(self, name, shape=None, dtype=dtypes.float32, initializer=None, regularizer=None, partition_info=None, reuse=None, trainable=None, caching_device=None, validate_shape=True, constraint=None, synchronization=vs.VariableSynchronization.AUTO, aggregation=vs.VariableAggregation.NONE):
initializi... | Get or create a single Variable (e.g.
a shard or entire variable).
See the documentation of get_variable above (ignore partitioning components)
for details.
Args:
name: see get_variable.
shape: see get_variable.
dtype: see get_variable.
initializer: see get_variable.
regularizer: see get_variable.
partition_info: _P... | github-repos |
def generate_contour_data(pid):
if isinstance(pid, GenInput):
pid = pid.return_dict()
begin_time = time.time()
WORKING_DIRECTORY = '.'
if 'WORKING_DIRECTORY' not in pid['general'].keys():
pid['general']['WORKING_DIRECTORY'] = WORKING_DIRECTORY
running_process =... | Main function for this program.
This will read in sensitivity_curves and binary parameters; calculate snrs
with a matched filtering approach; and then read the contour data out to a file.
Args:
pid (obj or dict): GenInput class or dictionary containing all of the input information for
the generation. See BOWIE docume... | juraj-google-style |
def delete(filething):
t = OggFLAC(filething)
filething.fileobj.seek(0)
t.delete(filething) | delete(filething)
Arguments:
filething (filething)
Raises:
mutagen.MutagenError
Remove tags from a file. | juraj-google-style |
def _determine_hpp_url(self, platform, action):
base_uri = settings.BASE_HPP_URL.format(platform)
service = (action + '.shtml')
result = '/'.join([base_uri, service])
return result | This returns the Adyen HPP endpoint based on the provided platform,
and action.
Args:
platform (str): Adyen platform, ie 'live' or 'test'.
action (str): the HPP action to perform.
possible actions: select, pay, skipDetails, directory | codesearchnet |
def expand_char_ngrams(source, minn, maxn, itself='ASIS', name=None):
with ops.name_scope(name, 'ExpandCharNgrams', [source]):
source = convert_to_tensor_or_sparse_tensor(source, dtype=tf.string)
if isinstance(source, tf.SparseTensor):
(child_indices, child_values, child_shape) = ops_mod... | Split unicode strings into char ngrams.
Ngrams size configures with minn and max
Args:
source: `Tensor` or `SparseTensor` of any shape, strings to split
minn: Minimum length of char ngram
minn: Maximum length of char ngram
itself: Scalar value, strategy for source word preserving.
One of `"ASIS"`, `"NEVER"`, `"ALWAYS"... | codesearchnet |
def unwrap_outputs(distribution_strategy, grouped_outputs, with_loss_tensor=False):
if not with_loss_tensor:
return flatten_per_replica_values(distribution_strategy, grouped_outputs)
if not isinstance(grouped_outputs, list):
grouped_outputs = [grouped_outputs]
loss = distribution_strategy.re... | Unwrap the list of outputs contained in the PerReplica parameters.
This function calls `flatten_per_replica_values` to parse each of the input
parameters into a list of outputs on the different devices. If we set
`with_loss_tensor` to be True, we also call `reduce` on the list of losses on
the different devices to giv... | github-repos |
def dml_loss(pred, labels, weights_fn=_weights_one_third, reduce_sum=True):
real_labels = convert_rgb_to_symmetric_real(labels)
dml_loss_value = discretized_mix_logistic_loss(pred=pred, labels=real_labels)
weights = weights_fn(labels)
loss_num = (weights * dml_loss_value)
loss_den = weights_nonzero(... | Discretized mixture of logistics loss.
Args:
pred: A [batch, height, width, num_mixtures*10] tensor of floats
comprising one unconstrained mixture probability, three means
(one per channel), three standard deviations (one per channel),
and three coefficients which linearly parameterize dependence across
channels.
labe... | codesearchnet |
def __init__(self, filename: str, mode: str = 'r+', *, validate: bool = True, spec_version: str = "2.0.1") -> None:
if not os.path.exists(filename):
raise IOError(f"File '{filename}' not found")
if mode != 'r+' and mode != 'r':
raise ValueError("Mode must be either 'r' or 'r+'")
self.filename = filena... | Establish a connection to a Loom file.
Args:
filename: Name of the .loom file to open
mode: read/write mode, accepts 'r+' (read/write) or
'r' (read-only), defaults to 'r+' without arguments,
and to 'r' with incorrect arguments
validate: Validate that the file conforms with the Loom specification
Returns:
Nothin... | juraj-google-style |
def create_workspace(self, did, name, version_id=None):
payload = {
'isPublic': True,
'name': name,
}
if version_id:
payload['versionId'] = version_id
return self._api.request('post', '/api/documents/d/' + did + '/workspaces', body=payload) | Create a workspace in the specified document.
Args:
- did (str): the document id of where to create the new workspace
- name (str): the new name of the copied workspace.
- version_id (str): the ID of the version to be copied into a new workspace
Returns:
- requests.Response: Onshape response data | juraj-google-style |
def post_file(self, url, filename, file_stream, *args, **kwargs):
res = self._conn.post(url, files={filename: file_stream},
headers=self._prepare_headers(**kwargs))
if res.status_code == 200 or res.status_code == 201:
return res.text
else:
... | Uploads file to provided url.
Returns contents as text
Args:
**url**: address where to upload file
**filename**: Name of the uploaded file
**file_stream**: file like object to upload
.. versionadded:: 0.3.2
**additional_headers**: (optional) Additional headers
to be used with request
Returns:
string | juraj-google-style |
def __init__(self, python_function, name, input_signature=None, autograph=True, jit_compile=None, reduce_retracing=False, experimental_implements=None, experimental_autograph_options=None, experimental_attributes=None):
self._lock = threading.RLock()
self._python_function = python_function
self._function_ty... | Initializes a `Function`.
Args:
python_function: the function to be wrapped.
name: the name given to it.
input_signature: See the documentation for `tf.function`.
autograph: See the documentation for `tf.function`.
jit_compile: See the documentation for `tf.function`.
reduce_retracing: See the documentation for `tf.fu... | github-repos |
def _read_signer(key_filename):
filename = key_filename
if filename is None:
filename = os.path.join(os.path.expanduser('~'),
'.sawtooth',
'keys',
getpass.getuser() + '.priv')
try:
with open... | Reads the given file as a hex key.
Args:
key_filename: The filename where the key is stored. If None,
defaults to the default key for the current user.
Returns:
Signer: the signer
Raises:
CliException: If unable to read the file. | juraj-google-style |
def synchronize_task(self, func, *args, **kwargs):
async def _runner():
return func(*args, **kwargs)
return self.emulator.run_task_external(_runner()) | Run callable in the rpc thread and wait for it to finish.
The callable ``func`` will be passed into the EmulationLoop and run
there. This method will block until ``func`` is finished and
return/raise whatever that callable returns/raises.
This method is mainly useful for performing an activity that needs to
be synch... | codesearchnet |
def _calculateCrcString(inputstring):
_checkString(inputstring, description='input CRC string')
register = 0xFFFF
for char in inputstring:
register = (register >> 8) ^ _CRC16TABLE[(register ^ ord(char)) & 0xFF]
return _numToTwoByteString(register, LsbFirst=True) | Calculate CRC-16 for Modbus.
Args:
inputstring (str): An arbitrary-length message (without the CRC).
Returns:
A two-byte CRC string, where the least significant byte is first. | juraj-google-style |
def extract_keywords(self, sentence, span_info=False):
keywords_extracted = []
if (not sentence):
return keywords_extracted
if (not self.case_sensitive):
sentence = sentence.lower()
current_dict = self.keyword_trie_dict
sequence_start_pos = 0
sequence_end_pos = 0
reset_curren... | Searches in the string for all keywords present in corpus.
Keywords present are added to a list `keywords_extracted` and returned.
Args:
sentence (str): Line of text where we will search for keywords
Returns:
keywords_extracted (list(str)): List of terms/keywords found in sentence that match our corpus
Examples:
>>>... | codesearchnet |
def get_metrics_namespace(self) -> str:
return 'BeamML_PyTorch' | Returns:
A namespace for metrics collected by the RunInference transform. | github-repos |
def service_status(self, short_name):
if short_name not in self.services:
raise ArgumentError("Unknown service name", short_name=short_name)
info = {}
service = self.services[short_name]['state']
info['heartbeat_age'] = monotonic() - service.last_heartbeat
... | Get the current status of a service.
Returns information about the service such as the length since the last
heartbeat, any status messages that have been posted about the service
and whether the heartbeat should be considered out of the ordinary.
Args:
short_name (string): The short name of the service to query
Ret... | juraj-google-style |
def values_override(self) -> Optional[Mapping[str, Any]]:
if hasattr(self._config, 'use_cache'):
return {'use_cache': False}
return None | Dictionary of keys to override in the model's config before exporting
Returns:
Dictionary with the keys (and their corresponding values) to override | github-repos |
def nic_b(msg):
tc = typecode(msg)
if tc < 9 or tc > 18:
raise RuntimeError("%s: Not a airborne position message, expecting 8<TC<19" % msg)
msgbin = common.hex2bin(msg)
nic_b = int(msgbin[39])
return nic_b | Obtain NICb, navigation integrity category supplement-b
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
int: NICb number (0 or 1) | juraj-google-style |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.