content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def converter_log10_to_lin(data): """Return 10 ** data""" return 10 ** data
cdfa4c69a888d4ba69e4b1ed2aa0d618308c4dcb
572,656
def barcode_size(codes): """Returns the barcode size in modules.""" num_rows = len(codes) num_cols = len(codes[0]) # 17 bodules per column, last column has an additional module width = num_cols * 17 + 1 height = num_rows return width, height
c1bb318fe156bf5f645e82abea2ec18066f20d2d
572,657
def FcMw(Mw, m, b): """Defines the corner frequency for a given moment magnitude The common use is with the help of scipy.optimize.curve_fit, to find the parameters m and b that fit a straight line in the frequency domain (see interpolate_Fc_Mw()) :param Mw: the moment magnitude :type Mw: floa...
f3cbce4b0500147033af1b4ada22a8cf010442bc
572,658
def parse_key_value_list(values: list) -> dict: """ Option callback to validate a list of key/value arguments. Converts 'NAME=VALUE' CLI parameters to a dictionary. :raises: ValueError """ if not values: return {} params = {} for value in values: parts = value.split(...
f581b5cd27f993462076bf1378ad2b0baaa3567e
572,662
def linear_h(theta, x): """linear_h: The linear hypothesis regressor. :param theta: parameters for our linear regressor; shape (1, features) :type theta: np.ndarray :param x: input that model is predicting; shape (samples, features) :type x: np.ndarray :return: The predictions of our model on in...
a029563bee5adec25616fdd21956547287698faa
572,663
def normalise(test, ref, strict=False): """ Routine to normalise contents of test by contents of ref. :param dict test: Dictionary of test metrics :param dict ref: Dictionary of reference metrics :param bool strict: if True then test and ref must have same metrics :returns: Dictionary of normal...
b4df1ee3bbc46bd56201d7dd7682748e42370919
572,666
def rescale_range(X, old_range, new_range): """Rescale X linearly to be in `new_range` rather than `old_range`.""" old_min = old_range[0] new_min = new_range[0] old_delta = old_range[1] - old_min new_delta = new_range[1] - new_min return (((X - old_min) * new_delta) / old_delta) + new_min
70e87e13c5a4f6887a390130c1aca130a5d4ce79
572,667
import torch import unittest def require_multi_gpu(test_case): """ Decorator marking a test that requires a multi-GPU setup. These tests are skipped on a machine without multiple GPUs. """ if torch.cuda.device_count() < 2: return unittest.skip("test requires multiple GPUs")(test_case) ...
84b32c17519ed6030346691a2812f03248730057
572,669
import calendar def get_year_for_first_weekday(weekday=0): """Get the year that starts on 'weekday', eg. Monday=0.""" if weekday > 6: raise ValueError("weekday must be between 0 and 6") year = 2020 not_found = True while not_found: firstday = calendar.weekday(year, 1, 1) i...
21bc137686b1cdc046fabdc0a58cfd0a5a147682
572,671
import torch def translation_error(t1, t2): """ Torch batch implementation of the rotation error between the estimated and the ground truth rotatiom matrix. Rotation error is defined as r_e = \arccos(\frac{Trace(\mathbf{R}_{ij}^{T}\mathbf{R}_{ij}^{\mathrm{GT}) - 1}{2}) Args: t1 (torch tenso...
bef343053f8653cff23b734f27d94a599fbf5e45
572,673
def get_max_AMR_level(solution): """ Get the max AMR level in a solution object. """ max_level = 1 for state in solution.states: p = state.patch if p.level > max_level: max_level = p.level return max_level
4e844ec8ee5848b9b00295b7853ed8a51f43758b
572,679
def returns_reference(decl): """Return True iff the declaration returns a pointer or reference.""" c = decl.return_type.decl_string[-1] return c == '&' or c == '*'
bd49862bf84af8a644c2fcedfd2571cc00c06290
572,680
def get_no_control_guides(df, guide_base_score): """Get guides that are not paired with controls Parameters ---------- df: DataFrame DataFrame with the column anchor_gene guide_base_score: DataFrame Guide scores when paired with controls Returns ------- list Gui...
598e9d3c45bf7d391dcb8c81c475ad66c71a73a9
572,681
def generate_options_for_mode(server=None, control_value=None, **kwargs): """ Define a list of tuples that will be returned to generate the field options for the mode Action Input, depending on the value from monitoring_tool passed in as the control_value argument. each tuple follows this order: (v...
2c0da8abc151b1742de9036d51dc76f217ec477e
572,682
def load_stopwords(path): """Loads stopwords from `path`, assume each word in new line.""" stopwords = set() with open(path) as f: for line in f: stopwords.add(line.strip()) return stopwords
a1bb465f15a6678ab35895a119352d3334a879d6
572,693
def get_build_systems(entries): """ Given a list of entries, calculates statistics about the used build systems and returns the statistics as sorted list of elements (build-system-name, occurence). "n/a" is used if no build system was specified """ build_systems = [] for entry in entries: ...
25ca1979c855b79006085a38b69f1e33744aab4a
572,695
def _no_overlap(entity_one, entity_two): """ Returns True if two query entities do not overlap. Args: entity_one (QueryEntity): First entity. entity_two (QueryEntity): Second Entity. Returns: no_overlap (bool): True if no overlap. """ return ( entity_one.span.start >...
291e98903d4a47e7034ca6eb713276d00e3e2b1b
572,696
def make_matrix(sizex, sizey): """Creates a sizex by sizey matrix filled with zeros.""" return [[0] * sizey for i in range(sizex)]
1b4c66a9db61e5f54f435957280a6195c97ae6f1
572,701
def build_message(cmd, data): """ Gets command name (str) and data field (str) and creates a valid protocol message Returns: str, or None if error occured """ if len(cmd)>16 or len(data)>9999: return None spaces=' ' zeos="0000" full_msg=cmd +spaces[0:16-len(cmd)]+"|"+zeos[0:4-len(str(len(data))...
1bca88019ea321bf019da79f25641277a222c1eb
572,705
from typing import Tuple def extended_euclid(a: int, b: int) -> Tuple[int, int, int]: """Extended Euclidean algorithm that computes the Bézout coefficients as well as :math:`gcd(a, b)` Returns ``x, y, d`` where *x* and *y* are a solution to :math:`ax + by = d` and :math:`d = gcd(a, b)`. *x* and *y* are a...
5a921d59d886e555b8acfdca68e84adafce78864
572,706
def mul_of_3_or_5(limit: int) -> int: """Computes the sum of all the multiples of 3 or 5 below the given limit, using filter and range. :param limit: Limit of the values to sum (exclusive). :return: Sum of all the multiples of 3 or 5 below the given limit. """ return sum(filter( lambda ...
cb82fcdd01cb222c5a8938fefee9ce8a547bdb61
572,707
def parse_alpm_dict(blob): """ Parse a blob of text as ALPM file. The results are returned as a dictionary with each key having a list of values. """ result = {} key = None values = [] for line in blob.splitlines(): if len(line) == 0: continue if line[0] == '%' and line[-1] == '%': if key is not None...
fd6fac09e969983583095828da38961790c2e251
572,709
def calc_hubbard_u(iv, iv_p1, d_mm_avg): """ Calculate the estimated hubbard energy (eV) of a structure. :param iv: Float, the vth ionization energy :param iv_p1: Float, the (v+1)th ionization energy :param d_mm_avg: Float, the average metal-metal distance :return: Float, the estimated hubbard ...
bcd0e189658aaa559ddf532a8289dc652ecffefc
572,712
def bool_to_str(boolean): """Convert ``boolean`` to string like PHP. :param boolean: boolean value :type boolean: bool :return: string representation :rtype: str """ return '1' if boolean else ''
0bca43f3141589c60cd6d1c0a3d0d2479a370216
572,715
def get_experiment_label(path): """Extracts short experiment name from file path""" label = path.split("/") label = ".".join([*label[2:4], label[5]]) label = label.replace(".metrics", "") label = label.replace(".main", "") return label
2d9f0d59dbb89f2064d4e9205acab7a190030fc3
572,718
def is_not_round(neuron_max_x_y, coef=2): """Receives the length/width of the object, and returns True if the object is not round. coef: the x/y or y/x maximal ratio.""" x_len, y_len = neuron_max_x_y if (x_len/y_len) > coef or (y_len/x_len) > coef: return True else: return False
6f52ff971f5f3e69f8fcbe587fa2479b5e2ff299
572,723
def save_stage(stage, file_path=None): """ Saves given stage data into file path :param stage: Usd.Stage :param file_path: str """ return stage.Save(file_path) if file_path else stage.Save()
8da78849e63de8f896859bc3eff2e9b56e9e339f
572,724
def image_check(link: str): """ Function that checks the passed in link's end extension. Parameters ---------- link: str the link to check for Returns ------- bool whether or not the passed in link contains "image" format ending """ return link.lower().endswith(...
140bf4f6dadcd5f465e5f36f49823a1d689064c7
572,725
def build_url(url_type, bucket, key=None, region=None, credential_name=None): """ Construct an S3 URL Args: url_type: one of 's3', 's3-credential', 'bucket-in-path', 'bucket-in-netloc' bucket: S3 bucket name key: Key within bucket (optional) region: S3 region name (optional) ...
aa1c789329b54ad0bd9d792afb17bc3867019dcf
572,729
def get_node_property_list(nodes, properties): """Get list of a number of node properties fron a list of networkx nodes. Args: nodes (list): List of networkx format nodes. properties (list): List of string denoting the property keys to extract. Returns: list: List of lists of node properties. [[node1_prop1, ...
bde90e2e0ef2719c8b1105589c568edbbc6e9dc6
572,731
def is_integer(s): """ Return whether the string can be interpreted as an integer :param string: s, string to check for an integer """ if len(s) == 0: return False elif s[0] in ('-', '+'): return s[1:].isdigit() return s.isdigit()
2e27e1438ba9b5bcb04bdca020d10bb93d7b94e6
572,733
def identity(arg=None, *args, **kwargs): """ The identity function. Simply returns the value of its first input. All other inputs are ignored. Defaults to None if called without args. Args: arg (object, default=None): some value *args: ignored **kwargs: ignored Returns: ...
d52a7a4e47a1e77e78cbb7c5cb2b30a500089767
572,734
def isRenderTreeDump(data): """Returns true if data appears to be a render tree dump as opposed to a plain text dump.""" return data.find("RenderView at (0,0)") != -1
73636cd9578fa2c3014bcf9ede5d5732aa0a8e19
572,735
import unittest def get_attribute(obj, name): """Get an attribute, raising SkipTest if AttributeError is raised.""" try: attribute = getattr(obj, name) except AttributeError: raise unittest.SkipTest("object %r has no attribute %r" % (obj, name)) else: return attribute
2543bd7af7fd8ddf390bb4cfefcdcb53b0b69cc3
572,736
def get_link_to_gmaps(lat, lon, label='', zoom=15): """Return link to gmaps map centered in lat, lon.""" return ('https://maps.google.com/maps?ll=%(lat)s,%(lon)s' '&q=%(label)s@%(lat)s,%(lon)s&zoom=%(zoom)s' % {'lat': lat, 'lon': lon, ...
ccebaf2859ceea4bf728f80bd266172af5fcc5c4
572,737
def _create_issue_result_json(issue_id, summary, key, **kwargs): """Returns a minimal json object for an issue.""" return { "id": "%s" % issue_id, "summary": summary, "key": key, "self": kwargs.get("self", "http://example.com/%s" % issue_id), }
5f23fd24089d2b198d551ccca4f7cc4130aa85c9
572,738
def drop_col_with_name(df, col_name): """ Drops a column with specified name. :param df: Data Frame Object :param col_name: Name of column to drop :return: Data Frame Object """ return df.drop(col_name, 1)
6f28f3d78264839ce16d53ac9d47a248344232bc
572,739
def ordinal(string, d): """Return the ordinal of the character at dth position. Specifically, the ordinal of end-of-string is defined to be -1. """ if d < len(string): return ord(string[d]) elif d == len(string): return -1 else: raise IndexError
64b96e6d1a489281ca068c59c89473a94bbc89f2
572,741
def spreadsheet_repr(spreadsheet=None, spreadsheet_metadata=None): """ Returns a simple string representation of a Spreadsheet object Args: spreadsheet (pygsheets.spreadsheet.Spreadsheet or None): spreadsheet_metadata (dict or None): A dict of spreadsheet metadata Returns: str:...
58337abcdc8987051cf00b823125e479d77a7a9e
572,748
def scan_critical(fname): """ Find critical path and Fmax from VPR log (if any). Returns ------- critical_path : str Critical path delay in nsec fmax : str Fmax in MHz. """ try: with open(fname, 'r') as f: for line in f: if line.startswit...
1cded71ed408c7014fb603d6735e01eac54d2425
572,752
def impedance_delany_and_bazley(frequency, flow_resistivity): """ Normalised specific acoustic impedance according to the empirical one-parameter model by Delany and Bazley. :param frequency: Frequency :math:`f`. :param flow_resistivity: Flow resistivity :math:`\\sigma`. The impedance :mat...
8582953f6fda634af0c59fb3aa727a9d2c22cd6c
572,754
def merge_dicts(origin, patch): """ Merge two dictionaries, w/o overwriting missing keys :param origin: The origin dictionary :param patch: The dictionary containing the diffs :return: The result of the merge: a new dictionary """ for key in patch: if key in origin: if ...
b2ee36f899e8f487c3ae8ca193a7caf8774ab31f
572,759
def table_stats_comp(current, reference): """Check some basic properties of the tables like length and columns.""" assert len(current) >= len(reference), "Current results have {} rows compared to reference with {}".format(len(current), len(reference)) for col in reference.colnames: assert col in cur...
c5b8506f4043d0f4d924f1c4e004fb436894f99b
572,760
def is_iterable(x): """True if x can be iterated over""" return hasattr(x, '__iter__')
107a505b4426fc8b5720c784813d150b85a14d89
572,763
from typing import Optional def remove_dot(str: Optional[str]) -> Optional[str]: """Remove leading ./ from Parsoid titles""" if str: str = str[2:] return str
ffac38edb8ebc09fa83959f6a4a13c36b75b7221
572,765
def applyfs(funcs, args): """ Applies several functions to single set of arguments. This function takes a list of functions, applies each to given arguments, and returns the list of obtained results. For example: >>> from operator import add, sub, mul >>> list(applyfs([add, sub, mul], (...
47cc05f1df82a0b09787e2c969ec70891d968f55
572,766
def read_until_whitespace(stream, maxchars=None): """ Reads non-whitespace characters and returns them. Stops upon encountering whitespace or when maxchars is reached. """ if maxchars == 0: return b'' def _build(): stop_at = None if maxchars is None else stream.tell() + maxchars...
b245f3abc8ec0d9267c9faf970d8d722db0636b9
572,773
import base64 def hex_to_base64(hex_string: str) -> str: """Convert a hexadecimal string into base64 string Args: hex_string (str): Hexadecimal string Returns: str: Base64 encoded string """ return base64.b64encode(bytes.fromhex(hex_string)).decode("utf-8")
5accf98fbde52e741b68fdff7d097284d4ab8c57
572,778
import torch def attention_consistency_loss(attention_weights, reattention_weights): """Returns Attention consistency loss. Attention consistency loss is defined as the distance between the visual attention maps learned in the attention layer (learned from the fusion of the question and image feature...
b29d36975d5b11fd87bb54f13fe9fb10290056f8
572,779
import calendar def utc_datetime_to_ts(dt): """ convert datetime instance to timestamp in second Args: dt(datetime): datetime instance Returns: int: timestamp in second. """ return int(calendar.timegm(dt.timetuple()))
c263937976489347b58e7a4ef4ec4b0bce3ecfcb
572,783
from timeit import default_timer as clock def timing(f, *args, **kwargs): """ Returns time elapsed for evaluating ``f()``. Optionally arguments may be passed to time the execution of ``f(*args, **kwargs)``. If the first call is very quick, ``f`` is called repeatedly and the best time is returned....
fd800fcd5956743bad0cffe48c7ce319b2bbdadc
572,784
def separate_list(inlist, rule): """ Separates a list in two based on the rule. The rule is a string that is mached for last characters of list elements. """ lrule = len(rule) list1 = [] list2 = [] for item in inlist: if (item[-lrule:] == rule): list1.append(item) ...
a041037601391cf049f4c0451568f1309672523c
572,791
def bitmap_to_bytes(bitmap): """Turn bitmap into string of bytes The returned value is representation of bitmap suitable for store in the DataFrame, and ultimately in the HDF5 file. Parameters ---------- bitmap : BitMap Bitmap / bitset, which representation we want to get. Returns...
577faeadb6cc6f117308111f18282e4f6d6ebd0e
572,794
def indicator_volbands(df_t, lookback=20, multiplier=0.3): """Create bands around a mean based on volatility Args: df_t (frame): requires "close" and "vol36" -- which is daily volatility lookback (`obj`:int, optional): lookback for moving average multiplier (`obj`:float, optional): mult...
362b784894f7551e0eb6c494e4182609f17ade60
572,795
def visualThreshold(npArray, value): """ Thresholds all pixel values greater than 0 in numPy array and sets them to given value Arguments: npArray: A numpy array value: int to set all values greater than zero to Returns: Numpy array """ #npArray = npArray.astype('uint8') #print(mito_anno) npArra...
f3ba99e36f670f65f7911acf5fc30df51aeff422
572,797
import re def is_slender(text: str) -> bool: """Checks if a string ends with a slender vowel""" return re.search(r'[eiéí][^aeiouáéíóú]+$', text.lower()) is not None
1a16cbb07620ac171eca912044f794a198ab3f8b
572,803
def postsWithTag(posts, tag): """Returns all the posts with a given tag""" return [post for post in posts if tag in post['tags']]
cf50a4cfa451d45b3a0eee8f749162993e4fc8dd
572,805
def select_topn(df, top_n=25): """ Select top-n keywords for each ranking and value_normalized """ assert df.columns.str.contains("ranking").any(), "select_topn failed. Missing 'ranking' column." # top-n by ranking topn_idx = df.groupby("ranking").value_normalized.nlargest(top_n).droplevel(0).index...
1b0932036fb9124ea5cb7ea63d85734df3d4a0ec
572,806
def find_knn(test, knn, k): """make a prediction using the knn. :param test: input value :type test: numpy array :param knn: model :type knn: cv2 KNearest :param k: k value :type k: int :return: result :rtype: int """ ret, results, neighbours, dist = knn.findNearest(test, k)...
6e127ea45a8b965d03f8bde107d650838f2c328f
572,808
def semi_angle_limit(Lambda, C_3=1): """ Convergence semi-angle if the probe size is diffraction limited. Params: Lambda: electron wavelength in Å C_3: spherical aberration constant in mm, default 1. Returns: Convergence semi-angle in mrad. """ C_3 *= 1.e7 return 1.51 * C_3 ** (-...
3bd98406bd10f0e6c516301cd73c998948b653f1
572,816
def match_to_html(match): """ Render a Module Characteristic """ return ('<p class="module-characteristic"><strong>{0}</strong>: {1}</p>' .format(match.group('key'), match.group('value')))
63cb4aa2c86fe227b07591693de1d790c3d9bb2e
572,818
def validate_logginglevel(slackchannelconfiguration_logginglevel): """ Validate LoggingLevel for SlackChannelConfiguration Property: SlackChannelConfiguration.LoggingLevel """ VALID_SLACKCHANNELCONFIGURATION_LOGGINGLEVEL = ("ERROR", "INFO", "NODE") if ( slackchannelconfiguration_loggin...
9032879ed9b9cf3b207a6f73c84e6fa77cba093e
572,819
def symbols_to_data(vocab, list_of_symbols): """ Transform the symbol to original word. Args: vocab: a list of words, the dictionary. list_of_symbols: a list of string lists. """ list_of_sentences = [] for symbols in list_of_symbols: # a list of symbols sentence = [vocab[i] for i in symbols] lis...
997dd9aa9b693b59a195365ea89ea1af4048b18b
572,820
def split_list(lis, splitter): """applies splitting function splitter to list items, return two new lists, where the first contains all the entries where splitter returns true""" left = [] right = [] for i in lis: if splitter(i): left.append(i) else: right.append(i) return left, right
e643e02a91733d801149f57df3d54e48e4164054
572,824
def hex_to_position(value: str) -> int: """Convert hex string to int position. """ return int(value, 16)
a7fd0489d1bf5aa3d6bc61a5b763aad36c444c8b
572,825
def min_max(PE_data): """ Will normalize all the data to within the interval 0 to 1. The input should be a Dataframe with the trials as columns and a timeline as index. If a different interval is required, simply multiply the data by the width of that interval and add the floor. Examples: >>> PE_norm = min...
aa80c1b660ca43283fa631a39163c6ae168d56b1
572,826
from typing import Tuple from typing import List def unpack_version_number(version_string: str) -> Tuple[int, int, int]: """ Unpacks the version number converting it into a Tuple of integers. Args: version_string: (str) the version to be unpacked Returns: (Tuple[int, int, int]) the version n...
e978235e49d66fa1116e1b9a6dfe59ed41e6c012
572,829
def step_momentum(params, grad, alpha, v, beta=0.9): """Single iteration of gradient descent with momentum. NB! In-place modification of 'v'. Args: params (ndarray[1, n]): parameters for current step grad (ndarray[1, n]): gradient for current step alpha (float): learn...
18ec17cc2d42f8fa10761af30f88bc5617ca05d4
572,831
from typing import Tuple def smallest_labelizer(metrics: dict) -> Tuple[str, float]: """Given dict of metrics result, returns (key, metrics[key]) whose value is the smallest.""" items = list(metrics.items()) # print(items) label, smaller = items[0] for model_name, val in items[1:]: if val ...
64cf40df7b9fee38978676af910d8216190b308b
572,832
import base64 def hex_to_base64(hex): """ Takes a unicode hex string and base64 encodes it. """ hex = hex.decode('hex') data = base64.b64encode(hex) return data
56200f6f2e571d3409967b1e6c2e06a2c8a69d38
572,835
def clamp(x, lo, up): """ clamp x to be lo <= x <= up """ assert lo <= up return lo if x < lo else up if x > up else x
1778a202559c7773cc3f0724d05235399ba96312
572,837
def lsymbol(self, x="", y="", symang="", symtyp="", symsiz="", keybmp="", **kwargs): """Creates annotation symbols (GUI). APDL Command: /LSYMBOL Parameters ---------- x X location for symbol (-1.0 < X < 2.0). y Y location for symbol (-1.0 < Y < 1.0). symang ...
704247734d1722b61e5432561dcb0a2439da975d
572,839
import asyncio async def spawn(*args): """Spawns a process asynchronously.""" proc = await asyncio.create_subprocess_exec(*args, stdout=asyncio.subprocess.PIPE) return proc
964fc3b871913f3f4572289e907c23ffa689e7a2
572,841
from datetime import datetime def str_to_date(s): """ Get python datetime object from string. It tests for only two formats used in RRFS: YYYYMMDD and YYYYMMDDHHMM Args: s: a string Returns: datetime object or None """ try: v = datetime.strptime(s, "%Y%m%d%H%M") ...
ae5a5e9099af440aa058b10be4eca5ab3de9a73e
572,845
from datetime import datetime def convert_date_to_timestamp(date_to_convert): """ This function is useful to convert date (YYYYmmdd) to timestamp Args: date_to_convert (str): date (YYYYmmdd) to be converted in timestamp Returns: (timestamp): date_to_convert converted in timestamp ...
a43add163f3c303246ac92ad043cbff452e7cc6b
572,849
import pickle def obtainCalibrationPointsFromFile(fname="all_writeup/camera_calibrations_pickle1.p"): """ Uses pickle to open/unpack camera calibration values from file. Expects pickle with the two following keys: 'cMatrix' == camera matrix 'dCoeff' == distortion coefficients Assumes f...
38aaf5c3276a13ae36c4cebc9b6f2f8288006f18
572,850
def none_conv(result): """Just in case of a None result, to prevent script crashing""" if result != None: return result else: new_result = 0.0 return new_result
f81d689bca5283cc577567a2ea8ba9aa0109844d
572,851
def alias_setup(probs): """ Compute utility lists for non-uniform sampling from discrete distributions. Refer to https://hips.seas.harvard.edu/blog/2013/03/03/the-alias-method-efficient-sampling-with-many-discrete-outcomes/ for details """ K = len(probs) q = [0 for i in range(K)] # torch.zer...
9fc285f27d6dbe45d1a686858d352269ae7941c7
572,852
import math def rotate(origin, point, angle): """ Rotate point by angle around origin. Parameters ---------- origin : tuple coordinates of origin point : ndarray (size: 2,2) coordinates of point angle : float angle to rotate in radians Returns ------- ...
e9f10eb933aa2928f400db2a0177e4cdfe069a45
572,859
def _corr_dist(mat_corr): """ Compute a distance matrix based on correlation. Parameters ---------- mat_corr: np.ndarray[ndim=2, dtype=float] or pd.DataFrame Matrix correlation. Returns ------- mat_dist_corr: np.ndarray[ndim=2, dtype=float] or pd.DataFrame Matrix distance c...
92ee4abb46da07f1967470714bce6b7551248531
572,861
from inspect import findsource from dis import findlinestarts def get_func_source(obj): """Get object's source code. Returns None when source can't be found. """ try: lines, lnum = findsource(obj) ls = list(findlinestarts(obj.func_code)) lstart = ls[0][1] lend = ls[-1][1] ...
c62b4625b90f6067159e68d432fbbb0ec906a1d4
572,864
def decompress_amount(x): """ Decompresses the Satoshi amount of a UTXO stored in the LevelDB. Code is a port from the Bitcoin Core C++ source: https://github.com/bitcoin/bitcoin/blob/v0.13.2/src/compressor.cpp#L161#L185 :param x: Compressed amount to be decompressed. :type x: int :return: T...
85856d220be484b294622b99433ada47d04ec4e0
572,865
def split_long_message(message: str, limit: int = 2000): """ Splits message string by 2000 characters with safe newline splitting """ split_output: list[str] = [] lines = message.split("\n") temp = "" for line in lines: if len(temp) + len(line) + 1 > limit: split_output....
52932801a6f2ca7cf03e65d1cffd7fc2e7e16cfc
572,867
import math def uniform_crop(images, size, spatial_idx): """ Perform uniform spatial sampling on the images. Args: images (tensor): images to perform uniform crop. The dimension is `num frames` x `channel` x `height` x `width`. size (int): size of height and weight to crop the ...
66e849a8764316d85857f7f8a82658b7cd1c729f
572,868
import torch def yolo_filter_boxes(box_confidence: torch.Tensor, boxes: torch.Tensor, box_class_probs: torch.Tensor, threshold: float=.6): """filter boxes that has score smaller than threshold Parameters ---------- box_confidence : torch.Tensor Object confidence shape [batch_size, num...
e83d463f715998534eab3d17dead206103219a95
572,869
def list_index(list, value): """Return the index in the list that houses the value""" return list.index(value)
45f4dc63016f974e5c0d4627dd726f9601044724
572,870
import re def rm_stress(word_list): """ Takes a list of strings in IPA that contain prosodic accent marks and removes the dashes to clean the data. :word_list: list of strings :returns: list of strings without prosodic accent marks :rtype: list of strings """ new_list = [] for s...
a05b24a552380d5a2af2abe219a89b3496351f42
572,871
def float_from_request(params, key, default): """ Get float from request GET, POST, etc :param params: dict POST, GET, etc :param key: key to find :param default: default value :return: float """ value = params.get(key, default) # str if isinstance(value, str): try: ...
b1fa76220321ab5e225526e4d0ef519e5bbc7e90
572,877
def _rangelen(begin, end): """Returns length of the range specified by begin and end. As this is typically used to calculate the length of a buffer, it always returns a result >= 0. See functions like `_safeDoubleArray` and `safeLongArray`. """ # We allow arguments like begin=0, end=-1 on purp...
8e010b08ef91b5ce011b348832ca1cdb829e519a
572,882
import sqlite3 import logging def get_row_from_vms_table(conn, tenant_uuid): """ Get rows from vms table for a given tenant. Return value: -- error_msg: return None on success or error string -- result: returns rows in vms table with given tenant_uuid on success, return...
82ab70e4cea4e212089a6fd570fb95575755e281
572,887
def parse_cell_value(val): """Parse value from table cell. >>>parse_cell_value("5.4") (5.4, None) >>>parse_cell_value("5 432") (5432.0, None) >>>parse_cell_value("--") (None, "Saknas") :param val (str): cell content :returns (tuple): value and status as tuple """ missing_...
296b267a2134d4f1ec8afad58c7b3a390ea276f3
572,892
def query(field, op, value, type=''): """Assemble a dict representing a query filter. :param field: Field to query :type field: String :param op: Query operator :type op: String :param value: Value to query :type value: String :param type: Type of the value :type type: String :r...
9fa98cbfefc062782e8aa1e89bcaabcac926a49a
572,894
def get_idx_first_conv(model): """Returns the index of the first convolutional layer found """ first_conv_idx = None for layer_idx,layer in enumerate(model.layers): if 'conv' in layer.name: first_conv_idx = layer_idx break return first_conv_idx
27941340a1d5fafc82651058461641ea3ae41ef4
572,895
def query_string_to_dict(request): """Extract the query string from the request and return it as a dict.""" query_string = {} for pair in request.args.items(): query_string.update({pair[0]: pair[1]}) return query_string
ed5720b2860d113d35fda53ada11c20ec9c83db1
572,897
def expand_series(ser, columns): """ Helper function to quickly expand a series to a dataframe with according column axis and every single column being the equal to the given series. """ return ser.to_frame(columns[0]).reindex(columns=columns).ffill(axis=1)
e86956f5a32cb44066361846a0e602d53cfb241b
572,901
def inRange(v1, minVal = 0, maxVal = 1): """ Check if every value in v1 is in the range (minVal, maxVal) """ for v in v1: if v < minVal or v > maxVal: return False return True
c166f7d9aaa94988eb4e245cb41c34b44ace86cf
572,902
def remove_silence(seg): """ Wrapper for audiosegment_object.filter_silence() """ return seg.filter_silence()
8fd3d07fde2435f442d572e341302c2823e09785
572,904
def character_mapping(string_a, string_b): """ Return a boolean of either it is possible to map every unique character from string a to string b with a one to one relation. O(n log n) time O(n) space """ dico_a = {} dico_b = {} for char in string_a: dico_a[char] = dico_a[char]+1 if char in dico_a else 1 fo...
444122ad41af53cce2a8d6646eb3ccbb7397956a
572,905
def respCoords(r, plot=False): """Return coordinates of the response peptide Plot option returns coordinates based on start and length of peptide, as opposed to end coordinate which is subject to indsertions/deletions Use end like a stop in range(start, stop)""" if plot: return list(range(in...
d2f08a4e3f788b03651c92dd6130189368d9108d
572,909
def removeZ(coords): """ Remove Z values from coordinates """ newcoords = coords.copy() for p in newcoords[0]: p.pop(2) return newcoords
1afa31d7fa596ccdd385d6311096f96dd13b160d
572,910