content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import Dict def linear_utility( exchange_params_by_currency_id: Dict[str, float], balance_by_currency_id: Dict[str, int], ) -> float: """ Compute agent's utility given her utility function params and a good bundle. :param exchange_params_by_currency_id: exchange params by currency ...
0d8346d35862a88c117d50919889735e3ef7b626
674,219
def sum_of_square_deviations(data, c): """Return sum of square deviations of sequence data.""" ss = sum((float(x) - c)**2 for x in data) return ss
866376cd9c2426c580f7bd75980e452cff2de588
674,225
def DataArray_to_dictionary(da, include_data=True): """ Convert DataArray to dictionary Args: da (DataArray): data to convert include_data (bool): If True then include the .ndarray field Returns: dict: dictionary containing the serialized data """ fields = ['label', 'name',...
cad39855f269ab8f1c98362fecd9da02633c0ab8
674,227
from torch.utils.data._utils.collate import default_collate from typing import Sequence from typing import Dict def multi_supervision_collate_fn(batch: Sequence[Dict]) -> Dict: """ Custom collate_fn for K2SpeechRecognitionDataset. It merges the items provided by K2SpeechRecognitionDataset into the follow...
3b85c2ca4dcdbbd3b5d902bb2b061562401422ae
674,230
def ebc_to_srm(ebc): """ Convert EBC to SRM Color :param float ebc: EBC Color :return: SRM Color :rtype: float """ return ebc / 1.97
f5a2411f2ee89d979950fe7c7fdcdf5531a4203d
674,232
def _unique_id_to_host_id(unique_id): """Return the chip id unique to the daplink host procesor Unique ID has the following fomat Board ID - 4 bytes Version - 4 bytes Host ID - Everything else """ return unique_id[8:8 + 32]
d59dcbcdfe5a6e14dced44736efab38d9e0419ef
674,234
import ntpath def pathLeaf(path): """ Returns the basename of the file/directory path in an _extremely_ robust way. For example, pathLeaf('/hame/saheel/git_repos/szz/abc.c/') will return 'abc.c'. Args ---- path: string Path to some file or directory in the system Returns...
f0d28f160dd9e32e6d2e99106bff870ca5995f52
674,236
import copy def convertUnits(ww_params, pixel_size): """ Convert to the units currently used by the analysis pipeline. This also adds additional zeros as needed to match the length expected by the analysis pipeline. """ ww_params = copy.copy(ww_params) ww_params[0] = ww_params[0] * pi...
cb32938ccacee6b76dbacbb1c4bd76e4f13b1cef
674,241
import random def generate_smallest_secret(poly_degree, crc_length, min_size=0, echo=False): """ Helper function to generate smallest secret which is: - divisible by 8, so that it can be encoded to bytes - secret length + crc_length is divisible by poly_degree + 1 to be able to split s...
5bfba7e9a13150175e681eda91799e2c08e144a9
674,244
def force_key(d, k): """Return a key from a dict if existing and not None, else an empty string """ return d[k] if d.has_key(k) and d[k] is not None else ""
1b7b5d74a56347685412cfe4d334f3dd787c268b
674,246
def foundSolution(solver_result): """ Check if a solution was found. """ return "Valid" not in solver_result and "unsat" not in solver_result
61e82ecd4f346b9536553bef114376f67f5d71f8
674,247
import torch def one_hotify(vec, number_of_classes, dimension): """ Turn a tensor of integers into a matrix of one-hot vectors. :param vec: The vector to be converted. :param number_of_classes: How many possible classes the one hot vectors encode. :param dimension: Which dimension stores the ...
583ce1ed52d99b4c428d2f8b5ab03b2987d13ee7
674,252
def get_fuels(collection, country): """ Accumulate capacities for each fuel type for a given country """ result = collection.aggregate([ { # Search country '$search': { 'index': 'default', 'text': { 'query': country, 'path': 'coun...
fab8b976663ead606a8c1200c1309de88e2b5878
674,256
def extract_category(report, key): """ Create a dict from a classification report for a given category. Args: report: The report key: The key to a category on the report """ result = report.get(key) result['category'] = key return result
14a3e54a50065bd49a1d7d9941f7cb8918e48ffe
674,257
def get_int_from_little_endian_bytearray(array, offset): """ Get an int from a byte array, using little-endian representation,\ starting at the given offset :param array: The byte array to get the int from :type array: bytearray :param offset: The offset at which to start looking :type offs...
1c87a6f36642b92ac084d0a269003ed4250312a5
674,258
def simple_dist(x1: float, x2: float) -> float: """Get distance between two samples for dtw distance. Parameters ---------- x1: first value x2: second value Returns ------- float: distance between x1 and x2 """ return abs(x1 - x2)
dea3188f7589bda30092ecec8b19ba02a47d5e58
674,264
def fitness_bc(agent, environment, raw_fitness, path): """ Returns as a tuple the raw fitness and raw observation of an agent evaluation. """ if len(path) > 0: return raw_fitness, path return raw_fitness, [0]
c08df3a6c27b5c5c2550e3c346a50779eaba67ef
674,268
def accuracy(y_pred, y_truth): """ Accuracy: #right / #all Parameters ------------- y_pred : numpy array, (m, 1) the predicted labels y_truth : numpy array, (m, 1) the true labels Returns -------- accuracy : double larger is better """ re...
f2971aa477f467020220f75a7a36e541ef4571c2
674,269
def train_test_split(t, df): """ Splits time series dataset into train, validation and test set with a 60-20-20 split. Targeted to be used in an apply function to a Series object. :param t: current timestep (int) :param df: pandas Dataframe containing the data :returns: subset categorization as ...
8d79cbf86586893519c85939cfa0c2cdb132b250
674,270
import traceback def cut_traceback(tb, func_name): """ Cut off a traceback at the function with the given name. The func_name's frame is excluded. Args: tb: traceback object, as returned by sys.exc_info()[2] func_name: function name Returns: Reduced traceback. """ ...
c7e5558eebf75b24bda1ddb49563220f8c497bce
674,271
def crop_2d_using_xy_boundaries(mask, boundaries): """ :mask: any 2D dataset :boundaries: dict{xmin,xmax,ymin,ymax} :return: cropped mask """ b = boundaries return mask[b['ymin']:b['ymax'], b['xmin']:b['xmax']]
1212a1a2a0441cc0542c5271bf5aedc65c0fbc7d
674,273
def get_unit(a): """Extract the time unit from array's dtype""" typestr = a.dtype.str i = typestr.find('[') if i == -1: raise TypeError("Expected a datetime64 array, not %s", a.dtype) return typestr[i + 1: -1]
22f132af5ab751afdb75c60689086874fa3dfd99
674,274
def find_dimension_contexts(instance,context,dimensions): """Returns a list of contexts containing the given dimension values and having the same period as the given context.""" contexts = [] for dimcontext in instance.contexts: if dimcontext.period_aspect_value == context.period_aspect_value and di...
fee072ebccdeb68a3f7bf13158c5c39ce8aa8ca9
674,275
def atoms_to_xyz_file(atoms, filename, title_line='', append=False): """ Print a standard .xyz file from a list of atoms Arguments: atoms (list(autode.atoms.Atom)): List of autode atoms to print filename (str): Name of the file (with .xyz extension) Keyword Arguments: title_lin...
de1fab407935c7b1b95471ee61cebbbb59f25419
674,276
from typing import List from typing import Dict import torch def prepare_batch(batch: List) -> Dict[str, torch.Tensor]: """ Take a list of samples from a Dataset and collate them into a batch. Returns: A dictionary of tensors """ input_ids = torch.stack([example['input_ids'] for example in...
eece79f3eb1c99c04876679247796c2286f8dd6e
674,277
def variants(*strings): """Creates three variants of each string: - lowercase (e.g. `husky`) - title version (e.g. `Husky`) - uppercase (e.g. `HUSKY`) :return: A list of all variants of all given strings. :rtype: list """ result = [] for string in strings: lowercase = strin...
a4c1af7ecdba9642c95cef8ac8a5516d703c1ad7
674,278
def get_start_end(title, print_char="-", size=150, nl_str=True, nl_end=True): """ :return: start: ------------------------------- <title> ------------------------------- end: ----------------------------------------------------------------------- """ title_len = len(title) print_ch...
abe8f063153069b32cd6503fac287c421d6f0c53
674,279
def has_text(text): """ Return False if the text is empty or has only spaces. A true value is returned otherwise. """ # This is faster than "not text.rstrip()" because no new string is # built. return text and not text.isspace()
c0b4ef15b2979f21aff835fbb6a2168cc3d72521
674,282
import torch def jacobian(f, x): """Computes the Jacobian of f w.r.t x. This is according to the reverse mode autodiff rule, sum_i v^b_i dy^b_i / dx^b_j = sum_i x^b_j R_ji v^b_i, where: - b is the batch index from 0 to B - 1 - i, j are the vector indices from 0 to N-1 - v^b_i is a "test...
913053f45b25d6f88d95cf26a757e7b4ba586089
674,283
from typing import List def mimes_to_codec(mimes: List[str]) -> str: """Utility function for turning mutagen's mime types into a single codec string.""" if any(["codecs=opus" in m for m in mimes]): return "opus" else: return mimes[0].replace("audio/", "")
7f902dface33111bca108304f902223fea61a095
674,284
import re def split_source_id(source_id): """Retrieve the source_name and version information from a source_id. Not complex logic, but easier to have in one location. Standard form: {source_name}_v{search_version}.{submission_version} Arguments: source_id (str): The source_id to split. If this is...
731d3c4733471cd3293de05d3b3f97a62916b245
674,288
def pruneListByIndices(lst, indices): """Prunes a `lst` to only keep elements at the given `indices`.""" return [l for i, l in enumerate(lst) if i in indices]
9cc59c1f05775557a973f7ac4f0fccd3004af235
674,289
def get_machine_type(cpu_cores, memory, accelerator_type): """Returns the GCP AI Platform machine type.""" if accelerator_type.value == "TPU_V2" or accelerator_type.value == "TPU_V3": return "cloud_tpu" machine_type_map = { (4, 15): "n1-standard-4", (8, 30): "n1-standard-8", ...
426116d4b8742a110e2716415ceb7ae171068114
674,291
import torch def unk_init(dim): """ Initialize out of vocabulary words as uniform distribution in range 0 to 1. :param dim: word embedding dimension :return: randomly initialized vector """ return torch.rand(1, dim)
9e887107a96ad9a22329a4f8b57db5f324e3da82
674,294
def convert_txt_to_inds(txt, char2ind, eos=False, sos=False): """ Args: txt: Array of chars to convert to inds. char2ind: Lookup dict from chars to inds. Returns: The converted chars, i.e. array of ints. """ txt_to_inds = [char2ind[ch] for ch in txt] if eos: txt_to_ind...
48e3364e3af18d7a2a3b1820fd9c474920652269
674,296
def pairwise_prefs(A,P,params,distance_bound=1): """ Return a dict pref that gives for each pair (i,j) of alternatives from A the sum, over voters that prefer i to j, of how many positions higher i is than j in the voter's ballot (but not more than "distance_bound" per ballot). If params["missing_pr...
e28174539029397565434f4fb1ba667b5351a178
674,303
def common_parent(a, b): """ Find the common parent tile of both a and b. The common parent is the tile at the highest zoom which both a and b can be transformed into by lowering their zoom levels. """ if a.zoom < b.zoom: b = b.zoomTo(a.zoom).container() elif a.zoom > b.zoom: ...
d3c8fdce19f19e431d3b4e894314e56dc9a45396
674,304
import calendar import random def random_day(month): """Return a random int within the range of the month provided.""" dayRange = calendar.monthrange(2020, month)[1] return random.randint(1, dayRange)
402f9b6900a06fe11a35e8cf118efd7ebc0de855
674,305
def divide(dataset, target_column): """ Divides the dataset in X and y. This function is called inside prepare_data function (see below) in order to prepare data. :param dataset: :param target_column: :return: X and y """ X = dataset.drop(columns=[target_column]) y = dataset[target_...
ba12b8e4c037f6181b3b2fa4f0201a3e15be4abd
674,316
def extract_post_story(div_id_story): """ Extracts the post text contents, strips line breaks and whitespaces. """ before_keyword = "SHARE /" post_story = div_id_story.get_text().strip().replace('\n', ' ').replace('\r', '') return post_story[:post_story.find(before_keyword)]
995347c56165f4fb701ab18499ef05bf2744e1b1
674,317
def mean(x): """Return the mean of an array across the first dimension.""" return x.mean(axis=0)
c45f1fc16e71e5284eb47369ccc0603321a927ce
674,318
from typing import List from typing import Set def _extract_target_labels(targets_in_order: List[dict], target_name: str) -> Set[str]: """Collect a set of all the board names from the inherits field in each target in the hierarchy. Args: targets_in_order: list of targets in order of inheritance, star...
f47dcd90427efd70b0ac965ea017852db68381e4
674,322
def svm_predict(classifier, test_data): """ Predict the labels of the given test data with the given classifier pipeline. :param sklearn.pipeline.Pipeline classifier: The classifier pipeline with which the labels of the given test data should be predicted :param pandas.core.series.Series test_data:...
61b21073bce9ef1bff931b558331a591a780e409
674,323
def PLR_analysis(PLR): """ Analysis PLR(Positive likelihood ratio) with interpretation table. :param PLR: positive likelihood ratio :type PLR : float :return: interpretation result as str """ try: if PLR == "None": return "None" if PLR < 1: return "N...
0742a315cc8bbe6d8fcc05ac875e9469cd850b51
674,325
def contfractbeta( a: float, b: float, x: float, ITMAX: int = 5000, EPS: float = 1.0e-7 ) -> float: """Continued fraction form of the incomplete Beta function. Code translated from: Numerical Recipes in C. Example kindly taken from blog: https://malishoaib.wordpress.com/2014/04/15/the-beautiful-be...
cfe30b64ae14717dc007866a8d3634a5ce1e1042
674,326
def readMetadata(lines): """ Read metadata tags and values from a TNTP file, returning a dictionary whose keys are the tags (strings between the <> characters) and corresponding values. The last metadata line (reading <END OF METADATA>) is stored with a value giving the line number this tag was found in....
e4a93539ccb203b350d17c33fd0daa4cb9afbac9
674,327
def extracthypos(synset, limit=999): """Given a synset object, return a set with all synsets underneath it in the PWN structure (including the original).""" l = limit-1 result = [] result.append(synset) if synset.hyponyms() and l > 0: for each in synset.hyponyms(): x = extra...
e1696a937891eb1ae8a39e683bf71c18124c2984
674,329
def decimal_to_percent(value, decimal_place=2): """ Format a decimal to percentage with two decimal :param value: the value to be formatted :param decimal_place default decimal place, default to 2 :return: a string in percentage format, 20.50% etc """ format_str = '{:.' + str(2) + '%}' r...
c2d777d608458151b3b9752897305dab79498778
674,330
def sec2hms(seconds): """ Convert seconds into a string with hours, minutes and seconds. Parameters: * seconds : float Time in seconds Returns: * time : str String in the format ``'%dh %dm %2.5fs'`` Example:: >>> print sec2hms(62.2) 0h 1m 2.20000s ...
6dea7e13567660c2c4dd8f2d0d0ef78f2a4e994c
674,331
def get_HTML(file): """ Retrieves the source code from a specified saved html file args: file: The Specified html to retrieve the source code from """ f = open(file, 'r') lines = f.readlines() f.close() return "".join(lines)
0b0f555b840715bd19804047793a2f6c168e3da5
674,334
import fsspec def map_tgt(tgt, connection_string): """Uses fsspec to creating mapped object from target connection string""" tgt_map = fsspec.get_mapper(tgt, connection_string=connection_string) return tgt_map
a5b4a8bb39ea69b3f9340c06266e0fa8a9b42dee
674,336
import torch def compute_brier_score(y_pred, y_true): """Brier score implementation follows https://papers.nips.cc/paper/7219-simple-and-scalable-predictive-uncertainty-estimation-using-deep-ensembles.pdf. The lower the Brier score is for a set of predictions, the better the predictions are calibrated.""...
0cafeccc2422499cce6aeb148a407a29f4fdd0f8
674,337
def color_blend(a, b): """ Performs a Screen blend on RGB color tuples, a and b """ return (255 - (((255 - a[0]) * (255 - b[0])) >> 8), 255 - (((255 - a[1]) * (255 - b[1])) >> 8), 255 - (((255 - a[2]) * (255 - b[2])) >> 8))
dbfed8d7697736879aab6ffa107d7f4f7927be4b
674,344
import colorsys def ncolors(levels): """Generate len(levels) colors with darker-to-lighter variants for each color Args: levels(list): List with one element per required color. Element indicates number of variants for that color Returns: List of lists with variants for ea...
1eb9c569c1548eb349bfe3d6d35cbb8e5b71b8fb
674,347
def compileStatus(lOutput, iWarning, iCritical, sFilesystem): """ compiles OK/WARNING/CRITICAL/UNKNOWN status gets: lOutput : list of dicts for each Disk iWarning : warning threshold iCritical : critical threshold sFilesystem: filesystem which to compare iWarning and iCritical agains...
db3e64785b447833167de2fa83cc67505b7adfbe
674,351
def get_entities_filter(search_entities): """Forms filter dictionary for search_entities Args: search_entities (string): entities in search text Returns: dict: ES filter query """ return { "nested": { "path": "data.entities", "filter":{ "bool":{ "should": [ { "terms":...
406f92124c95219a5c4c5e698bffe0e8f2f2a83e
674,357
import math def rect(r, theta): """ theta in degrees returns tuple; (float, float); (x,y) """ x = r * math.cos(math.radians(theta)) y = r * math.sin(math.radians(theta)) return x, y
cc3b1384be3c24b4a515a3c5c61cc5167bc3f6c1
674,362
def task_update() -> dict: """Update existing message catalogs from a *.pot file.""" return { "actions": [ "pybabel update -D shooter -i shooter/po/shooter.pot -d shooter/locale -l en", "pybabel update -D shooter -i shooter/po/shooter.pot -d shooter/locale -l ru", ], ...
b430472f4fd837c17866c52a91b1e16564cafd2e
674,365
def _json_force_object(v): """Force a non-dictionary object to be a JSON dict object""" if not isinstance(v, dict): v = {'payload': v} return v
bf6f86c92b05e0859723296b3cc58cd32863637c
674,372
def erbs2hz(erbs): """ Convert values in Equivalent rectangle bandwidth (ERBs) to values in Hertz (Hz) Parameters from [1] Args: erbs (float): real number in ERBs Returns: hz (float): real number in Hertz References: [1] Camacho, A., & Harris, J. G. (2008). A sawt...
9919ecdf4979e1dc28d2de2c87ff8246ec106fb2
674,378
def split_df_by_regions(df): """ Split the dataframe based on TotalUS, regions and sub-regions """ df_US = df[df.region == 'TotalUS'] regions = ['West', 'Midsouth', 'Northeast', 'SouthCentral', 'Southeast'] df_regions = df[df.region.apply(lambda x: x in regions and x != 'TotalUS')] df_subreg...
7a74315a8e5bf9dba8e156df4d8bf0e370b6be0c
674,382
def is_week_day(the_date): """ Decides if the given date is a weekday. Args: the_date: Date object. The date to decide. Returns: Boolean. Whether the given date is a weekday. """ return the_date.isoweekday() in [1, 2, 3, 4, 5]
ddc3f7735062beb0b7cd4509a317dcc8d3acc439
674,387
def path_in_book(path): """ A filter function that checks if a given path is part of the book. """ if ".ipynb_checkpoints" in str(path): return False if "README.md" in str(path): return False return True
ba2be7b47ce6ad6581d26411149db3b0cd3b1e3d
674,388
from typing import List import posixpath def format_path(base: str, components: List[str]) -> str: """ Formats a base and http components with the HTTP protocol and the expected port. """ url = "http://{}:8000/".format(base) for component in components: url = posixpath.join(url, component...
7b55147db9dbdf0f87cd428a319c5cd3aa7276fe
674,392
def FV(pv:float, r:float, n:float, m = 1): """ FV(): A function to calculate Future Value. :param pv: Present Value :type pv: float :param r: Rate of Interest/Discount Rate (in decimals eg: 0.05 for 5%) :type r: float :param n: Number of Years :type n: float :param m: Frequency of Interest Calculatio...
ae0ad0fc37edd19983dc0ab44f1e238bc763084c
674,394
def __equivalent_lists(list1, list2): """Return True if list1 and list2 contain the same items.""" if len(list1) != len(list2): return False for item in list1: if item not in list2: return False for item in list2: if item not in list1: return False ...
f9ef5b643ed0ba4b6bddd3a6394af9a22ed118ee
674,396
from typing import List import math def check_root(string: str) -> str: """ A function which takes numbers separated by commas in string format and returns the number which is a perfect square and the square root of that number. If string contains other characters than number or it has more o...
fb31b1cf3b9dc83d1cafec22dde273b16f9cc218
674,397
def get_dictvalue_from_xpath(full_dict, path_string): """ get a value in a dict given a path's string """ key_value = full_dict for i in path_string.split('/')[1:] : key_value = key_value[i] return key_value
fd3b0a38cc346eba2bcdb3355bc039a2a6fb82da
674,398
import re def extract_nterm_mods(seq): """ Extract nterminal mods, e.g. acA. Args: seq: str, peptide sequence Returns: ar-like, list of modifications """ # matches all nterminal mods, e.g. glD or acA nterm_pattern = re.compile(r'^([a-z]+)([A-Z])') mods = [] # test...
956215c420e78215206e207c1b1fe3dae1cd8eb8
674,400
def cubic_bezier(p0, p1, p2, p3, t): """ evaluate cubic bezier curve from p0 to p3 at fraction t for control points p1 and p2 """ return p0 * (1 - t)**3 + 3 * p1 * t*(1 - t)**2 + 3 * p2 * t**2*(1 - t) + p3 * t**3
ab308bc593e4674a8b3d4c2779c936286bf28f99
674,401
def filter_results(results, filters, exact_match) -> list[dict]: """ Returns a list of results that match the given filter criteria. When exact_match = true, we only include results that exactly match the filters (ie. the filters are an exact subset of the result). When exact-match = false, we ...
7120c4239ba830a4624bebc033389158e17e4d30
674,405
def fact(n): """Finding factorial iteratively""" if n == 1 or n == 0: return 1 result = 1 for i in range(n, 1, -1): result = result * i return result
0ecbf67c679266c3b8d61f96bb84df48b7b0cbfe
674,410
def SignDotNetManifest(env, target, unsigned_manifest): """Signs a .NET manifest. Args: env: The environment. target: Name of signed manifest. unsigned_manifest: Unsigned manifest. Returns: Output node list from env.Command(). """ sign_manifest_cmd = ('@mage -Sign $SOURCE -ToFile $TARGET -Ti...
44cc1e8be57fc1f1bac32885cdb852edc392574d
674,411
def calc_gene_lens(coords, prefix=False): """Calculate gene lengths by start and end coordinates. Parameters ---------- coords : dict Gene coordinates table. prefix : bool Prefix gene IDs with nucleotide IDs. Returns ------- dict of dict Mapping of genes to leng...
7eb54195f05d22c0240ef412fd69b93e1d46e140
674,413
import torch def int_to_one_hot(class_labels, nb_classes, device, soft_target=1.): """ Convert tensor containing a batch of class indexes (int) to a tensor containing one hot vectors.""" one_hot_tensor = torch.zeros((class_labels.shape[0], nb_classes), device=device) f...
ef0360cd41e34b78b158e015a02d3d8490069e51
674,417
def read_file(path: str) -> str: # pragma: nocover """ This function simply reads contents of the file. It's moved out to a function purely to simplify testing process. Args: path: File to read. Returns: content(str): Content of given file. """ return open(path).read()
743db60ee698baa67166c21dc514e93ccb0de912
674,419
def text_to_list(element, delimiter='|'): """ Receives a text and a delimiter Return a list of elements by the delimiter """ return element.split(delimiter)
3638da81e7c952e8821bd843498e19b877c1d9aa
674,421
def living_expenses(after_tax_income): """ Returns the yearly living expenses, which is 5% of the after tax income. :param after_tax_income: The yearly income after income tax. :return: The living expenses. """ return after_tax_income * 0.05
a2c5b7c306cf8db8f11fc5f88282fd62e675c9ab
674,422
def comma_separated(xs): """Convert each value in the sequence xs to a string, and separate them with commas. >>> comma_separated(['spam', 5, False]) 'spam, 5, False' >>> comma_separated([5]) '5' >>> comma_separated([]) '' """ return ', '.join([str(x) for x in xs])
da46d93d9f1b545f1d592da3ba51698e4ae96d5f
674,424
def dummy_category(create_category): """Create a mocked dummy category.""" return create_category(title='dummy')
02846f429da808394af2aebbb1cb07a8d008956c
674,425
def is_list_like(arg): """Returns True if object is list-like, False otherwise""" return (hasattr(arg, '__iter__') and not isinstance(arg, str))
9897b3859fa618c74c548b1d8ffa94796bbe2b5d
674,426
from typing import Dict from typing import List def extract_tracks(plist: Dict) -> List[Dict[str, str]]: """Takes a Dict loaded from plistlib and extracts the in-order tracks. :param plist: the xml plist parsed into a Dict. :returns: a list of the extracted track records. """ try: ...
dc596d084909a68c0f7070d05db8a79585898993
674,431
import inspect def _source(obj): """ Returns the source code of the Python object `obj` as a list of lines. This tries to extract the source from the special `__wrapped__` attribute if it exists. Otherwise, it falls back to `inspect.getsourcelines`. If neither works, then the empty list is re...
0faf18c32fa03ef3ac39b8e163b8e2ea028e1191
674,432
def _CheckForUseOfWrongClock(input_api, output_api): """Make sure new lines of media code don't use a clock susceptible to skew.""" def FilterFile(affected_file): """Return true if the file could contain code referencing base::Time.""" return affected_file.LocalPath().endswith( ('.h', '.cc', '.cpp'...
73d85dd534a59f5aa650e9d8586a01c6b958a195
674,433
import csv def precip_table_etl_cnrccep( ws_precip, rainfall_adjustment=1 ): """ Extract, Transform, and Load data from a Cornell Northeast Regional Climate Center Extreme Precipitation estimates csv into an array Output: 1D array containing 24-hour duration estimate for frequencies 1...
ed1fef33ad36b0a5c1405242ef491b327e5d5911
674,437
def find_9(s): """Return -1 if '9' not found else its location at position >= 0""" return s.split('.')[1].find('9')
63c9fca569f50adcf5b41c03ab4146ce5c0bdd54
674,438
def normalize_cov_type(cov_type): """ Normalize the cov_type string to a canonical version Parameters ---------- cov_type : str Returns ------- normalized_cov_type : str """ if cov_type == 'nw-panel': cov_type = 'hac-panel' if cov_type == 'nw-groupsum': cov_...
1ba4d7c750964382525c50ef84e4c262f226e70a
674,440
import json def parse_payload(payload): """Returns a dict of command data""" return json.loads(payload.get('data').decode())
6db1d1681635edd9729a4686cfc4db107307dc8d
674,443
from typing import List def uniform_knot_vector(count: int, order: int, normalize=False) -> List[float]: """ Returns an uniform knot vector for a B-spline of `order` and `count` control points. `order` = degree + 1 Args: count: count of control points order: spline order norm...
5b8369e0164d8a75d39ee014064a0266d4e55e93
674,445
def process_mmdet_results(mmdet_results, cat_id=1): """Process mmdet results, and return a list of bboxes. :param mmdet_results: :param cat_id: category id (default: 1 for human) :return: a list of detected bounding boxes """ if isinstance(mmdet_results, tuple): det_results = mmdet_resu...
ec04ee586276dce6ff9d68439107adde8ac2ba5b
674,448
def get_top_header(table, field_idx): """ Return top header by field header index. :param table: Rendered table (dict) :param field_idx: Field header index (int) :return: dict or None """ tc = 0 for th in table['top_header']: tc += th['colspan'] if tc > field_idx: ...
58e8c21b0cabc31f7a8d0a55b413c2c00c96929b
674,449
def incident_related_resource_data_to_xsoar_format(resource_data, incident_id): """ Convert the incident relation from the raw to XSOAR format. :param resource_data: (dict) The related resource raw data. :param incident_id: The incident id. """ properties = resource_data.get('properties', {}) ...
4154540b6a4566775d372713dea6b08295df453a
674,456
import torch def is_gpu_available() -> bool: """Check if GPU is available Returns: bool: True if GPU is available, False otherwise """ return torch.cuda.is_available()
a56cdd29dfb5089cc0fc8c3033ba1f464820778a
674,458
def find_ingredients_graph_leaves(product): """ Recursive function to search the ingredients graph and find its leaves. Args: product (dict): Dict corresponding to a product or a compound ingredient. Returns: list: List containing the ingredients graph leaves. """ if 'ingredie...
40bebe2a8ec73d492f0312a350a324e9b54a849c
674,460
def getPathName(path): """Get the name of the final entity in C{path}. @param path: A fully-qualified C{unicode} path. @return: The C{unicode} name of the final element in the path. """ unpackedPath = path.rsplit(u'/', 1) return path if len(unpackedPath) == 1 else unpackedPath[1]
6c5559c1f8b6667f7b592798b3c67bec0f7b0874
674,462
import pipes def shell_join(command): """Return a valid shell string from a given command list. >>> shell_join(['echo', 'Hello, World!']) "echo 'Hello, World!'" """ return ' '.join([pipes.quote(x) for x in command])
67252a291c0b03858f41bbbde61ff4cd811895b6
674,466
def gen_fasta2phy_cmd(fasta_file, phylip_file): """ Returns a "fasta2phy" command <list> Input: fasta_file <str> -- path to fasta file phylip_file <str> -- path to output phylip file """ return ['fasta2phy', '-i', fasta_file, '-o', phylip_file]
90136ca5c60a9ca6990f7e66eae2bfe452310c86
674,468
import re def strip_multi_value_operators(string): """The Search API will parse a query like `PYTHON OR` as an incomplete multi-value query, and raise an error as it expects a second argument in this query language format. To avoid this we strip the `AND` / `OR` operators tokens from the end of query ...
582c8ba2da345bdb7e9eb5b092fdbb1b5e5f656e
674,475
def get_nodes(database): """Get all connected nodes as a list of objects with node_id and node_label as elements""" results = list(database["nodes"].find()) nodes = [] for node in results: nodes.append({"id": node["_id"], "description": node["label"]}) return nodes
5033e2500921e4f40d8f0c35d9394b1b06998895
674,483
import re def extract_code(text): """ Extracts the python code from the message Return value: (success, code) success: True if the code was found, False otherwise code: the code if success is True, None otherwise """ regex = r"(?s)```(python)?(\n)?(.*?)```" match = re.search(rege...
a912c90973f1d5ebbc356f4a9310a45757928d63
674,485