code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def buy(self, product_id, order_type, **kwargs):
return self.place_order(product_id, 'buy', order_type, **kwargs) | Place a buy order.
This is included to maintain backwards compatibility with older versions
of cbpro-Python. For maximum support from docstrings and function
signatures see the order type-specific functions place_limit_order,
place_market_order, and place_stop_order.
Args:
product_id (str): Product to order (eg. 'BTC... | codesearchnet |
def download_image(self, handle, dest):
with log_utils.LogTask(('Download image %s' % handle), logger=LOGGER):
self.open_url(url=handle, dest=dest)
self.extract_image_xz(dest) | Downloads the image from the http server
Args:
handle (str): url from the `self.baseurl` to the remote template
dest (str): Path to store the downloaded url to, must be a file
path
Returns:
None | codesearchnet |
def discover(package, cls_match_func):
matched_classes = set()
for _, module_name, _ in pkgutil.walk_packages(
package.__path__,
prefix=package.__name__ + '.',
):
module = __import__(module_name, fromlist=[str('__trash')], level=0)
for _, imported_clas... | Returns a set of classes in the directory matched by cls_match_func
Args:
path - A Python package
cls_match_func - Function taking a class and returning true if the
class is to be included in the output. | juraj-google-style |
def _get_row_partition_type_tensor_pairs(rt_input):
partitions = rt_input._nested_row_partitions
tail = [_get_row_partition_type_tensor_pairs_tail(x) for x in partitions[1:]]
if partitions[0]._value_rowids is not None:
return [('FIRST_DIM_SIZE', partitions[0].nrows()), ('VALUE_ROWIDS', partitions[0]... | Gets a list of the row partitions for rt_input.
If value_rowids are defined, then they are used. Otherwise, row_splits
are used. If the outermost level has value_rowids defind, then nrows is
also added.
Args:
rt_input: a ragged tensor.
Returns:
A list of (row_partition_type, row_partition_tensor) pairs. | github-repos |
def get_details(self, ids):
if isinstance(ids, list):
if (len(ids) > 5):
ids = ids[:5]
id_param = (';'.join(ids) + '/')
else:
ids = str(ids)
id_param = (ids + '/')
(header, content) = self._http_request(id_param)
resp = json.loads(content)
if (not self._is... | Locu Venue Details API Call Wrapper
Args:
list of ids : ids of a particular venues to get insights about. Can process up to 5 ids | codesearchnet |
def __init__(self, scaffold=None, master='', config=None, max_wait_secs=30 * 60):
self._scaffold = scaffold or Scaffold()
self._session_manager = None
self._master = master
self._config = config
self._max_wait_secs = max_wait_secs | Initializes a worker session creator.
Args:
scaffold: A `Scaffold` used for gathering or building supportive ops. If
not specified a default one is created. It's used to finalize the graph.
master: `String` representation of the TensorFlow master to use.
config: `ConfigProto` proto used to configure the session.
max_w... | github-repos |
def stringize(
self,
rnf_profile=RnfProfile(),
):
sorted_segments = sorted(self.segments,
key=lambda x: (
x.genome_id * (10 ** 23) +
x.chr_id * (10 ** 21) +
(x.left + (int(x.left == 0) * x.right - 1)) * (10 ** 11) +
x.right * (10 ** ... | Create RNF representation of this read.
Args:
read_tuple_id_width (int): Maximal expected string length of read tuple ID.
genome_id_width (int): Maximal expected string length of genome ID.
chr_id_width (int): Maximal expected string length of chromosome ID.
coor_width (int): Maximal expected string length of a coordi... | juraj-google-style |
def implicit_static(cls, for_type=None, for_types=None):
for type_ in cls.__get_type_args(for_type, for_types):
implementations = {}
for function in cls.required():
method = getattr(type_, function.__name__, None)
if not callable(method):
... | Automatically generate implementations for a type.
Implement the protocol for the 'for_type' type by dispatching each
member function of the protocol to an instance method of the same name
declared on the type 'for_type'.
Arguments:
for_type: The type to implictly implement the protocol with.
Raises:
TypeError if no... | juraj-google-style |
def generate_pb_config(pb_id: str, pb_config: dict=None, workflow_config: dict=None) -> dict:
if (workflow_config is None):
workflow_config = dict()
if (pb_config is None):
pb_config = dict()
pb_type = pb_config.get('type', choice(PB_TYPES))
workflow_id = workflow_config.get('id')
if... | Generate a PB configuration dictionary.
Args:
pb_id (str): Processing Block Id
pb_config (dict, optional) PB configuration.
workflow_config (dict, optional): Workflow configuration
Returns:
dict, PB configuration dictionary. | codesearchnet |
class InputExample:
example_id: str
question: str
contexts: list[str]
endings: list[str]
label: Optional[str] | A single training/test example for multiple choice
Args:
example_id: Unique id for the example.
question: string. The untokenized text of the second sequence (question).
contexts: list of str. The untokenized text of the first sequence (context of corresponding question).
endings: list of str. multiple choice's option... | github-repos |
def training_loop_hparams_from_scoped_overrides(scoped_overrides, trial_id):
trial_hp_overrides = scoped_overrides.values()
loop_hp = create_loop_hparams()
model_hp_name = trial_hp_overrides.get(
"loop.generative_model_params", loop_hp.generative_model_params)
model_hp = registry.hparams(model_hp_n... | Create HParams suitable for training loop from scoped HParams.
Args:
scoped_overrides: HParams, with keys all scoped by one of HP_SCOPES. These
parameters are overrides for the base HParams created by
create_loop_hparams.
trial_id: str, trial identifier. This is used to register unique HParams
names for the underlying... | juraj-google-style |
def _is_apk_install_success(stdout: bytes, stderr: str) -> bool:
if utils.grep('Failure', stdout):
return False
return any([not stderr, stderr == 'Success', 'waiting for device' in stderr]) | Checks output of the adb install command and decides if install succeeded.
Args:
stdout: string, the standard out output of an adb install command.
stderr: string, the standard error output of an adb install command.
Returns:
True if the installation succeeded; False otherwise. | github-repos |
def remove_duplicate_sg(security_groups):
for each_sg, duplicate_sg_name in SECURITYGROUP_REPLACEMENTS.items():
if each_sg in security_groups and duplicate_sg_name in security_groups:
LOG.info('Duplicate SG found. Removing %s in favor of %s.', duplicate_sg_name, each_sg)
securit... | Removes duplicate Security Groups that share a same name alias
Args:
security_groups (list): A list of security group id to compare against SECURITYGROUP_REPLACEMENTS
Returns:
security_groups (list): A list of security groups with duplicate aliases removed | juraj-google-style |
def running_instances(self, context, process_name):
handle = (id(context), process_name)
it = self.processes.get(handle, {}).itervalues()
entries = [x for x in it if x[0].poll() is None]
return entries | Get a list of running instances.
Args:
context (`ResolvedContext`): Context the process is running in.
process_name (str): Name of the process.
Returns:
List of (`subprocess.Popen`, start-time) 2-tuples, where start_time
is the epoch time the process was added. | juraj-google-style |
def _FormatSocketUnixToken(self, token_data):
protocol = bsmtoken.BSM_PROTOCOLS.get(token_data.socket_family, 'UNKNOWN')
return {'protocols': protocol, 'family': token_data.socket_family, 'path': token_data.socket_path} | Formats an Unix socket token as a dictionary of values.
Args:
token_data (bsm_token_data_sockunix): AUT_SOCKUNIX token data.
Returns:
dict[str, str]: token values. | codesearchnet |
def GetEntries(self, parser_mediator, match=None, **unused_kwargs):
backup_alias_map = self._GetDataTypeMap('timemachine_backup_alias')
destinations = match.get('Destinations', [])
for destination in destinations:
backup_alias_data = destination.get('BackupAlias', b'')
try:
backup_... | Extracts relevant TimeMachine entries.
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 _run_graph(self, device, input_shape, variable, num_inputs, axis, grad, num_iters):
graph = ops.Graph()
with graph.as_default():
outputs = build_graph(device, input_shape, variable, num_inputs, axis, grad)
config = config_pb2.ConfigProto(graph_options=config_pb2.GraphOptions(optimizer_options=co... | Run the graph and print its execution time.
Args:
device: string, the device to run on.
input_shape: shape of the input tensors.
variable: whether or not the input shape should be fixed
num_inputs: the number of inputs to concat
axis: axis to be concat'ed
grad: if True compute the gradient
num_iters: number of steps t... | github-repos |
def wait_for_boot_completion(self, timeout=DEFAULT_TIMEOUT_BOOT_COMPLETION_SECOND):
timeout_start = time.time()
self.adb.wait_for_device(timeout=timeout)
while (time.time() < (timeout_start + timeout)):
try:
if self.is_boot_completed():
return
except adb.AdbError:... | Waits for Android framework to broadcast ACTION_BOOT_COMPLETED.
This function times out after 15 minutes.
Args:
timeout: float, the number of seconds to wait before timing out.
If not specified, no timeout takes effect. | codesearchnet |
def Open(self, file_object):
if not file_object:
raise ValueError('Missing file-like object.')
file_object.seek(0, os.SEEK_SET)
data = file_object.read(len(self._HEADER_SIGNATURE))
if data != self._HEADER_SIGNATURE:
file_object.close()
raise IOError('Unsupported ... | Opens the database file object.
Args:
file_object (FileIO): file-like object.
Raises:
IOError: if the SQLite database signature does not match.
OSError: if the SQLite database signature does not match.
ValueError: if the file-like object is invalid. | juraj-google-style |
def work_model_factory(*, validator=validators.is_work_model, **kwargs):
kwargs['ld_type'] = 'AbstractWork'
return _model_factory(validator=validator, **kwargs) | Generate a Work model.
Expects ``data``, ``validator``, ``model_cls``, and ``ld_context``
as keyword arguments.
Raises:
:exc:`ModelError`: If a non-'AbstractWork' ``ld_type`` keyword
argument is given. | codesearchnet |
def _get_head_block(self, request):
if request.head_id:
if (self._id_regex.fullmatch(request.head_id) is None):
LOGGER.debug('Invalid head id requested: %s', request.head_id)
raise _ResponseFailed(self._status.NO_ROOT)
try:
return self._block_store[request.head_id... | Fetches the request specified head block, or the chain head.
Note:
This method will fail if `_block_store` has not been set
Args:
request (object): The parsed protobuf request object
Returns:
Block: the block object at the head of the requested chain
Raises:
ResponseFailed: Failed to retrieve a head block | codesearchnet |
def non_deterministic_ints(shape, dtype=dtypes.int64):
return gen_stateful_random_ops.non_deterministic_ints(shape=shape, dtype=dtype) | Non-deterministically generates some integers.
This op may use some OS-provided source of non-determinism (e.g. an RNG), so
each execution will give different results.
Args:
shape: the shape of the result.
dtype: (optional) the dtype of the result.
Returns:
a tensor whose element values are non-deterministically cho... | github-repos |
def from_file_obj(cls, fp):
log.debug('Parsing email from file object')
try:
fp.seek(0)
except IOError:
pass
finally:
s = fp.read()
return cls.from_string(s) | Init a new object from a file-like object.
Not for Outlook msg.
Args:
fp (file-like object): file-like object of raw email
Returns:
Instance of MailParser | codesearchnet |
def find_library_windows(cls):
dll = cls.get_appropriate_windows_sdk_name() + '.dll'
root = 'C:\\'
for d in os.listdir(root):
dir_path = os.path.join(root, d)
if d.startswith('Program Files') and os.path.isdir(dir_path):
dir_path = o... | Loads the SEGGER DLL from the windows installation directory.
On Windows, these are found either under:
- ``C:\\Program Files\\SEGGER\\JLink``
- ``C:\\Program Files (x86)\\SEGGER\\JLink``.
Args:
cls (Library): the ``Library`` class
Returns:
The paths to the J-Link library files in the order that they are
found. | juraj-google-style |
def decrypt(key, ciphertext):
key = ''.join(key)
alphabet = string.ascii_letters
cipher_alphabet = (key.lower() + key.upper())
return ciphertext.translate(str.maketrans(cipher_alphabet, alphabet)) | Decrypt Simple Substitution enciphered ``ciphertext`` using ``key``.
Example:
>>> decrypt("PQSTUVWXYZCODEBRAKINGFHJLM", "XUOOB")
HELLO
Args:
key (iterable): The key to use
ciphertext (str): The text to decrypt
Returns:
Decrypted ciphertext | codesearchnet |
def upgrade_code(self):
if (not self.__squid):
return ''
have_scan_key = '{0}\\{1}\\{2}'.format(self.__reg_hive, self.__reg_upgradecode_path, self.__reg_32bit)
if ((not self.__upgrade_codes) or (self.__reg_key_guid not in self.__upgrade_codes)):
try:
uc_handle = win32api.RegOpenK... | For installers which follow the Microsoft Installer standard, returns
the ``Upgrade code``.
Returns:
value (str): ``Upgrade code`` GUID for installed software. | codesearchnet |
def get_arguments(context):
context.assert_key_has_value(key='pype', caller=__name__)
pype = context.get_formatted('pype')
try:
pipeline_name = pype['name']
if (pipeline_name is None):
raise KeyInContextHasNoValueError("pypyr.steps.pype ['pype']['name'] exists but is empty.")
... | Parse arguments for pype from context and assign default values.
Args:
context: pypyr.context.Context. context is mandatory.
Returns:
tuple (pipeline_name, #str
use_parent_context, #bool
pipe_arg, #str
skip_parse, #bool
raise_error #bool
)
Raises:
pypyr.errors.KeyNotInContextError: if ['pype']['name'] is missing.
py... | codesearchnet |
def get_protocol_version(protocol=None, target=None):
target = get_py_internals(target)
if protocol is None:
protocol = target['pickle_default_protocol']
if protocol > cPickle.HIGHEST_PROTOCOL:
warnings.warn('Downgrading pickle protocol, running python supports up to %d.' % cPickle.H... | Return a suitable pickle protocol version for a given target.
Arguments:
target: The internals description of the targeted python
version. If this is ``None`` the specification of the currently
running python version will be used.
protocol(None or int): The requested protocol version (or None for the
default of the ta... | juraj-google-style |
def preprocess_input(x, data_format=None):
return x | A placeholder method for backward compatibility.
The preprocessing logic has been included in the convnext model
implementation. Users are no longer required to call this method to
normalize the input data. This method does nothing and only kept as a
placeholder to align the API surface between old and new version of ... | github-repos |
def generate_packer_filename(provider, region, builder):
filename = '{0}_{1}_{2}.json'.format(provider, region, builder)
return filename | Generate a filename to be used by packer.
Args:
provider (str): Name of Spinnaker provider.
region (str): Name of provider region to use.
builder (str): Name of builder process type.
Returns:
str: Generated filename based on parameters. | codesearchnet |
def get_ip_address_country(ip_address, parallel=False):
def download_country_database(location="GeoLite2-Country.mmdb"):
if parallel:
logging.warning("Cannot download GeoIP database in parallel mode")
return
url = "https:
"GeoLite2-Country.tar.gz"
... | Uses the MaxMind Geolite2 Country database to return the ISO code for the
country associated with the given IPv4 or IPv6 address
Args:
ip_address (str): The IP address to query for
parallel (bool): Parallel processing
Returns:
str: And ISO country code associated with the given IP address | juraj-google-style |
def as_money(self, number, **options):
if isinstance(number, list):
return map((lambda val: self.as_money(val, **options)))
decimal = options.get('decimal')
number = self.parse(number, decimal)
if check_type(options, 'dict'):
options = self.settings['currency'].update(options)
format... | Format a number into currency.
Usage: accounting.formatMoney(number, symbol, precision, thousandsSep,
decimalSep, format)
defaults: (0, "$", 2, ",", ".", "%s%v")
Localise by overriding the symbol, precision,
thousand / decimal separators and format
Second param can be an object matching `settings.currency`
which is th... | codesearchnet |
def sun_events(latitude, longitude, date, timezone=0, zenith=None):
return (sun_rise_set(latitude, longitude, date, 'rise', timezone, zenith), sun_rise_set(latitude, longitude, date, 'set', timezone, zenith)) | Convenience function for calculating sunrise and sunset.
Civil twilight starts/ends when the Sun's centre is 6 degrees below
the horizon.
Nautical twilight starts/ends when the Sun's centre is 12 degrees
below the horizon.
Astronomical twilight starts/ends when the Sun's centre is 18 degrees below
the horizon.
Args... | codesearchnet |
def parse_functions(
bels: list, char_locs: CharLocs, parsed: Parsed, errors: Errors
) -> Tuple[Parsed, Errors]:
parens = char_locs["parens"]
if not parens:
bels_len = len(bels) - 1
span = (0, bels_len)
parsed[span] = {
"name": "".join(bels),
"type"... | Parse functions from BEL using paren, comma, quote character locations
Args:
bels: BEL string as list of chars
char_locs: paren, comma, quote character locations
errors: Any error messages generated during the parse
Returns:
(functions, errors): function names and locations and error messages | juraj-google-style |
def url(self, pattern, method=None, name=None):
def _inner(call):
self._url_manager.add(pattern, method, call, name)
return call
return _inner | Decorator to map url pattern to the callable.
Args:
pattern (:obj:`str`): URL pattern to add. This is usually '/'
separated path. Parts of the URL can be parameterised using
curly braces.
Examples: "/", "/path/to/resource", "/resoures/{param}"
method (:obj:`str`, :obj:`list` of :obj:`str`, optional): HTTP
methods for ... | codesearchnet |
def _get_colordata(bs, elements, bs_projection):
contribs = {}
if bs_projection and bs_projection.lower() == "elements":
projections = bs.get_projection_on_elements()
for spin in (Spin.up, Spin.down):
if spin in bs.bands:
contribs[spin] = []
... | Get color data, including projected band structures
Args:
bs: Bandstructure object
elements: elements (in desired order) for setting to blue, red, green
bs_projection: None for no projection, "elements" for element projection
Returns: | juraj-google-style |
def _alter_code(code, **attrs):
PyCode_New = ctypes.pythonapi.PyCode_New
PyCode_New.argtypes = (ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.py_object, ctypes.py_object, ctypes.py_object, ctypes.py_object, ctypes.py_object, ctypes.py_object, ctypes.py_object, ctypes.py_object, ct... | Create a new code object by altering some of ``code`` attributes
Args:
code: code objcect
attrs: a mapping of names of code object attrs to their values | codesearchnet |
def all_cities():
cities = []
fname = pkg_resources.resource_filename(__name__, 'resources/CityPops.csv')
with open(fname, 'rU') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
cities.append(row[0])
cities.sort()
return cities | Get a list of all Backpage city names.
Returns:
list of city names as Strings | codesearchnet |
def BuildParamsWithMask(self, graph_fn, dtype, input_shapes, output_shapes, input_mask, output_mask, extra_inputs, extra_outputs):
def _ValidateShapes(shapes):
for shape in shapes:
assert all(shape), f'Shape unspecified: {shape}'
_ValidateShapes(input_shapes)
_ValidateShapes(output_shap... | Build test parameters with static or dynamic input shapes.
To define dynamic shapes give a boolean mask that describes which
dimensions to treat as known. The values in input_mask are interpreted the
following way:
- True: known dim (use the corresponding value from input_shapes)
- False: unknown dim (replace the corr... | github-repos |
def process_file(filename: str,
filetypes: List[str],
move_to: str,
delete_if_not_specified_file_type: bool,
show_zip_output: bool) -> None:
try:
reader = CorruptedOpenXmlReader(filename,
sh... | Deals with an OpenXML, including if it is potentially corrupted.
Args:
filename: filename to process
filetypes: list of filetypes that we care about, e.g.
``['docx', 'pptx', 'xlsx']``.
move_to: move matching files to this directory
delete_if_not_specified_file_type: if ``True``, and the file is **not**
a type specifie... | juraj-google-style |
def get_book_progress(self, asin):
kbp = self._get_api_call('get_book_progress', ('"%s"' % asin))
return KindleCloudReaderAPI._kbp_to_progress(kbp) | Returns the progress data available for a book.
NOTE: A summary of the two progress formats can be found in the
docstring for `ReadingProgress`.
Args:
asin: The asin of the book to be queried.
Returns:
A `ReadingProgress` instance corresponding to the book associated with
`asin`. | codesearchnet |
def add_toolkit(topology, location):
import streamsx.topology.topology
assert isinstance(topology, streamsx.topology.topology.Topology)
tkinfo = dict()
tkinfo['root'] = os.path.abspath(location)
topology.graph._spl_toolkits.append(tkinfo) | Add an SPL toolkit to a topology.
Args:
topology(Topology): Topology to include toolkit in.
location(str): Location of the toolkit directory. | juraj-google-style |
def get_obj(self, objpath, metahash, dst_path):
incachepath = self.path_in_cache(objpath, metahash)
if not os.path.exists(incachepath):
raise CacheMiss('%s not in cache.' % incachepath)
else:
log.debug('Cache hit! %s~%s', objpath, metahash.hexdigest())
... | Get object from cache, write it to dst_path.
Args:
objpath: filename relative to buildroot
(example: mini-boot/blahblah/somefile.bin)
metahash: metahash. See targets/base.py
dst_path: Absolute path where the file should be written.
Raises:
CacheMiss: if the item is not in the cache | juraj-google-style |
def is_generator_function(obj):
CO_GENERATOR = 32
return bool(((inspect.isfunction(obj) or inspect.ismethod(obj)) and (obj.func_code.co_flags & CO_GENERATOR))) | Return true if the object is a user-defined generator function.
Generator function objects provides same attributes as functions.
See isfunction.__doc__ for attributes listing.
Adapted from Python 2.6.
Args:
obj: an object to test.
Returns:
true if the object is generator function. | codesearchnet |
def _log_submission(submission, student_item):
logger.info(u'Created submission uuid={submission_uuid} for (course_id={course_id}, item_id={item_id}, anonymous_student_id={anonymous_student_id})'.format(submission_uuid=submission['uuid'], course_id=student_item['course_id'], item_id=student_item['item_id'], anonymo... | Log the creation of a submission.
Args:
submission (dict): The serialized submission model.
student_item (dict): The serialized student item model.
Returns:
None | codesearchnet |
def GetFileEntryByPath(self, path):
if path is None:
return None
file_entry_type, _ = self._paths.get(path, (None, None))
if not file_entry_type:
return None
path_spec = fake_path_spec.FakePathSpec(location=path)
return fake_file_entry.FakeFileEntry(
self._resolver_context... | Retrieves a file entry for a path.
Args:
path (str): path of the file entry.
Returns:
FakeFileEntry: a file entry or None if not available. | juraj-google-style |
def pmean(tensor, axis_name=None):
if axis_name != _pmap_config.axis_name():
raise ValueError('axis_name (%s) is not equal to that of the surrounding pmap (%s)' % (axis_name, _pmap_config.axis_name()))
devices = _pmap_config.devices()
if devices is None:
raise ValueError("Can't retrieve the ... | Mean all-reduction.
Args:
tensor: A tensor.
axis_name: The axis name to reduce. Must equal to that of the surrounding
pmap.
Returns:
The mean of the `tensor` replicas on each participating devices. | github-repos |
def defaults(cls, *options, **kwargs):
if kwargs and len(kwargs) != 1 and list(kwargs.keys())[0] != 'backend':
raise Exception('opts.defaults only accepts "backend" keyword argument')
cls._linemagic(cls._expand_options(merge_options_to_dict(options)), backend=kwargs.get('backend')) | Set default options for a session.
Set default options for a session. whether in a Python script or
a Jupyter notebook.
Args:
*options: Option objects used to specify the defaults.
backend: The plotting extension the options apply to | juraj-google-style |
def abort_expired_batches(self, request_timeout_ms, cluster):
expired_batches = []
to_remove = []
count = 0
for tp in list(self._batches.keys()):
assert (tp in self._tp_locks), 'TopicPartition not in locks dict'
if (tp in self.muted):
continue
with self._tp_locks[tp]:... | Abort the batches that have been sitting in RecordAccumulator for
more than the configured request_timeout due to metadata being
unavailable.
Arguments:
request_timeout_ms (int): milliseconds to timeout
cluster (ClusterMetadata): current metadata for kafka cluster
Returns:
list of ProducerBatch that were expired | codesearchnet |
def on_snapshot(self, proto):
TargetChange = firestore_pb2.TargetChange
target_changetype_dispatch = {TargetChange.NO_CHANGE: self._on_snapshot_target_change_no_change, TargetChange.ADD: self._on_snapshot_target_change_add, TargetChange.REMOVE: self._on_snapshot_target_change_remove, TargetChange.RESET: self._o... | Called everytime there is a response from listen. Collect changes
and 'push' the changes in a batch to the customer when we receive
'current' from the listen response.
Args:
listen_response(`google.cloud.firestore_v1beta1.types.ListenResponse`):
Callback method that receives a object to | codesearchnet |
def GetLastHealthyElement(self):
for element in reversed(self.elements):
if not element.HasError():
return element
return self.elements[0] | Returns the last element of the trace that is not an error.
This element will contain the final component indicated by the trace.
Returns:
The last element of the trace that is not an error. | github-repos |
def __init__(self, args):
self.args = args.args
self.varargs = args.vararg
self.kwarg = args.kwarg
self.kwonlyargs = args.kwonlyargs
self.defaults = args.defaults
self.kw_defaults = args.kw_defaults
self.arguments = list()
if self.args:
... | Argument container class.
Args:
args(list(ast.args): The arguments in a function AST node. | juraj-google-style |
def build_cfg(cls, node):
if not isinstance(node, gast.FunctionDef):
raise TypeError('input must be a function definition')
cfg = cls()
cfg.entry = Node(node.args)
cfg.head = [cfg.entry]
cfg.visit_statements(node.body)
cfg.exit = Node(None)
cfg.set_head(cfg.exit)
cfg.backlink(... | Build a CFG for a function.
Args:
node: A function definition the body of which to analyze.
Returns:
A CFG object.
Raises:
TypeError: If the input is not a function definition. | juraj-google-style |
def pairwise_intersection(boxlist1, boxlist2):
x_min1, y_min1, x_max1, y_max1 = tf.split(boxlist1, 4, axis=1)
x_min2, y_min2, x_max2, y_max2 = tf.split(boxlist2, 4, axis=1)
all_pairs_min_ymax = tf.minimum(y_max1, tf.transpose(y_max2))
all_pairs_max_ymin = tf.maximum(y_min1, tf.transpose(y_min2))
... | Compute pairwise intersection areas between boxes.
Args:
boxlist1: Nx4 floatbox
boxlist2: Mx4
Returns:
a tensor with shape [N, M] representing pairwise intersections | juraj-google-style |
def transformer_revnet_decoder(decoder_input,
encoder_output,
decoder_self_attention_bias,
encoder_decoder_attention_bias,
hparams,
name="decoder"):
def f(x, s... | A stack of transformer layers.
Args:
decoder_input: a Tensor
encoder_output: a Tensor
decoder_self_attention_bias: bias Tensor for self-attention
(see common_attention.attention_bias())
encoder_decoder_attention_bias: bias Tensor for encoder-decoder attention
(see common_attention.attention_bias())
hparams: hyperparam... | juraj-google-style |
def gather_available_device_info():
device_info_list = []
devices = device_lib.list_local_devices()
for d in devices:
device_info = test_log_pb2.AvailableDeviceInfo()
device_info.name = d.name
device_info.type = d.device_type
device_info.memory_limit = d.memory_limit
... | Gather list of devices available to TensorFlow.
Returns:
A list of test_log_pb2.AvailableDeviceInfo messages. | github-repos |
def restore(self, state):
own_properties = set(self.get_properties())
state_properties = set(state)
to_restore = own_properties.intersection(state_properties)
for name in to_restore:
value = state.get(name)
if name in self._complex_properties:
... | Restore this state from the output of a previous call to dump().
Only those properties in this object and listed in state will be
updated. Other properties will not be modified and state may contain
keys that do not correspond with properties in this object.
Args:
state (dict): A serialized representation of this ob... | juraj-google-style |
def set(self, **kwargs):
for (port_name, port_value) in kwargs.items():
if hasattr(port_value, 'value'):
port_value = port_value.value
self.inputs.__setattr__(port_name, port_value) | Set input values on task
Args:
arbitrary_keys: values for the keys
Returns:
None | codesearchnet |
def matches(x, y, regex_expr=False):
x = strip_regex(x) if regex_expr and isregex_expr(x) else x
if PY_3:
x = x.pattern if isregex(x) else x
return test_case().assertRegex(y, x) or True
if isinstance(x, str):
x = re.compile(x, re.IGNORECASE)
... | Tries to match a regular expression value ``x`` against ``y``.
Aliast``unittest.TestCase.assertEqual()``
Arguments:
x (regex|str): regular expression to test.
y (str): value to match.
regex_expr (bool): enables regex string based expression matching.
Raises:
AssertionError: in case of mismatching.
Returns:
bool | juraj-google-style |
def local_reduction_attention(x, block_length, multihead_params):
@expert_utils.add_name_scope()
def dot_product_self_local_attention_flattened(q, k, v):
'Strided block local self-attention.\n\n No overlap between the blocks.\n\n Args:\n q (tf.Tensor): shape [batch, heads, length, depth_k]\n... | Reduce the length dimension using self attention.
Args:
x (tf.Tensor): float32 of shape [batch, length, depth]
block_length (int): Block length for local attention (Compression factor)
multihead_params (dict): parameters for multihead attention
Returns:
tf.Tensor: Compressed tensor of shape [batch, length // factor, ... | codesearchnet |
def _restore_checkpoint(self, master: str, saver: saver_lib.Saver=None, checkpoint_dir: str=None, checkpoint_filename_with_path: str=None, wait_for_checkpoint=False, max_wait_secs=7200, config=None) -> Tuple[session.Session, bool]:
self._target = master
strategy = distribute_lib.get_strategy()
if strategy a... | Creates a `Session`, and tries to restore a checkpoint.
Args:
master: `String` representation of the TensorFlow master to use.
saver: A `Saver` object used to restore a model.
checkpoint_dir: Path to the checkpoint files. The latest checkpoint in the
dir will be used to restore.
checkpoint_filename_with_path: Full fi... | github-repos |
def GetModifyTimestamp(self):
if self.modify_time is None:
self.modify_time = self._ReadTimestamp(self.modify_file)
return self.modify_time | Return the timestamp of the last cache modification.
Args: None
Returns:
An int with the number of seconds since epoch, or None if the timestamp
file doesn't exist or has errors. | github-repos |
def decode_metar(self, metar):
try:
from metar import Metar
except:
return "Unable to parse metars. Please install parser from https:
m = Metar.Metar(metar)
return m.string() | Simple method that decodes a given metar string.
Args:
metar (str): The metar data
Returns:
The metar data in readable format
Example::
from pyflightdata import FlightData
f=FlightData()
f.decode_metar('WSSS 181030Z 04009KT 010V080 9999 FEW018TCU BKN300 29/22 Q1007 NOSIG') | juraj-google-style |
def touch(self, mode=438, exist_ok=True):
if self._closed:
self._raise_closed()
if self.exists():
if exist_ok:
self.filesystem.utime(self._path(), None)
else:
self.filesystem.raise_os_error(errno.EEXIST, self._path())
else:
fake_file = self.open('w')
... | Create a fake file for the path with the given access mode,
if it doesn't exist.
Args:
mode: the file mode for the file if it does not exist
exist_ok: if the file already exists and this is True, nothing
happens, otherwise FileExistError is raised
Raises:
OSError: (Python 2 only) if the file exists and exits_ok is Fa... | codesearchnet |
def GetClientURNsForHostnames(hostnames, token=None):
if data_store.RelationalDBEnabled():
index = ClientIndex()
else:
index = CreateClientIndex(token=token)
keywords = set()
for hostname in hostnames:
if hostname.startswith("host:"):
keywords.add(hostname)
else:
keywords.add("h... | Gets all client_ids for a given list of hostnames or FQDNS.
Args:
hostnames: A list of hostnames / FQDNs.
token: An ACL token.
Returns:
A dict with a list of all known GRR client_ids for each hostname. | juraj-google-style |
def _process_has_edge_degree_filter_directive(filter_operation_info, location, context, parameters):
if isinstance(filter_operation_info.field_ast, InlineFragment):
raise AssertionError(u'Received InlineFragment AST node in "has_edge_degree" filter handler. This should have been caught earlier: {}'.format(f... | Return a Filter basic block that checks the degree of the edge to the given vertex field.
Args:
filter_operation_info: FilterOperationInfo object, containing the directive and field info
of the field where the filter is to be applied.
location: Location where this filter is used.
context: dict, various per-compilation... | codesearchnet |
def sg_inject(path, mod_name):
import sys
if (path not in list(sys.path)):
sys.path.append(path)
globals()[mod_name] = importlib.import_module(mod_name)
for func_name in dir(globals()[mod_name]):
if isinstance(globals()[mod_name].__dict__.get(func_name), types.FunctionType):
... | r"""Converts all functions in the given Python module to sugar functions
so that they can be used in a chainable manner.
Args:
path: A string. Path to the Python module
mod_name: A string. The name of the Python module to inject.
Returns:
None | codesearchnet |
def serialize_cert_to_der(cert_obj):
return cert_obj.public_bytes(
cryptography.hazmat.primitives.serialization.Encoding.DER
) | Serialize certificate to DER.
Args:
cert_obj: cryptography.Certificate
Returns:
bytes: DER encoded certificate | juraj-google-style |
def set_key_color(self, color: Tuple[(int, int, int)]) -> None:
lib.TCOD_image_set_key_color(self.image_c, color) | Set a color to be transparent during blitting functions.
Args:
color (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance. | codesearchnet |
def all_sample_md5s(self, type_tag=None):
if type_tag:
cursor = self.database[self.sample_collection].find({'type_tag': type_tag}, {'md5': 1, '_id': 0})
else:
cursor = self.database[self.sample_collection].find({}, {'md5': 1, '_id': 0})
return [match.values()[0]... | Return a list of all md5 matching the type_tag ('exe','pdf', etc).
Args:
type_tag: the type of sample.
Returns:
a list of matching samples. | juraj-google-style |
def _to_key_ranges_by_shard(cls, app, namespaces, shard_count, query_spec):
key_ranges_by_ns = []
for namespace in namespaces:
ranges = cls._split_ns_by_scatter(shard_count, namespace, query_spec.entity_kind, app)
random.shuffle(ranges)
key_ranges_by_ns.append(ranges)
ranges_by_shard... | Get a list of key_ranges.KeyRanges objects, one for each shard.
This method uses scatter index to split each namespace into pieces
and assign those pieces to shards.
Args:
app: app_id in str.
namespaces: a list of namespaces in str.
shard_count: number of shards to split.
query_spec: model.QuerySpec.
Returns:
a list... | codesearchnet |
def run_simulations(self, parameter_list, data_folder):
self.data_folder = data_folder
with Pool(processes=MAX_PARALLEL_PROCESSES) as pool:
for result in pool.imap_unordered(self.launch_simulation,
parameter_list):
yield ... | This function runs multiple simulations in parallel.
Args:
parameter_list (list): list of parameter combinations to simulate.
data_folder (str): folder in which to create output folders. | juraj-google-style |
def filter_cold_days(input_data, month_filter):
projection_fields = ['year', 'month', 'day', 'mean_temp']
fields_of_interest = input_data | 'Projected' >> beam.Map(lambda row: {f: row[f] for f in projection_fields})
global_mean = AsSingleton(fields_of_interest | 'ExtractMean' >> beam.Map(lambda row: row['me... | Workflow computing rows in a specific month with low temperatures.
Args:
input_data: a PCollection of dictionaries representing table rows. Each
dictionary must have the keys ['year', 'month', 'day', and 'mean_temp'].
month_filter: an int representing the month for which colder-than-average
days should be returned.
R... | github-repos |
def to_routing_header(params):
if (sys.version_info[0] < 3):
return urlencode(params).replace('%2F', '/')
return urlencode(params, safe='/') | Returns a routing header string for the given request parameters.
Args:
params (Mapping[str, Any]): A dictionary containing the request
parameters used for routing.
Returns:
str: The routing header string. | codesearchnet |
def insert_and_get(self, **fields):
if ((not self.conflict_target) and (not self.conflict_action)):
return super().create(**fields)
compiler = self._build_insert_compiler([fields])
rows = compiler.execute_sql(return_id=False)
columns = rows[0]
model_columns = {}
for field in self.model._... | Creates a new record in the database and then gets
the entire row.
This allows specifying custom conflict behavior using .on_conflict().
If no special behavior was specified, this uses the normal Django create(..)
Arguments:
fields:
The fields of the row to create.
Returns:
The model instance representing the row th... | codesearchnet |
def get_hyperparameters(self):
hyperparameters = {}
for (block_name, block) in self.blocks.items():
hyperparameters[block_name] = block.get_hyperparameters()
return hyperparameters | Get the current hyperparamters of each block.
Returns:
dict:
A dictionary containing the block names as keys and
the current block hyperparameters dictionary as values. | codesearchnet |
def adapt_logger(logger):
if isinstance(logger, logging.Logger):
return logger
if isinstance(logger, (SimpleLogger, NoOpLogger)):
return logger.logger
return logger | Adapt our custom logger.BaseLogger object into a standard logging.Logger object.
Adaptations are:
- NoOpLogger turns into a logger with a single NullHandler.
- SimpleLogger turns into a logger with a StreamHandler and level.
Args:
logger: Possibly a logger.BaseLogger, or a standard python logging.Logger.
Returns: a ... | juraj-google-style |
def _MakePackagePages(self, package, showprivate=False, nested=False, showinh=False):
def checkNoNested(mod):
try:
all = mod.__all__
except AttributeError:
return False
mems = inspect.getmembers(mod, inspect.ismodule)
mems... | An internal helper to generate all of the pages for a given package
Args:
package (module): The top-level package to document
showprivate (bool): A flag for whether or not to display private members
nested (bool): Foor internal use ONLY
Returns:
str: The file names ready to be appended to a top-level toctree | juraj-google-style |
def assertAllDifferent(self, tensors):
tensors = [array_ops.reshape(t, shape=[-1]) for t in tensors]
ls = array_ops.concat(tensors, axis=0).numpy().tolist()
self.assertAllEqual(len(ls), len(set(ls))) | Checks that there are no duplicate elements anywhere among the tensors.
Args:
tensors: a list of tensors. They can have different shapes. | github-repos |
def email(self, subject, text_body, html_body=None, sender=None, **kwargs):
self.configuration.emailer().send([self.data['email']], subject, text_body, html_body=html_body, sender=sender, **kwargs) | Emails a user.
Args:
subject (str): Email subject
text_body (str): Plain text email body
html_body (str): HTML email body
sender (Optional[str]): Email sender. Defaults to SMTP username.
**kwargs: See below
mail_options (List): Mail options (see smtplib documentation)
rcpt_options (List): Recipient options (see smtpli... | codesearchnet |
def delete(self, webhookId):
check_type(webhookId, basestring, may_be_none=False)
self._session.delete(((API_ENDPOINT + '/') + webhookId)) | Delete a webhook, by ID.
Args:
webhookId(basestring): The ID of the webhook to be deleted.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error. | codesearchnet |
def ApprovalRevokeRaw(aff4_path, token):
try:
urn = rdf_client.ClientURN(aff4_path)
except type_info.TypeValueError:
urn = rdfvalue.RDFURN(aff4_path)
approval_urn = aff4.ROOT_URN.Add("ACL").Add(urn.Path()).Add(
token.username).Add(utils.EncodeReasonString(token.reason))
super_token = access_c... | Revokes an approval for a given token.
This method requires raw datastore access to manipulate approvals directly.
Args:
aff4_path: The aff4_path or client id the approval should be created for.
token: The token that should be revoked. | juraj-google-style |
def parse_from_xml(root):
if (root.tag != 'ubcpi'):
raise UpdateFromXmlError(_('Every peer instruction tool must contain an "ubcpi" element.'))
display_name_el = root.find('display_name')
if (display_name_el is None):
raise UpdateFromXmlError(_('Every peer instruction tool must contain a "di... | Update the UBCPI XBlock's content from an XML definition.
We need to be strict about the XML we accept, to avoid setting
the XBlock to an invalid state (which will then be persisted).
Args:
root (lxml.etree.Element): The XML definition of the XBlock's content.
Returns:
A dictionary of all of the XBlock's content.
R... | codesearchnet |
def __init__(self, access_token, access_token_type, refresh_token=None, expires_in=None, state=None):
self.access_token = access_token
self.access_token_type = access_token_type
self.refresh_token = refresh_token
self.expires_in = expires_in
self.state = state | Initialziation of the object
Args:
access_token (str): Access token
access_token_type (str): Access token type
refresh_token (str):
expires_in (int): Seconds after which the token will expire
state (str): | juraj-google-style |
def __new__(cls, month=1, day=1, hour=0, minute=0, leap_year=False):
year = 2016 if leap_year else 2017
hour, minute = cls._calculate_hour_and_minute(hour + minute / 60.0)
try:
return datetime.__new__(cls, year, month, day, hour, minute)
except ValueError as e:
... | Create Ladybug datetime.
Args:
month: A value for month between 1-12 (Defualt: 1).
day: A value for day between 1-31 (Defualt: 1).
hour: A value for hour between 0-23 (Defualt: 0).
minute: A value for month between 0-59 (Defualt: 0).
leap_year: A boolean to indicate if datetime is for a leap year
(Default: False). | juraj-google-style |
def plot_densities(self, ax=None, **kwargs):
(ax, fig, plt) = get_ax_fig_plt(ax)
ax.grid(True)
ax.set_xlabel('r [Bohr]')
for (i, den_name) in enumerate(['ae_core_density', 'pseudo_core_density']):
rden = getattr(self, den_name)
label = ('$n_c$' if (i == 1) else '$\\tilde{n}_c$')
... | Plot the PAW densities.
Args:
ax: matplotlib :class:`Axes` or None if a new figure should be created.
Returns:
`matplotlib` figure | codesearchnet |
def GetArtifactCollectorArgs(flow_args, knowledge_base):
args = rdf_artifacts.ClientArtifactCollectorArgs()
args.knowledge_base = knowledge_base
args.apply_parsers = flow_args.apply_parsers
args.ignore_interpolation_errors = flow_args.ignore_interpolation_errors
args.max_file_size = flow_args.max_fi... | Prepare bundle of artifacts and their dependencies for the client.
Args:
flow_args: An `ArtifactCollectorFlowArgs` instance.
knowledge_base: contains information about the client
Returns:
rdf value object containing a list of extended artifacts and the
knowledge base | codesearchnet |
def is_uniform(self):
return self._uniform_row_length is not None | Returns true if the partition is known to be uniform statically.
This is based upon the existence of self._uniform_row_length. For example:
RowPartition.from_row_lengths([3,3,3]).is_uniform()==false
RowPartition.from_uniform_row_length(5, nvals=20).is_uniform()==true
RowPartition.from_row_lengths([2,0,2]).is_uniform()... | github-repos |
def visualize_reconstruction(inputs, reconstruct, num=3, name='reconstruction'):
reconstruct = tf.clip_by_value(reconstruct, 0.0, 1.0)
inputs_and_reconstruct = tf.concat((inputs[:num], reconstruct[:num]), axis=0)
image_summary(inputs_and_reconstruct, name) | Visualizes the reconstruction of inputs in TensorBoard.
Args:
inputs: A tensor of the original inputs, of shape [batch, timesteps,
h, w, c].
reconstruct: A tensor of a reconstruction of inputs, of shape
[batch, timesteps, h, w, c].
num: Integer for the number of examples to visualize.
name: String name of this summary... | codesearchnet |
def Detect(self, baseline, host_data):
result = CheckResult()
for detector in self.detectors:
finding = detector(baseline, host_data)
if finding:
result.ExtendAnomalies([finding])
if result:
return result | Run host_data through detectors and return them if a detector triggers.
Args:
baseline: The base set of rdf values used to evaluate whether an issue
exists.
host_data: The rdf values passed back by the filters.
Returns:
A CheckResult message containing anomalies if any detectors identified an
issue, None otherwise. | codesearchnet |
def GetEnabledInterfaces():
interfaces = []
show_args = ['/c', 'netsh', 'show', 'interface']
res = client_utils_common.Execute('cmd', show_args, time_limit=(- 1), bypass_whitelist=True)
pattern = re.compile('\\s*')
for line in res[0].split('\r\n'):
interface_info = pattern.split(line)
... | Gives a list of enabled interfaces. Should work on all windows versions.
Returns:
interfaces: Names of interfaces found enabled. | codesearchnet |
def get_port_monitor(self):
uri = '{}{}'.format(self.data['uri'], self.PORT_MONITOR_PATH)
return self._helper.do_get(uri) | Gets the port monitor configuration of a logical interconnect.
Returns:
dict: The Logical Interconnect. | codesearchnet |
def get_countries_in_region(cls, region, use_live=True, exception=None):
countriesdata = cls.countriesdata(use_live=use_live)
if isinstance(region, int):
regioncode = region
else:
regionupper = region.upper()
regioncode = countriesdata['regio... | Get countries (ISO3 codes) in region
Args:
region (Union[int,str]): Three digit UNStats M49 region code or region name
use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.
exception (Optional[ExceptionUpperBound]): An exception to raise if region not found. Defaults to No... | juraj-google-style |
def get_updates(
self,
display_all_distributions=False,
verbose=False
):
if verbose:
logging.basicConfig(
stream=sys.stdout,
level=logging.INFO,
format='%(message)s',
)
logging.info('Checki... | When called, get the environment updates and write updates to a CSV
file and if a new config has been provided, write a new configuration
file.
Args:
display_all_distributions (bool): Return distribution even if it is
up-to-date.
verbose (bool): If ``True``, log to terminal to terminal. | juraj-google-style |
def get_data(name, train_batch_size, test_batch_size):
if name not in ['mnist', 'cifar10']:
raise ValueError(
'Expected dataset \'mnist\' or \'cifar10\', but got %s' % name)
dataset = getattr(tf.keras.datasets, name)
num_classes = 10
raw_data = dataset.load_data()
(images_train, labels_trai... | Gets training and testing dataset iterators.
Args:
name: String. Name of dataset, either 'mnist' or 'cifar10'.
train_batch_size: Integer. Batch size for training.
test_batch_size: Integer. Batch size for testing.
Returns:
Dict containing:
train_iterator: A tf.data.Iterator, over training data.
test_iterator: A tf.dat... | juraj-google-style |
def QueryAllFeatures(self, url=None, where='1=1', out_fields='*', timeFilter=None, geometryFilter=None, returnFeatureClass=False, out_fc=None, outSR=None, chunksize=1000, printIndent=''):
if (url is None):
return
fl = None
try:
fl = FeatureLayer(url=url, securityHandler=self._securityHandler... | Performs an SQL query against a hosted feature service layer
and returns all features regardless of service limit.
Args:
url (str): The URL of the feature service layer.
where - the selection sql statement
out_fields - the attribute fields to return
timeFilter - a TimeFilter object where either the start time
or start... | codesearchnet |
def description(self, force_refresh=False):
if force_refresh:
self.clear_cache()
if (not self._tuning_job_describe_result):
self._tuning_job_describe_result = self._sage_client.describe_hyper_parameter_tuning_job(HyperParameterTuningJobName=self.name)
return self._tuning_job_describe_result | Call ``DescribeHyperParameterTuningJob`` for the hyperparameter tuning job.
Args:
force_refresh (bool): Set to True to fetch the latest data from SageMaker API.
Returns:
dict: The Amazon SageMaker response for ``DescribeHyperParameterTuningJob``. | codesearchnet |
def __init__(self, parent):
super(ModuleUIFrame, self).__init__(parent)
self.columnconfigure(0, weight=1)
self.rowconfigure(1, weight=1)
from ....datatools import get_data
data = get_data()
api_frame = ttk.LabelFrame(self, padding=8, text="Go... | Create a new UI for the module
Args:
parent: A tk or ttk object | juraj-google-style |
def get_barycenter(self):
try:
mass = self['mass'].values
except KeyError:
mass = self.add_data('mass')['mass'].values
pos = self.loc[(:, ['x', 'y', 'z'])].values
return ((pos * mass[(:, None)]).sum(axis=0) / self.get_total_mass()) | Return the mass weighted average location.
Args:
None
Returns:
:class:`numpy.ndarray`: | codesearchnet |
def createList(self, title=None, items=None):
if items is None:
items = []
node = _node.List()
if title is not None:
node.title = title
for text, checked in items:
node.add(text, checked)
self.add(node)
return node | Create a new list and populate it. Any changes to the note will be uploaded when :py:meth:`sync` is called.
Args:
title (str): The title of the list.
items (List[(str, bool)]): A list of tuples. Each tuple represents the text and checked status of the listitem.
Returns:
gkeepapi.node.List: The new list. | juraj-google-style |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.