code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def __init__(self, file_system, mount_point, environment_variables=None): super(FileSystemWinRegistryFileReader, self).__init__() self._file_system = file_system self._path_resolver = self._CreateWindowsPathResolver( file_system, mount_point, environment_variables=environment_variables)
Initializes a Windows Registry file reader object. Args: file_system (dfvfs.FileSystem): file system. mount_point (dfvfs.PathSpec): mount point path specification. environment_variables (Optional[list[EnvironmentVariableArtifact]]): environment variables.
juraj-google-style
def parse_content(self, content): self.active_lines_unparsed = get_active_lines(content) if content is not None else [] self.active_settings = split_kv_pairs(content, use_partition=False) if content is not None else []
Main parsing class method which stores all interesting data from the content. Args: content (context.content): Parser context content
juraj-google-style
def _disc_kn(clearness_index, airmass, max_airmass=12): kt = clearness_index am = airmass am = min(am, max_airmass) kt2 = kt * kt kt3 = kt2 * kt if kt <= 0.6: a = 0.512 - 1.56*kt + 2.286*kt2 - 2.222*kt3 b = 0.37 + 0.962*kt c = -0.28 + 0.932*kt - 2....
Calculate Kn for `disc` Args: clearness_index : numeric airmass : numeric max_airmass : float airmass > max_airmass is set to max_airmass before being used in calculating Kn. Returns: Kn : numeric am : numeric airmass used in the calculation of Kn. am <= max_airmass.
juraj-google-style
def crossing_times(ts, c=0.0, d=0.0): ts = ts.squeeze() if (ts.ndim is not 1): raise ValueError('Currently can only use on single variable timeseries') ts = (ts - c) tsa = ts[0:(- 1)] tsb = ts[1:] zc = (np.nonzero((((tsa < 0) & (tsb >= 0)) | ((tsa > 0) & (tsb <= 0))))[0] + 1) va = ts...
For a single variable timeseries, find the times at which the value crosses ``c`` from above or below. Can optionally set a non-zero ``d`` to impose the condition that the value must wander at least ``d`` units away from ``c`` between crossings. If the timeseries begins (or ends) exactly at ``c``, then time zero (or t...
codesearchnet
def is_valid(container, path): try: tmp_hash_path = (container.filename + '.hash') with open(tmp_hash_path, 'r') as tmp_file: tmp_hash = tmp_file.readline() except IOError: LOG.info('No .hash-file in the tmp-directory.') container_hash_path = (local.path(path) / 'gentoo.t...
Checks if a container exists and is unpacked. Args: path: The location where the container is expected. Returns: True if the container is valid, False if the container needs to unpacked or if the path does not exist yet.
codesearchnet
def _FishScript(name, commands, default_options=None): default_options = default_options or set() global_options, options_map, subcommands_map = _GetMaps(name, commands, default_options) fish_source = 'function __fish_using_command\n set cmd (commandline -opc)\n for i in (seq (count $cmd) 1)\n ...
Returns a Fish script registering a completion function for the commands. Args: name: The first token in the commands, also the name of the command. commands: A list of all possible commands that tab completion can complete to. Each command is a list or tuple of the string tokens that make up that command. default_opt...
github-repos
def search_stack_for_var(varname, verbose=util_arg.NOT_QUIET): curr_frame = inspect.currentframe() if verbose: print(' * Searching parent frames for: ' + six.text_type(varname)) frame_no = 0 while curr_frame.f_back is not None: if varname in curr_frame.f_locals.keys(): i...
Finds a varable (local or global) somewhere in the stack and returns the value Args: varname (str): variable name Returns: None if varname is not found else its value
juraj-google-style
def find(self, name): collectors = self.get_collectors() for collector in collectors: if (name.lower() == collector['name'].lower()): self.collector_id = collector['id'] return collector return {'status': 'No results found.'}
Returns a dict of collector's details if found. Args: name (str): name of collector searching for
codesearchnet
def is_descriptor_class(desc, include_abstract=False): return (isinstance(desc, type) and issubclass(desc, Descriptor) and (True if include_abstract else (not inspect.isabstract(desc))))
r"""Check calculatable descriptor class or not. Returns: bool
codesearchnet
def get_impacted_files_from_tiny_model_summary(diff_with_last_commit: bool=False) -> List[str]: repo = Repo(PATH_TO_REPO) folder = Path(repo.working_dir) if not diff_with_last_commit: print(f'main is at {repo.refs.main.commit}') print(f'Current head is at {repo.head.commit}') commits...
Return a list of python modeling files that are impacted by the changes of `tiny_model_summary.json` in between: - the current head and the main branch if `diff_with_last_commit=False` (default) - the current head and its parent commit otherwise. Returns: `List[str]`: The list of Python modeling files that are impact...
github-repos
def __add_scraped_requests_to_queue(self, queue_item, scraped_requests): new_queue_items = [] for scraped_request in scraped_requests: HTTPRequestHelper.patch_with_options(scraped_request, self.__options, queue_item) if (not HTTPRequestHelper.complies_with_scope(queue_item, scraped_request, self...
Convert the scraped requests to queue items, return them and also add them to the queue. Args: queue_item (:class:`nyawc.QueueItem`): The request/response pair that finished. new_requests list(:class:`nyawc.http.Request`): All the requests that were found during this request. Returns: list(:class:`nyawc.QueueItem`): ...
codesearchnet
def _parse_batch_lastlog(last_log): regexp = re.compile('(-?[0-9]\d*):\W+(.*)') wrong_commands = list() for line in last_log: result = regexp.match(line) if result is not None: status_code = result.group(1) command = result.group(...
This static method will help reading the result of the commit, command by command. Args: last_log(list): A list containing, line by line, the result of committing the changes. Returns: A list of tuples that went wrong. The tuple will contain (*status_code*, *command*)
juraj-google-style
def populate_ast_nsarg_orthologs(ast, species): ortholog_namespace = "EG" if isinstance(ast, NSArg): if re.match(ortholog_namespace, ast.canonical): orthologs = bel.terms.orthologs.get_orthologs( ast.canonical, list(species.keys()) ) for species...
Recursively collect NSArg orthologs for BEL AST This requires bo.collect_nsarg_norms() to be run first so NSArg.canonical is available Args: ast: AST at recursive point in belobj species: dictionary of species ids vs labels for or
juraj-google-style
def refresh(self, updated_self): logger.debug('refreshing binary attributes') self.mimetype = updated_self.binary.mimetype self.data = updated_self.binary.data
method to refresh binary attributes and data Args: updated_self (Resource): resource this binary data attaches to Returns: None: updates attributes
codesearchnet
def __init__(self, cipher_suites=None): super(TLS12AuthenticationSuite, self).__init__(cipher_suites) self._protocol = ssl.PROTOCOL_TLSv1_2
Create a TLS12AuthenticationSuite object. Args: cipher_suites (list): A list of strings representing the names of cipher suites to use. Overrides the default set of cipher suites. Optional, defaults to None.
juraj-google-style
def _do_logoff(self): session_uri = '/api/sessions/this-session' self.delete(session_uri, logon_required=False) self._session_id = None self._session = None self._headers.pop('X-API-Session', None)
Log off, unconditionally. Raises: :exc:`~zhmcclient.ServerAuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.HTTPError`
codesearchnet
def run_and_monitor(args, pid_to_wait, std_out_filter_fn=None, cwd=None): monitor_process = None try: p = subprocess.Popen(args, cwd=cwd, env=os.environ, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) ...
Start a process, and have it depend on another specified process. Args: args: the args of the process to start and monitor. pid_to_wait: the process to wait on. If the process ends, also kill the started process. std_out_filter_fn: a filter function which takes a string content from the stdout of the started process, ...
juraj-google-style
def process_python_objects(data, filepath=None): def _process(value): if isinstance(value, dict): for (k, v) in value.items(): value[k] = _process(v) return value elif isfunction(value): func = value if hasattr(func, '_early'): ...
Replace certain values in the given package data dict. Does things like: * evaluates @early decorated functions, and replaces with return value; * converts functions into `SourceCode` instances so they can be serialized out to installed packages, and evaluated later; * strips some values (modules, __-leading variables...
codesearchnet
def CheckParenthesisSpacing(filename, clean_lines, linenum, error): line = clean_lines.elided[linenum] match = Search(r' (if\(|for\(|while\(|switch\()', line) if match: error(filename, linenum, 'whitespace/parens', 5, 'Missing space before ( in %s' % match.group(1)) match = ...
Checks for horizontal spacing around parentheses. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
juraj-google-style
def array_to_jsbuffer(array): if array.ndim != 1: raise TypeError('Only 1d arrays can be converted JS TypedArray.') if array.dtype.name not in JS_ARRAY_TYPES: raise TypeError('Array dtype not supported by JS TypedArray.') js_type_name = array.dtype.name.capitalize() + 'Array' data_base64 = base64.b64...
Serialize 1d NumPy array to JS TypedArray. Data is serialized to base64-encoded string, which is much faster and memory-efficient than json list serialization. Args: array: 1d NumPy array, dtype must be one of JS_ARRAY_TYPES. Returns: JS code that evaluates to a TypedArray as string. Raises: TypeError: if array dty...
juraj-google-style
def delete_group_maintainer(self, grp_name, user): self.service.delete_group_maintainer( grp_name, user, self.url_prefix, self.auth, self.session, self.session_send_opts)
Delete the given user to the named group. Both group and user must already exist for this to succeed. Args: name (string): Name of group. user (string): User to add to group. Raises: requests.HTTPError on failure.
juraj-google-style
def _call_wrapped_cell(self, inputs, state, cell_call_fn, **kwargs): def _should_dropout(p): return not isinstance(p, float) or p < 1 if _should_dropout(self._input_keep_prob): inputs = self._dropout(inputs, 'input', self._recurrent_input_noise, self._input_keep_prob) output, new_state = ce...
Runs the wrapped cell and applies dropout. Args: inputs: A tensor with wrapped cell's input. state: A tensor or tuple of tensors with wrapped cell's state. cell_call_fn: Wrapped cell's method to use for step computation (cell's `__call__` or 'call' method). **kwargs: Additional arguments. Returns: A pair containing: ...
github-repos
def __init__(self, channel): self.ListProfiles = channel.unary_unary( "/google.cloud.talent.v4beta1.ProfileService/ListProfiles", request_serializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_profile__service__pb2.ListProfilesRequest.SerializeToString, respon...
Constructor. Args: channel: A grpc.Channel.
juraj-google-style
def dataset_docs_str(datasets=None): module_to_builder = make_module_to_builder_dict(datasets) sections = sorted(list(module_to_builder.keys())) section_tocs = [] section_docs = [] for section in sections: builders = tf.nest.flatten(module_to_builder[section]) builders = sorted(builders, key=lambd...
Create dataset documentation string for given datasets. Args: datasets: list of datasets for which to create documentation. If None, then all available datasets will be used. Returns: string describing the datasets (in the MarkDown format).
juraj-google-style
def _create_op_from_tf_operation(self, c_op, compute_device=True) -> 'Operation': self._check_not_finalized() ret = Operation._from_c_op(c_op=c_op, g=self) name_key = ret.name.lower() if name_key not in self._names_in_use: self._names_in_use[name_key] = 1 self._create_op_helper(ret, compute_...
Creates an `Operation` in this graph from the supplied TF_Operation. This method is like create_op() except the new Operation is constructed using `c_op`. The returned Operation will have `c_op` as its _c_op field. This is used to create Operation objects around TF_Operations created indirectly by the C API (e.g. by T...
github-repos
def image(request, data): try: width = int(request.GET.get("w", PYDENTICON_WIDTH)) except ValueError: raise SuspiciousOperation("Identicon width must be a positive integer.") try: height = int(request.GET.get("h", PYDENTICON_HEIGHT)) except ValueError: rai...
Generates identicon image based on passed data. Arguments: data - Data which should be used for generating an identicon. This data will be used in order to create a digest which is used for generating the identicon. If the data passed is a hex digest already, the digest will be used as-is. Returns: Identicon image ...
juraj-google-style
def name(self): return ctypes.cast(self.sName, ctypes.c_char_p).value.decode()
Returns the name of the device. Args: self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance Returns: Device name.
juraj-google-style
def add_prop_descriptor_to_class(self, class_name, new_class_attrs, names_with_refs, container_names, dataspecs): from .bases import ContainerProperty from .dataspec import DataSpec name = self.name if (name in new_class_attrs): raise RuntimeError(('Two property generators both created %s.%s' % ...
``MetaHasProps`` calls this during class creation as it iterates over properties to add, to update its registry of new properties. The parameters passed in are mutable and this function is expected to update them accordingly. Args: class_name (str) : name of the class this descriptor is added to new_class_attrs(dict...
codesearchnet
def get_named_tensor(self, name): if (name in self.named_tensors): return (True, self.named_tensors[name]) else: return (False, None)
Returns a named tensor if available. Returns: valid: True if named tensor found, False otherwise tensor: If valid, will be a tensor, otherwise None
codesearchnet
def encode_all_features(dataset, vocabulary): def my_fn(features): ret = {} for k, v in features.items(): v = vocabulary.encode_tf(v) v = tf.concat([tf.to_int64(v), [1]], 0) ret[k] = v return ret return dataset.map(my_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE)
Encode all features. Args: dataset: a tf.data.Dataset vocabulary: a vocabulary.Vocabulary Returns: a tf.data.Dataset
juraj-google-style
def _normalize_direction(heading: int) -> int: while (heading > 359): heading = int((heading - 359)) while (heading < 0): heading = int((heading + 359)) return heading
Make sure that 0 < heading < 360 Args: heading: base heading Returns: corrected heading
codesearchnet
def _FindCodeObjectsReferents(module, start_objects, visit_recorder): def CheckIgnoreCodeObject(code_object): 'Checks if the code object can be ignored.\n\n Code objects that are not implemented in the module, or are from a lambda or\n generator expression can be ignored.\n\n If the module was pre...
Looks for all the code objects referenced by objects in start_objects. The traversal implemented by this function is a shallow one. In other words if the reference chain is a -> b -> co1 -> c -> co2, this function will return [co1] only. The traversal is implemented with BFS. The maximum depth is limited to avoid tou...
codesearchnet
def convert_bboxes_from_albumentations(bboxes, target_format, rows, cols, check_validity=False): return [convert_bbox_from_albumentations(bbox, target_format, rows, cols, check_validity) for bbox in bboxes]
Convert a list of bounding boxes from the format used by albumentations to a format, specified in `target_format`. Args: bboxes (list): List of bounding box with coordinates in the format used by albumentations target_format (str): required format of the output bounding box. Should be 'coco' or 'pascal_voc'. rows (int...
codesearchnet
def MultiNotifyQueue(self, notifications, mutation_pool=None): extract_queue = (lambda notification: notification.session_id.Queue()) for (queue, notifications) in iteritems(collection.Group(notifications, extract_queue)): self._MultiNotifyQueue(queue, notifications, mutation_pool=mutation_pool)
This is the same as NotifyQueue but for several session_ids at once. Args: notifications: A list of notifications. mutation_pool: A MutationPool object to schedule Notifications on. Raises: RuntimeError: An invalid session_id was passed.
codesearchnet
def automatic_control_dependencies(f): def wrapper(*args, **kwargs): with AutomaticControlDependencies() as a: result = f(*args, **kwargs) result_flat = [a.mark_as_return(t) for t in nest.flatten(result)] return nest.pack_sequence_as(result, result_flat) return tf_de...
Wraps f to automatically insert control dependencies. The inserted dependencies ensure that: 1. All stateful ops in f run when the result of f runs 2. Updates to the same resources happen in order. Args: f: the function to be wrapped. Returns: The wrapped function.
github-repos
def argv(cls, name, short_name=None, type=None, help=None): cls.__hierarchy.append(argv.Argv(name, short_name, type, help))
Set command line arguments as a source Parses the command line arguments described by the parameters. Args: name: the long name of the argument (foo) short_name: the optional short name of the argument (f) type: the optional type of the argument, defaults to bool help: the optional help text for the argument
juraj-google-style
def _PromptUserForPartitionIdentifiers( self, volume_system, volume_identifiers): print_header = True while True: if print_header: self._PrintTSKPartitionIdentifiersOverview( volume_system, volume_identifiers) print_header = False lines = self._textwrapper.wr...
Prompts the user to provide partition identifiers. Args: volume_system (dfvfs.TSKVolumeSystem): volume system. volume_identifiers (list[str]): volume identifiers including prefix. Returns: list[str]: selected volume identifiers including prefix or None.
juraj-google-style
def get_ethernet_settings(self): uri = '{}/ethernetSettings'.format(self.data['uri']) return self._helper.do_get(uri)
Gets the Ethernet interconnect settings for the Logical Interconnect. Returns: dict: Ethernet Interconnect Settings
codesearchnet
def close(self): self._dll.JLINKARM_Close() if (self._lock is not None): del self._lock self._lock = None return None
Closes the open J-Link. Args: self (JLink): the ``JLink`` instance Returns: ``None`` Raises: JLinkException: if there is no connected JLink.
codesearchnet
def set_acl(self, role, users): acl_updates = [{"user": user, "role": role} for user in users] r = fapi.update_repository_method_acl( self.namespace, self.name, self.snapshot_id, acl_updates, self.api_url ) fapi._check_response_code(r, 200)
Set permissions for this method. Args: role (str): Access level one of {one of "OWNER", "READER", "WRITER", "NO ACCESS"} users (list(str)): List of users to give role to
juraj-google-style
def combine(self, x): depth = tf.shape(x)[-1] x *= tf.expand_dims(self._nonpadding, -1) ret = tf.unsorted_segment_sum( x, self._flat_indices, num_segments=self._batch * self._length) ret = tf.reshape(ret, [self._batch, self._length, depth]) return ret
Return the output from the experts. When one example goes to multiple experts, the outputs are summed. Args: x: a Tensor with shape [batch, num_experts, expert_capacity, depth] Returns: a `Tensor` with shape `[batch, length, depth]
juraj-google-style
def are_equal(self, sp1, sp2): for s1 in sp1.keys(): spin1 = getattr(s1, 'spin', 0) oxi1 = getattr(s1, 'oxi_state', 0) for s2 in sp2.keys(): spin2 = getattr(s2, 'spin', 0) oxi2 = getattr(s2, 'oxi_state', 0) if ((s1.symbol == s2.symbol) and (oxi1 == oxi2) a...
True if species are exactly the same, i.e., Fe2+ == Fe2+ but not Fe3+. and the spins are reversed. i.e., spin up maps to spin down, and vice versa. Args: sp1: First species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite. sp2: Second species. A dict of {specie/element: amt} as per the d...
codesearchnet
def is_subgroup(self, supergroup): warnings.warn("This is not fully functional. Only trivial subsets are tested right now. ") return set(self.symmetry_ops).issubset(supergroup.symmetry_ops)
True if this group is a subgroup of the supplied group. Args: supergroup (SymmetryGroup): Supergroup to test. Returns: True if this group is a subgroup of the supplied group.
juraj-google-style
def eval(self, session=None): return self._variable.eval(session=session)
In a session, computes and returns the value of this variable. This is not a graph construction method, it does not add ops to the graph. This convenience method requires a session where the graph containing this variable has been launched. If no session is passed, the default session is used. See `tf.compat.v1.Sess...
github-repos
def run(self, tag=None, output=None, **kwargs): start = datetime.datetime.now() count = 0 if tag: tag = Uri(tag) xml_generator = etree.iterparse(self.source, tag=tag.etree) else: xml_generator = etree.iterparse(self.source) i = 0 for (event, element) in xml_generator: ...
runs the extractor Args: ----- output: ['filepath', None]
codesearchnet
def determine_git_ref(self, config): ref_config_keys = 0 for i in ['commit', 'tag', 'branch']: if config.get(i): ref_config_keys += 1 if ref_config_keys > 1: raise ImportError("Fetching remote git sources failed: " ...
Determine the ref to be used for 'git checkout'. Args: config (dict): git config dictionary Returns: str: A commit id or tag name
juraj-google-style
def parse(type: Type): def decorator(parser): EnvVar.parsers[type] = parser return parser return decorator
Register a parser for a attribute type. Parsers will be used to parse `str` type objects from either the commandline arguments or environment variables. Args: type: the type the decorated function will be responsible for parsing a environment variable to.
codesearchnet
def parse_column_path(column: str) -> list: nested_columns = [] for col in column.split('.'): parts = PATTERN.match(col) if parts: column_name, key = (parts.groups()[0], parts.groups()[1]) else: column_name, key = (col, None) if not column_name: ...
Parse the column string to extract nested fields and array indices. Args: column (str): The column string with potential nested fields and array indices. Returns: list: A list of tuples, where each tuple contains the column name and the key/index.
github-repos
def __init__(self, input_dataset, target_device, source_device='/cpu:0'): self._input_dataset = input_dataset._apply_debug_options() self._target_device = target_device spec = framework_device.DeviceSpec().from_string(self._target_device) self._is_gpu_target = spec.device_type == 'GPU' self._source_...
Constructs a _CopyToDeviceDataset. Args: input_dataset: `Dataset` to be copied target_device: The name of the device to which elements would be copied. source_device: Device where input_dataset would be placed.
github-repos
def dot(r1, r2): if r1.size != r2.size: raise ValueError("Both arguments must have the same input size.") if r1.deriv != r2.deriv: raise ValueError("Both arguments must have the same deriv.") return r1.x*r2.x + r1.y*r2.y + r1.z*r2.z
Compute the dot product Arguments: | ``r1``, ``r2`` -- two :class:`Vector3` objects (Returns a Scalar)
juraj-google-style
def parse(self, values): type_map = {} for name, t in self._hparam_types.items(): param_type, _ = t type_map[name] = param_type values_map = parse_values(values, type_map) return self.override_from_dict(values_map)
Override existing hyperparameter values, parsing new values from a string. See parse_values for more detail on the allowed format for values. Args: values: String. Comma separated list of `name=value` pairs where 'value' must follow the syntax described above. Returns: The `HParams` instance. Raises: ValueError: I...
juraj-google-style
def get_checkpoint_factories_and_keys(object_names, object_map=None): checkpoint_factory_map = object_identity.ObjectIdentityDictionary() unmapped_registered_savers = collections.defaultdict(dict) for trackable, object_name in object_names.items(): object_to_save = util.get_mapped_trackable(trackabl...
Gets a map of saveable factories and corresponding checkpoint keys. Args: object_names: a dictionary that maps `Trackable` objects to auto-generated string names. object_map: a dictionary mapping `Trackable` to copied `Trackable` objects. The copied objects are generated from `Trackable. _export_to_saved_model_graph()...
github-repos
def create_function(self, vpc_config): zip_file = 'lambda-holder.zip' with zipfile.ZipFile(zip_file, mode='w') as zipped: zipped.writestr('index.py', 'print "Hello world"') contents = '' with open('lambda-holder.zip', 'rb') as openfile: contents = openfi...
Create lambda function, configures lambda parameters. We need to upload non-zero zip when creating function. Uploading hello_world python lambda function since AWS doesn't care which executable is in ZIP. Args: vpc_config (dict): Dictionary of SubnetIds and SecurityGroupsIds for using a VPC in lambda
juraj-google-style
def submit_files(self, halt_on_error=True): if (self.halt_on_file_error is not None): halt_on_error = self.halt_on_file_error upload_status = [] for (xid, content_data) in self._files.items(): del self._files[xid] status = True if (self.debug and (xid in self.saved_xids)): ...
Submit Files for Documents and Reports to ThreatConnect API. Critical Errors * There is insufficient document storage allocated to this account. Args: halt_on_error (bool, default:True): If True any exception will raise an error. Returns: dict: The upload status for each xid.
codesearchnet
def search(cls, session, queries): return super(Conversations, cls).search(session, queries, SearchConversation)
Search for a conversation given a domain. Args: session (requests.sessions.Session): Authenticated session. queries (helpscout.models.Domain or iter): The queries for the domain. If a ``Domain`` object is provided, it will simply be returned. Otherwise, a ``Domain`` object will be generated from the complex queries. I...
codesearchnet
def __init__(self, identifier): super(Volume, self).__init__() self.identifier = identifier self._attributes = {} self._extents = [] self._is_parsed = False
Initializes a volume. Args: identifier (str): identifier of the attribute within the volume.
juraj-google-style
def AddEventSource(self, event_source): self._RaiseIfNotWritable() self._AddAttributeContainer( self._CONTAINER_TYPE_EVENT_SOURCE, event_source)
Adds an event source. Args: event_source (EventSource): event source. Raises: IOError: when the storage file is closed or read-only. OSError: when the storage file is closed or read-only.
juraj-google-style
def stacked_bi_rnn(units: tf.Tensor, n_hidden_list: List, cell_type='gru', seq_lengths=None, use_peepholes=False, name='RNN_layer'): for (n, n_hidden) in enumerate(n_hidden_list): with tf.variable_scope(((name + '_') + str(n))): if (cell_type == 'gru'): forward_cell = tf.nn.rnn_c...
Stackted recurrent neural networks GRU or LSTM Args: units: a tensorflow tensor with dimensionality [None, n_tokens, n_features] n_hidden_list: list with number of hidden units at the ouput of each layer seq_lengths: length of sequences for different length sequences in batch can be None for maximum length as a length...
codesearchnet
def __init__(self, job_context, shard_state): self.job_context = job_context self.id = shard_state.shard_id self.number = shard_state.shard_number self.attempt = shard_state.retries + 1 self._state = shard_state
Init. The signature of __init__ is subject to change. Read only properties: job_context: JobContext object. id: str. of format job_id-shard_number. number: int. shard number. 0 indexed. attempt: int. The current attempt at executing this shard. Starting at 1. Args: job_context: map_job.JobConfig. shard_state: model....
juraj-google-style
def proxy_num(self, protocol=None): http_num = len(self.proxies['http']) https_num = len(self.proxies['https']) if protocol == 'http': return http_num elif protocol == 'https': return https_num else: return http_num + https_num
Get the number of proxies in the pool Args: protocol (str, optional): 'http' or 'https' or None. (default None) Returns: If protocol is None, return the total number of proxies, otherwise, return the number of proxies of corresponding protocol.
juraj-google-style
def get_model_filepath(self, infodict): u = infodict['uniprot_ac'] original_filename = '{}_{}_{}_{}'.format(infodict['from'], infodict['to'], infodict['template'], infodict['coordinate_id']) file_path = op.join(self.metadata_dir, u[:2], u[2:4], u[4:6], 'swissmodel', '{}.pdb'.format(original_filename)) i...
Get the path to the homology model using information from the index dictionary for a single model. Example: use self.get_models(UNIPROT_ID) to get all the models, which returns a list of dictionaries. Use one of those dictionaries as input to this function to get the filepath to the model itself. Args: infodict (dict...
codesearchnet
def is_array_str(x: Any) -> bool: if isinstance(x, (bytes, str)): return True elif is_array(x): return is_dtype_str(x.dtype) else: return False
Returns True if the given array is a `str` array. Note: Also returns True for scalar `str`, `bytes` values. For compatibility with `tensor.numpy()` which returns `bytes` Args: x: The array to test Returns: True or False
github-repos
def set_authentication_profile(profile=None, deploy=False): if not profile: raise CommandExecutionError("Profile name option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/dev...
Set the authentication profile of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: profile (str): The name of the authentication profile to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: ba...
juraj-google-style
def _send_request(self, url, method="get", data=None, extra_headers=None): headers = {'Content-type': 'application/json'} if isinstance(extra_headers, dict): headers.update(extra_headers) if not data or "password" not in data: logger.debug("Sending {method} requ...
Performs a given request and returns a json object Args: url (str): URL of the request method (str): Any of "get", "post", "delete" data (any): Possible extra data to send with the request extra_headers (dict): Possible extra headers to send along in the request Returns: dict
juraj-google-style
def assert_almost_eq(arr_test, arr_target, thresh=1E-11): r if util_arg.NO_ASSERTS: return import utool as ut arr1 = np.array(arr_test) arr2 = np.array(arr_target) passed, error = ut.almost_eq(arr1, arr2, thresh, ret_error=True) if not np.all(passed): failed_xs = np.where(np....
r""" Args: arr_test (ndarray or list): arr_target (ndarray or list): thresh (scalar or ndarray or list):
juraj-google-style
def make_anchor(file_path: pathlib.Path, offset: int, width: int, context_width: int, metadata, encoding: str='utf-8', handle=None): @contextmanager def get_handle(): if (handle is None): with file_path.open(mode='rt', encoding=encoding) as fp: (yield fp) else: ...
Construct a new `Anchor`. Args: file_path: The absolute path to the target file for the anchor. offset: The offset of the anchored text in codepoints in `file_path`'s contents. width: The width in codepoints of the anchored text. context_width: The width in codepoints of context on either side of the anchor. metadata:...
codesearchnet
def secure_channel(target, credentials, options=None, *, loop=None, executor=None, standalone_pool_for_streaming=False): return Channel(_grpc.secure_channel(target, credentials, options), loop, executor, standalone_pool_for_streaming)
Creates a secure Channel to a server. Args: target: The server address. credentials: A ChannelCredentials instance. options: An optional list of key-value pairs (channel args in gRPC runtime) to configure the channel. Returns: A Channel object.
juraj-google-style
def DeserializeExclusiveData(self, reader): self.Nonce = reader.ReadUInt32() self.Type = TransactionType.MinerTransaction
Deserialize full object. Args: reader (neo.IO.BinaryReader):
juraj-google-style
def AddBlob(self, blob_id, length): if self.finalized and length > 0: raise IOError("Can't add blobs to finalized BlobImage") self.content_dirty = True self.index.seek(0, 2) self.index.write(blob_id.AsBytes()) self.size += length if length < self.chunksize: self.finalized = Tr...
Add another blob to this image using its hash. Once a blob is added that is smaller than the chunksize we finalize the file, since handling adding more blobs makes the code much more complex. Args: blob_id: rdf_objects.BlobID object. length: int length of blob Raises: IOError: if blob has been finalized.
juraj-google-style
def forward(self, encoder_hidden_states): hidden_states = encoder_hidden_states.transpose(1, -1) for layer in self.conv_layers: hidden_states = layer(hidden_states) hidden_states = self.linear(hidden_states.transpose(1, -1)).squeeze(-1) if not self.training: hidden_states = torch.clamp(t...
Args: hidden_states (`torch.Tensor` of shape `(batch_size, max_text_length, input_dim)`): Batch of input sequences. padding_masks (`torch.ByteTensor` of shape `(batch_size, max_text_length)`, *optional*): Batch of masks indicating padded part. Returns: `torch.Tensor`: Batch of predicted durations in log domain `(batch...
github-repos
def order_by(self, *args): clone = copy.deepcopy(self) clone.adapter.ordered = True if args: clone.adapter.order_by(*args) return clone
Applies query ordering. Args: **args: Order by fields names. Defaults to ascending, prepend with hypen (-) for desecending ordering. Returns: Self. Queryset object. Examples: >>> Person.objects.order_by('-name', 'join_date')
juraj-google-style
def circuit_to_image(circ: Circuit, qubits: Qubits = None) -> PIL.Image: latex = circuit_to_latex(circ, qubits) img = render_latex(latex) return img
Create an image of a quantum circuit. A convenience function that calls circuit_to_latex() and render_latex(). Args: circ: A quantum Circuit qubits: Optional qubit list to specify qubit order Returns: Returns: A PIL Image (Use img.show() to display) Raises: NotImplementedError: For unsupported gates. OSEr...
juraj-google-style
def update_labels(self, node_name: str, labels: dict): if (not self._manager): raise RuntimeError('Only the Swarm manager node can update node details.') node_spec = {'Availability': 'active', 'Name': node_name, 'Role': 'manager', 'Labels': labels} node = self._client.nodes.get(node_name) node.u...
Update label of a node. Args: node_name (string): Name of the node. labels (dict): Label to add to the node
codesearchnet
def ParseFileObject(self, parser_mediator, file_object): display_name = parser_mediator.GetDisplayName() if not zipfile.is_zipfile(file_object): raise errors.UnableToParseFile( '[{0:s}] unable to parse file: {1:s} with error: {2:s}'.format( self.NAME, display_name, 'Not a Zip...
Parses a compound ZIP file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): a file-like object. Raises: UnableToParseFile: when the file cannot be parsed.
juraj-google-style
def shakespeare(chunk_size): file_name = maybe_download('http: 'shakespear.txt') with open(file_name) as f: shakespeare_full = f.read() length = (len(shakespeare_full) if length < len(shakespeare_full): shakespeare_full = shakespeare_full[:length] arr = np.array([c...
Downloads Shakespeare, converts it into ASCII codes and chunks it. Args: chunk_size: The dataset is broken down so that it is shaped into batches x chunk_size. Returns: A numpy array of ASCII codes shaped into batches x chunk_size.
juraj-google-style
def resize_file(fobj, diff, BUFFER_SIZE=2 ** 16): fobj.seek(0, 2) filesize = fobj.tell() if diff < 0: if filesize + diff < 0: raise ValueError fobj.truncate(filesize + diff) elif diff > 0: try: while diff: addsize = min(BUFF...
Resize a file by `diff`. New space will be filled with zeros. Args: fobj (fileobj) diff (int): amount of size to change Raises: IOError
juraj-google-style
def fn(x: int) -> int: return x
Test function Args: x: The input Returns: The output
github-repos
def trace_region_count(self): cmd = enums.JLinkTraceCommand.GET_NUM_REGIONS data = ctypes.c_uint32(0) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data)) if (res == 1): raise errors.JLinkException('Failed to get trace region count.') return data.value
Retrieves a count of the number of available trace regions. Args: self (JLink): the ``JLink`` instance. Returns: Count of the number of available trace regions.
codesearchnet
def clear(self, color: Tuple[(int, int, int)]) -> None: lib.TCOD_image_clear(self.image_c, color)
Fill this entire Image with color. Args: color (Union[Tuple[int, int, int], Sequence[int]]): An (r, g, b) sequence or Color instance.
codesearchnet
def VerifyServerPEM(self, http_object): try: server_pem = http_object.data server_url = http_object.url if (b'BEGIN CERTIFICATE' in server_pem): server_certificate = rdf_crypto.RDFX509Cert(server_pem) self.communicator.LoadServerCertificate(server_certificate=server_c...
Check the server PEM for validity. This is used to determine connectivity to the server. Sometimes captive portals return a valid HTTP status, but the data is corrupted. Args: http_object: The response received from the server. Returns: True if the response contains a valid server certificate.
codesearchnet
def from_maildir(self, codes: str) -> FrozenSet[Flag]: flags = set() for code in codes: if code == ',': break to_sys = self._to_sys.get(code) if to_sys is not None: flags.add(to_sys) else: to_kwd = s...
Return the set of IMAP flags that correspond to the letter codes. Args: codes: The letter codes to map.
juraj-google-style
def problem(problem_name, **kwargs): spec = parse_problem_name(problem_name) try: return Registries.problems[spec.base_name]( was_copy=spec.was_copy, was_reversed=spec.was_reversed) except KeyError: return env_problem(problem_name, **kwargs)
Get possibly copied/reversed problem in `base_registry` or `env_registry`. Args: problem_name: string problem name. See `parse_problem_name`. **kwargs: forwarded to env problem's initialize method. Returns: possibly reversed/copied version of base problem registered in the given registry.
juraj-google-style
def encode(self, s): return [(int(w) + self._num_reserved_ids) for w in s.split()]
Transform a human-readable string into a sequence of int ids. The ids should be in the range [num_reserved_ids, vocab_size). Ids [0, num_reserved_ids) are reserved. EOS is not appended. Args: s: human-readable string to be converted. Returns: ids: list of integers
codesearchnet
def napalm_cli(task: Task, commands: List[str]) -> Result: device = task.host.get_connection("napalm", task.nornir.config) result = device.cli(commands) return Result(host=task.host, result=result)
Run commands on remote devices using napalm Arguments: commands: commands to execute Returns: Result object with the following attributes set: * result (``dict``): result of the commands execution
juraj-google-style
def increment_id(cls, _id: ObjectId, inc: int) -> ObjectId: id_number = _ObjectIdHelper.id_to_int(_id) new_number = id_number + inc if new_number < 0 or new_number >= 1 << 96: raise ValueError('invalid incremental, inc value must be within [%s, %s)' % (0 - id_number, 1 << 96 - id_number)) return...
Increment object_id binary value by inc value and return new object id. Args: _id: The `_id` to change. inc(int): The incremental int value to be added to `_id`. Returns: `_id` incremented by `inc` value
github-repos
def infer(msg, mrar=False): df = common.df(msg) if common.allzeros(msg): return 'EMPTY' if (df == 17): tc = common.typecode(msg) if (1 <= tc <= 4): return 'BDS08' if (5 <= tc <= 8): return 'BDS06' if (9 <= tc <= 18): return 'BDS05' ...
Estimate the most likely BDS code of an message. Args: msg (String): 28 bytes hexadecimal message string mrar (bool): Also infer MRAR (BDS 44) and MHR (BDS 45). Defaults to False. Returns: String or None: BDS version, or possible versions, or None if nothing matches.
codesearchnet
def wrap(access_pyxb, read_only=False): w = AccessPolicyWrapper(access_pyxb) yield w if not read_only: w.get_normalized_pyxb()
Work with the AccessPolicy in a SystemMetadata PyXB object. Args: access_pyxb : AccessPolicy PyXB object The AccessPolicy to modify. read_only: bool Do not update the wrapped AccessPolicy. When only a single AccessPolicy operation is needed, there's no need to use this context manager. Instead, use the generated con...
juraj-google-style
def FileEntryExistsByPathSpec(self, path_spec): location = getattr(path_spec, 'location', None) if (location is None or not location.startswith(self.LOCATION_ROOT)): return False if len(location) == 1: return True try: self._tar_file.getmember(location[1:]) return...
Determines if a file entry for a path specification exists. Args: path_spec (PathSpec): path specification. Returns: bool: True if the file entry exists.
juraj-google-style
def private_map(self): return self._private_map
A map from parents to symbols that should not be included at all. This map can be edited, but it should not be edited once traversal has begun. Returns: The map marking symbols to not include.
github-repos
def __init__(self, match=None, qps=None, user_qps=None, daily=None, analytics_id=None): _CheckType(match, basestring, 'match') _CheckType(qps, int, 'qps') _CheckType(user_qps, int, 'user_qps') _CheckType(daily, int, 'daily') _CheckType(analytics_id, basestring, 'analytics_id') ...
Constructor for ApiFrontEndLimitRule. Args: match: string, the matching rule that defines this traffic segment. qps: int, the aggregate QPS for this segment. user_qps: int, the per-end-user QPS for this segment. daily: int, the aggregate daily maximum for this segment. analytics_id: string, the project ID under which ...
juraj-google-style
def __init__(self, username, email, manager): super(User, self).__init__(manager) self.username = username self.email = email
Initialize a user. Args: username (str): The user's username. email (str): The user's email. manager (:class:`saltant.models.user.UserManager`): The manager which spawned this user instance.
juraj-google-style
def do_usufy(self, query, **kwargs): try: self.wrapperAPI = TwitterAPIWrapper() results = self.wrapperAPI.get_user(query) for r in results: aux = {} aux["type"]="i3visio.uri" alias=r["value"]...
Verifying a usufy query in this platform. This might be redefined in any class inheriting from Platform. Args: ----- query: The element to be searched. Return: ------- A list of elements to be appended.
juraj-google-style
def CreateDataTypeMapByType(cls, data_type_definition): data_type_map_class = cls._MAP_PER_DEFINITION.get( data_type_definition.TYPE_INDICATOR, None) if not data_type_map_class: return None return data_type_map_class(data_type_definition)
Creates a specific data type map by type indicator. Args: data_type_definition (DataTypeDefinition): data type definition. Returns: DataTypeMap: data type map or None if the date type definition is not available.
juraj-google-style
def append_item(self, item): did_remove = self.remove_exit() item.menu = self self.items.append(item) if did_remove: self.add_exit()
Add an item to the end of the menu before the exit item. Args: item (MenuItem): The item to be added.
juraj-google-style
def persist_perf(run, session, svg_path): from benchbuild.utils import schema as s with open(svg_path, 'r') as svg_file: svg_data = svg_file.read() session.add( s.Metadata(name="perf.flamegraph", value=svg_data, run_id=run.id))
Persist the flamegraph in the database. The flamegraph exists as a SVG image on disk until we persist it in the database. Args: run: The run we attach these perf measurements to. session: The db transaction we belong to. svg_path: The path to the SVG file we want to store.
juraj-google-style
def merge_json_fhir_object_into_proto(json_value: Dict[str, Any], target: message.Message, *, validate: bool=True, default_timezone: str=_primitive_time_utils.SIMPLE_ZULU) -> None: parser = _json_parser.JsonParser.json_parser_with_default_timezone(_PRIMITIVE_HANDLER, default_timezone=default_timezone) parser.me...
Merges the provided json_value object into a target Message. Args: json_value: The parsed JSON object to merge into target. target: The Message instance to merge raw_json into. validate: A Boolean value indicating if validation should be performed on the resultant Message. Validation takes the form of ensuring that ba...
github-repos
def __init__(self, action_meanings): self.action_meanings = action_meanings self._wait = True self.action_space = None self._last_step_tuples = None self.action_meanings = action_meanings self.name_to_action_num = {name: num for num, name in enumerate(sel...
Constructor for PlayerEnv. Args: action_meanings: list of strings indicating action names. Can be obtain by >>> env = gym.make("PongNoFrameskip-v4") # insert your game name >>> env.unwrapped.get_action_meanings() See gym AtariEnv get_action_meanings() for more details.
juraj-google-style
def run(self, args): jlink = self.create_jlink(args) if args.downgrade: if (not jlink.firmware_newer()): print('DLL firmware is not older than J-Link firmware.') else: jlink.invalidate_firmware() try: jlink.update_firmware() except ...
Runs the firmware command. Args: self (FirmwareCommand): the ``FirmwareCommand`` instance args (Namespace): arguments to parse Returns: ``None``
codesearchnet
def extract_all(self): (longmin, longmax, latmin, latmax) = self.Boundary() (sample_min, sample_max) = map(int, (self.SAMPLE_FIRST_PIXEL, self.SAMPLE_LAST_PIXEL)) (line_min, line_max) = map(int, (self.LINE_FIRST_PIXEL, self.LINE_LAST_PIXEL)) X = np.array(map(self.long_id, range(sample_min, (sample_max +...
Extract all the image Returns: A tupple of three arrays ``(X,Y,Z)`` with ``X`` contains the longitudes, ``Y`` contains the latitude and ``Z`` the values extracted from the image. Note: All return arrays have the same size. All coordinate are in degree.
codesearchnet
def validate_json_schema(data, schema, name="task"): try: jsonschema.validate(data, schema) except jsonschema.exceptions.ValidationError as exc: raise ScriptWorkerTaskException( "Can't validate {} schema!\n{}".format(name, str(exc)), exit_code=STATUSES['malformed-pay...
Given data and a jsonschema, let's validate it. This happens for tasks and chain of trust artifacts. Args: data (dict): the json to validate. schema (dict): the jsonschema to validate against. name (str, optional): the name of the json, for exception messages. Defaults to "task". Raises: ScriptWorkerTaskException: o...
juraj-google-style