code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def from_mapping(cls, mapping): out = cls() for (elem, count) in mapping.items(): out._set_count(elem, count) return out
Create a bag from a dict of elem->count. Each key in the dict is added if the value is > 0. Raises: ValueError: If any count is < 0.
codesearchnet
def __init__(self, input_reader=None, output_writer=None): super(ImageExportTool, self).__init__( input_reader=input_reader, output_writer=output_writer) self._abort = False self._artifact_definitions_path = None self._artifact_filters = None self._artifacts_registry = None self._custom_artifacts_path = None self._destination_path = None self._digests = {} self._filter_collection = file_entry_filters.FileEntryFilterCollection() self._filter_file = None self._path_spec_extractor = extractors.PathSpecExtractor() self._process_memory_limit = None self._resolver_context = context.Context() self._skip_duplicates = True self._source_type = None self.has_filters = False self.list_signature_identifiers = False
Initializes the CLI tool object. Args: input_reader (Optional[InputReader]): input reader, where None indicates that the stdin input reader should be used. output_writer (Optional[OutputWriter]): output writer, where None indicates that the stdout output writer should be used.
juraj-google-style
def get_tld(url): if url not in URLHelper.__cache: URLHelper.__cache[url] = urlparse(url) parts = URLHelper.__cache[url].netloc.split(".") if len(parts) == 1: return "" else: return parts[-1]
Get the tld of the given URL. Args: url (str): The URL to get the tld from. Returns: str: The tld
juraj-google-style
def update_subscription(self, *, subscription_id, credit_card_token): payload = { "creditCardToken": credit_card_token } fmt = 'subscriptions/{}'.format(subscription_id) return self.client._put(self.url + fmt, json=payload, headers=self.get_headers())
Update information associated with the specified subscription. At the moment it is only possible to update the token of the credit card to which the charge of the subscription is made. Args: subscription_id: Identification of the subscription. credit_card_token: Returns:
juraj-google-style
def calculate_part_visibility(self, ports): source_port_lookup = {} for part_name, port_infos in SourcePortInfo.filter_parts(ports).items(): for port_info in port_infos: source_port_lookup[port_info.connected_value] = ( part_name, port_info.port) for part_name, port_infos in SinkPortInfo.filter_parts( ports).items(): for port_info in port_infos: if port_info.value != port_info.disconnected_value: conn_part, port = source_port_lookup.get( port_info.value, (None, None)) if conn_part and port == port_info.port: if conn_part not in self.part_visibility: self.part_visibility[conn_part] = True if part_name not in self.part_visibility: self.part_visibility[part_name] = True
Calculate what is connected to what Args: ports: {part_name: [PortInfo]} from other ports
juraj-google-style
def point_dist2(p1, p2): v = vector(p1, p2) return np.dot(v, v)
compute the square of the euclidian distance between two 3D points Args: p1, p2: indexable objects with indices 0, 1, 2 corresponding to 3D cartesian coordinates. Returns: The square of the euclidian distance between the points.
juraj-google-style
def _print_task_data(self, task): print(' {0:s} ({1:s})'.format(task['name'], task['id'])) paths = task.get('saved_paths', []) if (not paths): return for path in paths: if path.endswith('worker-log.txt'): continue if path.endswith('{0:s}.log'.format(task.get('id'))): continue if path.startswith('/'): continue print((' ' + path))
Pretty-prints task data. Args: task: Task dict generated by Turbinia.
codesearchnet
def read(self, length, timeout): self._read_messages_until_true( lambda: self._buffer_size and self._buffer_size >= length, timeout) with self._read_buffer_lock: data, push_back = ''.join(self._read_buffer), '' if length: data, push_back = data[:length], data[length:] self._read_buffer.clear() self._buffer_size = len(push_back) if push_back: self._read_buffer.appendleft(push_back) return data
Read 'length' bytes from this stream transport. Args: length: If not 0, read this many bytes from the stream, otherwise read all available data (at least one byte). timeout: timeouts.PolledTimeout to use for this read operation. Returns: The bytes read from this stream.
juraj-google-style
def parse_mip_analysis(mip_config_raw: dict, qcmetrics_raw: dict, sampleinfo_raw: dict) -> dict: outdata = _define_output_dict() _config(mip_config_raw, outdata) _qc_metrics(outdata, qcmetrics_raw) _qc_sample_info(outdata, sampleinfo_raw) return outdata
Parse the output analysis files from MIP for adding info to trend database Args: mip_config_raw (dict): raw YAML input from MIP analysis config file qcmetrics_raw (dict): raw YAML input from MIP analysis qc metric file sampleinfo_raw (dict): raw YAML input from MIP analysis qc sample info file Returns: dict: parsed data
juraj-google-style
def isnan(self: EventSetOrNode) -> EventSetOrNode: from temporian.core.operators.unary import isnan return isnan(self)
Returns boolean features, `True` in the NaN elements of the [`EventSet`][temporian.EventSet]. Note that for `int` and `bool` this will always be `False` since those types don't support NaNs. It only makes actual sense to use on `float` (or `tp.float32`) features. See also `evset.notnan()`. Example: ```python >>> a = tp.event_set( ... timestamps=[1, 2, 3], ... features={"M":[np.nan, 5., np.nan], "N": [-1, 0, 5]}, ... ) >>> b = a.isnan() >>> b indexes: ... 'M': [ True False True] 'N': [False False False] ... >>> # Count nans >>> b["M"].cast(int).cumsum() indexes: ... timestamps: [1. 2. 3.] 'M': [1 1 2] ... ``` Returns: EventSet with boolean features.
github-repos
def _MergeDifferentId(self): for a in self._GetIter(self.feed_merger.a_schedule): for b in self._GetIter(self.feed_merger.b_schedule): try: self._Add(a, b, self._MergeEntities(a, b)) self._num_merged += 1 except MergeError: continue for a in self._GetIter(self.feed_merger.a_schedule): if (a not in self.feed_merger.a_merge_map): self._num_not_merged_a += 1 newid = self._HasId(self.feed_merger.b_schedule, self._GetId(a)) self._Add(a, None, self._Migrate(a, self.feed_merger.a_schedule, newid)) for b in self._GetIter(self.feed_merger.b_schedule): if (b not in self.feed_merger.b_merge_map): self._num_not_merged_b += 1 newid = self._HasId(self.feed_merger.a_schedule, self._GetId(b)) self._Add(None, b, self._Migrate(b, self.feed_merger.b_schedule, newid)) return self._num_merged
Tries to merge all possible combinations of entities. This tries to merge every entity in the old schedule with every entity in the new schedule. Unlike _MergeSameId, the ids do not need to match. However, _MergeDifferentId is much slower than _MergeSameId. This method makes use of various methods like _Merge and _Migrate which are not implemented in the abstract DataSetMerger class. These method should be overwritten in a subclass to allow _MergeSameId to work with different entity types. Returns: The number of merged entities.
codesearchnet
def categorytree(self, category, depth=5): def __cat_tree_rec(cat, depth, tree, level, categories, links): ' recursive function to build out the tree ' tree[cat] = dict() tree[cat]['depth'] = level tree[cat]['sub-categories'] = dict() tree[cat]['links'] = list() tree[cat]['parent-categories'] = list() parent_cats = list() if (cat not in categories): tries = 0 while True: if (tries > 10): raise MediaWikiCategoryTreeError(cat) try: pag = self.page('{0}:{1}'.format(self.category_prefix, cat)) categories[cat] = pag parent_cats = categories[cat].categories links[cat] = self.categorymembers(cat, results=None, subcategories=True) break except PageError: raise PageError('{0}:{1}'.format(self.category_prefix, cat)) except KeyboardInterrupt: raise except Exception: tries = (tries + 1) time.sleep(1) else: parent_cats = categories[cat].categories tree[cat]['parent-categories'].extend(parent_cats) tree[cat]['links'].extend(links[cat][0]) if (depth and (level >= depth)): for ctg in links[cat][1]: tree[cat]['sub-categories'][ctg] = None else: for ctg in links[cat][1]: __cat_tree_rec(ctg, depth, tree[cat]['sub-categories'], (level + 1), categories, links) if (not isinstance(category, list)): cats = [category] else: cats = category if ((len(cats) == 1) and ((cats[0] is None) or (cats[0] == ''))): msg = "CategoryTree: Parameter 'category' must either be a list of one or more categories or a string; provided: '{}'".format(category) raise ValueError(msg) if ((depth is not None) and (depth < 1)): msg = "CategoryTree: Parameter 'depth' must be either None (for the full tree) or be greater than 0" raise ValueError(msg) results = dict() categories = dict() links = dict() for cat in cats: if ((cat is None) or (cat == '')): continue __cat_tree_rec(cat, depth, results, 0, categories, links) return results
Generate the Category Tree for the given categories Args: category(str or list of strings): Category name(s) depth(int): Depth to traverse the tree Returns: dict: Category tree structure Note: Set depth to **None** to get the whole tree Note: Return Data Structure: Subcategory contains the same \ recursive structure >>> { 'category': { 'depth': Number, 'links': list, 'parent-categories': list, 'sub-categories': dict } } .. versionadded:: 0.3.10
codesearchnet
def find_synonym(self, word): if (word and self.synonyms): reverse_lookup = {} for (k, v) in self.synonyms.items(): for i in v: reverse_lookup[i.lower()] = k.lower() if (word.lower() in reverse_lookup): return reverse_lookup[word.lower()] return word
Given a string and a dict of synonyms, returns the 'preferred' word. Case insensitive. Args: word (str): A word. Returns: str: The preferred word, or the input word if not found. Example: >>> syn = {'snake': ['python', 'adder']} >>> find_synonym('adder', syn) 'snake' >>> find_synonym('rattler', syn) 'rattler' TODO: Make it handle case, returning the same case it received.
codesearchnet
def _set_label(self, which, label, **kwargs): prop_default = { 'fontsize': 18, } for prop, default in prop_default.items(): kwargs[prop] = kwargs.get(prop, default) setattr(self.label, which, label) setattr(self.label, which + '_kwargs', kwargs) return
Private method for setting labels. Args: which (str): The indicator of which part of the plots to adjust. This currently handles `xlabel`/`ylabel`, and `title`. label (str): The label to be added. fontsize (int, optional): Fontsize for associated label. Default is None.
juraj-google-style
def enable_store_parameters_in_results(kernel): kernel_stack = [] while (hasattr(kernel, 'parameters') and ('inner_kernel' in kernel.parameters)): kernel_stack.append(kernel) kernel = kernel.parameters['inner_kernel'] def _recreate_kernel(kernel, parameters): new_parameters = kernel.parameters.copy() new_parameters.update(parameters) if ('store_parameters_in_results' in new_parameters): new_parameters['store_parameters_in_results'] = True with deprecation.silence(): return type(kernel)(**new_parameters) if hasattr(kernel, 'parameters'): kernel = _recreate_kernel(kernel, {}) for outer_kernel in reversed(kernel_stack): outer_kernel = _recreate_kernel(outer_kernel, {'inner_kernel': kernel}) kernel = outer_kernel return kernel
Enables the `store_parameters_in_results` parameter in a chain of kernels. This is a temporary utility for use during the transition period of the parameter storage methods. Args: kernel: A TransitionKernel. Returns: kernel: The same kernel, but recreated with `store_parameters_in_results` recursively set to `True` in its parameters and its inner kernels (as appropriate).
codesearchnet
def __validate_args(self, func_name, args, kwargs): from pyvalid.validators import Validator for (i, (arg_name, accepted_values)) in enumerate(self.accepted_args): if (i < len(args)): value = args[i] elif (arg_name in kwargs): value = kwargs[arg_name] elif (i in self.optional_args): continue else: raise InvalidArgumentNumberError(func_name) is_valid = False for accepted_val in accepted_values: is_validator = (isinstance(accepted_val, Validator) or (isinstance(accepted_val, MethodType) and hasattr(accepted_val, '__func__') and isinstance(accepted_val.__func__, Validator))) if is_validator: is_valid = accepted_val(value) elif isinstance(accepted_val, type): is_valid = isinstance(value, accepted_val) else: is_valid = (value == accepted_val) if is_valid: break if (not is_valid): ord_num = self.__ordinal((i + 1)) raise ArgumentValidationError(ord_num, func_name, value, accepted_values)
Compare value of each required argument with list of accepted values. Args: func_name (str): Function name. args (list): Collection of the position arguments. kwargs (dict): Collection of the keyword arguments. Raises: InvalidArgumentNumberError: When position or count of the arguments is incorrect. ArgumentValidationError: When encountered unexpected argument value.
codesearchnet
def get_video_transcript_data(video_id, language_code): video_transcript = VideoTranscript.get_or_none(video_id, language_code) if video_transcript: try: return dict(file_name=video_transcript.filename, content=video_transcript.transcript.file.read()) except Exception: logger.exception( '[edx-val] Error while retrieving transcript for video=%s -- language_code=%s', video_id, language_code ) raise
Get video transcript data Arguments: video_id(unicode): An id identifying the Video. language_code(unicode): it will be the language code of the requested transcript. Returns: A dict containing transcript file name and its content.
juraj-google-style
def compile_date(self): result = self._dll.JLINKARM_GetCompileDateTime() return ctypes.cast(result, ctypes.c_char_p).value.decode()
Returns a string specifying the date and time at which the DLL was translated. Args: self (JLink): the ``JLink`` instance Returns: Datetime string.
juraj-google-style
def load(self, spec): if spec.template is not None: return self.loader.unicode(spec.template, spec.template_encoding) path = self._find(spec) return self.loader.read(path, spec.template_encoding)
Find and return the template associated to a TemplateSpec instance. Returns the template as a unicode string. Arguments: spec: a TemplateSpec instance.
juraj-google-style
def get_extended_attention_mask(self, attention_mask: torch.Tensor, input_shape: Tuple[int], device: torch.device, has_query: bool=False) -> torch.Tensor: if attention_mask.dim() == 3: extended_attention_mask = attention_mask[:, None, :, :] elif attention_mask.dim() == 2: extended_attention_mask = attention_mask[:, None, None, :] else: raise ValueError(f'Wrong shape for input_ids (shape {input_shape}) or attention_mask (shape {attention_mask.shape})') extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0 return extended_attention_mask
Makes broadcastable attention and causal masks so that future and masked tokens are ignored. Arguments: attention_mask (`torch.Tensor`): Mask with ones indicating tokens to attend to, zeros for tokens to ignore. input_shape (`Tuple[int]`): The shape of the input to the model. device: (`torch.device`): The device of the input to the model. Returns: `torch.Tensor` The extended attention mask, with a the same dtype as `attention_mask.dtype`.
github-repos
def validate_element(self, value): if (not isinstance(value, self.type)): if (isinstance(value, six.integer_types) and (self.type == float)): return float(value) if (value is None): if self.required: raise ValidationError('Required field is missing') else: try: name = self.name except AttributeError: raise ValidationError(('Expected type %s for %s, found %s (type %s)' % (self.type, self.__class__.__name__, value, type(value)))) else: raise ValidationError(('Expected type %s for field %s, found %s (type %s)' % (self.type, name, value, type(value)))) return value
Validate single element of field. This is different from validate in that it is used on individual values of repeated fields. Args: value: Value to validate. Returns: The value casted in the expected type. Raises: ValidationError if value is not expected type.
codesearchnet
def CheckTrailingSemicolon(filename, clean_lines, linenum, error): line = clean_lines.elided[linenum] match = Match('^(.*\\)\\s*)\\{', line) if match: closing_brace_pos = match.group(1).rfind(')') opening_parenthesis = ReverseCloseExpression(clean_lines, linenum, closing_brace_pos) if (opening_parenthesis[2] > (- 1)): line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]] macro = Search('\\b([A-Z_][A-Z0-9_]*)\\s*$', line_prefix) func = Match('^(.*\\])\\s*$', line_prefix) if ((macro and (macro.group(1) not in ('TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST', 'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED', 'LOCKS_EXCLUDED', 'INTERFACE_DEF'))) or (func and (not Search('\\boperator\\s*\\[\\s*\\]', func.group(1)))) or Search('\\b(?:struct|union)\\s+alignas\\s*$', line_prefix) or Search('\\bdecltype$', line_prefix) or Search('\\s+=\\s*$', line_prefix)): match = None if (match and (opening_parenthesis[1] > 1) and Search('\\]\\s*$', clean_lines.elided[(opening_parenthesis[1] - 1)])): match = None else: match = Match('^(.*(?:else|\\)\\s*const)\\s*)\\{', line) if (not match): prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if (prevline and Search('[;{}]\\s*$', prevline)): match = Match('^(\\s*)\\{', line) if match: (endline, endlinenum, endpos) = CloseExpression(clean_lines, linenum, len(match.group(1))) if ((endpos > (- 1)) and Match('^\\s*;', endline[endpos:])): raw_lines = clean_lines.raw_lines ParseNolintSuppressions(filename, raw_lines[(endlinenum - 1)], (endlinenum - 1), error) ParseNolintSuppressions(filename, raw_lines[endlinenum], endlinenum, error) error(filename, endlinenum, 'readability/braces', 4, "You don't need a ; after a }")
Looks for redundant trailing semicolon. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
codesearchnet
def _parameter_net(self, theta, kernel_shape=9): with argscope(FullyConnected, nl=tf.nn.leaky_relu): net = FullyConnected('fc1', theta, 64) net = FullyConnected('fc2', net, 128) pred_filter = FullyConnected('fc3', net, kernel_shape ** 2, nl=tf.identity) pred_filter = tf.reshape(pred_filter, [BATCH, kernel_shape, kernel_shape, 1], name="pred_filter") logger.info('Parameter net output: {}'.format(pred_filter.get_shape().as_list())) return pred_filter
Estimate filters for convolution layers Args: theta: angle of filter kernel_shape: size of each filter Returns: learned filter as [B, k, k, 1]
juraj-google-style
def _concat(self): if len(self._variable_list) == 1: with ops.name_scope(None): return array_ops.identity(self._variable_list[0], name=self._name) partition_axes = self._partition_axes() if len(partition_axes) > 1: raise NotImplementedError('Cannot concatenate along more than one dimension: %s. Multi-axis partition concat is not supported' % str(partition_axes)) partition_ix = partition_axes[0] with ops.name_scope(self._name + '/ConcatPartitions/'): concatenated = array_ops.concat(self._variable_list, partition_ix) with ops.name_scope(None): return array_ops.identity(concatenated, name=self._name)
Returns the overall concatenated value as a `Tensor`. This is different from using the partitioned variable directly as a tensor (through tensor conversion and `as_tensor`) in that it creates a new set of operations that keeps the control dependencies from its scope. Returns: `Tensor` containing the concatenated value.
github-repos
def to_dict(self): d = {} d[TestResultEnums.RECORD_NAME] = self.test_name d[TestResultEnums.RECORD_CLASS] = self.test_class d[TestResultEnums.RECORD_BEGIN_TIME] = self.begin_time d[TestResultEnums.RECORD_END_TIME] = self.end_time d[TestResultEnums.RECORD_RESULT] = self.result d[TestResultEnums.RECORD_UID] = self.uid d[TestResultEnums.RECORD_SIGNATURE] = self.signature d[TestResultEnums.RECORD_RETRY_PARENT] = self.retry_parent.signature if self.retry_parent else None d[TestResultEnums.RECORD_PARENT] = {'parent': self.parent[0].signature, 'type': self.parent[1].value} if self.parent else None d[TestResultEnums.RECORD_EXTRAS] = self.extras d[TestResultEnums.RECORD_DETAILS] = self.details d[TestResultEnums.RECORD_TERMINATION_SIGNAL_TYPE] = self.termination_signal_type d[TestResultEnums.RECORD_EXTRA_ERRORS] = {key: value.to_dict() for key, value in self.extra_errors.items()} d[TestResultEnums.RECORD_STACKTRACE] = self.stacktrace return d
Gets a dictionary representating the content of this class. Returns: A dictionary representating the content of this class.
github-repos
def status(self, order_id): self.logger.debug('Get status of order ' + order_id) url = '%(base_url)s/order/%(order_id)s' % { 'base_url': self.base_url, 'order_id': order_id } r = self.gbdx_connection.get(url) r.raise_for_status() return r.json().get("acquisitions", {})
Checks imagery order status. There can be more than one image per order and this function returns the status of all images within the order. Args: order_id (str): The id of the order placed. Returns: List of dictionaries, one per image. Each dictionary consists of the keys 'acquisition_id', 'location' and 'state'.
juraj-google-style
def remove_sites_from_neighbours( self, remove_labels ): if type( remove_labels ) is str: remove_labels = [ remove_labels ] self.neighbours = set( n for n in self.neighbours if n.label not in remove_labels )
Removes sites from the set of neighbouring sites if these have labels in remove_labels. Args: Remove_labels (List) or (Str): List of Site labels to be removed from the cluster neighbour set. Returns: None
juraj-google-style
def dimension_values(self, dimension, expanded=True, flat=True): index = self.get_dimension_index(dimension) if index == 0: return np.array([self.data if np.isscalar(self.data) else self.data[index]]) elif index == 1: return [] if np.isscalar(self.data) else np.array([self.data[1]]) else: return super(Annotation, self).dimension_values(dimension)
Return the values along the requested dimension. Args: dimension: The dimension to return values for expanded (bool, optional): Whether to expand values flat (bool, optional): Whether to flatten array Returns: NumPy array of values along the requested dimension
juraj-google-style
def Match(self, file_entry): if not file_entry: return False filename = file_entry.name.lower() return filename == self._filename
Determines if a file entry matches the filter. Args: file_entry (dfvfs.FileEntry): a file entry. Returns: bool: True if the file entry matches the filter.
juraj-google-style
def _build_request(self, verb, verb_arguments): method = getattr(self._component, verb) method_args = {str(k): v for k, v in verb_arguments.items()} return method(**method_args)
Builds HttpRequest object. Args: verb (str): Request verb (ex. insert, update, delete). verb_arguments (dict): Arguments to be passed with the request. Returns: httplib2.HttpRequest: HttpRequest to be sent to the API.
juraj-google-style
def extract_lookups(value): lookups = set() if isinstance(value, basestring): lookups = lookups.union(extract_lookups_from_string(value)) elif isinstance(value, list): for v in value: lookups = lookups.union(extract_lookups(v)) elif isinstance(value, dict): for v in value.values(): lookups = lookups.union(extract_lookups(v)) return lookups
Recursively extracts any stack lookups within the data structure. Args: value (one of str, list, dict): a structure that contains lookups to output values Returns: list: list of lookups if any
juraj-google-style
def _validate_chain_strength(sampler, chain_strength): properties = sampler.properties if 'extended_j_range' in properties: max_chain_strength = - min(properties['extended_j_range']) elif 'j_range' in properties: max_chain_strength = - min(properties['j_range']) else: raise ValueError("input sampler should have 'j_range' and/or 'extended_j_range' property.") if chain_strength is None: chain_strength = max_chain_strength elif chain_strength > max_chain_strength: raise ValueError("Provided chain strength exceedds the allowed range.") return chain_strength
Validate the provided chain strength, checking J-ranges of the sampler's children. Args: chain_strength (float) The provided chain strength. Use None to use J-range. Returns (float): A valid chain strength, either provided or based on available J-range. Positive finite float.
juraj-google-style
def __init__(self, counter_factory, state_sampler): self._counter_factory = counter_factory self._state_sampler = state_sampler self._latest_step = None self.bytes_read_counter = None self.scoped_state = None
Create a new IO read counter. Args: counter_factory: A counters.CounterFactory to create byte counters. state_sampler: A statesampler.StateSampler to transition into read states.
github-repos
def partial_tile(cls, tile_assignment): if not isinstance(tile_assignment, _np.ndarray): raise TypeError('PartialTile assignment must be of type np.ndarray') dims = list(tile_assignment.shape) flattened_devices = tile_assignment.reshape(-1, order='C') return Sharding(proto=xla_data_pb2.OpSharding(type=xla_data_pb2.OpSharding.OTHER, tile_assignment_dimensions=dims, tile_assignment_devices=list(flattened_devices), replicate_on_last_tile_dim=True))
Returns a partially tiled sharding attribute. This is similar to tile(), but tile_assignment has one more dimension than the tensor, and tiles in the last dimension of tile_assignment are replicated. Args: tile_assignment: An np.ndarray describing the topology of the tiling and which device will compute which part of the topology. Raises: TypeError: tile_assignment was not of np.array type.
github-repos
def has_no_error(state, incorrect_msg='Your code generated an error. Fix it and try again!'): if state.reporter.get_errors(): state.do_test(incorrect_msg) return state
Check whether the submission did not generate a runtime error. Simply use ``Ex().has_no_error()`` in your SCT whenever you want to check for errors. By default, after the entire SCT finished executing, ``sqlwhat`` will check for errors before marking the exercise as correct. You can disable this behavior by using ``Ex().allow_error()``. Args: incorrect_msg: If specified, this overrides the automatically generated feedback message in case the student's query did not return a result.
codesearchnet
def entry_point(__func: Callable) -> Callable: if __func.__module__ == '__main__': import sys sys.exit(__func()) else: return __func
Execute function when module is run directly. Note: This allows fall through for importing modules that use it. Args: __func: Function to run
juraj-google-style
def cmd_startstop(options): statelu = {"start": "stopped", "stop": "running"} options.inst_state = statelu[options.command] debg.dprint("toggle set state: ", options.inst_state) (i_info, param_str) = gather_data(options) (tar_inst, tar_idx) = determine_inst(i_info, param_str, options.command) response = awsc.startstop(tar_inst, options.command) responselu = {"start": "StartingInstances", "stop": "StoppingInstances"} filt = responselu[options.command] resp = {} state_term = ('CurrentState', 'PreviousState') for i, j in enumerate(state_term): resp[i] = response["{0}".format(filt)][0]["{0}".format(j)]['Name'] print("Current State: {}{}{} - Previous State: {}{}{}\n". format(C_STAT[resp[0]], resp[0], C_NORM, C_STAT[resp[1]], resp[1], C_NORM))
Start or Stop the specified instance. Finds instances that match args and instance-state expected by the command. Then, the target instance is determined, the action is performed on the instance, and the eturn information is displayed. Args: options (object): contains args and data from parser.
juraj-google-style
def predict_proba(self, a, b, idx=0, **kwargs): return self.predict_dataset(DataFrame([[a, b]], columns=['A', 'B']))
Use Jarfo to predict the causal direction of a pair of vars. Args: a (numpy.ndarray): Variable 1 b (numpy.ndarray): Variable 2 idx (int): (optional) index number for printing purposes Returns: float: Causation score (Value : 1 if a->b and -1 if b->a)
codesearchnet
def _handle_message(self, message, handle_wrte=True): if (message.command == 'OKAY'): self._set_or_check_remote_id(message.arg0) if (not self._expecting_okay): raise usb_exceptions.AdbProtocolError('%s received unexpected OKAY: %s', self, message) self._expecting_okay = False elif (message.command == 'CLSE'): self.closed_state = self.ClosedState.CLOSED elif (not handle_wrte): raise usb_exceptions.AdbProtocolError('%s received WRTE before OKAY/CLSE: %s', self, message) else: with self._read_buffer_lock: self._read_buffer.append(message.data) self._buffer_size += len(message.data)
Handle a message that was read for this stream. For each message type, this means: OKAY: Check id's and make sure we are expecting an OKAY. Clear the self._expecting_okay flag so any pending write()'s know. CLSE: Set our internal state to closed. WRTE: Add the data read to our internal read buffer. Note we don't return the actual data because it may not be this thread that needs it. Args: message: Message that was read. handle_wrte: If True, we can handle WRTE messages, otherwise raise. Raises: AdbProtocolError: If we get a WRTE message but handle_wrte is False.
codesearchnet
def parse_date(value): if (not value): return None if isinstance(value, datetime.date): return value return parse_datetime(value).date()
Attempts to parse `value` into an instance of ``datetime.date``. If `value` is ``None``, this function will return ``None``. Args: value: A timestamp. This can be a string, datetime.date, or datetime.datetime value.
codesearchnet
def get_enabled_references(self, datas, meta_references): references = OrderedDict() for section in meta_references: references[section] = self.get_reference(datas, section) return references
Get enabled manifest references declarations. Enabled references are defined through meta references declaration, every other references are ignored. Arguments: datas (dict): Data where to search for reference declarations. This is commonly the fully parsed manifest. meta_references (list): List of enabled reference names. Returns: collections.OrderedDict: Serialized enabled references datas.
juraj-google-style
def setup_gpu(required_gpus): if required_gpus == 0: return available_gpus = tf.config.experimental.list_physical_devices('GPU') if not available_gpus: raise ValueError('requires at least one physical GPU') if len(available_gpus) >= required_gpus: tf.config.set_visible_devices(available_gpus[:required_gpus]) else: num_logical_gpus = required_gpus - len(available_gpus) + 1 logical_gpus = [tf.config.LogicalDeviceConfiguration(memory_limit=256) for _ in range(num_logical_gpus)] tf.config.set_logical_device_configuration(available_gpus[0], logical_gpus)
Sets up the GPU devices. If there're more available GPUs than needed, it hides the additional ones. If there're less, it creates logical devices. This is to make sure the tests see a fixed number of GPUs regardless of the environment. Args: required_gpus: an integer. The number of GPUs required. Raises: ValueError: if num_gpus is larger than zero but no GPU is available.
github-repos
def _create_route(self, env, item): if item.name in env: if isinstance(env[item.name], ApiRoutesByVersion): if item.version in env[item.name].at_version: existing_dt = env[item.name].at_version[item.version] raise InvalidSpec( 'Route %s at version %d already defined (%s:%d).' % ( quote(item.name), item.version, existing_dt._ast_node.path, existing_dt._ast_node.lineno), item.lineno, item.path) else: existing_dt = env[item.name] raise InvalidSpec( 'Symbol %s already defined (%s:%d).' % ( quote(item.name), existing_dt._ast_node.path, existing_dt._ast_node.lineno), item.lineno, item.path) else: env[item.name] = ApiRoutesByVersion() route = ApiRoute( name=item.name, version=item.version, ast_node=item, ) env[route.name].at_version[route.version] = route return route
Constructs a route and adds it to the environment. Args: env (dict): The environment of defined symbols. A new key is added corresponding to the name of this new route. item (AstRouteDef): Raw route definition from the parser. Returns: stone.api.ApiRoutesByVersion: A group of fully-defined routes indexed by versions.
juraj-google-style
def __init__(self, unique_identifier=None, attribute_names=None): super(GetAttributesRequestPayload, self).__init__( enums.Tags.REQUEST_PAYLOAD) self._unique_identifier = None self._attribute_names = list() self.unique_identifier = unique_identifier self.attribute_names = attribute_names
Construct a GetAttributes request payload. Args: unique_identifier (string): The ID of the managed object with which the retrieved attributes should be associated. Optional, defaults to None. attribute_names: A list of strings identifying the names of the attributes associated with the managed object. Optional, defaults to None.
juraj-google-style
def shadow_calc(data): up_shadow = abs(data.high - (max(data.open, data.close))) down_shadow = abs(data.low - (min(data.open, data.close))) entity = abs(data.open - data.close) towards = True if data.open < data.close else False print('=' * 15) print('up_shadow : {}'.format(up_shadow)) print('down_shadow : {}'.format(down_shadow)) print('entity: {}'.format(entity)) print('towards : {}'.format(towards)) return up_shadow, down_shadow, entity, data.date, data.code
计算上下影线 Arguments: data {DataStruct.slice} -- 输入的是一个行情切片 Returns: up_shadow {float} -- 上影线 down_shdow {float} -- 下影线 entity {float} -- 实体部分 date {str} -- 时间 code {str} -- 代码
juraj-google-style
def _runOneBenchmark(self, default_device, num_iters=10, static_unroll=False, steps=10): def loop_body(i, x): with ops.device('/gpu:0'): nx = nn_ops.conv2d(input=x, filter=kernel, strides=[1, 1, 1, 1], padding='SAME', data_format='NHWC', name='conv2d') ni = math_ops.add(i, 1) return (ni, nx) ops.reset_default_graph() with session.Session() as sess, ops.device(default_device): i, x, kernel = self._getInitVariables() self.evaluate(variables.global_variables_initializer()) if static_unroll: for _ in range(steps): i, x = loop_body(i, x) else: i, x = while_loop_tf.while_loop(lambda i, _: i < steps, loop_body, [i, x], parallel_iterations=steps, swap_memory=True) r = math_ops.reduce_sum(x) dx, dk = gradients_impl.gradients(r, [x, kernel]) r = control_flow_ops.group(dx, dk) for _ in range(3): self.evaluate(r) start_time = time.time() for _ in range(num_iters): self.evaluate(r) return (time.time() - start_time) / num_iters
Evaluate the while loop performance. Args: default_device: The default device to run all ops except the loop_body. loop_body is always run on GPU. num_iters: Number of iterations to run. static_unroll: If true, run unrolled version; otherwise, run while_loop. steps: Total number of repeated steps to run the loop. Returns: The duration of the run in seconds.
github-repos
def _get_rest_doc(self, request, start_response): api = request.body_json['api'] version = request.body_json['version'] generator = discovery_generator.DiscoveryGenerator(request=request) services = [s for s in self._backend.api_services if s.api_info.name == api and s.api_info.api_version == version] doc = generator.pretty_print_config_to_json(services) if not doc: error_msg = ('Failed to convert .api to discovery doc for ' 'version %s of api %s') % (version, api) _logger.error('%s', error_msg) return util.send_wsgi_error_response(error_msg, start_response) return self._send_success_response(doc, start_response)
Sends back HTTP response with API directory. This calls start_response and returns the response body. It will return the discovery doc for the requested api/version. Args: request: An ApiRequest, the transformed request sent to the Discovery API. start_response: A function with semantics defined in PEP-333. Returns: A string, the response body.
juraj-google-style
def attention_mask_autoregressive(query_pos, dtype=tf.float32): memory_pos = rename_length_to_memory_length(query_pos) return (mtf.cast(mtf.less(query_pos, memory_pos), dtype) * (- 1000000000.0))
Bias for self-attention where attention to the right is disallowed. Args: query_pos: a mtf.Tensor with shape [..., length_dim] dtype: a tf.dtype Returns: a mtf.Tensor with shape [..., length_dim, memory_length_dim]
codesearchnet
def unwrap_or_else(self, callback: Callable[([], U)]) -> Union[(T, U)]: return (self._val if self._is_some else callback())
Returns the contained value or computes it from ``callback``. Args: callback: The the default callback. Returns: The contained value if the :py:class:`Option` is ``Some``, otherwise ``callback()``. Examples: >>> Some(0).unwrap_or_else(lambda: 111) 0 >>> NONE.unwrap_or_else(lambda: 'ha') 'ha'
codesearchnet
def to_barrier_key(cls, barrier_index_key): barrier_index_path = barrier_index_key.to_path() (pipeline_kind, dependent_pipeline_id, unused_kind, purpose) = barrier_index_path[-4:] barrier_record_path = ( pipeline_kind, dependent_pipeline_id, _BarrierRecord.kind(), purpose) return db.Key.from_path(*barrier_record_path)
Converts a _BarrierIndex key to a _BarrierRecord key. Args: barrier_index_key: db.Key for a _BarrierIndex entity. Returns: db.Key for the corresponding _BarrierRecord entity.
juraj-google-style
def clear_tc(self, owner, data, clear_type): batch = self.tcex.batch(owner, action='Delete') tc_type = data.get('type') path = data.get('path') if (tc_type in self.tcex.group_types): name = self.tcex.playbook.read(data.get('name')) name = self.path_data(name, path) if (name is not None): print('Deleting ThreatConnect Group: {}{}{}'.format(c.Style.BRIGHT, c.Fore.MAGENTA, name)) self.log.info('[{}] Deleting ThreatConnect {} with name: {}.'.format(clear_type, tc_type, name)) batch.group(tc_type, name) elif (tc_type in self.tcex.indicator_types): if (data.get('summary') is not None): summary = self.tcex.playbook.read(data.get('summary')) else: resource = self.tcex.resource(tc_type) summary = resource.summary(data) summary = self.path_data(summary, path) if (summary is not None): print('Deleting ThreatConnect Indicator: {}{}{}'.format(c.Style.BRIGHT, c.Fore.MAGENTA, summary)) self.log.info('[{}] Deleting ThreatConnect {} with value: {}.'.format(clear_type, tc_type, summary)) batch.indicator(tc_type, summary) batch_results = batch.submit() self.log.debug('[{}] Batch Results: {}'.format(clear_type, batch_results)) for error in (batch_results.get('errors') or []): self.log.error('[{}] Batch Error: {}'.format(clear_type, error))
Delete threat intel from ThreatConnect platform. Args: owner (str): The ThreatConnect owner. data (dict): The data for the threat intel to clear. clear_type (str): The type of clear action.
codesearchnet
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): local_stream = BytearrayStream() if self._unique_identifier: self._unique_identifier.write( local_stream, kmip_version=kmip_version ) else: raise ValueError( "Invalid struct missing the unique identifier attribute." ) if self._cryptographic_parameters: self._cryptographic_parameters.write( local_stream, kmip_version=kmip_version ) self.length = local_stream.length() super(MACSignatureKeyInformation, self).write( output_stream, kmip_version=kmip_version ) output_stream.write(local_stream.buffer)
Write the data encoding the MACSignatureKeyInformation struct to a stream. Args: output_stream (stream): A data stream in which to encode object data, supporting a write method; usually a BytearrayStream object. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be encoded. Optional, defaults to KMIP 1.0.
juraj-google-style
def _get_element_by_names(source, names): if source is None: return source else: if names: head, *rest = names if isinstance(source, dict) and head in source: return _get_element_by_names(source[head], rest) elif isinstance(source, list) and head.isdigit(): return _get_element_by_names(source[int(head)], rest) elif not names[0]: pass else: source = None return source
Given a dict and path '/' or '.' separated. Digs into de dict to retrieve the specified element. Args: source (dict): set of nested objects in which the data will be searched path (list): list of attribute names
juraj-google-style
def from_unknown_text(text, strict=False): if text.startswith('+'): crs = from_proj4(text, strict) elif text.startswith(('PROJCS[', 'GEOGCS[')): crs = from_unknown_wkt(text, strict) elif text.startswith('EPSG:'): crs = from_epsg_code(text.split(':')[1]) elif text.startswith('ESRI:'): crs = from_esri_code(text.split(':')[1]) elif text.startswith('SR-ORG:'): crs = from_sr_code(text.split(':')[1]) else: raise FormatError('Could not auto-detect the type of crs format, make sure it is one of the supported formats') return crs
Detect crs string format and parse into crs object with appropriate function. Arguments: - *text*: The crs text representation of unknown type. - *strict* (optional): When True, the parser is strict about names having to match exactly with upper and lowercases. Default is not strict (False). Returns: - CRS object.
codesearchnet
def from_structures(cls, structures, constant_lattice=True, **kwargs): frac_coords = [structure.frac_coords for structure in structures] if constant_lattice: lattice = structures[0].lattice.matrix else: lattice = [structure.lattice.matrix for structure in structures] site_properties = [structure.site_properties for structure in structures] return cls(lattice, structures[0].species, frac_coords, site_properties=site_properties, constant_lattice=constant_lattice, **kwargs)
Convenience constructor to obtain trajectory from a list of structures. Note: Assumes no atoms removed during simulation Args: structures (list): list of pymatgen Structure objects. constant_lattice (bool): Whether the lattice changes during the simulation, such as in an NPT MD simulation. True results in Returns: (Trajectory)
juraj-google-style
def get(cls, ns, key): return getattr(db, cls.__name__).find_one((ConfigItem.namespace_prefix == ns), (ConfigItem.key == key))
Fetch an item by namespace and key Args: ns (str): Namespace prefix key (str): Item key Returns: :obj:`Configitem`: Returns config item object if found, else `None`
codesearchnet
def search(self, trace_func: Callable[([List[LineSequence], float, float, float, bool], None)]=None) -> List[LineSequence]: def search_trace(state: _STATE, temp: float, cost: float, probability: float, accepted: bool): if trace_func: (trace_seqs, _) = state trace_func(trace_seqs, temp, cost, probability, accepted) (seqs, _) = optimization.anneal_minimize(self._create_initial_solution(), self._quadratic_sum_cost, self._force_edges_active_move, self._rand.random_sample, trace_func=search_trace) return seqs
Issues new linear sequence search. Each call to this method starts new search. Args: trace_func: Optional callable which will be called for each simulated annealing step with arguments: solution candidate (list of linear sequences on the chip), current temperature (float), candidate cost (float), probability of accepting candidate (float), and acceptance decision (boolean). Returns: List of linear sequences on the chip found by this method.
codesearchnet
def CheckCompletedBlocks(self, filename, error): for obj in self.stack: if isinstance(obj, _ClassInfo): error(filename, obj.starting_linenum, 'build/class', 5, ('Failed to find complete declaration of class %s' % obj.name)) elif isinstance(obj, _NamespaceInfo): error(filename, obj.starting_linenum, 'build/namespaces', 5, ('Failed to find complete declaration of namespace %s' % obj.name))
Checks that all classes and namespaces have been completely parsed. Call this when all lines in a file have been processed. Args: filename: The name of the current file. error: The function to call with any errors found.
codesearchnet
def add_subassistants_to(cls, parser, assistant_tuple, level, alias=None): name = alias or assistant_tuple[0].name p = parser.add_parser(name, description=assistant_tuple[0].description, argument_default=argparse.SUPPRESS) for arg in assistant_tuple[0].args: arg.add_argument_to(p) if len(assistant_tuple[1]) > 0: subparsers = cls._add_subparsers_required(p, dest=settings.SUBASSISTANT_N_STRING.format(level), title=cls.subparsers_str, description=cls.subparsers_desc) for subas_tuple in sorted(assistant_tuple[1], key=lambda x: x[0].name): cls.add_subassistants_to(subparsers, subas_tuple, level + 1) elif level == 1: subparsers = cls._add_subparsers_required(p, dest=settings.SUBASSISTANT_N_STRING.format(level), title=cls.subparsers_str, description=devassistant_argparse.ArgumentParser.no_assistants_msg)
Adds assistant from given part of assistant tree and all its subassistants to a given argument parser. Args: parser: instance of devassistant_argparse.ArgumentParser assistant_tuple: part of assistant tree (see generate_argument_parser doc) level: level of subassistants that given assistant is at
juraj-google-style
def nac_v(msg): tc = typecode(msg) if (tc != 19): raise RuntimeError(('%s: Not an airborne velocity message, expecting TC = 19' % msg)) msgbin = common.hex2bin(msg) NACv = common.bin2int(msgbin[42:45]) try: HFOMr = uncertainty.NACv[NACv]['HFOMr'] VFOMr = uncertainty.NACv[NACv]['VFOMr'] except KeyError: (HFOMr, VFOMr) = (uncertainty.NA, uncertainty.NA) return (HFOMr, VFOMr)
Calculate NACv, Navigation Accuracy Category - Velocity Args: msg (string): 28 bytes hexadecimal message string, TC = 19 Returns: int or string: 95% horizontal accuracy bounds for velocity, Horizontal Figure of Merit int or string: 95% vertical accuracy bounds for velocity, Vertical Figure of Merit
codesearchnet
def metta_config(quarter, num_dimensions): (first_day, last_day) = quarter_boundaries(quarter) return {'start_time': first_day, 'end_time': last_day, 'prediction_window': 3, 'label_name': 'onet_soc_code', 'label_type': 'categorical', 'matrix_id': 'job_postings_{}'.format(quarter), 'feature_names': ['doc2vec_{}'.format(i) for i in range(num_dimensions)]}
Returns metta metadata for a quarter's SOC code classifier matrix Args: quarter (str) quarter, in format '2015Q1' num_dimensions (int) Number of features in matrix Returns: (dict) metadata suitable for metta.archive_train_test
codesearchnet
def find_library_windows(cls): dll = (cls.get_appropriate_windows_sdk_name() + '.dll') root = 'C:\\' for d in os.listdir(root): dir_path = os.path.join(root, d) if (d.startswith('Program Files') and os.path.isdir(dir_path)): dir_path = os.path.join(dir_path, 'SEGGER') if (not os.path.isdir(dir_path)): continue ds = filter((lambda x: x.startswith('JLink')), os.listdir(dir_path)) for jlink_dir in ds: lib_path = os.path.join(dir_path, jlink_dir, dll) if os.path.isfile(lib_path): (yield lib_path)
Loads the SEGGER DLL from the windows installation directory. On Windows, these are found either under: - ``C:\\Program Files\\SEGGER\\JLink`` - ``C:\\Program Files (x86)\\SEGGER\\JLink``. Args: cls (Library): the ``Library`` class Returns: The paths to the J-Link library files in the order that they are found.
codesearchnet
def values(self, column_major=False): if column_major: return list(map(list, zip(*self._values))) return [row[:] for row in self._values]
Return a nested list with the worksheet values. Args: column_major (bool): as list of columns (default list of rows) Returns: list: list of lists with values
codesearchnet
def _notify_mutated(self, obj, old, hint=None): value = self.__get__(obj, obj.__class__) value = self.property.prepare_value(obj, self.name, value) self._real_set(obj, old, value, hint=hint)
A method to call when a container is mutated "behind our back" and we detect it with our |PropertyContainer| wrappers. Args: obj (HasProps) : The object who's container value was mutated old (object) : The "old" value of the container In this case, somewhat weirdly, ``old`` is a copy and the new value should already be set unless we change it due to validation. hint (event hint or None, optional) An optional update event hint, e.g. ``ColumnStreamedEvent`` (default: None) Update event hints are usually used at times when better update performance can be obtained by special-casing in some way (e.g. streaming or patching column data sources) Returns: None
codesearchnet
def _sym_missing(self) -> Dict[str, Any]: missing = dict() for k, v in self._sym_attributes.items(): if pg_typing.MISSING_VALUE != v and isinstance(v, base.Symbolic): missing_child = v.sym_missing(flatten=False) if missing_child: missing[k] = missing_child return missing
Returns missing values for Functor. Semantically unbound arguments are not missing, thus we only return partial bound arguments in `sym_missing`. As a result, a functor is partial only when any of its bound arguments is partial. Returns: A dict of missing key (or path) to missing value.
github-repos
def code_string_to_enum_value_descriptor(code_string: str, enum_descriptor: descriptor.EnumDescriptor) -> descriptor.EnumValueDescriptor: value_descriptor = _get_enum_value_descriptor_memo(enum_descriptor, code_string) if value_descriptor is not None: return value_descriptor fhir_case_code_string = code_string.upper().replace('-', '_') value_descriptor = enum_descriptor.values_by_name.get(fhir_case_code_string) if value_descriptor is not None: _set_enum_value_descriptor_memo(enum_descriptor, code_string, value_descriptor) return value_descriptor for value_descriptor in enum_descriptor.values: if value_descriptor.GetOptions().HasExtension(annotations_pb2.fhir_original_code) and value_descriptor.GetOptions().Extensions[annotations_pb2.fhir_original_code] == code_string: _set_enum_value_descriptor_memo(enum_descriptor, code_string, value_descriptor) return value_descriptor raise fhir_errors.InvalidFhirError(f'Failed to convert {code_string!r} to {enum_descriptor.full_name}. No matching enum found.')
Returns an EnumValueDescriptor for a provided EnumDescriptor and raw code. Args: code_string: A raw string representation of the code to retrieve. enum_descriptor: The EnumDescriptor the desired EnumValueDescriptor belongs to. Returns: An instance of EnumValueDescriptor that the code_string represents. Raises: fhir_errors.InvalidFhirError: In the event that a conversion from code_string was unsuccessful.
github-repos
def _prep_noise_interpolants(self): noise_lists = {} self.noise_interpolants = {} if isinstance(self.sensitivity_curves, str): self.sensitivity_curves = [self.sensitivity_curves] if isinstance(self.noise_type_in, list): if (len(self.noise_type_in) != len(self.sensitivity_curves)): raise ValueError((('noise_type_in must have same shape as sensitivity_curves if it is' + 'provided as a list.') + 'If all curves are of the same type, provide a string.')) else: assert isinstance(self.noise_type_in, str) self.noise_type_in = [self.noise_type_in for _ in self.sensitivity_curves] if isinstance(self.signal_type, str): self.signal_type = [self.signal_type] for (num, sc) in enumerate(self.sensitivity_curves): if isinstance(sc, str): (f, h_n) = read_noise_curve(sc, noise_type_in=self.noise_type_in[num], noise_type_out='char_strain') if (sc[(- 4):] == '.txt'): key = sc.split('.')[0].split('/')[(- 1)] else: key = sc elif isinstance(sc, list): (f, h_n) = sc key = str(num) else: raise ValueError(('Sensitivity curves must either be string' + 'or list containing f_n and asd_n.')) noise_lists[key] = [f, h_n] if (str(self.add_wd_noise).lower() in ['true', 'both', 'yes']): if isinstance(self.wd_noise, str): (f_n_wd, h_n_wd) = read_noise_curve(self.wd_noise, noise_type_in=self.wd_noise_type_in, noise_type_out='char_strain') elif isinstance(self, wd_noise, list): (f_n_wd, h_n_wd) = self.wd_noise trans_dict = {} for sc in noise_lists.keys(): (f_n, h_n) = noise_lists[sc] if (self.add_wd_noise.lower() == 'both'): trans_dict[sc] = [f_n, h_n] (f_n, h_n) = combine_with_wd_noise(f_n, h_n, f_n_wd, h_n_wd) trans_dict[(sc + '_wd')] = [f_n, h_n] noise_lists = trans_dict for sc in noise_lists: (f_n, h_n) = noise_lists[sc] self.noise_interpolants[sc] = interpolate.interp1d(f_n, h_n, bounds_error=False, fill_value=1e+30) return
Construct interpolated sensitivity curves This will construct the interpolated sensitivity curves using scipy.interpolate.interp1d. It will add wd noise if that is requested. Raises: ValueError: ``len(noise_type_in) != len(sensitivity_curves)`` ValueError: Issue with sensitivity curve type provided.
codesearchnet
def print_source(self, args, screen_info=None): del screen_info parsed = self._arg_parsers['print_source'].parse_args(args) device_name_regex = re.compile(parsed.device_name_filter) if parsed.device_name_filter else None profile_data = [] data_generator = self._get_profile_data_generator() device_count = len(self._run_metadata.step_stats.dev_stats) for index in range(device_count): device_stats = self._run_metadata.step_stats.dev_stats[index] if device_name_regex and (not device_name_regex.match(device_stats.device)): continue profile_data.extend(data_generator(device_stats)) source_annotation = source_utils.annotate_source_against_profile(profile_data, os.path.expanduser(parsed.source_file_path), node_name_filter=parsed.node_name_filter, op_type_filter=parsed.op_type_filter) if not source_annotation: return debugger_cli_common.RichTextLines(['The source file %s does not contain any profile information for the previous Session run under the following filters:' % parsed.source_file_path, ' --%s: %s' % (_DEVICE_NAME_FILTER_FLAG, parsed.device_name_filter), ' --%s: %s' % (_NODE_NAME_FILTER_FLAG, parsed.node_name_filter), ' --%s: %s' % (_OP_TYPE_FILTER_FLAG, parsed.op_type_filter)]) max_total_cost = 0 for line_index in source_annotation: total_cost = self._get_total_cost(source_annotation[line_index], parsed.cost_type) max_total_cost = max(max_total_cost, total_cost) source_lines, line_num_width = source_utils.load_source(parsed.source_file_path) cost_bar_max_length = 10 total_cost_head = parsed.cost_type column_widths = {'cost_bar': cost_bar_max_length + 3, 'total_cost': len(total_cost_head) + 3, 'num_nodes_execs': len(self._NUM_EXECS_SUB_HEAD) + 1, 'line_number': line_num_width} head = RL(' ' * column_widths['cost_bar'] + total_cost_head + ' ' * (column_widths['total_cost'] - len(total_cost_head)) + self._NUM_NODES_HEAD + ' ' * (column_widths['num_nodes_execs'] - len(self._NUM_NODES_HEAD)), font_attr=self._LINE_COST_ATTR) head += RL(self._LINENO_HEAD, font_attr=self._LINE_NUM_ATTR) sub_head = RL(' ' * (column_widths['cost_bar'] + column_widths['total_cost']) + self._NUM_EXECS_SUB_HEAD + ' ' * (column_widths['num_nodes_execs'] - len(self._NUM_EXECS_SUB_HEAD)) + ' ' * column_widths['line_number'], font_attr=self._LINE_COST_ATTR) sub_head += RL(self._SOURCE_HEAD, font_attr='bold') lines = [head, sub_head] output_annotations = {} for i, line in enumerate(source_lines): lineno = i + 1 if lineno in source_annotation: annotation = source_annotation[lineno] cost_bar = self._render_normalized_cost_bar(self._get_total_cost(annotation, parsed.cost_type), max_total_cost, cost_bar_max_length) annotated_line = cost_bar annotated_line += ' ' * (column_widths['cost_bar'] - len(cost_bar)) total_cost = RL(cli_shared.time_to_readable_str(self._get_total_cost(annotation, parsed.cost_type), force_time_unit=parsed.time_unit), font_attr=self._LINE_COST_ATTR) total_cost += ' ' * (column_widths['total_cost'] - len(total_cost)) annotated_line += total_cost file_path_filter = re.escape(parsed.source_file_path) + '$' command = 'lp --file_path_filter %s --min_lineno %d --max_lineno %d' % (file_path_filter, lineno, lineno + 1) if parsed.device_name_filter: command += ' --%s %s' % (_DEVICE_NAME_FILTER_FLAG, parsed.device_name_filter) if parsed.node_name_filter: command += ' --%s %s' % (_NODE_NAME_FILTER_FLAG, parsed.node_name_filter) if parsed.op_type_filter: command += ' --%s %s' % (_OP_TYPE_FILTER_FLAG, parsed.op_type_filter) menu_item = debugger_cli_common.MenuItem(None, command) num_nodes_execs = RL('%d(%d)' % (annotation.node_count, annotation.node_exec_count), font_attr=[self._LINE_COST_ATTR, menu_item]) num_nodes_execs += ' ' * (column_widths['num_nodes_execs'] - len(num_nodes_execs)) annotated_line += num_nodes_execs else: annotated_line = RL(' ' * sum((column_widths[col_name] for col_name in column_widths if col_name != 'line_number'))) line_num_column = RL(' L%d' % lineno, self._LINE_NUM_ATTR) line_num_column += ' ' * (column_widths['line_number'] - len(line_num_column)) annotated_line += line_num_column annotated_line += line lines.append(annotated_line) if parsed.init_line == lineno: output_annotations[debugger_cli_common.INIT_SCROLL_POS_KEY] = len(lines) - 1 return debugger_cli_common.rich_text_lines_from_rich_line_list(lines, annotations=output_annotations)
Print a Python source file with line-level profile information. Args: args: Command-line arguments, excluding the command prefix, as a list of str. screen_info: Optional dict input containing screen information such as cols. Returns: Output text lines as a RichTextLines object.
github-repos
def is_active(self, node): if (isinstance(node.value, gast.Call) and anno.getanno(node.value, 'func', False) == utils.pop): return True for succ in gast.walk(node.value): if (isinstance(succ, gast.Name) and isinstance(succ.ctx, gast.Load) and succ.id in self.active_variables): return True return False
Checks whether a statement is active. An assignment is active when its right hand side contains active variables. Args: node: an instance of gast.Assign Returns: Whether the statement is active.
juraj-google-style
def __init__(self, channel): self.ListContexts = channel.unary_unary( '/google.cloud.dialogflow.v2beta1.Contexts/ListContexts', request_serializer=google_dot_cloud_dot_dialogflow__v2beta1_dot_proto_dot_context__pb2.ListContextsRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_dialogflow__v2beta1_dot_proto_dot_context__pb2.ListContextsResponse.FromString, ) self.GetContext = channel.unary_unary( '/google.cloud.dialogflow.v2beta1.Contexts/GetContext', request_serializer=google_dot_cloud_dot_dialogflow__v2beta1_dot_proto_dot_context__pb2.GetContextRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_dialogflow__v2beta1_dot_proto_dot_context__pb2.Context.FromString, ) self.CreateContext = channel.unary_unary( '/google.cloud.dialogflow.v2beta1.Contexts/CreateContext', request_serializer=google_dot_cloud_dot_dialogflow__v2beta1_dot_proto_dot_context__pb2.CreateContextRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_dialogflow__v2beta1_dot_proto_dot_context__pb2.Context.FromString, ) self.UpdateContext = channel.unary_unary( '/google.cloud.dialogflow.v2beta1.Contexts/UpdateContext', request_serializer=google_dot_cloud_dot_dialogflow__v2beta1_dot_proto_dot_context__pb2.UpdateContextRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_dialogflow__v2beta1_dot_proto_dot_context__pb2.Context.FromString, ) self.DeleteContext = channel.unary_unary( '/google.cloud.dialogflow.v2beta1.Contexts/DeleteContext', request_serializer=google_dot_cloud_dot_dialogflow__v2beta1_dot_proto_dot_context__pb2.DeleteContextRequest.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, ) self.DeleteAllContexts = channel.unary_unary( '/google.cloud.dialogflow.v2beta1.Contexts/DeleteAllContexts', request_serializer=google_dot_cloud_dot_dialogflow__v2beta1_dot_proto_dot_context__pb2.DeleteAllContextsRequest.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, )
Constructor. Args: channel: A grpc.Channel.
juraj-google-style
def ReadSerializableArray(self, class_name, max=sys.maxsize): module = '.'.join(class_name.split('.')[:-1]) klassname = class_name.split('.')[-1] klass = getattr(importlib.import_module(module), klassname) length = self.ReadVarInt(max=max) items = [] try: for i in range(0, length): item = klass() item.Deserialize(self) items.append(item) except Exception as e: logger.error("Couldn't deserialize %s " % e) return items
Deserialize a stream into the object specific by `class_name`. Args: class_name (str): a full path to the class to be deserialized into. e.g. 'neo.Core.Block.Block' max (int): (Optional) maximum number of bytes to read. Returns: list: list of `class_name` objects deserialized from the stream.
juraj-google-style
def DetermineType(value): object_type = type(value) if not hasattr(object_type, '__name__'): return None type_string = getattr(object_type, '__module__', '') if type_string: type_string += '.' type_string += object_type.__name__ return type_string
Determines the type of val, returning a "full path" string. For example: DetermineType(5) -> __builtin__.int DetermineType(Foo()) -> com.google.bar.Foo Args: value: Any value, the value is irrelevant as only the type metadata is checked Returns: Type path string. None if type cannot be determined.
juraj-google-style
def SetServerInformation(self, server, port): self._host = server self._port = port logger.debug('Elasticsearch server: {0!s} port: {1:d}'.format( server, port))
Set the server information. Args: server (str): IP address or hostname of the server. port (int): Port number of the server.
juraj-google-style
def google_maps_geoloc_link(data): if isinstance(data, str): lat_lon = ip_geoloc(data) if lat_lon is None: return '' lat, lon = lat_lon else: lat, lon = data loc = '%s,%s' % (lat, lon) return 'https: 'data=!3m1!4b1!4m5!3m4!1s0x0:0x0!8m2!3d%s!4d%s' % ( loc, lat, lon)
Get a link to google maps pointing on this IP's geolocation. Args: data (str/tuple): IP address or (latitude, longitude). Returns: str: a link to google maps pointing on this IP's geolocation.
juraj-google-style
def limit(self, count): query = query_mod.Query(self) return query.limit(count)
Create a limited query with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.limit` for more information on this method. Args: count (int): Maximum number of documents to return that match the query. Returns: ~.firestore_v1beta1.query.Query: A limited query.
codesearchnet
def upload(self, resource_id, data): self.body = data self.content_type = 'application/octet-stream' self.resource_id(str(resource_id)) self._request_uri = '{}/upload'.format(self._request_uri)
Update the request URI to upload the a document to this resource. Args: resource_id (integer): The group id. data (any): The raw data to upload.
codesearchnet
def get_dataset(self, dsid, dsinfo): data = self[dsinfo.get('file_key', dsid.name)] data.attrs.update(dsinfo) data.attrs['platform_name'] = self['/attr/satellite_name'] data.attrs['sensor'] = self['/attr/instrument_name'] return data
Get dataset function Args: dsid: Dataset ID param2: Dataset Information Returns: Dask DataArray: Data
codesearchnet
def from_base_10_int(decimal, output_base=10): if decimal <= 0: return (0,) if output_base == 1: return (1,) * decimal length = digits(decimal, output_base) converted = tuple(digit(decimal, i, output_base) for i in range(length)) return converted[::-1]
Converts a decimal integer to a specific base. Args: decimal(int) A base 10 number. output_base(int) base to convert to. Returns: A tuple of digits in the specified base. Examples: >>> from_base_10_int(255) (2, 5, 5) >>> from_base_10_int(255, 16) (15, 15) >>> from_base_10_int(9988664439, 8) (1, 1, 2, 3, 2, 7, 5, 6, 6, 1, 6, 7) >>> from_base_10_int(0, 17) (0,)
juraj-google-style
def get_ogr_driver(filepath): (filename, file_extension) = os.path.splitext(filepath) EXTENSION = file_extension[1:] ogr_driver_count = ogr.GetDriverCount() for idx in range(ogr_driver_count): driver = ogr.GetDriver(idx) driver_extension = (driver.GetMetadataItem(str('DMD_EXTENSION')) or '') driver_extensions = (driver.GetMetadataItem(str('DMD_EXTENSIONS')) or '') if ((EXTENSION == driver_extension) or (EXTENSION in driver_extensions)): return driver else: msg = 'No driver found for the following file extension: {}'.format(EXTENSION) raise ValueError(msg)
Get the OGR driver from the provided file extension. Args: file_extension (str): file extension Returns: osgeo.ogr.Driver Raises: ValueError: no driver is found
codesearchnet
def generate_exact(self, model, vcpu_num, host_cpu): nested = {'Intel': 'vmx', 'AMD': 'svm'} cpu = ET.Element('cpu', match='exact') ET.SubElement(cpu, 'model').text = model cpu.append(self.generate_topology(vcpu_num)) vendor = host_cpu.findtext('vendor') if (not nested.get(vendor)): LOGGER.debug('Unknown vendor: {0}, did not configure nested virtualization cpu flag on guest.'.format(vendor)) return cpu model_vendor = LibvirtCPU.get_cpu_vendor(family=model) if (vendor != model_vendor): LOGGER.debug('Not enabling nested virtualization feature, host vendor is: {0}, guest vendor: {1}'.format(vendor, model_vendor)) return cpu flag = nested[vendor] if (host_cpu.find('feature/[@name="{0}"]'.format(flag)) is not None): cpu.append(self.generate_feature(name=flag)) else: LOGGER.debug('missing {0} cpu flag on host, nested virtualization will probably not work.'.format(flag)) return cpu
Generate exact CPU model with nested virtualization CPU feature. Args: model(str): libvirt supported CPU model vcpu_num(int): number of virtual cpus host_cpu(lxml.etree.Element): the host CPU model Returns: lxml.etree.Element: CPU XML node
codesearchnet
def guess_task_type(name, task_defn): parts = name.split(':') task_type = parts[(- 1)] if (task_type == 'parent'): if is_action(task_defn): task_type = 'action' else: task_type = 'decision' if (task_type not in get_valid_task_types()): raise CoTError('Invalid task type for {}!'.format(name)) return task_type
Guess the task type of the task. Args: name (str): the name of the task. Returns: str: the task_type. Raises: CoTError: on invalid task_type.
codesearchnet
def internal_convert_n_to_tensor_or_indexed_slices(values, dtype=None, name=None, as_ref=False): if not isinstance(values, collections_abc.Iterable): raise TypeError('Argument `values` must be iterable.') ret = [] for i, value in enumerate(values): if value is None: ret.append(value) else: n = None if name is None else '%s_%d' % (name, i) ret.append(internal_convert_to_tensor_or_indexed_slices(value, dtype=dtype, name=n, as_ref=as_ref)) return ret
Converts `values` to a list of `Tensor` or `IndexedSlices` objects. Any `IndexedSlices` or `SparseTensor` objects in `values` are returned unmodified. Args: values: An iterable of `None`, `IndexedSlices`, `SparseTensor`, or objects that can be consumed by `convert_to_tensor()`. dtype: (Optional.) The required `DType` of the returned `Tensor` or `IndexedSlices`. name: (Optional.) A name prefix to used when a new `Tensor` is created, in which case element `i` will be given the name `name + '_' + i`. as_ref: True if the caller wants the results as ref tensors. Returns: A list of `Tensor`, `IndexedSlices`, `SparseTensor` and/or `None` objects. Raises: TypeError: If no conversion function is registered for an element in `values`. RuntimeError: If a registered conversion function returns an invalid value.
github-repos
def _decorate_block(self, start, end): color = self._get_scope_highlight_color() draw_order = DRAW_ORDERS.get('codefolding') d = TextDecoration(self.editor.document(), start_line=start, end_line=end+1, draw_order=draw_order) d.set_background(color) d.set_full_width(True, clear=False) self.editor.decorations.add(d) self._scope_decos.append(d)
Create a decoration and add it to the editor. Args: start (int) start line of the decoration end (int) end line of the decoration
juraj-google-style
def prepare_for_send(self, full_url=False): assert self.url assert self.method assert self.version url_info = self.url_info if ('Host' not in self.fields): self.fields['Host'] = url_info.hostname_with_port if (not full_url): if url_info.query: self.resource_path = '{0}?{1}'.format(url_info.path, url_info.query) else: self.resource_path = url_info.path else: self.resource_path = url_info.url
Modify the request to be suitable for HTTP server. Args: full_url (bool): Use full URL as the URI. By default, only the path of the URL is given to the server.
codesearchnet
def add_arguments(cls, parser): parser.add_argument( '-t', '--title', action='store', nargs='?', const='', dest='title', help="[issue] task/issue title.", ) parser.add_argument( '-b', '--body', action='store', nargs='?', const='', dest='body', help="[issue] task/issue body.", ) pass
Add arguments to the parser for collection in app.args. Args: parser: `argparse.ArgumentParser`. Parser. Arguments added here are server on self.args.
juraj-google-style
def populate_ast_nsarg_orthologs(ast, species): ortholog_namespace = 'EG' if isinstance(ast, NSArg): if re.match(ortholog_namespace, ast.canonical): orthologs = bel.terms.orthologs.get_orthologs(ast.canonical, list(species.keys())) for species_id in species: if (species_id in orthologs): orthologs[species_id]['species_label'] = species[species_id] ast.orthologs = copy.deepcopy(orthologs) if hasattr(ast, 'args'): for arg in ast.args: populate_ast_nsarg_orthologs(arg, species) return ast
Recursively collect NSArg orthologs for BEL AST This requires bo.collect_nsarg_norms() to be run first so NSArg.canonical is available Args: ast: AST at recursive point in belobj species: dictionary of species ids vs labels for or
codesearchnet
def draw_sunpath(self, hoys=None, origin=None, scale=1, sun_scale=1, annual=True, rem_night=True): assert ladybug.isplus, '"draw_sunpath" method can only be used in the [+] libraries.' hoys = (hoys or ()) origin = (origin or (0, 0, 0)) try: origin = tuple(origin) except TypeError as e: try: origin = (origin.X, origin.Y, origin.Z) except AttributeError: raise TypeError(str(e)) scale = (scale or 1) sun_scale = (sun_scale or 1) assert (annual or hoys), 'For daily sunpath you need to provide at least one hour.' radius = (200 * scale) base_curves = plus.base_curves(origin, radius, self.north_angle) if annual: asuns = self._analemma_suns() analemma_curves = plus.analemma_curves(asuns, origin, radius) else: analemma_curves = () if hoys: suns = tuple((self.calculate_sun_from_hoy(hour) for hour in hoys)) else: suns = () if rem_night: suns = tuple((sun for sun in suns if sun.is_during_day)) sun_geos = plus.sun_geometry(suns, origin, radius) if annual: dts = (DateTime(m, 21) for m in xrange(1, 13)) else: dts = (sun.datetime for sun in suns) dsuns = self._daily_suns(dts) daily_curves = plus.daily_curves(dsuns, origin, radius) SPGeo = namedtuple('SunpathGeo', ('compass_curves', 'analemma_curves', 'daily_curves', 'suns', 'sun_geos')) return SPGeo(base_curves, analemma_curves, daily_curves, suns, sun_geos)
Create sunpath geometry. \ This method should only be used from the + libraries. Args: hoys: An optional list of hours of the year(default: None). origin: Sunpath origin(default: (0, 0, 0)). scale: Sunpath scale(default: 1). sun_scale: Scale for the sun spheres(default: 1). annual: Set to True to draw an annual sunpath. Otherwise a daily sunpath is drawn. rem_night: Remove suns which are under the horizon(night!). Returns: base_curves: A collection of curves for base plot. analemma_curves: A collection of analemma_curves. daily_curves: A collection of daily_curves. suns: A list of suns.
codesearchnet
def offTagAdd(self, name, func): if '*' in name: self.ontagaddglobs.rem(name, func) return cblist = self.ontagadds.get(name) if cblist is None: return try: cblist.remove(func) except ValueError: pass
Unregister a callback for tag addition. Args: name (str): The name of the tag or tag glob. func (function): The callback func(node, tagname, tagval).
juraj-google-style
def orthorhombic(a: float, b: float, c: float): return Lattice.from_parameters(a, b, c, 90, 90, 90)
Convenience constructor for an orthorhombic lattice. Args: a (float): *a* lattice parameter of the orthorhombic cell. b (float): *b* lattice parameter of the orthorhombic cell. c (float): *c* lattice parameter of the orthorhombic cell. Returns: Orthorhombic lattice of dimensions a x b x c.
juraj-google-style
def apply_filter(self, structure_filter): def test_transformed_structure(ts): return structure_filter.test(ts.final_structure) self.transformed_structures = list(filter(test_transformed_structure, self.transformed_structures)) for ts in self.transformed_structures: ts.append_filter(structure_filter)
Applies a structure_filter to the list of TransformedStructures in the transmuter. Args: structure_filter: StructureFilter to apply.
codesearchnet
def UnwrapPyTree(tree): unwrapper = PyTreeUnwrapper() unwrapper.Visit(tree) llines = unwrapper.GetLogicalLines() llines.sort(key=lambda x: x.lineno) return llines
Create and return a list of logical lines from the given pytree. Arguments: tree: the top-level pytree node to unwrap.. Returns: A list of LogicalLine objects.
github-repos
def as_operation(self, timer=datetime.utcnow): now = timer() op = sc_messages.Operation(endTime=timestamp.to_rfc3339(now), startTime=timestamp.to_rfc3339(now), importance=sc_messages.Operation.ImportanceValueValuesEnum.LOW) if self.operation_id: op.operationId = self.operation_id if self.operation_name: op.operationName = self.operation_name if (self.api_key and self.api_key_valid): op.consumerId = (u'api_key:' + self.api_key) elif self.consumer_project_id: op.consumerId = (u'project:' + self.consumer_project_id) return op
Makes an ``Operation`` from this instance. Returns: an ``Operation``
codesearchnet
def generate_rpn_proposals(boxes, scores, img_shape, pre_nms_topk, post_nms_topk=None): assert boxes.shape.ndims == 2, boxes.shape if post_nms_topk is None: post_nms_topk = pre_nms_topk topk = tf.minimum(pre_nms_topk, tf.size(scores)) topk_scores, topk_indices = tf.nn.top_k(scores, k=topk, sorted=False) topk_boxes = tf.gather(boxes, topk_indices) topk_boxes = clip_boxes(topk_boxes, img_shape) topk_boxes_x1y1x2y2 = tf.reshape(topk_boxes, (-1, 2, 2)) topk_boxes_x1y1, topk_boxes_x2y2 = tf.split(topk_boxes_x1y1x2y2, 2, axis=1) wbhb = tf.squeeze(topk_boxes_x2y2 - topk_boxes_x1y1, axis=1) valid = tf.reduce_all(wbhb > cfg.RPN.MIN_SIZE, axis=1) topk_valid_boxes_x1y1x2y2 = tf.boolean_mask(topk_boxes_x1y1x2y2, valid) topk_valid_scores = tf.boolean_mask(topk_scores, valid) topk_valid_boxes_y1x1y2x2 = tf.reshape( tf.reverse(topk_valid_boxes_x1y1x2y2, axis=[2]), (-1, 4), name='nms_input_boxes') nms_indices = tf.image.non_max_suppression( topk_valid_boxes_y1x1y2x2, topk_valid_scores, max_output_size=post_nms_topk, iou_threshold=cfg.RPN.PROPOSAL_NMS_THRESH) topk_valid_boxes = tf.reshape(topk_valid_boxes_x1y1x2y2, (-1, 4)) proposal_boxes = tf.gather(topk_valid_boxes, nms_indices) proposal_scores = tf.gather(topk_valid_scores, nms_indices) tf.sigmoid(proposal_scores, name='probs') return tf.stop_gradient(proposal_boxes, name='boxes'), tf.stop_gradient(proposal_scores, name='scores')
Sample RPN proposals by the following steps: 1. Pick top k1 by scores 2. NMS them 3. Pick top k2 by scores. Default k2 == k1, i.e. does not filter the NMS output. Args: boxes: nx4 float dtype, the proposal boxes. Decoded to floatbox already scores: n float, the logits img_shape: [h, w] pre_nms_topk, post_nms_topk (int): See above. Returns: boxes: kx4 float scores: k logits
juraj-google-style
def masked_within_block_local_attention_1d(q, k, v, block_length=64, name=None): with tf.variable_scope(name, default_name='within_local_attention_1d', values=[q, k, v]): (batch, heads, length, depth_k) = common_layers.shape_list(q) depth_v = common_layers.shape_list(v)[(- 1)] if isinstance(block_length, tf.Tensor): const = tf.contrib.util.constant_value(block_length) if (const is not None): block_length = int(const) original_length = length padding_size = tf.mod((- length), block_length) length += padding_size padding = [[0, 0], [0, 0], [0, padding_size], [0, 0]] q = tf.pad(q, padding) k = tf.pad(k, padding) v = tf.pad(v, padding) num_blocks = tf.div(length, block_length) q = tf.reshape(q, [batch, heads, num_blocks, block_length, depth_k]) k = tf.reshape(k, [batch, heads, num_blocks, block_length, depth_k]) v = tf.reshape(v, [batch, heads, num_blocks, block_length, depth_v]) attention = tf.matmul(q, k, transpose_b=True) attention += tf.reshape(attention_bias_lower_triangle(block_length), [1, 1, 1, block_length, block_length]) attention = tf.nn.softmax(attention) output = tf.matmul(attention, v) output = tf.reshape(output, [batch, heads, (- 1), depth_v]) output = tf.slice(output, [0, 0, 0, 0], [(- 1), (- 1), original_length, (- 1)]) output.set_shape([(None if isinstance(dim, tf.Tensor) else dim) for dim in (batch, heads, length, depth_v)]) return output
Attention to the source and a neighborhood to the left within a block. The sequence is divided into blocks of length block_length. Attention for a given query position can only see memory positions less than or equal to the query position in the corresponding block. Args: q: a Tensor with shape [batch, heads, length, depth_k] k: a Tensor with shape [batch, heads, length, depth_k] v: a Tensor with shape [batch, heads, length, depth_v] block_length: an integer name: an optional string Returns: a Tensor of shape [batch, heads, length, depth_v]
codesearchnet
def bdp_bds_cache(func, tickers, flds, **kwargs) -> ToQuery: cache_data = [] log_level = kwargs.get('log', logs.LOG_LEVEL) logger = logs.get_logger(bdp_bds_cache, level=log_level) kwargs['has_date'] = kwargs.pop('has_date', func == 'bds') kwargs['cache'] = kwargs.get('cache', True) tickers = utils.flatten(tickers) flds = utils.flatten(flds) loaded = pd.DataFrame(data=0, index=tickers, columns=flds) for ticker, fld in product(tickers, flds): data_file = storage.ref_file( ticker=ticker, fld=fld, ext='pkl', **{ k: v for k, v in kwargs.items() if k not in EXC_COLS } ) if not files.exists(data_file): continue logger.debug(f'reading from {data_file} ...') cache_data.append(pd.read_pickle(data_file)) loaded.loc[ticker, fld] = 1 to_qry = loaded.where(loaded == 0)\ .dropna(how='all', axis=1).dropna(how='all', axis=0) return ToQuery( tickers=to_qry.index.tolist(), flds=to_qry.columns.tolist(), cached_data=cache_data )
Find cached `BDP` / `BDS` queries Args: func: function name - bdp or bds tickers: tickers flds: fields **kwargs: other kwargs Returns: ToQuery(ticker, flds, kwargs)
juraj-google-style
def convert(self, value): if (self._type is str): return str(value) elif (self._type is int): try: return int(value) except (UnicodeError, ValueError): raise WorkflowArgumentError('Cannot convert {} to int'.format(value)) elif (self._type is float): try: return float(value) except (UnicodeError, ValueError): raise WorkflowArgumentError('Cannot convert {} to float'.format(value)) elif (self._type is bool): if isinstance(value, bool): return bool(value) value = value.lower() if (value in ('true', '1', 'yes', 'y')): return True elif (value in ('false', '0', 'no', 'n')): return False raise WorkflowArgumentError('Cannot convert {} to bool'.format(value)) else: return value
Convert the specified value to the type of the option. Args: value: The value that should be converted. Returns: The value with the type given by the option.
codesearchnet
def to_FIB(self, other): if (not isinstance(other, GroundedFunctionNetwork)): raise TypeError(f'Expected GroundedFunctionNetwork, but got {type(other)}') def shortname(var): return var[(var.find('::') + 2):var.rfind('_')] def shortname_vars(graph, shortname): return [v for v in graph.nodes() if (shortname in v)] this_var_nodes = [shortname(n) for (n, d) in self.nodes(data=True) if (d['type'] == 'variable')] other_var_nodes = [shortname(n) for (n, d) in other.nodes(data=True) if (d['type'] == 'variable')] shared_vars = set(this_var_nodes).intersection(set(other_var_nodes)) full_shared_vars = {full_var for shared_var in shared_vars for full_var in shortname_vars(self, shared_var)} return ForwardInfluenceBlanket(self, full_shared_vars)
Creates a ForwardInfluenceBlanket object representing the intersection of this model with the other input model. Args: other: The GroundedFunctionNetwork object to compare this model to. Returns: A ForwardInfluenceBlanket object to use for model comparison.
codesearchnet
def update_config(config): update(bigchaindb.config, update_types(config, bigchaindb.config)) bigchaindb.config['CONFIGURED'] = True
Update bigchaindb.config with whatever is in the provided config dict, and then set bigchaindb.config['CONFIGURED'] = True Args: config (dict): the config dict to read for changes to the default config
juraj-google-style
def parse(self, argument): if isinstance(argument, self.enum_class): return argument if argument not in self.enum_class.__members__: raise ValueError('value should be one of <%s>' % '|'.join(self.enum_class.__members__.keys())) else: return self.enum_class[argument]
Determines validity of argument and returns the correct element of enum. Args: argument: str or Enum class member, the supplied flag value. Returns: The first matching Enum class member in Enum class. Raises: ValueError: Raised when argument didn't match anything in enum.
juraj-google-style
def _update_field(self, uri, field): payload = None if type(field) is not StreakField: return requests.codes.bad_request, None payload = field.to_dict(rw = True) try: uri = '/'.join([ uri, field.attributes['key'] ]) except KeyError: return requests.codes.bad_request, None code, data = self._req('post', uri , json.dumps(payload)) return code, data
Updates a field with the provided attributes. Args: key reqiured identifier for the pipeline or box field StreakField object kwargs {name, type} see StreakField for details return (status code, field dict)
juraj-google-style