code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def bbox2distance(points, bbox, max_num_bins, reg_scale, up, eps=0.1):
reg_scale = abs(reg_scale)
left = (points[:, 0] - bbox[:, 0]) / (points[..., 2] / reg_scale + 1e-16) - 0.5 * reg_scale
top = (points[:, 1] - bbox[:, 1]) / (points[..., 3] / reg_scale + 1e-16) - 0.5 * reg_scale
right = (bbox[:, 2] - p... | Converts bounding box coordinates to distances from a reference point.
Args:
points (Tensor): (n, 4) [x, y, w, h], where (x, y) is the center.
bbox (Tensor): (n, 4) bounding boxes in "xyxy" format.
max_num_bins (float): Maximum bin value.
reg_scale (float): Controlling curvarture of W(n).
up (Tensor): Controlling uppe... | github-repos |
def set_help_intro(self, help_intro):
self._help_intro = help_intro | Set an introductory message to help output.
Args:
help_intro: (RichTextLines) Rich text lines appended to the
beginning of the output of the command "help", as introductory
information. | github-repos |
def register(self, cmd: Type[Command]) -> None:
self.commands[cmd.command] = cmd | Register a new IMAP command.
Args:
cmd: The new command type. | juraj-google-style |
def qry_create(options):
qry_string = filt_end = param_str = ""
filt_st = "Filters=["
param_str_default = "All"
if options.id:
qry_string += "InstanceIds=['%s']" % (options.id)
param_str += "id: '%s'" % (options.id)
param_str_default = ""
if options.instname:
(... | Create query from the args specified and command chosen.
Creates a query string that incorporates the args in the options
object, and creates the title for the 'list' function.
Args:
options (object): contains args and data from parser
Returns:
qry_string (str): the query to be used against the aws ec2 client.
param_... | juraj-google-style |
def realtime(widget, url_name=None, url_regex=None, time_interval=None):
if (not hasattr(widget, 'get_updated_content')):
raise AttributeError(('Widget %s must implement get_updated_content method.' % widget))
elif (not callable(widget.get_updated_content)):
raise ValueError(('get_updated_conten... | Return a widget as real-time.
Args:
widget (Widget): the widget to register and return as real-time.
url_name (str): the URL name to call to get updated content.
url_regex (regex): the URL regex to be matched.
time_interval (int): the interval of refreshment in milliseconds.
Returns:
Widget: the "real-timed" widget. | codesearchnet |
def remove(self, force=False):
return self.client.api.remove_node(self.id, force=force) | Remove this node from the swarm.
Args:
force (bool): Force remove an active node. Default: `False`
Returns:
`True` if the request was successful.
Raises:
:py:class:`docker.errors.NotFound`
If the node doesn't exist in the swarm.
:py:class:`docker.errors.APIError`
If the server returns an error. | juraj-google-style |
def extend_validators(raw_validators, override_validators):
if (not raw_validators):
return override_validators
elif (not override_validators):
return raw_validators
else:
def_validators_mapping = _convert_validators_to_mapping(raw_validators)
ref_validators_mapping = _conver... | extend raw_validators with override_validators.
override_validators will merge and override raw_validators.
Args:
raw_validators (dict):
override_validators (dict):
Returns:
list: extended validators
Examples:
>>> raw_validators = [{'eq': ['v1', 200]}, {"check": "s2", "expect": 16, "comparator": "len_eq"}]
>>> overr... | codesearchnet |
def create_issue(self, data, params=None):
return self._post((self.API_URL + 'issue'), data=data, params=params) | Creates an issue or a sub-task from a JSON representation.
You can provide two parameters in request's body: update or fields. The fields, that can be set on an issue
create operation, can be determined using the /rest/api/2/issue/createmeta resource. If a particular field is
not configured to appear on the issue's Cr... | codesearchnet |
def fragmentate(self, give_only_index=False, use_lookup=None):
if (use_lookup is None):
use_lookup = settings['defaults']['use_lookup']
fragments = []
pending = set(self.index)
self.get_bonds(use_lookup=use_lookup)
while pending:
index = self.get_coordination_sphere(pending.pop(), us... | Get the indices of non bonded parts in the molecule.
Args:
give_only_index (bool): If ``True`` a set of indices is returned.
Otherwise a new Cartesian instance.
use_lookup (bool): Use a lookup variable for
:meth:`~chemcoord.Cartesian.get_bonds`.
use_lookup (bool): Use a lookup variable for
:meth:`~chemcoord.Cartesian.... | codesearchnet |
def list_tasks(target=None):
from os import getcwd, chdir
from glob import glob
original = getcwd()
if (target is None):
target = _dbdir()
chdir(target)
result = {}
for filename in glob('*.*.json'):
(project, task) = filename.split('.')[0:2]
if (project not in result)... | Returns a list of all the projects and tasks available in the `acorn`
database directory.
Args:
target (str): directory to list the projects for. Defaults to the configured
database directory.
Returns:
dict: keys are project names; values are lists of tasks associated with the
project. | codesearchnet |
def deep_update(d, u):
for (k, v) in u.items():
if isinstance(v, Mapping):
d[k] = deep_update(d.get(k, {}), v)
elif isinstance(v, list):
existing_elements = d.get(k, [])
d[k] = (existing_elements + [ele for ele in v if (ele not in existing_elements)])
else... | Deeply updates a dictionary. List values are concatenated.
Args:
d (dict): First dictionary which will be updated
u (dict): Second dictionary use to extend the first one
Returns:
dict: The merge dictionary | codesearchnet |
def map(self, map_fn, desc=None):
if desc is None:
desc = getattr(map_fn, '__name__', '')
desc = u'map({})'.format(desc)
return self.transform(lambda xs: (map_fn(x) for x in xs), desc=desc) | Return a copy of this query, with the values mapped through `map_fn`.
Args:
map_fn (callable): A callable that takes a single argument and returns a new value.
Keyword Args:
desc (str): A description of the mapping transform, for use in log message.
Defaults to the name of the map function.
Returns:
Query | juraj-google-style |
def is50(msg):
if allzeros(msg):
return False
d = hex2bin(data(msg))
if wrongstatus(d, 1, 3, 11):
return False
if wrongstatus(d, 12, 13, 23):
return False
if wrongstatus(d, 24, 25, 34):
return False
if wrongstatus(d, 35, 36, 45):
return Fa... | Check if a message is likely to be BDS code 5,0
(Track and turn report)
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False | juraj-google-style |
def _ProcessFileEntryDataStream(self, mediator, file_entry, data_stream):
display_name = mediator.GetDisplayName()
data_stream_name = (getattr(data_stream, 'name', '') or '')
logger.debug('[ProcessFileEntryDataStream] processing data stream: "{0:s}" of file entry: {1:s}'.format(data_stream_name, display_nam... | Processes a specific data stream of a file entry.
Args:
mediator (ParserMediator): mediates the interactions between
parsers and other components, such as storage and abort signals.
file_entry (dfvfs.FileEntry): file entry containing the data stream.
data_stream (dfvfs.DataStream): data stream or None if the file entr... | codesearchnet |
def run_suite_class(argv=None):
cli_args = _parse_cli_args(argv)
suite_class = _find_suite_class()
if cli_args.list_tests:
_print_test_names_for_suite(suite_class)
sys.exit(0)
test_configs = config_parser.load_test_config_file(cli_args.config, cli_args.test_bed)
config_count = len(te... | Executes tests in the test suite.
Args:
argv: A list that is then parsed as CLI args. If None, defaults to sys.argv. | github-repos |
def trainable_variables(self):
return tuple((v for v in self.variables if v.trainable)) | A sequence of trainable variables accessed by this FuncGraph.
Note that functions keep only weak references to variables. Calling the
function after a variable it accesses has been deleted is an error.
Returns:
Sequence of trainable variables for this func graph. | github-repos |
def hwvtep_add_loopback_interface(self, **kwargs):
name = kwargs.pop('name')
id = kwargs.pop('int_id')
ip_args = dict(name=name, loopback_id=id)
method_name = 'overlay_gateway_ip_interface_loopback_loopback_id'
method_class = self._brocade_tunnels
gw_attr = getat... | Add loopback interface to the overlay-gateway
Args:
name (str): gateway-name
int_id (int): loopback inteface id
callback (function): A function executed upon completion of the
method.
Returns:
Return value of `callback`.
Raises:
None | juraj-google-style |
def build_losses(self, logits_real, logits_fake):
with tf.name_scope("GAN_loss"):
score_real = tf.sigmoid(logits_real)
score_fake = tf.sigmoid(logits_fake)
tf.summary.histogram('score-real', score_real)
tf.summary.histogram('score-fake', score_fake)
... | Build standard GAN loss and set `self.g_loss` and `self.d_loss`.
D and G play two-player minimax game with value function V(G,D)
min_G max _D V(D, G) = IE_{x ~ p_data} [log D(x)] + IE_{z ~ p_fake} [log (1 - D(G(z)))]
Args:
logits_real (tf.Tensor): discrim logits from real samples
logits_fake (tf.Tensor): discrim log... | juraj-google-style |
def ScanForStorageMediaImage(self, source_path_spec):
try:
type_indicators = analyzer.Analyzer.GetStorageMediaImageTypeIndicators(source_path_spec, resolver_context=self._resolver_context)
except RuntimeError as exception:
raise errors.BackEndError('Unable to process source path specification wi... | Scans the path specification for a supported storage media image format.
Args:
source_path_spec (PathSpec): source path specification.
Returns:
PathSpec: storage media image path specification or None if no supported
storage media image type was found.
Raises:
BackEndError: if the source cannot be scanned or more th... | codesearchnet |
def _GetStringValue(self, data_dict, name, default_value=None):
values = data_dict.get(name, None)
if not values:
return default_value
for index, value in enumerate(values):
if ',' in value:
values[index] = '"{0:s}"'.format(value)
return ', '.join(values) | Retrieves a specific string value from the data dict.
Args:
data_dict (dict[str, list[str]): values per name.
name (str): name of the value to retrieve.
default_value (Optional[object]): value to return if the name has no value
set in data_dict.
Returns:
str: value represented as a string. | juraj-google-style |
def _CallMethod(self, srvc, method_descriptor,
rpc_controller, request, callback):
if method_descriptor.containing_service != self.descriptor:
raise RuntimeError(
'CallMethod() given method descriptor for wrong service type.')
method = getattr(srvc, method_descriptor.name)... | Calls the method described by a given method descriptor.
Args:
srvc: Instance of the service for which this method is called.
method_descriptor: Descriptor that represent the method to call.
rpc_controller: RPC controller to use for this method's execution.
request: Request protocol message.
callback: A callback to in... | juraj-google-style |
def __init__(self, domain_postfix='_domain'):
super(ReverseDNS, self).__init__()
self.domain_postfix = domain_postfix
self.ip_lookup_cache = cache.Cache(timeout=600)
self.output_stream = self.process_for_rdns() | Initialize ReverseDNS Class
Args:
domain_postfix: the string to be appended to the ip fields (e.g. IP.src -> IP.src_domain) | juraj-google-style |
def add(self, distinguished_name, object_class, attributes):
self.conn.add(distinguished_name, object_class, attributes) | Add object to LDAP.
Args:
distinguished_name: the DN of the LDAP record to be added
object_class: The objectClass of the record to be added.
This is a list of length >= 1.
attributes: a dictionary of LDAP attributes to add
See ldap_tools.api.group.API#__ldap_attr | juraj-google-style |
def set_reprompt_text(self, text):
self.response.reprompt.outputSpeech.type = 'PlainText'
self.response.reprompt.outputSpeech.text = text | Set response reprompt output speech as plain text type.
Args:
text: str. Response speech used when type is 'PlainText'. Cannot
exceed 8,000 characters. | juraj-google-style |
def __register_methods(self, parsed_config):
methods = parsed_config.get('methods')
if (not methods):
return
for (method_name, method) in methods.iteritems():
self.__api_methods[method_name] = method.get('rosyMethod') | Register all methods from the given api config file.
Methods are stored in a map from method_name to rosyMethod,
the name of the ProtoRPC method to be called on the backend.
If no rosyMethod was specified the value will be None.
Args:
parsed_config: The JSON object with the API configuration being added. | codesearchnet |
def CheckRValueReference(filename, clean_lines, linenum, nesting_state, error):
line = clean_lines.elided[linenum]
match = Match('^(.*\\S)&&', line)
if (not match):
match = Match('(.*)&&\\S', line)
if ((not match) or ('(&&)' in line) or Search('\\boperator\\s*$', match.group(1))):
return... | Check for rvalue references.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function t... | codesearchnet |
def save_lines(lines, filename):
with open(filename, 'w', encoding='utf-8') as f:
f.write('\n'.join(lines)) | Save an array of lines to a file.
Args:
lines: An array of strings that will be saved as individual lines.
filename: Path to the output file. | juraj-google-style |
def _get_memory_contents(self):
if (self._memory_contents is not None):
return self._memory_contents
schedule = scheduler.minimize_peak_memory(self._graph, self._scheduler_alg)
self._memory_contents = self._graph.compute_memory_contents_under_schedule(schedule)
return self._memory_contents | Runs the scheduler to determine memory contents at every point in time.
Returns:
a list of frozenset of strings, where the ith entry describes the tensors
in memory when executing operation i (where schedule[i] is an index into
GetAllOperationNames()). | codesearchnet |
def issuperset(self, other):
other = self._cast_to_frameset(other)
if other is NotImplemented:
return NotImplemented
return self.items >= other.items | Check if the contents of `self` is a superset of the contents of
`other.`
Args:
other (:class:`FrameSet`):
Returns:
bool:
:class:`NotImplemented`: if `other` fails to convert to a :class:`FrameSet` | juraj-google-style |
def insert(self, lines=None):
for i, (key, line) in enumerate(lines.items()):
n = key + i
first_half = self._lines[:n]
last_half = self._lines[n:]
self._lines = first_half + [line] + last_half | Insert lines into the editor.
Note:
To insert before the first line, use :func:`~exa.core.editor.Editor.preappend`
(or key 0); to insert after the last line use :func:`~exa.core.editor.Editor.append`.
Args:
lines (dict): Dictionary of lines of form (lineno, string) pairs | juraj-google-style |
def compute_qkv(query_antecedent, memory_antecedent, total_key_depth, total_value_depth, q_filter_width=1, kv_filter_width=1, q_padding='VALID', kv_padding='VALID', vars_3d_num_heads=0, layer_collection=None):
if (memory_antecedent is None):
memory_antecedent = query_antecedent
q = compute_attention_com... | Computes query, key and value.
Args:
query_antecedent: a Tensor with shape [batch, length_q, channels]
memory_antecedent: a Tensor with shape [batch, length_m, channels]
total_key_depth: an integer
total_value_depth: an integer
q_filter_width: An integer specifying how wide you want the query to be.
kv_filter_width: A... | codesearchnet |
def get_all_function_definitions(base_most_function):
return ([base_most_function] + [function for derived_contract in base_most_function.contract.derived_contracts for function in derived_contract.functions if (function.full_name == base_most_function.full_name)]) | Obtains all function definitions given a base-most function. This includes the provided function, plus any
overrides of that function.
Returns:
(list): Returns any the provided function and any overriding functions defined for it. | codesearchnet |
def _simple_name(distribution):
simple_name = distribution.name
if simple_name.endswith('/'):
simple_name = simple_name.split('/')[(- 2)]
parts = simple_name.split('_')
if parts[(- 1)].isdigit():
simple_name = '_'.join(parts[:(- 1)])
return simple_name | Infer the original name passed into a distribution constructor.
Distributions typically follow the pattern of
with.name_scope(name) as name:
super(name=name)
so we attempt to reverse the name-scope transformation to allow
addressing of RVs by the distribution's original, user-visible
name kwarg.
Args:
distribution: a... | codesearchnet |
class TFXGLMModel(TFXGLMPreTrainedModel):
def __init__(self, config: XGLMConfig, embed_tokens: Optional[TFSharedEmbeddings]=None, *inputs: Any, **kwargs: Any) -> None:
super().__init__(config, *inputs, **kwargs)
self.model = TFXGLMMainLayer(config, embed_tokens=embed_tokens, name='model')
@unp... | Transformer decoder consisting of *config.num_layers* layers. Each layer is a [`TFXGLMDecoderLayer`]
Args:
config: XGLMConfig
embed_tokens: [TFSharedEmbeddings]: output embedding | github-repos |
def _manage_location(attr):
return property(lambda self: getattr(self, '_%s' % attr),
lambda self, value: self._set_location(attr, value)) | Build managed property interface.
Args:
attr (str): Property's name
Returns:
property: Managed property interface | juraj-google-style |
def compute_files(user1, user2, file_list, dir_pre, start_num):
match_total = 0
test_total = 0
gold_total = 0
for fi in file_list:
file1 = dir_pre + user1 + "/" + fi + ".txt"
file2 = dir_pre + user2 + "/" + fi + ".txt"
if not os.path.exists(file1):
print("******... | Compute the smatch scores for a file list between two users
Args:
user1: user 1 name
user2: user 2 name
file_list: file list
dir_pre: the file location prefix
start_num: the number of restarts in smatch
Returns:
smatch f score. | juraj-google-style |
def matches(self, spec):
if (callable(spec) and (not isinstance(spec, type))):
return spec(self)
elif isinstance(spec, type):
return isinstance(self, spec)
specification = (self.__class__.__name__, self.group, self.label)
split_spec = (tuple(spec.split('.')) if (not isinstance(spec, tupl... | Whether the spec applies to this object.
Args:
spec: A function, spec or type to check for a match
* A 'type[[.group].label]' string which is compared
against the type, group and label of this object
* A function which is given the object and returns
a boolean.
* An object type matched using isinstance.
Returns:
bool... | codesearchnet |
def split_input(cls, mapper_spec):
params = _get_params(mapper_spec)
blob_keys = params[cls.BLOB_KEYS_PARAM]
if isinstance(blob_keys, basestring):
blob_keys = blob_keys.split(",")
blob_sizes = {}
for blob_key in blob_keys:
blob_info = blobstore.BlobInfo.get(blobstore.... | Returns a list of shard_count input_spec_shards for input_spec.
Args:
mapper_spec: The mapper specification to split from. Must contain
'blob_keys' parameter with one or more blob keys.
Returns:
A list of BlobstoreInputReaders corresponding to the specified shards. | juraj-google-style |
def SetInputSourceConfiguration(self, configuration):
mount_path = configuration.mount_path
if mount_path and mount_path.endswith(os.sep):
mount_path = mount_path[:-1]
self._mount_path = mount_path | Sets the input source configuration settings.
Args:
configuration (InputSourceConfiguration): input source configuration. | juraj-google-style |
def _use_widgets(objs):
from ..models.widgets import Widget
return _any(objs, (lambda obj: isinstance(obj, Widget))) | Whether a collection of Bokeh objects contains a any Widget
Args:
objs (seq[Model or Document]) :
Returns:
bool | codesearchnet |
def limit_weights(weights, limit=0.1):
if ((1.0 / limit) > len(weights)):
raise ValueError('invalid limit -> 1 / limit must be <= len(weights)')
if isinstance(weights, dict):
weights = pd.Series(weights)
if (np.round(weights.sum(), 1) != 1.0):
raise ValueError(('Expecting weights (th... | Limits weights and redistributes excedent amount
proportionally.
ex:
- weights are {a: 0.7, b: 0.2, c: 0.1}
- call with limit=0.5
- excess 0.2 in a is ditributed to b and c
proportionally.
- result is {a: 0.5, b: 0.33, c: 0.167}
Args:
* weights (Series): A series describing the weights
* limit (float): Maximum weight... | codesearchnet |
def geojson_polygon_to_mask(feature, shape, lat_idx, lon_idx):
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from matplotlib import patches
import numpy as np
if (feature.geometry.type not in ('Polygon', 'MultiPolygon')):
raise ValueError(('Cannot handle feature... | Convert a GeoJSON polygon feature to a numpy array
Args:
feature (pygeoj.Feature): polygon feature to draw
shape (tuple(int, int)): shape of 2D target numpy array to draw polygon in
lat_idx (func): function converting a latitude to the (fractional) row index in the map
lon_idx (func): function converting a longitude t... | codesearchnet |
def build(self, text, matrix, skim_depth=10, d_weights=False):
for anchor in bar(matrix.keys):
n1 = text.unstem(anchor)
pairs = matrix.anchored_pairs(anchor).items()
for (term, weight) in list(pairs)[:skim_depth]:
if d_weights:
weight = (1 - weight)
n2... | 1. For each term in the passed matrix, score its KDE similarity with
all other indexed terms.
2. With the ordered stack of similarities in hand, skim off the top X
pairs and add them as edges.
Args:
text (Text): The source text instance.
matrix (Matrix): An indexed term matrix.
skim_depth (int): The number of sibling... | codesearchnet |
def start(self):
resp = self.post('start')
if resp.is_fail():
return None
if ('result' not in resp.data):
return None
result = resp.data['result']
return {'user': result['user'], 'ws_host': result['ws_host']} | Gets the rtm ws_host and user information
Returns:
None if request failed,
else a dict containing "user"(User) and "ws_host" | codesearchnet |
def isna(obj):
if isinstance(obj, BasePandasDataset):
return obj.isna()
else:
return pandas.isna(obj) | Detect missing values for an array-like object.
Args:
obj: Object to check for null or missing values.
Returns:
bool or array-like of bool | juraj-google-style |
def set_tag(self, key, value, update_session=True):
existing_tags = {x.key: x for x in self.tags}
if key in existing_tags:
tag = existing_tags[key]
if tag.value == value:
return False
tag.value = value
else:
tag = Tag()
... | Create or set the value of the tag with `key` to `value`. Returns `True` if the tag was created or updated or
`False` if there were no changes to be made.
Args:
key (str): Key of the tag
value (str): Value of the tag
update_session (bool): Automatically add the change to the SQLAlchemy session. Default: True
Returns:... | juraj-google-style |
def to_grayscale(img):
gray = numpy.asarray(ImageOps.grayscale(img)).astype(numpy.float)
imbands = img.getbands()
alpha = None
if 'A' in imbands:
alpha = numpy.asarray(img.split()[-1]).astype(numpy.float)
return gray, alpha | Convert PIL image to numpy grayscale array and numpy alpha array.
Args:
img (PIL.Image): PIL Image object.
Returns:
(gray, alpha): both numpy arrays. | juraj-google-style |
def match_exists(self, field, required=True, new_group=False):
return self.match_field(field, '*', required=required, new_group=new_group) | Require a field to exist in the results.
Matches will have some value in ``field``.
Arguments:
field (str): The field to check.
The field must be namespaced according to Elasticsearch rules
using the dot syntax.
For example, ``"mdf.source_name"`` is the ``source_name`` field
of the ``mdf`` dictionary.
required (bool):... | codesearchnet |
def get(quantity, min_type=EventType.firstevent, max_type=EventType.lastevent):
return _peep(quantity, lib.SDL_GETEVENT, min_type, max_type) | Return events at the front of the event queue, within the specified minimum and maximum type,
and remove them from the queue.
Args:
quantity (int): The maximum number of events to return.
min_type (int): The minimum value for the event type of the returned events.
max_type (int): The maximum value for the event type o... | codesearchnet |
def Install(self, apk_path, destination_dir='', replace_existing=True, grant_permissions=False, timeout_ms=None, transfer_progress_callback=None):
if (not destination_dir):
destination_dir = '/data/local/tmp/'
basename = os.path.basename(apk_path)
destination_path = posixpath.join(destination_dir, b... | Install an apk to the device.
Doesn't support verifier file, instead allows destination directory to be
overridden.
Args:
apk_path: Local path to apk to install.
destination_dir: Optional destination directory. Use /system/app/ for
persistent applications.
replace_existing: whether to replace existing application
gra... | codesearchnet |
def from_sample_rate(sample_rate, n_bands, always_even=False):
fb = FrequencyBand(0, sample_rate.nyquist)
return LinearScale(fb, n_bands, always_even=always_even) | Return a :class:`~zounds.spectral.LinearScale` instance whose upper
frequency bound is informed by the nyquist frequency of the sample rate.
Args:
sample_rate (SamplingRate): the sample rate whose nyquist frequency
will serve as the upper frequency bound of this scale
n_bands (int): the number of evenly-spaced frequen... | juraj-google-style |
def _tower_loss(images, labels, num_classes, scope, reuse_variables=None):
restore_logits = (not FLAGS.fine_tune)
with tf.variable_scope(tf.get_variable_scope(), reuse=reuse_variables):
logits = inception.inference(images, num_classes, for_training=True, restore_logits=restore_logits, scope=scope)
s... | Calculate the total loss on a single tower running the ImageNet model.
We perform 'batch splitting'. This means that we cut up a batch across
multiple GPU's. For instance, if the batch size = 32 and num_gpus = 2,
then each tower will operate on an batch of 16 images.
Args:
images: Images. 4D tensor of size [batch_siz... | codesearchnet |
def alltoall(self, x, mesh_axis, split_axis, concat_axis):
return self._collective_with_groups(x, [mesh_axis], functools.partial(alltoall_ring, split_axis=split_axis, concat_axis=concat_axis)) | Grouped alltoall.
Args:
x: a LaidOutTensor
mesh_axis: an integer the mesh axis along which to group
split_axis: an integer (the Tensor axis along which to split)
concat_axis: an integer (the Tensor axis along which to concatenate)
Returns:
a LaidOutTensor | codesearchnet |
def _extract_units(self, obj, value):
if isinstance(value, dict):
if ('units' in value):
value = copy(value)
units = value.pop('units', None)
if units:
self.units_prop.__set__(obj, units)
return value | Internal helper for dealing with units associated units properties
when setting values on |UnitsSpec| properties.
When ``value`` is a dict, this function may mutate the value of the
associated units property.
Args:
obj (HasProps) : instance to update units spec property value for
value (obj) : new value to set for th... | codesearchnet |
def sg_summary_gradient(tensor, gradient, prefix=None, name=None):
r
prefix = '' if prefix is None else prefix + '/'
name = prefix + _pretty_name(tensor) if name is None else prefix + name
_scalar(name + '/grad', tf.reduce_mean(tf.abs(gradient)))
_histogram(name + '/grad-h', tf.a... | r"""Register `tensor` to summary report as `gradient`
Args:
tensor: A `Tensor` to log as gradient
gradient: A 0-D `Tensor`. A gradient to log
prefix: A `string`. A prefix to display in the tensor board web UI.
name: A `string`. A name to display in the tensor board web UI.
Returns:
None | juraj-google-style |
def teleport(self, location=None, rotation=None):
val = 0
if (location is not None):
val += 1
np.copyto(self._teleport_buffer, location)
if (rotation is not None):
np.copyto(self._rotation_buffer, rotation)
val += 2
self._teleport_bool_buffer[0] = val | Teleports the agent to a specific location, with a specific rotation.
Args:
location (np.ndarray, optional): An array with three elements specifying the target world coordinate in meters.
If None, keeps the current location. Defaults to None.
rotation (np.ndarray, optional): An array with three elements specifying the... | codesearchnet |
def load_sst(path=None, url='http:
if (path is None):
path = os.path.expanduser('~/stanford_sentiment_treebank/')
makedirs(path, exist_ok=True)
fnames = download_sst(path, url)
return {key: import_tree_corpus(value) for (key, value) in fnames.items()} | Download and read in the Stanford Sentiment Treebank dataset
into a dictionary with a 'train', 'dev', and 'test' keys. The
dictionary keys point to lists of LabeledTrees.
Arguments:
----------
path : str, (optional defaults to ~/stanford_sentiment_treebank),
directory where the corpus should be downloaded (and
importe... | codesearchnet |
def unfold_tensor(tensor, max_seq_len):
_, _, D = tensor.shape
tensor = tensor.transpose(-1, -2)
tensor = F.unfold(tensor[..., None, :], kernel_size=(1, max_seq_len), stride=(1, max_seq_len))
new_bsz, _, slen = tensor.shape
tensor = tensor.view(new_bsz, -1, max_seq_len, slen)
tensor = tensor.per... | For a given tensor with shape of (N, T, D), if sequence length T is longer than max_seq_len,
this function unfold it to a (NT', max_seq_len, D) where T' is T // max_seq_len.
Args:
tensor: N, T, D | github-repos |
def mark_flag_as_required(flag_name, flag_values=FLAGS):
if (flag_values[flag_name].default is not None):
warnings.warn(('Flag %s has a non-None default value; therefore, mark_flag_as_required will pass even if flag is not specified in the command line!' % flag_name))
register_validator(flag_name, (lamb... | Ensures that flag is not None during program execution.
Registers a flag validator, which will follow usual validator rules.
Important note: validator will pass for any non-None value, such as False,
0 (zero), '' (empty string) and so on.
It is recommended to call this method like this:
if __name__ == '__main__':
gf... | codesearchnet |
def owned_by(self, owner, also_check_group=False):
if also_check_group:
return self.owner == owner and self.group == owner
else:
return self.owner == owner | Checks if the specified user or user and group own the file.
Args:
owner (str): the user (or group) name for which we ask about ownership
also_check_group (bool): if set to True, both user owner and group owner checked
if set to False, only user owner checked
Returns:
bool: True if owner of the file is the specified ... | juraj-google-style |
class JsonPipelineDataFormat(PipelineDataFormat):
def __init__(self, output_path: Optional[str], input_path: Optional[str], column: Optional[str], overwrite=False):
super().__init__(output_path, input_path, column, overwrite=overwrite)
with open(input_path, 'r') as f:
self._entries = js... | Support for pipelines using JSON file format.
Args:
output_path (`str`): Where to save the outgoing data.
input_path (`str`): Where to look for the input data.
column (`str`): The column to read.
overwrite (`bool`, *optional*, defaults to `False`):
Whether or not to overwrite the `output_path`. | github-repos |
def GetWindowsEventMessage(self, log_source, message_identifier):
database_reader = self._GetWinevtRcDatabaseReader()
if (not database_reader):
return None
if (self._lcid != self.DEFAULT_LCID):
message_string = database_reader.GetMessage(log_source, self.lcid, message_identifier)
if ... | Retrieves the message string for a specific Windows Event Log source.
Args:
log_source (str): Event Log source, such as "Application Error".
message_identifier (int): message identifier.
Returns:
str: message string or None if not available. | codesearchnet |
def assert_matches_stdout(actual, expected_stdout, normalize_fn=lambda elem: elem, label=''):
def stdout_to_python_object(elem_str):
try:
elem = ast.literal_eval(elem_str)
except (SyntaxError, ValueError):
elem = elem_str
return normalize_fn(elem)
actual = actual... | Asserts a PCollection of strings matches the expected stdout elements.
Args:
actual (beam.PCollection): A PCollection.
expected (List[str]): A list of stdout elements, one line per element.
normalize_fn (Function[any]): A function to normalize elements before
comparing them. Can be used to sort lists before comparing.... | github-repos |
async def _auth_plain(self, username, password):
mechanism = 'PLAIN'
credentials = '\x00{}\x00{}'.format(username, password)
encoded_credentials = SMTP.b64enc(credentials)
try:
(code, message) = (await self.do_cmd('AUTH', mechanism, encoded_credentials, success=(235, 503)))
except SMTPComman... | Performs an authentication attempt using the PLAIN mechanism.
Protocol:
1. Format the username and password in a suitable way ;
2. The formatted string is base64-encoded ;
3. The string 'AUTH PLAIN' and a space character are prepended to
the base64-encoded username and password and sent to the
server ;
4. If the serv... | codesearchnet |
def VerifyStructure(self, parser_mediator, lines):
match = self._PARSING_COMPONENTS['msg_left_delimiter'].match
return match in lines | Verifies whether content corresponds to an SCCM log file.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
lines (str): one or more lines from the text file.
Returns:
bool: True if this is the correct parser, False otherwise. | juraj-google-style |
def load_ui_wrapper(uifile, base_instance=None):
if 'PySide' in __binding__:
return pyside_load_ui(uifile, base_instance)
elif 'PyQt' in __binding__:
uic = __import__(__binding__ + ".uic").uic
return uic.loadUi(uifile, base_instance) | Load a Qt Designer .ui file and returns an instance of the user interface
Args:
uifile (str): Absolute path to .ui file
base_instance (QWidget): The widget into which UI widgets are loaded
Returns:
function: pyside_load_ui or uic.loadUi | juraj-google-style |
def __call__(self, *args, **kwargs):
retry_timedelta = kwargs.pop('retry_timedelta', self._retry_timedelta)
if retry_timedelta is None:
retry_timedelta = datetime.timedelta(days=1000000)
num_retries = kwargs.pop('num_retries', self._num_retries)
if num_retries is N... | Call the wrapped function, with retries.
Args:
retry_timedelta (kwarg): amount of time to retry before giving up.
sleep_base (kwarg): amount of time to sleep upon first failure, all other sleeps
are derived from this one. | juraj-google-style |
def __init__(self, channel):
self.DeployStorageSecret = channel.unary_unary(
'/deploy.API/DeployStorageSecret',
request_serializer=client_dot_deploy_dot_deploy__pb2.DeployStorageSecretRequest.SerializeToString,
response_deserializer=client_dot_deploy_dot_deploy__pb2.DeployStorageSecretR... | Constructor.
Args:
channel: A grpc.Channel. | juraj-google-style |
def try_add_variable(self, variable_name: str, replacement: VariableReplacement) -> None:
if (variable_name not in self):
self[variable_name] = (replacement.copy() if isinstance(replacement, Multiset) else replacement)
else:
existing_value = self[variable_name]
if isinstance(existing_val... | Try to add the variable with its replacement to the substitution.
This considers an existing replacement and will only succeed if the new replacement
can be merged with the old replacement. Merging can occur if either the two replacements
are equivalent. Replacements can also be merged if the old replacement for the v... | codesearchnet |
def fetch_github_pull_request(destination_directory: str, repository: github_repository.GithubRepository, pull_request_number: int, verbose: bool) -> prepared_env.PreparedEnv:
branch = 'pull/{}/head'.format(pull_request_number)
os.chdir(destination_directory)
print('chdir', destination_directory, file=sys.s... | Uses content from github to create a dir for testing and comparisons.
Args:
destination_directory: The location to fetch the contents into.
repository: The github repository that the commit lives under.
pull_request_number: The id of the pull request to clone. If None, then
the master branch is cloned instead.
verbose... | codesearchnet |
def pool_function(args):
is_valid = True
try:
checker = emailahoy.VerifyEmail()
status, message = checker.verify_email_smtp(args, from_host='gmail.com', from_email='sample@gmail.com')
if status == 250:
print("\t[*] Verification of '{}' status: {}. Details:\n\t\t{}".form... | A wrapper for being able to launch all the threads.
We will use python-emailahoy library for the verification.
Args:
-----
args: reception of the parameters for getPageWrapper as a tuple.
Returns:
--------
A dictionary representing whether the verification was ended
successfully. The format is as follows:
```
{"plat... | juraj-google-style |
def create_config(cnf_file, uid, overwrite):
conf = None
if not os.path.exists(settings.DEB_CONF_PATH):
os.makedirs(settings.DEB_CONF_PATH, 0755)
os.chown(settings.DEB_CONF_PATH, uid, -1)
if not os.path.exists(cnf_file):
conf = CLEAN_CONFIG
elif overwrite: ... | Creates configuration file and the directory where it should be stored and
set correct permissions.
Args:
cnf_file (str): Path to the configuration file.
uid (int): User ID - will be used for chown.
overwrite (bool): Overwrite the configuration with :attr:`CLEAN_CONFIG`. | juraj-google-style |
def parse_arguments(argv):
parser = argparse.ArgumentParser(description='write-to-pubsub')
parser.add_argument('-m', '--mode', help='Mode to run pipeline in.', choices=['local', 'cloud'], default='local')
parser.add_argument('-p', '--project', help='GCP project to run pipeline on.', default=cfg.PROJECT_ID)
... | Parses the arguments passed to the command line and returns them as an object
Args:
argv: The arguments passed to the command line.
Returns:
The arguments that are being passed in. | github-repos |
def get_permissions(self, namespace, explicit=False):
if (not isinstance(namespace, Namespace)):
namespace = Namespace(namespace)
keys = namespace.keys
(p, _) = self._check(keys, self.index, explicit=explicit)
return p | Returns the permissions level for the specified namespace
Arguments:
namespace -- permissioning namespace (str)
explicit -- require explicitly set permissions to the provided namespace
Returns:
int -- permissioning flags | codesearchnet |
def nhs_check_digit(ninedigits: Union[(str, List[Union[(str, int)]])]) -> int:
if ((len(ninedigits) != 9) or (not all((str(x).isdigit() for x in ninedigits)))):
raise ValueError('bad string to nhs_check_digit')
check_digit = (11 - (sum([(int(d) * f) for (d, f) in zip(ninedigits, NHS_DIGIT_WEIGHTINGS)]) ... | Calculates an NHS number check digit.
Args:
ninedigits: string or list
Returns:
check digit
Method:
1. Multiply each of the first nine digits by the corresponding
digit weighting (see :const:`NHS_DIGIT_WEIGHTINGS`).
2. Sum the results.
3. Take remainder after division by 11.
4. Subtract the remainder from 11
5. If ... | codesearchnet |
def add_user(self, group, username):
try:
self.lookup_id(group)
except ldap_tools.exceptions.InvalidResult as err:
raise err from None
operation = {'memberUid': [(ldap3.MODIFY_ADD, [username])]}
self.client.modify(self.__distinguished_name(group), oper... | Add a user to the specified LDAP group.
Args:
group: Name of group to update
username: Username of user to add
Raises:
ldap_tools.exceptions.InvalidResult:
Results of the query were invalid. The actual exception raised
inherits from InvalidResult. See #lookup_id for more info. | juraj-google-style |
def _register_bounds_validator_if_needed(parser, name, flag_values):
if parser.lower_bound is not None or parser.upper_bound is not None:
def checker(value):
if value is not None and parser.is_outside_bounds(value):
message = '%s is not %s' % (value, parser.syntactic_help)
raise _excepti... | Enforces lower and upper bounds for numeric flags.
Args:
parser: NumericParser (either FloatParser or IntegerParser), provides lower
and upper bounds, and help text to display.
name: str, name of the flag
flag_values: FlagValues. | juraj-google-style |
def get_id(page):
start_pos = page.find('<id>')
end_pos = page.find('</id>')
assert (start_pos != (- 1))
assert (end_pos != (- 1))
start_pos += len('<id>')
return int(page[start_pos:end_pos]) | Extract the id from a page.
Args:
page: a string
Returns:
an integer | codesearchnet |
def to_jdbc_url(self) -> str:
return self._build_jdbc_url(socketFactory='com.google.cloud.sql.postgres.SocketFactory', database_type='postgresql') | Convert options to a properly formatted JDBC URL.
Returns:
JDBC URL string configured with all options. | github-repos |
def md(cls, data, force_field, temperature, nsteps, other_settings=None):
template_path = os.path.join(cls.template_dir, 'md.txt')
with open(template_path) as f:
script_template = f.read()
settings = (other_settings.copy() if (other_settings is not None) else {})
settings.update({'force_field': ... | Example for a simple MD run based on template md.txt.
Args:
data (LammpsData or str): Data file as a LammpsData
instance or path to an existing data file.
force_field (str): Combined force field related cmds. For
example, 'pair_style eam\npair_coeff * * Cu_u3.eam'.
temperature (float): Simulation temperature.
nsteps (... | codesearchnet |
def _list_objects(self, client_kwargs, max_request_entries):
client_kwargs = self._update_listing_client_kwargs(
client_kwargs, max_request_entries)
with _handle_azure_exception():
for obj in self.client.list_directories_and_files(**client_kwargs):
yield... | Lists objects.
args:
client_kwargs (dict): Client arguments.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
generator of tuple: object name str, object header dict,
directory bool | juraj-google-style |
def __init__(self, channel):
self.MemberAdd = channel.unary_unary(
'/etcdserverpb.Cluster/MemberAdd',
request_serializer=rpc__pb2.MemberAddRequest.SerializeToString,
response_deserializer=rpc__pb2.MemberAddResponse.FromString,
)
self.MemberRemove = channel.unary_unary(
... | Constructor.
Args:
channel: A grpc.Channel. | juraj-google-style |
def Copy(self, name=None):
new = copy.copy(self)
new.d = copy.copy(self.d)
new.name = (name if (name is not None) else self.name)
return new | Returns a copy.
Make a shallow copy of d. If you want a deep copy of d,
use copy.deepcopy on the whole object.
Args:
name: string name for the new Hist | codesearchnet |
def assign_sub(self, delta, use_locking=None, name=None, read_value=True):
with _handle_graph(self.handle), self._assign_dependencies():
assign_sub_op = gen_resource_variable_ops.assign_sub_variable_op(self.handle, ops.convert_to_tensor(delta, dtype=self.dtype), name=name)
if read_value:
return ... | Subtracts a value from this variable.
Args:
delta: A `Tensor`. The value to subtract from this variable.
use_locking: If `True`, use locking during the operation.
name: The name to use for the operation.
read_value: A `bool`. Whether to read and return the new value of the
variable or not.
Returns:
If `read_value` is... | github-repos |
def locate_file(start_path, file_name):
if os.path.isfile(start_path):
start_dir_path = os.path.dirname(start_path)
elif os.path.isdir(start_path):
start_dir_path = start_path
else:
raise exceptions.FileNotFound('invalid path: {}'.format(start_path))
file_path = os.path.join(star... | locate filename and return absolute file path.
searching will be recursive upward until current working directory.
Args:
start_path (str): start locating path, maybe file path or directory path
Returns:
str: located file path. None if file not found.
Raises:
exceptions.FileNotFound: If failed to locate file. | codesearchnet |
def as_text(bytes_or_text, encoding='utf-8'):
encoding = codecs.lookup(encoding).name
if isinstance(bytes_or_text, str):
return bytes_or_text
elif isinstance(bytes_or_text, bytes):
return bytes_or_text.decode(encoding)
else:
raise TypeError('Expected binary or unicode string, got... | Converts any string-like python input types to unicode.
Returns the input as a unicode string. Uses utf-8 encoding for text
by default.
Args:
bytes_or_text: A `bytes`, `str`, or `unicode` object.
encoding: A string indicating the charset for decoding unicode.
Returns:
A `unicode` (Python 2) or `str` (Python 3) objec... | github-repos |
def set_precision(predictions, labels, weights_fn=common_layers.weights_nonzero):
with tf.variable_scope('set_precision', values=[predictions, labels]):
labels = tf.squeeze(labels, [2, 3])
weights = weights_fn(labels)
labels = tf.one_hot(labels, predictions.shape[(- 1)])
labels = tf.... | Precision of set predictions.
Args:
predictions : A Tensor of scores of shape [batch, nlabels].
labels: A Tensor of int32s giving true set elements,
of shape [batch, seq_length].
weights_fn: A function to weight the elements.
Returns:
hits: A Tensor of shape [batch, nlabels].
weights: A Tensor of shape [batch, nlabel... | codesearchnet |
def parse_aggregate_report_file(_input, nameservers=None, dns_timeout=2.0,
parallel=False):
xml = extract_xml(_input)
return parse_aggregate_report_xml(xml,
nameservers=nameservers,
timeout=dns_time... | Parses a file at the given path, a file-like object. or bytes as a
aggregate DMARC report
Args:
_input: A path to a file, a file like object, or bytes
nameservers (list): A list of one or more nameservers to use
(Cloudflare's public DNS resolvers by default)
dns_timeout (float): Sets the DNS timeout in seconds
paralle... | juraj-google-style |
def List(device, device_path):
files = device.List(device_path)
files.sort(key=lambda x: x.filename)
maxname = max(len(f.filename) for f in files)
maxsize = max(len(str(f.size)) for f in files)
for f in files:
mode = (
('d' if stat.S_ISDIR(f.mode) else '-') +
... | Prints a directory listing.
Args:
device_path: Directory to list. | juraj-google-style |
def make_query(self, ns):
if issubclass(self.model_class, db.Model):
query = db.Query(self.model_class, namespace=ns)
for f in self.filters:
query.filter("%s %s" % (f[0], f[1]), f[2])
else:
query = self.model_class.query(namespace=ns)
for f in self.filters:
query = q... | Make a query of entities within this range.
Query options are not supported. They should be specified when the query
is run.
Args:
ns: namespace of this query.
Returns:
a db.Query or ndb.Query, depends on the model class's type. | juraj-google-style |
def load_terms(fo: IO, metadata: dict, forceupdate: bool):
version = metadata['metadata']['version']
with timy.Timer('Load Terms') as timer:
es = bel.db.elasticsearch.get_client()
es_version = version.replace('T', '').replace('-', '').replace(':', '')
index_prefix = f"terms_{metadata['me... | Load terms into Elasticsearch and ArangoDB
Forceupdate will create a new index in Elasticsearch regardless of whether
an index with the resource version already exists.
Args:
fo: file obj - terminology file
metadata: dict containing the metadata for terminology
forceupdate: force full update - e.g. don't leave Elasti... | codesearchnet |
def __make_id(receiver):
if __is_bound_method(receiver):
return (id(receiver.__func__), id(receiver.__self__))
return id(receiver) | Generate an identifier for a callable signal receiver.
This is used when disconnecting receivers, where we need to correctly
establish equivalence between the input receiver and the receivers assigned
to a signal.
Args:
receiver: A callable object.
Returns:
An identifier for the receiver. | juraj-google-style |
def keypoint_rot90(keypoint, factor, rows, cols, **params):
if factor < 0 or factor > 3:
raise ValueError('Parameter n must be in range [0;3]')
x, y, angle, scale = keypoint
if factor == 1:
keypoint = [y, (cols - 1) - x, angle - math.pi / 2, scale]
if factor == 2:
keypoint =... | Rotates a keypoint by 90 degrees CCW (see np.rot90)
Args:
keypoint (tuple): A tuple (x, y, angle, scale).
factor (int): Number of CCW rotations. Must be in range [0;3] See np.rot90.
rows (int): Image rows.
cols (int): Image cols. | juraj-google-style |
def handle_error(program_name, cmd, log=None):
print('\nHouston, we have a problem.', ('\n%s did not finish successfully. Review the log' % program_name), 'file and the input file(s) to see what went wrong.')
print(('%s command: "%s"' % (program_name, cmd)))
if (log is not None):
print(('log: "%s"' ... | Subprocess program error handling
Args:
program_name (str): name of the subprocess program
Returns:
break_now (bool): indicate whether calling program should break out of loop | codesearchnet |
def _get_contexts_for_squash(self, batch_signature):
batch = self._batches_by_id[batch_signature].batch
index = self._batches.index(batch)
contexts = []
txns_added_predecessors = []
for b in self._batches[index::(- 1)]:
batch_is_valid = True
contexts_from_batch = []
for txn i... | Starting with the batch referenced by batch_signature, iterate back
through the batches and for each valid batch collect the context_id.
At the end remove contexts for txns that are other txn's predecessors.
Args:
batch_signature (str): The batch to start from, moving back through
the batches in the scheduler
Returns... | codesearchnet |
def RegisterPlugin(cls, plugin_class):
plugin_name = plugin_class.NAME.lower()
if plugin_name in cls._plugin_classes:
raise KeyError((
'Plugin class already set for name: {0:s}.').format(
plugin_class.NAME))
cls._plugin_classes[plugin_name] = plugin_class | Registers a plugin class.
The plugin classes are identified based on their lower case name.
Args:
plugin_class (type): class of the plugin.
Raises:
KeyError: if plugin class is already set for the corresponding name. | juraj-google-style |
def cmd_startstop(options):
statelu = {'start': 'stopped', 'stop': 'running'}
options.inst_state = statelu[options.command]
debg.dprint('toggle set state: ', options.inst_state)
(i_info, param_str) = gather_data(options)
(tar_inst, tar_idx) = determine_inst(i_info, param_str, options.command)
re... | Start or Stop the specified instance.
Finds instances that match args and instance-state expected by the
command. Then, the target instance is determined, the action is
performed on the instance, and the eturn information is displayed.
Args:
options (object): contains args and data from parser. | codesearchnet |
def exclude(self, scheduled_operation: ScheduledOperation) -> bool:
try:
self.scheduled_operations.remove(scheduled_operation)
return True
except ValueError:
return False | Omits a scheduled operation from the schedule, if present.
Args:
scheduled_operation: The operation to try to remove.
Returns:
True if the operation was present and is now removed, False if it
was already not present. | codesearchnet |
def secure_channel(target, credentials, options=None, *, loop=None, executor=None, standalone_pool_for_streaming=False):
return Channel(_grpc.secure_channel(target, credentials, options), loop, executor, standalone_pool_for_streaming) | Creates a secure Channel to a server.
Args:
target: The server address.
credentials: A ChannelCredentials instance.
options: An optional list of key-value pairs (channel args in gRPC runtime)
to configure the channel.
Returns:
A Channel object. | codesearchnet |
def Execute(self, http, sleep_between_polls=5, max_retries=5, max_batch_size=None, batch_request_callback=None):
requests = [request for request in self.api_requests if (not request.terminal_state)]
batch_size = (max_batch_size or len(requests))
for attempt in range(max_retries):
if attempt:
... | Execute all of the requests in the batch.
Args:
http: httplib2.Http object for use in the request.
sleep_between_polls: Integer number of seconds to sleep between
polls.
max_retries: Max retries. Any requests that have not succeeded by
this number of retries simply report the last response or
exception, whatever it ha... | codesearchnet |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.