content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def preprocess_img(img): """Preprocessing function for images.""" return img/255
11651a809288d5c3aa776b318099b7eb750d28ec
6,292
def cdf(vals, reverse=False): """Computes the CDF of a list of values""" vals = sorted(vals, reverse=reverse) tot = float(len(vals)) x = [] y = [] for i, x2 in enumerate(vals): x.append(x2) y.append((i+1) / tot) return x, y
3cc64dcb8876f7620f02da873e29569e77477823
6,295
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
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
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 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
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
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 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 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 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 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 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 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 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
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 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 is_private(name): """Check whether a Python object is private based on its name.""" return name.startswith("_")
d04dfd84884bbc8c8be179c6bc5fc1371f426a78
6,385
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 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
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 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 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
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
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
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 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
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
def get_total_obs_num_samples(obs_length=None, num_blocks=None, length_mode='obs_length', num_antennas=1, sample_rate=3e9, block_size=134217728, num_bits=8, num_pols=2, num_branches=1024, num_chans=64): """ Calculate number of required real voltage time samples for as given `obs_length` or `num_blocks`, without directly using a `RawVoltageBackend` object. Parameters ---------- obs_length : float, optional Length of observation in seconds, if in `obs_length` mode num_blocks : int, optional Number of data blocks to record, if in `num_blocks` mode length_mode : str, optional Mode for specifying length of observation, either `obs_length` in seconds or `num_blocks` in data blocks num_antennas : int Number of antennas sample_rate : float Sample rate in Hz block_size : int Block size used in recording GUPPI RAW files num_bits : int Number of bits in requantized data (for saving into file). Can be 8 or 4. num_pols : int Number of polarizations recorded num_branches : int Number of branches in polyphase filterbank num_chans : int Number of coarse channels written to file Returns ------- num_samples : int Number of samples """ tbin = num_branches / sample_rate chan_bw = 1 / tbin bytes_per_sample = 2 * num_pols * num_bits / 8 if length_mode == 'obs_length': if obs_length is None: raise ValueError("Value not given for 'obs_length'.") num_blocks = int(obs_length * chan_bw * num_antennas * num_chans * bytes_per_sample / block_size) elif length_mode == 'num_blocks': if num_blocks is None: raise ValueError("Value not given for 'num_blocks'.") pass else: raise ValueError("Invalid option given for 'length_mode'.") return num_blocks * int(block_size / (num_antennas * num_chans * bytes_per_sample)) * num_branches
0d5c3de03723c79d31c7f77ece29226daaf4f442
6,437
def get_page_index(obj, amongst_live_pages=True): """ Get oage's index (a number) within its siblings. :param obj: Wagtail page object :param amongst_live_pages: Get index amongst live pages if True or all pages if False. :return: Index of a page if found or None if page doesn't have an index. """ qs = obj.__class__.objects.filter(depth=obj.depth).values_list('pk', flat=True) if amongst_live_pages: qs = qs.live() if obj.depth > 1: # making sure the non-root nodes share a parent parentpath = obj._get_basepath(obj.path, obj.depth - 1) qs = qs.filter( path__range=obj._get_children_path_interval(parentpath)) try: index = list(qs).index(obj.pk) return index except ValueError: return None
fd1950533a398019ab0d3e208a1587f86b134a13
6,441
import math def plagdet_score(rec, prec, gran): """Combines recall, precision, and granularity to a allow for ranking.""" if (rec == 0 and prec == 0) or prec < 0 or rec < 0 or gran < 1: return 0 return ((2 * rec * prec) / (rec + prec)) / math.log(1 + gran, 2)
f8debf876d55296c3945d0d41c7701588a1869b6
6,446
def get_matrix_header(filename): """ Returns the entries, rows, and cols of a matrix market file. """ with open(filename) as f: entries = 0 rows = 0 cols = 0 for line in f.readlines(): if line.startswith('%'): continue line = line.split() entries = int(line[0]) rows = int(line[1]) cols = int(line[2]) return entries, rows, cols
66200661715cb9a67522ced7b13d4140a3905c28
6,447
def get_satellite_params(platform=None): """ Helper function to generate Landsat or Sentinel query information for quick use during NRT cube creation or sync only. Parameters ---------- platform: str Name of a satellite platform, Landsat or Sentinel only. params """ # check platform name if platform is None: raise ValueError('Must provide a platform name.') elif platform.lower() not in ['landsat', 'sentinel']: raise ValueError('Platform must be Landsat or Sentinel.') # set up dict params = {} # get porams depending on platform if platform.lower() == 'landsat': # get collections collections = [ 'ga_ls5t_ard_3', 'ga_ls7e_ard_3', 'ga_ls8c_ard_3'] # get bands bands = [ 'nbart_red', 'nbart_green', 'nbart_blue', 'nbart_nir', 'nbart_swir_1', 'nbart_swir_2', 'oa_fmask'] # get resolution resolution = 30 # build dict params = { 'collections': collections, 'bands': bands, 'resolution': resolution} else: # get collections collections = [ 's2a_ard_granule', 's2b_ard_granule'] # get bands bands = [ 'nbart_red', 'nbart_green', 'nbart_blue', 'nbart_nir_1', 'nbart_swir_2', 'nbart_swir_3', 'fmask'] # get resolution resolution = 10 # build dict params = { 'collections': collections, 'bands': bands, 'resolution': resolution} return params
2298c100eed431a48a9531bc3038c5ab8565025d
6,451
def list_agg(object_list, func): """Aggregation function for a list of objects.""" ret = [] for elm in object_list: ret.append(func(elm)) return ret
b2d8eef9c795e4700d111a3949922df940435809
6,459
def all_children(wid): """Return all children of a widget.""" _list = wid.winfo_children() for item in _list: if item.winfo_children(): _list.extend(item.winfo_children()) return _list
ca52791b06db6f2dd1aeedc3656ecf08cb7de6d8
6,466
def _mgSeqIdToTaxonId(seqId): """ Extracts a taxonId from sequence id used in the Amphora or Silva mg databases (ends with '|ncbid:taxonId") @param seqId: sequence id used in mg databases @return: taxonId @rtype: int """ return int(seqId.rsplit('|', 1)[1].rsplit(':', 1)[1])
2ce74f453e3496c043a69b4205f258f06bfd0452
6,471
def url_to_filename(url): """Converts a URL to a valid filename.""" return url.replace('/', '_')
db3023c582590a47a6adc32501a2e3f5fd72f24f
6,472
def get_params_out_of_range( params: list, lower_params: list, upper_params: list ) -> list: """ Check if any parameter specified by the user is out of the range that was defined :param params: List of parameters read from the .inp file :param lower_params: List of lower bounds provided by the user in the .inp file :param upper_params: List of upper bounds provided by the user in the .inp file :return: List of parameters out of the defined range """ params_out = [ i for i in range(len(lower_params)) if params[i] < lower_params[i] or params[i] > upper_params[i] ] return params_out
67a8ca57a29da8b431ae26f863ff8ede58f41a34
6,483
def limit(value, limits): """ :param <float> value: value to limit :param <list>/<tuple> limits: (min, max) limits to which restrict the value :return <float>: value from within limits, if input value readily fits into the limits its left unchanged. If value exceeds limit on either boundary its set to that boundary. """ if value < limits[0]: value = limits[0] elif value > limits[1]: value = limits[1] else: pass return value
55fb603edb478a26b238d7c90084e9c17c3113b8
6,485
def _FilterSubstructureMatchByAtomMapNumbers(Mol, PatternMol, AtomIndices, AtomMapIndices): """Filter substructure match atom indices by atom map indices corresponding to atom map numbers. """ if AtomMapIndices is None: return list(AtomIndices) return [AtomIndices[Index] for Index in AtomMapIndices]
3594a11452848c9ae11f770fa560fe29d68aa418
6,490
from typing import Any from typing import Set import inspect from unittest.mock import Mock def _get_default_arguments(obj: Any) -> Set[str]: """Get the names of the default arguments on an object The default arguments are determined by comparing the object to one constructed from the object's class's initializer with Mocks for all positional arguments Arguments: obj: the object to find default arguments on Returns: the set of default arguments """ cls = type(obj) obj_sig = inspect.signature(cls.__init__) try: mocked_obj = cls( **{ param.name: Mock() for param in obj_sig.parameters.values() if param.default == param.empty and param.kind != param.VAR_KEYWORD and param.name != "self" } ) except Exception: return set() return { key for key, value in obj.__dict__.items() if key in mocked_obj.__dict__ and mocked_obj.__dict__[key] == value }
483fe82dd79aadfe1da387fb0c602beb503f344b
6,493
import csv def main(file_in, file_out): """ Read in lines, flatten list of lines to list of words, sort and tally words, write out tallies. """ with open(file_in, 'r') as f_in: word_lists = [line.split() for line in f_in] # Flatten the list # http://stackoverflow.com/questions/952914/\ # making-a-flat-list-out-of-list-of-lists-in-python words = [word for word_list in word_lists for word in word_list] counts = map(words.count, words) tallies = sorted(set(zip(words, counts))) with open(file_out, 'w') as f_out: writer = csv.writer(f_out, quoting=csv.QUOTE_NONNUMERIC) for (word, count) in tallies: writer.writerow([word, count]) return None
225dd5d5b4c2bcb158ee61aa859f78e1e608a5fe
6,500
def load_atomic(val): """ Load a std::atomic<T>'s value. """ valty = val.type.template_argument(0) # XXX This assumes std::atomic<T> has the same layout as a raw T. return val.address.reinterpret_cast(valty.pointer()).dereference()
307bcc9d3eae2eede6a8e2275104280a1e7b4b94
6,501
def dataId_to_dict(dataId): """ Parse an LSST dataId to a dictionary. Args: dataId (dataId): The LSST dataId object. Returns: dict: The dictionary version of the dataId. """ return dataId.to_simple().dict()["dataId"]
77b7566492b80a8c6e2becacafff36737c8a7256
6,502
def _get_exploration_memcache_key(exploration_id): """Returns a memcache key for an exploration.""" return 'exploration:%s' % exploration_id
1400607cc86f84c242201c9c9fe36a7a06cd2357
6,505
def pairs_from_array(a): """ Given an array of strings, create a list of pairs of elements from the array Creates all possible combinations without symmetry (given pair [a,b], it does not create [b,a]) nor repetition (e.g. [a,a]) :param a: Array of strings :return: list of pairs of strings """ pairs = list() for i in range(len(a)): for j in range(len(a[i + 1 :])): pairs.append([a[i], a[i + 1 + j]]) return pairs
50c489d660a7e82c18baf4800e599b8a3cd083f0
6,507
from typing import Any def complex_key(c: complex) -> Any: """Defines a sorting order for complex numbers.""" return c.real != int(c.real), c.real, c.imag
55c17b0d4adf8bcfb39b50c66d5bd8133f5bb814
6,510
def get_campaign_goal(campaign, goal_identifier): """Returns goal from given campaign and Goal_identifier. Args: campaign (dict): The running campaign goal_identifier (string): Goal identifier Returns: dict: Goal corresponding to goal_identifer in respective campaign """ if not campaign or not goal_identifier: return None for goal in campaign.get("goals"): if goal.get("identifier") == goal_identifier: return goal return None
1a8738416ee8187ad2a6a977b36b68f66052bfe8
6,511
def _unsigned16(data, littleEndian=False): """return a 16-bit unsigned integer with selectable Endian""" assert len(data) >= 2 if littleEndian: b0 = data[1] b1 = data[0] else: b0 = data[0] b1 = data[1] val = (b0 << 8) + b1 return val
22feb074aca7f4ab7d489eacb573c3653cad9272
6,515
def calculate_term_frequencies(tokens): """Given a series of `tokens`, produces a sorted list of tuples in the format of (term frequency, token). """ frequency_dict = {} for token in tokens: frequency_dict.setdefault(token, 0) frequency_dict[token] += 1 tf = [] for token, count in frequency_dict.items(): tf.append( (count, token) ) return sorted(tf, reverse=True)
b764175cd59fe25c4a87576faee2a76273097c5e
6,516
import math def _rescale_read_counts_if_necessary(n_ref_reads, n_total_reads, max_allowed_reads): """Ensures that n_total_reads <= max_allowed_reads, rescaling if necessary. This function ensures that n_total_reads <= max_allowed_reads. If n_total_reads is <= max_allowed_reads, n_ref_reads and n_total_reads are just returned. However, if n_total_reads > max_allowed_reads, then n_ref_reads and n_total_reads are rescaled to new values n_ref_reads' and n_total_reads' so that n_total_reads' == max_allowed_reads and n_ref_reads' / n_total_reads' ~ n_ref_reads / n_total_reads. Args: n_ref_reads: int. Number of reference supporting reads. n_total_reads: int. Total number of reads. max_allowed_reads: int. The maximum value allowed for n_total after rescaling, if necessary. Returns: New values for n_ref_reads and n_total_reads. """ if n_total_reads > max_allowed_reads: ratio = n_ref_reads / (1.0 * n_total_reads) n_ref_reads = int(math.ceil(ratio * max_allowed_reads)) n_total_reads = max_allowed_reads return n_ref_reads, n_total_reads
d09b343cee12f77fa06ab467335a194cf69cccb4
6,521
def load_dict(path): """ Load a dictionary and a corresponding reverse dictionary from the given file where line number (0-indexed) is key and line string is value. """ retdict = list() rev_retdict = dict() with open(path) as fin: for idx, line in enumerate(fin): text = line.strip() retdict.append(text) rev_retdict[text] = idx return retdict, rev_retdict
31a67c2a28518a3632a47ced2889150c2ce98a78
6,525
def get_square(array, size, y, x, position=False, force=False, verbose=True): """ Return an square subframe from a 2d array or image. Parameters ---------- array : 2d array_like Input frame. size : int Size of the subframe. y : int Y coordinate of the center of the subframe (obtained with the function ``frame_center``). x : int X coordinate of the center of the subframe (obtained with the function ``frame_center``). position : bool, optional If set to True return also the coordinates of the bottom-left vertex. force : bool, optional Size and the size of the 2d array must be both even or odd. With ``force`` set to True this condition can be avoided. verbose : bool optional If True, warning messages might be shown. Returns ------- array_out : array_like Sub array. y0, x0 : int [position=True] Coordinates of the bottom-left vertex. """ size_init = array.shape[0] # assuming square frames if array.ndim != 2: raise TypeError('Input array is not a 2d array.') if not isinstance(size, int): raise TypeError('`Size` must be integer') if size >= size_init: # assuming square frames msg = "`Size` is equal to or bigger than the initial frame size" raise ValueError(msg) if not force: # Even input size if size_init % 2 == 0: # Odd size if size % 2 != 0: size += 1 if verbose: print("`Size` is odd (while input frame size is even). " "Setting `size` to {} pixels".format(size)) # Odd input size else: # Even size if size % 2 == 0: size += 1 if verbose: print("`Size` is even (while input frame size is odd). " "Setting `size` to {} pixels".format(size)) else: # Even input size if size_init % 2 == 0: # Odd size if size % 2 != 0 and verbose: print("WARNING: `size` is odd while input frame size is even. " "Make sure the center coordinates are set properly") # Odd input size else: # Even size if size % 2 == 0 and verbose: print("WARNING: `size` is even while input frame size is odd. " "Make sure the center coordinates are set properly") # wing is added to the sides of the subframe center wing = (size - 1) / 2 y0 = int(y - wing) y1 = int(y + wing + 1) # +1 cause endpoint is excluded when slicing x0 = int(x - wing) x1 = int(x + wing + 1) if y0 < 0 or x0 < 0 or y1 > size_init or x1 > size_init: # assuming square frames raise RuntimeError('square cannot be obtained with size={}, y={}, x={}' ''.format(size, y, x)) array_out = array[y0: y1, x0: x1].copy() if position: return array_out, y0, x0 else: return array_out
8d83d4d16241e118bbb65593c14f9f9d5ae0834c
6,530
import json def read_json(json_file): """ Read input JSON file and return the dict. """ json_data = None with open(json_file, 'rt') as json_fh: json_data = json.load(json_fh) return json_data
4e1ea153d040ec0c3478c2d1d3136eb3c48bfe1c
6,531
def alt_or_ref(record, samples: list): """ takes in a single record in a vcf file and returns the sample names divided into two lists: ones that have the reference snp state and ones that have the alternative snp state Parameters ---------- record the record supplied by the vcf reader samples: list list of sample names Returns ------- ref_group, alt_group : list lists of samples divided by ref or alt snp state """ tracker = 0 ref_group = [] alt_group = [] for call in record.calls: state = int(call.data.get('GT')) sample_name = samples[tracker] if state == 0: ref_group.append(sample_name) elif state == 1: alt_group.append(sample_name) else: print("there is a problem reading the state information") raise SystemExit(0) tracker += 1 return ref_group, alt_group
abaccfeef02ee625d103da88b23fce82a40bc04c
6,534
def is_const_component(record_component): """Determines whether a group or dataset in the HDF5 file is constant. Parameters ---------- record_component : h5py.Group or h5py.Dataset Returns ------- bool True if constant, False otherwise References ---------- .. https://github.com/openPMD/openPMD-standard/blob/latest/STANDARD.md, section 'Constant Record Components' """ return "value" in record_component.attrs.keys()
4adb2ff7f6fb04086b70186a32a4589ae9161bb5
6,535
def compat(data): """ Check data type, transform to string if needed. Args: data: The data. Returns: The data as a string, trimmed. """ if not isinstance(data, str): data = data.decode() return data.rstrip()
51d2d37b427e77b038d8f18bebd22efa4b4fdcce
6,541
def rsa_decrypt(cipher: int, d: int, n: int) -> int: """ decrypt ciphers with the rsa cryptosystem :param cipher: the ciphertext :param d: your private key :param n: your public key (n) :return: the plaintext """ return pow(cipher, d, n)
33822a0a683eca2f86b0e2b9b319a42806ae56cc
6,542
import yaml def config_get_timesteps(filepath): """Get list of time steps from YAML configuration file. Parameters ---------- filepath : pathlib.Path or str Path of the YAML configuration file. Returns ------- list List of time-step indices (as a list of integers). """ with open(filepath, 'r') as infile: config = yaml.safe_load(infile)['parameters'] config.setdefault('startStep', 0) nstart, nt, nsave = config['startStep'], config['nt'], config['nsave'] return list(range(nstart, nt + 1, nsave))
8a51e1437edbf2d73884cb633dbf05e9cfe5a98d
6,543
from typing import List from typing import Tuple def _broads_cores(sigs_in: List[Tuple[str]], shapes: Tuple[Tuple[int, ...]], msg: str ) -> Tuple[List[Tuple[int, ...]], List[Tuple[int, ...]]]: """Extract broadcast and core shapes of arrays Parameters ---------- sigs_in : Tuple[str, ...] Core signatures of input arrays shapes : Tuple[int, ...] Shapes of input arrays msg : str Potential error message Returns ------- broads : List[Tuple[int, ...]] Broadcast shape of input arrays cores : List[Tuple[int, ...]] Core shape of input arrays Raises ------ ValueError If arrays do not have enough dimensions. """ dims = [len(sig) for sig in sigs_in] broads, cores = [], [] if any(len(shape) < dim for shape, dim in zip(shapes, dims)): raise ValueError('Core array does not have enough ' + msg) for shape, dim in zip(shapes, dims): if dim: broads.append(shape[:-dim]) cores.append(shape[-dim:]) else: broads.append(shape) cores.append(()) return broads, cores
228cbe06e4bc1e092cf92034255bfd60f01664c1
6,545
def cal_rank_from_proc_loc(pnx: int, pi: int, pj: int): """Given (pj, pi), calculate the rank. Arguments --------- pnx : int Number of MPI ranks in x directions. pi, pj : int The location indices of this rank in x and y direction in the 2D Cartesian topology. Returns ------- rank : int """ # pylint: disable=invalid-name return pj * pnx + pi
97146de9f69dd2f62173c19dfdb98d8281036697
6,549
def filter_matches(matches, threshold=0.75): """Returns filterd copy of matches grater than given threshold Arguments: matches {list(tuple(cv2.DMatch))} -- List of tupe of cv2.DMatch objects Keyword Arguments: threshold {float} -- Filter Threshold (default: {0.75}) Returns: list(cv2.DMatch) -- List of cv2.DMatch objects that satisfy ratio test """ filtered = [] for m, n in matches: if m.distance < threshold * n.distance: filtered.append(m) return filtered
c2cbec1da42d96575eb422bfdda6a1351e24508b
6,553
import string import random def createRandomStrings(l,n,chars=None,upper=False): """create list of l random strings, each of length n""" names = [] if chars == None: chars = string.ascii_lowercase #for x in random.sample(alphabet,random.randint(min,max)): if upper == True: chars = [i.upper() for i in chars] for i in range(l): val = ''.join(random.choice(chars) for x in range(n)) names.append(val) return names
678b5aeb3cc98ae2b47822500fcbaff05081058a
6,554
def get_previous_quarter(today): """There are four quarters, 01-03, 04-06, 07-09, 10-12. If today is in the last month of a quarter, assume it's the current quarter that is requested. """ end_year = today.year end_month = today.month - (today.month % 3) + 1 if end_month <= 0: end_year -= 1 end_month += 12 if end_month > 12: end_year += 1 end_month -= 12 end = '%d-%02d-01' % (end_year, end_month) begin_year = end_year begin_month = end_month - 3 if begin_month <= 0: begin_year -= 1 begin_month += 12 begin = '%d-%02d-01' % (begin_year, begin_month) return begin, end
4175c80d2aa75c0e3e02cdffe8a766c4a63686d0
6,555
def get_payload(address): """ According to an Address object, return a valid payload required by create/update address api routes. """ return { "address": address.address, "city": address.city, "country": str(address.country), "first_name": address.first_name, "last_name": address.last_name, "title": address.title, "postcode": address.postcode, }
34fde5090aae774a24a254ea7dd7f03cc0f784be
6,556
import torch def string_to_tensor(string, char_list): """A helper function to create a target-tensor from a target-string params: string - the target-string char_list - the ordered list of characters output: a torch.tensor of shape (len(string)). The entries are the 1-shifted indices of the characters in the char_list (+1, as 0 represents the blank-symbol) """ target = [] for char in string: pos = char_list.index(char) + 1 target.append(pos) result = torch.tensor(target, dtype=torch.int32) return result
eb6c7fcccc9802462aedb80f3da49abec9edc465
6,562
def _add_sld_boilerplate(symbolizer): """ Wrap an XML snippet representing a single symbolizer in the appropriate elements to make it a valid SLD which applies that symbolizer to all features, including format strings to allow interpolating a "name" variable in. """ return """ <StyledLayerDescriptor version="1.0.0" xmlns="http://www.opengis.net/sld" xmlns:ogc="http://www.opengis.net/ogc" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/sld http://schemas.opengis.net/sld/1.0.0/StyledLayerDescriptor.xsd"> <NamedLayer> <Name>%(name)s</Name> <UserStyle> <Name>%(name)s</Name> <Title>%(name)s</Title> <FeatureTypeStyle> <Rule> """ + symbolizer + """ </Rule> </FeatureTypeStyle> </UserStyle> </NamedLayer> </StyledLayerDescriptor> """
971199333570d5bc7baefec88f35b92922ef6176
6,564
def sequence_names_match(r1, r2): """ Check whether the sequences r1 and r2 have identical names, ignoring a suffix of '1' or '2'. Some old paired-end reads have names that end in '/1' and '/2'. Also, the fastq-dump tool (used for converting SRA files to FASTQ) appends a .1 and .2 to paired-end reads if option -I is used. """ name1 = r1.name.split(None, 1)[0] name2 = r2.name.split(None, 1)[0] if name1[-1:] in '12' and name2[-1:] in '12': name1 = name1[:-1] name2 = name2[:-1] return name1 == name2
645ac09011cc4b94c5b6d60bf691b6b1734d5b6b
6,565
def _check_type(value, expected_type): """Perform type checking on the provided value This is a helper that will raise ``TypeError`` if the provided value is not an instance of the provided type. This method should be used sparingly but can be good for preventing problems earlier when you want to restrict duck typing to make the types of fields more obvious. If the value passed the type check it will be returned from the call. """ if not isinstance(value, expected_type): raise TypeError("Value {value!r} has unexpected type {actual_type!r}, expected {expected_type!r}".format( value=value, expected_type=expected_type, actual_type=type(value), )) return value
a18ecfe9d63e6a88c56fc083da227a5c12ee18db
6,570
def addCol(adjMatrix): """Adds a column to the end of adjMatrix and returns the index of the comlumn that was added""" for j in range(len(adjMatrix)): adjMatrix[j].append(0) return len(adjMatrix[0])-1
29ee11953cbdb757e8ea80e897751059e42f1d90
6,572
def _compound_register(upper, lower): """Return a property that provides 16-bit access to two registers.""" def get(self): return (upper.fget(None) << 8) | lower.fget(None) def set(self, value): upper.fset(None, value >> 8) lower.fset(None, value) return property(get, set)
00f315cc4c7f203755689adb5004f152a8b26823
6,577