code stringlengths 20 4.93k | docstring stringlengths 33 1.27k | source stringclasses 3
values |
|---|---|---|
def all_min(tensors):
return _apply_all_reduce('min', tensors) | Returns a list of tensors with the all-reduce min across `tensors`.
The computation is done with an all-reduce operation, so if only some of the
returned tensors are evaluated then the computation will hang.
Args:
tensors: The input tensors across which to reduce; must be assigned
to GPU devices.
Returns:
List of te... | github-repos |
def parse(filename, encoding=None):
with open(filename, encoding=encoding) as source:
for line in source:
for word in line.split():
yield word | !DEMO!
Simple file parsing generator
Args:
filename: absolute or relative path to file on disk
encoding: encoding string that is passed to open function | juraj-google-style |
def _GetSourceFileSystem(self, source_path_spec, resolver_context=None):
if not source_path_spec:
raise RuntimeError('Missing source.')
file_system = path_spec_resolver.Resolver.OpenFileSystem(
source_path_spec, resolver_context=resolver_context)
type_indicator = source_path_spec.type_i... | Retrieves the file system of the source.
Args:
source_path_spec (dfvfs.PathSpec): source path specification of the file
system.
resolver_context (dfvfs.Context): resolver context.
Returns:
tuple: containing:
dfvfs.FileSystem: file system.
dfvfs.PathSpec: mount point path specification that refers
to the base locatio... | juraj-google-style |
def abort_all_if(expr, reason, extras=None):
if expr:
abort_all(reason, extras) | Abort all subsequent tests, if the expression evaluates to True.
Args:
expr: The expression that is evaluated.
reason: The reason to abort.
extras: An optional field for extra information to be included in
test result.
Raises:
signals.TestAbortAll: Abort all subsequent tests. | github-repos |
def __init__(self, paths, case_sensitive=True, path_segment_separator='/'):
super(PathFilterScanTree, self).__init__()
self._case_sensitive = case_sensitive
self._path_segment_separator = path_segment_separator
self._root_node = None
if not self._case_sensitive:
paths = [path.lower() for... | Initializes and builds a path filter scan tree.
Args:
paths: a list of strings containing the paths.
case_sensitive: optional boolean value to indicate string matches should
be case sensitive.
path_segment_separator: optional string containing the path segment
separator. | juraj-google-style |
def find_required_filehandlers(self, requirements, filename_info):
req_fh = []
filename_info = set(filename_info.items())
if requirements:
for requirement in requirements:
for fhd in self.file_handlers[requirement]:
if set(fhd.filename_info.items()).issubset(filename_info... | Find the necessary file handlers for the given requirements.
We assume here requirements are available.
Raises:
KeyError, if no handler for the given requirements is available.
RuntimeError, if there is a handler for the given requirements,
but it doesn't match the filename info. | codesearchnet |
def make_connection(self): | Makes a connection to the snippet server on the remote device.
This function makes a connection to the server and sends a handshake
request to ensure the server is available for upcoming RPCs.
There are two types of connections used by snippet clients:
* The client makes a new connection each time it needs to send an... | github-repos |
def _get_attributes(self, attributes):
params = []
if isinstance(attributes, dict):
for attribute_key in attributes.keys():
attribute_value = attributes.get(attribute_key)
if validator.is_attribute_valid(attribute_key, attribute_value):
attribute_id = self.config.... | Get attribute(s) information.
Args:
attributes: Dict representing user attributes and values which need to be recorded.
Returns:
List consisting of valid attributes for the user. Empty otherwise. | juraj-google-style |
def CheckFlowCanBeStartedOnClient(flow_name):
flow_cls = flow.GRRFlow.GetPlugin(flow_name)
if flow_cls.category:
return True
else:
raise access_control.UnauthorizedAccess(("Flow %s can't be started on a client by non-suid users." % flow_name)) | Checks if flow can be started on a particular client.
Only flows with a category can bestarted. Having a category means that the
flow will be accessible from the UI.
Args:
flow_name: Name of the flow to check access for.
Returns:
True if flow is externally accessible.
Raises:
access_control.UnauthorizedAccess: if fl... | codesearchnet |
def AddFile(self, fd, external=True):
files_for_write = []
for sub_store in self.GetChildrenByPriority(allow_external=external):
new_file = sub_store.AddFile(fd)
if new_file:
files_for_write.append(new_file)
fd.Seek(0)
while files_for_write:
data = fd.Read(self.CH... | Create a new file in the file store.
We delegate the actual file addition to our contained
implementations. Implementations can either implement the AddFile() method,
returning a file like object which will be written on, or directly support
the AddBlobToStore() method which can copy the VFSBlobImage efficiently.
Arg... | juraj-google-style |
def __init__(self, channel):
self.Predict = channel.unary_unary(
"/google.cloud.automl.v1beta1.PredictionService/Predict",
request_serializer=google_dot_cloud_dot_automl__v1beta1_dot_proto_dot_prediction__service__pb2.PredictRequest.SerializeToString,
response_deseri... | Constructor.
Args:
channel: A grpc.Channel. | juraj-google-style |
def __init__(self, **namespaces):
super(Configuration, self).__init__()
for key, entry in compat.iteritems(namespaces):
self.register(key, entry) | Initialize a configuration with a series of namespaces.
Args:
**namespaces: Each keyword should be a Namespace object which will
be added to the configuration file.
Raises:
TypeError: If an entry is not a Namespace object.
ValueError: If the namespace is already registered. | juraj-google-style |
def persist_compilestats(run, session, stats):
for stat in stats:
stat.run_id = run.id
session.add(stat) | Persist the run results in the database.
Args:
run: The run we attach the compilestats to.
session: The db transaction we belong to.
stats: The stats we want to store in the database. | juraj-google-style |
def find_divisors(n):
if not isinstance(n, int):
raise TypeError("Expecting a strictly positive integer")
if n <= 0:
raise ValueError("Expecting a strictly positive integer")
for i in range(1, int(n**0.5) + 1):
if n % i == 0:
divisors = {i, n
for divis... | Find all the positive divisors of the given integer n.
Args:
n (int): strictly positive integer
Returns:
A generator of all the positive divisors of n
Raises:
TypeError: if n is not an integer
ValueError: if n is negative | juraj-google-style |
def _ParseCmdItem(self, cmd_input, template_file=None):
fsm = textfsm.TextFSM(template_file)
if not self._keys:
self._keys = set(fsm.GetValuesByAttrib('Key'))
table = texttable.TextTable()
table.header = fsm.header
for record in fsm.ParseText(cmd_input):
table.Appen... | Creates Texttable with output of command.
Args:
cmd_input: String, Device response.
template_file: File object, template to parse with.
Returns:
TextTable containing command output.
Raises:
CliTableError: A template was not found for the given command. | juraj-google-style |
def _rand_dtype(rand, shape, dtype, scale=1.0, post=lambda x: x):
r = lambda: numpy_compat.np_asarray(scale * rand(*_dims_of_shape(shape)), dtype)
if onp.issubdtype(dtype, onp.complexfloating):
vals = r() + 1j * r()
else:
vals = r()
return _cast_to_shape(numpy_compat.np_asarray(post(vals... | Produce random values given shape, dtype, scale, and post-processor.
Args:
rand: a function for producing random values of a given shape, e.g. a
bound version of either onp.RandomState.randn or onp.RandomState.rand.
shape: a shape value as a tuple of positive integers.
dtype: a numpy dtype.
scale: optional, a multipli... | github-repos |
def GetLogicalLines(self):
self._StartNewLine()
return self._logical_lines | Fetch the result of the tree walk.
Note: only call this after visiting the whole tree.
Returns:
A list of LogicalLine objects. | github-repos |
def _ParseCachedEntry2003(self, value_data, cached_entry_offset):
try:
cached_entry = self._ReadStructureFromByteStream(value_data[cached_entry_offset:], cached_entry_offset, self._cached_entry_data_type_map)
except (ValueError, errors.ParseError) as exception:
raise errors.ParseError('Unable to... | Parses a Windows 2003 cached entry.
Args:
value_data (bytes): value data.
cached_entry_offset (int): offset of the first cached entry data
relative to the start of the value data.
Returns:
AppCompatCacheCachedEntry: cached entry.
Raises:
ParseError: if the value data could not be parsed. | codesearchnet |
def object_hook(self, object_dict):
instance = self.decoder(object_dict)
self.condition_list.append(instance)
self.index += 1
return self.index | Hook which when passed into a json.JSONDecoder will replace each dict
in a json string with its index and convert the dict to an object as defined
by the passed in condition_decoder. The newly created condition object is
appended to the conditions_list.
Args:
object_dict: Dict representing an object.
Returns:
An inde... | juraj-google-style |
def diff(self, sym: Symbol, n: int = 1, expand_simplify: bool = True):
if not isinstance(sym, sympy.Basic):
raise TypeError("%s needs to be a Sympy symbol" % sym)
if sym.free_symbols.issubset(self.free_symbols):
deriv = QuantumDeriv... | Differentiate by scalar parameter `sym`.
Args:
sym: What to differentiate by.
n: How often to differentiate
expand_simplify: Whether to simplify the result.
Returns:
The n-th derivative. | juraj-google-style |
def put(self, item, *args, **kwargs):
if (not self.enabled):
return
timeout = kwargs.pop('timeout', None)
if (timeout is None):
timeout = self.default_timeout
cache_key = self.make_key(args, kwargs)
with self._cache_lock:
self._cache[cache_key] = ((time() + timeout), item) | Put an item into the cache, for this combination of args and kwargs.
Args:
*args: any arguments.
**kwargs: any keyword arguments. If ``timeout`` is specified as one
of the keyword arguments, the item will remain available
for retrieval for ``timeout`` seconds. If ``timeout`` is
`None` or not specified, the ``default_t... | codesearchnet |
def render_header(image: np.ndarray, header: str, input_data_format: Optional[Union[str, ChildProcessError]]=None, **kwargs):
requires_backends(render_header, 'vision')
image = to_pil_image(image, input_data_format=input_data_format)
header_image = render_text(header, **kwargs)
new_width = max(header_im... | Renders the input text as a header on the input image.
Args:
image (`np.ndarray`):
The image to render the header on.
header (`str`):
The header text.
data_format (`Union[ChannelDimension, str]`, *optional*):
The data format of the image. Can be either "ChannelDimension.channels_first" or
"ChannelDimension.channels_la... | github-repos |
def get_asset_filename_to_add(asset_filepath, asset_filename_map):
asset_filename = os.path.basename(asset_filepath)
if asset_filename not in asset_filename_map:
return asset_filename
other_asset_filepath = asset_filename_map[asset_filename]
if other_asset_filepath == asset_filepath:
ret... | Get a unique basename to add to the SavedModel if this file is unseen.
Assets come from users as full paths, and we save them out to the
SavedModel as basenames. In some cases, the basenames collide. Here,
we dedupe asset basenames by first checking if the file is the same,
and, if different, generate and return an in... | github-repos |
def resolve_variables(variables, context, provider):
for variable in variables:
variable.resolve(context, provider) | Given a list of variables, resolve all of them.
Args:
variables (list of :class:`stacker.variables.Variable`): list of
variables
context (:class:`stacker.context.Context`): stacker context
provider (:class:`stacker.provider.base.BaseProvider`): subclass of the
base provider | codesearchnet |
def matrices_to_flat_transforms(transform_matrices):
with ops.name_scope('matrices_to_flat_transforms'):
transform_matrices = ops.convert_to_tensor(transform_matrices, name='transform_matrices')
if transform_matrices.shape.ndims not in (2, 3):
raise ValueError('Matrices should be 2D or 3... | Converts affine matrices to `tf.contrib.image` projective transforms.
Note that we expect matrices that map output coordinates to input coordinates.
To convert forward transformation matrices, call `tf.linalg.inv` on the
matrices and use the result here.
Args:
transform_matrices: One or more affine transformation mat... | github-repos |
def loop_until_valid_response(prompt):
responses = {"Y": True, "YES": True, "TRUE": True,
"N": False, "NO": False, "FALSE": False}
response = ""
while response.upper() not in responses:
response = raw_input(prompt)
return responses[response.upper()] | Loop over entering input until it is a valid bool-ish response.
Args:
prompt: Text presented to user.
Returns:
The bool value equivalent of what was entered. | juraj-google-style |
def path(self, source, target):
visited = set(source.split('+'))
targets = (set(target.split('+')) - visited)
for tablename in visited.union(targets):
self[tablename]
if (len(targets) == 0):
return []
paths = [[(tablename, None)] for tablename in visited]
while True:
newp... | Find the path of id fields connecting two tables.
This is just a basic breadth-first-search. The relations file
should be small enough to not be a problem.
Returns:
list: (table, fieldname) pairs describing the path from
the source to target tables
Raises:
:class:`delphin.exceptions.ItsdbError`: when no path is
found... | codesearchnet |
def graph(self, as_dot=False):
if not self.has_graph:
return None
if not as_dot:
if self.graph_ is None:
self.graph_ = read_graph_from_string(self.graph_string)
return self.graph_
if self.graph_string:
if... | Get the resolve graph.
Args:
as_dot: If True, get the graph as a dot-language string. Otherwise,
a pygraph.digraph object is returned.
Returns:
A string or `pygraph.digraph` object, or None if there is no graph
associated with the resolve. | juraj-google-style |
def Serialize(self, writer):
self.SerializeUnsigned(writer)
writer.WriteSerializableArray(self.scripts) | Serialize object.
Args:
writer (neo.IO.BinaryWriter): | juraj-google-style |
def event_stream(app, *, filter_by_prefix=None):
q = Queue()
def handle_event(event):
if ((filter_by_prefix is None) or ((filter_by_prefix is not None) and event['type'].startswith(filter_by_prefix))):
q.put(event)
def receive_events():
with app.connection() as connection:
... | Generator function that returns celery events.
This function turns the callback based celery event handling into a generator.
Args:
app: Reference to a celery application object.
filter_by_prefix (str): If not None, only allow events that have a type that
starts with this prefix to yield an generator event.
Returns:... | codesearchnet |
def _get_sample_generator(samples):
if isinstance(samples, Mapping):
def samples_generator():
for ind in range(samples[list(samples.keys())[0]].shape[0]):
(yield np.array([samples[s][(ind, :)] for s in sorted(samples)]))
elif isinstance(samples, np.ndarray):
def sam... | Get a sample generator from the given polymorphic input.
Args:
samples (ndarray, dict or generator): either an matrix of shape (d, p, n) with d problems, p parameters and
n samples, or a dictionary with for every parameter a matrix with shape (d, n) or, finally,
a generator function that yields sample arrays of shape ... | codesearchnet |
def _chglog(amend: bool = False, stage: bool = False, next_version: str = None, auto_next_version: bool = False):
if config.CHANGELOG_DISABLE():
LOGGER.info('skipping changelog update as per config')
else:
epab.utils.ensure_exe('git')
epab.utils.ensure_exe('gitchangelog')
LO... | Writes the changelog
Args:
amend: amend last commit with changes
stage: stage changes | juraj-google-style |
def to_representation(self, instance):
updated_course = copy.deepcopy(instance)
enterprise_customer_catalog = self.context['enterprise_customer_catalog']
updated_course['enrollment_url'] = enterprise_customer_catalog.get_course_enrollment_url(updated_course['key'])
for course_run in updated_course['cour... | Return the updated course data dictionary.
Arguments:
instance (dict): The course data.
Returns:
dict: The updated course data. | codesearchnet |
def guided_registration(request, page_number=None):
PAGE_PROFILE = 1
PAGE_TICKET = 2
PAGE_PRODUCTS = 3
PAGE_PRODUCTS_MAX = 4
TOTAL_PAGES = 4
ticket_category = inventory.Category.objects.get(id=settings.TICKET_PRODUCT_CATEGORY)
cart = CartController.for_user(request.user)
attendee = peopl... | Goes through the registration process in order, making sure user sees
all valid categories.
The user must be logged in to see this view.
Parameter:
page_number:
1) Profile form (and e-mail address?)
2) Ticket type
3) Remaining products
4) Mark registration as complete
Returns:
render: Renders ``registrasion/guided_r... | codesearchnet |
def _get_required_params_for_conversion(self, event_key, event_tags):
snapshot = {}
event_dict = {
self.EventParams.EVENT_ID: self.config.get_event(event_key).id,
self.EventParams.TIME: self._get_time(),
self.EventParams.KEY: event_key,
self.EventParams.UUID: str(uuid.uuid4())
... | Get parameters that are required for the conversion event to register.
Args:
event_key: Key representing the event which needs to be recorded.
event_tags: Dict representing metadata associated with the event.
Returns:
Dict consisting of the decisions and events info for conversion event. | juraj-google-style |
def loadfile(method=True, writable=False, create=False):
def convert_file_args(args, kwargs):
filething = (args[0] if args else None)
filename = kwargs.pop('filename', None)
fileobj = kwargs.pop('fileobj', None)
return (filething, filename, fileobj, args[1:], kwargs)
def wrap(f... | A decorator for functions taking a `filething` as a first argument.
Passes a FileThing instance as the first argument to the wrapped function.
Args:
method (bool): If the wrapped functions is a method
writable (bool): If a filename is passed opens the file readwrite, if
passed a file object verifies that it is writab... | codesearchnet |
def Collect(self, top_frame):
frame = top_frame
top_line = self.breakpoint['location']['line']
breakpoint_frames = self.breakpoint['stackFrames']
try:
if ('expressions' in self.breakpoint):
self.breakpoint['evaluatedExpressions'] = [self._CaptureExpression(top_frame, expression) for ... | Collects call stack, local variables and objects.
Starts collection from the specified frame. We don't start from the top
frame to exclude the frames due to debugger. Updates the content of
self.breakpoint.
Args:
top_frame: top frame to start data collection. | codesearchnet |
def in_coord_list_pbc(fcoord_list, fcoord, atol=1e-8):
return len(find_in_coord_list_pbc(fcoord_list, fcoord, atol=atol)) > 0 | Tests if a particular fractional coord is within a fractional coord_list.
Args:
fcoord_list: List of fractional coords to test
fcoord: A specific fractional coord to test.
atol: Absolute tolerance. Defaults to 1e-8.
Returns:
True if coord is in the coord list. | juraj-google-style |
def invoke_string(self, line):
line = str(line)
if len(line) == 0:
return True
if line[0] == u'
return True
args = self._split_line(line)
return self.invoke(args) | Parse and invoke a string line.
Args:
line (str): The line that we want to parse and invoke.
Returns:
bool: A boolean specifying if the last function created a new context
(False if a new context was created) and a list with the remainder of the
command line if this function did not consume all arguments.) | juraj-google-style |
def altitude_diff(msg):
tc = common.typecode(msg)
if (tc != 19):
raise RuntimeError(('%s: Not a airborne velocity message, expecting TC=19' % msg))
msgbin = common.hex2bin(msg)
sign = ((- 1) if int(msgbin[80]) else 1)
value = common.bin2int(msgbin[81:88])
if ((value == 0) or (value == 12... | Decode the differece between GNSS and barometric altitude
Args:
msg (string): 28 bytes hexadecimal message string, TC=19
Returns:
int: Altitude difference in ft. Negative value indicates GNSS altitude
below barometric altitude. | codesearchnet |
def execute(self, triple_map, output, **kwargs):
subjects = []
found_elements = self.source.xpath(str(triple_map.logicalSource.iterator), namespaces=self.xml_ns)
for element in found_elements:
subject = self.generate_term(term_map=triple_map.subjectMap, element=element, **kwargs)
start = len... | Method executes mapping between source
Args:
-----
triple_map: SimpleNamespace, Triple Map | codesearchnet |
def delete(self, service):
url = self._url_format(service)
return self.rest_action(
self._session.delete, url
) | Generic DELETE operation for Learning Modules API.
Args:
service (str): The endpoint service to use, i.e. gradebook
Raises:
requests.RequestException: Exception connection error
ValueError: Unable to decode response content
Returns:
list: the json-encoded content of the response | juraj-google-style |
def transformer_prepare_decoder(targets, hparams, features=None):
if hparams.causal_decoder_self_attention:
if hparams.prepend_mode == "prepend_inputs_full_attention":
decoder_self_attention_bias = (
common_attention.attention_bias_prepend_inputs_full_attention(
common_attent... | Prepare one shard of the model for the decoder.
Args:
targets: a Tensor.
hparams: run hyperparameters
features: optionally pass the entire features dictionary as well. This is
needed now for "packed" datasets.
Returns:
decoder_input: a Tensor, bottom of decoder stack
decoder_self_attention_bias: a bias tensor for use... | juraj-google-style |
def create_or_update_video_transcript(video_id, language_code, metadata, file_data=None):
metadata = {
prop: value
for prop, value in six.iteritems(metadata)
if prop in ['provider', 'language_code', 'file_name', 'file_format'] and value
}
file_format = metadata.get('file_f... | Create or Update video transcript for an existing video.
Arguments:
video_id: it can be an edx_video_id or an external_id extracted from external sources in a video component.
language_code: language code of a video transcript
metadata (dict): A dict containing (to be overwritten) properties
file_data (InMemoryUploade... | juraj-google-style |
def f2format(filename):
print(('Now converting %r...' % filename))
encoding = os.getenv('F2FORMAT_ENCODING', LOCALE_ENCODING)
lineno = dict()
content = list()
with open(filename, 'r', encoding=encoding) as file:
lineno[1] = 0
for (lnum, line) in enumerate(file, start=1):
... | Wrapper works for conversion.
Args:
- filename -- str, file to be converted | codesearchnet |
def add_arguments(self, parser):
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-l', '--list', nargs='?', type=str.lower, default='_', choices=['usb', 'ip'], help='list all the connected emulators')
group.add_argument('-s', '--supported', nargs=1, help='query whether a device... | Adds the arguments for the emulator command.
Args:
self (EmulatorCommand): the ``EmulatorCommand`` instance
parser (argparse.ArgumentParser): parser to add the commands to
Returns:
``None`` | codesearchnet |
def list_documents(project_id, knowledge_base_id):
import dialogflow_v2beta1 as dialogflow
client = dialogflow.DocumentsClient()
knowledge_base_path = client.knowledge_base_path(project_id, knowledge_base_id)
print('Documents for Knowledge Id: {}'.format(knowledge_base_id))
for document in client.li... | Lists the Documents belonging to a Knowledge base.
Args:
project_id: The GCP project linked with the agent.
knowledge_base_id: Id of the Knowledge base. | codesearchnet |
def convert_upsample_bilinear(params, w_name, scope_name, inputs, layers, weights, names):
print('Converting upsample...')
if names == 'short':
tf_name = 'UPSL' + random_string(4)
elif names == 'keep':
tf_name = w_name
else:
tf_name = w_name + str(random.random())
outp... | Convert upsample_bilinear2d layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras layers | juraj-google-style |
def repsep(parser: Union[(Parser, Sequence[Input])], separator: Union[(Parser, Sequence[Input])]) -> RepeatedSeparatedParser:
if isinstance(parser, str):
parser = lit(parser)
if isinstance(separator, str):
separator = lit(separator)
return RepeatedSeparatedParser(parser, separator) | Match a parser zero or more times separated by another parser.
This matches repeated sequences of ``parser`` separated by ``separator``. A
list is returned containing the value from each match of ``parser``. The
values from ``separator`` are discarded. If there are no matches, an empty
list is returned.
Args:
parser:... | codesearchnet |
def encode(self, object_):
if self.enforce_reversible:
self.enforce_reversible = False
if self.decode(self.encode(object_)) != object_:
raise ValueError('Encoding is not reversible for "%s"' % object_)
self.enforce_reversible = True
return ob... | Encodes an object.
Args:
object_ (object): Object to encode.
Returns:
object: Encoding of the object. | juraj-google-style |
def get(self, name: str) -> Optional[ListEntry]:
parts = name.split(self._delimiter)
try:
node = self._find(self._root, *parts)
except KeyError:
return None
else:
marked = self._marked.get(name)
return ListEntry(name, node.exists, ... | Return the named entry in the list tree.
Args:
name: The entry name. | juraj-google-style |
def notebook_content(model, notebook_comms_target=None, theme=FromCurdoc):
if (not isinstance(model, Model)):
raise ValueError('notebook_content expects a single Model instance')
with OutputDocumentFor([model], apply_theme=theme, always_new=True) as new_doc:
(docs_json, [render_item]) = standalo... | Return script and div that will display a Bokeh plot in a Jupyter
Notebook.
The data for the plot is stored directly in the returned HTML.
Args:
model (Model) : Bokeh object to render
notebook_comms_target (str, optional) :
A target name for a Jupyter Comms object that can update
the document that is rendered to thi... | codesearchnet |
def is44(msg):
if allzeros(msg):
return False
d = hex2bin(data(msg))
if wrongstatus(d, 5, 6, 23):
return False
if wrongstatus(d, 35, 36, 46):
return False
if wrongstatus(d, 47, 48, 49):
return False
if wrongstatus(d, 50, 51, 56):
return False
if (bin2i... | Check if a message is likely to be BDS code 4,4.
Meteorological routine air report
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
bool: True or False | codesearchnet |
def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error):
line = clean_lines.elided[linenum]
match = Search(pattern, line)
if (not match):
return False
context = line[0:(match.start(1) - 1)]
if Match('.*\\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\\s*$', context):
... | Checks for a C-style cast by looking for the pattern.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
cast_type: The string for the C++ cast to recommend. This is either
reinterpret_cast, static_cast, or const_cast, dep... | codesearchnet |
def compute_serialized_parameters_size(num_parameters: int, dtype: ParameterFormat) -> int:
return num_parameters * dtype.size | Compute the size taken by all the parameters in the given the storage format when serializing the model
Args:
num_parameters: Number of parameters to be saved
dtype: The data format each parameter will be saved
Returns:
Size (in byte) taken to save all the parameters | github-repos |
def _compute_static_batch_dim(self):
new_batch_dim = tensor_util.constant_value(self._batch_sizes)
if new_batch_dim is None:
return None
if isinstance(new_batch_dim, np.ndarray):
if len(new_batch_dim.shape) == 1:
if np.all(new_batch_dim == new_batch_dim[0]):
new_b... | Computes the static batch dimension of a dataset if it can be determined.
Given the RebatchDataset parameters, determines the batch dimension of this
dataset statically. Returns None if this cannot be determined or is
variable.
Returns:
An integer representing the batch dimension of the dataset. If it cannot
be deter... | github-repos |
def from_series(self, series, add_index_column=True):
if series.name:
self.headers = [series.name]
else:
self.headers = ["value"]
self.type_hints = [self.__get_typehint_from_dtype(series.dtype)]
if add_index_column:
self.headers = [""] + se... | Set tabular attributes to the writer from :py:class:`pandas.Series`.
Following attributes are set by the method:
- :py:attr:`~.headers`
- :py:attr:`~.value_matrix`
- :py:attr:`~.type_hints`
Args:
series(pandas.Series):
Input pandas.Series object.
add_index_column(bool, optional):
If |True|, add a column of ``index`` ... | juraj-google-style |
def _cache_form_details(self, form):
cache = FormCache()
form['model']['form_key'] = cache.form_id
form['model']['form_name'] = self.__class__.__name__
cache.set(
{
'model': list(form['model'].keys()),
'non_data_fields': self.non_dat... | Caches some form details to lates process and validate incoming (response) form data
Args:
form: form dict | juraj-google-style |
def __init__(self, fut, file_obj, tid=None):
super().__init__()
self._tid = tid
if isinstance(file_obj, str):
self.file_obj = File(file_obj)
elif isinstance(file_obj, File):
self.file_obj = file_obj
else:
raise ValueError("DataFuture m... | Construct the DataFuture object.
If the file_obj is a string convert to a File.
Args:
- fut (AppFuture) : AppFuture that this DataFuture will track
- file_obj (string/File obj) : Something representing file(s)
Kwargs:
- tid (task_id) : Task id that this DataFuture tracks | juraj-google-style |
def _reset_build_compile_trackers(model):
model.built = False
model.inputs = None
model.outputs = None
model._is_compiled = False
if not ops.executing_eagerly_outside_functions():
model._v1_compile_was_called = False
model.optimizer = None | Reset state trackers for model.
Note that we do not actually zero out attributes such as optimizer,
but instead rely on the expectation that all of the attrs will be
over-written on calling build/compile/etc. This is somewhat fragile,
insofar as we check elsewhere for the presence of these attributes as
evidence of ha... | github-repos |
def substring_evaluator(self, index):
condition_name = self.condition_data[index][0]
condition_value = self.condition_data[index][1]
user_value = self.attributes.get(condition_name)
if not isinstance(condition_value, string_types):
self.logger.warning(audience_logs.UNKNOWN_CONDITION_VALUE.fo... | Evaluate the given substring match condition for the given user attributes.
Args:
index: Index of the condition to be evaluated.
Returns:
Boolean:
- True if the condition value is a substring of the user attribute value.
- False if the condition value is not a substring of the user attribute value.
None: if the condi... | juraj-google-style |
def create_unique_autosave_filename(self, filename, autosave_dir):
basename = osp.basename(filename)
autosave_filename = osp.join(autosave_dir, basename)
if (autosave_filename in self.name_mapping.values()):
counter = 0
(root, ext) = osp.splitext(basename)
while (autosave_filename in... | Create unique autosave file name for specified file name.
Args:
filename (str): original file name
autosave_dir (str): directory in which autosave files are stored | codesearchnet |
def _start_job(self, request: 'bigquery.BigqueryJobsInsertRequest', stream=None):
try:
upload = None
if stream:
upload = Upload.FromStream(stream, mime_type=UNKNOWN_MIME_TYPE)
response = self.client.jobs.Insert(request, upload=upload)
_LOGGER.info('Started BigQuery job: %... | Inserts a BigQuery job.
If the job exists already, it returns it.
Args:
request (bigquery.BigqueryJobsInsertRequest): An insert job request.
stream (IO[bytes]): A bytes IO object open for reading. | github-repos |
def setKstar(self, term_i, Ks):
assert (Ks.shape[0] == self.N)
self.vd.getTerm(term_i).getKcf().setK0cross(Ks) | Set the kernel for predictions
Args:
term_i: index of the term we are interested in
Ks: (TODO: is this the covariance between train and test or the covariance between test points?) | codesearchnet |
def get_single_item_from_sequence(sequence, condition, ErrorClass=ValueError, no_item_error_message='No item matched condition', too_many_item_error_message='Too many items matched condition', append_sequence_to_error_message=True):
filtered_sequence = [item for item in sequence if condition(item)]
number_of_it... | Return an item from a python sequence based on the given condition.
Args:
sequence (sequence): The sequence to filter
condition: A function that serves to filter items from `sequence`. Function
must have one argument (a single item from the sequence) and return a boolean.
ErrorClass (Exception): The error type raised ... | codesearchnet |
def start(component, exact):
version_file = conf.get_path('version_file', 'VERSION')
develop = conf.get('git.devel_branch', 'develop')
common.assert_on_branch(develop)
with conf.within_proj_dir():
out = shell.run('git status --porcelain', capture=True).stdout
lines = out.spli... | Create a new release branch.
Args:
component (str):
Version component to bump when creating the release. Can be *major*,
*minor* or *patch*.
exact (str):
The exact version to set for the release. Overrides the component
argument. This allows to re-release a version if something went
wrong with the release upload. | juraj-google-style |
def _TSKFileTimeCopyToStatTimeTuple(self, tsk_file, time_value):
if ((not tsk_file) or (not tsk_file.info) or (not tsk_file.info.meta) or (not tsk_file.info.fs_info)):
raise errors.BackEndError('Missing TSK File .info, .info.meta. or .info.fs_info')
stat_time = getattr(tsk_file.info.meta, time_value, No... | Copies a SleuthKit file object time value to a stat timestamp tuple.
Args:
tsk_file (pytsk3.File): TSK file.
time_value (str): name of the time value.
Returns:
tuple[int, int]: number of seconds since 1970-01-01 00:00:00 and fraction
of second in 100 nano seconds intervals. The number of seconds is None
on error, or ... | codesearchnet |
def has_entities(status):
try:
if sum(len(v) for v in status.entities.values()) > 0:
return True
except AttributeError:
if sum(len(v) for v in status['entities'].values()) > 0:
return True
return False | Returns true if a Status object has entities.
Args:
status: either a tweepy.Status object or a dict returned from Twitter API | juraj-google-style |
def update_paths_and_config(self, config, pkg_dir_name, pkg_cache_dir=None):
if (pkg_cache_dir is None):
pkg_cache_dir = self.package_cache_dir
cached_dir_path = os.path.join(pkg_cache_dir, pkg_dir_name)
if config.get('paths'):
for path in config['paths']:
path_to_append = os.pat... | Handle remote source defined sys.paths & configs.
Args:
config (dict): git config dictionary
pkg_dir_name (string): directory name of the stacker archive
pkg_cache_dir (string): fully qualified path to stacker cache
cache directory | codesearchnet |
def load_file(file_path, credentials=None):
if file_path.startswith('gs:
return _load_file_from_gcs(file_path, credentials)
else:
return open(file_path, 'r') | Load a file from either local or gcs.
Args:
file_path: The target file path, which should have the prefix 'gs://' if
to be loaded from gcs.
credentials: Optional credential to be used to load the file from gcs.
Returns:
A python File object if loading file from local or a StringIO object if
loading from gcs. | codesearchnet |
def init_from_class_batches(self, class_batches, num_shards=None):
shards_for_submissions = {}
shard_idx = 0
for idx, (batch_id, batch_val) in enumerate(iteritems(class_batches)):
work_id = DEFENSE_WORK_ID_PATTERN.format(idx)
submission_id = batch_val['submission_id']
shard_id = None
... | Initializes work pieces from classification batches.
Args:
class_batches: dict with classification batches, could be obtained
as ClassificationBatches.data
num_shards: number of shards to split data into,
if None then no sharding is done. | juraj-google-style |
def ColumnTypeParser(description):
if (not description):
raise DataTableException('Description error: empty description given')
if (not isinstance(description, (six.string_types, tuple))):
raise DataTableException(('Description error: expected either string or tuple, got %s.' % type(description)... | Parses a single column description. Internal helper method.
Args:
description: a column description in the possible formats:
'id'
('id',)
('id', 'type')
('id', 'type', 'label')
('id', 'type', 'label', {'custom_prop1': 'custom_val1'})
Returns:
Dictionary with the following keys: id, label, type, and
custom_properties w... | codesearchnet |
def run(self, row, **kwargs):
self.source = row
kwargs['output'] = self.__graph__()
super(CSVRowProcessor, self).run(**kwargs)
return kwargs['output'] | Methods takes a row and depending if a dict or list,
runs RML rules.
Args:
-----
row(Dict, List): Row from CSV Reader | juraj-google-style |
def pb(scalars_layout):
import tensorflow.compat.v1 as tf
assert isinstance(scalars_layout, layout_pb2.Layout)
tensor = tf.make_tensor_proto(
scalars_layout.SerializeToString(), dtype=tf.string)
tf_summary_metadata = tf.SummaryMetadata.FromString(
metadata.create_summary_metadata().SerializeT... | Creates a summary that contains a layout.
When users navigate to the custom scalars dashboard, they will see a layout
based on the proto provided to this function.
Args:
scalars_layout: The scalars_layout_pb2.Layout proto that specifies the
layout.
Returns:
A summary proto containing the layout. | juraj-google-style |
def get_func_graphs(op):
def _get_func_graph_for_branch(name_attr_list, cached_attr_name=None):
func_graph = None
if cached_attr_name is not None:
func_graph = getattr(op, cached_attr_name, None)
inputs = op.inputs[1:]
if func_graph is None:
input_sh... | Returns `FuncGraph`s for the input op branches.
Args:
op: The If or Case Operation.
Returns:
A tuple of the `FuncGraph`s of the then_branch and else_branch (all branches
for Case). | github-repos |
def get_filename(self, tag):
if tag.find('filename', recursive=False) is not None:
return tag.filename.contents[0]
elif tag.find('anchorfile', recursive=False) is not None:
return tag.anchorfile.contents[0] + ' | Extract and return a documentation filename from a tag.
Override as necessary, though this default implementation probably
covers all the cases of interest.
Args:
tag: A BeautifulSoup Tag that satisfies match_criterion.
Returns:
A string that would be appropriate to use as the documentation
filename for an entry in ... | juraj-google-style |
def convert_to_rgb(self, video: 'torch.Tensor') -> VideoInput:
video = F.grayscale_to_rgb(video)
if video.shape[-3] == 3 or not (video[..., 3, :, :] < 255).any():
return video
alpha = video[..., 3, :, :] / 255.0
video = (1 - alpha[..., None, :, :]) * 255 + alpha[..., None, :, :] * video[..., :3,... | Converts a video to RGB format.
Args:
video (`"torch.Tensor"`):
The video to convert.
Returns:
`torch.Tensor`: The converted video. | github-repos |
def __init__(self, regex: str, option_suffix: str):
super().__init__(option_suffix)
self._regex = self._build_matcher(regex) | Create a new instance.
Args:
regex:
The regular expression describing the entry line to match. The
first matching line is selected. The expression must contain a
single capture group that contains the data to return.
option_suffix:
Suffix for each configuration option | juraj-google-style |
def build_grab_exception(ex, curl):
if (ex.args[0] == 23):
if (getattr(curl, 'grab_callback_interrupted', None) is True):
return None
else:
return error.GrabNetworkError(ex.args[1], ex)
elif (ex.args[0] == 28):
return error.GrabTimeoutError(ex.args[1], ex)
eli... | Build Grab exception from the pycurl exception
Args:
ex - the original pycurl exception
curl - the Curl instance raised the exception | codesearchnet |
def search(self,limit,start_date=None,end_date=None,clipper=None):
search_string = self._query_builder(start_date,
end_date,
clipper
)
... | The main method of Search class. It searches tTheia Landsat API
Returns python dictionary
Arguments:
start_date -- date string. format: YYYY-MM-DD
end_date -- date string. format: YYYY-MM-DD
limit -- integer specigying the maximum results return.
clipper -- clipper object : clipper.bbox / clipper.town | juraj-google-style |
def check_supported_model_or_raise(model: Union['PreTrainedModel', 'TFPreTrainedModel'], feature: str='default') -> Tuple[str, Callable]:
model_type = model.config.model_type.replace('_', '-')
model_name = getattr(model, 'name', '')
model_features = FeaturesManager.get_supported_features_for_model_type(mode... | Check whether or not the model has the requested features.
Args:
model: The model to export.
feature: The name of the feature to check if it is available.
Returns:
(str) The type of the model (OnnxConfig) The OnnxConfig instance holding the model export properties. | github-repos |
def _analyze_indexed_fields(indexed_fields):
result = {}
for field_name in indexed_fields:
if (not isinstance(field_name, basestring)):
raise TypeError(('Field names must be strings; got %r' % (field_name,)))
if ('.' not in field_name):
if (field_name in result):
... | Internal helper to check a list of indexed fields.
Args:
indexed_fields: A list of names, possibly dotted names.
(A dotted name is a string containing names separated by dots,
e.g. 'foo.bar.baz'. An undotted name is a string containing no
dots, e.g. 'foo'.)
Returns:
A dict whose keys are undotted names. For each u... | codesearchnet |
def wait_for_task(self, task, timeout=(- 1)):
self.__wait_task_completion(task, timeout)
task = self.get(task)
logger.debug(('Waiting for task. Percentage complete: ' + str(task.get('computedPercentComplete'))))
logger.debug(('Waiting for task. Task state: ' + str(task.get('taskState'))))
task_respo... | Wait for task execution and return associated resource.
Args:
task: task dict
timeout: timeout in seconds
Returns:
Associated resource when creating or updating; True when deleting. | codesearchnet |
def get_list(self, obj_class, data, subset):
url = obj_class.get_url(data)
if obj_class.can_list and obj_class.can_get:
if (subset and len(subset) == 1 and subset[0].upper() ==
"BASIC") and obj_class is jssobjects.Computer:
url += "/subset/basic"
... | Get a list of objects as JSSObjectList.
Args:
obj_class: The JSSObject subclass type to search for.
data: None
subset: Some objects support a subset for listing; namely
Computer, with subset="basic".
Returns:
JSSObjectList | juraj-google-style |
def get_subscript(self, sub_script_name):
tree = self.treeWidget()
items = tree.findItems(sub_script_name, QtCore.Qt.MatchExactly | QtCore.Qt.MatchRecursive)
if len(items) >= 1:
subscript_item = [sub_item for sub_item in items if isinstance(sub_item.... | finds the item that contains the sub_script with name sub_script_name
Args:
sub_script_name: name of subscript
Returns: B26QTreeItem in QTreeWidget which is a script | juraj-google-style |
def reverse_transform_table(self, table, table_meta, missing=None):
if missing is None:
missing = self.missing
else:
self.missing = missing
warnings.warn(
DEPRECATION_MESSAGE.format('reverse_transform_table'), DeprecationWarning)
re... | Transform a `table` back to its original format.
Args:
table(pandas.DataFrame): Contents of the table to be transformed.
table_meta(dict): Metadata for the given table.
missing(bool): Wheter or not use NullTransformer to handle missing values.
Returns:
pandas.DataFrame: Table in original format. | juraj-google-style |
def cudnn_gru(units, n_hidden, n_layers=1, trainable_initial_states=False, seq_lengths=None, input_initial_h=None, name='cudnn_gru', reuse=False):
with tf.variable_scope(name, reuse=reuse):
gru = tf.contrib.cudnn_rnn.CudnnGRU(num_layers=n_layers, num_units=n_hidden)
if trainable_initial_states:
... | Fast CuDNN GRU implementation
Args:
units: tf.Tensor with dimensions [B x T x F], where
B - batch size
T - number of tokens
F - features
n_hidden: dimensionality of hidden state
trainable_initial_states: whether to create a special trainable variable
to initialize the hidden states of the network or use just zeros
se... | codesearchnet |
def _PrintWarningCounters(self, storage_counters):
warnings_by_pathspec = storage_counters.get('warnings_by_path_spec', {})
warnings_by_parser_chain = storage_counters.get(
'warnings_by_parser_chain', {})
if not warnings_by_parser_chain:
self._output_writer.Write('No warnings stored.\n\n'... | Prints a summary of the warnings.
Args:
storage_counters (dict): storage counters. | juraj-google-style |
def auto_repr(obj: Any, with_addr: bool = False,
sort_attrs: bool = True, joiner: str = COMMA_SPACE) -> str:
if sort_attrs:
keys = sorted(obj.__dict__.keys())
else:
keys = obj.__dict__.keys()
elements = ["{}={}".format(k, repr(getattr(obj, k))) for k in keys]
return re... | Convenience function for :func:`__repr__`.
Works its way through the object's ``__dict__`` and reports accordingly.
Args:
obj: object to display
with_addr: include the memory address of ``obj``
sort_attrs: sort the attributes into alphabetical order?
joiner: string with which to join the elements
Returns:
string: :fu... | juraj-google-style |
def pull_datapackage(descriptor, name, backend, **backend_options):
warnings.warn('Functions "push/pull_datapackage" are deprecated. Please use "Package" class', UserWarning)
datapackage_name = name
plugin = import_module(('jsontableschema.plugins.%s' % backend))
storage = plugin.Storage(**backend_optio... | Pull Data Package from storage.
All parameters should be used as keyword arguments.
Args:
descriptor (str): path where to store descriptor
name (str): name of the pulled datapackage
backend (str): backend name like `sql` or `bigquery`
backend_options (dict): backend options mentioned in backend docs | codesearchnet |
def update_location_centroid(point, cluster, max_distance, min_samples):
cluster.append(point)
points = [p.gen2arr() for p in cluster]
eps = estimate_meters_to_deg(max_distance, precision=6)
p_cluster = DBSCAN(eps=eps, min_samples=min_samples)
p_cluster.fit(points)
clusters = {}
... | Updates the centroid of a location cluster with another point
Args:
point (:obj:`Point`): Point to add to the cluster
cluster (:obj:`list` of :obj:`Point`): Location cluster
max_distance (float): Max neighbour distance
min_samples (int): Minimum number of samples
Returns:
(:obj:`Point`, :obj:`list` of :obj:`Point`): T... | juraj-google-style |
def _FormatDateTime(self, event):
if not event.timestamp:
return 'N/A'
date_time = dfdatetime_posix_time.PosixTimeInMicroseconds(
timestamp=event.timestamp)
year, month, day_of_month = date_time.GetDate()
hours, minutes, seconds = date_time.GetTimeOfDay()
try:
r... | Formats the date and time.
Args:
event (EventObject): event.
Returns:
str: date and time string or "N/A" if no event timestamp is available. | juraj-google-style |
def on_message(self, event):
metadata = self._parse_metadata(event)
message = Message(text=metadata['text'],
metadata=metadata).__dict__
if message.get('text'):
message['text'] = self.find_and_replace_userids(message['text'])
message['t... | Runs when a message event is received
Args:
event: RTM API event.
Returns:
Legobot.messge | juraj-google-style |
def write_rtt(jlink):
try:
while jlink.connected():
bytes = list(bytearray(input(), "utf-8") + b"\x0A\x00")
bytes_written = jlink.rtt_write(0, bytes)
except Exception:
print("IO write thread exception, exiting...")
thread.interrupt_main()
raise | Writes kayboard input to JLink RTT buffer #0.
This method is a loop that blocks waiting on stdin. When enter is pressed,
LF and NUL bytes are added to the input and transmitted as a byte list.
If the JLink is disconnected, it will exit gracefully. If any other
exceptions are raised, they will be caught and re-raised a... | juraj-google-style |
def __get_valid_form_data_elements(self, soup):
elements = []
for element in soup.find_all(['input', 'button', 'textarea', 'select']):
if element.has_attr('name'):
elements.append(element)
return elements | Get all valid form input elements.
Note:
An element is valid when the value can be updated client-side
and the element has a name attribute.
Args:
soup (obj): The BeautifulSoup form.
Returns:
list(obj): Soup elements. | codesearchnet |
def make_target(url, extra_opts=None):
parts = compat.urlparse(url, allow_fragments=False)
scheme = parts.scheme.lower()
if (scheme in ['ftp', 'ftps']):
creds = (parts.username, parts.password)
tls = (scheme == 'ftps')
from ftpsync import ftp_target
target = ftp_target.FtpTar... | Factory that creates `_Target` objects from URLs.
FTP targets must begin with the scheme ``ftp://`` or ``ftps://`` for TLS.
Note:
TLS is only supported on Python 2.7/3.2+.
Args:
url (str):
extra_opts (dict, optional): Passed to Target constructor. Default: None.
Returns:
:class:`_Target` | codesearchnet |
def undo_last_change(self):
if (len(self.history) == 0):
raise IndexError("Can't undo. Already at oldest change.")
if ('input_structure' not in self.history[(- 1)]):
raise IndexError("Can't undo. Latest history has no input_structure")
h = self.history.pop()
self._undone.append((h, self.... | Undo the last change in the TransformedStructure.
Raises:
IndexError: If already at the oldest change. | codesearchnet |
def create_context(self, state_hash, base_contexts, inputs, outputs):
for address in inputs:
if (not self.namespace_is_valid(address)):
raise CreateContextException('Address or namespace {} listed in inputs is not valid'.format(address))
for address in outputs:
if (not self.namespace... | Create a ExecutionContext to run a transaction against.
Args:
state_hash: (str): Merkle root to base state on.
base_contexts (list of str): Context ids of contexts that will
have their state applied to make this context.
inputs (list of str): Addresses that can be read from.
outputs (list of str): Addresses that can b... | codesearchnet |
def subscribe(self, peer_jid):
self.roster.subscribe(aioxmpp.JID.fromstr(peer_jid).bare()) | Asks for subscription
Args:
peer_jid (str): the JID you ask for subscriptiion | juraj-google-style |
def daylight_saving_start_day(self, value=None):
if value is not None:
try:
value = str(value)
except ValueError:
raise ValueError(
'value {} need to be of type str '
'for field `daylight_saving_start_day`'.... | Corresponds to IDD Field `daylight_saving_start_day`
Args:
value (str): value for IDD Field `daylight_saving_start_day`
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises:
ValueError: if `value` is not a valid value | juraj-google-style |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.