code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def _set_per_output_metric_attributes(self, metrics_dict, output_index): updated_metrics_dict = collections.OrderedDict() for metric_name, metric_fn in metrics_dict.items(): metric_name = self._add_unique_metric_name(metric_name, metric_fn, output_index) metric_fn._name = metric_name upd...
Sets the metric attributes on the model for the given output. Args: metrics_dict: A dict with metric names as keys and metric fns as values. output_index: The index of the model output for which the metric attributes are added. Returns: Metrics dict updated with unique metric names as keys.
github-repos
def logical_switches(self): if (not self.__logical_switches): self.__logical_switches = LogicalSwitches(self.__connection) return self.__logical_switches
Gets the LogicalSwitches API client. Returns: LogicalSwitches:
codesearchnet
def IsBlockInNameSpace(nesting_state, is_forward_declaration): if is_forward_declaration: return len(nesting_state.stack) >= 1 and ( isinstance(nesting_state.stack[-1], _NamespaceInfo)) return (len(nesting_state.stack) > 1 and nesting_state.stack[-1].check_namespace_indentation and ...
Checks that the new block is directly in a namespace. Args: nesting_state: The _NestingState object that contains info about our state. is_forward_declaration: If the class is a forward declared class. Returns: Whether or not the new block is directly in a namespace.
juraj-google-style
def _sub_entity_map(self, assignments, item, campaign): for assignment in assignments: placement = self._placement_dao.get(assignment, required=True) event_tag = self._event_tag_dao.get(assignment, required=True) creative = self._creative_dao.get(assignment, required=True) landing_pa...
Maps ids and names of sub entities so they can be updated in the Bulkdozer feed. When Bulkdozer is done processing an item, it writes back the updated names and ids of related objects, this method makes sure those are updated in the ad feed. Args: assignments: List of child feeds to map. item: The DCM ad object that ...
github-repos
def createLabel(self, name): if self.findLabel(name): raise exception.LabelException('Label exists') node = _node.Label() node.name = name self._labels[node.id] = node return node
Create a new label. Args: name (str): Label name. Returns: gkeepapi.node.Label: The new label. Raises: LabelException: If the label exists.
juraj-google-style
def slice_hidden(self, x): x_sliced = tf.reshape( x, shape=[-1, self.hparams.num_blocks, self.hparams.block_dim]) return x_sliced
Slice encoder hidden state into block_dim. Args: x: Encoder hidden state of shape [-1, hidden_size]. Returns: Sliced states of shape [-1, num_blocks, block_dim].
juraj-google-style
def load(self, email, master_token, android_id): self._email = email self._android_id = android_id self._master_token = master_token self.refresh() return True
Authenticate to Google with the provided master token. Args: email (str): The account to use. master_token (str): The master token. android_id (str): An identifier for this client. Raises: LoginException: If there was a problem logging in.
codesearchnet
def __type_check_attributes(self, node: yaml.Node, mapping: CommentedMap, argspec: inspect.FullArgSpec) -> None: logger.debug('Checking for extraneous attributes') logger.debug('Constructor arguments: {}, mapping: {}'.format(argspec.args, list(mapping.keys()))) for (key, value) in mapping.items(): i...
Ensure all attributes have a matching constructor argument. This checks that there is a constructor argument with a \ matching type for each existing attribute. If the class has a yatiml_extra attribute, then extra \ attributes are okay and no error will be raised if they exist. Args: node: The node we're processing...
codesearchnet
def convert_positional_argument(self, index, arg_value): if self._has_self: if index == 0: return arg_value index -= 1 arg_name = self.arg_names[index] return self.convert_argument(arg_name, arg_value)
Convert and validate a positional argument. Args: index (int): The positional index of the argument arg_value (object): The value to convert and validate Returns: object: The converted value.
juraj-google-style
def scan_devices(self, subnet, timeout=None): max_range = { 16: 256, 24: 256, 25: 128, 27: 32, 28: 16, 29: 8, 30: 4, 31: 2 } if "/" not in subnet: mas...
Scan cameras in a range of ips Params: subnet - subnet, i.e: 192.168.1.0/24 if mask not used, assuming mask 24 timeout_sec - timeout in sec Returns:
juraj-google-style
def add_value(self, field_name: str, value: object=None, json_path: str=None, json_path_extraction: str=None, keep_empty: bool=False) -> None: def validate(v): if (v is not None): if isinstance(v, str): if ((v.strip() != '') or keep_empty): return True ...
Add a value to knowledge graph. Input can either be a value or a json_path. If the input is json_path, the helper function _add_doc_value is called. If the input is a value, then it is handled Args: field_name: str, the field name in the knowledge graph value: the value to be added to the knowledge graph json_path: st...
codesearchnet
def __init__(self, command_sequence, sess, dump_root=None): local_cli_wrapper.LocalCLIDebugWrapperSession.__init__(self, sess, dump_root=dump_root) self._command_sequence = command_sequence self._command_pointer = 0 self.observers = {'debug_dumps': [], 'tf_errors': [], 'run_start_cli_run_numbers': [], '...
Constructor of the for-test subclass. Args: command_sequence: (list of list of str) A list of command arguments, including the command prefix, each element of the list is such as: ["run", "-n"], ["print_feed", "input:0"]. sess: See the doc string of LocalCLIDebugWrapperSession.__init__. dump_root: See the doc string o...
github-repos
def token_network_connect(self, registry_address: PaymentNetworkID, token_address: TokenAddress, funds: TokenAmount, initial_channel_target: int=3, joinable_funds_target: float=0.4) -> None: if (not is_binary_address(registry_address)): raise InvalidAddress('registry_address must be a valid address in binar...
Automatically maintain channels open for the given token network. Args: token_address: the ERC20 token network to connect to. funds: the amount of funds that can be used by the ConnectionMananger. initial_channel_target: number of channels to open proactively. joinable_funds_target: fraction of the funds that will be ...
codesearchnet
def tdist95conf_level(df): df = int(round(df)) highest_table_df = len(_T_DIST_95_CONF_LEVELS) if df >= 200: return 1.960 if df >= 100: return 1.984 if df >= 80: return 1.990 if df >= 60: return 2.000 if df >= 50: return 2.009 if df >= 40: ...
Approximate the 95% confidence interval for Student's T distribution. Given the degrees of freedom, returns an approximation to the 95% confidence interval for the Student's T distribution. Args: df: An integer, the number of degrees of freedom. Returns: A float.
juraj-google-style
def download_decompress(url: str, download_path: [Path, str], extract_paths=None): file_name = Path(urlparse(url).path).name download_path = Path(download_path) if (extract_paths is None): extract_paths = [download_path] elif isinstance(extract_paths, list): extract_paths = [Path(path) f...
Download and extract .tar.gz or .gz file to one or several target locations. The archive is deleted if extraction was successful. Args: url: URL for file downloading download_path: path to the directory where downloaded file will be stored until the end of extraction extract_paths: path or list of paths where contents...
codesearchnet
def connection_made(self, transport): self.transport = transport self.transport.sendto(self.message) self.transport.close()
Create connection, use to send message and close. Args: transport (asyncio.DatagramTransport): Transport used for sending.
codesearchnet
def _DefaultValueConstructorForField(field): if _IsMapField(field): return _GetInitializeDefaultForMap(field) if field.label == _FieldDescriptor.LABEL_REPEATED: if field.has_default_value and field.default_value != []: raise ValueError('Repeated field default value not empty list: %s' % ( ...
Returns a function which returns a default value for a field. Args: field: FieldDescriptor object for this field. The returned function has one argument: message: Message instance containing this field, or a weakref proxy of same. That function in turn returns a default value for this field. The default value may r...
juraj-google-style
def allow_nan_stats(self): return self._allow_nan_stats
Python `bool` describing behavior when a stat is undefined. Stats return +/- infinity when it makes sense. E.g., the variance of a Cauchy distribution is infinity. However, sometimes the statistic is undefined, e.g., if a distribution's pdf does not achieve a maximum within the support of the distribution, the mode is...
github-repos
def is_point(self): if self.childCount() == 2: if self.child(0).valid_values == float and self.child(1).valid_values == float: return True else: return False
figures out if item is a point, that is if it has two subelements of type float Args: self: Returns: if item is a point (True) or not (False)
juraj-google-style
def _flatten_obs(self, obs_dict, verbose=False): ob_lst = [] for key in obs_dict: if (key in self.keys): if verbose: print('adding key: {}'.format(key)) ob_lst.append(obs_dict[key]) return np.concatenate(ob_lst)
Filters keys of interest out and concatenate the information. Args: obs_dict: ordered dictionary of observations
codesearchnet
def __init__(self, options): self.__options = options self.count_total = 0 self.items_queued = OrderedDict() self.items_in_progress = OrderedDict() self.items_finished = OrderedDict() self.items_cancelled = OrderedDict() self.items_errored = OrderedDict(...
Constructs a Queue instance. Args: options (:class:`nyawc.Options`): The options to use.
juraj-google-style
def _ip_assigned(self): output = [] cmd = ['/sbin/ip', 'address', 'show', 'dev', self.config['interface'], 'to', self.ip_with_prefixlen] if self.ip_check_disabled: self.log.info('checking for IP assignment on interface %s is disabled', self.config['interface']) return True self.log.debug...
Check if IP prefix is assigned to loopback interface. Returns: True if IP prefix found assigned otherwise False.
codesearchnet
def from_value(cls, value): return cls(value.shape, dtype=value.dtype, trainable=value.trainable)
Creates a `VariableSpec` from the given `Variable`. `value`'s shape, dtype, and trainable attributes will be used to create the new `VariableSpec`. Example: >>> v = tf.Variable([1., 2., 3.]) >>> VariableSpec.from_value(v) VariableSpec(shape=(3,), dtype=tf.float32, trainable=True, alias_id=None) Args: value: A Varia...
github-repos
def _new_import(self, import_name): assert self.root_path is not None, \ '"import" statement can not be used if meta-model is ' \ 'loaded from string.' current_namespace = self._namespace_stack[-1] if '.' in current_namespace: ...
Starts a new import. Args: import_name(str): A relative import in the dot syntax (e.g. "first.second.expressions")
juraj-google-style
def delete_datastore(self): (success, result) = self._read_from_hdx('datastore', self.data['id'], 'resource_id', self.actions()['datastore_delete'], force=True) if (not success): logger.debug(result)
Delete a resource from the HDX datastore Returns: None
codesearchnet
def __init__(self, scopes=None, service_account_name='default', **kwds): self.__service_account_name = service_account_name cached_scopes = None cache_filename = kwds.get('cache_filename') if cache_filename: cached_scopes ...
Initializes the credentials instance. Args: scopes: The scopes to get. If None, whatever scopes that are available to the instance are used. service_account_name: The service account to retrieve the scopes from. **kwds: Additional keyword args.
juraj-google-style
def evaluate(self, instance, step, extra): chain = step.chain[1:] if self.strict and not chain: raise TypeError( "A ContainerAttribute in 'strict' mode can only be used " "within a SubFactory.") return self.function(instance, chain)
Evaluate the current ContainerAttribute. Args: obj (LazyStub): a lazy stub of the object being constructed, if needed. containers (list of LazyStub): a list of lazy stubs of factories being evaluated in a chain, each item being a future field of next one.
juraj-google-style
def decrease_exponent_to(self, new_exp): if (new_exp > self.exponent): raise ValueError(('New exponent %i should be more negative thanold exponent %i' % (new_exp, self.exponent))) factor = pow(self.BASE, (self.exponent - new_exp)) new_enc = ((self.encoding * factor) % self.public_key.n) return s...
Return an `EncodedNumber` with same value but lower exponent. If we multiply the encoded value by :attr:`BASE` and decrement :attr:`exponent`, then the decoded value does not change. Thus we can almost arbitrarily ratchet down the exponent of an :class:`EncodedNumber` - we only run into trouble when the encoded intege...
codesearchnet
def num_samples(self, dataset_split): return { problem.DatasetSplit.TRAIN: 1000000, problem.DatasetSplit.EVAL: 10000, problem.DatasetSplit.TEST: 10000 }[dataset_split]
Determine the dataset sized given a dataset_split. Args: dataset_split: A problem.DatasetSplit. Returns: The desired number of samples for this dataset_split.
juraj-google-style
def get_stream(self, error_callback=None, live=True): self.join() return Stream(self, error_callback=error_callback, live=live)
Get room stream to listen for messages. Kwargs: error_callback (func): Callback to call when an error occurred (parameters: exception) live (bool): If True, issue a live stream, otherwise an offline stream Returns: :class:`Stream`. Stream
codesearchnet
def get_filtered_vts_list(self, vts, vt_filter): if (not vt_filter): raise RequiredArgument('vt_filter: A valid filter is required.') filters = self.parse_filters(vt_filter) if (not filters): return None _vts_aux = vts.copy() for (_element, _oper, _filter_val) in filters: for...
Gets a collection of vulnerability test from the vts dictionary, which match the filter. Arguments: vt_filter (string): Filter to apply to the vts collection. vts (dictionary): The complete vts collection. Returns: Dictionary with filtered vulnerability tests.
codesearchnet
def get_go_server(settings=None): if (not settings): settings = get_settings() return gocd.Server(settings.get('server'), user=settings.get('user'), password=settings.get('password'))
Returns a `gocd.Server` configured by the `settings` object. Args: settings: a `gocd_cli.settings.Settings` object. Default: if falsey calls `get_settings`. Returns: gocd.Server: a configured gocd.Server instance
codesearchnet
def _GetConfigValue(self, config_parser, section_name, value_name): try: return config_parser.get(section_name, value_name) except configparser.NoOptionError: return None
Retrieves a value from the config parser. Args: config_parser (ConfigParser): configuration parser. section_name (str): name of the section that contains the value. value_name (str): name of the value. Returns: object: configuration value or None if the value does not exists.
juraj-google-style
def vector(p1, p2): return np.subtract(p1[COLS.XYZ], p2[COLS.XYZ])
compute vector between two 3D points Args: p1, p2: indexable objects with indices 0, 1, 2 corresponding to 3D cartesian coordinates. Returns: 3-vector from p1 - p2
juraj-google-style
def is_alive(self) -> bool: return self._thread.is_alive()
Returns whether the thread is alive. This method returns True just before the run() method starts until just after the run() method terminates. Returns: True if the thread is alive, otherwise False.
github-repos
def _render_objects(self, items, attributes=None, datatype='object'): if (not items): return if (datatype == 'chartdata'): if (not attributes): attributes = [items['cols'][i]['label'] for i in range(0, len(items['cols']))] items = items['rows'] indices = {attributes[i...
Renders an HTML table with the specified list of objects. Args: items: the iterable collection of objects to render. attributes: the optional list of properties or keys to render. datatype: the type of data; one of 'object' for Python objects, 'dict' for a list of dictionaries, or 'chartdata' for Google chart data.
codesearchnet
def _send_offset_commit_request(self, offsets): assert self.config['api_version'] >= (0, 8, 1), 'Unsupported Broker API' assert all(map(lambda k: isinstance(k, TopicPartition), offsets)) assert all(map(lambda v: isinstance(v, OffsetAndMetadata), offsets.values()))...
Commit offsets for the specified list of topics and partitions. This is a non-blocking call which returns a request future that can be polled in the case of a synchronous commit or ignored in the asynchronous case. Arguments: offsets (dict of {TopicPartition: OffsetAndMetadata}): what should be committed Returns: Fu...
juraj-google-style
def transition_scope(self, state: Sequence[tf.Tensor], action: Sequence[tf.Tensor]) -> Dict[str, TensorFluent]: scope = {} scope.update(self.non_fluents_scope()) scope.update(self.state_scope(state)) scope.update(self.action_scope(action)) return scope
Returns the complete transition fluent scope for the current `state` and `action` fluents. Args: state (Sequence[tf.Tensor]): The current state fluents. action (Sequence[tf.Tensor]): The action fluents. Returns: A mapping from fluent names to :obj:`rddl2tf.fluent.TensorFluent`.
juraj-google-style
def command(self, server_id, command, *args): server = self._storage[server_id] try: if args: result = getattr(server, command)(*args) else: result = getattr(server, command)() except AttributeError: raise ValueError("C...
run command Args: server_id - server identity command - command which apply to server
juraj-google-style
def __nonzero__(self): self._disallow_bool_casting()
Dummy method to prevent a tensor from being used as a Python `bool`. This is the Python 2.x counterpart to `__bool__()` above. Raises: `TypeError`.
github-repos
def prettyprint_cfg_node(node, decorate_after_node=0, full=False): if node.id <= decorate_after_node: return repr(node) + f' [{len(node.bindings)} bindings]' if full: name = lambda x: getattr(x, 'name', str(x)) else: name = str bindings = collections.defaultdict(list) for b i...
A reasonably compact representation of all the bindings at a node. Args: node: The node to prettyprint. decorate_after_node: Don't print bindings unless node_id > this. full: Print the full string representation of a binding's data Returns: A prettyprinted node.
github-repos
def _read_output(self, stream, callback, output_file): if (((callback is None) and (output_file is None)) or stream.closed): return False line = stream.readline() if line: if (callback is not None): callback(line.decode(), self._data, self._store, self._signal, self._context) ...
Read the output of the process, executed the callback and save the output. Args: stream: A file object pointing to the output stream that should be read. callback(callable, None): A callback function that is called for each new line of output. output_file: A file object to which the full output is written. Returns: b...
codesearchnet
def merge_nodes(self, n1: str, n2: str, same_polarity: bool = True): for p in self.predecessors(n1): for st in self[p][n1]["InfluenceStatements"]: if not same_polarity: st.obj_delta["polarity"] = -st.obj_delta["polarity"] st.obj.db_refs["...
Merge node n1 into node n2, with the option to specify relative polarity. Args: n1 n2 same_polarity
juraj-google-style
def unpack_wstring(self, offset, length): start = self._offset + offset end = self._offset + offset + 2 * length try: return bytes(self._buf[start:end]).decode("utf16") except AttributeError: return bytes(self._buf[start:end]).decode('utf16')
Returns a string from the relative offset with the given length, where each character is a wchar (2 bytes) Arguments: - `offset`: The relative offset from the start of the block. - `length`: The length of the string. Throws: - `UnicodeDecodeError`
juraj-google-style
def get_policy(self, name): address = _create_policy_address(name) policy_list_bytes = None try: policy_list_bytes = self._state_view.get(address=address) except KeyError: return None if (policy_list_bytes is not None): policy_list = _create_from_bytes(policy_list_bytes, iden...
Get a single Policy by name. Args: name (str): The name of the Policy. Returns: (:obj:`Policy`) The Policy that matches the name.
codesearchnet
def Deserialize(self, reader): self.Type = reader.ReadByte() self.Hashes = reader.ReadHashes()
Deserialize full object. Args: reader (neo.IO.BinaryReader):
juraj-google-style
def extract_sub_graph(graph_def, dest_nodes): if not isinstance(graph_def, graph_pb2.GraphDef): raise TypeError(f'graph_def must be a graph_pb2.GraphDef proto, but got type {type(graph_def)}.') if isinstance(dest_nodes, str): raise TypeError(f'dest_nodes must be an iterable of strings, but got t...
Extract the subgraph that can reach any of the nodes in 'dest_nodes'. Args: graph_def: A graph_pb2.GraphDef proto. dest_nodes: An iterable of strings specifying the destination node names. Returns: The GraphDef of the sub-graph. Raises: TypeError: If 'graph_def' is not a graph_pb2.GraphDef proto.
github-repos
def get(object_ids): if isinstance(object_ids, (tuple, np.ndarray)): return ray.get(list(object_ids)) elif isinstance(object_ids, dict): keys_to_get = [ k for k, v in object_ids.items() if isinstance(v, ray.ObjectID) ] ids_to_get = [ v for k, v in obj...
Get a single or a collection of remote objects from the object store. This method is identical to `ray.get` except it adds support for tuples, ndarrays and dictionaries. Args: object_ids: Object ID of the object to get, a list, tuple, ndarray of object IDs to get or a dict of {key: object ID}. Returns: A Python obje...
juraj-google-style
def execute(self, container: Container, test: TestCase, verbose: bool=False) -> TestOutcome: bug = self.__installation.bugs[container.bug] response = self.command(container, cmd=test.command, context=test.context, stderr=True, time_limit=test.time_limit, kill_after=test.kill_after, verbose=verbose) passed =...
Runs a specified test inside a given container. Returns: the outcome of the test execution.
codesearchnet
def _expand_variable_match(positional_vars, named_vars, match): positional = match.group('positional') name = match.group('name') if (name is not None): try: return six.text_type(named_vars[name]) except KeyError: raise ValueError("Named variable '{}' not specified an...
Expand a matched variable with its value. Args: positional_vars (list): A list of positonal variables. This list will be modified. named_vars (dict): A dictionary of named variables. match (re.Match): A regular expression match. Returns: str: The expanded variable to replace the match. Raises: ValueError: If a posit...
codesearchnet
def to_df(self, **kwargs): return pd.read_sql(sql=self.statement, con=self.session.bind, **kwargs)
[pandas.read_sql] Arguments: Query {[type]} -- [description] Returns: [pd.DataFrame or generate] -- [description]
juraj-google-style
def start_prompt(self, message, text_input=False, cli_color=''): with self._cond: if self._prompt: raise MultiplePromptsError prompt_id = uuid.uuid4().hex _LOG.debug('Displaying prompt (%s): "%s"%s', prompt_id, message, ', Expects text input.' if text_input else '') ...
Display a prompt. Args: message: A string to be presented to the user. text_input: A boolean indicating whether the user must respond with text. cli_color: An ANSI color code, or the empty string. Raises: MultiplePromptsError: There was already an existing prompt. Returns: A string uniquely identifying the prompt.
juraj-google-style
def get_keys(self, alias_name, key_format): uri = self.URI + "/keys/" + alias_name + "?format=" + key_format return self._client.get(uri)
Retrieves the contents of PKCS12 file in the format specified. This PKCS12 formatted file contains both the certificate as well as the key file data. Valid key formats are Base64 and PKCS12. Args: alias_name: Key pair associated with the RabbitMQ key_format: Valid key formats are Base64 and PKCS12. Returns: dict: Rabb...
juraj-google-style
def torque_off(self): data = [] data.append(0x0A) data.append(self.servoid) data.append(RAM_WRITE_REQ) data.append(TORQUE_CONTROL_RAM) data.append(0x01) data.append(0x00) send_data(data)
Set the torques of Herkulex to zero In this mode, position control and velocity control will not work, enable torque before that. Also the servo shaft is freely movable Args: none
juraj-google-style
def _update_sample_weight_modes(self, sample_weights=None): if not self._is_compiled: return if sample_weights and any((s is not None for s in sample_weights)): for endpoint in self._training_endpoints: endpoint.sample_weight_mode = endpoint.sample_weight_mode or 'samplewise' els...
Updates sample weight modes based on training/eval inputs. Sample weight placeholders will be created for all or no outputs based on whether sample_weight is provided for any output. If model contains `_sample_weight_modes` we check if the input `sample_weights` corresponds to the sample weight modes. 1. Set sample w...
github-repos
def noisy_wrap(__func: Callable) -> Callable: def wrapper(*args, **kwargs): DebugPrint.enable() try: __func(*args, **kwargs) finally: DebugPrint.disable() return wrapper
Decorator to enable DebugPrint for a given function. Args: __func: Function to wrap Returns: Wrapped function
juraj-google-style
def get_mask_from_raster(rasterfile, outmaskfile, keep_nodata=False): raster_r = RasterUtilClass.read_raster(rasterfile) xsize = raster_r.nCols ysize = raster_r.nRows nodata_value = raster_r.noDataValue srs = raster_r.srs x_min = raster_r.xMin y_max = raster_r.yMax dx = raster_r.dx d...
Generate mask data from a given raster data. Args: rasterfile: raster file path. outmaskfile: output mask file path. Returns: Raster object of mask data.
codesearchnet
def delete(paths): if isinstance(paths, str): raise BeamIOError('Delete passed string argument instead of list: %s' % paths) if len(paths) == 0: return filesystem = FileSystems.get_filesystem(paths[0]) return filesystem.delete(paths)
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 Raises: ``BeamIOError``: if any of the delete operations fail
github-repos
def just_load_srno(srno, prm_filename=None): from cellpy import dbreader, filefinder print("just_load_srno: srno: %i" % srno) print("just_load_srno: making class and setting prms") d = CellpyData() print() print("just_load_srno: starting to load reader") ...
Simply load an dataset based on serial number (srno). This convenience function reads a dataset based on a serial number. This serial number (srno) must then be defined in your database. It is mainly used to check that things are set up correctly. Args: prm_filename: name of parameter file (optional). srno (int): ser...
juraj-google-style
def build_transcript(transcript_info, build='37'): try: transcript_id = transcript_info['ensembl_transcript_id'] except KeyError: raise KeyError('Transcript has to have ensembl id') build = build is_primary = transcript_info.get('is_primary', False) refseq_id = transcript_info.get('r...
Build a hgnc_transcript object Args: transcript_info(dict): Transcript information Returns: transcript_obj(HgncTranscript) { transcript_id: str, required hgnc_id: int, required build: str, required refseq_id: str, chrom: str, required start: int, required end: int, required is_primary: bool }
codesearchnet
def _definition_from_example(example): assert isinstance(example, dict) def _has_simple_type(value): accepted = (str, int, float, bool) return isinstance(value, accepted) definition = {'type': 'object', 'properties': {}} for (key, value) in example.items(): if (not _has_simple_t...
Generates a swagger definition json from a given example Works only for simple types in the dict Args: example: The example for which we want a definition Type is DICT Returns: A dict that is the swagger definition json
codesearchnet
def get_cross_attention_token_mask(input_ids: List[int], image_token_id: int) -> List[List[int]]: image_token_locations = [i for i, token in enumerate(input_ids) if token == image_token_id] if len(image_token_locations) == 0: return [] if len(image_token_locations) == 1: return [[image_token...
Generate a cross-attention token mask for image tokens in the input sequence. This function identifies the positions of image tokens in the input sequence and creates a mask that defines which subsequent tokens each image token should attend to. Args: input_ids (List[int]): A list of token ids representing the input ...
github-repos
def __init__(self, data_type=None): super(EventData, self).__init__() self.data_type = data_type self.offset = None self.query = None
Initializes an event data attribute container. Args: data_type (Optional[str]): event data type indicator.
juraj-google-style
def _ParseCredentialOptions(self, options): credentials = getattr(options, 'credentials', []) if not isinstance(credentials, list): raise errors.BadConfigOption('Unsupported credentials value.') for credential_string in credentials: credential_type, _, credential_data = credential_string.p...
Parses the credential options. Args: options (argparse.Namespace): command line arguments. Raises: BadConfigOption: if the options are invalid.
juraj-google-style
def uniprot_ec(uniprot_id): r = requests.post(('http: ec = r.content.decode('utf-8').splitlines()[1] if (len(ec) == 0): ec = None return ec
Retrieve the EC number annotation for a UniProt ID. Args: uniprot_id: Valid UniProt ID Returns:
codesearchnet
def validate_per_replica_inputs(distribution_strategy, x): per_replica_list = nest.flatten(x, expand_composites=True) x_values_list = [] for x in per_replica_list: x_values = distribution_strategy.unwrap(x) for value in x_values: if not tensor_util.is_tf_type(value): ...
Validates PerReplica dataset input list. Args: distribution_strategy: The current DistributionStrategy used to call `fit`, `evaluate` and `predict`. x: A list of PerReplica objects that represent the input or target values. Returns: List containing the first element of each of the PerReplica objects in the input list...
github-repos
def extract_example_parser_configuration(parse_example_op, sess): if parse_example_op.type == 'ParseExample': return _extract_from_parse_example(parse_example_op, sess) elif parse_example_op.type == 'ParseExampleV2': return _extract_from_parse_example_v2(parse_example_op, sess) else: ...
Returns an ExampleParserConfig proto. Args: parse_example_op: A ParseExample or ParseExampleV2 `Operation` sess: A tf.compat.v1.Session needed to obtain some configuration values. Returns: A ExampleParserConfig proto. Raises: ValueError: If attributes are inconsistent.
github-repos
def _get_or_create_eval_step(): graph = ops.get_default_graph() eval_steps = graph.get_collection(ops.GraphKeys.EVAL_STEP) if len(eval_steps) == 1: return eval_steps[0] elif len(eval_steps) > 1: raise ValueError('Multiple tensors added to tf.GraphKeys.EVAL_STEP') else: counte...
Gets or creates the eval step `Tensor`. Returns: A `Tensor` representing a counter for the evaluation step. Raises: ValueError: If multiple `Tensors` have been added to the `tf.GraphKeys.EVAL_STEP` collection.
github-repos
def execute_wait(self, cmd, walltime=2, envs={}): stdin, stdout, stderr = self.ssh_client.exec_command( self.prepend_envs(cmd, envs), bufsize=-1, timeout=walltime ) exit_status = stdout.channel.recv_exit_status() return exit_status, stdout.read().d...
Synchronously execute a commandline string on the shell. Args: - cmd (string) : Commandline string to execute - walltime (int) : walltime in seconds Kwargs: - envs (dict) : Dictionary of env variables Returns: - retcode : Return code from the execution, -1 on fail - stdout : stdout string - stderr : stderr string ...
juraj-google-style
def set_hostname(hostname): with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] return comp.Rename(Name=hostname)
Set the hostname of the windows minion, requires a restart before this will be updated. .. versionadded:: 2016.3.0 Args: hostname (str): The hostname to set Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_hostname newhostname
codesearchnet
def set_type(self, agent_type): type_str = SpawnAgentCommand.__type_keys[agent_type] self.add_string_parameters(type_str)
Set the type of agent to spawn in Holodeck. Currently accepted agents are: DiscreteSphereAgent, UAVAgent, and AndroidAgent. Args: agent_type (str): The type of agent to spawn.
juraj-google-style
def assert_raises_regex(expected_exception, expected_regex, extras=None, *args, **kwargs): context = _AssertRaisesContext(expected_exception, expected_regex, extras=extras) return context
Assert that an exception is raised when a function is called. If no exception is raised, test fail. If an exception is raised but not of the expected type, the exception is let through. If an exception of the expected type is raised but the error message does not match the expected_regex, test fail. This should only ...
github-repos
def data_group_association(self, xid): groups = [] group_data = None if (self.groups.get(xid) is not None): group_data = self.groups.get(xid) del self.groups[xid] elif (self.groups_shelf.get(xid) is not None): group_data = self.groups_shelf.get(xid) del self.groups_shelf[...
Return group dict array following all associations. Args: xid (str): The xid of the group to retrieve associations. Returns: list: A list of group dicts.
codesearchnet
def get_symbol(self, symbol): self._ensure_symbols_loaded() if type(symbol) is int: return self._symbols_by_index[symbol] else: return self._symbols_by_name[symbol]
Get a specific symbol by index or name. Args: symbol(int or str): The index or name of the symbol to return. Returns: ELF.Symbol: The symbol. Raises: KeyError: The requested symbol does not exist.
juraj-google-style
def update(self, uid: int, flag_set: Iterable[Flag], op: FlagOp = FlagOp.REPLACE) -> FrozenSet[Flag]: orig_set = self._flags.get(uid, frozenset()) new_flags = op.apply(orig_set, self & flag_set) if new_flags: self._flags[uid] = new_flags else: ...
Update the flags for the session, returning the resulting flags. Args: uid: The message UID value. flag_set: The set of flags for the update operation. op: The type of update.
juraj-google-style
def _UpdateEtag(self, response): etag = response.headers.get('etag', self.etag) etag_updated = (self.etag != etag) self.etag = etag return etag_updated
Update the etag from an API response. Args: response: HTTP response with a header field. Returns: bool, True if the etag in the response header updated.
codesearchnet
def ParseOptions(cls, options, configuration_object): if not isinstance(configuration_object, tools.CLITool): raise errors.BadConfigObject( 'Configuration object is not an instance of CLITool') number_of_extraction_workers = cls._ParseNumericOption( options, 'workers', default_valu...
Parses and validates options. Args: options (argparse.Namespace): parser options. configuration_object (CLITool): object to be configured by the argument helper. Raises: BadConfigObject: when the configuration object is of the wrong type. BadConfigOption: when a configuration parameter fails validation.
juraj-google-style
def array_view(array, slicing=None, mapping=None): dtype = translate_dtype(array.dtype) sliced_array = (array[command_parser._parse_slices(slicing)] if slicing else array) if (np.isscalar(sliced_array) and (str(dtype) == 'string')): ndims = len(array.shape) slice_shape = [] for _ in ...
View a slice or the entirety of an ndarray. Args: array: The input array, as an numpy.ndarray. slicing: Optional slicing string, e.g., "[:, 1:3, :]". mapping: Optional mapping string. Supported mappings: `None` or case-insensitive `'None'`: Unmapped nested list. `'image/png'`: Image encoding of a 2D sliced array or 3D...
codesearchnet
def trace(self, graph_element_name): self._depth_count += 1 node_name = get_node_name(graph_element_name) if node_name == self._destination_node_name: raise GraphTracingReachedDestination() if node_name in self._skip_node_names: return if node_name in self._visited_nodes: ret...
Trace inputs. Args: graph_element_name: Name of the node or an output tensor of the node, as a str. Raises: GraphTracingReachedDestination: if destination_node_name of this tracer object is not None and the specified node is reached.
github-repos
def pretty_dump(fn): @wraps(fn) def pretty_dump_wrapper(*args, **kwargs): response.content_type = "application/json; charset=utf-8" return json.dumps( fn(*args, **kwargs), indent=4, separators=(',', ': ') ) return pretty_dump_w...
Decorator used to output prettified JSON. ``response.content_type`` is set to ``application/json; charset=utf-8``. Args: fn (fn pointer): Function returning any basic python data structure. Returns: str: Data converted to prettified JSON.
juraj-google-style
def dispatch(self, event): if event.is_directory: return paths = [] if has_attribute(event, 'dest_path'): paths.append(os.path.realpath( unicode_paths.decode(event.dest_path))) if event.src_path: paths.append(os.path.realpath( ...
Only dispatch if the event does not correspond to an ignored file. Args: event (watchdog.events.FileSystemEvent)
juraj-google-style
def psd(data, dt, ndivide=1, window=hanning, overlap_half=False): logger = getLogger('decode.utils.ndarray.psd') if overlap_half: step = int(len(data) / (ndivide + 1)) size = step * 2 else: step = int(len(data) / ndivide) size = step if bin(len(data)).count('1') !=...
Calculate power spectrum density of data. Args: data (np.ndarray): Input data. dt (float): Time between each data. ndivide (int): Do averaging (split data into ndivide, get psd of each, and average them). ax (matplotlib.axes): Axis you want to plot on. doplot (bool): Plot how averaging works. overlap_half (bool): Spli...
juraj-google-style
def __init__(self, compression_method=None, parent=None, **kwargs): if not compression_method or not parent: raise ValueError('Missing compression method or parent value.') super(CompressedStreamPathSpec, self).__init__(parent=parent, **kwargs) self.compression_method = compression_method
Initializes a path specification. Note that the compressed stream path specification must have a parent. Args: compression_method (Optional[str]): method used to the compress the data. parent (Optional[PathSpec]): parent path specification. Raises: ValueError: when compression method or parent are not set.
juraj-google-style
def _from_string(cls, serialized): if ':' not in serialized: raise InvalidKeyError( "BlockTypeKeyV1 keys must contain ':' separating the block family from the block_type.", serialized) family, __, block_type = serialized.partition(':') return cls(family, bloc...
Return an instance of `cls` parsed from its `serialized` form. Args: cls: The :class:`OpaqueKey` subclass. serialized (unicode): A serialized :class:`OpaqueKey`, with namespace already removed. Raises: InvalidKeyError: Should be raised if `serialized` is not a valid serialized key understood by `cls`.
juraj-google-style
def get_block_entity_data(self, pos_or_x, y=None, z=None): if (None not in (y, z)): pos_or_x = (pos_or_x, y, z) coord_tuple = tuple((int(floor(c)) for c in pos_or_x)) return self.block_entities.get(coord_tuple, None)
Access block entity data. Returns: BlockEntityData subclass instance or None if no block entity data is stored for that location.
codesearchnet
def feature_info(self): feature_list = self.prop('available-features-list', None) if (feature_list is None): raise ValueError(('Firmware features are not supported on CPC %s' % self.name)) return feature_list
Returns information about the features available for this CPC. Authorization requirements: * Object-access permission to this CPC. Returns: :term:`iterable`: An iterable where each item represents one feature that is available for this CPC. Each item is a dictionary with the following items: * `name` (:term:`unic...
codesearchnet
def total_duration(utterances: List[Utterance]) -> int: return sum([duration(utter) for utter in utterances])
Get the duration of an entire list of utterances in milliseconds Args: utterances: The list of utterance we are finding the duration of
juraj-google-style
def get_input_info_dict(self, signature=None): return self._spec.get_input_info_dict(signature=signature, tags=self._tags)
Describes the inputs required by a signature. Args: signature: A string with the signature to get inputs information for. If None, the default signature is used if defined. Returns: The result of ModuleSpec.get_input_info_dict() for the given signature, and the graph variant selected by `tags` when this Module was in...
juraj-google-style
def __call__(self, input_values, attention_mask=None, mask_time_indices=None, gumbel_temperature: int=1, deterministic: bool=True, output_attentions=None, output_hidden_states=None, freeze_feature_encoder=False, return_dict=None): return_dict = return_dict if return_dict is not None else self.config.use_return_dict...
Returns: Example: ```python ```
github-repos
def true_num_reactions(model, custom_spont_id=None): true_num = 0 for rxn in model.reactions: if (len(rxn.genes) == 0): continue if ((len(rxn.genes) == 1) and is_spontaneous(list(rxn.genes)[0], custom_id=custom_spont_id)): continue else: true_num += 1 ...
Return the number of reactions associated with a gene. Args: model (Model): custom_spont_id (str): Optional custom spontaneous ID if it does not match the regular expression ``[Ss](_|)0001`` Returns: int: Number of reactions associated with a gene
codesearchnet
def _normalize_string(raw_str): return " ".join( token.strip() for token in tokenizer.encode(text_encoder.native_to_unicode(raw_str)))
Normalizes the string using tokenizer.encode. Args: raw_str: the input string Returns: A string which is ready to be tokenized using split()
juraj-google-style
def random_unitary_matrix(num_qubits): hermitian_matrix = random_hermitian_matrix(num_qubits) return tf.linalg.expm(-1j * hermitian_matrix)
Returns a random unitary matrix. Uses the property that e^{-iH} is unitary for any Hermitian matrix H. Args: num_qubits: Number of qubits on which the matrix acts.
github-repos
def isUserCert(self, name): crtpath = self._getPathJoin('users', ('%s.crt' % name)) return os.path.isfile(crtpath)
Checks if a user certificate exists. Args: name (str): The name of the user keypair. Examples: Check if the user cert "myuser" exists: exists = cdir.isUserCert('myuser') Returns: bool: True if the certificate is present, False otherwise.
codesearchnet
def _module_to_paths(module): submodules = [] module_segments = module.split('.') for i in range(len(module_segments)): submodules.append('.'.join(module_segments[:i + 1])) paths = [] for submodule in submodules: if not submodule: paths.append('__init__.py') c...
Get all API __init__.py file paths for the given module. Args: module: Module to get file paths for. Returns: List of paths for the given module. For e.g. module foo.bar requires 'foo/__init__.py' and 'foo/bar/__init__.py'.
github-repos
def disease_term(self, disease_identifier): query = {} try: disease_identifier = int(disease_identifier) query['disease_nr'] = disease_identifier except ValueError: query['_id'] = disease_identifier return self.disease_term_collection.find_on...
Return a disease term Checks if the identifier is a disease number or a id Args: disease_identifier(str) Returns: disease_obj(dict)
juraj-google-style
def distance_similarity(a, b, p, T=CLOSE_DISTANCE_THRESHOLD): d = distance_to_line(a, b, p) r = (-1/float(T)) * abs(d) + 1 return r if r > 0 else 0
Computes the distance similarity between a line segment and a point Args: a ([float, float]): x and y coordinates. Line start b ([float, float]): x and y coordinates. Line end p ([float, float]): x and y coordinates. Point to compute the distance Returns: float: between 0 and 1. Where 1 is very similar and 0 is comple...
juraj-google-style
class QuantLinear(nn.Module): def __init__(self, in_features, out_features, bias=True, weight_bit=8, bias_bit=32, per_channel=False, quant_mode=False): super().__init__() self.in_features = in_features self.out_features = out_features self.weight = nn.Parameter(torch.zeros([out_feat...
Quantized version of `torch.nn.Linear`. Adds quantization-specific arguments on top of `torch.nn.Linear`. Args: weight_bit (`int`, *optional*, defaults to `8`): Bitwidth for the quantized weight. bias_bit (`int`, *optional*, defaults to `32`): Bitwidth for the quantized bias. per_channel (`bool`, *optional*, defaults ...
github-repos
def ParseIfaddrs(ifaddrs): precondition.AssertOptionalType(ifaddrs, ctypes.POINTER(Ifaddrs)) ifaces = {} for ifaddr in IterIfaddrs(ifaddrs): ifname = ctypes.string_at(ifaddr.ifa_name).decode("utf-8") iface = ifaces.setdefault(ifname, rdf_client_network.Interface()) iface.ifname = ifname if n...
Parses contents of the intrusive linked list of `ifaddrs`. Args: ifaddrs: A pointer to the first node of `ifaddrs` linked list. Can be NULL. Returns: An iterator over instances of `rdf_client_network.Interface`.
juraj-google-style
def _unverified_decode(token): token = _helpers.to_bytes(token) if (token.count(b'.') != 2): raise ValueError('Wrong number of segments in token: {0}'.format(token)) (encoded_header, encoded_payload, signature) = token.split(b'.') signed_section = ((encoded_header + b'.') + encoded_payload) ...
Decodes a token and does no verification. Args: token (Union[str, bytes]): The encoded JWT. Returns: Tuple[str, str, str, str]: header, payload, signed_section, and signature. Raises: ValueError: if there are an incorrect amount of segments in the token.
codesearchnet
def orient_undirected_graph(self, data, graph, **kwargs): self.arguments['{CITEST}'] = self.dir_CI_test[self.CI_test] self.arguments['{METHOD_INDEP}'] = self.dir_method_indep[self.method_indep] self.arguments['{DIRECTED}'] = 'TRUE' self.arguments['{ALPHA}'] = str(self.alpha) self.arguments['{NJOBS}'...
Run PC on an undirected graph. Args: data (pandas.DataFrame): DataFrame containing the data graph (networkx.Graph): Skeleton of the graph to orient Returns: networkx.DiGraph: Solution given by PC on the given skeleton.
codesearchnet