code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def show_bokehjs(bokehjs_action, develop=False): print() if develop: print('Installed Bokeh for DEVELOPMENT:') else: print('Installed Bokeh:') if (bokehjs_action in ['built', 'installed']): print((' - using %s built BokehJS from bokehjs/build\n' % (bright(yellow('NEWLY')) if (bo...
Print a useful report after setuptools output describing where and how BokehJS is installed. Args: bokehjs_action (str) : one of 'built', 'installed', or 'packaged' how (or if) BokehJS was installed into the python source tree develop (bool, optional) : whether the command was for "develop" mode (default: False) Ret...
codesearchnet
def parse_unique_urlencoded(content): urlencoded_params = urllib.parse.parse_qs(content) params = {} for key, value in six.iteritems(urlencoded_params): if len(value) != 1: msg = ('URL-encoded content contains a repeated value:' '%s -> %s' % (key, ', '.join(value)...
Parses unique key-value parameters from urlencoded content. Args: content: string, URL-encoded key-value pairs. Returns: dict, The key-value pairs from ``content``. Raises: ValueError: if one of the keys is repeated.
juraj-google-style
def get_decomposition_energy(self, entry, pH, V): if (self._multielement and (not isinstance(entry, MultiEntry))): possible_entries = self._generate_multielement_entries(self._filtered_entries, forced_include=[entry]) if (entry.phase_type == 'solid'): possible_entries = [e for e in possi...
Finds decomposition to most stable entry Args: entry (PourbaixEntry): PourbaixEntry corresponding to compound to find the decomposition for pH (float): pH at which to find the decomposition V (float): voltage at which to find the decomposition Returns: reaction corresponding to the decomposition
codesearchnet
def _ReadIntegerDataTypeDefinition(self, definitions_registry, definition_values, definition_name, is_member=False): definition_object = self._ReadFixedSizeDataTypeDefinition(definitions_registry, definition_values, data_types.IntegerDefinition, definition_name, self._SUPPORTED_ATTRIBUTES_INTEGER, is_member=is_memb...
Reads an integer data type definition. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. definition_values (dict[str, object]): definition values. definition_name (str): name of the definition. is_member (Optional[bool]): True if the data type definition is a member data type de...
codesearchnet
def load(self, *modules): for module in modules: if isinstance(module, six.string_types): try: module = get_object(module) except Exception as e: self.errors[module] = e continue self.mod...
Load one or more modules. Args: modules: Either a string full path to a module or an actual module object.
juraj-google-style
def case(store, institute_obj, case_obj): case_obj['individual_ids'] = [] for individual in case_obj['individuals']: try: sex = int(individual.get('sex', 0)) except ValueError as err: sex = 0 individual['sex_human'] = SEX_MAP[sex] pheno_map = PH...
Preprocess a single case. Prepare the case to be displayed in the case view. Args: store(adapter.MongoAdapter) institute_obj(models.Institute) case_obj(models.Case) Returns: data(dict): includes the cases, how many there are and the limit.
juraj-google-style
def convert_squeeze(params, w_name, scope_name, inputs, layers, weights, names): print('Converting squeeze ...') if len(params['axes']) > 1: raise AssertionError('Cannot convert squeeze by multiple dimensions') def target_layer(x, axis=int(params['axes'][0])): import tensorflow as tf ...
Convert squeeze operation. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for keras layers
juraj-google-style
def Render(self): xs = [self.xs[0]] ps = [0.0] for (i, p) in enumerate(self.ps): xs.append(self.xs[i]) ps.append(p) try: xs.append(self.xs[(i + 1)]) ps.append(p) except IndexError: pass return (xs, ps)
Generates a sequence of points suitable for plotting. An empirical CDF is a step function; linear interpolation can be misleading. Returns: tuple of (xs, ps)
codesearchnet
def gradient_tensors(self): return self._gradient_tensors
Get the gradient tensors that this object is aware of. Returns: A dict mapping x-tensor names to gradient tensor objects. x-tensor refers to the tensors on the denominator of the differentation.
github-repos
def RemoveEventAttribute(self, attribute_name): if attribute_name not in self._extra_event_attributes: raise KeyError('Event attribute: {0:s} not set'.format(attribute_name)) del self._extra_event_attributes[attribute_name]
Removes an attribute from being set on all events produced. Args: attribute_name (str): name of the attribute to remove. Raises: KeyError: if the event attribute is not set.
juraj-google-style
def handle_encodnig(html): encoding = _get_encoding(dhtmlparser.parseString(html.split('</head>')[0])) if (encoding == 'utf-8'): return html return html.decode(encoding).encode('utf-8')
Look for encoding in given `html`. Try to convert `html` to utf-8. Args: html (str): HTML code as string. Returns: str: HTML code encoded in UTF.
codesearchnet
def list_merge(list_a, list_b): result = [] for item in list_a: if not item in result: result.append(item) for item in list_b: if not item in result: result.append(item) return result
Merge two lists without duplicating items Args: list_a: list list_b: list Returns: New list with deduplicated items from list_a and list_b
juraj-google-style
def pop(self, rebuild=True): layer = self._layers.pop() self.built = False self._functional = None if rebuild: self._maybe_rebuild() return layer
Removes the last layer in the model. Args: rebuild: `bool`. Whether to rebuild the model after removing the layer. Defaults to `True`. Returns: layer: layer instance.
github-repos
def add_input(self, input_): if (not isinstance(input_, Input)): raise TypeError('`input_` must be a Input instance') self.inputs.append(input_)
Adds an input to a Transaction's list of inputs. Args: input_ (:class:`~bigchaindb.common.transaction. Input`): An Input to be added to the Transaction.
codesearchnet
def wc(filename, contents, parsed=None, is_jekyll=False): if is_jekyll: fmt = 'jekyll' else: fmt = 'md/txt' body = parsed.strip() if parsed else contents.strip() words = re.sub(r'\s+', ' ', body, re.MULTILINE) for punctuation in INTERSTITIAL_PUNCTUATION: words = re...
Count the words, characters, and paragraphs in a string. Args: contents: the original string to count filename (optional): the filename as provided to the CLI parsed (optional): a parsed string, expected to be plaintext only is_jekyll: whether the original contents were from a Jekyll file Returns: An object containin...
juraj-google-style
def iter_packages(name, range_=None, paths=None): entries = _get_families(name, paths) seen = set() for (repo, family_resource) in entries: for package_resource in repo.iter_packages(family_resource): key = (package_resource.name, package_resource.version) if (key in seen): ...
Iterate over `Package` instances, in no particular order. Packages of the same name and version earlier in the search path take precedence - equivalent packages later in the paths are ignored. Packages are not returned in any specific order. Args: name (str): Name of the package, eg 'maya'. range_ (VersionRange or st...
codesearchnet
def resource(self, resource_type): try: resource = getattr(self.resources, self.safe_rt(resource_type))(self) except AttributeError: self._resources(True) resource = getattr(self.resources, self.safe_rt(resource_type))(self) return resource
Get instance of Resource Class with dynamic type. Args: resource_type: The resource type name (e.g Adversary, User Agent, etc). Returns: (object): Instance of Resource Object child class.
codesearchnet
def process(self, element, *args, **kwargs): (text, uid), prediction = element embedding = prediction.inference l2_norm = np.linalg.norm(embedding) yield {'text': text, 'id': uid, 'embedding': embedding / l2_norm}
For each element in the input PCollection, normalize the embedding vector, and yield a new element with the normalized embedding added Args: element: The element to be processed.
github-repos
def easeOutBack(n, s=1.70158): _checkRange(n) n = (n - 1) return (((n * n) * (((s + 1) * n) + s)) + 1)
A tween function that overshoots the destination a little and then backs into the destination. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
codesearchnet
def swapdim(P, dim1=1, dim2=0): if (not isinstance(P, Poly)): return numpy.swapaxes(P, dim1, dim2) dim = P.dim shape = P.shape dtype = P.dtype if (dim1 == dim2): return P m = max(dim1, dim2) if (P.dim <= m): P = chaospy.poly.dimension.setdim(P, (m + 1)) dim = ...
Swap the dim between two variables. Args: P (Poly): Input polynomial. dim1 (int): First dim dim2 (int): Second dim. Returns: (Poly): Polynomial with swapped dimensions. Examples: >>> x,y = variable(2) >>> P = x**4-y >>> print(P) q0^4-q1 >>> print(swapdim(P)) q1^4-q0
codesearchnet
def enable_collective_ops(self, server_def): if not server_def: raise ValueError('server_def is None.') self._collective_ops_server_def = server_def if self._context_handle is not None: logging.warning('Enabling collective ops after program startup may cause error when accessing previously c...
Enable distributed collective ops with an appropriate server_def. Args: server_def: A tensorflow::ServerDef proto. Enables execution on remote devices. Raises: ValueError: if server_def is None. RuntimeError: if this method is not called at program startup.
github-repos
def _get_generated_ngrams(banned_ngrams, prev_input_ids, ngram_size, cur_len): start_idx = cur_len + 1 - ngram_size ngram_idx = tuple(prev_input_ids[start_idx:cur_len].tolist()) return banned_ngrams.get(ngram_idx, [])
Determines the banned tokens for the current hypothesis based on previously generated n-grams. Args: banned_ngrams (`dict`): A dictionary containing previously generated n-grams for each hypothesis. prev_input_ids (`torch.Tensor`): Generated token ids for the current hypothesis. ngram_size (`int`): The number sequenti...
github-repos
def _assert_validators(self, validators): for validator in sorted( validators, key=lambda validator: validator.insertion_index): try: validator.verify(self) except _exceptions.ValidationError as e: message = validator.print_flags_with_values(self) raise _exceptions.I...
Asserts if all validators in the list are satisfied. It asserts validators in the order they were created. Args: validators: Iterable(validators.Validator), validators to be verified. Raises: AttributeError: Raised if validators work with a non-existing flag. IllegalFlagValueError: Raised if validation fails for at l...
juraj-google-style
def create_parser(default_name: str) -> argparse.ArgumentParser: argparser = argparse.ArgumentParser(fromfile_prefix_chars='@') argparser.add_argument('-H', '--host', help='Host to which the app binds. [%(default)s]', default='0.0.0.0') argparser.ad...
Creates the default brewblox_service ArgumentParser. Service-agnostic arguments are added. The parser allows calling code to add additional arguments before using it in create_app() Args: default_name (str): default value for the --name commandline argument. Returns: argparse.ArgumentParser: a Python ArgumentParser ...
juraj-google-style
def set_pair(self, term1, term2, value, **kwargs): key = self.key(term1, term2) self.keys.update([term1, term2]) self.pairs[key] = value
Set the value for a pair of terms. Args: term1 (str) term2 (str) value (mixed)
codesearchnet
def __init__(self, coords): self._coords = np.array(coords) self.simplex_dim, self.space_dim = self._coords.shape self.origin = self._coords[-1] if self.simplex_dim == self.space_dim + 1: self.T = self._coords[:-1] - self.origin self.T_inv = ...
Initializes a Simplex from vertex coordinates. Args: coords ([[float]]): Coords of the vertices of the simplex. E.g., [[1, 2, 3], [2, 4, 5], [6, 7, 8], [8, 9, 10].
juraj-google-style
def summary(self, fmt=None, initial=True, default=''): if (default and (not self.__dict__)): return default if (fmt == ''): return default keys = [k for (k, v) in self.__dict__.items() if (v is not '')] f = (fmt or (('{' + '}, {'.join(keys)) + '}')) try: summary = CustomForma...
Given a format string, return a summary description of a component. Args: component (dict): A component dictionary. fmt (str): Describes the format with a string. If no format is given, you will just get a list of attributes. If you give the empty string (''), you'll get `default` back. By default this gives you the e...
codesearchnet
def script_dir_plus_file(filename, pyobject, follow_symlinks=True): return join(script_dir(pyobject, follow_symlinks), filename)
Get current script's directory and then append a filename Args: filename (str): Filename to append to directory path pyobject (Any): Any Python object in the script follow_symlinks (Optional[bool]): Follow symlinks or not. Defaults to True. Returns: str: Current script's directory and with filename appended
juraj-google-style
def join(self, *data: Iterable[MaybeBytes]) -> bytes: return self.how.join([bytes(item) for item in chain(*data)])
Iterable join on a delimiter. Args: data: Iterable of items to join. Examples: :: BytesFormat(b' ').join([b'one', b'two', b'three'])
codesearchnet
def export(self, top=True): out = [] if top: out.append(self._internal_name) out.append(self._to_str(self.year)) out.append(self._to_str(self.month)) out.append(self._to_str(self.day)) out.append(self._to_str(self.hour)) out.append(self._to_st...
Exports object to its string representation. Args: top (bool): if True appends `internal_name` before values. All non list objects should be exported with value top=True, all list objects, that are embedded in as fields inlist objects should be exported with `top`=False Returns: str: The objects string representatio...
juraj-google-style
def ParseDestList(self, parser_mediator, olecf_item): header_map = self._GetDataTypeMap('dest_list_header') try: (header, entry_offset) = self._ReadStructureFromFileObject(olecf_item, 0, header_map) except (ValueError, errors.ParseError) as exception: raise errors.UnableToParseFile('Unable t...
Parses the DestList OLECF item. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. olecf_item (pyolecf.item): OLECF item. Raises: UnableToParseFile: if the DestList cannot be parsed.
codesearchnet
def preprocess(self, xs): return [self.nesting_field.preprocess(x) for x in super(NestedField, self).preprocess(xs)]
Preprocess a single example. Firstly, tokenization and the supplied preprocessing pipeline is applied. Since this field is always sequential, the result is a list. Then, each element of the list is preprocessed using ``self.nesting_field.preprocess`` and the resulting list is returned. Arguments: xs (list or str): Th...
codesearchnet
def write(self, name, **data): data["name"] = name if not ("timestamp" in data): data["timestamp"] = datetime.utcnow() try: self.client.index( index=self.get_index(), doc_type=self.doc_type, id=None, ...
Write the metric to elasticsearch Args: name (str): The name of the metric to write data (dict): Additional data to store with the metric
juraj-google-style
def call(self, hidden_states: tf.Tensor, prev_group_token: tf.Tensor | None=None, output_attentions: bool=False, training: bool=False) -> Tuple[tf.Tensor]: if self.with_group_token: group_token = tf.tile(self.group_token, multiples=(shape_list(hidden_states)[0], 1, 1)) if self.group_projector is not...
Args: hidden_states (`tf.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`tf.Tensor`): attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. `(config.encoder_attention_heads,)`. output_attentions (`bool`, *optional*)...
github-repos
def __init__(self, num_packs=1): if num_packs <= 0: raise ValueError('num_packs must be greater than zero.') self.num_packs = num_packs
Initialize the _ConcatAndSplitPacker object. Args: num_packs: specifies the number of split packs that will be formed. Raises: ValueError: if num_packs is not greater than 0.
github-repos
def requires_swimlane_version(min_version=None, max_version=None): if ((min_version is None) and (max_version is None)): raise ValueError('Must provide either min_version, max_version, or both') if (min_version and max_version and (compare_versions(min_version, max_version) < 0)): raise ValueErr...
Decorator for SwimlaneResolver methods verifying Swimlane server build version is within a given inclusive range Raises: InvalidVersion: Raised before decorated method call if Swimlane server version is out of provided range ValueError: If neither min_version or max_version were provided, or if those values conflict (...
codesearchnet
def remove_metric(self, metric_name): with self._lock: metric = self._metrics.pop(metric_name, None) if metric: for reporter in self._reporters: reporter.metric_removal(metric) return metric
Remove a metric if it exists and return it. Return None otherwise. If a metric is removed, `metric_removal` will be invoked for each reporter. Arguments: metric_name (MetricName): The name of the metric Returns: KafkaMetric: the removed `KafkaMetric` or None if no such metric exists
juraj-google-style
def set_examples(self, examples): self.store('examples', examples) if len(examples) > 0: self.store('are_sequence_examples', isinstance(examples[0], tf.train.SequenceExample)) return self
Sets the examples to be displayed in WIT. Args: examples: List of example protos. Returns: self, in order to enabled method chaining.
juraj-google-style
def get_mem_usage(**kwargs): try: con_mem_data_list = con._client.get_memory(session=kwargs['con']._session, memory_level=kwargs['mem_type']) usedram = 0 freeram = 0 for con_mem_data in con_mem_data_list: page_size = con_mem_data.page_size node_memory_data_lis...
Calculates memory statistics from mapd_server _client.get_memory call Kwargs: con(class 'pymapd.connection.Connection'): Mapd connection mem_type(str): [gpu, cpu] Type of memory to gather metrics for Returns: ramusage(dict)::: usedram(float): Amount of memory (in MB) used freeram(float): Amount of memory (in MB) free...
codesearchnet
def select_inputs(self, address, nfees, ntokens, min_confirmations=6): unspents = self._t.get(address, min_confirmations=min_confirmations)['unspents'] unspents = [u for u in unspents if u not in self._spents.queue] if len(unspents) == 0: raise Exception("No spendable output...
Selects the inputs for the spool transaction. Args: address (str): bitcoin address to select inputs for nfees (int): number of fees ntokens (int): number of tokens min_confirmations (Optional[int]): minimum number of required confirmations; defaults to 6
juraj-google-style
def _compile_graphql_generic(language, lowering_func, query_emitter_func, schema, graphql_string, type_equivalence_hints, compiler_metadata): ir_and_metadata = graphql_to_ir(schema, graphql_string, type_equivalence_hints=type_equivalence_hints) lowered_ir_blocks = lowering_func(ir_and_metadata.ir_blocks, ir_and...
Compile the GraphQL input, lowering and emitting the query using the given functions. Args: language: string indicating the target language to compile to. lowering_func: Function to lower the compiler IR into a compatible form for the target language backend. query_emitter_func: Function that emits a query in the targ...
codesearchnet
def object_metadata(save_path): reader = py_checkpoint_reader.NewCheckpointReader(save_path) try: object_graph_string = reader.get_tensor(base.OBJECT_GRAPH_PROTO_KEY) except errors_impl.NotFoundError: raise ValueError(f'The specified checkpoint "{save_path}" does not appear to be object-base...
Retrieves information about the objects in a checkpoint. Example usage: ```python object_graph = tf.contrib.checkpoint.object_metadata( tf.train.latest_checkpoint(checkpoint_directory)) ckpt_variable_names = set() for node in object_graph.nodes: for attribute in node.attributes: ckpt_variable_names.add(attribute.full...
github-repos
def get_individuals(variant_source, case_lines=None, case_type='ped', variant_mode='vcf'): individuals = [] ind_dict ={} if variant_mode == 'vcf': head = get_header(variant_source) for index, ind in enumerate(head.individuals): ind_...
Get the individuals from a vcf file, gemini database, and/or a ped file. Args: variant_source (str): Path to a variant source case_lines(Iterable): Ped like lines case_type(str): Format of ped lines Returns: individuals (generator): generator with Individuals
juraj-google-style
def _indexed_case_helper(branch_fns, default, branch_index, name, lower_using_switch_merge=None): branch_fns = _indexed_case_verify_and_canonicalize_args(branch_fns, default, branch_index) with ops.name_scope(name, 'case', [branch_index]): if context.executing_eagerly() and (not hasattr(branch_index, 'g...
Implementation of case that emits the n-way indexed Case op. Args: branch_fns: Dict or list of pairs of a boolean scalar tensor, and a callable which returns a list of tensors. default: Optional callable that returns a list of tensors. branch_index: Optional int `Tensor`, which selects for the corresponding pred_fn_pa...
github-repos
def print_stack_events(self): first_token = '7be7981bd6287dd8112305e8f3822a6f' keep_going = True next_token = first_token current_request_token = None rows = [] try: while keep_going and next_token: if next_token == first_token: ...
List events from the given stack Args: None Returns: None
juraj-google-style
def _with_dependencies(self, dependencies): new_row_splits = control_flow_ops.with_dependencies(dependencies, self._row_splits) return RowPartition(row_splits=new_row_splits, row_lengths=self._row_lengths, value_rowids=self._value_rowids, nrows=self._nrows, uniform_row_length=self._uniform_row_length, internal=...
Returns a new RowPartition equal to self with control dependencies. Specifically, self._row_splits is gated by the given control dependencies. Used to add sanity checks to the constructors. Args: dependencies: a list of tensors to use as dependencies. Returns: A new RowPartition object.
github-repos
def get_atom_map(structure): syms = [site.specie.symbol for site in structure] unique_pot_atoms = [] [unique_pot_atoms.append(i) for i in syms if not unique_pot_atoms.count(i)] atom_map = {} for i, atom in enumerate(unique_pot_atoms): atom_map[atom] = i + 1 return atom_map
Returns a dict that maps each atomic symbol to a unique integer starting from 1. Args: structure (Structure) Returns: dict
juraj-google-style
def emit_counters(self, category, name, pid, timestamp, counters): event = self._create_event('C', category, name, pid, 0, timestamp) event['args'] = counters.copy() self._events.append(event)
Emits a counter record for the dictionary 'counters'. Args: category: The event category as a string. name: The event name as a string. pid: Identifier of the process generating this event as an integer. timestamp: The timestamp of this event as a long integer. counters: Dictionary of counter values.
github-repos
def create_tracker(self, restriction): raise NotImplementedError
Produces a new ``RestrictionTracker`` for the given restriction. This API is required to be implemented. Args: restriction: an object that defines a restriction as identified by a Splittable ``DoFn`` that utilizes the current ``RestrictionProvider``. For example, a tuple that gives a range of positions for a Splittab...
github-repos
async def claim_work(context): log.debug("Calling claimWork...") payload = { 'workerGroup': context.config['worker_group'], 'workerId': context.config['worker_id'], 'tasks': 1, } try: return await context.queue.claimWork( context.config[...
Find and claim the next pending task in the queue, if any. Args: context (scriptworker.context.Context): the scriptworker context. Returns: dict: a dict containing a list of the task definitions of the tasks claimed.
juraj-google-style
def siblings(self, as_resources=False): siblings = set() for parent in self.parents(as_resources=True): for sibling in parent.children(as_resources=as_resources): siblings.add(sibling) if as_resources: siblings.remove(self) if (not as_resources): siblings.remove(self....
method to return hierarchical siblings of this resource. Args: as_resources (bool): if True, opens each as appropriate resource type instead of return URI only Returns: (list): list of resources
codesearchnet
def make_access_request(self): del self.issued_at assertion = b'.'.join((self.header(), self.claims(), self.signature())) post_data = {'grant_type': GRANT_TYPE, 'assertion': assertion} resp = requests.post(AUDIENCE, post_data) if (resp.status_code != 200): raise AuthenticationError(resp) ...
Makes an OAuth2 access token request with crafted JWT and signature. The core of this module. Based on arguments it creates proper JWT for you and signs it with supplied private key. Regardless of present valid token, it always clears ``issued_at`` property, which in turn results in requesting fresh OAuth2 access toke...
codesearchnet
def get_overall_services_health(self) -> str: services_health_status = self.get_services_health() health_status = all(((status == 'Healthy') for status in services_health_status.values())) if health_status: overall_status = 'Healthy' else: overall_status = 'Unhealthy' return overall_...
Get the overall health of all the services. Returns: str, overall health status
codesearchnet
def _parse_device(s: str) -> Tuple[(List[GridQubit], Dict[(str, Set[GridQubit])])]: lines = s.strip().split('\n') qubits = [] measurement_lines = {} for (row, line) in enumerate(lines): for (col, c) in enumerate(line.strip()): if (c != '-'): qubit = GridQubit(row, col...
Parse ASCIIart device layout into info about qubits and connectivity. Args: s: String representing the qubit layout. Each line represents a row, and each character in the row is a qubit, or a blank site if the character is a hyphen '-'. Different letters for the qubit specify which measurement line that qubit is conne...
codesearchnet
def _PrepareAttributeContainer(self, attribute_container): attribute_values_hash = hash(attribute_container.GetAttributeValuesString()) identifier = identifiers.FakeIdentifier(attribute_values_hash) attribute_container.SetIdentifier(identifier) return copy.deepcopy(attribute_container)
Prepares an attribute container for storage. Args: attribute_container (AttributeContainer): attribute container. Returns: AttributeContainer: copy of the attribute container to store in the fake storage.
juraj-google-style
def _get_connection_state(self, conn_or_int_id): key = conn_or_int_id if isinstance(key, str): table = self._int_connections elif isinstance(key, int): table = self._connections else: raise ArgumentError('You must supply either an int connection id or a string internal id to _get...
Get a connection's state by either conn_id or internal_id This routine must only be called from the internal worker thread. Args: conn_or_int_id (int, string): The external integer connection id or and internal string connection id
codesearchnet
def _encode_dict_as_row(record, column_name_map): for k in list(record.keys()): v = record[k] if (isinstance(v, pandas.Timestamp) or isinstance(v, datetime.datetime)): v = record[k] = record[k].isoformat() if (k not in column_name_map): column_name_map[k] = ''.join((c...
Encode a dictionary representing a table row in a form suitable for streaming to BQ. This includes encoding timestamps as ISO-compatible strings and removing invalid characters from column names. Args: record: a Python dictionary representing the table row. column_name_map: a dictionary mapping dictionary keys to col...
codesearchnet
def decode_header_part(header): if not header: return six.text_type() output = six.text_type() try: for d, c in decode_header(header): c = c if c else 'utf-8' output += ported_string(d, c, 'ignore') except (HeaderParseError, UnicodeError): log...
Given an raw header returns an decoded header Args: header (string): header to decode Returns: str (Python 3) or unicode (Python 2)
juraj-google-style
def ceil(cls, x: 'TensorFluent') -> 'TensorFluent': return cls._unary_op(x, tf.ceil, tf.float32)
Returns a TensorFluent for the ceil function. Args: x: The input fluent. Returns: A TensorFluent wrapping the ceil function.
codesearchnet
def open(in_file, in_fmt=None): fmt = in_file.split('.')[(- 1)] if in_fmt: fmt = in_fmt fmt = fmt.lower() if (fmt in ['png', 'jpg', 'tiff', 'tif', 'jpeg']): return Image.open(in_file) else: raise NotImplementedError('Cannot open file of type {fmt}'.format(fmt))
Reads in a file from disk. Arguments: in_file: The name of the file to read in in_fmt: The format of in_file, if you want to be explicit Returns: numpy.ndarray
codesearchnet
def _parse_publisher(details): publisher = _get_td_or_none(details, 'ctl00_ContentPlaceHolder1_tblRowNakladatel') if (not publisher): return None publisher = dhtmlparser.removeTags(publisher).strip() if (not publisher): return None return publisher
Parse publisher of the book. Args: details (obj): HTMLElement containing slice of the page with details. Returns: str/None: Publisher's name as string or None if not found.
codesearchnet
def add_to_loader(loader_cls: Type, classes: List[Type]) -> None: if (not isinstance(classes, list)): classes = [classes] for class_ in classes: tag = '!{}'.format(class_.__name__) if issubclass(class_, enum.Enum): loader_cls.add_constructor(tag, EnumConstructor(class_)) ...
Registers one or more classes with a YAtiML loader. Once a class has been registered, it can be recognized and \ constructed when reading a YAML text. Args: loader_cls: The loader to register the classes with. classes: The class(es) to register, a plain Python class or a \ list of them.
codesearchnet
def update_dns_zone_record(env, zone_id, **kwargs): client = boto3.Session(profile_name=env).client('route53') response = {} hosted_zone_info = client.get_hosted_zone(Id=zone_id) zone_name = hosted_zone_info['HostedZone']['Name'].rstrip('.') dns_name = kwargs.get('dns_name') if dns_name a...
Create a Route53 CNAME record in _env_ zone. Args: env (str): Deployment environment. zone_id (str): Route53 zone id. Keyword Args: dns_name (str): FQDN of application's dns entry to add/update. dns_name_aws (str): FQDN of AWS resource dns_ttl (int): DNS time-to-live (ttl)
juraj-google-style
def to_xml(self, xmllint=False): root = self._tree.getroot() ret = ET.tostring(ET.ElementTree(root), pretty_print=True) if xmllint: ret = xmllint_format(ret) return ret
Serialize all properties as pretty-printed XML Args: xmllint (boolean): Format with ``xmllint`` in addition to pretty-printing
juraj-google-style
def match_filenames_once(pattern, name=None): with ops.name_scope(name, 'matching_filenames', [pattern]) as name: return variable_v1.VariableV1(name=name, initial_value=io_ops.matching_files(pattern), trainable=False, validate_shape=False, collections=[ops.GraphKeys.LOCAL_VARIABLES])
Save the list of files matching pattern, so it is only computed once. NOTE: The order of the files returned is deterministic. Args: pattern: A file pattern (glob), or 1D tensor of file patterns. name: A name for the operations (optional). Returns: A variable that is initialized to the list of files matching the patt...
github-repos
def sheets_tab_delete(config, auth, sheet_url_or_name, sheet_tab): if config.verbose: print('SHEETS DELETE', sheet_url_or_name, sheet_tab) spreadsheet = sheets_get(config, auth, sheet_url_or_name) if spreadsheet: if len(spreadsheet['sheets']) == 1 and spreadsheet['sheets'][0]['properties']['...
Delete a tab in a sheet. Args: config - see starthinker/util/configuration.py auth - user or service url_or_name - one of: URL, document title, or id sheet_tab - name of tab to get id for No Return
github-repos
def __setattr__(self, name: str, val: np.ndarray) -> None: if name.startswith("!"): super(AttributeManager, self).__setattr__(name[1:], val) elif "/" in name: raise KeyError("Attribute name cannot contain slash (/)") else: if self.ds is not None: values = loompy.normalize_attr_values(val) a = ...
Set the value of a named attribute Args: name (str) Name of the attribute val (np.ndarray) Value of the attribute Remarks: Length must match the corresponding matrix dimension The values are automatically HMTL escaped and converted to ASCII for storage
juraj-google-style
def register_hook(self, hook, priority='NORMAL'): assert isinstance(hook, Hook) if hasattr(hook, 'priority'): raise ValueError('"priority" is a reserved attribute for hooks') priority = get_priority(priority) hook.priority = priority inserted = False...
Register a hook into the hook list. Args: hook (:obj:`Hook`): The hook to be registered. priority (int or str or :obj:`Priority`): Hook priority. Lower value means higher priority.
juraj-google-style
def egress(self, envelope, http_headers, operation, binding_options): custom_headers = self._header_handler.GetHTTPHeaders() http_headers.update(custom_headers) return (envelope, http_headers)
Overriding the egress function to set our headers. Args: envelope: An Element with the SOAP request data. http_headers: A dict of the current http headers. operation: The SoapOperation instance. binding_options: An options dict for the SOAP binding. Returns: A tuple of the envelope and headers.
codesearchnet
def check_dihedral(self, construction_table): c_table = construction_table angles = self.get_angle_degrees(c_table.iloc[(3:, :)].values) problem_index = np.nonzero(((175 < angles) | (angles < 5)))[0] rename = dict(enumerate(c_table.index[3:])) problem_index = [rename[i] for i in problem_index] r...
Checks, if the dihedral defining atom is colinear. Checks for each index starting from the third row of the ``construction_table``, if the reference atoms are colinear. Args: construction_table (pd.DataFrame): Returns: list: A list of problematic indices.
codesearchnet
def prepare_request( url: Union[str, methods], data: Optional[MutableMapping], headers: Optional[MutableMapping], global_headers: MutableMapping, token: str, as_json: Optional[bool] = None, ) -> Tuple[str, Union[str, MutableMapping], MutableMapping]: if isinstance(url, methods): ...
Prepare outgoing request Create url, headers, add token to the body and if needed json encode it Args: url: :class:`slack.methods` item or string of url data: Outgoing data headers: Custom headers global_headers: Global headers token: Slack API token as_json: Post JSON to the slack API Returns: :py:class:`tuple` (url...
juraj-google-style
def __init__(self, bits: List[int], initializer: tf.keras.initializers.Initializer=tf.keras.initializers.RandomUniform(), name: Union[None, str]=None): pre_process = [energy_utils.SpinsFromBitstrings()] post_process = [energy_utils.VariableDot(initializer=initializer)] super().__init__(bits, pre_process + p...
Initializes a BernoulliEnergy. Args: bits: Unique labels for the bits on which this distribution is supported. initializer: A `tf.keras.initializers.Initializer` which specifies how to initialize the values of the parameters. name: Optional name for the model.
github-repos
def replace_punctuation(self, text, excluded=None, replacement=''): if excluded is None: excluded = set() elif not isinstance(excluded, set): excluded = set(excluded) punct = ''.join(self.__punctuation.difference(excluded)) return self.replace_characters...
Replace punctuation symbols in text. Removes punctuation from input text or replaces them with a string if specified. Characters replaced will be those in string.punctuation. Args: text: The text to be processed. excluded: Set of characters to exclude. replacement: New text that will replace punctuation. Returns: Th...
juraj-google-style
def update_file(filename, result, content, indent): parts = re.split('---+', content, 2) frontmatter = yaml.safe_load(parts[1]) frontmatter['counts'] = result['counts'] parts[1] = '\n{}'.format( yaml.safe_dump(frontmatter, default_flow_style=False, indent=indent)...
Updates a Jekyll file to contain the counts form an object This just converts the results to YAML and adds to the Jekyll frontmatter. Args: filename: the Jekyll file to update result: the results object from `wc` content: the contents of the original file indent: the indentation level for dumping YAML
juraj-google-style
def scrape_hive_url(mc_url, num_tracks=sys.maxsize, folders=False, custom_path=''): try: data = get_hive_data(mc_url) except Exception as e: puts_safe((colored.red('Problem downloading ') + mc_url)) print(e) filenames = [] return filenames
Scrape a Hive.co download page. Returns: list: filenames to open
codesearchnet
def plot(self, figure_list): if not self.data == {} and self.data['image_data'] is None: axes = figure_list[0].axes[0] if len(axes.images)>0: self.data['image_data'] = np.array(axes.images[0].get_array()) self.data['extent'] = np.array(a...
Plots a dot on top of each selected NV, with a corresponding number denoting the order in which the NVs are listed. Precondition: must have an existing image in figure_list[0] to plot over Args: figure_list:
juraj-google-style
def run_task_external(self, coroutine): self.verify_calling_thread(False, 'run_task_external must not be called from the emulation thread') future = asyncio.run_coroutine_threadsafe(coroutine, self._loop) return future.result()
Inject a task into the emulation loop and wait for it to finish. The coroutine parameter is run as a Task inside the EmulationLoop until it completes and the return value (or any raised Exception) is pased back into the caller's thread. Args: coroutine (coroutine): The task to inject into the event loop. Returns: ob...
codesearchnet
def __init__( self, cipher_mode=None, initialization_vector=None, key=None, **kwargs): if not key: raise ValueError('Missing key.') cipher_mode = self.ENCRYPTION_MODES.get(cipher_mode, None) if cipher_mode is None: raise ValueError('Unsupported cipher mode: {0!s}'.format(cipher_mode)...
Initializes a decrypter. Args: cipher_mode (Optional[str]): cipher mode. initialization_vector (Optional[bytes]): initialization vector. key (Optional[bytes]): key. kwargs (dict): keyword arguments depending on the decrypter. Raises: ValueError: when key is not set, block cipher mode is not supported, or initializati...
juraj-google-style
def _get_instance(self, iname, namespace, property_list, local_only, include_class_origin, include_qualifiers): instance_repo = self._get_instance_repo(namespace) rtn_tup = self._find_instance(iname, instance_repo) inst = rtn_tup[1] if (inst is None): raise CIMError(CIM_ERR_NOT_FOUND, _format('I...
Local method implements getinstance. This is generally used by other instance methods that need to get an instance from the repository. It attempts to get the instance, copies it, and filters it for input parameters like localonly, includequalifiers, and propertylist. Returns: CIMInstance copy from the repository wi...
codesearchnet
def get_enabled(): raw_services = _get_services() services = set() for service in raw_services: if (info(service['ServiceName'])['StartType'] in ['Auto']): services.add(service['ServiceName']) return sorted(services)
Return a list of enabled services. Enabled is defined as a service that is marked to Auto Start. Returns: list: A list of enabled services CLI Example: .. code-block:: bash salt '*' service.get_enabled
codesearchnet
def __init__(self, max_iterations, damping, unroll_loop=False): assert damping >= 0.0 self.damping = damping super(ConjugateGradient, self).__init__(max_iterations=max_iterations, unroll_loop=unroll_loop)
Creates a new conjugate gradient solver instance. Args: max_iterations: Maximum number of iterations before termination. damping: Damping factor. unroll_loop: Unrolls the TensorFlow while loop if true.
juraj-google-style
def content_ratings(self, **kwargs): path = self._get_id_path('content_ratings') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the content ratings for a TV Series. Args: language: (optional) ISO 639 code. append_to_response: (optional) Comma separated, any collection method. Returns: A dict respresentation of the JSON returned from the API.
juraj-google-style
def add_ema_control_dependencies(vector_quantizer, one_hot_assignments, codes, commitment_loss, decay): updated_ema_count = moving_averages.assign_moving_average(vector_quantizer.ema_count, tf.reduce_sum(input_tensor=one_hot_assignments, axis=[0, 1]), decay, zero_debias=False) updated_ema_means = moving_average...
Add control dependencies to the commmitment loss to update the codebook. Args: vector_quantizer: An instance of the VectorQuantizer class. one_hot_assignments: The one-hot vectors corresponding to the matched codebook entry for each code in the batch. codes: A `float`-like `Tensor` containing the latent vectors to be ...
codesearchnet
def push(self, x): self._median_tracker.push(x) median = self._median_tracker.get() self._diff_median_tracker.push(abs(x - median))
Adds a new value to the tracker and updates the MAD. Args: x: The value to be added to the tracked stream.
github-repos
class FlaxGreedySearchOutput(ModelOutput): sequences: Optional[jnp.ndarray] = None
Flax Base class for outputs of decoder-only generation models using greedy search. Args: sequences (`jnp.ndarray` of shape `(batch_size, max_length)`): The generated sequences.
github-repos
def get_service_for_handle(self, handle): for s in self.services.values(): if s.start_handle <= handle and s.end_handle >= handle: return s return None
Given a characteristic handle, return the :class:`Service` object that the handle belongs to. Args: handle (int): the characteristic handle Returns: None if no service matches the given handle, otherwise a :class:`Service` object.
juraj-google-style
def batch_inputs(dataset, batch_size, train, num_preprocess_threads=None, num_readers=1): with tf.name_scope('batch_processing'): data_files = dataset.data_files() if (data_files is None): raise ValueError('No data files found for this dataset') if train: filename_que...
Contruct batches of training or evaluation examples from the image dataset. Args: dataset: instance of Dataset class specifying the dataset. See dataset.py for details. batch_size: integer train: boolean num_preprocess_threads: integer, total number of preprocessing threads num_readers: integer, number of parallel rea...
codesearchnet
def nlargest(self, n=None): if (n is None): return sorted(self.counts(), key=itemgetter(1), reverse=True) else: return heapq.nlargest(n, self.counts(), key=itemgetter(1))
List the n most common elements and their counts. List is from the most common to the least. If n is None, the list all element counts. Run time should be O(m log m) where m is len(self) Args: n (int): The number of elements to return
codesearchnet
def Create(self, name): precondition.AssertType(name, Text) try: constructor = self._constructors[name] except KeyError: message = "No constructor for name '%s' has been registered" message %= name raise ValueError(message) instance = constructor() if not isinstance(in...
Creates a new instance. Args: name: A name identifying the constructor to use for instantiation. Returns: An instance of the type that the factory supports.
juraj-google-style
def _GetUsers(self, key_path_suffix): user_key_name, _, key_path_suffix = key_path_suffix.partition( definitions.KEY_PATH_SEPARATOR) if user_key_name == '.DEFAULT': search_key_name = 'S-1-5-18' else: search_key_name = user_key_name user_profile_list_key = self.GetKey...
Virtual key callback to determine the users sub keys. Args: key_path_suffix (str): users Windows Registry key path suffix with leading path separator. Returns: WinRegistryKey: the users Windows Registry key or None if not available.
juraj-google-style
def __init__(self, parent): logger.debug("Initialising log panel") super(Log, self).__init__(parent, padding=8, text="Python console log") log = tk.Text(self, wrap="none") log.grid(column=0, row=0, sticky="W E N S") log.tag_config('critical', foregro...
Create a new text box for the console log. Args: parent: A tk or ttk object
juraj-google-style
def __init__(self, start, width, num_buckets): self._start = start self._width = width self._num_buckets = num_buckets
Create a histogram with linear buckets. Args: start: Lower bound of a starting bucket. width: Bucket width. Smaller width implies a better resolution for percentile estimation. num_buckets: The number of buckets. Upper bound of an ending bucket is defined by start + width * numBuckets.
github-repos
def step(self, observations, raw_rewards, processed_rewards, dones, actions): assert isinstance(observations, np.ndarray) assert isinstance(raw_rewards, np.ndarray) assert isinstance(processed_rewards, np.ndarray) assert isinstance(dones, np.ndarray) assert isinstance(actions, np.ndarray) assert...
Record the information obtained from taking a step in all envs. Records (observation, rewards, done) in a new time-step and actions in the current time-step. If any trajectory gets done, we move that trajectory to completed_trajectories. Args: observations: ndarray of first dimension self.batch_size, which has the o...
codesearchnet
def next_trials(self): trials = list(self._trial_generator) if self._shuffle: random.shuffle(trials) self._finished = True return trials
Provides Trial objects to be queued into the TrialRunner. Returns: trials (list): Returns a list of trials.
codesearchnet
def reverse(path): if is_rooted(path) or '..' in path: from b2.manager import get_manager get_manager().errors()( 'reverse(path): path is either rooted or contains ".." in the path') if path == '.': return path path = os.path.normpath(path) return os.se...
Returns path2 such that `os.path.join(path, path2) == '.'`. `path` may not contain '..' or be rooted. Args: path (str): the path to reverse Returns: the string of the reversed path Example: >>> p1 = 'path/to/somewhere' >>> p2 = reverse('path/to/somewhere') >>> p2 '../../..' >>> os.path.normpath(os.path.join(p1, p2)...
juraj-google-style
def forward(self, hidden_states: torch.Tensor, output_attentions: Optional[bool]=False) -> Tuple[torch.FloatTensor]: residual = hidden_states hidden_states = self.layer_norm1(hidden_states) hidden_states, attn_weights = self.self_attn(hidden_states=hidden_states, output_attentions=output_attentions) hid...
Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail.
github-repos
def trigger_methods(instance, args): for name in sorted(args): value = args[name] target = instance if (name.startswith('response_') or name.startswith('reply_')): name = name.replace('response_', '').replace('reply_', '') if hasattr(instance, '_response'): ...
Triggers specific class methods using a simple reflection mechanism based on the given input dictionary params. Arguments: instance (object): target instance to dynamically trigger methods. args (iterable): input arguments to trigger objects to Returns: None
codesearchnet
def put(self, id, name, description, private, runs_executable_tasks, runs_docker_container_tasks, runs_singularity_container_tasks, active, whitelists): request_url = (self._client.base_api_url + self.detail_url.format(id=id)) data_to_put = {'name': name, 'description': description, 'private': private, 'runs_ex...
Updates a task queue on the saltant server. Args: id (int): The ID of the task queue. name (str): The name of the task queue. description (str): The description of the task queue. private (bool): A Booleon signalling whether the queue can only be used by its associated user. runs_executable_tasks (bool): A Boolean spe...
codesearchnet
def compile_protofile(proto_file_path): out_file = tempfile.mkstemp()[1] try: subprocess.check_output(['protoc', '--include_source_info', '--descriptor_set_out', out_file, proto_file_path]) except subprocess.CalledProcessError as e: sys.exit('protoc returned status {}'.format(e.returncode)) ...
Compile proto file to descriptor set. Args: proto_file_path: Path to proto file to compile. Returns: Path to file containing compiled descriptor set. Raises: SystemExit if the compilation fails.
codesearchnet
async def _async_loop(self, urls): results = [] async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as session: for url in urls: result = asyncio.ensure_future(self._get_async(url, session)) results.append(result) responses = (await asyncio.gather(...
Asynchronous internal method used to request multiple URLs Args: urls (list): URLs to fetch Returns: responses (obj): All URL requests' response coroutines
codesearchnet