code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def reverse_transform(self, col): output = pd.DataFrame() new_name = '?' + self.col_name col.loc[col[new_name] == 0, self.col_name] = np.nan output[self.col_name] = col[self.col_name] return output
Converts data back into original format. Args: col(pandas.DataFrame): Data to transform. Returns: pandas.DataFrame
juraj-google-style
def call(self, input_ids=None, position_ids=None, token_type_ids=None, inputs_embeds=None, training=False): assert not (input_ids is None and inputs_embeds is None) if input_ids is not None: check_embeddings_within_bounds(input_ids, self.config.vocab_size) inputs_embeds = tf.gather(params=self.w...
Applies embedding based on inputs tensor. Returns: final_embeddings (`tf.Tensor`): output embedding tensor.
github-repos
def __init__(self, window, index=-1, flags=frozenset()): self._ptr = check_ptr_err(lib.SDL_CreateRenderer(window._ptr, index, enumtools.get_mask(flags)))
Create a 2D rendering context for a window. Args: window (Window): The window where rendering is displayed. index (int): The index of the rendering driver to initialize, or -1 to initialize the first one supporting the requested flags. flags (Set[RendererFlags]): The requested renderer flags. Raises: SDLError: If the...
juraj-google-style
def get_size_ratio(path_a: str, path_b: str) -> float: size_a = get_dir_size(path_a) size_b = get_dir_size(path_b) return size_a / size_b
Return the size ratio of the given paths. Args: path_a: Path of a directory or a file to be the nominator of the ratio. path_b: Path of a directory or a file to be the denominator of the ratio. Returns: Ratio of size of path_a / size of path_b.
github-repos
def GetArtifactsForCollection(os_name, artifact_list): artifact_arranger = ArtifactArranger(os_name, artifact_list) artifact_names = artifact_arranger.GetArtifactsInProperOrder() return artifact_names
Wrapper for the ArtifactArranger. Extend the artifact list by dependencies and sort the artifacts to resolve the dependencies. Args: os_name: String specifying the OS name. artifact_list: List of requested artifact names. Returns: A list of artifacts such that if they are collected in the given order their dependenc...
codesearchnet
def download_mmcif_header(pdb_id, outdir='', force_rerun=False): pdb_id = pdb_id.lower() file_type = 'cif' folder = 'header' outfile = op.join(outdir, '{}.header.{}'.format(pdb_id, file_type)) if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile): download_link = 'http: urlre...
Download a mmCIF header file from the RCSB PDB by ID. Args: pdb_id: PDB ID outdir: Optional output directory, default is current working directory force_rerun: If the file should be downloaded again even if it exists Returns: str: Path to outfile
codesearchnet
def from_hubo(cls, H, offset=None): poly = cls(H, Vartype.BINARY) if offset is not None: poly[()] = poly.get((), 0) + offset return poly
Construct a binary polynomial from a higher-order unconstrained binary optimization (HUBO) problem. Args: H (dict): Coefficients of a higher-order unconstrained binary optimization (HUBO) model. Returns: :obj:`.BinaryPolynomial` Examples: >>> poly = dimod.BinaryPolynomial.from_hubo({('a', 'b', 'c'): -1})
juraj-google-style
def _maybe_broadcast_to_outputs(self, outputs, objects): if not self._should_broadcast(objects): return objects should_copy_objects = len(nest.flatten(outputs)) > 1 def _broadcast_fn(): if should_copy_objects: return nest.map_structure(self._copy_object, objects) return ...
Determines if losses / metrics should be applied to all outputs. NOTE: This method should only be called for Metrics / Losses, not for y_true / sample_weight. Args: outputs: Model predictions. objects: Arbitrary nested structure (e.g. of losses or metrics) Returns: Arbitrary nested structure of objects, maybe copied...
github-repos
def _ip_unnumbered_name(self, **kwargs): method_name = 'interface_%s_ip_ip_config_unnumbered_ip_donor_'\ 'interface_name' % kwargs['int_type'] ip_unnumbered_name = getattr(self._interface, method_name) config = ip_unnumbered_name(**kwargs) if kwargs['delete']: ...
Return the `ip unnumbered` donor name XML. You should not use this method. You probably want `Interface.ip_unnumbered`. Args: int_type (str): Type of interface. (gigabitethernet, tengigabitethernet etc). delete (bool): Remove the configuration if ``True``. ip_donor_interface_name (str): The donor interface name (1, 2...
juraj-google-style
def get_model_details(self, model_name): full_name = model_name if not model_name.startswith('projects/'): full_name = ('projects/%s/models/%s' % (self._project_id, model_name)) return self._api.projects().models().get(name=full_name).execute()
Get details of the specified model from CloudML Service. Args: model_name: the name of the model. It can be a model full name ("projects/[project_id]/models/[model_name]") or just [model_name]. Returns: a dictionary of the model details.
juraj-google-style
def change_password(username, new_password): assert username in passwd_reader.load_users(),\ "Username '%s' not found!" % username sh.ftpasswd( "--change-password", passwd=True, name=username, stdin=True, file=settings.LOGIN_FILE, ...
Change password for given `username`. Args: username (str): User's name. new_password (str): User's new password.
juraj-google-style
def inverse(self): if (not self.definition): raise QiskitError(('inverse() not implemented for %s.' % self.name)) inverse_gate = self.copy(name=(self.name + '_dg')) inverse_gate._definition = [] for (inst, qargs, cargs) in reversed(self._definition): inverse_gate._definition.append((inst...
Invert this instruction. If the instruction is composite (i.e. has a definition), then its definition will be recursively inverted. Special instructions inheriting from Instruction can implement their own inverse (e.g. T and Tdg, Barrier, etc.) Returns: Instruction: a fresh instruction for the inverse Raises: Qiski...
codesearchnet
def patch_request(self, uri, body, custom_headers=None, timeout=-1): logger.debug('Patch resource (uri = %s, data = %s)' % (uri, body)) if not custom_headers: custom_headers = {} if self._connection._apiVersion >= 300 and 'Content-Type' not in custom_headers: c...
Uses the PATCH to update a resource. Only one operation can be performed in each PATCH call. Args: body (list): Patch request body timeout (int): Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView; it just stops waiting for its completion. custom_headers (dict...
juraj-google-style
def __contains__(self, key): path = self.keypath(key) return fs.exists(path)
Check cache contents. Arguments: key: Key. Returns: bool: True if key in cache, else false.
juraj-google-style
class TFCvtEncoder(keras.layers.Layer): config_class = CvtConfig def __init__(self, config: CvtConfig, **kwargs): super().__init__(**kwargs) self.config = config self.stages = [TFCvtStage(config, stage_idx, name=f'stages.{stage_idx}') for stage_idx in range(len(config.depth))] def ...
Convolutional Vision Transformer encoder. CVT has 3 stages of encoder blocks with their respective number of layers (depth) being 1, 2 and 10. Args: config ([`CvtConfig`]): Model configuration class.
github-repos
def flatten(index, name='segmented_flatten'): batch_size = torch.prod(torch.tensor(list(index.batch_shape()))) offset = torch.arange(start=0, end=batch_size, device=index.num_segments.device) * index.num_segments offset = offset.view(index.batch_shape()) for _ in range(index.batch_dims, len(index.indice...
Flattens a batched index map (which is typically of shape batch_size, seq_length) to a 1d index map. This operation relabels the segments to keep batch elements distinct. The k-th batch element will have indices shifted by *num_segments* * (k - 1). The result is a tensor with *num_segments* multiplied by the number of ...
github-repos
def load_schema(schema_name, resolved=False): schema_data = '' with open(get_schema_path(schema_name, resolved)) as schema_fd: schema_data = json.loads(schema_fd.read()) return schema_data
Load the given schema from wherever it's installed. Args: schema_name(str): Name of the schema to load, for example 'authors'. resolved(bool): If True will return the resolved schema, that is with all the $refs replaced by their targets. Returns: dict: the schema with the given name.
juraj-google-style
async def inspect(self, *, node_id: str) -> Mapping[(str, Any)]: response = (await self.docker._query_json('nodes/{node_id}'.format(node_id=node_id), method='GET')) return response
Inspect a node Args: node_id: The ID or name of the node
codesearchnet
def run(self, text): for pp in self.pre_processors: text = pp.run(text) return text
Run each substitution on ``text``. Args: text (string): the input text. Returns: string: text after all substitutions have been sequentially applied.
codesearchnet
def test_rpc_stage_dependencies(self, mock_handle_resp, mock_decode_resp_str, mock_send_request, mock_gen_request, mock_precheck): self.client.initialize() expected_response_str = '{"id": 0, "result": 123, "error": null, "callback": null}' expected_response_dict = {'id': 0, 'result': 123, 'error': None, 'ca...
Test the internal dependencies when sending an RPC. When sending an RPC, it calls multiple functions in specific order, and each function uses the output of the previously called function. This test case checks above dependencies. Args: mock_handle_resp: the mock function of FakeClient._handle_rpc_response. mock_deco...
github-repos
def get_cluster_interfaces(cluster, extra_cond=lambda nic: True): nics = get_nics(cluster) nics = [(nic['device'], nic['name']) for nic in nics if nic['mountable'] and nic['interface'] == 'Ethernet' and not nic['management'] and ...
Get the network interfaces names corresponding to a criteria. Note that the cluster is passed (not the individual node names), thus it is assumed that all nodes in a cluster have the same interface names same configuration. In addition to ``extra_cond``, only the mountable and Ehernet interfaces are returned. Args: c...
juraj-google-style
def __instantiate_page_object(page_obj_class, webdriver, **kwargs): try: page = page_obj_class(webdriver, **kwargs) return page except InvalidPageError: return True except TypeError: retu...
Attempts to instantiate a page object. Args: page_obj_class (PageObject) - PageObject to instantiate. webdriver (WebDriver) - Selenium webdriver to associate with the PageObject Returns: PageObject - If page object instantiation succeeded. True - If page object instantiation failed, but validation was called. None - ...
juraj-google-style
def _is_molecule_linear(self, mol): if mol.NumAtoms() < 3: return True a1 = mol.GetAtom(1) a2 = mol.GetAtom(2) for i in range(3, mol.NumAtoms()+1): angle = float(mol.GetAtom(i).GetAngle(a2, a1)) if angle < 0.0: angle = -angle ...
Is the molecule a linear one Args: mol: The molecule. OpenBabel OBMol object. Returns: Boolean value.
juraj-google-style
def get(self, filter=False): result = {} for (k, v) in self.elements().items(): intermediate = v.get(filter=filter) if intermediate: result[k] = intermediate return result
Returns a dictionary with the values of the model. Note that the values of the leafs are YANG classes. Args: filter (bool): If set to ``True``, show only values that have been set. Returns: dict: A dictionary with the values of the model. Example: >>> pretty_print(config.get(filter=True)) >>> { >>> "interfaces"...
codesearchnet
async def report_winner(self, winner: Participant, scores_csv: str): await self._report(scores_csv, winner._id)
report scores and give a winner |methcoro| Args: winner: :class:Participant instance scores_csv: Comma separated set/game scores with player 1 score first (e.g. "1-3,3-0,3-2") Raises: ValueError: scores_csv has a wrong format APIException
juraj-google-style
def deserialize(segment): link_target = segment.link_data.link_target return ChatMessageSegment( segment.text, segment_type=segment.type, is_bold=segment.formatting.bold, is_italic=segment.formatting.italic, is_strikethrough=segment.formatting.str...
Construct :class:`ChatMessageSegment` from ``Segment`` message. Args: segment: ``Segment`` message to parse. Returns: :class:`ChatMessageSegment` object.
juraj-google-style
def _begin(self, retry_id=None): if self.in_progress: msg = _CANT_BEGIN.format(self._id) raise ValueError(msg) transaction_response = self._client._firestore_api.begin_transaction( self._client._database_string, options_=self._options_protobuf(re...
Begin the transaction. Args: retry_id (Optional[bytes]): Transaction ID of a transaction to be retried. Raises: ValueError: If the current transaction has already begun.
juraj-google-style
def _AvgPoolAlongCols(self, input_matrix, col_seq, overlapping): input_matrix = input_matrix.transpose() output_matrix = self._AvgPoolAlongRows(input_matrix, col_seq, overlapping) return output_matrix.transpose()
Perform average 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 _SetExtractionParsersAndPlugins(self, configuration, session): names_generator = parsers_manager.ParsersManager.GetParserAndPluginNames( parser_filter_expression=configuration.parser_filter_expression) session.enabled_parser_names = list(names_generator) session.parser_filter_expression = ...
Sets the parsers and plugins before extraction. Args: configuration (ProcessingConfiguration): processing configuration. session (Session): session.
juraj-google-style
def rebuild(cls, session, tree_id=None): trees = session.query(cls).filter_by(parent_id=None) if tree_id: trees = trees.filter_by(tree_id=tree_id) for tree in trees: cls.rebuild_tree(session, tree.tree_id)
This function rebuid tree. Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session Kwargs: tree_id (int or str): id of tree, default None Example: * :mod:`sqlalchemy_mptt.tests.TestTree.test_rebuild`
codesearchnet
def get_example_from_prop_spec(self, prop_spec, from_allof=False): easy_keys = ['example', 'x-example', 'default'] for key in easy_keys: if key in prop_spec.keys() and self.use_example: return prop_spec[key] if 'enum' in prop_spec.keys(): ...
Return an example value from a property specification. Args: prop_spec: the specification of the property. from_allof: whether these properties are part of an allOf section Returns: An example value
juraj-google-style
def __recognize_scalar(self, node: yaml.Node, expected_type: Type) -> RecResult: logger.debug('Recognizing as a scalar') if (isinstance(node, yaml.ScalarNode) and (node.tag == scalar_type_to_tag[expected_type])): return ([expected_type], '') message = 'Failed to recognize a {}\n{}\n'.format(type_to_...
Recognize a node that we expect to be a scalar. Args: node: The node to recognize. expected_type: The type it is expected to be. Returns: A list of recognized types and an error message
codesearchnet
def to_qasm(self, header: Optional[str]=None, precision: int=10, qubit_order: ops.QubitOrderOrList=ops.QubitOrder.DEFAULT) -> str: return str(self._to_qasm_output(header, precision, qubit_order))
Returns QASM equivalent to the circuit. Args: header: A multi-line string that is placed in a comment at the top of the QASM. Defaults to a cirq version specifier. precision: Number of digits to use when representing numbers. qubit_order: Determines how qubits are ordered in the QASM register.
codesearchnet
def VisitUnionType(self, union): intersection = self.hierarchy.ExpandSuperClasses(str(union.type_list[0])) for t in union.type_list[1:]: intersection.intersection_update(self.hierarchy.ExpandSuperClasses(str(t))) new_type_list = tuple((pytd.NamedType(cls) for cls in intersection if not self.hierarch...
Given a union type, try to find a simplification by using superclasses. This is a lossy optimization that tries to map a list of types to a common base type. For example, int and bool are both base classes of int, so it would convert "Union[int, bool]" to "int". Arguments: union: A union type. Returns: A simplified ...
github-repos
def __init__(self, vendor_identification=None, attribute_name=None): super(AttributeReference, self).__init__( tag=enums.Tags.ATTRIBUTE_REFERENCE ) self._vendor_identification = None self._attribute_name = None self.vendor_identification = vendor_identifica...
Construct an AttributeReference structure. Args: vendor_identification (string): A string identifying the vendor associated with the attribute. Optional, defaults to None. Required for read/write. attribute_name (string): A string containing the attribute name. Optional, defaults to None. Required for read/write.
juraj-google-style
def launch(self, workflow): try: r = self.gbdx_connection.post(self.workflows_url, json=workflow) try: r.raise_for_status() except: print(('GBDX API Status Code: %s' % r.status_code)) print(('GBDX API Response: %s' % r.text)) r.raise_for_status...
Launches GBDX workflow. Args: workflow (dict): Dictionary specifying workflow tasks. Returns: Workflow id (str).
codesearchnet
def DisjoinCalendars(self, cutoff): def TruncatePeriod(service_period, start, end): 'Truncate the service period to into the range [start, end].\n\n Args:\n service_period: The service period to truncate.\n start: The start date as a string in YYYYMMDD format.\n end: The end date ...
Forces the old and new calendars to be disjoint about a cutoff date. This truncates the service periods of the old schedule so that service stops one day before the given cutoff date and truncates the new schedule so that service only begins on the cutoff date. Args: cutoff: The cutoff date as a string in YYYYMMDD fo...
codesearchnet
def present_weather_codes(self, value=None): if (value is not None): try: value = int(value) except ValueError: raise ValueError('value {} need to be of type int for field `present_weather_codes`'.format(value)) self._present_weather_codes = value
Corresponds to IDD Field `present_weather_codes` Args: value (int): value for IDD Field `present_weather_codes` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
codesearchnet
def format_terminal_row(headers, example_row): def format_column(col): if isinstance(col, str): return '{{:{w}.{w}}}' return '{{:<{w}}}' widths = [max(len(h), len(str(d))) for h, d in zip(headers, example_row)] original_last_width = widths[-1] if sys.stdout.isatt...
Uses headers and a row of example data to generate a format string for printing a single row of data. Args: headers (tuple of strings): The headers for each column of data example_row (tuple): A representative tuple of strings or ints Returns string: A format string with a size for each column
juraj-google-style
def _begin_connection_action(self, action): connection_id = action.data['connection_id'] internal_id = action.data['internal_id'] callback = action.data['callback'] if self._get_connection_state(connection_id) != self.Disconnected: callback(connection_id, ...
Begin a connection attempt Args: action (ConnectionAction): the action object describing what we are connecting to
juraj-google-style
def make(target='all', dir='.', **kwargs): if (not fs.isfile(fs.path(dir, 'Makefile'))): raise NoMakefileError("No makefile in '{}'".format(fs.abspath(dir))) fs.cd(dir) if ('timeout' not in kwargs): kwargs['timeout'] = 300 (ret, out, err) = system.run(['make', target], **kwargs) fs.c...
Run make. Arguments: target (str, optional): Name of the target to build. Defaults to "all". dir (str, optional): Path to directory containing Makefile. **kwargs (optional): Any additional arguments to be passed to system.run(). Returns: (int, str, str): The first element is the return code of the make command. The...
codesearchnet
def __init__(self, callback, *args, interval=5): self.interval = interval self.cb_args = args self.callback = callback self._wake_up_time = time.time() + 1 self._kill_event = threading.Event() self._thread = threading.Thread(target=self._wake_up_timer, args=(se...
Initialize the flowcontrol object We start the timer thread here Args: - dfk (DataFlowKernel) : DFK object to track parsl progress KWargs: - threshold (int) : Tasks after which the callback is triggered - interval (int) : seconds after which timer expires
juraj-google-style
def least_squares_effective_mass(cartesian_k_points, eigenvalues): if (not points_are_in_a_straight_line(cartesian_k_points)): raise ValueError('k-points are not collinear') dk = (cartesian_k_points - cartesian_k_points[0]) mod_dk = np.linalg.norm(dk, axis=1) delta_e = (eigenvalues - eigenvalues...
Calculate the effective mass using a least squares quadratic fit. Args: cartesian_k_points (np.array): Cartesian reciprocal coordinates for the k-points eigenvalues (np.array): Energy eigenvalues at each k-point to be used in the fit. Returns: (float): The fitted effective mass Notes: If the k-points do not s...
codesearchnet
def _broadcast_dynamic_shape_one_layer(a, b): a_0 = a[0] b_0 = b[0] def broadcast_from_a(): a_layer = array_ops.zeros(b_0, dtype=b_0.dtype) b_layer = math_ops.range(b_0) target = b return [a_layer, b_layer, target] a_static = tensor_util.constant_value(a) if a_static...
Broadcast two vectors, given their shapes. Args: a: the number of rows in a. b: the number of rows in b. Returns: (layer_a, layer_b, target_shape) layer_a is a _LayerBroadcaster from a to the target_shape. layer_b is a _LayerBroadcaster from b to the target_shape. target_shape is the target_shape Raises: InvalidArgu...
github-repos
def exchange(self, pubkey): try: return self.priv.exchange(c_ec.ECDH(), pubkey.publ) except ValueError as e: raise s_exc.BadEccExchange(mesg=str(e))
Perform a ECDH key exchange with a public key. Args: pubkey (PubKey): A PubKey to perform the ECDH with. Returns: bytes: The ECDH bytes. This is deterministic for a given pubkey and private key.
codesearchnet
def __init__(self, learning_rate, global_step, initial_gradient_squared_accumulator_value=0.1, l1_regularization_strength=0.0, l2_regularization_strength=0.0, use_locking=False, name='AdagradDA'): if initial_gradient_squared_accumulator_value <= 0.0: raise ValueError('initial_gradient_squared_accumulator_va...
Construct a new AdagradDA optimizer. Args: learning_rate: A `Tensor` or a floating point value. The learning rate. global_step: A `Tensor` containing the current training step number. initial_gradient_squared_accumulator_value: A floating point value. Starting value for the accumulators, must be positive. l1_regulari...
github-repos
def send_cmd(cmd, args, ret): from dvc.daemon import daemon if not Analytics._is_enabled(cmd): return analytics = Analytics() analytics.collect_cmd(args, ret) daemon(["analytics", analytics.dump()])
Collect and send analytics for CLI command. Args: args (list): parsed args for the CLI command. ret (int): return value of the CLI command.
juraj-google-style
def get_signature(self, base_commit=None): if (base_commit is None): base_commit = 'HEAD' self.run('add', '-A', self.path) sha = self.run('rev-parse', '--verify', base_commit).strip() diff = self.run('diff', sha).strip() if (len(diff) == 0): try: return self.get_signature...
Get the signature of the current state of the repository TODO right now `get_signature` is an effectful process in that it adds all untracked file to staging. This is the only way to get accruate diff on new files. This is ok because we only use it on a disposable copy of the repo. Args: base_commit - the base commit...
codesearchnet
def _execute_primitives(self, commands): for p in commands: if self._scanchain and self._scanchain._debug: print(" Executing", p) p.execute(self)
Run a list of executable primitives on this controller, and distribute the returned data to the associated TDOPromises. Args: commands: A list of Executable Primitives to be run in order.
juraj-google-style
def _multiplex(self, target_gate, list_of_angles): list_len = len(list_of_angles) local_num_qubits = (int(math.log2(list_len)) + 1) q = QuantumRegister(local_num_qubits) circuit = QuantumCircuit(q, name=('multiplex' + local_num_qubits.__str__())) lsb = q[0] msb = q[(local_num_qubits - 1)] if...
Return a recursive implementation of a multiplexor circuit, where each instruction itself has a decomposition based on smaller multiplexors. The LSB is the multiplexor "data" and the other bits are multiplexor "select". Args: target_gate (Gate): Ry or Rz gate to apply to target qubit, multiplexed over all other "sele...
codesearchnet
def dtype_checker_df(df, dtype, return_=None): dtype_range = dtype_ranges[dtype] df_out_of_range = (((df < dtype_range[0]) | (df > dtype_range[1])) | (~ np.isfinite(df))) if df_out_of_range.any().any(): if (return_ == 'colsums'): df_out_of_range = df_out_of_range.apply(sum, axis=0) ...
Check if there are NaN values of values outside of a given datatype range. Arguments: df {dataframe} -- A dataframe. dtype {str} -- The datatype to check for. Keyword Arguments: return_ {str} -- Returns a boolean dataframe with the values not in the range of the dtype ('all'), the row ('rowsums') or column ('colsums')...
codesearchnet
def cancel_signature_request(self, signature_request_id): request = self._get_request() request.post(url=self.SIGNATURE_REQUEST_CANCEL_URL + signature_request_id, get_json=False)
Cancels a SignatureRequest Cancels a SignatureRequest. After canceling, no one will be able to sign or access the SignatureRequest or its documents. Only the requester can cancel and only before everyone has signed. Args: signing_request_id (str): The id of the signature request to cancel Returns: None
juraj-google-style
def _render_timestep(self, t: int, s: Fluents, a: Fluents, f: Fluents, r: np.float32) -> None: print('============================') print('TIME = {}'.format(t)) print('============================') fluent_variables = self._compiler.rddl.action_fluent_variables self._render_fluent_timestep('action'...
Prints fluents and rewards for the given timestep `t`. Args: t (int): timestep s (Sequence[Tuple[str], np.array]: State fluents. a (Sequence[Tuple[str], np.array]: Action fluents. f (Sequence[Tuple[str], np.array]: Interm state fluents. r (np.float32): Reward.
codesearchnet
def score_prediction_adapter(keyed_prediction: tuple[KeyT, PredictionResult]) -> tuple[KeyT, AnomalyPrediction]: key, prediction = keyed_prediction score = prediction.inference assert isinstance(score, SupportsFloat) return (key, AnomalyPrediction(score=float(score)))
Extracts a float score from `PredictionResult.inference` and wraps it. Takes a keyed `PredictionResult` from common ModelHandler output, assumes its `inference` attribute is a float-convertible score, and returns the key paired with an `AnomalyPrediction` containing that float score. Args: keyed_prediction: tuple of ...
github-repos
def optional(self, value = None): if value is None: return this._optional else: this._optional = value and True or False
Optional Getter/Setter method for optional flag Args: value (bool): If set, the method is a setter Returns: bool | None
juraj-google-style
def unload(self, keepables=None): to_del = [ds_id for ds_id, projectable in self.datasets.items() if ds_id not in self.wishlist and (not keepables or ds_id not in keepables)] for ds_id in to_del: LOG.debug("Unloa...
Unload all unneeded datasets. Datasets are considered unneeded if they weren't directly requested or added to the Scene by the user or they are no longer needed to generate composites that have yet to be generated. Args: keepables (iterable): DatasetIDs to keep whether they are needed or not.
juraj-google-style
def __getitem__(self, index): rank = self.rank if isinstance(index, slice): if index.step is not None and index.step != 1: raise IndexError('Cannot stride through a shape') start = index.start stop = index.stop if start is None: start = 0 start = _...
Returns a dimension or a slice of the shape. Ragged shapes can have ragged dimensions that depend upon other dimensions. Therefore, if you ask for a dimension that is ragged, this function returns a ValueError. For similar reasons, if a slice is selected that includes a ragged dimension without including the zero dime...
github-repos
def get_access_token_from_cli(): if (('ACC_CLOUD' in os.environ) and ('MSI_ENDPOINT' in os.environ)): endpoint = os.environ['MSI_ENDPOINT'] headers = {'Metadata': 'true'} body = {'resource': 'https: ret = requests.post(endpoint, headers=headers, data=body) return ret.json()['...
Get an Azure authentication token from CLI's cache. Will only work if CLI local cache has an unexpired auth token (i.e. you ran 'az login' recently), or if you are running in Azure Cloud Shell (aka cloud console) Returns: An Azure authentication token string.
codesearchnet
def add_argument(self, parser, bootstrap=False): if self.cli_expose: for child in self.children.values(): child.add_argument(parser, bootstrap)
Add dict-style item as an argument to the given parser. The dict item will take all the nested items in the dictionary and namespace them with the dict name, adding each child item as their own CLI argument. Examples: A non-nested dict item with the name 'db' and children named 'port' and 'host' will result in the fo...
codesearchnet
def _pypi_push(dist): for filename in os.listdir(dist): full_path = os.path.join(dist, filename) if os.path.isfile(full_path): _shell('twine register ' + shlex.quote(full_path), check=False) _shell('twine upload ' + shlex.quote(dist + '/*'))
Push created package to PyPI. Requires the following defined environment variables: - TWINE_USERNAME: The PyPI username to upload this package under - TWINE_PASSWORD: The password to the user's account Args: dist (str): The distribution to push. Must be a valid directory; shell globs are NOT allowed.
juraj-google-style
def list_registered_stateful_ops_without_inputs(): return set([name for (name, op) in op_def_registry.get_registered_ops().items() if (op.is_stateful and (not op.input_arg))])
Returns set of registered stateful ops that do not expect inputs. This list is used to identify the ops to be included in the state-graph and that are subsequently fed into the apply-graphs. Returns: A set of strings.
codesearchnet
def test_src_dir_path(relative_path): return _googletest.test_src_dir_path(relative_path)
Creates an absolute test srcdir path given a relative path. Args: relative_path: a path relative to tensorflow root. e.g. "core/platform". Returns: An absolute path to the linked in runfiles.
github-repos
def _get_parameter_info(param_name, documented_params, source_args_dict, param_type, optional): description = None shape = None shape_string = '' is_documented = True additional_info = None if param_name in documented_params: if param_type == '' and documented_params[param_name].get('typ...
Get parameter documentation details from the appropriate source. Tensor shape, optional status and description are taken from the custom docstring in priority if available. Type is taken from the function signature first, then from the custom docstring if missing from the signature Args: param_name (`str`): Name of th...
github-repos
def _padding_value_to_tensor(value, output_type): value = ops.convert_to_tensor(value, name='padding_value') if not value.shape.is_compatible_with(tensor_shape.TensorShape([])): raise ValueError(f'Invalid `padding_values`. `padding_values` values should be scalars, but got {value.shape}.') if value....
Converts the padding value to a tensor. Args: value: The padding value. output_type: Its expected dtype. Returns: A scalar `Tensor`. Raises: ValueError: if the padding value is not a scalar. TypeError: if the padding value's type does not match `output_type`.
github-repos
def assert_text(self, *args, **kwargs): query = TextQuery(*args, **kwargs) @self.synchronize(wait=query.wait) def assert_text(): count = query.resolve_for(self) if not (matches_count(count, query.options) and (count > 0 or expects_none(quer...
Asserts that the page or current node has the given text content, ignoring any HTML tags. Args: *args: Variable length argument list for :class:`TextQuery`. **kwargs: Arbitrary keyword arguments for :class:`TextQuery`. Returns: True Raises: ExpectationNotMet: If the assertion hasn't succeeded during the wait time.
juraj-google-style
def __init__(self, inputs=[], outputs=[], attributes=[], scripts=[]): super(Transaction, self).__init__() self.inputs = inputs self.outputs = outputs self.Attributes = attributes self.scripts = scripts self.InventoryType = 0x01 self.__references = None
Create an instance. Args: inputs (list): of neo.Core.CoinReference.CoinReference. outputs (list): of neo.Core.TX.Transaction.TransactionOutput items. attributes (list): of neo.Core.TX.TransactionAttribute. scripts:
juraj-google-style
def equal_distribution_folds(y, folds=2): n, classes = y.shape dist = y.sum(axis=0).astype('float') dist /= dist.sum() index_list = [] fold_dist = np.zeros((folds, classes), dtype='float') for _ in range(folds): index_list.append([]) for i in range(n): if i < fold...
Creates `folds` number of indices that has roughly balanced multi-label distribution. Args: y: The multi-label outputs. folds: The number of folds to create. Returns: `folds` number of indices that have roughly equal multi-label distributions.
juraj-google-style
def __init__(self,consumer_key,consumer_secret,access_token=None): self.consumer = oauth.Consumer(consumer_key, consumer_secret) if access_token: self.setAccessToken(access_token)
Initializes the splitwise class. Sets consumer and access token Args: consumer_key (str) : Consumer Key provided by Spliwise consumer_secret (str): Consumer Secret provided by Splitwise access_token (:obj: `dict`) Access Token is a combination of oauth_token and oauth_token_secret Returns: A Splitwise Object
juraj-google-style
def UpdateNumberOfEventTags( self, number_of_consumed_event_tags, number_of_produced_event_tags): consumed_event_tags_delta = 0 if number_of_consumed_event_tags is not None: if number_of_consumed_event_tags < self.number_of_consumed_event_tags: raise ValueError( 'Number of c...
Updates the number of event tags. Args: number_of_consumed_event_tags (int): total number of event tags consumed by the process. number_of_produced_event_tags (int): total number of event tags produced by the process. Returns: bool: True if either number of event tags has increased. Raises: ValueError: if the consum...
juraj-google-style
def get_plot_frame(map_obj, key_map, cached=False): if map_obj.kdims and len(map_obj.kdims) == 1 and map_obj.kdims[0] == 'Frame': return map_obj.last key = tuple(key_map[kd.name] for kd in map_obj.kdims if kd.name in key_map) if key in map_obj.data and cached: return map_obj.da...
Returns the current frame in a mapping given a key mapping. Args: obj: Nested Dimensioned object key_map: Dictionary mapping between dimensions and key value cached: Whether to allow looking up key in cache Returns: The item in the mapping corresponding to the supplied key.
juraj-google-style
def get(self, node_id): return self.prepare_model(self.client.api.inspect_node(node_id))
Get a node. Args: node_id (string): ID of the node to be inspected. Returns: A :py:class:`Node` object. Raises: :py:class:`docker.errors.APIError` If the server returns an error.
juraj-google-style
def create_template(self, s, provider_name=None): if provider_name is None: provider_name = self.supported_providers[0] return template_exception_handler( lambda: self.get_provider(provider_name).create_template(s), self.error_context )
Creates a template from the given string based on the specified provider or the provider with highest precedence. Args: s: The string to convert to a template. provider_name: The name of the provider to use to create the template.
juraj-google-style
def create_file(self, filename): self.response.write(('Creating file %s\n' % filename)) write_retry_params = gcs.RetryParams(backoff_factor=1.1) gcs_file = gcs.open(filename, 'w', content_type='text/plain', options={'x-goog-meta-foo': 'foo', 'x-goog-meta-bar': 'bar'}, retry_params=write_retry_params) gc...
Create a file. The retry_params specified in the open call will override the default retry params for this particular file handle. Args: filename: filename.
codesearchnet
def diff_lineMode(self, text1, text2, deadline): (text1, text2, linearray) = self.diff_linesToChars(text1, text2) diffs = self.diff_main(text1, text2, False, deadline) self.diff_charsToLines(diffs, linearray) self.diff_cleanupSemantic(diffs) diffs.append((self.DIFF_EQUAL, '')) pointer = 0 co...
Do a quick line-level diff on both strings, then rediff the parts for greater accuracy. This speedup can produce non-minimal diffs. Args: text1: Old string to be diffed. text2: New string to be diffed. deadline: Time when the diff should be complete by. Returns: Array of changes.
codesearchnet
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...
juraj-google-style
def __init__(self, scope, parent): CodeStatement.__init__(self, scope, parent) self.variables = []
Constructor for declaration statements. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree.
juraj-google-style
def _AddForwardedIps(self, forwarded_ips, interface): for address in forwarded_ips: self.ip_forwarding_utils.AddForwardedIp(address, interface)
Configure the forwarded IP address on the network interface. Args: forwarded_ips: list, the forwarded IP address strings to configure. interface: string, the output device to use.
codesearchnet
def convert_error(exc_src, exc_dest): def wrap(func): @wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except exc_dest: raise except exc_src as err: reraise(exc_dest, err, sys.exc_info()...
A decorator for reraising exceptions with a different type. Mostly useful for IOError. Args: exc_src (type): The source exception type exc_dest (type): The target exception type.
codesearchnet
def _on_write_request(self, request): if request['connection_handle'] != self._connection_handle: return False attribute_handle = request['attribute_handle'] config_handles = [ ReceiveHeaderChar.config_handle, ReceivePayloadChar.config_hand...
Callback function called when a write request has been received. It is executed in the baBLE working thread: should not be blocking. Args: request (dict): Information about the request - connection_handle (int): The connection handle that sent the request - attribute_handle (int): The attribute handle to write - value...
juraj-google-style
def get_servo_status(self): data = [] data.append(9) data.append(self.servoid) data.append(RAM_READ_REQ) data.append(STATUS_ERROR_RAM) data.append(BYTE1) send_data(data) rxdata = [] try: rxdata = SERPORT.read(12) return (ord(rxdata[9]) & 255) except: raise...
Get the error status of servo This function gets the error status (if any) of the servo Args: none Returns: int: an integer corresponding to the servo status * refer datasheet
codesearchnet
def LessThan(self, value): self._awql = self._CreateSingleValueCondition(value, '<') return self._query_builder
Sets the type of the WHERE clause as "less than". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to.
juraj-google-style
def get_event_consumer(config, success_channel, error_channel, metrics, **kwargs): builder = event_consumer.GPSEventConsumerBuilder(config, success_channel, error_channel, metrics, **kwargs) return builder.build_event_consumer()
Get a GPSEventConsumer client. A factory function that validates configuration, creates schema validator and parser clients, creates an auth and a pubsub client, and returns an event consumer (:interface:`gordon.interfaces. IRunnable` and :interface:`gordon.interfaces.IMessageHandler`) provider. Args: config (dict): ...
codesearchnet
def _ConvertListToObject(cls, json_list): list_value = [] for json_list_element in json_list: if isinstance(json_list_element, dict): list_value.append(cls._ConvertDictToObject(json_list_element)) elif isinstance(json_list_element, list): list_value.append(cls._ConvertLis...
Converts a JSON list into an object. Args: json_list (list[object]): JSON serialized objects. Returns: list[object]: a deserialized list.
codesearchnet
def get_choices_for(self, field): choices = self._fields[field].choices if isinstance(choices, six.string_types): return [(d['value'], d['name']) for d in self._choices_manager.get_all(choices)] else: return choices
Get the choices for the given fields. Args: field (str): Name of field. Returns: List of tuples. [(name, value),...]
codesearchnet
def dump_size_bytes(self): return self._dump_size_bytes
Size of the dump file. Unit: byte. Returns: If the dump file exists, size of the dump file, in bytes. If the dump file does not exist, None.
github-repos
def load_maps(maps_dir): maps_dir = os.path.abspath(maps_dir) maps = {} for root, dirnames, filenames in os.walk(maps_dir): for filename in filenames: if filename.endswith(".xml"): xml_file = os.path.join(root, filename) map = MapSource.from_xml(xml_f...
Load all xml map sources from a given directory. Args: maps_dir: path to directory to search for maps Returns: dict of MapSource:
juraj-google-style
def _get_authenticated_session(self): session = requests.Session() session.auth = self.auth return session
Return an authenticated requests session. Returns: requests.Session: Authenticated session for use.
codesearchnet
def FindMessageTypeByName(self, full_name): full_name = _NormalizeFullyQualifiedName(full_name) if full_name not in self._descriptors: self.FindFileContainingSymbol(full_name) return self._descriptors[full_name]
Loads the named descriptor from the pool. Args: full_name: The full name of the descriptor to load. Returns: The descriptor for the named type.
juraj-google-style
def create_sns_topic(self, region): sns = self.session.client('sns', region_name=region) self.log.info('Creating SNS topic for {}/{}'.format(self.account, region)) res = sns.create_topic(Name=self.topic_name) arn = res['TopicArn'] tmpl = get_template(...
Creates an SNS topic if needed. Returns the ARN if the created SNS topic Args: region (str): Region name Returns: `str`
juraj-google-style
def _start_app_and_connect(self): self._check_app_installed() self.disable_hidden_api_blacklist() persists_shell_cmd = self._get_persist_command() self.log.info('Launching snippet apk %s with protocol %d.%d', self.package, _PROTOCOL_MAJOR_VERSION, _PROTOCOL_MINOR_VERSION) cmd = _LAUNCH_CMD.format(sh...
Starts snippet apk on the device and connects to it. After prechecks, this launches the snippet apk with an adb cmd in a standing subprocess, checks the cmd response from the apk for protocol version, then sets up the socket connection over adb port-forwarding. Args: ProtocolVersionError, if protocol info or port inf...
github-repos
def _as_document(self, identifier): return { 'identifier': u('{}').format(identifier['identifier']), 'type': u('{}').format(identifier['type']), 'name': u('{}').format(identifier['name']) }
Converts given identifier to the document indexed by FTS backend. Args: identifier (dict): identifier to convert. Dict contains at least 'identifier', 'type' and 'name' keys. Returns: dict with structure matches to BaseIdentifierIndex._schema.
juraj-google-style
def test(verbosity=1): import unittest from .tests import test_suite unittest.TextTestRunner(verbosity=verbosity).run(test_suite)
Executes all the tests for pyplink. Args: verbosity (int): The verbosity level for :py:mod:`unittest`. Just set ``verbosity`` to an integer higher than ``1`` to have more information about the tests.
juraj-google-style
def link(target, link_to): assert isinstance(target, str) assert os.path.exists(target) assert isinstance(link_to, str) abs_path = os.path.dirname(os.path.abspath(link_to)) if (not os.path.isdir(abs_path)): os.makedirs(abs_path) chmod(target) os.symlink(target, link_to)
Create a link to a target file or a folder. For simplicity sake, both target and link_to must be absolute path and must include the filename of the file or folder. Also do not include any trailing slash. e.g. link('/path/to/file', '/path/to/link') But not: link('/path/to/file', 'path/to/') or link('/path/to/folder/'...
codesearchnet
def list(self, pattern='*'): if self._descriptors is None: self._descriptors = self._client.list_resource_descriptors( filter_string=self._filter_string) return [resource for resource in self._descriptors if fnmatch.fnmatch(resource.type, pattern)]
Returns a list of resource descriptors that match the filters. Args: pattern: An optional pattern to further filter the descriptors. This can include Unix shell-style wildcards. E.g. ``"aws*"``, ``"*cluster*"``. Returns: A list of ResourceDescriptor objects that match the filters.
juraj-google-style
def __init__(self, workflow, generator, work): super(Barrier, self).__init__() self.workflow = workflow self.generator = generator if isinstance(work, (list, tuple)): self[:] = list(work) self.was_list = True self.wait_any = False eli...
Initializer. Args: workflow: WorkflowItem instance this is for. generator: Current state of the WorkflowItem's generator. work: Next set of work to do. May be a single WorkItem object or a list or tuple that contains a set of WorkItems to run in parallel.
juraj-google-style
def _add_sub_parsers(self, top_level_parser, methods_to_parse, class_name): description = 'Accessible methods of {}'.format(class_name) sub_parsers = top_level_parser.add_subparsers(description=description, dest='method') parser_to_method = {} for (method_name, parser) in methods_to_parse.items(): ...
Add all the sub-parsers to the top_level_parser. Args: top_level_parser: the top level parser methods_to_parse: dict of method name pointing to their associated argument parser class_name: name of the decorated class Returns: a dict of registered name of the parser i.e. sub command name pointing to the method real na...
codesearchnet
def save(self, force=False): from time import time from datetime import datetime savefreq = TaskDB.get_option('savefreq', 2, int) if (self.lastsave is not None): delta = (datetime.fromtimestamp(time()) - datetime.fromtimestamp(self.lastsave)) elapsed = int((delta.total_seconds() / 60)) ...
Serializes the database file to disk. Args: force (bool): when True, the elapsed time since last save is ignored and the database is saved anyway (subject to global :data:`writeable` setting).
codesearchnet
class Activation(Layer): def __init__(self, activation, **kwargs): super(Activation, self).__init__(**kwargs) self.supports_masking = True self.activation = activations.get(activation) def call(self, inputs): return self.activation(inputs) def compute_output_shape(self, in...
Applies an activation function to an output. Args: activation: Activation function, such as `tf.nn.relu`, or string name of built-in activation function, such as "relu". Usage: >>> layer = tf.keras.layers.Activation('relu') >>> output = layer([-3.0, -1.0, 0.0, 2.0]) >>> list(output.numpy()) [0.0, 0.0, 0.0, 2.0] >>> ...
github-repos
def _make_request(self, url, method="get", data=None, extra_headers=None): attempts = 0 while attempts < 1: if not self._is_authenticated: self._authenticate() try: return self._send_request(url, met...
Prepares the request, checks for authentication and retries in case of issues 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 _secured_storage_parameters(self): parameters = (self._storage_parameters or dict()) if self._unsecure: parameters = parameters.copy() parameters['protocol'] = 'http' return parameters
Updates storage parameters with unsecure mode. Returns: dict: Updated storage_parameters.
codesearchnet