content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def check_for_solve(grid): """ checks if grid is full / filled""" for x in range(9): for y in range(9): if grid[x][y] == 0: return False return True
5fc4a8e7a2efaa016065fc0736aa5bdb7d4c92f8
6,299
import copy def _normalize_annotation(annotation, tag_index): """ Normalize the annotation anchorStart and anchorEnd, in the sense that we start to count the position from the beginning of the sentence and not from the beginning of the disambiguated page. :param annotation: Annotation object :param tag_index: start index (int) :return: a new Annotation object """ # norm_annotation = copy.deepcopy(annotation) norm_annotation = annotation norm_annotation.anchorStart = int(annotation.anchorStart) - tag_index norm_annotation.anchorEnd = int(annotation.anchorEnd) - tag_index return copy.copy(norm_annotation)
a7da5810711ada97a2ddcc308be244233fe813be
6,301
import click def parse_rangelist(rli): """Parse a range list into a list of integers""" try: mylist = [] for nidrange in rli.split(","): startstr, sep, endstr = nidrange.partition("-") start = int(startstr, 0) if sep: end = int(endstr, 0) if end < start: mylist.extend(range(start, end - 1, -1)) else: mylist.extend(range(start, end + 1)) else: mylist.append(start) except ValueError: # pylint: disable=raise-missing-from raise click.ClickException("Invalid range list %s" % rli) return mylist
321496a1170b81d02b8378d687d8ce6d6295bff6
6,303
import os def intersect_by_tf(emotion_dict): """ Takes multiple emotion word lists and intersects them by their term frequency, leading to the emotional difference between sets of any size. Args: emotion_dict: dict of summed up emotional scores based on the tf scores of the underlying words Returns: tf_intersection_dict: The comparison of each two sets in a dict. Of the keys: Second element is subtracted by the first one. """ key_list = [*emotion_dict] tf_intersection_dict = {} for i in range(len(key_list)): for j in range(i + 1, len(key_list)): both_docs = "intersect: " + os.path.basename(os.path.normpath(key_list[i])) + " and " \ + os.path.basename(os.path.normpath(key_list[j])) tf_intersection_dict[both_docs] = \ {k: emotion_dict[key_list[i]][k] - emotion_dict[key_list[j]][k] for k in emotion_dict[key_list[i]]} return tf_intersection_dict
f46a02b736a76bd3adcc1efaf7638452241567ce
6,304
def transcript_segments(location_descriptors, gene_descriptors): """Provide possible transcript_segment input.""" return [ { "transcript": "refseq:NM_152263.3", "exon_start": 1, "exon_start_offset": -9, "exon_end": 8, "exon_end_offset": 7, "gene_descriptor": gene_descriptors[0], "component_genomic_start": location_descriptors[2], "component_genomic_end": location_descriptors[3] }, { "component_type": "transcript_segment", "transcript": "refseq:NM_034348.3", "exon_start": 1, "exon_end": 8, "gene_descriptor": gene_descriptors[3], "component_genomic_start": location_descriptors[0], "component_genomic_end": location_descriptors[1] }, { "component_type": "transcript_segment", "transcript": "refseq:NM_938439.4", "exon_start": 7, "exon_end": 14, "exon_end_offset": -5, "gene_descriptor": gene_descriptors[4], "component_genomic_start": location_descriptors[0], "component_genomic_end": location_descriptors[1] }, { "component_type": "transcript_segment", "transcript": "refseq:NM_938439.4", "exon_start": 7, "gene_descriptor": gene_descriptors[4], "component_genomic_start": location_descriptors[0] } ]
3ca9041ff278dcd19432b6d314b9c01de6be1983
6,305
def encode_label(text): """Encode text escapes for the static control and button labels The ampersand (&) needs to be encoded as && for wx.StaticText and wx.Button in order to keep it from signifying an accelerator. """ return text.replace("&", "&&")
b4402604f87f19dab9dbda4273798374ee1a38d8
6,306
from warnings import filterwarnings def calcRSI(df): """ Calculates RSI indicator Read about RSI: https://www.investopedia.com/terms/r/rsi.asp Args: df : pandas.DataFrame() dataframe of historical ticker data Returns: pandas.DataFrame() dataframe of calculated RSI indicators + original data """ filterwarnings("ignore") df["price_change"] = df["adjclose"].pct_change() df["Upmove"] = df["price_change"].apply(lambda x: x if x > 0 else 0) df["Downmove"] = df["price_change"].apply(lambda x: abs(x) if x < 0 else 0) df["avg_Up"] = df["Upmove"].ewm(span=19).mean() df["avg_Down"] = df["Downmove"].ewm(span=19).mean() df = df.dropna() df["RS"] = df["avg_Up"] / df["avg_Down"] df["RSI"] = df["RS"].apply(lambda x: 100 - (100 / (x + 1))) return df
4c2c76159473bf8b23e24cb02af00841977c7cd3
6,307
import struct def add_header(input_array, codec, length, param): """Add the header to the appropriate array. :param the encoded array to add the header to :param the codec being used :param the length of the decoded array :param the parameter to add to the header :return the prepended encoded byte array""" return struct.pack(">i", codec) + struct.pack(">i", length) + struct.pack(">i", param) + input_array
228db86bb6eb9e3c7cc59cc48b67e443d46cc36d
6,308
def _get_positional_body(*args, **kwargs): """Verify args and kwargs are valid, and then return the positional body, if users passed it in.""" if len(args) > 1: raise TypeError("There can only be one positional argument, which is the POST body of this request.") if "options" in kwargs: raise TypeError("The 'options' parameter is positional only.") return args[0] if args else None
c777296ab9c0e95d0f4d7f88dfd4ae292bfc558f
6,309
def question_input (user_decision=None): """Obtains input from user on whether they want to scan barcodes or not. Parameters ---------- user_decision: default is None, if passed in, will not ask user for input. string type. Returns ------- True if user input was 'yes' False is user input was anything else """ # Ask user if they would like to scan a barcode, and obtain their input if user_decision == None: decision = input("Would you like to scan a barcode? Type 'yes' to begin. ") else: decision = user_decision # Return boolean value based on user response if decision == 'yes': return True else: return False
afb7f3d4eef0795ad8c4ff7878e1469e07ec1875
6,310
def depth(d): """Check dictionary depth""" if isinstance(d, dict): return 1 + (max(map(depth, d.values())) if d else 0) return 0
6fd72b255a5fba193612cfa249bf4d242b315be1
6,311
import logging def validate_analysis_possible(f): """ Decorator that validates that the amount of information is sufficient for attractor analysis. :param f: function :return: decorated function """ def f_decorated(*args, **kwargs): db_conn, *_ = args if db_conn.root.n_aggregated_attractors() == 1 or \ db_conn.root.total_frequency() <= 2: logging.getLogger().info('Not enough attractors to infer node correlations.') return None else: return f(*args, **kwargs) return f_decorated
9de0cbf2e18e47d14912ae3ebdff526a73f2c25d
6,312
def remove_whitespace(sentences): """ Clear out spaces and newlines from the list of list of strings. Arguments: ---------- sentences : list<list<str>> Returns: -------- list<list<str>> : same strings as input, without spaces or newlines. """ return [[w.rstrip() for w in sent] for sent in sentences]
ed50124aec20feba037ea775490ede14457d6943
6,313
def mongo_stat(server, args_array, **kwargs): """Method: mongo_stat Description: Function stub holder for mongo_perf.mongo_stat. Arguments: (input) server (input) args_array (input) **kwargs class_cfg """ status = True if server and args_array and kwargs.get("class_cfg", True): status = True return status
45ae8fd66a1d0cae976959644837fae585d68e65
6,314
import pkg_resources def get_pkg_license(pkgname): """ Given a package reference (as from requirements.txt), return license listed in package metadata. NOTE: This function does no error checking and is for demonstration purposes only. """ pkgs = pkg_resources.require(pkgname) pkg = pkgs[0] for line in pkg.get_metadata_lines('PKG-INFO'): (k, v) = line.split(': ', 1) if k == "License": return v return None
238f2b3d33de6bf8ebfcca8f61609a58357e6da1
6,315
import traceback def get_err_str(exception, message, trace=True): """Return an error string containing a message and exception details. Args: exception (obj): the exception object caught. message (str): the base error message. trace (bool): whether the traceback is included (default=True). """ if trace: trace_str = "".join(traceback.format_tb(exception.__traceback__)).strip() err_str = "{}\nTYPE: {}\nDETAILS: {}\nTRACEBACK:\n\n{}\n" \ "".format(message, type(exception), exception, trace_str) else: err_str = "{}\nTYPE: {}\nDETAILS: {}\n".format(message, type(exception), exception) return err_str
0ede3de80fb1097b0537f90337cf11ffa1edecf7
6,316
def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
685ff34e14c26fcc408e5d4f9219483118bfd3c0
6,317
import platform import pickle def load_pickle(f): """使用pickle加载文件""" version = platform.python_version_tuple() # 取python版本号 if version[0] == '2': return pickle.load(f) # pickle.load, 反序列化为python的数据类型 elif version[0] == '3': return pickle.load(f, encoding='latin1') raise ValueError("invalid python version: {}".format(version))
33db0ba6dbd8b1d2b3eba57e63d4069d91fbcb0b
6,318
from typing import Any def check_int(data: Any) -> int: """Check if data is `int` and return it.""" if not isinstance(data, int): raise TypeError(data) return data
814155f2407cd0e8b580372679f4cecfcc087d9e
6,319
def getFirstValid(opts, default): """Returns the first valid entry from `opts`, or `default` if none found. Valid is defined as ``if o`` returns true.""" for o in opts: if o: return o return default
799a6ea4a993f0a112fa38b882566d72a0d223e0
6,320
def check_string_is_nonempty(string, string_type='string'): """Ensures input is a string of non-zero length""" if string is None or \ (not isinstance(string, str)) or \ len(string) < 1: raise ValueError('name of the {} must not be empty!' ''.format(string_type)) return string
527e60b35f6a827ee9b1eae3c9a3f7abc596b7ff
6,322
import hashlib def md5(filename): """Hash function for files to be uploaded to Fl33t""" md5hash = hashlib.md5() with open(filename, "rb") as filehandle: for chunk in iter(lambda: filehandle.read(4096), b""): md5hash.update(chunk) return md5hash.hexdigest()
35068abafee2c5c4b1ac672f603b0e720a8c9a8c
6,326
def dustSurfaceDensitySingle(R, Rin, Sig0, p): """ Calculates the dust surface density (Sigma d) from single power law. """ return Sig0 * pow(R / Rin, -p)
441466f163a7b968cf193e503d43a1b014be7c5d
6,327
def compute_edits(old, new): """Compute the in-place edits needed to convert from old to new Returns a list ``[(index_1,change_1), (index_2,change_2)...]`` where ``index_i`` is an offset into old, and ``change_1`` is the new bytes to replace. For example, calling ``compute_edits("abcdef", "qbcdzw")`` will return ``[(0, "q"), (4, "zw")]``. That is, the update should be preformed as (abusing notation): ``new[index:index+len(change)] = change`` :param str old: The old data :param str new: The new data :returns: A list of tuples (index_i, change_i) """ deltas = [] delta = None for index, (n, o) in enumerate(zip(new, old)): if n == o: if delta is not None: deltas.append(delta) delta = None else: if delta is None: delta = (index, []) delta[1].append(n) if delta is not None: deltas.append(delta) return [(i, "".join(x)) for i, x in deltas]
f729addf84207f526e27d67932bb5300ced24b54
6,328
def pre_order(size): """List in pre order of integers ranging from 0 to size in a balanced binary tree. """ interval_list = [None] * size interval_list[0] = (0, size) tail = 1 for head in range(size): start, end = interval_list[head] mid = (start + end) // 2 if mid > start: interval_list[tail] = (start, mid) tail += 1 if mid + 1 < end: interval_list[tail] = (mid + 1, end) tail += 1 interval_list[head] = mid return interval_list
45ab688c627c19cd0b9c1200830a91b064d46bda
6,329
def inner_product(D1, D2): """ Take the inner product of the frequency maps. """ result = 0. for key in D1: if key in D2: result += D1[key] * D2[key] return result
95efb9f63d6a379e1c5f7c8f6ad4bfd4061e2032
6,331
def reorder_kernel_weight(torch_weight): """ Reorder a torch kernel weight into a tf format """ len_shape = len(torch_weight.shape) transpose_target = list(range(len_shape)) transpose_target = transpose_target[2:] + transpose_target[:2][::-1] return torch_weight.transpose(transpose_target)
2e289d768d31d3ed875fbb3613ec0e3061b65cd9
6,335
def interpolate(arr_old, arr_new, I_old, J_old): # deprecated 2013-08-26 """ input: array, i, j output: value (int(x), int(y)+1) + + (int(x)+1, int(y)+1) (x,y) + + (int(x)+1, int(y)) (int(x), int(y)) be careful - floor(x)=ceil(x)=x for integer x, so we really want floor(x) and floor(x)+1 """ I = I_old.copy() J = J_old.copy() arr_new2 = arr_new * 0 arr_new2 += (-999) height_new, width_new = arr_new.shape height_old, width_old = arr_old.shape # set all out-of-bounds to (0,0) for convenience I = (I>=0) * (I<height_old-1) * I #e.g. i>=0 and i<=4 for i=[0,1,2,3,4], width=5 J = (J>=0) * (J<width_old -1) * J # the loopings are necessary since we don't know beforehand where the (i_old, j_old) # would land for i in range(height_new): for j in range(width_new): i0 = int(I[i,j]) j0 = int(J[i,j]) i1 = i0 + 1 j1 = j0 + 1 i_frac = i % 1 j_frac = j % 1 f00 = arr_old[i0,j0] f01 = arr_old[i0,j1] f10 = arr_old[i1,j0] f11 = arr_old[i1,j1] arr_new2[i, j] = (1-i_frac)*(1-j_frac) * f00 + \ (1-i_frac)*( j_frac) * f01 + \ ( i_frac)*(1-j_frac) * f00 + \ ( i_frac)*( j_frac) * f00 return arr_new2
bcb34c33ca462c43390ff0dd8802d05dc0512dd3
6,336
import numpy def movmeanstd(ts, m=0): """ Calculate the mean and standard deviation within a moving window passing across a time series. Parameters ---------- ts: Time series to evaluate. m: Width of the moving window. """ if m <= 1: raise ValueError("Query length must be longer than one") mInt = int(m) zero = 0 ts = ts.astype(numpy.longdouble) # Add zero to the beginning of the cumulative sum of ts s = numpy.insert(numpy.cumsum(ts), zero, zero) # Add zero to the beginning of the cumulative sum of ts ** 2 sSq = numpy.insert(numpy.cumsum(ts ** 2), zero, zero) segSum = s[mInt:] - s[:-mInt] segSumSq = sSq[mInt:] - sSq[:-mInt] mov_mean = segSum / m mov_stdP = (segSumSq / m) - ((segSum / m) ** 2) if not numpy.all(mov_stdP == 0): mov_std = numpy.sqrt(numpy.abs(mov_stdP)) else: mov_std = mov_stdP return [mov_mean, mov_std]
8a9e56db4f26862bff972a3dbfac87f6ea5b8c35
6,337
def get_sec (hdr,key='BIASSEC') : """ Returns the numpy range for a FITS section based on a FITS header entry using the standard format {key} = '[{col1}:{col2},{row1}:row2}]' where 1 <= col <= NAXIS1, 1 <= row <= NAXIS2. """ if key in hdr : s = hdr.get(key) # WITHOUT CARD COMMENT ny = hdr['NAXIS2'] sx = s[s.index('[')+1:s.index(',')].split(':') sy = s[s.index(',')+1:s.index(']')].split(':') return [ny-int(sy[1]),ny-int(sy[0])+1,int(sx[0])-1,int(sx[1])] else : return None
3927e6f5d62818079fa9475976f04dda1824e976
6,338
def string_to_gast(node): """ handles primitive string base case example: "hello" exampleIn: Str(s='hello') exampleOut: {'type': 'str', 'value': 'hello'} """ return {"type": "str", "value": node.s}
a3dcd89e893c6edd4a9ba6095cd107bb48cc9782
6,341
def estimate_operating_empty_mass(mtom, fuse_length, fuse_width, wing_area, wing_span, TURBOPROP): """ The function estimates the operating empty mass (OEM) Source: Raymer, D.P. "Aircraft design: a conceptual approach" AIAA educational Series, Fourth edition (2006). Args: mtom (float): Maximum take off mass [kg] fuse_length (float): Fuselage length [m] fuse_width (float): Fuselage width [m] wing_area (float): Wing area [m^2] wing_span (float): Wing span [m] TURBOPROP (bool): True if the the engines are turboprop False otherwise. Returns: oem (float): Operating empty mass [kg] """ G = 9.81 # [m/s^2] Acceleration of gravity. KC = 1.04 # [-] Wing with variable sweep (1.0 otherwhise). if TURBOPROP: C = -0.05 # [-] General aviation twin turboprop if fuse_length < 15.00: A = 0.96 elif fuse_length < 30.00: A = 1.07 else: A = 1.0 else: C = -0.08 # [-] General aviation twin engines if fuse_length < 30.00: A = 1.45 elif fuse_length < 35.00: A = 1.63 elif fuse_length < 60.00: if wing_span > 61: A = 1.63 else: A = 1.57 else: A = 1.63 oem = round((A * KC * (mtom*G)**(C)) * mtom,3) return oem
5b9bed8cef76f3c10fed911087727f0164cffab2
6,342
def getSqTransMoment(system): """//Input SYSTEM is a string with both the molecular species AND the band "system" // Electronic transition moment, Re, needed for "Line strength", S = |R_e|^2*q_v'v" or just |R_e|^2 // //Allen's Astrophysical quantities, 4.12.2 - 4.13.1 // // ROtational & vibrational constants for TiO states:, p. 87, Table 4.17""" #// Square electronic transition moment, |Re|^2, #// needed for "Line strength", S = |R_e|^2*q_v'v" or just |R_e|^2 #// // //Allen's Astrophysical quantities, 4.12.2 - 4.13.1 #// As of Feb 2017 - try the band-head value R_00^2 from last column of table: RSqu = 0.0 #//default initialization #TiO alpha system if ("TiO_C3Delta_X3Delta" == system): RSqu = 0.84 #TiO beta system if ("TiO_c1Phi_a1Delta" == system): RSqu = 4.63 #TiO gamma system if ("TiO_A3Phi_X3Delta" == system): RSqu = 5.24 #CH A^2Delta_X^2Pi system - "G band" at 4300 A if ("CH_A2Delta_X2Pi" == system): RSqu = 0.081 #mean of two values given #// return RSqu
19c5311f7d8fde4bb834d809fd2f6ed7dd2c036e
6,343
def is_configured(): """Return if Azure account is configured.""" return False
5662656b513330e0a05fa25decc03c04b5f367fa
6,344
def box_strings(*strings: str, width: int = 80) -> str: """Centre-align and visually box some strings. Args: *strings (str): Strings to box. Each string will be printed on its own line. You need to ensure the strings are short enough to fit in the box (width-6) or the results will not be as intended. width (int, optional): Width of the box. Defaults to 80. Returns: str: The strings, centred and surrounded by a border box. """ lines = ["+" + "-"*(width-2) + "+", "|" + " "*(width-2) + "|"] lines.extend(f'| {string.center(width-6)} |' for string in strings) lines.extend(lines[:2][::-1]) return "\n".join(lines)
b47aaf020cf121b54d2b588bdec3067a3b83fd27
6,345
def buildDictionary(message): """ counts the occurrence of every symbol in the message and store it in a python dictionary parameter: message: input message string return: python dictionary, key = symbol, value = occurrence """ _dict = dict() for c in message: if c not in _dict.keys(): _dict[c] = 1 else: _dict[c] += 1 return _dict
71b196aaccfb47606ac12242585af4ea2554a983
6,348
import six def logger_has_handlers(logger): """ Check if given logger has at least 1 handler associated, return a boolean value. Since Python 2 doesn't provide Logger.hasHandlers(), we have to perform the lookup by ourself. """ if six.PY3: return logger.hasHandlers() else: c = logger rv = False while c: if c.handlers: rv = True break if not c.propagate: break else: c = c.parent return rv
dc0093dd25a41c997ca92759ccb9fa17ad265bdd
6,350
def setup_train_test_idx(X, last_train_time_step, last_time_step, aggregated_timestamp_column='time_step'): """ The aggregated_time_step_column needs to be a column with integer values, such as year, month or day """ split_timesteps = {} split_timesteps['train'] = list(range(last_train_time_step + 1)) split_timesteps['test'] = list(range(last_train_time_step + 1, last_time_step + 1)) train_test_idx = {} train_test_idx['train'] = X[X[aggregated_timestamp_column].isin(split_timesteps['train'])].index train_test_idx['test'] = X[X[aggregated_timestamp_column].isin(split_timesteps['test'])].index return train_test_idx
256fbe66c0b27b651c8190101e5068f7e0542498
6,351
def add_lists(list1, list2): """ Add corresponding values of two lists together. The lists should have the same number of elements. Parameters ---------- list1: list the first list to add list2: list the second list to add Return ---------- output: list a new list containing the sum of the given lists """ output = [] for it1, it2 in zip(list1, list2): output.append(it1 + it2) return output
e4efbc079a981caa4bcbff4452c8845a7e534195
6,352
def optimize_solution(solution): """ Eliminate moves which have a full rotation (N % 4 = 0) since full rotations don't have any effects in the cube also if two consecutive moves are made in the same direction this moves are mixed in one move """ i = 0 while i < len(solution): dir, n = solution[i] if n % 4 == 0: solution.pop(i) if i > 0: i -= 1 elif i + 1 < len(solution): dir2, n2 = solution[i+1] if dir == dir2: solution[i] = (dir, (n + n2) % 4) solution.pop(i+1) else: i += 1 else: break return solution
4be6bf0e4200dbb629c37a9bdae8338ee32c262b
6,353
def read_file(filename): """ read filename and return its content """ in_fp = open(filename) content = in_fp.read() in_fp.close() return content
c707a412b6099591daec3e70e9e2305fee6511f9
6,354
import argparse def get_arguments(): """Return the values of CLI params""" parser = argparse.ArgumentParser() parser.add_argument("--image_folder", default="images") parser.add_argument("--image_width", default=400, type=int) args = parser.parse_args() return getattr(args, "image_folder"), getattr(args, "image_width")
288bb7a589bae308252a36febcb14b9349371603
6,355
def divide(x,y): """div x from y""" return x/y
74adba33dfd3db2102f80a757024696308928e38
6,356
def r2(data1, data2): """Return the r-squared difference between data1 and data2. Parameters ---------- data1 : 1D array data2 : 1D array Returns ------- output: scalar (float) difference in the input data """ ss_res = 0.0 ss_tot = 0.0 mean = sum(data1) / len(data1) for i in range(len(data1)): ss_res += (data1[i] - data2[i]) ** 2 ss_tot += (data1[i] - mean) ** 2 return 1 - ss_res / ss_tot
d42c06a5ad4448e74fcb1f61fa1eed1478f58048
6,357
import torch def l1_loss(pre, gt): """ L1 loss """ return torch.nn.functional.l1_loss(pre, gt)
c552224b3a48f9cde201db9d0b2ee08cd6335861
6,358
def get_image_unixtime2(ibs, gid_list): """ alias for get_image_unixtime_asfloat """ return ibs.get_image_unixtime_asfloat(gid_list)
2c5fb29359d7a1128fab693d8321d48c8dda782b
6,361
def wrap_arr(arr, wrapLow=-90.0, wrapHigh=90.0): """Wrap the values in an array (e.g., angles).""" rng = wrapHigh - wrapLow arr = ((arr-wrapLow) % rng) + wrapLow return arr
e07e8916ec060aa327c9c112a2e5232b9155186b
6,364
def largest_negative_number(seq_seq): """ Returns the largest NEGATIVE number in the given sequence of sequences of numbers. Returns None if there are no negative numbers in the sequence of sequences. For example, if the given argument is: [(30, -5, 8, -20), (100, -2.6, 88, -40, -5), (400, 500) ] then this function returns -2.6. As another example, if the given argument is: [(200, 2, 20), (500, 400)] then this function returns None. Preconditions: :type seq_seq: (list, tuple) and the given argument is a sequence of sequences, where each subsequence contains only numbers. """ # ------------------------------------------------------------------------- # DONE: 5. Implement and test this function. # Note that you should write its TEST function first (above). # # CHALLENGE: Try to solve this problem with no additional sequences # being constructed (so the SPACE allowed is limited to the # give sequence of sequences plus any non-list variables you want). # ------------------------------------------------------------------------- largest = 0 for k in range(len(seq_seq)): for j in range(len(seq_seq[k])): if seq_seq[k][j] < 0 and largest == 0: largest = seq_seq[k][j] if seq_seq[k][j] < 0 and seq_seq[k][j] > largest: largest = seq_seq[k][j] if largest != 0: return largest
b7326b3101d29fcc0b8f5921eede18a748af71b7
6,365
def filter_resources_sets(used_resources_sets, resources_sets, expand_resources_set, reduce_resources_set): """ Filter resources_set used with resources_sets defined. It will block a resources_set from resources_sets if an used_resources_set in a subset of a resources_set""" resources_expand = [expand_resources_set(resources_set) for resources_set in resources_sets] used_resources_expand = [expand_resources_set(used_resources_set) for used_resources_set in used_resources_sets] real_used_resources_sets = [] for resources_set in resources_expand: for used_resources_set in used_resources_expand: if resources_set.intersection(used_resources_set): real_used_resources_sets.append(reduce_resources_set(resources_set)) break return list(set(resources_sets).difference(set(real_used_resources_sets)))
2ecd752a0460fff99ecc6b8c34ed28782e848923
6,367
def dump_cups_with_first(cups: list[int]) -> str: """Dump list of cups with highlighting the first one :param cups: list of digits :return: list of cups in string format """ dump_cup = lambda i, cup: f'({cup})' if i == 0 else f' {cup} ' ret_val = ''.join([dump_cup(i, cup) for i, cup in enumerate(cups)]) return ret_val
5fe4111f09044c6afc0fbd0870c2b5d548bd3c1a
6,368
def init(strKernel, iKernelPar=1, iALDth=1e-4, iMaxDict=1e3): """ Function initializes krls dictionary. |br| Args: strKernel (string): Type of the kernel iKernelPar (float): Kernel parameter [default = 1] iALDth (float): ALD threshold [default = 1e-4] iMaxDict (int): Max size of the dictionary [default = 1e3] Returns: dAldKRLS (dictionary): Python dictionary which contains all the data of the current KRLS algorithm. Fields in the output dictionary: - a. **iALDth** (*int*): ALD threshold - b. **iMaxDt** (*float*): Max size of the dictionary - c. **strKernel** (*string*): Type of the kernel - d. **iKernelPar** (*float*): Kernel parameter - e. **bInit** (*int*): Initialization flag = 1. This flag is cleared with a first call to the 'train' function. """ dAldKRLS = {} # Initialize dictionary with data for aldkrls algorithm # Store all the parameters in the dictionary dAldKRLS['iALDth'] = iALDth; # ALD threshold dAldKRLS['iMaxDt'] = iMaxDict; # Maximum size of the dictionary dAldKRLS['strKernel'] = strKernel # Type of the kernel dAldKRLS['iKernelPar'] = iKernelPar # Kernel parameter dAldKRLS['bInit'] = 0 # Clear 'Initialization done' flag return dAldKRLS
652e0c498b4341e74bcd30ca7119163345c7f2cc
6,369
from typing import Optional from pathlib import Path import site def get_pipx_user_bin_path() -> Optional[Path]: """Returns None if pipx is not installed using `pip --user` Otherwise returns parent dir of pipx binary """ # NOTE: using this method to detect pip user-installed pipx will return # None if pipx was installed as editable using `pip install --user -e` # https://docs.python.org/3/install/index.html#inst-alt-install-user # Linux + Mac: # scripts in <userbase>/bin # Windows: # scripts in <userbase>/Python<XY>/Scripts # modules in <userbase>/Python<XY>/site-packages pipx_bin_path = None script_path = Path(__file__).resolve() userbase_path = Path(site.getuserbase()).resolve() try: _ = script_path.relative_to(userbase_path) except ValueError: pip_user_installed = False else: pip_user_installed = True if pip_user_installed: test_paths = ( userbase_path / "bin" / "pipx", Path(site.getusersitepackages()).resolve().parent / "Scripts" / "pipx.exe", ) for test_path in test_paths: if test_path.exists(): pipx_bin_path = test_path.parent break return pipx_bin_path
ccf9b886af41b73c7e2060704d45781938d8e811
6,370
def _normalize_int_key(key, length, axis_name=None): """ Normalizes an integer signal key. Leaves a nonnegative key as it is, but converts a negative key to the equivalent nonnegative one. """ axis_text = '' if axis_name is None else axis_name + ' ' if key < -length or key >= length: raise IndexError( f'Index {key} is out of bounds for signal {axis_text}axis with ' f'length {length}.') return key if key >= 0 else key + length
9b58b09e70c20c9ac5ee0be059333dd5058802ef
6,371
from typing import Iterable def prodi(items: Iterable[float]) -> float: """Imperative product >>> prodi( [1,2,3,4,5,6,7] ) 5040 """ p: float = 1 for n in items: p *= n return p
3b8e52f40a760939d5b291ae97c4d7134a5ab450
6,372
def hexString(s): """ Output s' bytes in HEX s -- string return -- string with hex value """ return ":".join("{:02x}".format(ord(c)) for c in s)
22c1e94f0d54ca3d430e0342aa5b714f28a5815b
6,373
from typing import List def normalize_resource_paths(resource_paths: List[str]) -> List[str]: """ Takes a list of resource relative paths and normalizes to lowercase and with the "ed-fi" namespace prefix removed. Parameters ---------- resource_paths : List[str] The list of resource relative paths Returns ------- List[str] A list of normalized resource relative paths. For example: ["studentschoolassociations", "tpdm/candidates"] """ return list( map( lambda r: r.removeprefix("/").removeprefix("ed-fi/").lower(), resource_paths, ) )
ec7e5020ae180cbbdc5b35519106c0cd0697a252
6,374
from functools import reduce def update(*p): """ Update dicts given in params with its precessor param dict in reverse order """ return reduce(lambda x, y: x.update(y) or x, (p[i] for i in range(len(p)-1,-1,-1)), {})
de7f5adbe5504dd9b1be2bbe52e14d11e05ae86f
6,375
def rangify(values): """ Given a list of integers, returns a list of tuples of ranges (interger pairs). :param values: :return: """ previous = None start = None ranges = [] for r in values: if previous is None: previous = r start = r elif r == previous + 1: pass else: # r != previous + 1 ranges.append((start, previous)) start = r previous = r ranges.append((start, previous)) return ranges
672b30d4a4ce98d2203b84db65ccebd53d1f73f5
6,376
def site_geolocation(site): """ Obtain lat-lng coordinate of active trials in the Cancer NCI API""" try: latitude = site['org_coordinates']['lat'] longitude = site['org_coordinates']['lon'] lat_lng = tuple((latitude, longitude)) return lat_lng except KeyError: # key ['org_coordinates'] is missing return None
9fefcd3f49d82233005c88e645efd1c00e1db564
6,378
def get_scaling_desired_nodes(sg): """ Returns the numb of desired nodes the scaling group will have in the future """ return sg.get_state()["desired_capacity"]
5a417f34d89c357e12d760b28243714a50a96f02
6,379
def notas(* valores, sit=False): """ -> Função para analisar notas e situações de vários alunos. :param valores: uma ou mais notas dos alunos (aceita várias) :param sit: valor opcional, indicando se deve ou não adicionar a situação :return: dicionário com várias informações sobre a situação da turma. """ dicionario = dict() dicionario["Quantidade de notas"] = len(valores) dicionario["Maior nota"] = max(valores) dicionario["Menor nota"] = min(valores) dicionario["Média da turma"] = sum(valores)/len(valores) if sit == True: if dicionario["Média da turma"] >= 7.0: dicionario["A situação"] = 'BOA' elif 5.0 <= dicionario["Média da turma"] < 7.0: dicionario["A situação"] = 'RAZOÁVEL' else: dicionario["A situação"] = 'RUIM' return dicionario
a6915e9b7b1feef0db2be6fdf97b6f236d73f282
6,381
def append_OrbitSection(df): """Use OrbitDirection flags to identify 4 sections in each orbit.""" df["OrbitSection"] = 0 ascending = (df["OrbitDirection"] == 1) & (df["QDOrbitDirection"] == 1) descending = (df["OrbitDirection"] == -1) & (df["QDOrbitDirection"] == -1) df["OrbitSection"].mask( (df["QDLat"] > 50) & ascending, 1, inplace=True ) df["OrbitSection"].mask( (df["QDLat"] > 50) & descending, 2, inplace=True ) df["OrbitSection"].mask( (df["QDLat"] < -50) & descending, 3, inplace=True ) df["OrbitSection"].mask( (df["QDLat"] < -50) & ascending, 4, inplace=True ) return df
4f2cad6cb2facf6a7a8c7a89ed7b3df0a56a54c2
6,382
def hex_to_64(hexstr): """Convert a hex string to a base64 string. Keyword arguments: hexstr -- the hex string we wish to convert """ B64CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' ## internals # bits contains the bits read off so far that don't make enough for a char bits = 0 # bits_left tracks how many bits are left until a char is ready to convert bits_left = 6 # output holds the accrued base64 string thus far output = '' # Read each hex char as four bits. Every time 6 are accrued, # convert them to base64 and continue. for h in hexstr: hbits = int(h, 16) if bits_left == 6: # h's bits aren't enough. Hold 'em and keep going. bits = hbits bits_left = 2 elif bits_left == 4: # h's bits are just enough. Add 'em to the bits bin and convert. bits = (bits << 4) | hbits output += B64CHARS[bits] bits = 0 bits_left = 6 else: # h's top two bits finish a set of 6. Convert the set # and save the last two of h's bits. bits = (bits << 2) | (hbits >> 2) output += B64CHARS[bits] bits = hbits & 3 bits_left = 4 # After reading hexstr, we may need some zeroes for padding. # We should also add '=' chars for each pair of padding bits. if bits_left < 6: output += B64CHARS[bits << bits_left] output += '=' * (bits_left // 2) return output
ca8c48bedf4ac776288a8faad06ec80c0289c11e
6,383
def is_private(name): """Check whether a Python object is private based on its name.""" return name.startswith("_")
d04dfd84884bbc8c8be179c6bc5fc1371f426a78
6,385
import warnings def get_suitable_output_file_name_for_current_output_format(output_file, output_format): """ renames the name given for the output_file if the results for current_output format are returned compressed by default and the name selected by the user does not contain the correct extension. output_file : str, optional, default None file name selected by the user output_format : str, optional, default 'votable' results format. Available formats in TAP are: 'votable', 'votable_plain', 'fits', 'csv', 'ecsv' and 'json'. Default is 'votable'. Returned results for formats 'votable' 'ecsv' and 'fits' are compressed gzip files. Returns ------- A string with the new name for the file. """ compressed_extension = ".gz" format_with_results_compressed = ['votable', 'fits', 'ecsv'] output_file_with_extension = output_file if output_file is not None: if output_format in format_with_results_compressed: # In this case we will have to take also into account the .fits format if not output_file.endswith(compressed_extension): warnings.warn('By default, results in "votable", "ecsv" and "fits" format are returned in ' f'compressed format therefore your file {output_file} ' f'will be renamed to {output_file}.gz') if output_format == 'votable': if output_file.endswith('.vot'): output_file_with_extension = output_file + '.gz' else: output_file_with_extension = output_file + '.vot.gz' elif output_format == 'fits': if output_file.endswith('.fits'): output_file_with_extension = output_file + '.gz' else: output_file_with_extension = output_file + '.fits.gz' elif output_format == 'ecsv': if output_file.endswith('.ecsv'): output_file_with_extension = output_file + '.gz' else: output_file_with_extension = output_file + '.ecsv.gz' # the output type is not compressed by default by the TAP SERVER but the users gives a .gz extension elif output_file.endswith(compressed_extension): output_file_renamed = output_file.removesuffix('.gz') warnings.warn(f'The output format selected is not compatible with compression. {output_file}' f' will be renamed to {output_file_renamed}') return output_file_with_extension
6925d721f06e52c8177c5e4f6404629043642cc4
6,386
def count_ents(phrase): """ Counts the number of Named Entities in a spaCy Doc/Span object. :param phrase: the Doc/Span object from which to remove Named Entities. :return: The number of Named Entities identified in the input object. """ named_entities = list(phrase.ents) return len(named_entities)
7e592442ebaf504320a903c4084454ff73896595
6,388
def get_Q_UT_CL_d_t_i(L_CL_d_t_i, Q_T_CL_d_t_i): """冷房設備機器の未処理冷房潜熱負荷(MJ/h)(20b)を計算する Args: Q_max_CL_d_t_i(ndarray): 最大冷房潜熱出力 L_CL_d_t_i(ndarray): 冷房潜熱負荷 Q_T_CL_d_t_i: returns: 冷房設備機器の未処理冷房潜熱負荷(MJ/h) Returns: ndarray: 冷房設備機器の未処理冷房潜熱負荷(MJ/h) """ return L_CL_d_t_i - Q_T_CL_d_t_i
4f46048e6df08d634153b176b241ac1caaae252f
6,389
import struct def txt2domainname(input, canonical_form=False): """turn textual representation of a domain name into its wire format""" if input == ".": d = b'\x00' else: d = b"" for label in input.split('.'): label = label.encode('ascii') if canonical_form: label = label.lower() length = len(label) d += struct.pack('B', length) + label return d
d5312ab1333810eaba6bac2f16e15441ea290dc9
6,392
import os import logging def create_dir(path_dir): """ create a folder if it not exists :param str path_dir: """ path_dir = os.path.abspath(path_dir) if not os.path.isdir(path_dir): os.makedirs(path_dir, mode=0o775) else: logging.warning('Folder already exists: %s', path_dir) return path_dir
e26004caed69c6d29de20ea08004bd54aa1f6cf8
6,393
def sample(x, n): """ Get n number of rows as a sample """ # import random # print(random.sample(list(x.index), n)) return x.iloc[list(range(n))]
3802f976f2a97a08945d8246093784c06fb07e67
6,394
def issubset(list1, list2): """ Examples: >>> issubset([], [65, 66, 67]) True >>> issubset([65], [65, 66, 67]) True >>> issubset([65, 66], [65, 66, 67]) True >>> issubset([65, 67], [65, 66, 67]) False """ n = len(list1) for startpos in range(len(list2) - n + 1): if list2[startpos:startpos+n] == list1: return True return False
2f4acbba54b303b7041febbe485d8960baa6528f
6,396
from typing import Any def is_none_or_empty(obj: Any) -> bool: """Determine if object is None or empty :param obj: object :return: if object is None or empty """ return obj is None or len(obj) == 0
a90245326e4c776ca1ee0066e965a4f656a20014
6,397
def reshape2D(x): """ Reshapes x from (batch, channels, H, W) to (batch, channels, H * W) """ return x.view(x.size(0), x.size(1), -1)
29851e54bb816fb45184d3ea20e28d786270f662
6,398
def get_fr_trj_ntrj(rslt, start, end, a_params): """Check whether event exhibits "blowup" behavior.""" # get spks during candidate replay event spks_evt = rslt.spks[(start <= rslt.ts) & (rslt.ts < end), :] # get mask over trj and non-trj PCs pc_mask = rslt.ntwk.types_rcr == 'PC' sgm_cutoff = .5 * (1 + rslt.p['SGM_MAX']) trj_mask = (rslt.ntwk.sgm * pc_mask.astype(float)) > sgm_cutoff ntrj_mask = (~trj_mask) & pc_mask # get trj-PC spks spks_trj = spks_evt[:, trj_mask] fr_trj = (spks_trj.sum(0) / (end - start)).mean() # get non-trj-PC spks spks_ntrj = spks_evt[:, ntrj_mask] fr_ntrj = (spks_ntrj.sum(0) / (end - start)).mean() # return trj-PC and non-trj-PC firing rates return fr_trj, fr_ntrj
7cb2f0262debba36789e4e230b4d26dd096cf950
6,399
def add_to_group(ctx, user, group): """Adds a user into a group. Returns ``True`` if is just added (not already was there). :rtype: bool """ result = ctx.sudo(f'adduser {user} {group}').stdout.strip() return 'Adding' in result
abb7b432f4e4206a3509d1376adca4babb02e9f0
6,400
import sys def trim_docstring(docstring): """ This is taken from PEP257, and was slightly modified to work with Python 3 (and renamed), but is otherwise included verbatim. https://www.python.org/dev/peps/pep-0257/ """ if not docstring: return '' # Convert tabs to spaces (following the normal Python rules) # and split into a list of lines: lines = docstring.expandtabs().splitlines() # Determine minimum indentation (first line doesn't count): indent = sys.maxsize for line in lines[1:]: stripped = line.lstrip() if stripped: indent = min(indent, len(line) - len(stripped)) # Remove indentation (first line is special): trimmed = [lines[0].strip()] if indent < sys.maxsize: for line in lines[1:]: trimmed.append(line[indent:].rstrip()) # Strip off trailing and leading blank lines: while trimmed and not trimmed[-1]: trimmed.pop() while trimmed and not trimmed[0]: trimmed.pop(0) # Return a single string: return '\n'.join(trimmed)
a4f115541dc6106749caecea44a530a095a92f57
6,401
import torch def load_ckp(model, ckp_path, device, parallel=False, strict=True): """Load checkpoint Args: ckp_path (str): path to checkpoint Returns: int, int: current epoch, current iteration """ ckp = torch.load(ckp_path, map_location=device) if parallel: model.module.load_state_dict( ckp['state_dict'], strict=strict) else: model.load_state_dict(ckp['state_dict'], strict=strict) return ckp['epoch'], ckp['iter']
4fe4e368d624583216add3eca62293d5d1539182
6,402
from typing import List from typing import Any from typing import Generator def neighborhood( iterable: List[Any], ) -> Generator[Any, Any, Any]: """ """ if not iterable: return iterable iterator = iter(iterable) prev_item = None current_item = next(iterator) # throws StopIteration if empty. for next_item in iterator: yield (prev_item, current_item, next_item) prev_item = current_item current_item = next_item yield (prev_item, current_item, None)
4d07ee920e4861fce88658b1fc5ce719907ba897
6,405
def _slice_slice(outer, outer_len, inner, inner_len): """ slice a slice - we take advantage of Python 3 range's support for indexing. """ assert(outer_len >= inner_len) outer_rng = range(*outer.indices(outer_len)) rng = outer_rng[inner] start, stop, step = rng.start, rng.stop, rng.step if step < 0 and stop < 0: stop = None return slice(start, stop, step)
4430ae752fbc9d7db6414418b18a0b8186f3d328
6,407
def dump_adcs(adcs, drvname='ina219', interface=2): """Dump xml formatted INA219 adcs for servod. Args: adcs: array of adc elements. Each array element is a tuple consisting of: slv: int representing the i2c slave address plus optional channel if ADC (INA3221 only) has multiple channels. For example, "0x40" : address 0x40 ... no channel "0x40:1" : address 0x40, channel 1 name: string name of the power rail sense: float of sense resitor size in ohms nom: float of nominal voltage of power rail. mux: string name of i2c mux leg these ADC's live on is_calib: boolean to determine if calibration is possible for this rail drvname: string name of adc driver to enumerate for controlling the adc. interface: interface index to handle low-level communication. Returns: string (large) of xml for the system config of these ADCs to eventually be parsed by servod daemon ( servo/system_config.py ) """ # Must match REG_IDX.keys() in servo/drv/ina2xx.py regs = ['cfg', 'shv', 'busv', 'pwr', 'cur', 'cal'] if drvname == 'ina231': regs.extend(['msken', 'alrt']) elif drvname == 'ina3221': regs = ['cfg', 'shv', 'busv', 'msken'] rsp = "" for (slv, name, nom, sense, mux, is_calib) in adcs: chan = '' if drvname == 'ina3221': (slv, chan_id) = slv.split(':') chan = 'channel="%s"' % chan_id rsp += ( '<control><name>%(name)s_mv</name>\n' '<doc>Bus Voltage of %(name)s rail in millivolts on i2c_mux:%(mux)s</doc>\n' '<params interface="%(interface)d" drv="%(drvname)s" slv="%(slv)s" %(chan)s' ' mux="%(mux)s" rsense="%(sense)s" type="get" subtype="millivolts"' ' nom="%(nom)s">\n</params></control>\n' '<control><name>%(name)s_shuntmv</name>\n' '<doc>Shunt Voltage of %(name)s rail in millivolts on i2c_mux:%(mux)s</doc>\n' '<params interface="%(interface)d" drv="%(drvname)s" slv="%(slv)s" %(chan)s' ' mux="%(mux)s" rsense="%(sense)s" type="get" subtype="shuntmv"' ' nom="%(nom)s">\n</params></control>\n' ) % {'name':name, 'drvname':drvname, 'interface':interface, 'slv':slv, 'mux':mux, 'sense':sense, 'nom':nom, 'chan':chan} # in some instances we may not know sense resistor size ( re-work ) or other # custom factors may not allow for calibration and those reliable readings # on the current and power registers. This boolean determines which # controls should be enumerated based on rails input specification if is_calib: rsp += ( '<control><name>%(name)s_ma</name>\n' '<doc>Current of %(name)s rail in milliamps on i2c_mux:%(mux)s</doc>\n' '<params interface="%(interface)d" drv="%(drvname)s" slv="%(slv)s" %(chan)s' 'rsense="%(sense)s" type="get" subtype="milliamps">\n' '</params></control>\n' '<control><name>%(name)s_mw</name>\n' '<doc>Power of %(name)s rail in milliwatts on i2c_mux:%(mux)s</doc>\n' '<params interface="%(interface)d" drv="%(drvname)s" slv="%(slv)s" %(chan)s' ' mux="%(mux)s" rsense="%(sense)s" type="get" subtype="milliwatts">\n' '</params></control>\n') % {'name':name, 'drvname':drvname, 'interface':interface, 'slv':slv, 'mux':mux, 'sense':sense, 'nom':nom, 'chan':chan} for reg in regs: rsp += ( '<control><name>%(name)s_%(reg)s_reg</name>\n' '<doc>Raw register value of %(reg)s on i2c_mux:%(mux)s</doc>' '<params cmd="get" interface="%(interface)d"' ' drv="%(drvname)s" slv="%(slv)s" %(chan)s' ' subtype="readreg" reg="%(reg)s" mux="%(mux)s"' ' fmt="hex">\n</params>') % {'name':name, 'drvname':drvname, 'interface':interface, 'slv':slv, 'mux':mux, 'sense':sense, 'reg':reg, 'chan':chan} if reg in ["cfg", "cal"]: map_str = "" if reg == "cal": map_str = ' map="calibrate"' rsp += ( '<params cmd="set" interface="%(interface)d"' ' drv="%(drvname)s" slv="%(slv)s" %(chan)s' ' subtype="writereg" reg="%(reg)s" mux="%(mux)s"' ' fmt="hex"%(map)s>\n</params></control>') % {'drvname':drvname, 'interface':interface, 'slv':slv, 'mux':mux, 'sense':sense, 'reg':reg, 'chan':chan, 'map':map_str} else: rsp += ('</control>') return rsp
b9c0aec3e6098a5de28a467910f4861e8860d723
6,408
def is_isbn_or_key(q): """ 判断搜索关键字是isbn还是key :param q: :return: """ # isbn13 13位0-9数字;isbn10 10位0-9数字,中间含有 '-' isbn_or_key = 'key' if len(q) == 13 and q.isdigit(): isbn_or_key = 'isbn' if '-' in q: short_q = q.replace('-', '') if len(short_q) == 10 and short_q.isdigit(): isbn_or_key = 'isbn' return isbn_or_key
cf35f13e8188741bd37715a1ed91cf40667cff40
6,409
def get_upright_box(waymo_box): """Convert waymo box to upright box format and return the convered box.""" xmin = waymo_box.center_x - waymo_box.length / 2 # xmax = waymo_box.center_x+waymo_box.length/2 ymin = waymo_box.center_y - waymo_box.width / 2 # ymax = waymo_box.center_y+waymo_box.width/2 return [xmin, ymin, waymo_box.length, waymo_box.width]
2c301e3d60078ba416446dfe133fb9802c96f09c
6,410
def update_two_contribution_score(click_time_one, click_time_two): """ user cf user contribution score update v2 :param click_time_one: different user action time to the same item :param click_time_two: time two :return: contribution score """ delta_time = abs(click_time_two - click_time_one) norm_num = 60 * 60 * 24 delta_time = delta_time / norm_num return 1 / (1 + delta_time)
df959e4581f84be5e0dffd5c35ebe70b97a78383
6,411
def fix_text_note(text): """Wrap CHS document text.""" if not text: return "" else: return """* CHS "Chicago Streets" Document:\n> «{}»""".format(text)
56cbcbad7e8b3eee6bb527a240ad96701c4eea2f
6,412
import multiprocessing def _fetch_cpu_count(): """ Returns the number of available CPUs on machine in use. Parameters: ----------- None Returns: -------- multiprocessing.cpu_count() Notes: ------ None """ return multiprocessing.cpu_count()
6c35446b706aa27b49bd678520b2378b1c7f8b90
6,414
def is_block_comment(line): """ Entering/exiting a block comment """ line = line.strip() if line == '"""' or (line.startswith('"""') and not line.endswith('"""')): return True if line == "'''" or (line.startswith("'''") and not line.endswith("'''")): return True return False
ea38c248964eeaec1eab928182022de6ecccad69
6,415
from typing import List from typing import Dict import requests def get_airtable_data(url: str, token: str) -> List[Dict[str, str]]: """ Fetch all data from airtable. Returns a list of records where record is an array like {'my-key': 'George W. Bush', 'my-value': 'Male'} """ response = requests.request("GET", url, headers={"Authorization": f"Bearer {token}"}) records = response.json()["records"] return [record["fields"] for record in records]
f91326938a663ddedd8b4a10f796c7c36981da4e
6,416
def displayname(user): """Returns the best display name for the user""" return user.first_name or user.email
aecebc897803a195b08cdfb46dbeb4c9df9ede09
6,417
def price(listing): """Score based on number of bedrooms.""" if listing.price is None: return -4000 score = 0.0 bedrooms = 1.0 if listing.bedrooms is None else listing.bedrooms if (bedrooms * 1000.0) > listing.price: score += -1000 - ((bedrooms * 750.0) / listing.price - 1.0) * 1000 return -1.0 * listing.price + score
7087da4e4f9dedf03fdaed5661029f1be0703f0e
6,418
import shlex def shell_quote(*args: str) -> str: """ Takes command line arguments as positional args, and properly quotes each argument to make it safe to pass on the command line. Outputs a string containing all passed arguments properly quoted. Uses :func:`shlex.join` on Python 3.8+, and a for loop of :func:`shlex.quote` on older versions. Example:: >>> print(shell_quote('echo', '"orange"')) echo '"orange"' """ return shlex.join(args) if hasattr(shlex, 'join') else " ".join([shlex.quote(a) for a in args]).strip()
b2d0ecde5a2569e46676fed81ed3ae034fb8d36c
6,419
import torch def normalized_state_to_tensor(state, building): """ Transforms a state dict to a pytorch tensor. The function ensures the correct ordering of the elements according to the list building.global_state_variables. It expects a **normalized** state as input. """ ten = [[ state[sval] for sval in building.global_state_variables ]] return torch.tensor(ten)
4aea246f388f941290d2e4aeb6da16f91e210caa
6,420
def translate_lat_to_geos5_native(latitude): """ The source for this formula is in the MERRA2 Variable Details - File specifications for GEOS pdf file. The Grid in the documentation has points from 1 to 361 and 1 to 576. The MERRA-2 Portal uses 0 to 360 and 0 to 575. latitude: float Needs +/- instead of N/S """ return ((latitude + 90) / 0.5)
b1fb1824bfefce3fd58ca7a26f9603b910779a61
6,421
def disabled_payments_notice(context, addon=None): """ If payments are disabled, we show a friendly message urging the developer to make his/her app free. """ addon = context.get('addon', addon) return {'request': context.get('request'), 'addon': addon}
b77dc41cf8ac656b2891f82328a04c1fe7aae49c
6,422
def construct_futures_symbols( symbol, start_year=2010, end_year=2014 ): """ Constructs a list of futures contract codes for a particular symbol and timeframe. """ futures = [] # March, June, September and # December delivery codes months = 'HMUZ' for y in range(start_year, end_year+1): for m in months: futures.append("%s%s%s" % (symbol, m, y)) return futures
2917a9eb008f5ab141576243bddf4769decfd1f3
6,423
def getAllChannels(): """ a func to see all valid channels :return: a list channels """ return ["Hoechst", 'ERSyto', 'ERSytoBleed', 'Ph_golgi', 'Mito']
d4fee111bad73f8476877a96645490aef37c07c9
6,425
from typing import Dict from typing import Any def merge_dicts(dict1: Dict[str, Any], dict2: Dict[str, Any], *dicts: Dict[str, Any]) -> Dict[str, Any]: """ Merge multiple dictionaries, producing a merged result without modifying the arguments. :param dict1: the first dictionary :param dict2: the second dictionary :param dicts: additional dictionaries :return: The merged dictionary. Keys in dict2 overwrite duplicate keys in dict1 """ res = dict1.copy() res.update(dict2) for d in dicts: res.update(d) return res
869399774cc07801e5fa95d9903e6a9f2dadfc25
6,428
from datetime import datetime def iso_date(iso_string): """ from iso string YYYY-MM-DD to python datetime.date Note: if only year is supplied, we assume month=1 and day=1 This function is not longer used, dates from lists always are strings """ if len(iso_string) == 4: iso_string = iso_string + '-01-01' d = datetime.strptime(iso_string, '%Y-%m-%d') return d.date()
7f29b22744d384187e293c546d4c28790c211e99
6,430
def number_to_string(s, number): """ :param s: word user input :param number: string of int which represent possible anagram :return: word of alphabet """ word = '' for i in number: word += s[int(i)] return word
7997b20264d0750e2b671a04aacb56c2a0559d8c
6,431
import torch def softmax(x): """Softmax activation function Parameters ---------- x : torch.tensor """ return torch.exp(x) / torch.sum(torch.exp(x), dim=1).view(-1, 1)
739219efe04174fe7a2b21fb8aa98816679f8389
6,434
def remove_element(nums, val): """ :type nums: List[int] :type val: int :rtype: int """ sz = len(nums) while sz > 0 and nums[sz - 1] == val: sz -= 1 i = 0 while i < sz: if nums[i] == val: nums[i], nums[sz - 1] = nums[sz - 1], nums[i] sz -= 1 while sz > 0 and nums[sz - 1] == val: sz -= 1 i += 1 return sz
4d29e8a8d43f191fe83ab0683f5dff005db799ec
6,435