code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def ToCsv(self, columns_order=None, order_by=(), separator=','): csv_buffer = six.StringIO() writer = csv.writer(csv_buffer, delimiter=separator) if (columns_order is None): columns_order = [col['id'] for col in self.__columns] col_dict = dict([(col['id'], col) for col in self.__columns]) d...
Writes the data table as a CSV string. Output is encoded in UTF-8 because the Python "csv" module can't handle Unicode properly according to its documentation. Args: columns_order: Optional. Specifies the order of columns in the output table. Specify a list of all column IDs in the order in which you want the table c...
codesearchnet
def __get__(self, inst, cls): if inst is None: return self._unbound_method else: if not hasattr(inst, INSTANCE_OBSERVER_ATTR): d = {} setattr(inst, INSTANCE_OBSERVER_ATTR, d) else: d = getattr(inst, INSTANCE_OB...
Return an ObservableBoundMethod or ObservableUnboundMethod. If accessed by instance, I return an ObservableBoundMethod which handles that instance. If accessed by class I return an ObservableUnboundMethod. Args: inst: The instance through which I was accessed. This will be None if I was accessed through the class, i....
juraj-google-style
def updateFeatureService(self, efs_config): if self.securityhandler is None: print ("Security handler required") return fsRes = None fst = None fURL = None resItm= None try: fsRes = [] fst = featureservicetools.fea...
Updates a feature service. Args: efs_config (list): A list of JSON configuration feature service details to update. Returns: dict: A dictionary of results objects.
juraj-google-style
def __init__(self, tcex, name, description, data_type, interval, keyed=False): self.tcex = tcex self._metric_data_type = data_type self._metric_description = description self._metric_id = None self._metric_interval = interval self._metric_keyed = keyed se...
Initialize the Class properties. Args: name (str): The name for the metric. description (str): The description of the metric. data_type (str): The type of metric: Sum, Count, Min, Max, First, Last, and Average. interval (str): The metric interval: Hourly, Daily, Weekly, Monthly, and Yearly. keyed (bool, default:False)...
juraj-google-style
def lchmod(self, path, mode): if self.filesystem.is_windows_fs: raise (NameError, "name 'lchmod' is not defined") self.filesystem.chmod(path, mode, follow_symlinks=False)
Change the permissions of a file as encoded in integer mode. If the file is a link, the permissions of the link are changed. Args: path: (str) Path to the file. mode: (int) Permissions.
codesearchnet
def apply_inverse(self, y): self._recompute() return self.solver.solve(self._process_input(y))
Apply the inverse of the covariance matrix to a vector or matrix Solve ``K.x = y`` for ``x`` where ``K`` is the covariance matrix of the GP with the white noise and ``yerr`` components included on the diagonal. Args: y (array[n] or array[n, nrhs]): The vector or matrix ``y`` described above. Returns: array[n] or arr...
codesearchnet
def get_last_next(self, date): past, future = (None, None), (None, None) for mjd, value in reversed(self.data): if mjd <= date: past = (mjd, value) break future = (mjd, value) return past, future
Provide the last and next leap-second events relative to a date Args: date (float): Date in MJD Return: tuple:
juraj-google-style
def ExpandSignature(sig): params = [] for param in sig.params: if isinstance(param.type, pytd.UnionType): params.append([param.Replace(type=t) for t in param.type.type_list]) else: params.append([param]) new_signatures = [sig.Replace(params=tuple(combination)) for com...
Expand a single signature. For argument lists that contain disjunctions, generates all combinations of arguments. The expansion will be done right to left. E.g., from (a or b, c or d), this will generate the signatures (a, c), (a, d), (b, c), (b, d). (In that order) Arguments: sig: A pytd.Signature instance. Returns...
github-repos
def CaptureFrameLocals(self, frame): variables = {n: self.CaptureNamedVariable(n, v, 1, self.default_capture_limits) for n, v in six.viewitems(frame.f_locals)} nargs = frame.f_code.co_argcount if frame.f_code.co_flags & inspect.C...
Captures local variables and arguments of the specified frame. Args: frame: frame to capture locals and arguments. Returns: (arguments, locals) tuple.
juraj-google-style
def _transform_filter_to_sql(filter_block, node, context): expression = filter_block.predicate return _expression_to_sql(expression, node, context)
Transform a Filter block to its corresponding SQLAlchemy expression. Args: filter_block: Filter, the Filter block to transform. node: SqlNode, the node Filter block applies to. context: CompilationContext, global compilation state and metadata. Returns: Expression, SQLAlchemy expression equivalent to the Filter.predi...
codesearchnet
def _MaxPoolAlongCols(self, input_matrix, col_seq, overlapping): input_matrix = input_matrix.transpose() output_matrix = self._MaxPoolAlongRows(input_matrix, col_seq, overlapping) return output_matrix.transpose()
Perform max pool along column of a 2-D matrix based on col_seq. Args: input_matrix: A 2-D matrix. col_seq: Cumulative pooling sequence along column. overlapping: Whether or not use overlapping when pooling. Returns: A 2-D matrix, with * num_rows = input_matrix.num_rows * num_cols = len(col_seq)-1.
github-repos
def HasColumn(self, table_name, column_name): if not self._connection: raise IOError('Not opened.') if not column_name: return False table_name = table_name.lower() column_names = self._column_names_per_table.get(table_name, None) if column_names is None: column_names = [] ...
Determines if a specific column exists. Args: table_name (str): name of the table. column_name (str): name of the column. Returns: bool: True if the column exists. Raises: IOError: if the database file is not opened. OSError: if the database file is not opened.
juraj-google-style
def perform(self, agent_indices, observ): with tf.name_scope('perform/'): observ = self._observ_filter.transform(observ) if (self._last_state is None): state = None else: state = tools.nested.map((lambda x: tf.gather(x, agent_indices)), self._last_state) with ...
Compute batch of actions and a summary for a batch of observation. Args: agent_indices: Tensor containing current batch indices. observ: Tensor of a batch of observations for all agents. Returns: Tuple of action batch tensor and summary tensor.
codesearchnet
def AddEventTag(self, event_tag): self._RaiseIfNotWritable() event_identifier = event_tag.GetEventIdentifier() if not isinstance(event_identifier, identifiers.FakeIdentifier): raise IOError('Unsupported event identifier type: {0:s}'.format( type(event_identifier))) event_tag = sel...
Adds an event tag. Args: event_tag (EventTag): event tag. Raises: IOError: when the storage writer is closed. OSError: when the storage writer is closed.
juraj-google-style
def get_assignee(self, main_type, sub_type, unique_id, assignee_id, params=None): params = params or {} return self.assignee(main_type, sub_type, unique_id, assignee_id, params=params)
Args: main_type: sub_type: unique_id: assignee_id: params: Return:
juraj-google-style
def is_test_executed(self, test_name): for record in self.executed: if record.test_name == test_name: return True return False
Checks if a specific test has been executed. Args: test_name: string, the name of the test to check. Returns: True if the test has been executed according to the test result, False otherwise.
github-repos
def check_time(timer_id): if (timer_id not in _g_timers): _g_timers[timer_id] = Timer() return 0 else: return _g_timers[timer_id].since_last_check()
Add check points in a single line. This method is suitable for running a task on a list of items. A timer will be registered when the method is called for the first time. :Example: >>> import time >>> import mmcv >>> for i in range(1, 6): >>> # simulate a code block >>> time.sleep(i) >>> mmcv.check_time(...
codesearchnet
def broker_metadata(self, broker_id): return self._brokers.get(broker_id) or self._bootstrap_brokers.get(broker_id)
Get BrokerMetadata Arguments: broker_id (int): node_id for a broker to check Returns: BrokerMetadata or None if not found
juraj-google-style
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): super(CreateKeyPairRequestPayload, self).read(input_buffer, kmip_version=kmip_version) local_buffer = utils.BytearrayStream(input_buffer.read(self.length)) if (kmip_version < enums.KMIPVersion.KMIP_2_0): if self.is_tag_next(enums...
Read the data encoding the CreateKeyPair request payload and decode it into its constituent parts. Args: input_buffer (stream): A data buffer containing encoded object data, supporting a read method. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, d...
codesearchnet
def intersect(self, other, strategy=_STRATEGY.GEOMETRIC, _verify=True): if _verify: if (not isinstance(other, Surface)): raise TypeError('Can only intersect with another surface', 'Received', other) if ((self._dimension != 2) or (other._dimension != 2)): raise NotImplementedE...
Find the common intersection with another surface. Args: other (Surface): Other surface to intersect with. strategy (Optional[~bezier.curve.IntersectionStrategy]): The intersection algorithm to use. Defaults to geometric. _verify (Optional[bool]): Indicates if extra caution should be used to verify assumptions about t...
codesearchnet
def seat_button_count(self): if (self.type != EventType.TABLET_TOOL_BUTTON): raise AttributeError(_wrong_prop.format(self.type)) return self._libinput.libinput_event_tablet_tool_get_seat_button_count(self._handle)
The total number of buttons pressed on all devices on the associated seat after the the event was triggered. For events that are not of type :attr:`~libinput.constant.EventType.TABLET_TOOL_BUTTON`, this property raises :exc:`AttributeError`. Returns: int: The seat wide pressed button count for the key of this event.
codesearchnet
def load_resource(path): with open(get_path_to_datafile(path), 'rb') as f: return f.read()
Load the resource at given path, where path is relative to tensorflow/. Args: path: a string resource path relative to tensorflow/. Returns: The contents of that resource. Raises: IOError: If the path is not found, or the resource can't be opened.
github-repos
def get(self: 'Option[Mapping[K,V]]', key: K, default=None) -> 'Option[V]': if self._is_some: return self._type.maybe(self._val.get(key, default)) return self._type.maybe(default)
Gets a mapping value by key in the contained value or returns ``default`` if the key doesn't exist. Args: key: The mapping key. default: The defauilt value. Returns: * ``Some`` variant of the mapping value if the key exists and the value is not None. * ``Some(default)`` if ``default`` is not None. * :py:data:`NONE` i...
codesearchnet
def default(self, obj): from ..model import Model from ..colors import Color from .has_props import HasProps if (pd and isinstance(obj, (pd.Series, pd.Index))): return transform_series(obj, force_list=True) elif isinstance(obj, np.ndarray): return transform_array(obj, force_list=True...
The required ``default`` method for ``JSONEncoder`` subclasses. Args: obj (obj) : The object to encode. Anything not specifically handled in this method is passed on to the default system JSON encoder.
codesearchnet
def choose_branch(exclude=None): if exclude is None: master = conf.get('git.master_branch', 'master') develop = conf.get('git.devel_branch', 'develop') exclude = {master, develop} branches = list(set(git.branches()) - exclude) for i, branch_name in enumerate(branches...
Show the user a menu to pick a branch from the existing ones. Args: exclude (list[str]): List of branch names to exclude from the menu. By default it will exclude master and develop branches. To show all branches pass an empty array here. Returns: str: The name of the branch chosen by the user. If the user inputs an ...
juraj-google-style
def do_batch(args): if args.subcommand == 'list': do_batch_list(args) if args.subcommand == 'show': do_batch_show(args) if args.subcommand == 'status': do_batch_status(args) if args.subcommand == 'submit': do_batch_submit(args)
Runs the batch list, batch show or batch status command, printing output to the console Args: args: The parsed arguments sent to the command at runtime
juraj-google-style
def _WriteFile(output_path, name, content): path = os.path.join(output_path, name) with open(path, 'wb') as f: f.write(content) return path
Write given content to a file in a given directory. Args: output_path: The directory to store the file in. name: The name of the file to store the content in. content: The content to write to the file.close Returns: The full path to the written file.
codesearchnet
def valueWritePreprocessor(valueString, replaceParamsFile=None): if type(valueString) is bool: log.warning("Only numerical variable types can be handled by the valueReadPreprocessor function.") return valueString variableString = valueString if replaceParamsFile is not None:...
Look up variable name in replace param file for the negative id given and return it. Args: valueString (str): String representing the value to be preprocessed. replaceParamsFile (gsshapy.orm.ReplaceParamFile, optional): Instance of the replace param file. Required if replacement variables are included in the project. ...
juraj-google-style
def write_compounds(self, stream, compounds, properties=None): self._write_entries( stream, compounds, self.convert_compound_entry, properties)
Write iterable of compounds as YAML object to stream. Args: stream: File-like object. compounds: Iterable of compound entries. properties: Set of compound properties to output (or None to output all).
juraj-google-style
def profile_graph(self, options): opts = _build_options(options) tfprof_node = tfprof_output_pb2.GraphNodeProto() try: tfprof_node.ParseFromString(print_mdl.Profile('graph'.encode('utf-8'), opts.SerializeToString())) except message.DecodeError as e: sys.stderr.write('Cannot parse returne...
Profile the statistics of graph nodes, organized by dataflow graph. Args: options: A dict of options. See core/profiler/g3doc/options.md. Returns: a GraphNodeProto that records the results.
github-repos
def validate(self, proxy_scanner, expected_num=20, queue_timeout=3, val_timeout=5): while self.proxy_num() < expected_num: try: candidate_proxy = proxy_scanner.proxy_queue.get( timeout=qu...
Target function of validation threads Args: proxy_scanner: A ProxyScanner object. expected_num: Max number of valid proxies to be scanned. queue_timeout: Timeout for getting a proxy from the queue. val_timeout: An integer passed to `is_valid` as argument `timeout`.
juraj-google-style
def __make_request(self, url, method, data, auth, cookies, headers, proxies, timeout, verify): request_by_method = getattr(requests, method) return request_by_method(url=url, data=data, auth=auth, cookies=cookies, headers=headers, proxies=proxies, timeout=timeout, verify=verify, allow_redirects=True, stream=Fal...
Execute a request with the given data. Args: url (str): The URL to call. method (str): The method (e.g. `get` or `post`). data (str): The data to call the URL with. auth (obj): The authentication class. cookies (obj): The cookie dict. headers (obj): The header dict. proxies (obj): The proxies dict. timeout (int): The ...
codesearchnet
def is_layouts_same(self, embedding_layouts) -> bool: if self._checkpoint_layouts.keys() != embedding_layouts.keys(): raise ValueError('Layouts in checkpoint and embedding must have the same keys. found {} and {}'.format(self._checkpoint_layouts.keys(), embedding_layouts.keys())) for key, layout in self...
Returns True if the all the embedding and checkpoint layouts are the same. Args: embedding_layouts: dict of layouts for embedding tables. Raises: ValueError if the embedding layouts and checkpoint layouts do not have the same keys. Returns: Bool representing if the embedding layouts match the layouts in checkpoint.
github-repos
def VerifyCipherSignature(self, remote_public_key): if (self.cipher_metadata.signature and remote_public_key): stats_collector_instance.Get().IncrementCounter('grr_rsa_operations') remote_public_key.Verify(self.serialized_cipher, self.cipher_metadata.signature) return True
Verifies the signature on the encrypted cipher block. This method returns True if the signature verifies correctly with the key given. Args: remote_public_key: The remote public key. Returns: None Raises: rdf_crypto.VerificationError: A signature and a key were both given but verification fails.
codesearchnet
def emit_completion(self, completion_percent): completion_mode = XBlockCompletionMode.get_mode(self) if not self.has_custom_completion or completion_mode != XBlockCompletionMode.COMPLETABLE: raise AttributeError( "Using `emit_completion` requires `has_custom_completi...
Emits completion event through Completion API. Unlike grading API, calling this method allows completion to go down - i.e. emitting a value of 0.0 on a previously completed block indicates that it is no longer considered complete. Arguments: completion_percent (float): Completion in range [0.0; 1.0] (inclusive), wher...
juraj-google-style
def filter(self, items=None, like=None, regex=None, axis=None): nkw = count_not_none(items, like, regex) if nkw > 1: raise TypeError( "Keyword arguments `items`, `like`, or `regex` are mutually exclusive" ) if nkw == 0: raise TypeError...
Subset rows or columns based on their labels Args: items (list): list of labels to subset like (string): retain labels where `arg in label == True` regex (string): retain labels matching regex input axis: axis to filter on Returns: A new DataFrame with the filter applied.
juraj-google-style
def from_dict(d: Dict[(str, Any)]) -> 'CoverageInstructions': name_type = d['type'] cls = _NAME_TO_INSTRUCTIONS[name_type] return cls.from_dict(d)
Loads a set of coverage instructions from a given dictionary. Raises: BadCoverageInstructions: if the given coverage instructions are illegal.
codesearchnet
def set_python_graph(self, python_graph): self._python_graph = python_graph self._node_traceback = {} if self._python_graph: for op in self._python_graph.get_operations(): self._node_traceback[op.name] = tuple(map(tuple, op.traceback))
Provide Python `Graph` object to the wrapper. Unlike the partition graphs, which are protobuf `GraphDef` objects, `Graph` is a Python object and carries additional information such as the traceback of the construction of the nodes in the graph. Args: python_graph: (ops.Graph) The Python Graph object.
github-repos
def load_from_dict(self, conf_dict=None): self.set_to_default() self._update_dict(self._config, conf_dict) self._update_python_paths()
Load the configuration from a dictionary. Args: conf_dict (dict): Dictionary with the configuration.
juraj-google-style
def __init__(self, pb_id): SchedulingObject.__init__(self, PB_KEY, pb_id) self._check_object_exists()
Create a PB object. Args: pb_id (str): Processing Block Identifier Raises: KeyError, if the specified PB does not exist
juraj-google-style
def list_file_extensions(path: str, reportevery: int = 1) -> List[str]: extensions = set() count = 0 for root, dirs, files in os.walk(path): count += 1 if count % reportevery == 0: log.debug("Walking directory {}: {!r}", count, root) for file in files: fi...
Returns a sorted list of every file extension found in a directory and its subdirectories. Args: path: path to scan reportevery: report directory progress after every *n* steps Returns: sorted list of every file extension found
juraj-google-style
def populate_settings_dir(force: bool=False) -> bool: res = False if (_default_settings_path == _settings_path): return res for src in list(_default_settings_path.glob('**/*.json')): dest = (_settings_path / src.relative_to(_default_settings_path)) if ((not force) and dest.exists()):...
Populate settings directory with default settings files Args: force: if ``True``, replace existing settings files with default ones Returns: ``True`` if any files were copied and ``False`` otherwise
codesearchnet
def __call__(self, text): text = remove(text, string.punctuation) words = text.split() invalid_words = list(filter(lambda word: word and word.lower() not in self.words, words)) return len(invalid_words) * self.floor
Score based on number of words not in the corpus. Example: >>> fitness = Corpus(["example"]) >>> fitness("example") 0 >>> fitness("different") -2.0 Args: text (str): The text to score Returns: Corpus score for text
juraj-google-style
def simulate_values(cls, num_events, lr_scheduler, **kwargs): copy_lr_scheduler = LRScheduler._replicate_lr_scheduler(lr_scheduler) values = [] scheduler = cls(save_history=False, lr_scheduler=copy_lr_scheduler) for i in range(num_events): ...
Method to simulate scheduled values during num_events events. Args: num_events (int): number of events during the simulation. lr_scheduler (subclass of `torch.optim.lr_scheduler._LRScheduler`): lr_scheduler object to wrap. Returns: list of pairs: [event_index, value]
juraj-google-style
def __render_config_block(self, config_block): config_block_str = '' for line in config_block: if isinstance(line, config.Option): line_str = self.__render_option(line) elif isinstance(line, config.Config): line_str = self.__render_config(...
Summary Args: config_block [config.Item, ...]: config lines Returns: str: config block str
juraj-google-style
def LoadConfig(config_obj, config_file=None, config_fd=None, secondary_configs=None, contexts=None, reset=False, parser=ConfigFileParser): if ((config_obj is None) or reset): config_obj = _CONFIG.MakeNewConfig() if (config_file is not None): config_obj.Initialize(filename=config_file, must_exist...
Initialize a ConfigManager with the specified options. Args: config_obj: The ConfigManager object to use and update. If None, one will be created. config_file: Filename to read the config from. config_fd: A file-like object to read config data from. secondary_configs: A list of secondary config URLs to load. contexts:...
codesearchnet
def cancel(batch_fn, cancel_fn, ops): canceled_ops = [] error_messages = [] max_batch = 256 total_ops = len(ops) for first_op in range(0, total_ops, max_batch): batch_canceled, batch_messages = _cancel_batch( batch_fn, cancel_fn, ops[first_op:first_op + max_batch]) canceled_ops....
Cancel operations. Args: batch_fn: API-specific batch function. cancel_fn: API-specific cancel function. ops: A list of operations to cancel. Returns: A list of operations canceled and a list of error messages.
juraj-google-style
def add_range_headers(self, range_header): self['Accept-Ranges'] = 'bytes' size = self.ranged_file.size try: ranges = self.ranged_file.parse_range_header(range_header, size) except ValueError: ranges = None if ranges is not None ...
Adds several headers that are necessary for a streaming file response, in order for Safari to play audio files. Also sets the HTTP status_code to 206 (partial content). Args: range_header (str): Browser HTTP_RANGE request header.
juraj-google-style
def clause(self, *args, **kwargs): if (args and isinstance(args[0], Clause)): clause = args[0] else: clause = Clause(*args, **kwargs) if (not clause.fields): clause.fields = self.all_fields if ((clause.wildcard & Query.WILDCARD_LEADING) and (clause.term[0] != Query.WILDCARD)): ...
Adds a `lunr.Clause` to this query. Unless the clause contains the fields to be matched all fields will be matched. In addition a default boost of 1 is applied to the clause. If the first argument is a `lunr.Clause` it will be mutated and added, otherwise args and kwargs will be used in the constructor. Returns: lun...
codesearchnet
def serialize_to_nested(self, name, datas): keys = datas.get('keys', None) splitter = datas.get('splitter', self._DEFAULT_SPLITTER) if not keys: msg = ("Nested reference '{}' lacks of required 'keys' variable " "or is empty") raise SerializerE...
Serialize given datas to a nested structure where each key create an item and each other variable is stored as a subitem with corresponding value (according to key index position). Arguments: name (string): Name only used inside possible exception message. datas (dict): Datas to serialize. Returns: dict: Nested dicti...
juraj-google-style
def merge_default_values(resource_list, default_values): def merge_item(resource): return merge_resources(default_values, resource) return lmap(merge_item, resource_list)
Generate a new list where each item of original resource_list will be merged with the default_values. Args: resource_list: list with items to be merged default_values: properties to be merged with each item list. If the item already contains some property the original value will be maintained. Returns: list: list con...
juraj-google-style
def get_iterator_spec_from_dataset(strategy, dataset): output_element_spec = dataset.element_spec if isinstance(dataset._type_spec, (DistributedDatasetSpec, DistributedDatasetsFromFunctionSpec)): iterator_type_spec = DistributedIteratorSpec(strategy.extended._input_workers_with_options(), output_element...
Returns an iterator spec from dataset function. This function constructs type spec for iterator obtained from iter(dataset). Args: strategy: a `tf.distribute.Strategy` object, used to run all-reduce to handle last partial batch. dataset: A tf.data.Dataset instance. If using a function that returns a tf.data.Dataset i...
github-repos
def run(self, dag): coupling_map = self._coupling_map ordered_virtual_gates = list(dag.serial_layers()) if self.initial_layout is None: if self.property_set["layout"]: self.initial_layout = self.property_set["layout"] else: self.i...
Run one pass of the lookahead mapper on the provided DAG. Args: dag (DAGCircuit): the directed acyclic graph to be mapped Returns: DAGCircuit: A dag mapped to be compatible with the coupling_map in the property_set. Raises: TranspilerError: if the coupling map or the layout are not compatible with the DAG
juraj-google-style
def merge_sketches(outdir, sketch_paths): merge_sketch_path = os.path.join(outdir, 'sistr.msh') args = ['mash', 'paste', merge_sketch_path] for x in sketch_paths: args.append(x) args.append(MASH_SKETCH_FILE) logging.info('Running Mash paste with command: %s', ' '.join(args)) p = Pop...
Merge new Mash sketches with current Mash sketches Args: outdir (str): output directory to write merged Mash sketch file sketch_paths (list of str): Mash sketch file paths for input fasta files Returns: str: output path for Mash sketch file with new and old sketches
juraj-google-style
def get_typed_value_descriptor(obj): if isinstance(obj, (bytes, str)): type_name = 'Text' elif isinstance(obj, bool): type_name = 'Boolean' elif isinstance(obj, int): type_name = 'Integer' elif isinstance(obj, float): type_name = 'Float' else: raise TypeError(...
For internal use only; no backwards-compatibility guarantees. Converts a basic type into a @type/value dictionary. Args: obj: A bytes, unicode, bool, int, or float to be converted. Returns: A dictionary containing the keys ``@type`` and ``value`` with the value for the ``@type`` of appropriate type. Raises: TypeErr...
github-repos
def _RegisterDebuggee(self, service): try: request = {'debuggee': self._GetDebuggee()} try: response = service.debuggees().register(body=request).execute() project_number = response['debuggee'].get('project') self._project_number = proje...
Single attempt to register the debuggee. If the registration succeeds, sets self._debuggee_id to the registered debuggee ID. Args: service: client to use for API calls Returns: (registration_required, delay) tuple
juraj-google-style
def var(x, axis=None, keepdims=False): if any_symbolic_tensors((x,)): return Var(axis=axis, keepdims=keepdims).symbolic_call(x) return backend.numpy.var(x, axis=axis, keepdims=keepdims)
Compute the variance along the specified axes. Args: x: Input tensor. axis: Axis or axes along which the variance is computed. The default is to compute the variance of the flattened tensor. keepdims: If this is set to `True`, the axes which are reduced are left in the result as dimensions with size one. Returns: Out...
github-repos
def route(self, dst=None, verbose=conf.verb): dst = dst or "0.0.0.0" if isinstance(dst, bytes): try: dst = plain_str(dst) except UnicodeDecodeError: raise TypeError("Unknown IP address input (bytes)") if dst in self.cache: ...
Returns the IPv4 routes to a host. parameters: - dst: the IPv4 of the destination host returns: (iface, output_ip, gateway_ip) - iface: the interface used to connect to the host - output_ip: the outgoing IP that will be used - gateway_ip: the gateway IP that will be used
juraj-google-style
def _time_delta_from_info(info): delta_seconds = (int(time.time()) - info.start_time) return str(datetime.timedelta(seconds=delta_seconds))
Format the elapsed time for the given TensorBoardInfo. Args: info: A TensorBoardInfo value. Returns: A human-readable string describing the time since the server described by `info` started: e.g., "2 days, 0:48:58".
codesearchnet
def union(self, *others): result = self.__copy__() _elements = result._elements _total = result._total for other in map(self._as_mapping, others): for (element, multiplicity) in other.items(): old_multiplicity = _elements.get(element, 0) if (multiplicity > old_multiplicit...
r"""Return a new multiset with all elements from the multiset and the others with maximal multiplicities. >>> ms = Multiset('aab') >>> sorted(ms.union('bc')) ['a', 'a', 'b', 'c'] You can also use the ``|`` operator for the same effect. However, the operator version will only accept a set as other operator, not any it...
codesearchnet
def restructure(modality_sizes: ModalitySizeType, inputs: torch.Tensor) -> Mapping[str, torch.Tensor]: outputs = {} index = 0 for modality in sorted(modality_sizes.keys()): size = modality_sizes[modality] inp = inputs[:, index:index + size] index += size outputs[modality] = i...
Partitions a [B, N, C] tensor into tensors for each modality. Args: modality_sizes dict specifying the size of the modality inputs: input tensor Returns: dict mapping name of modality to its associated tensor.
github-repos
def test_error(self, e=None): self._test_end(TestResultEnums.TEST_RESULT_ERROR, e)
To mark the test as error in this record. Args: e: An exception object.
github-repos
def has_event_handler(self, handler, event_name=None): if event_name is not None: if event_name not in self._event_handlers: return False events = [event_name] else: events = self._event_handlers for e in events: for h, _, ...
Check if the specified event has the specified handler. Args: handler (callable): the callable event handler. event_name: The event the handler attached to. Set this to ``None`` to search all events.
juraj-google-style
def get_value(self, field, quick): if callable(field.default): default = field.default(self) else: default = field.default if (quick and (default is not None)): return default shell.cprint('<90>{}', field.help) while True: try: answer = click.prompt(field....
Ask user the question represented by this instance. Args: field (Field): The field we're asking the user to provide the value for. quick (bool): Enable quick mode. In quick mode, the form will reduce the number of question asked by using defaults wherever possible. This can greatly reduce the number of interactions re...
codesearchnet
def with_env_recursive(cmd, **envvars): from plumbum.commands.base import BoundCommand, BoundEnvCommand if isinstance(cmd, BoundCommand): cmd.cmd = with_env_recursive(cmd.cmd, **envvars) elif isinstance(cmd, BoundEnvCommand): cmd.envvars.update(envvars) cmd.cmd = with_env_recurs...
Recursively updates the environment of cmd and all its subcommands. Args: cmd - A plumbum command-like object **envvars - The environment variables to update Returns: The updated command.
juraj-google-style
def prepare_headers(headers: list[str], srcs_dir: str) -> None: path_to_exclude = ['cuda_cccl/_virtual_includes', 'cuda_cublas/_virtual_includes', 'cuda_cudart/_virtual_includes', 'cuda_cudnn/_virtual_includes', 'cuda_cufft/_virtual_includes', 'cuda_cupti/_virtual_includes', 'cuda_curand/_virtual_includes', 'cuda_c...
Copy and rearrange header files in the target directory. Filter out headers by their path and replace paths for some of them. Args: headers: a list of paths to header files. srcs_dir: target directory where headers are copied to.
github-repos
def make_config_get(conf_path): project_root = _get_project_root_from_conf_path(conf_path) config = load_config_in_dir(project_root) return partial(config_get, config)
Return a function to get configuration options for a specific project Args: conf_path (path-like): path to project's conf file (i.e. foo.conf module)
juraj-google-style
def verify(self, obj): if not isinstance(obj, bool): raise ValidationError("Object is not a bool", reason='object is not a bool', object=obj) if self._require_value is not None and obj != self._require_value: raise ValidationError("Boolean is not equal to specified lit...
Verify that the object conforms to this verifier's schema Args: obj (object): A python object to verify Raises: ValidationError: If there is a problem verifying the dictionary, a ValidationError is thrown with at least the reason key set indicating the reason for the lack of validation.
juraj-google-style
def neighborhood_probability(self, threshold, radius): weights = disk(radius, dtype=np.uint8) thresh_data = np.zeros(self.data.shape[1:], dtype=np.uint8) neighbor_prob = np.zeros(self.data.shape, dtype=np.float32) for t in np.arange(self.data.shape[0]): thresh_data[(self.data[t] >= threshold)] =...
Calculate a probability based on the number of grid points in an area that exceed a threshold. Args: threshold: radius: Returns:
codesearchnet
def remove_feature(feature, remove_payload=False, image=None, restart=False): cmd = ['DISM', '/Quiet', ('/Image:{0}'.format(image) if image else '/Online'), '/Disable-Feature', '/FeatureName:{0}'.format(feature)] if remove_payload: cmd.append('/Remove') if (not restart): cmd.append('/NoResta...
Disables the feature. Args: feature (str): The feature to uninstall remove_payload (Optional[bool]): Remove the feature's payload. Must supply source when enabling in the future. image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targ...
codesearchnet
def log_estimator_evaluation_result(self, eval_results): if not isinstance(eval_results, dict): tf.logging.warning("eval_results should be directory for logging. Got %s", type(eval_results)) return global_step = eval_results[tf.GraphKeys.GLOBAL_STEP] for key in sort...
Log the evaluation result for a estimator. The evaluate result is a directory that contains metrics defined in model_fn. It also contains a entry for global_step which contains the value of the global step when evaluation was performed. Args: eval_results: dict, the result of evaluate() from a estimator.
juraj-google-style
def shift(self, time: int) -> 'Timeslot': return Timeslot(self.interval.shift(time), self.channel)
Return a new Timeslot shifted by `time`. Args: time: time to be shifted
juraj-google-style
def _WriteData(self, target, entry): sshkey_entry = '%s:%s' % (entry.name, entry.sshkey) target.write(sshkey_entry.encode() + b'\n') return len(sshkey_entry) + 1
Write a SshekeyMapEntry to the target cache. Args: target: A file-like object. entry: A SshkeyMapEntry. Returns: Number of bytes written to the target.
github-repos
def default_get_arg_names_from_class_name(class_name): parts = [] rest = class_name if rest.startswith('_'): rest = rest[1:] while True: m = re.match(r'([A-Z][a-z]+)(.*)', rest) if m is None: break parts.append(m.group(1)) rest = m.group(2) if...
Converts normal class names into normal arg names. Normal class names are assumed to be CamelCase with an optional leading underscore. Normal arg names are assumed to be lower_with_underscores. Args: class_name: a class name, e.g., "FooBar" or "_FooBar" Returns: all likely corresponding arg names, e.g., ["foo_bar"]
juraj-google-style
def remove(path, follow_symlink=False): if os.path.isfile(path): os.remove(path) elif os.path.islink(path): if follow_symlink: remove(os.readlink(path)) os.unlink(path) else: shutil.rmtree(path)
Implements an remove function that will delete files, folder trees and symlink trees 1.) Remove a file 2.) Remove a symlink and follow into with a recursive rm if follow_symlink 3.) Remove directory with rmtree Args: path (str): path to remove follow_symlink(bool): follow symlinks and removes whatever is in them
codesearchnet
def convert(self, calibration_inputs=None, num_runs=1) -> None: for trt_model in self._trt_models: trt_model.convert(calibration_inputs, num_runs)
Converts models with TensorRT and calibrates if using INT8 precision mode. Args: calibration_inputs: Mapping from input names to ndarrays in TF1. Or a sequence of tensors in TF2. Used as calibration data. num_runs: Number of calibration runs.
github-repos
def segment(self, text): files = {'text': text} res, status_code = self.post(self.segmentation_service, files=files) if status_code != 200: logger.debug('Segmentation failed.') return self.decode(res), status_code
Call the segmenter in order to split text in sentences. Args: text (str): Text to be segmented. Returns: dict, int: A dict containing a list of dicts with the offsets of each sentence; an integer representing the response code.
juraj-google-style
def DeregisterFormatter(cls, formatter_class): formatter_data_type = formatter_class.DATA_TYPE.lower() if (formatter_data_type not in cls._formatter_classes): raise KeyError('Formatter class not set for data type: {0:s}.'.format(formatter_class.DATA_TYPE)) del cls._formatter_classes[formatter_data_t...
Deregisters a formatter class. The formatter classes are identified based on their lower case data type. Args: formatter_class (type): class of the formatter. Raises: KeyError: if formatter class is not set for the corresponding data type.
codesearchnet
def __init__(self, sess): self._sess = sess self._wrapped_is_stoppable = isinstance(self._sess, _WrappedSession)
Creates a `_WrappedSession`. Args: sess: A `tf.compat.v1.Session` or `_WrappedSession` object. The wrapped session.
github-repos
def _ass_refresh_attrs(self, cached_ass, file_ass): loaded_ass = yaml_loader.YamlLoader.load_yaml_by_path(file_ass['source'], log_debug=True) attrs = loaded_ass yaml_checker.check(file_ass['source'], attrs) cached_ass['source'] = file_ass['source'] cached_ass['ctime'] = os.path.getctime(file_ass['so...
Completely refreshes cached assistant from file. Args: cached_ass: an assistant from cache hierarchy (for format see Cache class docstring) file_ass: the respective assistant from filesystem hierarchy (for format see what refresh_role accepts)
codesearchnet
def energies(self, samples_like, dtype=np.float): (samples, labels) = as_samples(samples_like) if labels: (idx, label) = zip(*enumerate(labels)) labeldict = dict(zip(label, idx)) else: labeldict = {} num_samples = samples.shape[0] energies = np.zeros(num_samples, dtype=dtype)...
The energies of the given samples. Args: samples_like (samples_like): A collection of raw samples. `samples_like` is an extension of NumPy's array_like structure. See :func:`.as_samples`. dtype (:class:`numpy.dtype`, optional): The data type of the returned energies. Defaults to float. Returns: :obj:`numpy.ndarray`:...
codesearchnet
def nmf_ensemble(data, k, n_runs=10, W_list=[], **nmf_params): nmf = NMF(k) if len(W_list)==0: W_list = [] for i in range(n_runs): W = nmf.fit_transform(data) W_list.append(W) W_stacked = np.hstack(W_list) nmf_w = nmf.fit_transform(W_stacked) nmf_h = nmf....
Runs an ensemble method on the list of NMF W matrices... Args: data: genes x cells array (should be log + cell-normalized) k: number of classes n_runs (optional): number of random initializations of state estimation M_list (optional): list of M arrays from state estimation se_params (optional): optional poisson_estima...
juraj-google-style
def delete(self, paths): exceptions = {} for path in paths: if path.endswith('/'): self._gcsIO().delete(path, recursive=True) continue else: path_to_use = path match_result = self.match([path_to_use])[0] statuses = self._gcsIO().delete_batch([m...
Deletes files or directories at the provided paths. Directories will be deleted recursively. Args: paths: list of paths that give the file objects to be deleted
github-repos
def convert_idx_to_name(self, y, lens): y = [[self.id2label[idx] for idx in row[:l]] for (row, l) in zip(y, lens)] return y
Convert label index to name. Args: y (list): label index list. lens (list): true length of y. Returns: y: label name list. Examples: >>> # assumes that id2label = {1: 'B-LOC', 2: 'I-LOC'} >>> y = [[1, 0, 0], [1, 2, 0], [1, 1, 1]] >>> lens = [1, 2, 3] >>> self.convert_idx_to_name(y, lens) [['B-LOC'], ['B-LOC', 'I-LOC...
codesearchnet
def _FormatSubjectExOrProcessExToken(self, token_data): if token_data.net_type == 4: ip_address = self._FormatPackedIPv4Address(token_data.ip_address) elif token_data.net_type == 16: ip_address = self._FormatPackedIPv6Address(token_data.ip_address) else: ip_address = 'unknown' re...
Formats a subject or process token as a dictionary of values. Args: token_data (bsm_token_data_subject32_ex|bsm_token_data_subject64_ex): AUT_SUBJECT32_EX, AUT_PROCESS32_EX, AUT_SUBJECT64_EX or AUT_PROCESS64_EX token data. Returns: dict[str, str]: token values.
juraj-google-style
def with_dependencies(dependencies, output_tensor, name=None): if tf.executing_eagerly(): return output_tensor with tf.name_scope((name or 'control_dependency')) as name: with tf.control_dependencies((d for d in dependencies if (d is not None))): output_tensor = tf.convert_to_tensor(...
Produces the content of `output_tensor` only after `dependencies`. In some cases, a user may want the output of an operation to be consumed externally only after some other dependencies have run first. This function returns `output_tensor`, but only after all operations in `dependencies` have run. Note that this means...
codesearchnet
def parse_arguments(argv): parser = argparse.ArgumentParser( description='Runs Prediction inside a beam or Dataflow job.') parser.add_argument('--project-id', help='The project to which the job will be submitted.') parser.add_argument('--cloud', action='stor...
Parse command line arguments. Args: argv: includes the script's name. Returns: argparse object
juraj-google-style
def _get_dict_of_block_index(self, axis, indices, ordered=False): all_partitions_and_idx = [self._get_blocks_containing_index(axis, i) for i in indices] if ordered: partitions_dict = [] last_part = (- 1) for (part_idx, internal_idx) in all_partitions_and_idx: if (part_idx == ...
Convert indices to a dict of block index to internal index mapping. Note: See `_get_blocks_containing_index` for primary usage. This method accepts a list of indices rather than just a single value, and uses `_get_blocks_containing_index`. Args: axis: The axis along which to get the indices (0 - columns, 1 - rows) in...
codesearchnet
def _configure_common(self, prefix, fallback_level, fallback_format, handler_name, handler, custom_args=''): log_level = self.config.get_option('LOGGING', (prefix + 'log_level'), None, fallback_level) log_format_name = self.config.get_option('LOGGING', (prefix + 'log_format'), None, None) log_format = (Repo...
commom configuration code Args: prefix (str): A prefix for the `log_level` and `log_format` keys to use with the config. #FIXME: Hacky, add separate sections for each logger config? fallback_level (str): Fallback/minimum log level, for if config does not have one. fallback_format (str): Fallback format for if it's not...
codesearchnet
def set_speech_ssml(self, ssml): self.response.outputSpeech.type = 'SSML' self.response.outputSpeech.ssml = ssml
Set response output speech as SSML type. Args: ssml: str. Response speech used when type is 'SSML', should be formatted with Speech Synthesis Markup Language. Cannot exceed 8,000 characters.
codesearchnet
def chosen_probabs(probab_observations, actions): (B, T) = actions.shape assert ((B, (T + 1)) == probab_observations.shape[:2]) return probab_observations[(np.arange(B)[(:, None)], np.arange(T), actions)]
Picks out the probabilities of the actions along batch and time-steps. Args: probab_observations: ndarray of shape `[B, T+1, A]`, where probab_observations[b, t, i] contains the log-probability of action = i at the t^th time-step in the b^th trajectory. actions: ndarray of shape `[B, T]`, with each entry in [0, A) den...
codesearchnet
def sendto(self, transport, addr): msg = bytes(self) + b'\r\n' logger.debug("%s:%s < %s", *(addr + (self,))) transport.sendto(msg, addr)
Send request to a given address via given transport. Args: transport (asyncio.DatagramTransport): Write transport to send the message on. addr (Tuple[str, int]): IP address and port pair to send the message to.
juraj-google-style
def zip(self, second_iterable, result_selector=(lambda x, y: (x, y))): if self.closed(): raise ValueError('Attempt to call zip() on a closed Queryable.') if (not is_iterable(second_iterable)): raise TypeError('Cannot compute zip() with second_iterable of non-iterable {0}'.format(str(type(second_...
Elementwise combination of two sequences. The source sequence and the second iterable are merged element-by- element using a function to combine them into the single corresponding element of the result sequence. The length of the result sequence is equal to the length of the shorter of the two input sequences. Note: ...
codesearchnet
def _ReadSources(self, artifact_definition_values, artifact_definition, name): sources = artifact_definition_values.get('sources') if not sources: raise errors.FormatError( 'Invalid artifact definition: {0:s} missing sources.'.format(name)) for source in sources: type_indicator =...
Reads the artifact definition sources. Args: artifact_definition_values (dict[str, object]): artifact definition values. artifact_definition (ArtifactDefinition): an artifact definition. name (str): name of the artifact definition. Raises: FormatError: if the type indicator is not set or unsupported, or if required a...
juraj-google-style
def my_sum(x, y, *args, **kwargs): del args, kwargs return x + y
Returns the sum of two integers. This function will return the sum of two integers. Examples: ``` ret = sum(1, 2) print(ret) ``` Args: x: An integer. y: Another integer. *args: Variable positional args. **kwargs: Variable keyword args. Returns: The sum of both. Raises: ValueError: when either `x` and `y` is not a...
github-repos
def __init__(self, options): self.event = Event.create(__name__) self.options = options self.logging_level = logging.DEBUG self.setup_logging() self.logger = Logger.get_logger(__name__)
Initialize application with command line options. Args: options (ApplicationOptions): given command line options.
juraj-google-style
def sentencecase(string): joiner = ' ' string = re.sub('[\\-_\\.\\s]', joiner, str(string)) if (not string): return string return capitalcase(trimcase(re.sub('[A-Z]', (lambda matched: (joiner + lowercase(matched.group(0)))), string)))
Convert string into sentence case. First letter capped and each punctuations are joined with space. Args: string: String to convert. Returns: string: Sentence cased string.
codesearchnet
def __init__(self, dsn, echo=False, foreign_keys=True, engine_kwargs=None, application_prefix='ambry'): self.dsn = dsn d = parse_url_to_dict(self.dsn) self.path = d['path'].replace(' self.driver = d['scheme'] self.engine_kwargs = engine_kwargs or {} self.Sess...
Initializes database. Args: dsn (str): database connect string, 'sqlite://' for example. echo (boolean): echo parameter of the create_engine. engine_kwargs (dict): parameters to pass to the create_engine method of the Sqlalchemy.
juraj-google-style
def move(self, delta): pos = self.pos self.pos = ((pos[0] + delta[0]), (pos[1] + delta[1]), (pos[2] + delta[0]), (pos[3] + delta[1])) for age in self.nodes: for node in age: node.move(delta)
Move the tree. Args: delta (tupel): The adjustment of the position.
codesearchnet
def check_rank(player, platform="steam"): webpage = requests.get( "https: ).text try: playerid_index = webpage.index("/live?ids=") + len("/live?ids=") playerid_end_index = webpage.index(, playerid_index) playerid = webpage[playerid_index:playerid_end_inde...
Gets the Rocket League stats and name and dp of a UserID Args: player (str): The UserID of the player we want to rank check platform (str): The platform to check for, can be 'steam', 'ps', or 'xbox' Returns: success (bool): Whether the rank check was successful package (tuple): If successful, the retrieved stats, in ...
juraj-google-style