code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def __init__(self, object_local_name: str, from_shard_layouts: Sequence[sparse_core_layout_pb2.SparseCoreTableLayout], to_shard_layouts: Sequence[sparse_core_layout_pb2.SparseCoreTableLayout]): logging.info('Creating EmbeddingReshardCallback for %s', object_local_name) self._object_local_name = object_local_nam...
Initializes Reshard callback. Args: object_local_name: The local name of the object being restored. from_shard_layouts: layouts as in checkpoint being restored from. to_shard_layouts: target layouts as specified in the embedding being restored.
github-repos
def igmpize(self): gaddr = (self.gaddr if (hasattr(self, 'gaddr') and self.gaddr) else '0.0.0.0') underlayer = self.underlayer if (self.type not in [17, 48]): self.mrcode = 0 if isinstance(underlayer, IP): if (self.type == 17): if (gaddr == '0.0.0.0'): underla...
Called to explicitly fixup the packet according to the IGMP RFC The rules are: General: 1. the Max Response time is meaningful only in Membership Queries and should be zero IP: 1. Send General Group Query to 224.0.0.1 (all systems) 2. Send Leave Group to 224.0.0.2 (all routers) 3a.Otherwise send the packet to the gro...
codesearchnet
def slideshow(self, **kwargs): for i, cycle in enumerate(self.cycles): cycle.plot(title="Relaxation step %s" % (i + 1), tight_layout=kwargs.pop("tight_layout", True), show=kwargs.pop("show", True))
Uses matplotlib to plot the evolution of the structural relaxation. Args: ax_list: List of axes. If None a new figure is produced. Returns: `matplotlib` figure
juraj-google-style
def apply(self, func, num_splits=None, other_axis_partition=None, **kwargs): if num_splits is None: num_splits = len(self.list_of_blocks) if other_axis_partition is not None: return [ PyarrowOnRayFramePartition(obj) for obj in deploy_ray_...
Applies func to the object in the plasma store. See notes in Parent class about this method. Args: func: The function to apply. num_splits: The number of times to split the result object. other_axis_partition: Another `PyarrowOnRayFrameAxisPartition` object to apply to func with this one. Returns: A list of `RayRemo...
juraj-google-style
def __init__(self, wildcard, sep="|"): self.pats = ["*"] if wildcard: self.pats = wildcard.split(sep)
Initializes a WildCard. Args: wildcard (str): String of tokens separated by sep. Each token represents a pattern. sep (str): Separator for shell patterns.
juraj-google-style
def alpha_blend(self, other): fa = ((self.__a + other.__a) - (self.__a * other.__a)) if (fa == 0): sa = 0 else: sa = min(1.0, (self.__a / other.__a)) da = (1.0 - sa) (sr, sg, sb) = [(v * sa) for v in self.__rgb] (dr, dg, db) = [(v * da) for v in other.__rgb] return Color(((sr...
Alpha-blend this color on the other one. Args: :other: The grapefruit.Color to alpha-blend with this one. Returns: A grapefruit.Color instance which is the result of alpha-blending this color on the other one. >>> c1 = Color.from_rgb(1, 0.5, 0, 0.2) >>> c2 = Color.from_rgb(1, 1, 1, 0.8) >>> c3 = c1.alpha_blend(c2) >...
codesearchnet
def post_process_semantic_segmentation(self, outputs, target_sizes: Optional[List[Tuple[int, int]]]=None): class_queries_logits = outputs.logits masks_queries_logits = outputs.pred_masks masks_classes = class_queries_logits.softmax(dim=-1)[..., :-1] masks_probs = masks_queries_logits.sigmoid() segme...
Converts the output of [`DetrForSegmentation`] into semantic segmentation maps. Only supports PyTorch. Args: outputs ([`DetrForSegmentation`]): Raw outputs of the model. target_sizes (`List[Tuple[int, int]]`, *optional*): A list of tuples (`Tuple[int, int]`) containing the target size (height, width) of each image in ...
github-repos
def daylight_saving_end_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_end_day`'.form...
Corresponds to IDD Field `daylight_saving_end_day` Args: value (str): value for IDD Field `daylight_saving_end_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
def __init__(self, channel): self.DetectIntent = channel.unary_unary( '/google.cloud.dialogflow.v2.Sessions/DetectIntent', request_serializer=google_dot_cloud_dot_dialogflow__v2_dot_proto_dot_session__pb2.DetectIntentRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_...
Constructor. Args: channel: A grpc.Channel.
juraj-google-style
def _create_session(self, username, password): session = requests.Session() session.verify = False try: response = session.get(self.host_url) except requests.exceptions.ConnectionError: return False soup = BeautifulSoup(response.text, 'html.parser') csrf_token = soup.find...
Create HTTP session. Args: username (str): Timesketch username password (str): Timesketch password Returns: requests.Session: Session object.
juraj-google-style
def _ConvertMapFieldValue(self, value, message, field): if (not isinstance(value, dict)): raise ParseError('Map field {0} must be in a dict which is {1}.'.format(field.name, value)) key_field = field.message_type.fields_by_name['key'] value_field = field.message_type.fields_by_name['value'] for ...
Convert map field value for a message map field. Args: value: A JSON object to convert the map field value. message: A protocol message to record the converted data. field: The descriptor of the map field to be converted. Raises: ParseError: In case of convert problems.
codesearchnet
def BatchConvert(self, metadata_value_pairs, token=None): msg_dict = {} for (metadata, msg) in metadata_value_pairs: msg_dict.setdefault(msg.source, []).append((metadata, msg)) metadata_objects = [] metadata_to_fetch = [] for client_urn in msg_dict: try: metadata_objects....
Converts a batch of GrrMessages into a set of RDFValues at once. Args: metadata_value_pairs: a list or a generator of tuples (metadata, value), where metadata is ExportedMetadata to be used for conversion and value is a GrrMessage to be converted. token: Security token. Returns: Resulting RDFValues. Empty list is a v...
codesearchnet
def __init__(self, channel): self.DeletePosixAccount = channel.unary_unary( "/google.cloud.oslogin.v1.OsLoginService/DeletePosixAccount", request_serializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.DeletePosixAccountRequest.SerializeToString, respo...
Constructor. Args: channel: A grpc.Channel.
juraj-google-style
def get_config_path(appdirs=DEFAULT_APPDIRS, file_name=DEFAULT_CONFIG_FILENAME): return os.path.join(appdirs.user_config_dir, file_name)
Return the path where the config file is stored. Args: app_name (text_type, optional): Name of the application, defaults to ``'projecthamster``. Allows you to use your own application specific namespace if you wish. file_name (text_type, optional): Name of the config file. Defaults to ``config.conf``. Returns: str: F...
codesearchnet
def _training(self): with tf.device(('/gpu:0' if self._use_gpu else '/cpu:0')): with tf.name_scope('training'): assert_full = tf.assert_equal(self._num_finished_episodes, self._config.update_every) with tf.control_dependencies([assert_full]): data = self._finished_epi...
Perform multiple training iterations of both policy and value baseline. Training on the episodes collected in the memory. Reset the memory afterwards. Always returns a summary string. Returns: Summary tensor.
codesearchnet
def get(self, type: Type[T], query: Mapping[(str, Any)]) -> T: LOGGER.info('Getting SourceHandlers for "{type}"'.format(type=type.__name__)) try: handlers = self._get_types[type] except KeyError: try: LOGGER.info('Building new SourceHandlers for "{type}"'.format(type=type.__name_...
Gets a query from the data pipeline. 1) Extracts the query the sequence of data sources. 2) Inserts the result into the data sinks (if appropriate). 3) Transforms the result into the requested type if it wasn't already. 4) Inserts the transformed result into any data sinks. Args: query: The query being requested. con...
codesearchnet
def keep_file(self, task, response, min_size=None, max_size=None): try: img = Image.open(BytesIO(response.content)) except (IOError, OSError): return False task['img_size'] = img.size if min_size and not self._size_gt(img.size, min_size): retu...
Decide whether to keep the image Compare image size with ``min_size`` and ``max_size`` to decide. Args: response (Response): response of requests. min_size (tuple or None): minimum size of required images. max_size (tuple or None): maximum size of required images. Returns: bool: whether to keep the image.
juraj-google-style
def min_edit_distance(source: Sequence[T], target: Sequence[T], ins_cost: Callable[(..., int)]=(lambda _x: 1), del_cost: Callable[(..., int)]=(lambda _x: 1), sub_cost: Callable[(..., int)]=(lambda x, y: (0 if (x == y) else 1))) -> int: n = len(target) m = len(source) distance = np.zeros(((m + 1), (n + 1)), ...
Calculates the minimum edit distance between two sequences. Uses the Levenshtein weighting as a default, but offers keyword arguments to supply functions to measure the costs for editing with different elements. Args: ins_cost: A function describing the cost of inserting a given char del_cost: A function describing t...
codesearchnet
def update_one_time_key_counts(self, counts): self.one_time_keys_manager.server_counts = counts if self.one_time_keys_manager.should_upload(): logger.info('Uploading new one-time keys.') self.upload_one_time_keys()
Update data on one-time keys count and upload new ones if necessary. Args: counts (dict): Counts of keys currently on the HS for each key type.
juraj-google-style
def batch_shape_tensor(self): batch_shape = tf.constant([], dtype=tf.int32) for param in self.parameters: batch_shape = tf.broadcast_dynamic_shape(batch_shape, param.prior.batch_shape_tensor()) return batch_shape
Runtime batch shape of models represented by this component. Returns: batch_shape: `int` `Tensor` giving the broadcast batch shape of all model parameters. This should match the batch shape of derived state space models, i.e., `self.make_state_space_model(...).batch_shape_tensor()`.
codesearchnet
def decode(data): decoded = None try: decoded = json.loads(data) except Exception, e: raise MetaParsingException("Can't parse your JSON data: %s" % e.message) decoded = validator.check_structure(decoded) return decoded
Handles decoding of the JSON `data`. Args: data (str): Data which will be decoded. Returns: dict: Dictionary with decoded data.
juraj-google-style
def check_publish_block(self, block_header): if any(((publisher_key != block_header.signer_public_key) for publisher_key in self._valid_block_publishers)): return False if (self._min_wait_time == 0): return True if (self._min_wait_time < 0): return False assert (self._min_wait_ti...
Check if a candidate block is ready to be claimed. block_header (BlockHeader): the block_header to be checked if it should be claimed Returns: Boolean: True if the candidate block_header should be claimed.
codesearchnet
def PreparePairedSequenceBatch(source, target_in, pad=0): target = target_in[:, :-1] target_y = target_in[:, 1:] source_mask = np.reshape(source != pad, (source.shape[0], 1, 1, source.shape[-1])) target_mask = MakeTargetMask(target, pad) memory_mask = ( np.reshape(np.arange...
Build masks for this batch. Args: source: (batch, source_len) array of integer-coded symbols for inputs target_in: (batch, batch_len) array of integer-coded symbols for targets pad: int: the padding symbol used to pad the above Returns: Prepared batch of tuple of arrays: source, input-target, shifted-target, source m...
juraj-google-style
def _build_node_error_message(op): node_error_message = [f'Detected at node {op.name!r} defined at (most recent call last):'] field_dict = _compute_field_dict(op) for frame in field_dict['definition_traceback']: if '<embedded' not in frame: node_error_message.extend([f' {line}' for line...
Returns the formatted error message for the given op. Args: op: The node. Returns: The formatted error message for the given op with traceback.
github-repos
def read_configs(__pkg: str, __name: str='config', *, local: bool=True) -> ConfigParser: configs = get_configs(__pkg, __name) if local: localrc = path.abspath('.{}rc'.format(__pkg)) if path.exists(localrc): configs.append(localrc) cfg = ConfigParser(converters={'datetime': parse_...
Process configuration file stack. We export the time parsing functionality of ``jnrbase`` as custom converters for :class:`configparser.ConfigParser`: =================== =========================================== Method Function =================== =========================================== ``.getd...
codesearchnet
def get_fixture(self, fixture_id, head2head=None): filters = [] if head2head is not None and int(head2head) > 0: self.logger.debug(f'Getting fixture {fixture_id}. head2head is {head2head}.') filters.append(self.__createFilter('head2head', head2head)) else: ...
Loads a single fixture. Args: * fixture_id (str): the id of the fixture * head2head (int, optional): load the previous n fixture of the two teams Returns: * :obj: json: the fixture-json
juraj-google-style
def id_pools_vwwn_ranges(self): if (not self.__id_pools_vwwn_ranges): self.__id_pools_vwwn_ranges = IdPoolsRanges('vwwn', self.__connection) return self.__id_pools_vwwn_ranges
Gets the IdPoolsRanges API Client for VWWN Ranges. Returns: IdPoolsRanges:
codesearchnet
def cluster_spec(self): if self._tpu != 'local': network_endpoints = self._cloud_tpu_client.network_endpoints() worker_list = ['%s:%s' % (endpoint['ipAddress'], endpoint['port']) for endpoint in network_endpoints] cluster_spec = {self.task_type: worker_list} if self._coordinator_addr...
Returns a ClusterSpec object based on the latest TPU information. We retrieve the information from the GCE APIs every time this method is called. Returns: A ClusterSpec containing host information returned from Cloud TPUs, or None. Raises: RuntimeError: If the provided TPU is not healthy.
github-repos
def _preprocess_tensor_input(x, data_format, mode): ndim = len(x.shape) if mode == 'tf': x /= 127.5 x -= 1.0 return x elif mode == 'torch': x /= 255.0 mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] else: if data_format == 'channels_first'...
Preprocesses a tensor encoding a batch of images. Args: x: Input tensor, 3D or 4D. data_format: Data format of the image tensor. mode: One of "caffe", "tf" or "torch". - caffe: will convert the images from RGB to BGR, then will zero-center each color channel with respect to the ImageNet dataset, without scaling. - tf:...
github-repos
def is_experimental_feature_activated(feature_name): return feature_name in os.environ.get('TF_TRT_EXPERIMENTAL_FEATURES', default='').split(',')
Determines if a TF-TRT experimental feature is enabled. This helper function checks if an experimental feature was enabled using the environment variable `TF_TRT_EXPERIMENTAL_FEATURES=feature_1,feature_2`. Args: feature_name: Name of the feature being tested for activation.
github-repos
def one_or_more(e, delimiter=None): if (delimiter is None): delimiter = (lambda s, grm, pos: (s, Ignore, (pos, pos))) msg = 'Expected one or more of: {}'.format(repr(e)) def match_one_or_more(s, grm=None, pos=0): start = pos (s, obj, span) = e(s, grm, pos) pos = span[1] ...
Create a PEG function to match one or more expressions. Args: e: the expression to match delimiter: an optional expression to match between the primary *e* matches.
codesearchnet
def int64_user_counter(namespace, name, metric, ptransform=None) -> metrics_pb2.MonitoringInfo: labels = create_labels(ptransform=ptransform, namespace=namespace, name=name) if isinstance(metric, int): metric = coders.VarIntCoder().encode(metric) return create_monitoring_info(USER_COUNTER_URN, SUM_I...
Return the counter monitoring info for the specifed URN, metric and labels. Args: urn: The URN of the monitoring info/metric. metric: The payload field to use in the monitoring info or an int value. ptransform: The ptransform id used as a label.
github-repos
def onWith(self, evnt, func): self.on(evnt, func) try: (yield self) finally: self.off(evnt, func)
A context manager which can be used to add a callback and remove it when using a ``with`` statement. Args: evnt (str): An event name func (function): A callback function to receive event tufo
codesearchnet
def update(self, instance, validated_data): is_primary = validated_data.pop("is_primary", False) instance = super(EmailSerializer, self).update( instance, validated_data ) if is_primary: instance.set_primary() return instance
Update the instance the serializer is bound to. Args: instance: The instance the serializer is bound to. validated_data: The data to update the serializer with. Returns: The updated instance.
juraj-google-style
def join(self, other): r assert self._load == other._load, 'loads must be the same' self._lists.extend(other._lists) self._cumlen.extend([c + self._len for c in other._cumlen]) self._len += other._len
r""" Args: other (?): CommandLine: python -m sortedcontainers.sortedlist join2 Example: >>> from utool.experimental.dynamic_connectivity import * # NOQA >>> self = EulerTourList([1, 2, 3, 2, 4, 2, 1], load=3) >>> other = EulerTourList([0, 5, 9, 5, 0], load=3) >>> result = self.join(other) >>> print(result)
juraj-google-style
def _prepare_sample_data(self, submission_type): images = np.random.randint(0, 256, size=[BATCH_SIZE, 299, 299, 3], dtype=np.uint8) for i in range(BATCH_SIZE): Image.fromarray(images[i, :, :, :]).save( os.path.join(self._sample_input_dir, IMAGE_NAME_PATTE...
Prepares sample data for the submission. Args: submission_type: type of the submission.
juraj-google-style
def find_layer_idx(model, layer_name): layer_idx = None for idx, layer in enumerate(model.layers): if layer.name == layer_name: layer_idx = idx break if layer_idx is None: raise ValueError("No layer with name '{}' within the model".format(layer_name)) return...
Looks up the layer index corresponding to `layer_name` from `model`. Args: model: The `keras.models.Model` instance. layer_name: The name of the layer to lookup. Returns: The layer index if found. Raises an exception otherwise.
juraj-google-style
def ensure_dir(path): os.makedirs(os.path.abspath(os.path.dirname(path)), exist_ok=True)
Create all parent directories of path if they don't exist. Args: path. Path-like object. Create parent dirs to this path. Return: None.
juraj-google-style
def _get_num_inputs_outputs(op_type): def _is_list_arg(arg): return arg.number_attr or arg.type_list_attr def _count_args(arg_defs): for arg in arg_defs: if _is_list_arg(arg): return -1 return len(arg_defs) op_def = op_def_registry.get(op_type) if no...
Returns (num_inputs, num_outputs). Args: op_type: String. The type of the Operation. Used to lookup the op in the registry. Returns: (num_inputs, num_outputs), for either num_inputs or num_outputs if the value can't be statically inferred from the OpDef alone or of the OpDef lookup fails, -1 is returned.
github-repos
def build_sanitiser_node_dict(cfg, sinks_in_file): sanitisers = list() for sink in sinks_in_file: sanitisers.extend(sink.sanitisers) sanitisers_in_file = list() for sanitiser in sanitisers: for cfg_node in cfg.nodes: if (sanitiser in cfg_node.label): sanitiser...
Build a dict of string -> TriggerNode pairs, where the string is the sanitiser and the TriggerNode is a TriggerNode of the sanitiser. Args: cfg(CFG): cfg to traverse. sinks_in_file(list[TriggerNode]): list of TriggerNodes containing the sinks in the file. Returns: A string -> TriggerNode dict.
codesearchnet
def scheduled_sample_prob(ground_truth_x, generated_x, batch_size, scheduled_sample_var): probability_threshold = scheduled_sample_var probability_of_generated = tf.random_uniform([batch_size]) return tf.where((probability_of_generated > probability_threshold), generated_x, ground_truth_x)
Probability based scheduled sampling. Args: ground_truth_x: tensor of ground-truth data points. generated_x: tensor of generated data points. batch_size: batch size scheduled_sample_var: probability of choosing from ground_truth. Returns: New batch with randomly selected data points.
codesearchnet
def fetcher(date=datetime.today(), url_pattern=URL_PATTERN): api_url = (url_pattern % date.strftime('%Y-%m-%d')) headers = {'Referer': 'http: raw_result = requests.get(api_url, headers=headers).json() return raw_result
Fetch json data from n.pl Args: date (date) - default today url_patter (string) - default URL_PATTERN Returns: dict - data from api
codesearchnet
def connect(filename: str, mode: str='r+', *, validate: bool=True, spec_version: str='2.0.1') -> LoomConnection: return LoomConnection(filename, mode, validate=validate, spec_version=spec_version)
Establish a connection to a .loom file. Args: filename: Path to the Loom file to open mode: Read/write mode, 'r+' (read/write) or 'r' (read-only), defaults to 'r+' validate: Validate the file structure against the Loom file format specification spec_version: The loom file spec version to validate against (e.g. "2....
codesearchnet
def __init__(self, name=None, description=None, hint=None, allow_failure=False, passes=None, arguments=None): if name: self.name = name if description: self.description = description if hint: self.hint = hint self.allow_failu...
Initialization method. Args: allow_failure (bool): still pass if failed or not. arguments (dict): arguments passed to the check method when run.
juraj-google-style
def update_state(self, y_true, y_pred, sample_weight=None): return metrics_utils.update_confusion_matrix_variables({self._confusion_matrix_cond: self.accumulator}, y_true, y_pred, thresholds=self.thresholds, thresholds_distributed_evenly=self._thresholds_distributed_evenly, sample_weight=sample_weight)
Accumulates the metric statistics. Args: y_true: The ground truth values. y_pred: The predicted values. sample_weight: Optional weighting of each example. Defaults to 1. Can be a `Tensor` whose rank is either 0, or the same rank as `y_true`, and must be broadcastable to `y_true`. Returns: Update op.
github-repos
def chunk_layer(layer: Callable, inputs: Dict[str, Any], chunk_size: int, no_batch_dims: int, low_mem: bool=False, _out: Any=None, _add_into_out: bool=False) -> Any: if not len(inputs) > 0: raise ValueError('Must provide at least one input') initial_dims = [shape[:no_batch_dims] for shape in _fetch_dims...
Implements the "chunking" procedure described in section 1.11.8. Layer outputs and inputs are assumed to be simple "pytrees," consisting only of (arbitrarily nested) lists, tuples, and dicts with torch.Tensor leaves. Args: layer: The layer to be applied chunk-wise inputs: A (non-nested) dictionary of keyworded inputs...
github-repos
def __init__(self, correction_limit=88., **kwargs): self.correction_limit = correction_limit super(SunZenithCorrector, self).__init__(**kwargs)
Collect custom configuration values. Args: correction_limit (float): Maximum solar zenith angle to apply the correction in degrees. Pixels beyond this limit have a constant correction applied. Default 88. max_sza (float): Maximum solar zenith angle in degrees that is considered valid and correctable. Default 95.0.
juraj-google-style
def read(self, uri): read_response = self.connect(uri) fedora_graph = rdflib.Graph().parse(data=read_response.read(), format='turtle') return fedora_graph
Method takes uri and creates a RDF graph from Fedora Repository Args: uri(str): URI of Fedora URI Returns: rdflib.Graph
codesearchnet
def get_output_details(self): return [self._get_tensor_details(i, subgraph_index=0) for i in self._interpreter.OutputIndices()]
Gets model output tensor details. Returns: A list in which each item is a dictionary with details about an output tensor. The dictionary contains the same fields as described for `get_input_details()`.
github-repos
def get_containers(self, container_class): with self._store_lock: return self.store.get(container_class.CONTAINER_TYPE, [])
Thread-safe method to retrieve data from the state's store. Args: container_class: AttributeContainer class used to filter data. Returns: A list of AttributeContainer objects of matching CONTAINER_TYPE.
codesearchnet
def load(path): importpath = path.replace("/", ".").replace("\\", ".") if importpath[-3:] == ".py": importpath = importpath[:-3] try: importlib.import_module(importpath) except (ModuleNotFoundError, TypeError): exec(open(path).read())
Helper function that tries to load a filepath (or python module notation) as a python module and on failure `exec` it. Args: path (str): Path or module to load The function tries to import `example.module` when either `example.module`, `example/module` or `example/module.py` is given.
juraj-google-style
def get_workflow(workflow_id: str, workflow_version: str) -> dict: name = 'workflow_definitions:{}:{}'.format(workflow_id, workflow_version) workflow = DB.get_hash_dict(name) workflow['stages'] = ast.literal_eval(workflow['stages']) return workflow
Get a workflow definition from the Configuration Database. Args: workflow_id (str): Workflow identifier workflow_version (str): Workflow version Returns: dict, Workflow definition dictionary
codesearchnet
def normalize_partial_name(decl): if decl.cache.normalized_partial_name is None: decl.cache.normalized_partial_name = normalize(decl.partial_name) return decl.cache.normalized_partial_name
Cached variant of normalize Args: decl (declaration.declaration_t): the declaration Returns: str: normalized name
juraj-google-style
def restore(self, directory=None, file=None): if file is None: file = tf.train.latest_checkpoint( checkpoint_dir=(self.saver_directory if directory is None else directory), ) elif directory is None: file = os.path.join(self.sa...
Restore TensorFlow model. If no checkpoint file is given, the latest checkpoint is restored. If no checkpoint directory is given, the model's default saver directory is used (unless file specifies the entire path). Args: directory: Optional checkpoint directory. file: Optional checkpoint file, or path if directory not...
juraj-google-style
class LabelAggregation(AggregationFn, _AggModelIdMixin, _SourcePredictionMixin): def __init__(self, agg_func: Callable[[Iterable[int]], int], agg_model_id: Optional[str]=None, include_source_predictions: bool=False, normal_label: int=DEFAULT_NORMAL_LABEL, outlier_label: int=DEFAULT_OUTLIER_LABEL, missing_label: in...
Aggregates anomaly predictions based on their labels. This is an abstract base class for `AggregationFn`s that combine multiple `AnomalyPrediction` objects into a single `AnomalyPrediction` based on the labels of the input predictions. Args: agg_func (Callable[[Iterable[int]], int]): A function that aggregates a coll...
github-repos
def restore_ops(self, reader=None): if self._has_registered_saver(): raise ValueError('Unable to run individual checkpoint restore for objects with registered savers.') restore_ops, tensor_saveables, python_positions, _ = self.gather_ops_or_named_saveables() restore_ops.extend(self._checkpoint.resto...
Create or fetch restore ops for this object's attributes. Requires that the `Trackable` Python object has been bound to an object ID in the checkpoint. Args: reader: A `CheckpointReader`. If None, a new instance will be created. Returns: A list of operations when graph building, or an empty list when executing eager...
github-repos
def get_object_errors(self): if (self._object_errors is None): self._object_errors = [{str(o): o.get_errors()} for o in self.objects() if o.has_error()] return self._object_errors
Gets a list of business error message strings for each of the requested objects that had a business error. If there was no error, returns an empty list Returns: List of strings
codesearchnet
def on_epoch_begin(self, epoch, logs=None): logs = self._process_logs(logs) for callback in self.callbacks: callback.on_epoch_begin(epoch, logs)
Calls the `on_epoch_begin` methods of its callbacks. This function should only be called during TRAIN mode. Args: epoch: Integer, index of epoch. logs: Dict. Currently no data is passed to this argument for this method but that may change in the future.
github-repos
def build_album_art_full_uri(self, url): if not url.startswith(('http:', 'https:')): url = 'http: return url
Ensure an Album Art URI is an absolute URI. Args: url (str): the album art URI. Returns: str: An absolute URI.
juraj-google-style
def delete(self, roomId): check_type(roomId, basestring, may_be_none=False) self._session.delete(((API_ENDPOINT + '/') + roomId))
Delete a room. Args: roomId(basestring): The ID of the room to be deleted. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
codesearchnet
def list_of_vars(arg_plot): lovs = [[[var for var in svars.split(',') if var] for svars in pvars.split('.') if svars] for pvars in arg_plot.split('-') if pvars] lovs = [[slov for slov in lov if slov] for lov in lovs if lov] return [lov for lov in lovs if lov]
Construct list of variables per plot. Args: arg_plot (str): string with variable names separated with ``_`` (figures), ``.`` (subplots) and ``,`` (same subplot). Returns: three nested lists of str - variables on the same subplot; - subplots on the same figure; - figures.
juraj-google-style
def confusion_matrix( gold, pred, null_pred=False, null_gold=False, normalize=False, pretty_print=True ): conf = ConfusionMatrix(null_pred=null_pred, null_gold=null_gold) gold = arraylike_to_numpy(gold) pred = arraylike_to_numpy(pred) conf.add(gold, pred) mat = conf.compile() if normal...
A shortcut method for building a confusion matrix all at once. Args: gold: an array-like of gold labels (ints) pred: an array-like of predictions (ints) null_pred: If True, include the row corresponding to null predictions null_gold: If True, include the col corresponding to null gold labels normalize: if True, divide...
juraj-google-style
def less_equal(x1, x2): if any_symbolic_tensors((x1, x2)): return LessEqual().symbolic_call(x1, x2) return backend.numpy.less_equal(x1, x2)
Return the truth value of `x1 <= x2` element-wise. Args: x1: First input tensor. x2: Second input tensor. Returns: Output tensor, element-wise comparison of `x1` and `x2`.
github-repos
def rescale(self, image: 'torch.Tensor', scale: float, **kwargs) -> 'torch.Tensor': return image * scale
Rescale an image by a scale factor. image = image * scale. Args: image (`torch.Tensor`): Image to rescale. scale (`float`): The scaling factor to rescale pixel values by. Returns: `torch.Tensor`: The rescaled image.
github-repos
def _delete(self, url, data, scope): self._create_session(scope) response = self.session.delete(url, data=data) return (response.status_code, response.text)
Make a DELETE request using the session object to a Degreed endpoint. Args: url (str): The url to send a DELETE request to. data (str): The json encoded payload to DELETE. scope (str): Must be one of the scopes Degreed expects: - `CONTENT_PROVIDER_SCOPE` - `COMPLETION_PROVIDER_SCOPE`
codesearchnet
def copy_to_device(target_device, source_device='/cpu:0'): def _apply_fn(dataset): return _CopyToDeviceDataset(dataset, target_device=target_device, source_device=source_device) return _apply_fn
A transformation that copies dataset elements to the given `target_device`. Args: target_device: The name of a device to which elements will be copied. source_device: The original device on which `input_dataset` will be placed. Returns: A `Dataset` transformation function, which can be passed to `tf.data.Dataset.appl...
github-repos
def convert_to_layout_rules(x): if isinstance(x, LayoutRules): return x if isinstance(x, str): x = _parse_string_to_list_of_pairs(x) return LayoutRules(x)
Converts input to a LayoutRules. Args: x: LayoutRules, str, or set-like of string pairs. Returns: LayoutRules.
juraj-google-style
def get_experiment_in_group(self, group, bucketing_id): experiment_id = self.bucketer.find_bucket(bucketing_id, group.id, group.trafficAllocation) if experiment_id: experiment = self.config.get_experiment_from_id(experiment_id) if experiment: self.logger.info(('User with bucketing ID...
Determine which experiment in the group the user is bucketed into. Args: group: The group to bucket the user into. bucketing_id: ID to be used for bucketing the user. Returns: Experiment if the user is bucketed into an experiment in the specified group. None otherwise.
codesearchnet
def oauth2_callback(request): if ('error' in request.GET): reason = request.GET.get('error_description', request.GET.get('error', '')) reason = html.escape(reason) return http.HttpResponseBadRequest('Authorization failed {0}'.format(reason)) try: encoded_state = request.GET['stat...
View that handles the user's return from OAuth2 provider. This view verifies the CSRF state and OAuth authorization code, and on success stores the credentials obtained in the storage provider, and redirects to the return_url specified in the authorize view and stored in the session. Args: request: Django request. R...
codesearchnet
def run(self, host='localhost', port=8000, shutdown_timeout=60.0, **kwargs): print((('Running service on http: self.config.port = port self.config.host = host try: if self.event_broker: self.event_broker.start() self.loop.run_until_complete(self.announce()) http_h...
This function starts the service's network intefaces. Args: port (int): The port for the http server.
codesearchnet
def _FormatExpression(self, frame, expression): (rc, value) = _EvaluateExpression(frame, expression) if (not rc): message = _FormatMessage(value['description']['format'], value['description'].get('parameters')) return (('<' + message) + '>') return self._FormatValue(value)
Evaluates a single watched expression and formats it into a string form. If expression evaluation fails, returns error message string. Args: frame: Python stack frame in which the expression is evaluated. expression: string expression to evaluate. Returns: Formatted expression value that can be used in the log messa...
codesearchnet
def get_metric_group_infos(self): mg_defs = self.get_metric_group_definitions() mg_infos = [] for mg_def in mg_defs: metric_infos = [] for (metric_name, metric_type) in mg_def.types: metric_infos.append({'metric-name': metric_name, 'metric-type': metric_type}) mg_info = {...
Get the faked metric group definitions for this context object that are to be returned from its create operation, in the format needed for the "Create Metrics Context" operation response. Returns: "metric-group-infos" JSON object as described for the "Create Metrics Context "operation response.
codesearchnet
def hwvtep_attach_vlan_vid(self, **kwargs): name = kwargs.pop('name') mac = kwargs.pop('mac') vlan = kwargs.pop('vlan') name_args = dict(name=name, vid=vlan, mac=mac) method_name = 'overlay_gateway_attach_vlan_mac' method_class = self._brocade_tunnels gw_...
Identifies exported VLANs in VXLAN gateway configurations. Args: name (str): overlay_gateway name vlan(str): vlan_id range callback (function): A function executed upon completion of the method. Returns: Return value of `callback`. Raises: None
juraj-google-style
def _allocate_subnets(self, conf): allocated_subnets = [] try: for net_spec in conf.get('nets', {}).itervalues(): if net_spec['type'] != 'nat': continue gateway = net_spec.get('gw') if gateway: ...
Allocate all the subnets needed by the given configuration spec Args: conf (dict): Configuration spec where to get the nets definitions from Returns: tuple(list, dict): allocated subnets and modified conf
juraj-google-style
def show_error(self, message): assert isinstance(message, string_types) self.post('error', data=message)
Send an error message to the active client. The new error will be displayed on any active GUI clients. Args: message (str): Plain-text message to display. Returns: None >>> s = _syncthing() >>> s.system.show_error('my error msg') >>> s.system.errors()[0] ... # doctest: +ELLIPSIS ErrorEvent(when=datetime.datetime(......
codesearchnet
def user(self, email): LOG.info("Fetching user %s", email) user_obj = self.user_collection.find_one({'_id': email}) return user_obj
Fetch a user from the database. Args: email(str) Returns: user_obj(dict)
juraj-google-style
def __init__(self, fn): if not callable(fn): raise TypeError('Expected a callable object instead of: %r' % fn) self._fn = fn
Initializes a PartitionFn object wrapping a callable. Args: fn: A callable object, which should accept the following arguments: element - element to assign to a partition. num_partitions - number of output partitions. and may accept additional arguments and side inputs. Raises: TypeError: if fn is not a callable type...
github-repos
def find_previous(a, value, index=False, return_distance=False): b = (a - value) i = np.where((b > 0))[0][0] d = ((value - a[(i - 1)]) / (a[i] - a[(i - 1)])) if index: if return_distance: return ((i - 1), d) else: return (i - 1) elif return_distance: r...
Find the nearest array value, or index of the array value, before some given value. Optionally also return the fractional distance of the given value from that previous value. Args: a (ndarray) value (float) index (bool): whether to return the index instead of the array value. Default: False. return_distance(bool): wh...
codesearchnet
def bfloat16_activations_var_getter(getter, *args, **kwargs): requested_dtype = kwargs['dtype'] if (requested_dtype == tf.bfloat16): kwargs['dtype'] = tf.float32 var = getter(*args, **kwargs) if (var.dtype.base_dtype != requested_dtype): var = tf.cast(var, requested_dtype) return var
A custom getter function for float32 parameters and bfloat16 activations. Args: getter: custom getter *args: arguments **kwargs: keyword arguments Returns: variables with the correct dtype. Raises: KeyError: if "dtype" is not provided as a kwarg.
codesearchnet
def create_view(self, state_root_hash=None): if state_root_hash is None: state_root_hash = INIT_ROOT_KEY merkle_db = MerkleDatabase(self._database, merkle_root=state_root_hash) return StateView(merkle_db)
Creates a StateView for the given state root hash. Args: state_root_hash (str): The state root hash of the state view to return. If None, returns the state view for the Returns: StateView: state view locked to the given root hash.
juraj-google-style
def traverse_data(obj, use_numpy=True, buffers=None): if (use_numpy and all((isinstance(el, np.ndarray) for el in obj))): return [transform_array(el, buffers=buffers) for el in obj] obj_copy = [] for item in obj: if (type(item) is float): if math.isnan(item): item...
Recursively traverse an object until a flat list is found. If NumPy is available, the flat list is converted to a numpy array and passed to transform_array() to handle ``nan``, ``inf``, and ``-inf``. Otherwise, iterate through all items, converting non-JSON items Args: obj (list) : a list of values or lists use_nump...
codesearchnet
def recipe_floodlight_monitor(config, auth_read, dcm_account, sheet): floodlight_monitor(config, {'auth': auth_read, 'account': dcm_account, 'template': {'template': {'sheet': 'https:
Monitor floodlight impressions specified in sheet and send email alerts. Args: auth_read (authentication) - Credentials used for reading data. dcm_account (string) - Specify an account_id as a number. sheet (string) - Full Name or URL to Google Sheet, Floodlight Monitor tab will be added.
github-repos
def from_gpx(gpx_track_point): return Point( lat=gpx_track_point.latitude, lon=gpx_track_point.longitude, time=gpx_track_point.time )
Creates a point from GPX representation Arguments: gpx_track_point (:obj:`gpxpy.GPXTrackPoint`) Returns: :obj:`Point`
juraj-google-style
def _transform_cur_commands(cur_commands, alias_table=None): transformed = [] alias_table = (alias_table if alias_table else get_alias_table()) for cmd in cur_commands: if ((cmd in alias_table.sections()) and alias_table.has_option(cmd, 'command')): transformed += alias_table.get(cmd, 'c...
Transform any aliases in cur_commands into their respective commands. Args: alias_table: The alias table. cur_commands: current commands typed in the console.
codesearchnet
def print_info(self, buf=None, format_=FileFormat.yaml, skip_attributes=None, include_release=False): data = self.validated_data().copy() data.pop('config', None) if self.config: if isinstance(self, Package): config_dict = self.data.get('config') else: config_dict = s...
Print the contents of the package. Args: buf (file-like object): Stream to write to. format_ (`FileFormat`): Format to write in. skip_attributes (list of str): List of attributes to not print. include_release (bool): If True, include release-related attributes, such as 'timestamp' and 'changelog'
codesearchnet
def _subsample_labels(self, label): pos_idx, neg_idx = subsample_labels(label, self.batch_size_per_image, self.positive_fraction, 0) label.fill_(-1) label.scatter_(0, pos_idx, 1) label.scatter_(0, neg_idx, 0) return label
Randomly sample a subset of positive and negative examples, and overwrite the label vector to the ignore value (-1) for all elements that are not included in the sample. Args: labels (Tensor): a vector of -1, 0, 1. Will be modified in-place and returned.
github-repos
def sign(x): return math_ops.sign(x)
Element-wise sign. Args: x: Tensor or variable. Returns: A tensor.
github-repos
def reconstruct_text(tokens: List[Token]) -> str: return ''.join([x.text_with_ws for x in tokens])
Given a list of tokens, reconstruct the original text with as much fidelity as possible. Args: [tokens]: Returns: a string.
codesearchnet
def initialize_plugs(self, plug_types=None): types = (plug_types if (plug_types is not None) else self._plug_types) for plug_type in types: plug_logger = self.logger.getChild(plug_type.__name__) if (plug_type in self._plugs_by_type): continue try: if (not issubcla...
Instantiate required plugs. Instantiates plug types and saves the instances in self._plugs_by_type for use in provide_plugs(). Args: plug_types: Plug types may be specified here rather than passed into the constructor (this is used primarily for unit testing phases).
codesearchnet
def Instance(reactor=None): if NodeLeader._LEAD is None: NodeLeader._LEAD = NodeLeader(reactor) return NodeLeader._LEAD
Get the local node instance. Args: reactor: (optional) custom reactor to use in NodeLeader. Returns: NodeLeader: instance.
juraj-google-style
def write(self, noautocmd=False): cmd = ('noautocmd write' if noautocmd else 'write') self._vim.command(cmd)
Writes the file of the current buffer. Args: noautocmd (bool): If true, write will skip autocommands. Todo: We should consider whether ``SourceFileInfo`` can replace most usage of noautocmd. See #298
codesearchnet
def __init__(self, types=None, capabilities=None, max_groups1=None, max_groups2=None, max_groups3=None, max_groups4=None, actions1=None, actions2=None, actions3=None, actions4=None): super().__init__() self.types = types self.capabilities = capabilities...
Create a GroupFeatures with the optional parameters below. Args: types: Bitmap of OFPGT_* values supported. capabilities: Bitmap of OFPGFC_* capability supported. max_groups: 4-position array; Maximum number of groups for each type. actions: 4-position array; Bitmaps of OFPAT_* that are supported.
juraj-google-style
def visit_membership(self, relation: _evaluation.MembershipRelationNode) -> Any: lhs_result = self.visit(relation.left) rhs_result = self.visit(relation.right) in_lhs = lhs_result if isinstance(relation, _evaluation.InNode) else rhs_result in_rhs = rhs_result if isinstance(relation, _evaluation.InNode) ...
Translates a FHIRPath membership relation to Standard SQL. For the `IN` relation, the LHS operand is assumed to be a collection of a single value. For 'CONTAINS', the RHS operand is assumed to be a collection of a single value. Args: relation: The FHIRPath AST `MembershipRelation` node. Returns: A compiled Standard ...
github-repos
def load_checkpoint(ckpt_dir_or_file): filename = _get_checkpoint_filename(ckpt_dir_or_file) if filename is None: raise ValueError("Couldn't find 'checkpoint' file or checkpoints in given directory %s" % ckpt_dir_or_file) return py_checkpoint_reader.NewCheckpointReader(filename)
Returns `CheckpointReader` for checkpoint found in `ckpt_dir_or_file`. If `ckpt_dir_or_file` resolves to a directory with multiple checkpoints, reader for the latest checkpoint is returned. Example usage: ```python import tensorflow as tf a = tf.Variable(1.0) b = tf.Variable(2.0) ckpt = tf.train.Checkpoint(var_list=...
github-repos
def SetHeaders(self, soap_headers, http_headers): self.suds_client.set_options(soapheaders=soap_headers, headers=http_headers)
Set the headers for the underlying client. Args: soap_headers: A SOAP element for the SOAP headers. http_headers: A dictionary for the http headers.
juraj-google-style
def setup_modules(self, args): def _setup_module_thread(module_description): "Calls the module's setup() function and sets an Event object for it.\n\n Args:\n module_description (dict): Corresponding recipe module description.\n " new_args = utils.import_args_from_dict(module_descr...
Performs setup tasks for each module in the module pool. Threads declared modules' setup() functions. Takes CLI arguments into account when replacing recipe parameters for each module. Args: args: Command line arguments that will be used to replace the parameters declared in the recipe.
codesearchnet
def haversine(px, py, r=r_mm): lat1, lon1 = px lat2, lon2 = py dlat = math.radians(lat2 - lat1) dlon = math.radians(lon2 - lon1) lat1 = math.radians(lat1) lat2 = math.radians(lat2) a = math.sin(dlat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2 c = 2 * math...
Calculate the haversine distance between two points defined by (lat,lon) tuples. Args: px ((float,float)): lat/long position 1 py ((float,float)): lat/long position 2 r (float): Radius of sphere Returns: (int): Distance in mm.
juraj-google-style
def __init__(self, exit_node: tensor_lib.Tensor, pfor_ops: List[ops.Operation], fallback_to_while_loop: bool, pfor_config: 'PForConfig'): self._fallback_to_while_loop = fallback_to_while_loop self._pfor_config = pfor_config self._pfor_ops = set(pfor_ops) self._pfor_op_ids = set((x._id for x in pfor_ops)...
Initializer. Args: exit_node: A tensor output from the while_loop. pfor_ops: list of ops inside the current pfor loop. fallback_to_while_loop: If True, fallback to while loop when conversion of an op is not supported pfor_config: PForConfig object used while constructing loop body.
github-repos
def __init__(self, key_value_pairs): self._dict = OrderedDict() for key, value in key_value_pairs: if key not in self._dict: self._dict[key] = [] self._dict[key].append(value) for key, value in iteritems(self._dict): ...
Construct a Lookup with a sequence of (key, value) tuples. Args: key_value_pairs: An iterable over 2-tuples each containing a key, value pair.
juraj-google-style
def clone(self, *args, **overrides): clone = super(Layout, self).clone(*args, **overrides) clone._max_cols = self._max_cols return clone
Clones the Layout, overriding data and parameters. Args: data: New data replacing the existing data shared_data (bool, optional): Whether to use existing data new_type (optional): Type to cast object to *args: Additional arguments to pass to constructor **overrides: New keyword arguments to pass to constructor Return...
codesearchnet