Search is not available for this dataset
text stringlengths 75 104k |
|---|
def _separate_masks(mask, threshold=0.025):
"""
Returns a list of segmentation masks each of the same dimension as the input one,
but where they each have exactly one segment in them and all other samples in them
are zeroed.
Only bothers to return segments that are larger in total area than `thresh... |
def _downsample_one_or_the_other(mask, mask_indexes, stft, stft_indexes):
"""
Takes the given `mask` and `stft`, which must be matrices of shape `frequencies, times`
and downsamples one of them into the other one's times, so that the time dimensions
are equal. Leaves the frequency dimension untouched.
... |
def _map_segmentation_mask_to_stft_domain(mask, times, frequencies, stft_times, stft_frequencies):
"""
Maps the given `mask`, which is in domain (`frequencies`, `times`) to the new domain (`stft_frequencies`, `stft_times`)
and returns the result.
"""
assert mask.shape == (frequencies.shape[0], times... |
def _asa_task(q, masks, stft, sample_width, frame_rate, nsamples_for_each_fft):
"""
Worker for the ASA algorithm's multiprocessing step.
"""
# Convert each mask to (1 or 0) rather than (ID or 0)
for mask in masks:
mask = np.where(mask > 0, 1, 0)
# Multiply the masks against STFTs
ma... |
def _get_filter_indices(seg, start_as_yes, prob_raw_yes, ms_per_input, model, transition_matrix, model_stats):
"""
Runs a Markov Decision Process over the given `seg` in chunks of `ms_per_input`, yielding `True` if
this `ms_per_input` chunk has been classified as positive (1) and `False` if this chunk has b... |
def _group_filter_values(seg, filter_indices, ms_per_input):
"""
Takes a list of 1s and 0s and returns a list of tuples of the form:
['y/n', timestamp].
"""
ret = []
for filter_value, (_segment, timestamp) in zip(filter_indices, seg.generate_frames_as_segments(ms_per_input)):
if filter_v... |
def _homogeneity_filter(ls, window_size):
"""
Takes `ls` (a list of 1s and 0s) and smoothes it so that adjacent values are more likely
to be the same.
:param ls: A list of 1s and 0s to smooth.
:param window_size: How large the smoothing kernel is.
:returns: A list of 1s and 0... |
def bandpass_filter(data, low, high, fs, order=5):
"""
Does a bandpass filter over the given data.
:param data: The data (numpy array) to be filtered.
:param low: The low cutoff in Hz.
:param high: The high cutoff in Hz.
:param fs: The sample rate (in Hz) of the data.
:param order: The orde... |
def lowpass_filter(data, cutoff, fs, order=5):
"""
Does a lowpass filter over the given data.
:param data: The data (numpy array) to be filtered.
:param cutoff: The high cutoff in Hz.
:param fs: The sample rate in Hz of the data.
:param order: The order of the filter. The higher the order, the ... |
def list_to_tf_input(data, response_index, num_outcomes):
"""
Separates the outcome feature from the data and creates the onehot vector for each row.
"""
matrix = np.matrix([row[:response_index] + row[response_index+1:] for row in data])
outcomes = np.asarray([row[response_index] for row in data], dtype=np.ui... |
def expand_and_standardize_dataset(response_index, response_header, data_set, col_vals, headers, standardizers, feats_to_ignore, columns_to_expand, outcome_trans_dict):
"""
Standardizes continuous features and expands categorical features.
"""
# expand and standardize
modified_set = []
for row_index, row in... |
def equal_ignore_order(a, b):
"""
Used to check whether the two edge lists have the same edges
when elements are neither hashable nor sortable.
"""
unmatched = list(b)
for element in a:
try:
unmatched.remove(element)
except ValueError:
return False
return not unmatched |
def repair(self, data_to_repair):
num_cols = len(data_to_repair[0])
col_ids = range(num_cols)
# Get column type information
col_types = ["Y"]*len(col_ids)
for i, col in enumerate(col_ids):
if i in self.features_to_ignore:
col_types[i] = "I"
elif i == self.feature_to_repair:
... |
def group_audit_ranks(filenames, measurer, similarity_bound=0.05):
"""
Given a list of audit files, rank them using the `measurer` and
return the features that never deviate more than `similarity_bound`
across repairs.
"""
def _partition_groups(feature_scores):
groups = []
for feature, score in fea... |
def accuracy(conf_matrix):
"""
Given a confusion matrix, returns the accuracy.
Accuracy Definition: http://research.ics.aalto.fi/events/eyechallenge2005/evaluation.shtml
"""
total, correct = 0.0, 0.0
for true_response, guess_dict in conf_matrix.items():
for guess, count in guess_dict.items():
if t... |
def BCR(conf_matrix):
"""
Given a confusion matrix, returns Balanced Classification Rate.
BCR is (1 - Balanced Error Rate).
BER Definition: http://research.ics.aalto.fi/events/eyechallenge2005/evaluation.shtml
"""
parts = []
for true_response, guess_dict in conf_matrix.items():
error = 0.0
total =... |
def get_median(values, kdd):
"""
Given an unsorted list of numeric values, return median value (as a float).
Note that in the case of even-length lists of values, we apply the value to
the left of the center to be the median (such that the median can only be
a value from the list of values).
Eg: get_median(... |
def expand_to_one_hot(data,expand = True,use_alternative=False):
header_dict = {'ALCABUS':0,'PRIRCAT':1,'TMSRVC':2,'SEX1':3,'RACE':4,'RELTYP':5,'age_1st_arrest':6,'DRUGAB':7,'Class':8,'RLAGE':9,'NFRCTNS':10}
new_data = []
for entry in data:
temp = {}
if expand == True:
if entry[header_dict["SEX1"]] ... |
def load_audit_confusion_matrices(filename):
"""
Loads a confusion matrix in a two-level dictionary format.
For example, the confusion matrix of a 75%-accurate model
that predicted 15 values (and mis-classified 5) may look like:
{"A": {"A":10, "B": 5}, "B": {"B":5}}
Note that raw boolean values are transl... |
def list_to_tf_input(data, response_index, num_outcomes):
"""
Separates the outcome feature from the data.
"""
matrix = np.matrix([row[:response_index] + row[response_index+1:] for row in data])
outcomes = np.asarray([row[response_index] for row in data], dtype=np.uint8)
return matrix, outcomes |
def FreedmanDiaconisBinSize(feature_values):
"""
The bin size in FD-binning is given by size = 2 * IQR(x) * n^(-1/3)
More Info: https://en.wikipedia.org/wiki/Freedman%E2%80%93Diaconis_rule
If the BinSize ends up being 0 (in the case that all values are the same),
return a BinSize of 1.
"""
q75, q25 = nu... |
def _update_index_url_from_configs(self):
""" Checks for alternative index-url in pip.conf """
if 'VIRTUAL_ENV' in os.environ:
self.pip_config_locations.append(os.path.join(os.environ['VIRTUAL_ENV'], 'pip.conf'))
self.pip_config_locations.append(os.path.join(os.environ['VIRTUAL_... |
def _fetch_index_package_info(self, package_name, current_version):
"""
:type package_name: str
:type current_version: version.Version
"""
try:
package_canonical_name = package_name
if self.PYPI_API_TYPE == 'simple_html':
package_canonical... |
def _parse_pypi_json_package_info(self, package_name, current_version, response):
"""
:type package_name: str
:type current_version: version.Version
:type response: requests.models.Response
"""
data = response.json()
all_versions = [version.parse(vers) for vers i... |
def _parse_simple_html_package_info(self, package_name, current_version, response):
"""
:type package_name: str
:type current_version: version.Version
:type response: requests.models.Response
"""
pattern = r'<a.*>.*{name}-([A-z0-9\.-]*)(?:-py|\.tar).*<\/a>'.format(name=re... |
def main():
""" Main CLI entrypoint. """
options = get_options()
Windows.enable(auto_colors=True, reset_atexit=True)
try:
# maybe check if virtualenv is not activated
check_for_virtualenv(options)
# 1. detect requirements files
filenames = RequirementsDetector(options.g... |
def _update_package(self, package):
""" Update (install) the package in current environment, and if success, also replace version in file """
try:
if not self.dry_run and not self.skip_package_installation: # pragma: nocover
subprocess.check_call(['pip', 'install', '{}=={}'.... |
def autodetect_files(self):
""" Attempt to detect requirements files in the current working directory """
if self._is_valid_requirements_file('requirements.txt'):
self.filenames.append('requirements.txt')
if self._is_valid_requirements_file('requirements.pip'): # pragma: nocover
... |
def resolve_streams(wait_time=1.0):
"""Resolve all streams on the network.
This function returns all currently available streams from any outlet on
the network. The network is usually the subnet specified at the local
router, but may also include a group of machines visible to each other via
mul... |
def resolve_byprop(prop, value, minimum=1, timeout=FOREVER):
"""Resolve all streams with a specific value for a given property.
If the goal is to resolve a specific stream, this method is preferred over
resolving all streams and then selecting the desired one.
Keyword arguments:
prop -- The S... |
def resolve_bypred(predicate, minimum=1, timeout=FOREVER):
"""Resolve all streams that match a given predicate.
Advanced query that allows to impose more conditions on the retrieved
streams; the given string is an XPath 1.0 predicate for the <description>
node (omitting the surrounding []'s), see also... |
def handle_error(errcode):
"""Error handler function. Translates an error code into an exception."""
if type(errcode) is c_int:
errcode = errcode.value
if errcode == 0:
pass # no error
elif errcode == -1:
raise TimeoutError("the operation failed due to a timeout.")
elif errc... |
def push_sample(self, x, timestamp=0.0, pushthrough=True):
"""Push a sample into the outlet.
Each entry in the list corresponds to one channel.
Keyword arguments:
x -- A list of values to push (one per channel).
timestamp -- Optionally the capture time of the sample, in agreeme... |
def push_chunk(self, x, timestamp=0.0, pushthrough=True):
"""Push a list of samples into the outlet.
samples -- A list of samples, either as a list of lists or a list of
multiplexed values.
timestamp -- Optionally the capture time of the most recent sample, in
... |
def wait_for_consumers(self, timeout):
"""Wait until some consumer shows up (without wasting resources).
Returns True if the wait was successful, False if the timeout expired.
"""
return bool(lib.lsl_wait_for_consumers(self.obj, c_double(timeout))) |
def info(self, timeout=FOREVER):
"""Retrieve the complete information of the given stream.
This includes the extended description. Can be invoked at any time of
the stream's lifetime.
Keyword arguments:
timeout -- Timeout of the operation. (default FOREVER)
... |
def open_stream(self, timeout=FOREVER):
"""Subscribe to the data stream.
All samples pushed in at the other end from this moment onwards will be
queued and eventually be delivered in response to pull_sample() or
pull_chunk() calls. Pulling a sample without some preceding open_stream
... |
def time_correction(self, timeout=FOREVER):
"""Retrieve an estimated time correction offset for the given stream.
The first call to this function takes several miliseconds until a
reliable first estimate is obtained. Subsequent calls are instantaneous
(and rely on periodic background ... |
def pull_sample(self, timeout=FOREVER, sample=None):
"""Pull a sample from the inlet and return it.
Keyword arguments:
timeout -- The timeout for this operation, if any. (default FOREVER)
If this is passed as 0.0, then the function returns only a
s... |
def pull_chunk(self, timeout=0.0, max_samples=1024, dest_obj=None):
"""Pull a chunk of samples from the inlet.
Keyword arguments:
timeout -- The timeout of the operation; if passed as 0.0, then only
samples available for immediate pickup will be returned.
... |
def child(self, name):
"""Get a child with a specified name."""
return XMLElement(lib.lsl_child(self.e, str.encode(name))) |
def next_sibling(self, name=None):
"""Get the next sibling in the children list of the parent node.
If a name is provided, the next sibling with the given name is returned.
"""
if name is None:
return XMLElement(lib.lsl_next_sibling(self.e))
else:
return... |
def previous_sibling(self, name=None):
"""Get the previous sibling in the children list of the parent node.
If a name is provided, the previous sibling with the given name is
returned.
"""
if name is None:
return XMLElement(lib.lsl_previous_sibling(self.e))
... |
def child_value(self, name=None):
"""Get child value (value of the first child that is text).
If a name is provided, then the value of the first child with the
given name is returned.
"""
if name is None:
res = lib.lsl_child_value(self.e)
else:
r... |
def append_child_value(self, name, value):
"""Append a child node with a given name, which has a (nameless)
plain-text child with the given text value."""
return XMLElement(lib.lsl_append_child_value(self.e,
str.encode(name),
... |
def prepend_child_value(self, name, value):
"""Prepend a child node with a given name, which has a (nameless)
plain-text child with the given text value."""
return XMLElement(lib.lsl_prepend_child_value(self.e,
str.encode(name),
... |
def set_child_value(self, name, value):
"""Set the text value of the (nameless) plain-text child of a named
child node."""
return XMLElement(lib.lsl_set_child_value(self.e,
str.encode(name),
str.... |
def set_name(self, name):
"""Set the element's name. Returns False if the node is empty."""
return bool(lib.lsl_set_name(self.e, str.encode(name))) |
def set_value(self, value):
"""Set the element's value. Returns False if the node is empty."""
return bool(lib.lsl_set_value(self.e, str.encode(value))) |
def append_child(self, name):
"""Append a child element with the specified name."""
return XMLElement(lib.lsl_append_child(self.e, str.encode(name))) |
def prepend_child(self, name):
"""Prepend a child element with the specified name."""
return XMLElement(lib.lsl_prepend_child(self.e, str.encode(name))) |
def append_copy(self, elem):
"""Append a copy of the specified element as a child."""
return XMLElement(lib.lsl_append_copy(self.e, elem.e)) |
def prepend_copy(self, elem):
"""Prepend a copy of the specified element as a child."""
return XMLElement(lib.lsl_prepend_copy(self.e, elem.e)) |
def remove_child(self, rhs):
"""Remove a given child element, specified by name or as element."""
if type(rhs) is XMLElement:
lib.lsl_remove_child(self.e, rhs.e)
else:
lib.lsl_remove_child_n(self.e, rhs) |
def results(self):
"""Obtain the set of currently present streams on the network.
Returns a list of matching StreamInfo objects (with empty desc
field), any of which can subsequently be used to open an inlet.
"""
# noinspection PyCallingNonCallable
buffer = (c_void_p*10... |
def pair(cmd, word):
"""See all token associated with a given token.
PAIR lilas"""
word = list(preprocess_query(word))[0]
key = pair_key(word)
tokens = [t.decode() for t in DB.smembers(key)]
tokens.sort()
print(white(tokens))
print(magenta('(Total: {})'.format(len(tokens)))) |
def do_AUTOCOMPLETE(cmd, s):
"""Shows autocomplete results for a given token."""
s = list(preprocess_query(s))[0]
keys = [k.decode() for k in DB.smembers(edge_ngram_key(s))]
print(white(keys))
print(magenta('({} elements)'.format(len(keys)))) |
def compute_edge_ngrams(token, min=None):
"""Compute edge ngram of token from min. Does not include token itself."""
if min is None:
min = config.MIN_EDGE_NGRAMS
token = token[:config.MAX_EDGE_NGRAMS + 1]
return [token[:i] for i in range(min, len(token))] |
def iter_pipe(pipe, processors):
"""Allow for iterators to return either an item or an iterator of items."""
if isinstance(pipe, str):
pipe = [pipe]
for it in processors:
pipe = it(pipe)
yield from pipe |
def import_by_path(path):
"""
Import functions or class by their path. Should be of the form:
path.to.module.func
"""
if not isinstance(path, str):
return path
module_path, *name = path.rsplit('.', 1)
func = import_module(module_path)
if name:
func = getattr(func, name[0]... |
def haversine_distance(point1, point2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees).
"""
lat1, lon1 = point1
lat2, lon2 = point2
# Convert decimal degrees to radians.
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2... |
def imap_unordered(self, func, iterable, chunksize):
"""Customized version of imap_unordered.
Directly send chunks to func, instead of iterating in each process and
sending one by one.
Original:
https://hg.python.org/cpython/file/tip/Lib/multiprocessing/pool.py#l271
Ot... |
def make_fuzzy(word, max=1):
"""Naive neighborhoods algo."""
# inversions
neighbors = []
for i in range(0, len(word) - 1):
neighbor = list(word)
neighbor[i], neighbor[i+1] = neighbor[i+1], neighbor[i]
neighbors.append(''.join(neighbor))
# substitutions
for letter in strin... |
def do_fuzzy(self, word):
"""Compute fuzzy extensions of word.
FUZZY lilas"""
word = list(preprocess_query(word))[0]
print(white(make_fuzzy(word))) |
def do_fuzzyindex(self, word):
"""Compute fuzzy extensions of word that exist in index.
FUZZYINDEX lilas"""
word = list(preprocess_query(word))[0]
token = Token(word)
neighbors = make_fuzzy(token)
neighbors = [(n, DB.zcard(dbkeys.token_key(n))) for n in neighbors]
neighbors.sort(key=lambda n... |
def extend_results_extrapoling_relations(helper):
"""Try to extract the bigger group of interlinked tokens.
Should generally be used at last in the collectors chain.
"""
if not helper.bucket_dry:
return # No need.
tokens = set(helper.meaningful + helper.common)
for relation in _extract... |
def do_help(self, command):
"""Display this help message."""
if command:
doc = getattr(self, 'do_' + command).__doc__
print(cyan(doc.replace(' ' * 8, '')))
else:
print(magenta('Available commands:'))
print(magenta('Type "HELP <command>" to get more... |
def do_BENCH(self, query):
"""Run a search many times to benchmark it.
BENCH [100] rue des Lilas"""
try:
count = int(re.match(r'^(\d+).*', query).group(1))
except AttributeError:
count = 100
self._search(query, count=count) |
def do_INTERSECT(self, words):
"""Do a raw intersect between tokens (default limit 100).
INTERSECT rue des lilas [LIMIT 100]"""
start = time.time()
limit = 100
if 'LIMIT' in words:
words, limit = words.split('LIMIT')
limit = int(limit)
tokens = [ke... |
def do_DBINFO(self, *args):
"""Print some useful infos from Redis DB."""
info = DB.info()
keys = [
'keyspace_misses', 'keyspace_hits', 'used_memory_human',
'total_commands_processed', 'total_connections_received',
'connected_clients']
for key in keys:
... |
def do_DBKEY(self, key):
"""Print raw content of a DB key.
DBKEY g|u09tyzfe"""
type_ = DB.type(key).decode()
if type_ == 'set':
out = DB.smembers(key)
elif type_ == 'string':
out = DB.get(key)
else:
out = 'Unsupported type {}'.format(ty... |
def do_GEODISTANCE(self, s):
"""Compute geodistance from a result to a point.
GEODISTANCE 772210180J 48.1234 2.9876"""
try:
_id, lat, lon = s.split()
except:
return self.error('Malformed query. Use: ID lat lon')
try:
result = Result(keys.docume... |
def do_GEOHASHTOGEOJSON(self, geoh):
"""Build GeoJSON corresponding to geohash given as parameter.
GEOHASHTOGEOJSON u09vej04 [NEIGHBORS 0|1|2]"""
geoh, with_neighbors = self._match_option('NEIGHBORS', geoh)
bbox = geohash.bbox(geoh)
try:
with_neighbors = int(with_neig... |
def do_GEOHASH(self, latlon):
"""Compute a geohash from latitude and longitude.
GEOHASH 48.1234 2.9876"""
try:
lat, lon = map(float, latlon.split())
except ValueError:
print(red('Invalid lat and lon {}'.format(latlon)))
else:
print(white(geohas... |
def do_GEOHASHMEMBERS(self, geoh):
"""Return members of a geohash and its neighbors.
GEOHASHMEMBERS u09vej04 [NEIGHBORS 0]"""
geoh, with_neighbors = self._match_option('NEIGHBORS', geoh)
key = compute_geohash_key(geoh, with_neighbors != '0')
if key:
for id_ in DB.smem... |
def do_GET(self, _id):
"""Get document from index with its id.
GET 772210180J"""
doc = doc_by_id(_id)
if not doc:
return self.error('id "{}" not found'.format(_id))
for key, value in doc.items():
if key == config.HOUSENUMBERS_FIELD:
continu... |
def do_INDEX(self, _id):
"""Get index details for a document by its id.
INDEX 772210180J"""
doc = doc_by_id(_id)
if not doc:
return self.error('id "{}" not found'.format(_id))
for field in config.FIELDS:
key = field['key']
if key in doc:
... |
def do_BESTSCORE(self, word):
"""Return document linked to word with higher score.
BESTSCORE lilas"""
key = keys.token_key(indexed_string(word)[0])
for _id, score in DB.zrevrange(key, 0, 20, withscores=True):
result = Result(_id)
print(white(result), blue(score), ... |
def do_REVERSE(self, latlon):
"""Do a reverse search. Args: lat lon.
REVERSE 48.1234 2.9876"""
lat, lon = latlon.split()
for r in reverse(float(lat), float(lon)):
print('{} ({} | {} km | {})'.format(white(r), blue(r.score),
blue... |
def do_STRDISTANCE(self, s):
"""Print the distance score between two strings. Use | as separator.
STRDISTANCE rue des lilas|porte des lilas"""
s = s.split('|')
if not len(s) == 2:
print(red('Malformed string. Use | between the two strings.'))
return
one, t... |
def do_CONFIG(self, name):
"""Inspect loaded Addok config. Output all config without argument.
CONFIG [CONFIG_KEY]"""
if not name:
for name in self.complete_CONFIG():
self.do_CONFIG(name)
return
value = getattr(config, name.upper(), 'Not found.')
... |
def do_SCRIPT(self, args):
"""Run a Lua script. Takes the raw Redis arguments.
SCRIPT script_name number_of_keys key1 key2… arg1 arg2
"""
try:
name, keys_count, *args = args.split()
except ValueError:
print(red('Not enough arguments'))
return
... |
def send(r, stream=False):
"""Just sends the request using its send method and returns its response. """
r.send(stream=stream)
return r.response |
def map(requests, stream=True, pool=None, size=1, exception_handler=None):
"""Concurrently converts a list of Requests to Responses.
:param requests: a collection of Request objects.
:param stream: If False, the content will not be downloaded immediately.
:param size: Specifies the number of workers to... |
def imap(requests, stream=True, pool=None, size=2, exception_handler=None):
"""Concurrently converts a generator object of Requests to
a generator of Responses.
:param requests: a generator of Request objects.
:param stream: If False, the content will not be downloaded immediately.
:param size: Spe... |
def imap_unordered(requests, stream=True, pool=None, size=2, exception_handler=None):
"""Concurrently converts a generator object of Requests to
a generator of Responses.
:param requests: a generator of Request objects.
:param stream: If False, the content will not be downloaded immediately.
:param... |
def getBits_from_array(array, wordWidth, start, end,
reinterpretElmToType=None):
"""
Gets value of bits between selected range from memory
:param start: bit address of start of bit of bits
:param end: bit address of first bit behind bits
:return: instance of BitsVal (derived ... |
def reinterptet_harray_to_bits(typeFrom, sigOrVal, bitsT):
"""
Cast HArray signal or value to signal or value of type Bits
"""
size = int(typeFrom.size)
widthOfElm = typeFrom.elmType.bit_length()
w = bitsT.bit_length()
if size * widthOfElm != w:
raise TypeConversionErr(
"... |
def slice_to_SLICE(sliceVals, width):
"""convert python slice to value of SLICE hdl type"""
if sliceVals.step is not None:
raise NotImplementedError()
start = sliceVals.start
stop = sliceVals.stop
if sliceVals.start is None:
start = INT.fromPy(width)
else:
start = toHVa... |
def getBusWordBitRange(self) -> Tuple[int, int]:
"""
:return: bit range which contains data of this part on bus data signal
"""
offset = self.startOfPart % self.parent.wordWidth
return (offset + self.bit_length(), offset) |
def getFieldBitRange(self) -> Tuple[int, int]:
"""
:return: bit range which contains data of this part on interface
of field
"""
offset = self.inFieldOffset
return (self.bit_length() + offset, offset) |
def fill_stm_list_with_enclosure(parentStm: Optional[HdlStatement],
current_enclosure: Set[RtlSignalBase],
statements: List["HdlStatement"],
do_enclose_for: List[RtlSignalBase],
enclosure:... |
def find_files(directory, pattern, recursive=True):
"""
Find files by pattern in directory
"""
if not os.path.isdir(directory):
if os.path.exists(directory):
raise IOError(directory + ' is not directory')
else:
raise IOError(directory + " does not exists")
if ... |
def SwitchLogic(cases, default=None):
"""
Generate if tree for cases like (syntax shugar for large elifs)
..code-block:: python
if cond0:
statements0
elif cond1:
statements1
else:
default
:param case: iterable of tuples (condition, statements... |
def In(sigOrVal, iterable):
"""
Hdl convertible in operator, check if any of items
in "iterable" equals "sigOrVal"
"""
res = None
for i in iterable:
i = toHVal(i)
if res is None:
res = sigOrVal._eq(i)
else:
res = res | sigOrVal._eq(i)
assert r... |
def StaticForEach(parentUnit, items, bodyFn, name=""):
"""
Generate for loop for static items
:param parentUnit: unit where this code should be instantiated
:param items: items which this "for" itering on
:param bodyFn: function which fn(item, index) or fn(item)
returns (statementList, ack)... |
def connect(src, *destinations, exclude: set=None, fit=False):
"""
Connect src (signals/interfaces/values) to all destinations
:param exclude: interfaces on any level on src or destinations
which should be excluded from connection process
:param fit: auto fit source width to destination width
... |
def rol(sig, howMany) -> RtlSignalBase:
"Rotate left"
width = sig._dtype.bit_length()
return sig[(width - howMany):]._concat(sig[:(width - howMany)]) |
def sll(sig, howMany) -> RtlSignalBase:
"Logical shift left"
width = sig._dtype.bit_length()
return sig[(width - howMany):]._concat(vec(0, howMany)) |
def log2ceil(x):
"""
Returns no of bits required to store x-1
for example x=8 returns 3
"""
if not isinstance(x, (int, float)):
x = int(x)
if x == 0 or x == 1:
res = 1
else:
res = math.ceil(math.log2(x))
return hInt(res) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.