code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def cacheResult(fn): cache = {} @functools.wraps(fn) def wrapper(*args, **kwargs): key = args + tuple(kwargs.items()) try: if key in cache: return cache[key] except TypeError: return fn(*args, **kwargs) cache[key] = fn(*args, **kwargs) return cache[key] wrapper.cache = cache return wrapper
Method decorator: calculate the value on first access, produce the cached value thereafter. If the function takes arguments, the cache is a dictionary using all arguments as the key. Args: fn (method): function to decorate Returns: method: wrapper function with caching
juraj-google-style
def _FormatPackedIPv6Address(self, packed_ip_address): octet_pairs = zip(packed_ip_address[0::2], packed_ip_address[1::2]) octet_pairs = [octet1 << 8 | octet2 for octet1, octet2 in octet_pairs] return ':'.join([ '{0:04x}'.format(octet_pair) for octet_pair in octet_pairs])
Formats a packed IPv6 address as a human readable string. Args: packed_ip_address (list[int]): packed IPv6 address. Returns: str: human readable IPv6 address.
juraj-google-style
def _gen_ipython_string(func, args, defaults, original_doc): magic_string = ('%s(' % func.__name__) if defaults: default_offset = (len(args) - len(defaults)) else: default_offset = len(args) for (i, value) in enumerate(args): if (i >= default_offset): magic_string += ('%s=%s, ' % (value, defaults[(i - default_offset)])) else: magic_string += ('%s, ' % value) if args: magic_string = magic_string[:(- 2)] magic_string += ')\n\n' if (original_doc is not None): magic_string += original_doc return magic_string
Provides auto-complete hint to ipython. If the first line in a docstring is fn(arg1=, arg2=) then they are added to auto-complete. This cannot be called on an instance method. Args: func: The function that will be modified. args: The arguments that this function takes in order. defaults: The default arguments corresponding the last arguments. original_doc: Original docstring to assign after the magic string. Returns: The new doc string with the magic bit prepended.
codesearchnet
def register_for_auto_class(cls, auto_class='AutoTokenizer'): if not isinstance(auto_class, str): auto_class = auto_class.__name__ import transformers.models.auto as auto_module if not hasattr(auto_module, auto_class): raise ValueError(f'{auto_class} is not a valid auto class.') cls._auto_class = auto_class
Register this class with a given auto class. This should only be used for custom tokenizers as the ones in the library are already mapped with `AutoTokenizer`. Args: auto_class (`str` or `type`, *optional*, defaults to `"AutoTokenizer"`): The auto class to register this new tokenizer with.
github-repos
def pre_verify(method): @wraps(method) def wrapper(self, *args, **kwargs): self._verify_page() return method(self, *args, **kwargs) return wrapper
Decorator that calls self._verify_page() before executing the decorated method Args: method (callable): The method to decorate. Returns: Decorated method
juraj-google-style
def evaluate_extracted_tokens(gold_content, extr_content): if isinstance(gold_content, string_): gold_content = simple_tokenizer(gold_content) if isinstance(extr_content, string_): extr_content = simple_tokenizer(extr_content) gold_set = set(gold_content) extr_set = set(extr_content) jaccard = (len((gold_set & extr_set)) / len((gold_set | extr_set))) levenshtein = dameraulevenshtein(gold_content, extr_content) return {'jaccard': jaccard, 'levenshtein': levenshtein}
Evaluate the similarity between gold-standard and extracted content, typically for a single HTML document, as another way of evaluating the performance of an extractor model. Args: gold_content (str or Sequence[str]): Gold-standard content, either as a string or as an already-tokenized list of tokens. extr_content (str or Sequence[str]): Extracted content, either as a string or as an already-tokenized list of tokens. Returns: Dict[str, float]
codesearchnet
def camelize(word): return ''.join(((w[0].upper() + w[1:]) for w in re.sub('[^A-Z^a-z^0-9^:]+', ' ', word).split(' ')))
Convert a word from lower_with_underscores to CamelCase. Args: word: The string to convert. Returns: The modified string.
codesearchnet
def is_common(schema): if isinstance(schema, StreamSchema): return schema.schema() in _SCHEMA_COMMON if isinstance(schema, CommonSchema): return True if isinstance(schema, basestring): return is_common(StreamSchema(schema)) return False
Is `schema` an common schema. Args: schema: Scheme to test. Returns: bool: ``True`` if schema is a common schema, otherwise ``False``.
juraj-google-style
def get_config(self): return {}
Returns a Python dict of the object config. A constraint config is a Python dictionary (JSON-serializable) that can be used to reinstantiate the same object. Returns: Python dict containing the configuration of the constraint object.
github-repos
def tpu_model_inference_fn(features): def custom_getter(getter, name, *args, **kwargs): with tf.control_dependencies(None): return tf.guarantee_const(getter(name, *args, **kwargs), name=(name + '/GuaranteeConst')) with tf.variable_scope('', custom_getter=custom_getter): t = int(time.time()) epoch_time = tf.constant(t, name=('epoch_time_%d' % t)) with tf.control_dependencies([epoch_time]): return model_inference_fn(features, False, FLAGS.flag_values_dict())
Builds the model graph suitable for running on TPU. It does two things: 1) Mark all weights as constant, which improves TPU inference performance because it prevents the weights being transferred to the TPU every call to Session.run(). 2) Adds constant to the graph with a unique value and marks it as a dependency on the rest of the model. This works around a TensorFlow bug that prevents multiple models being run on a single TPU. Returns: (policy_output, value_output, logits) tuple of tensors.
codesearchnet
def compose_full_url(pub, uuid_url=False): url = compose_path(pub, uuid_url) if WEB_PORT == 80: return "%s: return "%s:
Compose full url for given `pub`, with protocol, server's address and port. Args: pub (obj): :class:`.DBPublication` instance. uuid_url (bool, default False): Compose URL using UUID. Returns: str: Absolute url of the publication. Raises: PrivatePublicationError: When the `pub` is private publication.
juraj-google-style
def cast(self, dtype: tf.DType) -> 'TensorFluent': if (self.dtype == dtype): return self t = tf.cast(self.tensor, dtype) scope = self.scope.as_list() batch = self.batch return TensorFluent(t, scope, batch=batch)
Returns a TensorFluent for the cast operation with given `dtype`. Args: dtype: The output's data type. Returns: A TensorFluent wrapping the cast operation.
codesearchnet
def match_as_dict(self, film_sl_vectors, substrate_sl_vectors, film_vectors, substrate_vectors, match_area): d = {} d["film_sl_vecs"] = np.asarray(film_sl_vectors) d["sub_sl_vecs"] = np.asarray(substrate_sl_vectors) d["match_area"] = match_area d["film_vecs"] = np.asarray(film_vectors) d["sub_vecs"] = np.asarray(substrate_vectors) return d
Returns dict which contains ZSL match Args: film_miller(array) substrate_miller(array)
juraj-google-style
def mutate(self, dna: pg.DNA, global_state: pg.geno.AttributeDict, step: int=0) -> typing.Union[pg.DNA, List[pg.DNA]]: raise NotImplementedError()
Mutates the DNA at a given step. User should override this method or `mutate_list` method with optional keyword arguments 'global_state' and 'step'. Args: dna: DNA to mutate. global_state: An `AttributeDict` object as the container of global states. step: Number of examples historically proposed, which can be used for determining a mutation schedule. Returns: A new DNA or a DNA list as the result of the mutation.
github-repos
def migration_exchange(self, *, users: List[str], **kwargs) -> SlackResponse: kwargs.update({'users': users}) return self.api_call('migration.exchange', http_verb='GET', params=kwargs)
For Enterprise Grid workspaces, map local user IDs to global user IDs Args: users (list): A list of user ids, up to 400 per request. e.g. ['W1234567890', 'U2345678901', 'U3456789012']
codesearchnet
def search(self): safeEnvDict = {'freeSearch': self.freeSearch, 'extentSearch': self.extentSearch, 'indexSearch': self.indexSearch} for col in self._dataFrame.columns: safeEnvDict[col] = self._dataFrame[col] try: searchIndex = eval(self._filterString, {'__builtins__': None}, safeEnvDict) except NameError: return ([], False) except SyntaxError: return ([], False) except ValueError: return ([], False) except TypeError: return ([], False) return (searchIndex, True)
Applies the filter to the stored dataframe. A safe environment dictionary will be created, which stores all allowed functions and attributes, which may be used for the filter. If any object in the given `filterString` could not be found in the dictionary, the filter does not apply and returns `False`. Returns: tuple: A (indexes, success)-tuple, which indicates identified objects by applying the filter and if the operation was successful in general.
codesearchnet
def generate_state_data(means, weights): x_true = np.dot(means, weights) sample = np.random.poisson(x_true) return sample.astype(float)
Generates data according to the Poisson Convex Mixture Model. Args: means (array): Cell types- genes x clusters weights (array): Cell cluster assignments- clusters x cells Returns: data matrix - genes x cells
codesearchnet
def disasm(code, addr=0, syntax=None, target=None): if (target is None): target = pwnypack.target.target if (syntax is None): if (target.arch is pwnypack.target.Target.Arch.x86): syntax = AsmSyntax.nasm else: syntax = AsmSyntax.att if (syntax is AsmSyntax.nasm): if (target.arch is not pwnypack.target.Target.Arch.x86): raise NotImplementedError('nasm only supports x86.') p = subprocess.Popen(['ndisasm', '-b', str(target.bits.value), '-o', str(addr), '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, stderr) = p.communicate(code) if p.returncode: raise RuntimeError(stderr.decode('utf-8')) return [line.split(None, 2)[2] for line in stdout.decode('utf-8').split('\n') if (line and (not line.startswith(' ')))] elif (syntax in (AsmSyntax.intel, AsmSyntax.att)): md = prepare_capstone(syntax, target) statements = [] total_size = 0 for (_, size, mnemonic, op_str) in md.disasm_lite(code, addr): statements.append(((mnemonic + ' ') + op_str).strip()) total_size += size return statements else: raise NotImplementedError('Unsupported syntax for host platform.')
Disassemble machine readable code into human readable statements. Args: code(bytes): The machine code that is to be disassembled. addr(int): The memory address of the code (used for relative references). syntax(AsmSyntax): The output assembler syntax. This defaults to nasm on x86 architectures, AT&T on all other architectures. target(~pwnypack.target.Target): The architecture for which the code was written. The global target is used if this argument is ``None``. Returns: list of str: The disassembled machine code. Raises: NotImplementedError: In an unsupported target platform is specified. RuntimeError: If ndisasm encounters an error. Example: >>> from pwny import * >>> disasm(b'_\\xc3', target=Target(arch=Target.Arch.x86, bits=64)) ['pop rdi', 'ret']
codesearchnet
def from_json(cls, data): required_keys = ('hum_type', 'hum_value') optional_keys = {'barometric_pressure': 101325, 'schedule': '', 'wet_bulb_range': ''} for key in required_keys: assert (key in data), 'Required key "{}" is missing!'.format(key) for (key, val) in optional_keys.items(): if (key not in data): data[key] = val return cls(data['hum_type'], data['hum_value'], data['barometric_pressure'], data['schedule'], data['wet_bulb_range'])
Create a Humidity Condition from a dictionary. Args: data = { "hum_type": string, "hum_value": float, "barometric_pressure": float, "schedule": string, "wet_bulb_range": string}
codesearchnet
def _get_resized_lm_head_decoder(self, old_lm_head_decoder, new_num_tokens): new_lm_head_decoder = old_lm_head_decoder is_input_output_equals = tf.reduce_any(self._get_word_embedding_weight(self.get_input_embeddings()) == old_lm_head_decoder) if old_lm_head_decoder is not None and (not is_input_output_equals): old_embedding_dim = shape_list(old_lm_head_decoder)[1] decoder_mask, current_decoder = init_copy_embeddings(old_lm_head_decoder, new_num_tokens) new_lm_head_decoder = self.add_weight(shape=(new_num_tokens, old_embedding_dim), initializer='zeros', trainable=True, name=old_lm_head_decoder.name.split(':')[0]) init_decoder = tf.where(decoder_mask, current_decoder, new_lm_head_decoder.value()) new_lm_head_decoder.assign(init_decoder) return new_lm_head_decoder
Build a resized decoder from the old ones. Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end Args: old_lm_head_decoder (`tf.Variable`): Old lm head decoder to be resized. new_num_tokens (`int`, *optional*): New number of tokens in the linear matrix. Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end. If not provided or `None`, just returns None Return: `tf.Variable`: Pointer to the resized decoder or None if the output embeddings are different from the input ones.
github-repos
def __init__(self, initializer: tf.keras.initializers.Initializer=tf.keras.initializers.RandomUniform()): super().__init__() self._initializer = initializer
Initializes a VariableDot layer. Args: initializer: A `tf.keras.initializers.Initializer` which specifies how to initialize the values of the parameters.
github-repos
def _standardize_and_copy_config(config): kwargs = config.copy() for k, v in kwargs.items(): if isinstance(v, list): kwargs[k] = tuple(v) return kwargs
Returns a shallow copy of config with lists turned to tuples. Keras serialization uses nest to listify everything. This causes problems with the NumericColumn shape, which becomes unhashable. We could try to solve this on the Keras side, but that would require lots of tracking to avoid changing existing behavior. Instead, we ensure here that we revive correctly. Args: config: dict that will be used to revive a Feature Column Returns: Shallow copy of config with lists turned to tuples.
github-repos
def _RunOsLoginNssCache(self): try: return subprocess.call([constants.OSLOGIN_NSS_CACHE_SCRIPT]) except OSError as e: if (e.errno == errno.ENOENT): return None else: raise
Run the OS Login NSS cache binary. Returns: int, the return code from the call, or None if the script is not found.
codesearchnet
def validate(self, nanopub: Mapping[(str, Any)]) -> Tuple[(bool, List[Tuple[(str, str)]])]: (is_valid, messages) = validate_to_schema(nanopub, self.nanopub_schema) if (not is_valid): return messages if (nanopub['nanopub']['type']['name'].upper() == 'BEL'): bel_version = nanopub['nanopub']['type']['version'] else: is_valid = False return (is_valid, f"Not a BEL Nanopub according to nanopub.type.name: {nanopub['nanopub']['type']['name']}") all_messages = [] bel_obj = bel.lang.belobj.BEL(bel_version, self.endpoint) for edge in nanopub['nanopub']['edges']: bel_statement = f"{edge['subject']} {edge['relation']} {edge['object']}" parse_obj = bel_obj.parse(bel_statement) if (not parse_obj.valid): all_messages.extend(('ERROR', f'BEL statement parse error {parse_obj.error}, {parse_obj.err_visual}')) for context in nanopub['nanopub']['context']: (is_valid, messages) = self.validate_context(context) all_messages.extend(messages) is_valid = True for (_type, msg) in all_messages: if (_type == 'ERROR'): is_valid = False return (is_valid, all_messages)
Validates using the nanopub schema Args: nanopub (Mapping[str, Any]): nanopub dict Returns: Tuple[bool, List[Tuple[str, str]]]: bool: Is valid? Yes = True, No = False List[Tuple[str, str]]: Validation issues, empty if valid, tuple is ('ERROR|WARNING', msg) e.g. [('WARNING', "Context ID not found")]
codesearchnet
def expand(self, pcoll: beam.PCollection[Chunk]) -> beam.PTransform[Chunk, Any]: write_transform = self.database_config.create_write_transform() return pcoll | write_transform
Creates and applies the database-specific write transform. Args: pcoll: PCollection of Chunks with embeddings to write to the vector database. Each Chunk must have: - An embedding - An ID - Metadata used to filter results as specified by database config Returns: Result of writing to database (implementation specific).
github-repos
def _set_avg_session_metrics(session_group): assert session_group.sessions, 'SessionGroup cannot be empty.' metric_stats = collections.defaultdict(_MetricStats) for session in session_group.sessions: for metric_value in session.metric_values: metric_name = _MetricIdentifier(group=metric_value.name.group, tag=metric_value.name.tag) stats = metric_stats[metric_name] stats.total += metric_value.value stats.count += 1 stats.total_step += metric_value.training_step stats.total_wall_time_secs += metric_value.wall_time_secs del session_group.metric_values[:] for (metric_name, stats) in six.iteritems(metric_stats): session_group.metric_values.add(name=api_pb2.MetricName(group=metric_name.group, tag=metric_name.tag), value=(float(stats.total) / float(stats.count)), training_step=(stats.total_step
Sets the metrics for the group to be the average of its sessions. The resulting session group metrics consist of the union of metrics across the group's sessions. The value of each session group metric is the average of that metric values across the sessions in the group. The 'step' and 'wall_time_secs' fields of the resulting MetricValue field in the session group are populated with the corresponding averages (truncated for 'step') as well. Args: session_group: A SessionGroup protobuffer.
codesearchnet
def rprint(sep='\n', end='\n', file=sys.stdout, flush=False): try: first_item = (yield) file.write(str(first_item)) if flush: file.flush() while True: item = (yield) file.write(sep) file.write(str(item)) if flush: file.flush() except GeneratorExit: file.write(end) if flush: file.flush()
A coroutine sink which prints received items stdout Args: sep: Optional separator to be printed between received items. end: Optional terminator to be printed after the last item. file: Optional stream to which to print. flush: Optional flag to force flushing after each item.
juraj-google-style
def upload(self, file_path, uri=None, timeout=(- 1)): if (not uri): uri = self._uri upload_file_name = os.path.basename(file_path) (task, entity) = self._connection.post_multipart_with_response_handling(uri, file_path, upload_file_name) if (not task): return entity return self._task_monitor.wait_for_task(task, timeout)
Makes a multipart request. Args: file_path: File to upload. uri: A specific URI (optional). timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView; it just stops waiting for its completion. Returns: dict: Response body.
codesearchnet
def to_grayscale(img, num_output_channels=1): if (not _is_pil_image(img)): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) if (num_output_channels == 1): img = img.convert('L') elif (num_output_channels == 3): img = img.convert('L') np_img = np.array(img, dtype=np.uint8) np_img = np.dstack([np_img, np_img, np_img]) img = Image.fromarray(np_img, 'RGB') else: raise ValueError('num_output_channels should be either 1 or 3') return img
Convert image to grayscale version of image. Args: img (PIL Image): Image to be converted to grayscale. Returns: PIL Image: Grayscale version of the image. if num_output_channels = 1 : returned image is single channel if num_output_channels = 3 : returned image is 3 channel with r = g = b
codesearchnet
def usufyToXlsExport(d, fPath): from pyexcel_xls import get_data try: oldData = {'OSRFramework': get_data(fPath)} except: oldData = {'OSRFramework': []} tabularData = _generateTabularData(d, oldData) from pyexcel_xls import save_data save_data(fPath, tabularData)
Workaround to export to a .xls file. Args: ----- d: Data to export. fPath: File path for the output file.
codesearchnet
def stack(list_or_tensor, element_dtype=None, strict=True): if strict: def raise_error(x): raise ValueError('%s must be stackable when strict=True' % x) original_call = raise_error else: original_call = lambda x: x return data_structures.list_stack(list_or_tensor, data_structures.ListStackOpts(element_dtype=element_dtype, original_call=original_call))
Stacks the input, if it admits the notion of stacking. For example, a list of tensors can be stacked into a larger tensor. This function is similar to tf.stack, but it accepts non-lists and lists of non-tensors as arguments. In the latter case, the function does nothing. Args: list_or_tensor: Any element_dtype: tf.DType, optional dtypedtype for the elements in the list. Required if the input is stackable, and the list is untyped. strict: bool, if True an error is raised if the input is not stackable. Otherwise the function is a no-op. Returns: Any, if the input is stackable, the result will be a tf.Tensor. Otherwise, if strict=False, the result will be list_or_tensor. Raises: ValueError: if strict=True and the input is not stackable.
github-repos
def save(self, path, compressed=True, exist_ok=False): path = os.path.expandvars(os.path.expanduser(path)) if (os.path.isfile(path) and (not exist_ok)): raise OSError(17, os.strerror(17), path) if os.path.isdir(path): path = os.path.join(path, 'out.gdg') if compressed: bytes_written = cgaddag.gdg_save_compressed(self.gdg, path.encode('ascii')) else: bytes_written = cgaddag.gdg_save(self.gdg, path.encode('ascii')) if (bytes_written == (- 1)): errno = ctypes.c_int.in_dll(ctypes.pythonapi, 'errno').value raise OSError(errno, os.strerror(errno), path) return bytes_written
Save the GADDAG to file. Args: path: path to save the GADDAG to. compressed: compress the saved GADDAG using gzip. exist_ok: overwrite existing file at `path`.
codesearchnet
def arg_types(parsed: Parsed, errors: Errors) -> Tuple[Parsed, Errors]: func_pattern = re.compile(r"\s*[a-zA-Z]+\(") nsarg_pattern = re.compile(r"^\s*([A-Z]+):(.*?)\s*$") for span in parsed: if parsed[span]["type"] != "Function" or "parens_span" not in parsed[span]: continue for i, arg in enumerate(parsed[span]["args"]): nsarg_matches = nsarg_pattern.match(arg["arg"]) if func_pattern.match(arg["arg"]): parsed[span]["args"][i].update({"type": "Function"}) elif nsarg_matches: (start, end) = arg["span"] ns = nsarg_matches.group(1) ns_val = nsarg_matches.group(2) ns_span = nsarg_matches.span(1) ns_span = (ns_span[0] + start, ns_span[1] + start - 1) ns_val_span = nsarg_matches.span(2) ns_val_span = (ns_val_span[0] + start, ns_val_span[1] + start - 1) parsed[span]["args"][i].update( { "type": "NSArg", "ns": ns, "ns_span": ns_span, "ns_val": ns_val, "ns_val_span": ns_val_span, } ) else: parsed[span]["args"][i].update({"type": "StrArg"}) return parsed, errors
Add argument types to parsed function data structure Args: parsed: function and arg locations in BEL string errors: error messages Returns: (parsed, errors): parsed, arguments with arg types plus error messages
juraj-google-style
def gpu(self: EagerTensorType, gpu_index=0) -> EagerTensorType: return self._copy(context.context(), 'GPU:' + str(gpu_index))
A copy of this Tensor with contents backed by memory on the GPU. Args: gpu_index: Identifies which GPU to place the contents on the returned Tensor in. Returns: A GPU-memory backed Tensor object initialized with the same contents as this Tensor.
github-repos
def _get_password_url(self): password_url = None if (self._settings['user'] or self._settings['authorization']): if self._settings['url']: password_url = self._settings['url'] elif self._settings['base_url']: password_url = self._settings['base_url'] return password_url
Get URL used for authentication Returns: string: URL
codesearchnet
def get_structure_seqs(self, model): dont_overwrite = [] chains = list(model.get_chains()) for x in chains: if self.chains.has_id(x.id): if self.chains.get_by_id(x.id).seq_record: dont_overwrite.append(x.id) if len(dont_overwrite) == len(chains): log.debug('Not writing structure sequences, already stored') return structure_seqs = ssbio.protein.structure.properties.residues.get_structure_seqrecords(model) log.debug('{}: gathered chain sequences'.format(self.id)) for seq_record in structure_seqs: log.debug('{}: adding chain sequence to ChainProp'.format(seq_record.id)) my_chain = self.chains.get_by_id(seq_record.id) my_chain.seq_record = seq_record
Gather chain sequences and store in their corresponding ``ChainProp`` objects in the ``chains`` attribute. Args: model (Model): Biopython Model object of the structure you would like to parse
juraj-google-style
def _compute_args(self, data=dict(), **kwargs): for name, remote_attribute in self._attributes.items(): default_value = BambouConfig.get_default_attribute_value(self.__class__, name, remote_attribute.attribute_type) setattr(self, name, default_value) if len(data) > 0: self.from_dict(data) for key, value in kwargs.items(): if hasattr(self, key): setattr(self, key, value)
Compute the arguments Try to import attributes from data. Otherwise compute kwargs arguments. Args: data: a dict() kwargs: a list of arguments
juraj-google-style
def contextmanager(target: Callable[..., Iterator[_T]]) -> Callable[..., ContextManager[_T]]: context_manager = _contextlib.contextmanager(target) return tf_decorator.make_decorator(target, context_manager, 'contextmanager')
A tf_decorator-aware wrapper for `contextlib.contextmanager`. Usage is identical to `contextlib.contextmanager`. Args: target: A callable to be wrapped in a contextmanager. Returns: A callable that can be used inside of a `with` statement.
github-repos
def __init__(self, given, enum_type, options): super(InvalidEnumValue, self).__init__('Could not parse [{0}] into a valid {1}. Valid values are [{2}]'.format(given, enum_type, ', '.join(options)))
Constructs a new exception. Args: given: str, The given string that could not be parsed. enum_type: str, The human readable name of the enum you were trying to parse. options: list(str), The valid values for this enum.
github-repos
def infer_pyarrow_schema(data): column_data = OrderedDict() for row in data: for key, value in row.items(): column_data.setdefault(key, []).append(value) column_types = OrderedDict([(key, pa.array(value).type) for key, value in column_data.items()]) return pa.schema(list(column_types.items()))
For internal use only; no backwards-compatibility guarantees. Infer PyArrow schema for tabular data. Args: data (List[dict]): A list of dictionaries representing rows in a table. Returns: A PyArrow schema object.
github-repos
def _flatten_location_translations(location_translations): sources_to_process = set(six.iterkeys(location_translations)) def _update_translation(source): 'Return the proper (fully-flattened) translation for the given location.' destination = location_translations[source] if (destination not in location_translations): return destination else: sources_to_process.discard(destination) final_destination = _update_translation(destination) location_translations[source] = final_destination return final_destination while sources_to_process: _update_translation(sources_to_process.pop())
If location A translates to B, and B to C, then make A translate directly to C. Args: location_translations: dict of Location -> Location, where the key translates to the value. Mutated in place for efficiency and simplicity of implementation.
codesearchnet
def Reformat(llines, lines=None): final_lines = [] prev_line = None indent_width = style.Get('INDENT_WIDTH') for lline in _SingleOrMergedLines(llines): first_token = lline.first _FormatFirstToken(first_token, lline.depth, prev_line, final_lines) indent_amt = indent_width * lline.depth state = format_decision_state.FormatDecisionState(lline, indent_amt) state.MoveStateToNextToken() if not lline.disable: if lline.first.is_comment: lline.first.value = lline.first.value.rstrip() elif lline.last.is_comment: lline.last.value = lline.last.value.rstrip() if prev_line and prev_line.disable: _RetainRequiredVerticalSpacingBetweenTokens(lline.first, prev_line.last, lines) if any((tok.is_comment for tok in lline.tokens)): _RetainVerticalSpacingBeforeComments(lline) if lline.disable or _LineHasContinuationMarkers(lline): _RetainHorizontalSpacing(lline) _RetainRequiredVerticalSpacing(lline, prev_line, lines) _EmitLineUnformatted(state) elif _LineContainsPylintDisableLineTooLong(lline) or _LineContainsI18n(lline): _RetainRequiredVerticalSpacing(lline, prev_line, lines) _EmitLineUnformatted(state) elif _CanPlaceOnSingleLine(lline) and (not any((tok.must_break_before for tok in lline.tokens))): while state.next_token: state.AddTokenToState(newline=False, dry_run=False) elif not _AnalyzeSolutionSpace(state): state = format_decision_state.FormatDecisionState(lline, indent_amt) state.MoveStateToNextToken() _RetainHorizontalSpacing(lline) _RetainRequiredVerticalSpacing(lline, prev_line, None) _EmitLineUnformatted(state) final_lines.append(lline) prev_line = lline _AlignTrailingComments(final_lines) return _FormatFinalLines(final_lines)
Reformat the logical lines. Arguments: llines: (list of logical_line.LogicalLine) Lines we want to format. lines: (set of int) The lines which can be modified or None if there is no line range restriction. Returns: A string representing the reformatted code.
github-repos
def assembly(self, value): if value == self._defaults['assembly'] and 'assembly' in self._values: del self._values['assembly'] else: self._values['assembly'] = value
The assembly property. Args: value (string). the property value.
juraj-google-style
def make_report_table(fp, title, reports): reports.sort(key=lambda x: x[1]['tflite_converter'], reverse=False) reports.sort(key=lambda x: x[1]['tf'], reverse=True) def result_cell(x, row, col): s = html.escape(repr(x), quote=True) color = ' handler = 'ShowLog(%d, %d)' % (row, col) fp.write("<td style='background-color: %s' onclick='%s'>%s</td>\n" % (color, handler, s)) fp.write('<html>\n<head>\n<title>tflite report</title>\n<style>\nbody { font-family: Arial; }\nth { background-color: fp.write('<script> \n') fp.write('\nfunction ShowLog(row, col) {\n\nvar log = document.getElementById("log");\nlog.innerHTML = "<pre>" + data[row][col] + "</pre>";\n}\n') fp.write('var data = \n') logs = json.dumps([[escape_and_normalize(x[1]['tf_log']), escape_and_normalize(x[1]['tflite_converter_log'])] for x in reports]) fp.write(logs) fp.write(';</script>\n') fp.write('\n<body>\n<h1>TensorFlow Lite Conversion</h1>\n<h2>%s</h2>\n' % title) param_keys = {} for params, _ in reports: for k in params.keys(): param_keys[k] = True fp.write('<table>\n') fp.write("<tr><td class='horiz'>\n") fp.write("<div style='height:1000px; overflow:auto'>\n") fp.write('<table>\n') fp.write('<tr>\n') for p in param_keys: fp.write('<th>%s</th>\n' % html.escape(p, quote=True)) fp.write('<th>TensorFlow</th>\n') fp.write('<th>TensorFlow Lite Converter</th>\n') fp.write('</tr>\n') for idx, (params, vals) in enumerate(reports): fp.write('<tr>\n') for p in param_keys: fp.write(' <td>%s</td>\n' % html.escape(repr(params.get(p, None)), quote=True)) result_cell(vals['tf'], idx, 0) result_cell(vals['tflite_converter'], idx, 1) fp.write('</tr>\n') fp.write('</table>\n') fp.write('</div>\n') fp.write('</td>\n') fp.write("<td class='horiz' id='log'></td></tr>\n") fp.write('</table>\n') fp.write('<script>\n') fp.write('</script>\n') fp.write('\n </body>\n </html>\n ')
Make an HTML report of the success/failure reports. Args: fp: File-like object in which to put the html. title: "Title of the zip file this pertains to." reports: a list of conversion attempts. (report_args, report_vals) i.e. ({"shape": [1,2,3], "type": "tf.float32"}, {"tf": "SUCCESS", "tflite_converter": "FAILURE", "tf_log": "", "tflite_converter_log": "Unsupported type."})
github-repos
def env(mounts): f_mounts = [m.strip('/') for m in mounts] root = local.path('/') ld_libs = [((root / m) / 'lib') for m in f_mounts] ld_libs.extend([((root / m) / 'lib64') for m in f_mounts]) paths = [((root / m) / 'bin') for m in f_mounts] paths.extend([((root / m) / 'sbin') for m in f_mounts]) paths.extend([(root / m) for m in f_mounts]) return (paths, ld_libs)
Compute the environment of the change root for the user. Args: mounts: The mountpoints of the current user. Return: paths ld_libs
codesearchnet
def get_point_index(self, point): for (i, segment) in enumerate(self.segments): idx = segment.getPointIndex(point) if (idx != (- 1)): return (i, idx) return ((- 1), (- 1))
Gets of the closest first point Args: point (:obj:`Point`) Returns: (int, int): Segment id and point index in that segment
codesearchnet
def set_default_by_index(self, index): if index >= len(self._datasets): raise DataInvalidIndex('A dataset with index {} does not exist'.format(index)) self._default_index = index
Set the default dataset by its index. After changing the default dataset, all calls without explicitly specifying the dataset by index or alias will be redirected to this dataset. Args: index (int): The index of the dataset that should be made the default. Raises: DataInvalidIndex: If the index does not represent a valid dataset.
juraj-google-style
def setup_modules(self, args): def _setup_module_thread(module_description): new_args = utils.import_args_from_dict( module_description['args'], vars(args), self.config) module = self._module_pool[module_description['name']] try: module.setup(**new_args) except Exception as error: self.add_error( 'An unknown error occurred: {0!s}\nFull traceback:\n{1:s}'.format( error, traceback.format_exc()), critical=True) self.events[module_description['name']] = threading.Event() self.cleanup() threads = [] for module_description in self.recipe['modules']: t = threading.Thread( target=_setup_module_thread, args=(module_description, ) ) threads.append(t) t.start() for t in threads: t.join() self.check_errors(is_global=True)
Performs setup tasks for each module in the module pool. Threads declared modules' setup() functions. Takes CLI arguments into account when replacing recipe parameters for each module. Args: args: Command line arguments that will be used to replace the parameters declared in the recipe.
juraj-google-style
def from_encoder_decoder_configs(cls, encoder_config: PretrainedConfig, decoder_config: PretrainedConfig, **kwargs) -> PretrainedConfig: logger.info('Setting `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config') decoder_config.is_decoder = True decoder_config.add_cross_attention = True return cls(encoder=encoder_config.to_dict(), decoder=decoder_config.to_dict(), **kwargs)
Instantiate a [`VisionEncoderDecoderConfig`] (or a derived class) from a pre-trained encoder model configuration and decoder model configuration. Returns: [`VisionEncoderDecoderConfig`]: An instance of a configuration object
github-repos
def check_version(self, node_id=None, timeout=2, strict=False): self._lock.acquire() end = (time.time() + timeout) while (time.time() < end): try_node = (node_id or self.least_loaded_node()) if (try_node is None): self._lock.release() raise Errors.NoBrokersAvailable() self._maybe_connect(try_node) conn = self._conns[try_node] self._refresh_on_disconnects = False try: remaining = (end - time.time()) version = conn.check_version(timeout=remaining, strict=strict, topics=list(self.config['bootstrap_topics_filter'])) if (version >= (0, 10, 0)): self._api_versions = conn.get_api_versions() self._lock.release() return version except Errors.NodeNotReadyError: if (node_id is not None): self._lock.release() raise finally: self._refresh_on_disconnects = True else: self._lock.release() raise Errors.NoBrokersAvailable()
Attempt to guess the version of a Kafka broker. Note: It is possible that this method blocks longer than the specified timeout. This can happen if the entire cluster is down and the client enters a bootstrap backoff sleep. This is only possible if node_id is None. Returns: version tuple, i.e. (0, 10), (0, 9), (0, 8, 2), ... Raises: NodeNotReadyError (if node_id is provided) NoBrokersAvailable (if node_id is None) UnrecognizedBrokerVersion: please file bug if seen! AssertionError (if strict=True): please file bug if seen!
codesearchnet
def send(self, response): self._connection.connection.set('{}:{}'.format(SIGNAL_REDIS_PREFIX, response.uid), pickle.dumps(response))
Send a response back to the client that issued a request. Args: response (Response): Reference to the response object that should be sent.
codesearchnet
def get_config_parameter_boolean(config: ConfigParser, section: str, param: str, default: bool) -> bool: try: value = config.getboolean(section, param) except (TypeError, ValueError, NoOptionError): log.warning( "Configuration variable {} not found or improper in section [{}]; " "using default of {!r}", param, section, default) value = default return value
Get Boolean parameter from ``configparser`` ``.INI`` file. Args: config: :class:`ConfigParser` object section: section name within config file param: name of parameter within section default: default value Returns: parameter value, or default
juraj-google-style
def is_github_task(task): return any(((task.get('schedulerId') == 'taskcluster-github'), task.get('extra', {}).get('tasks_for', '').startswith('github-'), is_github_url(task.get('metadata', {}).get('source', ''))))
Determine if a task is related to GitHub. This function currently looks into the ``schedulerId``, ``extra.tasks_for``, and ``metadata.source``. Args: task (dict): the task definition to check. Returns: bool: True if a piece of data refers to GitHub
codesearchnet
def __init__(self, base_object=None, query=None): if not query: raise errors.FormatError('Missing query value.') super(WMIQuerySourceType, self).__init__() self.base_object = base_object self.query = query
Initializes a source type. Args: base_object (Optional[str]): WMI base object. query (Optional[str]): WMI query. Raises: FormatError: when query is not set.
juraj-google-style
def save_to_file(self, filename, remap_dim0=None, remap_dim1=None): with open(filename, 'w') as fobj: columns = list(sorted(self._dim1)) for col in columns: fobj.write(',') fobj.write(str((remap_dim1[col] if remap_dim1 else col))) fobj.write('\n') for row in sorted(self._dim0): fobj.write(str((remap_dim0[row] if remap_dim0 else row))) for col in columns: fobj.write(',') fobj.write(str(self[(row, col)])) fobj.write('\n')
Saves matrix to the file. Args: filename: name of the file where to save matrix remap_dim0: dictionary with mapping row indices to row names which should be saved to file. If none then indices will be used as names. remap_dim1: dictionary with mapping column indices to column names which should be saved to file. If none then indices will be used as names.
codesearchnet
def __getitem__(self, key): if not isinstance(key, basestring): raise Exception("LRU cache can only be indexed by strings (%s has type %s)" % (str(key), str(type(key)))) if key in self._cache: entry = self._cache[key] entry['last_used'] = datetime.datetime.now() return entry['value'] else: raise KeyError(key)
Get an item from the cache. Args: key: a string used as the lookup key. Returns: The cached item, if any. Raises: Exception if the key is not a string. KeyError if the key is not found.
juraj-google-style
def GetEntries( self, parser_mediator, cookie_data=None, url=None, **kwargs): fields = cookie_data.split('.') number_of_fields = len(fields) if number_of_fields > 5: variables = '.'.join(fields[4:]) fields = fields[0:4] fields.append(variables) number_of_fields = len(fields) if number_of_fields not in (1, 5): parser_mediator.ProduceExtractionWarning( 'unsupported number of fields: {0:d} in cookie: {1:s}'.format( number_of_fields, self.COOKIE_NAME)) return if number_of_fields == 1: domain_hash = None try: last_visit_posix_time = int(fields[0], 10) / 10000000 except ValueError: last_visit_posix_time = None number_of_sessions = None number_of_sources = None extra_attributes = {} elif number_of_fields == 5: domain_hash = fields[0] try: last_visit_posix_time = int(fields[1], 10) except ValueError: last_visit_posix_time = None try: number_of_sessions = int(fields[2], 10) except ValueError: number_of_sessions = None try: number_of_sources = int(fields[3], 10) except ValueError: number_of_sources = None extra_variables = fields[4].split('|') extra_attributes = {} for variable in extra_variables: key, _, value = variable.partition('=') if isinstance(value, py2to3.UNICODE_TYPE) and py2to3.PY_2: try: value = codecs.decode(value, 'ascii') except UnicodeEncodeError: value = codecs.decode(value, 'ascii', errors='replace') parser_mediator.ProduceExtractionWarning( 'Cookie contains non 7-bit ASCII characters, which have been ' 'replaced with a "?".') value = urlparse.unquote(value) if py2to3.PY_2: try: value = codecs.encode(value, 'utf-8') except UnicodeDecodeError: value = codecs.encode(value, 'utf-8', errors='replace') parser_mediator.ProduceExtractionWarning( 'Cookie value did not contain a Unicode string. Non UTF-8 ' 'characters have been replaced.') extra_attributes[key] = value if last_visit_posix_time is not None: date_time = dfdatetime_posix_time.PosixTime( timestamp=last_visit_posix_time) timestamp_description = definitions.TIME_DESCRIPTION_LAST_VISITED else: date_time = dfdatetime_semantic_time.SemanticTime('Not set') timestamp_description = definitions.TIME_DESCRIPTION_NOT_A_TIME event_data = GoogleAnalyticsEventData('utmz') event_data.cookie_name = self.COOKIE_NAME event_data.domain_hash = domain_hash event_data.sessions = number_of_sessions event_data.sources = number_of_sources event_data.url = url for key, value in iter(extra_attributes.items()): setattr(event_data, key, value) event = time_events.DateTimeValuesEvent(date_time, timestamp_description) parser_mediator.ProduceEventWithEventData(event, event_data)
Extracts event objects from the cookie. Args: parser_mediator (ParserMediator): parser mediator. cookie_data (str): cookie data. url (str): URL or path where the cookie got set.
juraj-google-style
def gnuplot(script_name, args_dict={}, data=[], silent=True): gnuplot_command = 'gnuplot' if data: assert ('data' not in args_dict), "Can't use 'data' variable twice." data_temp = _GnuplotDataTemp(*data) args_dict['data'] = data_temp.name if args_dict: gnuplot_command += ' -e "' for arg in args_dict.items(): gnuplot_command += (arg[0] + '=') if isinstance(arg[1], str): gnuplot_command += (("'" + arg[1]) + "'") elif isinstance(arg[1], bool): if (arg[1] is True): gnuplot_command += '1' else: gnuplot_command += '0' elif hasattr(arg[1], '__iter__'): gnuplot_command += (("'" + ' '.join([str(v) for v in arg[1]])) + "'") else: gnuplot_command += str(arg[1]) gnuplot_command += '; ' gnuplot_command = gnuplot_command[:(- 1)] gnuplot_command += '"' gnuplot_command += (' ' + script_name) if silent: gnuplot_command += ' > /dev/null 2>&1' os.system(gnuplot_command) return gnuplot_command
Call a Gnuplot script, passing it arguments and datasets. Args: scipt_name(str): The name of the Gnuplot script. args_dict(dict): A dictionary of parameters to pass to the script. The `key` is the name of the variable that the `item` will be passed to the Gnuplot script with. data(list): A list of lists containing lists to be plotted. The lists can be accessed by plotting the variable `data` in the Gnuplot script. The first list in the list of lists corresponds to the first column in data, and so on. silent (bool): `True` if Gnuplot stdout should be silenced, `False` if not. Returns: str: The Gnuplot command used to call the script.
codesearchnet
def MakeJoint(pmf1, pmf2): joint = Joint() for v1, p1 in pmf1.Items(): for v2, p2 in pmf2.Items(): joint.Set((v1, v2), p1 * p2) return joint
Joint distribution of values from pmf1 and pmf2. Args: pmf1: Pmf object pmf2: Pmf object Returns: Joint pmf of value pairs
juraj-google-style
def case_study_social_link_facebook(value): parsed = parse.urlparse(value.lower()) if not parsed.netloc.endswith('facebook.com'): raise ValidationError(MESSAGE_NOT_FACEBOOK)
Confirms that the social media url is pointed at the correct domain. Args: value (string): The url to check. Raises: django.forms.ValidationError
juraj-google-style
def get_file_path(self, digest): relPath = Fsdb.generate_tree_path(digest, self._conf['depth']) return os.path.join(self.fsdbRoot, relPath)
Retrieve the absolute path to the file with the given digest Args: digest -- digest of the file Returns: String rapresenting the absolute path of the file
codesearchnet
def instrument(self, package, options=None, runner=None, handler=None): if (runner is None): runner = DEFAULT_INSTRUMENTATION_RUNNER if (options is None): options = {} options_list = [] for (option_key, option_value) in options.items(): options_list.append(('-e %s %s' % (option_key, option_value))) options_string = ' '.join(options_list) instrumentation_command = ('am instrument -r -w %s %s/%s' % (options_string, package, runner)) logging.info('AndroidDevice|%s: Executing adb shell %s', self.serial, instrumentation_command) if (handler is None): self._exec_adb_cmd('shell', instrumentation_command, shell=False, timeout=None, stderr=None) else: return self._execute_adb_and_process_stdout('shell', instrumentation_command, shell=False, handler=handler)
Runs an instrumentation command on the device. This is a convenience wrapper to avoid parameter formatting. Example: .. code-block:: python device.instrument( 'com.my.package.test', options = { 'class': 'com.my.package.test.TestSuite', }, ) Args: package: string, the package of the instrumentation tests. options: dict, the instrumentation options including the test class. runner: string, the test runner name, which defaults to DEFAULT_INSTRUMENTATION_RUNNER. handler: optional func, when specified the function is used to parse the instrumentation stdout line by line as the output is generated; otherwise, the stdout is simply returned once the instrumentation is finished. Returns: The stdout of instrumentation command or the stderr if the handler is set.
codesearchnet
def _list(self, dir_or_prefix): try: for path, (size, updated) in self._blobstorageIO().list_files(dir_or_prefix, with_metadata=True): yield FileMetadata(path, size, updated) except Exception as e: raise BeamIOError('List operation failed', {dir_or_prefix: e})
List files in a location. Listing is non-recursive (for filesystems that support directories). Args: dir_or_prefix: (string) A directory or location prefix (for filesystems that don't have directories). Returns: Generator of ``FileMetadata`` objects. Raises: ``BeamIOError``: if listing fails, but not if no files were found.
github-repos
def contacts(self, *args, **kwargs): n = Contacts.read_cellframe(self, prune_neighbors=True) if ('measured_regions' in kwargs): n.measured_regions = kwargs['measured_regions'] else: n.measured_regions = self.get_measured_regions() if ('measured_phenotypes' in kwargs): n.measured_phenotypes = kwargs['measured_phenotypes'] else: n.measured_phenotypes = self.phenotypes n.microns_per_pixel = self.microns_per_pixel return n
Use assess the cell-to-cell contacts recorded in the celldataframe Returns: Contacts: returns a class that holds cell-to-cell contact information for whatever phenotypes were in the CellDataFrame before execution.
codesearchnet
def load_config(self, config): for (k, v) in config.items(): if hasattr(self, k): raise DeviceError(self, ('Attribute %s already exists with value %s, cannot set again.' % (k, getattr(self, k)))) setattr(self, k, v)
Add attributes to the AndroidDevice object based on config. Args: config: A dictionary representing the configs. Raises: Error: The config is trying to overwrite an existing attribute.
codesearchnet
def _detect(self): results = [] self.results = [] self.visited_all_paths = {} for contract in self.slither.contracts: for function in contract.functions: if function.is_implemented: uninitialized_storage_variables = [v for v in function.local_variables if (v.is_storage and v.uninitialized)] function.entry_point.context[self.key] = uninitialized_storage_variables self._detect_uninitialized(function, function.entry_point, []) for (function, uninitialized_storage_variable) in self.results: var_name = uninitialized_storage_variable.name info = '{} in {}.{} ({}) is a storage variable never initialiazed\n' info = info.format(var_name, function.contract.name, function.name, uninitialized_storage_variable.source_mapping_str) json = self.generate_json_result(info) self.add_variable_to_json(uninitialized_storage_variable, json) self.add_function_to_json(function, json) results.append(json) return results
Detect uninitialized storage variables Recursively visit the calls Returns: dict: [contract name] = set(storage variable uninitialized)
codesearchnet
def _Execute(statements, context, callback, trace): if trace: trace.exec_depth += 1 for i, statement in enumerate(statements): if isinstance(statement, six.string_types): callback(statement) else: try: func, args = statement func(args, context, callback, trace) except UndefinedVariable as e: start = max(0, i - 3) end = i + 3 e.near = statements[start:end] e.trace = trace raise
Execute a bunch of template statements in a ScopedContext. Args: callback: Strings are "written" to this callback function. trace: Trace object, or None This is called in a mutually recursive fashion.
juraj-google-style
def update_variant_compounds(self, variant, variant_objs=None): compound_objs = [] for compound in variant.get('compounds', []): not_loaded = True gene_objs = [] if variant_objs: variant_obj = variant_objs.get(compound['variant']) else: variant_obj = self.variant_collection.find_one({'_id': compound['variant']}) if variant_obj: not_loaded = False compound['rank_score'] = variant_obj['rank_score'] for gene in variant_obj.get('genes', []): gene_obj = {'hgnc_id': gene['hgnc_id'], 'hgnc_symbol': gene.get('hgnc_symbol'), 'region_annotation': gene.get('region_annotation'), 'functional_annotation': gene.get('functional_annotation')} gene_objs.append(gene_obj) compound['genes'] = gene_objs compound['not_loaded'] = not_loaded compound_objs.append(compound) return compound_objs
Update compounds for a variant. This will add all the necessary information of a variant on a compound object. Args: variant(scout.models.Variant) variant_objs(dict): A dictionary with _ids as keys and variant objs as values. Returns: compound_objs(list(dict)): A dictionary with updated compound objects.
codesearchnet
def image_needs_building(image): d = docker_client() try: d.images.get(image) except docker.errors.ImageNotFound: pass else: return False return image_needs_pushing(image)
Return whether an image needs building Checks if the image exists (ignores commit range), either locally or on the registry. Args: image (str): the `repository:tag` image to be build. Returns: True: if image needs to be built False: if not (image already exists)
codesearchnet
def set_hostname(hostname=None, deploy=False): if not hostname: raise CommandExecutionError("Hostname option must not be none.") ret = {} query = {'type': 'config', 'action': 'set', 'xpath': '/config/devices/entry[@name=\'localhost.localdomain\']/deviceconfig/system', 'element': '<hostname>{0}</hostname>'.format(hostname)} ret.update(__proxy__['panos.call'](query)) if deploy is True: ret.update(commit()) return ret
Set the hostname of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: hostname (str): The hostname to set deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash salt '*' panos.set_hostname newhostname salt '*' panos.set_hostname newhostname deploy=True
juraj-google-style
def create_software_renderer(self, surface): renderer = object.__new__(Renderer) renderer._ptr = self._ptr = check_ptr_err(lib.SDL_CreateSoftwareRenderer(surface._ptr)) return renderer
Create a 2D software rendering context for a surface. Args: surface (Surface): The surface where rendering is done. Returns: Renderer: A 2D software rendering context. Raises: SDLError: If there was an error creating the renderer.
codesearchnet
def delete(self, *args, **kwargs): api = Api() api.authenticate() api.delete_video(self.video_id) return super(Video, self).delete(*args, **kwargs)
Deletes the video from youtube Raises: OperationError
codesearchnet
def SetDecryptedStreamSize(self, decrypted_stream_size): if self._is_open: raise IOError('Already open.') if (decrypted_stream_size < 0): raise ValueError('Invalid decrypted stream size: {0:d} value out of bounds.'.format(decrypted_stream_size)) self._decrypted_stream_size = decrypted_stream_size
Sets the decrypted stream size. This function is used to set the decrypted stream size if it can be determined separately. Args: decrypted_stream_size (int): size of the decrypted stream in bytes. Raises: IOError: if the file-like object is already open. OSError: if the file-like object is already open. ValueError: if the decrypted stream size is invalid.
codesearchnet
def range(cls, start=None, stop=None, step=None, inclusive=False): def sign(x): 'Inner function for determining the sign of a float\n ' return ((- 1), 1)[(x >= 0)] if (not step): raise ValueError('Null step') if isinstance(stop, timedelta): stop = (start + stop) if (sign((stop - start).total_seconds()) != sign(step.total_seconds())): raise ValueError('start/stop order not coherent with step') date = start if (step.total_seconds() > 0): oper = ('__le__' if inclusive else '__lt__') else: oper = ('__ge__' if inclusive else '__gt__') while getattr(date, oper)(stop): (yield date) date += step
Generator of a date range Args: start (Date): stop (Date or datetime.timedelta)! step (timedelta): Keyword Args: inclusive (bool): If ``False``, the stopping date is not included. This is the same behavior as the built-in :py:func:`range`. Yield: Date:
codesearchnet
def _buckets(data, bucket_count=None): import tensorflow.compat.v1 as tf if bucket_count is None: bucket_count = summary_v2.DEFAULT_BUCKET_COUNT with tf.name_scope('buckets', values=[data, bucket_count]), \ tf.control_dependencies([tf.assert_scalar(bucket_count), tf.assert_type(bucket_count, tf.int32)]): data = tf.reshape(data, shape=[-1]) data = tf.cast(data, tf.float64) is_empty = tf.equal(tf.size(input=data), 0) def when_empty(): return tf.constant([], shape=(0, 3), dtype=tf.float64) def when_nonempty(): min_ = tf.reduce_min(input_tensor=data) max_ = tf.reduce_max(input_tensor=data) range_ = max_ - min_ is_singular = tf.equal(range_, 0) def when_nonsingular(): bucket_width = range_ / tf.cast(bucket_count, tf.float64) offsets = data - min_ bucket_indices = tf.cast(tf.floor(offsets / bucket_width), dtype=tf.int32) clamped_indices = tf.minimum(bucket_indices, bucket_count - 1) one_hots = tf.one_hot(clamped_indices, depth=bucket_count) bucket_counts = tf.cast(tf.reduce_sum(input_tensor=one_hots, axis=0), dtype=tf.float64) edges = tf.linspace(min_, max_, bucket_count + 1) left_edges = edges[:-1] right_edges = edges[1:] return tf.transpose(a=tf.stack( [left_edges, right_edges, bucket_counts])) def when_singular(): center = min_ bucket_starts = tf.stack([center - 0.5]) bucket_ends = tf.stack([center + 0.5]) bucket_counts = tf.stack([tf.cast(tf.size(input=data), tf.float64)]) return tf.transpose( a=tf.stack([bucket_starts, bucket_ends, bucket_counts])) return tf.cond(is_singular, when_singular, when_nonsingular) return tf.cond(is_empty, when_empty, when_nonempty)
Create a TensorFlow op to group data into histogram buckets. Arguments: data: A `Tensor` of any shape. Must be castable to `float64`. bucket_count: Optional positive `int` or scalar `int32` `Tensor`. Returns: A `Tensor` of shape `[k, 3]` and type `float64`. The `i`th row is a triple `[left_edge, right_edge, count]` for a single bucket. The value of `k` is either `bucket_count` or `1` or `0`.
juraj-google-style
def get_header(vcf_file_path): logger.info("Parsing header of file {0}".format(vcf_file_path)) head = HeaderParser() handle = get_vcf_handle(infile=vcf_file_path) for line in handle: line = line.rstrip() if line.startswith(' if line.startswith(' head.parse_meta_data(line) else: head.parse_header_line(line) else: break handle.close() return head
Parse the header and return a header object Args: vcf_file_path(str): Path to vcf Returns: head: A HeaderParser object
juraj-google-style
def set_tensor_shapes(tensors, shapes): if shapes: tensor_names_to_tensor = {get_tensor_name(tensor): tensor for tensor in tensors} for name, shape in shapes.items(): if name not in tensor_names_to_tensor: raise ValueError("Invalid tensor '{}' found in tensor shapes map.".format(name)) if shape is not None: tensor = tensor_names_to_tensor[name] try: tensor.set_shape(shape) except ValueError as error: message = "The shape of tensor '{0}' cannot be changed from {1} to {2}. {3}".format(name, tensor.shape, shape, str(error)) raise ValueError(message)
Sets Tensor shape for each tensor if the shape is defined. Args: tensors: TensorFlow tensor.Tensor. shapes: Dict of strings representing input tensor names to list of integers representing input shapes (e.g., {"foo": : [1, 16, 16, 3]}). Raises: ValueError: `shapes` contains an invalid tensor. `shapes` contains an invalid shape for a valid tensor.
github-repos
def iter_variants(self): for variant in self.repository.iter_variants(self.resource): (yield Variant(variant, context=self.context, parent=self))
Iterate over the variants within this package, in index order. Returns: `Variant` iterator.
codesearchnet
def _on_notification_received(self, success, result, failure_reason): if not success: self._logger.info("Notification received with failure failure_reason=%s", failure_reason) notification_id = (result['connection_handle'], result['attribute_handle']) callback = None with self.notification_callbacks_lock: if notification_id in self.notification_callbacks: callback, once = self.notification_callbacks[notification_id] if once: del self.notification_callbacks[notification_id] if callback is not None: callback(result['value'])
Callback function called when a notification has been received. It is executed in the baBLE working thread: should not be blocking. Args: success (bool): A bool indicating that the operation is successful or not result (dict): The notification information - value (bytes): Data notified failure_reason (any): An object indicating the reason why the operation is not successful (else None)
juraj-google-style
def ParseRecord(self, parser_mediator, key, structure): if (key != 'log_entry'): raise errors.ParseError('Unable to parse record, unknown structure: {0:s}'.format(key)) event_data = BashHistoryEventData() event_data.command = structure.command date_time = dfdatetime_posix_time.PosixTime(timestamp=structure.timestamp) event = time_events.DateTimeValuesEvent(date_time, definitions.TIME_DESCRIPTION_MODIFICATION) parser_mediator.ProduceEventWithEventData(event, event_data)
Parses a record and produces a Bash history event. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. key (str): name of the parsed structure. structure (pyparsing.ParseResults): elements parsed from the file. Raises: ParseError: when the structure type is unknown.
codesearchnet
def complete(self, default_output=None): if not self.async: raise UnexpectedPipelineError( 'May only call complete() method for asynchronous pipelines.') self._context.fill_slot( self._pipeline_key, self.outputs.default, default_output)
Marks this asynchronous Pipeline as complete. Args: default_output: What value the 'default' output slot should be assigned. Raises: UnexpectedPipelineError if the slot no longer exists or this method was called for a pipeline that is not async.
juraj-google-style
def delete(self, filething=None): self.tags.clear() self.save(filething, padding=lambda x: 0)
delete(filething=None) Args: filething (filething) Raises: mutagen.MutagenError
juraj-google-style
def handleresult(self, r): if r.status_code >= 400 and r.status_code < 500: msg = r.json() raise AuthenticationError(str(msg["code"]) + ": " + msg["msg"] + " (" + msg["ref"] + ")") elif r.status_code > 300: err = None try: msg = r.json() err = ServerError(str(msg["code"]) + ": " + msg["msg"] + " (" + msg["ref"] + ")") except: raise ServerError( "Server returned error, but did not give a valid error message") raise err return r
Handles HTTP error codes for the given request Raises: AuthenticationError on the appropriate 4** errors ServerError if the response is not an ok (2**) Arguments: r -- The request result
juraj-google-style
def _ExtractRequestSummaryFields(self, request, error=None): headers = request.headers summary_fields = {'server': request.get_full_url(), 'contentRange': headers['Content-range'], 'contentLength': headers['Content-length']} if error: summary_fields['isError'] = True summary_fields['errorMessage'] = error.reason else: summary_fields['isError'] = False return summary_fields
Extract fields used in the summary logs. Args: request: a urllib2.Request instance configured to make the request. [optional] error: a urllib2.HttpError instance used to retrieve error details. Returns: A dict containing the fields to be output in the summary logs.
codesearchnet
def cap17(msg): allbds = ['05', '06', '07', '08', '09', '0A', '20', '21', '40', '41', '42', '43', '44', '45', '48', '50', '51', '52', '53', '54', '55', '56', '5F', '60', 'NA', 'NA', 'E1', 'E2'] d = hex2bin(data(msg)) idx = [i for (i, v) in enumerate(d[:28]) if (v == '1')] capacity = [('BDS' + allbds[i]) for i in idx if (allbds[i] is not 'NA')] return capacity
Extract capacities from BDS 1,7 message Args: msg (String): 28 bytes hexadecimal message string Returns: list: list of suport BDS codes
codesearchnet
def cancel(self, **kwargs): path = '%s/%s/cancel' % (self.manager.path, self.get_id()) self.manager.gitlab.http_post(path)
Cancel the job. Args: **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabJobCancelError: If the job could not be canceled
juraj-google-style
def put(cls, obj): return PyarrowOnRayFramePartition(ray.put(pyarrow.Table.from_pandas(obj)))
Put an object in the Plasma store and wrap it in this object. Args: obj: The object to be put. Returns: A `RayRemotePartition` object.
codesearchnet
def set_bias(self, bias): self.x_offset += (bias - self._bias) self._bias = bias self._build_cdict()
Adjusts the image bias. Bias determines where the color changes start. At low bias, low intensities (i.e., low pixel values) will have non-zero color differences, while at high bias only high pixel values will have non-zero differences Args: bias: float A number between 0 and 1. Note that upon initialization the colormap has a default bias of 0.5. Returns: void
juraj-google-style
def set_key(self, structure_prefix, key_line): self._empty = False key_value = self._remove_structure_prefix(structure_prefix, key_line) if '=' in key_value: key, value = key_value.split('=', 1) self.current_key = key if key in self.known_keys: self.known_keys[key].append(value) else: self.unknown_keys[key].append(key_value)
Sets the current key for the instrumentation block. For unknown keys, the key is added to the value list in order to better contextualize the value in the output. Args: structure_prefix: string, the structure prefix that was matched and that needs to be removed. key_line: string, the raw instrumentation output line that contains the key-value pair.
github-repos
def _splitGenoSlidingWindow(self,size=5e4,step=None,minSnps=1.,maxSnps=SP.inf): if step is None: step = 0.5*size chroms = SP.unique(self.chrom) wnd_pos = [] idx_wnd_start = [] nSnps = [] wnd_i = 0 nSnps = [] for chrom_i in chroms: start = 0 Ichrom = self.chrom==chrom_i idx_chrom_start = SP.where(Ichrom)[0][0] pos_chr = self.pos[Ichrom] pos_chr_max = pos_chr.max() while 1: if start>pos_chr_max: break end = start+size Ir = (self.pos>=start)*(self.pos<end) _nSnps = Ir.sum() if _nSnps>minSnps and _nSnps<maxSnps: wnd_pos.append([chrom_i,start,start+size]) nSnps.append(_nSnps) idx_wnd_start.append(idx_chrom_start+SP.where(Ir)[0][0]) wnd_i+=1 start += step self._wnd_pos = SP.array(wnd_pos) self._idx_wnd_start = SP.array(idx_wnd_start) self._nSnps = SP.array(nSnps)
split into windows using a slide criterion Args: size: window size step: moving step (default: 0.5*size) minSnps: only windows with nSnps>=minSnps are considered maxSnps: only windows with nSnps>=maxSnps are considered
juraj-google-style
def global_horizontal_radiation(self, value=9999.0): if (value is not None): try: value = float(value) except ValueError: raise ValueError('value {} need to be of type float for field `global_horizontal_radiation`'.format(value)) if (value < 0.0): raise ValueError('value need to be greater or equal 0.0 for field `global_horizontal_radiation`') self._global_horizontal_radiation = value
Corresponds to IDD Field `global_horizontal_radiation` Args: value (float): value for IDD Field `global_horizontal_radiation` Unit: Wh/m2 value >= 0.0 Missing value: 9999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
codesearchnet
def JoinPath(stem='', *parts): parts = [SmartUnicode(path) for path in parts] result = (stem + NormalizePath(u'/'.join(parts))).replace(' result = result.rstrip('/') return (result or '/')
A sane version of os.path.join. The intention here is to append the stem to the path. The standard module removes the path if the stem begins with a /. Args: stem: The stem to join to. *parts: parts of the path to join. The first arg is always the root and directory traversal is not allowed. Returns: a normalized path.
codesearchnet
def conv2d_transpose(x, kernel, output_shape, strides=(1, 1), padding='valid', data_format=None, dilation_rate=(1, 1)): if data_format is None: data_format = image_data_format() if data_format not in {'channels_first', 'channels_last'}: raise ValueError('Unknown data_format: ' + str(data_format)) if data_format == 'channels_first' and dilation_rate != (1, 1): force_transpose = True else: force_transpose = False x, tf_data_format = _preprocess_conv2d_input(x, data_format, force_transpose) if data_format == 'channels_first' and tf_data_format == 'NHWC': output_shape = (output_shape[0], output_shape[2], output_shape[3], output_shape[1]) if output_shape[0] is None: output_shape = (shape(x)[0],) + tuple(output_shape[1:]) if isinstance(output_shape, (tuple, list)): output_shape = array_ops_stack.stack(list(output_shape)) padding = _preprocess_padding(padding) if tf_data_format == 'NHWC': strides = (1,) + strides + (1,) else: strides = (1, 1) + strides if dilation_rate == (1, 1): x = nn.conv2d_transpose(x, kernel, output_shape, strides, padding=padding, data_format=tf_data_format) else: assert dilation_rate[0] == dilation_rate[1] x = nn.atrous_conv2d_transpose(x, kernel, output_shape, rate=dilation_rate[0], padding=padding) if data_format == 'channels_first' and tf_data_format == 'NHWC': x = array_ops.transpose(x, (0, 3, 1, 2)) return x
2D deconvolution (i.e. transposed convolution). Args: x: Tensor or variable. kernel: kernel tensor. output_shape: 1D int tensor for the output shape. strides: strides tuple. padding: string, `"same"` or `"valid"`. data_format: string, `"channels_last"` or `"channels_first"`. dilation_rate: Tuple of 2 integers. Returns: A tensor, result of transposed 2D convolution. Raises: ValueError: if `data_format` is neither `channels_last` or `channels_first`.
github-repos
def map_creative_and_association_feeds(self, creative_feed, creative_association_feed): for creative in creative_feed: creative['associations'] = [association for association in creative_association_feed if self._assignment_matches(creative, association)]
Maps creative association feed to the corresponding creative. Creative association is a child object to the creative, and there is a 1 creative to many creative association relationship. In Bulkdozer they are represented by two separate tab in the feed, and this method maps the creatives to their respective creative association based on the creative ID. Args: creative_feed: Creative feed. creative_association_feed: Creative association feed.
github-repos
def get_read_write_resource_inputs(op): reads = object_identity.ObjectIdentitySet() writes = object_identity.ObjectIdentitySet() if op.type in RESOURCE_READ_OPS: reads.update((t for t in op.inputs if t.dtype == dtypes.resource)) return (reads, writes) try: read_only_input_indices = op.get_attr(READ_ONLY_RESOURCE_INPUTS_ATTR) except ValueError: writes.update((t for t in op.inputs if t.dtype == dtypes.resource)) return (reads, writes) read_only_index = 0 for i, t in enumerate(op.inputs): if op.inputs[i].dtype != dtypes.resource: continue if read_only_index < len(read_only_input_indices) and i == read_only_input_indices[read_only_index]: reads.add(op.inputs[i]) read_only_index += 1 else: writes.add(op.inputs[i]) return (reads, writes)
Returns a tuple of resource reads, writes in op.inputs. Args: op: Operation Returns: A 2-tuple of ObjectIdentitySets, the first entry containing read-only resource handles and the second containing read-write resource handles in `op.inputs`.
github-repos
def refer(self, text): data = self.reply(text) data['refer_key'] = self['key'] return data
Refers current message and replys a new message Args: text(str): message content Returns: RTMMessage
juraj-google-style
def get_optional_artifacts_per_task_id(upstream_artifacts): optional_artifacts_per_task_id = {} for artifact_definition in upstream_artifacts: if (artifact_definition.get('optional', False) is True): task_id = artifact_definition['taskId'] artifacts_paths = artifact_definition['paths'] add_enumerable_item_to_dict(dict_=optional_artifacts_per_task_id, key=task_id, item=artifacts_paths) return optional_artifacts_per_task_id
Return every optional artifact defined in ``upstream_artifacts``, ordered by taskId. Args: upstream_artifacts: the list of upstream artifact definitions Returns: dict: list of paths to downloaded artifacts ordered by taskId
codesearchnet
def check_satpy(readers=None, writers=None, extras=None): from satpy.readers import configs_for_reader from satpy.writers import configs_for_writer print('Readers') print('=======') for (reader, res) in sorted(check_yaml_configs(configs_for_reader(reader=readers), 'reader').items()): print((reader + ': '), res) print() print('Writers') print('=======') for (writer, res) in sorted(check_yaml_configs(configs_for_writer(writer=writers), 'writer').items()): print((writer + ': '), res) print() print('Extras') print('======') module_names = (extras if (extras is not None) else ('cartopy', 'geoviews')) for (module_name, res) in sorted(_check_import(module_names).items()): print((module_name + ': '), res) print()
Check the satpy readers and writers for correct installation. Args: readers (list or None): Limit readers checked to those specified writers (list or None): Limit writers checked to those specified extras (list or None): Limit extras checked to those specified Returns: bool True if all specified features were successfully loaded.
codesearchnet
def cluster_spec(self): task_list = [] self._gpu_allocation = [] self._cluster_allocation = {} for host, num_tasks in sorted(self._task_configuration.items()): for port_offset, gpu_offset in zip(range(num_tasks), range(0, self._gpus_per_node, self._gpus_per_task)): host_addr = '%s:%d' % (host, self._port_base + port_offset) task_list.append(host_addr) gpu_id_list = [] for gpu_id in range(gpu_offset, gpu_offset + self._gpus_per_task): gpu_id_list.append(str(gpu_id)) self._gpu_allocation.append(','.join(gpu_id_list)) cluster_rank_offset_start = 0 cluster_rank_offset_end = 0 for task_type, num_tasks in sorted(self._jobs.items()): cluster_rank_offset_end = cluster_rank_offset_start + num_tasks self._cluster_allocation[task_type] = task_list[cluster_rank_offset_start:cluster_rank_offset_end] if cluster_rank_offset_start <= self._rank < cluster_rank_offset_end: self.task_type = task_type self.task_id = self._rank - cluster_rank_offset_start cluster_rank_offset_start = cluster_rank_offset_end if self._auto_set_gpu: os.environ['CUDA_VISIBLE_DEVICES'] = self._gpu_allocation[self._rank] return ClusterSpec(self._cluster_allocation)
Returns a ClusterSpec object based on the latest instance group info. This returns a ClusterSpec object for use based on information from the specified initialization parameters and Slurm environment variables. The cluster specification is resolved each time this function is called. The resolver extract hostnames of nodes by scontrol and pack tasks in that order until a node a has number of tasks that is equal to specification. GPUs on nodes are allocated to tasks by specification through setting CUDA_VISIBLE_DEVICES environment variable. Returns: A ClusterSpec containing host information retrieved from Slurm's environment variables.
github-repos
def create_keyvault(access_token, subscription_id, rgname, vault_name, location, template_deployment=True, tenant_id=None, object_id=None): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', rgname, '/providers/Microsoft.KeyVault/vaults/', vault_name, '?api-version=', KEYVAULT_API]) if (tenant_id is None): ret = list_tenants(access_token) tenant_id = ret['value'][0]['tenantId'] access_policies = [{'tenantId': tenant_id, 'objectId': object_id, 'permissions': {'keys': ['get', 'create', 'delete', 'list', 'update', 'import', 'backup', 'restore', 'recover'], 'secrets': ['get', 'list', 'set', 'delete', 'backup', 'restore', 'recover'], 'certificates': ['get', 'list', 'delete', 'create', 'import', 'update', 'managecontacts', 'getissuers', 'listissuers', 'setissuers', 'deleteissuers', 'manageissuers', 'recover'], 'storage': ['get', 'list', 'delete', 'set', 'update', 'regeneratekey', 'setsas', 'listsas', 'getsas', 'deletesas']}}] vault_properties = {'tenantId': tenant_id, 'sku': {'family': 'A', 'name': 'standard'}, 'enabledForTemplateDeployment': template_deployment, 'accessPolicies': access_policies} vault_body = {'location': location, 'properties': vault_properties} body = json.dumps(vault_body) return do_put(endpoint, body, access_token)
Create a new key vault in the named resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. vault_name (str): Name of the new key vault. location (str): Azure data center location. E.g. westus2. template_deployment (boolean): Whether to allow deployment from template. tenant_id (str): Optionally specify a tenant ID (otherwise picks first response) from ist_tenants(). object_id (str): Optionally specify an object ID representing user or principal for the access policy. Returns: HTTP response. JSON body of key vault properties.
codesearchnet