content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def key_set(d): """A set of all the keys of a dict.""" return set(d.iterkeys())
e5e6ad8d1ad25003689d5a1135c2bd9919ae7729
694,563
def gimmick(message): """Detect if a message is the result of a gib gimmick.""" if message is None: return False if message.lower().count("oob") > 3: return True if message.lower().count("ob") > 4: return True if message.isupper(): return True return False
91f8ffa77e8ddddeb7b7de2b39809b964ffb502b
694,564
import yaml def load_yaml(data): """Parse a unicode string containing yaml. This calls ``yaml.load(data)`` but makes sure unicode is handled correctly. See :func:`yaml.load`. :raises yaml.YAMLError: if parsing fails""" class MyLoader(yaml.SafeLoader): def construct_yaml_str(self, node)...
f55e144582707d603d263066ef3555049d2ea377
694,568
from typing import Dict from typing import List def process_group_mappings( group_mapping_config: Dict[str, dict], sso_attributes: dict, groups: List[str] ): """Processes the groups from the mapping rule config into discourse compatible formats Args: group_mapping_config (Dict[str, dict]): Predef...
53643ab55607837ce04ce4a7a3637b558780fd08
694,573
def get_literal_type(value): """Get the data type :param value: The data :return: The data type as a string :rtype: str """ return type(value).__name__
ed0fe2541f2439f98be14345bc622c9d49b3165b
694,575
import yaml def parsed_site_config(site_config_yml): """Fixture that returns the parsed contents of the example site config YAML file in the resource directory""" return yaml.load(site_config_yml, Loader=yaml.SafeLoader)
71c692dc80cb631d813bf9e53d98b0e1cd9e5a9d
694,576
import inspect import six def _GetArgSpecFnInfo(fn): """Gives information pertaining to computing the ArgSpec of fn. Determines if the first arg is supplied automatically when fn is called. This arg will be supplied automatically if fn is a bound method or a class with an __init__ method. Also returns the...
939d7e0a5f49f317d881638fd77be26f379f5e9a
694,579
def gradezero(evtdata): """ Only accept counts with GRADE==0. Parameters ---------- evtdata: FITS data class This should be an hdu.data structure from a NuSTAR FITS file. Returns ------- goodinds: iterable Index of evtdata that passes the filtering. """...
370bbf16b25d9543b7e485f0e366b709d6261dfb
694,584
def exists_db(connection, name): """Check whether a database exists. :param connection: A connection :param name: The name of the database :returns: Whether the db exists :rtype: bool """ exists = connection.execute("SELECT 1 FROM pg_database WHERE datname = {}".format(name)).first() co...
2a729b85cbf9e9cdc30970bcaa4258a7ff8a97fb
694,586
def _ggm_qcondwait_whitt_ds3(cs2): """ Return the approximate E(V^3)/(EV)^2 where V is a service time; based on either a hyperexponential or Erlang distribution. Used in approximation of conditional wait time CDF (conditional on W>0). Whitt refers to conditional wait as D in his paper: See Whitt, ...
fb6f4cadafeae2f3cb29200a4ae3402a0317c63a
694,587
import re import click def validate_mfa_device_name(ctx, param, value): """Validates a virtual MFA device name.""" try: if not all([re.match(r"[\w+=/:,.@-]+", value), 9 <= len(value) <= 256]): raise ValueError(value) return value except ValueError: click.echo('Invalid d...
be3801383ebe2e4c2aed42b2e29601987dffc283
694,591
import json def write_to_json_file(obj, filename): """ Write on file filename the object in JSON format :param obj: object to be written on the JSON file :param filename: filename to be used to store the obj :return: success (bool) """ f = open(filename, "w") try: json.dump(o...
c074e379c51b0cc3468f812552ee3176e64eda51
694,597
def orbital_eccentricity(t: float) -> float: """ Calculate the eccentricity of earth's orbit around the sun. Parameters: t (float): The time in Julian Centuries (36525 days) since J2000.0 Returns: float: The earth's orbital eccentricity at the given time """ # t must be in the ...
d971c059259c875b00041a7cd558af628af1df09
694,598
def tagsAssoPerson(cnx,person,domain): """ Function to determine tags related to a person in the given domain :param cnx: connection object :param person: user with whom the tags are associated :param domain: domain id of the desired topic :return: list of tags associated with the user """ ...
188363fdee34a1ccbc94941e5fdb60dcbc529b3a
694,601
def type_prefix(typ) -> bytes: """ Return the prefix string for the given type. The prefix determine the type of the expected object. """ return b'o'
852d5802e912d0efd685e99c581e11670674d23e
694,602
def update_grad_w(grad, grad_old, grad_new): """Update the global gradient for W Parameters ---------- grad: theano tensor The global gradient grad_old: theano tensor The previous value of the local gradient grad_new: theano tensor The new version of the local gradient...
74015b8987fa7af0bc6bbb4d9de3d96c1d83b5d8
694,608
def product(list): """ Returns a product of a List :param list: :return: """ prod = 1 for e in list: prod = prod * e return prod
900ff8b30be04a0f6e440fa47ece772846c890e3
694,609
def map_indices_py(arr): """ Returns a dictionary with (element, index) pairs for each element in the given array/list """ return dict([(x, i) for i, x in enumerate(arr)])
d045d57ec95be50f2c1ab3f46e22b93ab3568637
694,611
import requests def _download_collection(url): """ Download all pages in a paginated mgnify data collection This returns a single structure with all entries appended to result['data'] """ result = {'data': []} while url is not None: resp = requests.get(url, params={'page_size': 100}).j...
31c5af3480a40f0cc700cfb81235cca7ab094469
694,616
def has_function(faker, key): """ helper function to check if a method is available on an object""" return hasattr(faker, key)
c57020222be5f7a336f2773a2e80a85c4eac867f
694,619
def outlierStats(outlier_list): """Takes a list of outliers and computes the mean and standard deviation""" try: outlierMean = outlier_list.mean() outlierStdev = outlier_list.std() return outlierMean, outlierStdev except TypeError : explanation = "Cannot compute statistics on...
98aeec98faa3eff4ce576e9ad4a3331f54d7a25d
694,620
def gcd(x, y): """greatest common divisor of x and y""" while y: x, y = y, x % y return x
211d6aeab23734a944a606b2a744bd4ab682a166
694,623
def _encode_for_display(text): """ Encodes strings so they can display as ASCII in a Windows terminal window. This function also encodes strings for processing by xml.etree.ElementTree functions. Returns an ASCII-encoded version of the text. Unicode characters are converted to ASCII placeholde...
59fa895204b764a105f0cc73f87f252c64e62871
694,624
def d_theta_parabolic(C, k, clk): """ A downwards concave parabola of form: f(x) = -c(x)(x - a) Here: C -> x k -> c clk -> a """ return -1 * k * C * (C - clk)
ac520d33bf11ba20e1a2f72d298a2a496ec00ca7
694,625
def get_blueprints(bot, base): """Gets the blueprints associated with the given base. Also returns whether or not the command is a shortcut. If the base is not found in the commands dictionary, returns (None, None) """ try: command = bot.commands[base] is_shortcut = base in command....
48b7a5bad96f64825cfe6178711d8714514d5bad
694,626
def is_good_response(res, content_type='html'): """ Returns True if the response seems to be Content type (default html), False otherwise. """ content_type = res.headers['Content-Type'].lower() return (res.status_code == 200 and content_type is not None and content_type.find(content_type) > -1)
d48ad85a7f8790be6e037d978e84756fa7091689
694,628
def can_infer(num_sensed_blocked: int, num_confirmed_blocked: int, num_sensed_unblocked: int, num_confirmed_unblocked: int): """ check whether we can infer or not from the current set of variables :param num_sensed_blocked: number of sensed blocks :param num_confirmed_blocked: number of co...
49eea4125ffb970c89f223afd21e3e7dd3c870d7
694,630
def get_contacts(filename): """ Return two lists names, emails containing names and email addresses read from a file specified by filename. """ names = [] emails = [] lineofdata = [] # print(names) # print(emails) with open(filename, mode='r', encoding='utf-8') as contacts_file:...
e3f3b862fca1e290c2b353ba440913479e1265c9
694,631
def _int32_to_bytes(i): # NOTE: This course is done on a Mac which is little-endian """Convert an integer to four bytes in little-endian format.""" # &: Bitwise 'and' # >>: Right shift return bytes((i & 0xff, i >> 8 & 0xff, i >> 16 & 0xff, ...
61606a87d7f074117637b3a322dcded43a514cd0
694,632
import math def calculateCents(referenceScale, newScale): """Takes two arrays of frequencies and calculates the cents difference. Returns 8 values in a list.""" centsList = [] for i in range(len(referenceScale)): ratio = newScale[i] / referenceScale[i] cents = round(((math.log(ratio) / mat...
94796baa067806b2a15fd536798adf84f5360901
694,635
def usage(err=''): """ Prints the Usage() statement for the program """ m = '%s\n' %err m += ' Default usage is to seach the Scan the currect directory for PE checkpoints.\n' m += ' It will look for linked CRs in a peer directory' m += ' create_pe_load \n' return m
3b9e7b34eb7b1072f02f0678dd505961bdf9aa39
694,636
def is_float(n: str) -> bool: """ Checks if a string is a valid float Parameters ---------- n: str The string to check. Returns ------- bool """ try: float(n) return True except ValueError: return False
dcbcdaafc857f69bcc3b9cf728a230088adf84b7
694,638
import zipfile import pathlib async def make_zip_archive( input_directory_path: str, output_file_path: str, ) -> dict: """ Creates zip file of a directory. Parameters ---------- input_directory_path : str Path to directory to be archived output_file_path : str Path where t...
a27729eeec533e6978047268e62b644d3ce9a038
694,639
def flowDiff(graph1, graph2): """ Return the difference between the flows of two graphs. Parameters ---------- graph1: netwrorkx obj graph2: networkx obj Returns ------- a dictionary with name od edge and diff in flows. graph1-graph2 """ flowDiff_ = {} for edge in gra...
65d7392607b01f935dd6fe2e282083530a3513d3
694,640
def tryint(s): """ try casting s to an int. if exception occurs, return s unchanged """ try: return int(s) except ValueError: return s
8a4b221a2930494a631dcd23544176d47f4ef6e0
694,646
import mimetypes def guess_mimetype(resource_path): """ Guesses the mimetype of a given resource. Args: resource_path: the path to a given resource. Returns: The mimetype string. """ mime = mimetypes.guess_type(resource_path)[0] if mime is None: return "applicati...
66f2554387966028a4ab1cf1bf3715878b3dc246
694,648
def hex_8bit(value): """Converts 8bit value into bytearray. args: 8bit value returns: bytearray of size 1 """ if value > 0xff or value < 0: raise Exception('Sar file 8bit value %s out of range' % value) return value.to_bytes(1, 'little')
597ecb6c9a499c7a5959f1f8ddd7300b78b06e9a
694,649
def lower(s): """ Returns the string `s` converted to lowercase. """ return s.lower()
e953cb79ee371128952a6ad7a0b7c91afc08c8b6
694,651
def episode_title(self): """Return episode title.""" return self.media_metadata.get("subtitle")
94b5be128e44334efe5f3c141e0b9dbc1bc10c3d
694,654
def weed_out_short_notes(pairs, **kwargs): """Remove notes from pairs whose duration are smaller than the threshold""" duration_threshold = kwargs.get('duration_threshold', 0.25) return [(n, d) for (n, d) in pairs if d > duration_threshold]
de9caea78313e4f8d77c16ed17ae885d4bed9e33
694,657
def datetime_format(datetime_obj, fmtstring = '%Y-%m-%d'): """ A function to string format a datetime.datetime object. """ return datetime_obj.strftime(fmtstring)
a64ce81cb28c59489bff3d57751feebb818e04c5
694,658
def start_ea(obj): """ Return start ea for supplied object. :param obj: Object to retrieve start ea. :return: start ea. """ if not obj: return None try: return obj.startEA except AttributeError: return obj.start_ea
fc00c290d493ec762f165c6ff657716c8218fab3
694,660
def has_tx_succeeded(tx_receipt): """ We check tx has succeeded by reading the `status` on the `tx_receipt` More info: https://docs.pantheon.pegasys.tech/en/latest/Reference/JSON-RPC-API-Objects/#transaction-receipt-object """ status = tx_receipt.get("status", None) if status == 1: retur...
3b9e54efd1b269a835b4829adeca7afe7cfe51a9
694,661
def derive_nums_from_text(comments, regex): """Given a string, derive all related case nums using given regexes""" return set(int(num) for num in regex.findall(comments) if num)
76d1a69acefaeba64a9be9763f15f2da24652bea
694,662
def _evaluate_cubic_spline_derivative_one(x, y, r, t): """Evaluate one point on the first derivative of the cubic spline. Parameters: x : rank-1 np.array of np.float64, length 2 data x coordinates y : rank-1 np.array of np.float64, length 2 data y coordinates r :...
ef9aa1454c412f2ec66a112d367b5171d9de4e35
694,666
import pickle def get_challenges_for_user_id(database, user_id, ctf_channel_id): """ Fetch a list of all challenges a user is working on for a given CTF. Return a list of matching Challenge objects. """ ctfs = pickle.load(open(database, "rb")) ctf = ctfs[ctf_channel_id] challenges = [] ...
bd2c048ca88aad630bfe9fda7c37924cf93c611b
694,667
def make_gmm_unaries(X, fg_gmm, bg_gmm): """ Make unaries by log probability under GMM. Take X: data in N x K ndarray where N is no. samples and K is no. features fg_gmm, bg_gmm: fitted sklearn.mixture.gmm Give fg_unary, bg_unary: log probabilities under the fg and bg gmms resp. """ fg_un, _ =...
d69b942d465262736c3d209be7e2de9a4ce2cf4b
694,669
def d(value: bytes) -> str: """ Decode a bytestring for interpolating into an error message. """ return value.decode(errors="backslashreplace")
5b37b195cc5a462c8eb665b0fd77cbe823f57e00
694,672
def impact_seq(impact_list): """String together all selected impacts in impact_list.""" impact_string = '' connector = '-' for impact in impact_list: impact_string += connector + impact.iname.strip() return impact_string
335a879c17e263690744c947b11be872c5ccf663
694,673
def url_to_path(url: str): """ Convert URL to path """ return url.replace("://", "___").replace(".", "__").replace("/", "_")
518fa3647d53838a9f7a68e175778f191cc82896
694,677
import requests def verify_physionet_credentials(username, password): """Returns True if the username and password are valid for the physionet.org website.""" url = "https://physionet.org/works/MIMICIIIClinicalDatabase/files/" r = requests.get(url, auth=(username, password)) return True if r.status_co...
2821de8abf6cb1d0f9363bbb0440f9a1ae65bc99
694,680
def _find_start_entry(line, n): """Find the starting character for entry ``n`` in a space delimited ``line`` (PRIVATE). n is counted starting with 1. The n=1 field by definition begins at the first character. Returns ------- starting character : str The starting character for entry ``n...
60b609b099bae2aa6e891008a1e49c7083c6de32
694,681
def startswith_whitespace(text): """Check if text starts with a whitespace If text is not a string return False """ if not isinstance(text, str): return False return text[:1].isspace()
4c1acdfea37fc1ffdcde13fb6c68567489d91b30
694,683
def triplet(n): """Find the Pythagorean triplet who's sum equals a given number.""" for c in range(n - 3, 1, -1): for b in range(c - 1, 1, -1): a = (c**2 - b**2)**.5 if a + b + c == n: return [c, b, int(a)] return False
0f4121ac169d8830a776f4fb44d9716077288cb8
694,689
def tlv_file_xml_mapped(tlv_data_xml_mapped, tmp_path): """Return the path to an mapped XML file containing the test tree.""" path = tmp_path / "expected_mapped.xml" path.write_bytes(tlv_data_xml_mapped) return path
314a0a55112259940b6dcbd7d72beb69da400134
694,698
def bissexto(ano): """Verifica se um ano é bissexto. Retorna True se ano for bissexto ou False caso contrário. Definição de ano bissexto: Um ano é bissexto se for divisível por 400 ou então se for divisível por 4 e, ao mesmo tempo, não for divisível por 100. """ return ano % 400 == 0 or ano...
388880697cdebe9c29b8815edb99b9fda80a2210
694,701
import re def find_all(item, items, regex=False, regex_flags=None): """ Finds the indexes and values for all values matching a given item. :param item: the value (or pattern) to match/find. :param items: an iterable of items to match against. :param regex: If True, item will be treated as a regex...
bf9e78ef94261c0ee88162e6a1be85a8cdb1dd54
694,703
def mark_doc(doc, wids, mark=None, pos=None): """ Given a list of words and a set of word positions, mark the words in those positions. :param list doc: a list of words (strings) :param set wids: the positions of the words to be marked :param string mark: a string that sets the mark that will be app...
481fb2d4ca8828181288d776c6f4b73e82f0443a
694,706
def unknown_char(char_name, id_ep): """Transforms character name into unknown version.""" if "#unknown#" in char_name:#trick when re-processing already processed files return char_name return f"{char_name}#unknown#{id_ep}"
061683efd275335e58129225fe4bc9dabc044c9b
694,707
def _copy_list(seq): """Recursively copy a list of lists""" def copy_items(seq): for item in seq: if isinstance(item, list): yield list(copy_items(item)) else: yield item return list(copy_items(seq))
2e179ed338bf9b5417772509ca27a84608c240d9
694,708
def calculate_occlusion(ray, obj, light, objects): """ Calculate if there is an object between the light and object Args: ray: A ray starting in the hit point with direction to the light obj: The object where the hit point is light: A source of light to calculate if it's occluded ...
c15acf785f8baf72da64307380cd36d7de6b6ef8
694,713
def get_integer(dictionary, key): """Gets value of a key in the dictionary as a integer. Args: dictionary (dict): A dictionary. key (str): A key in the dictionary. Returns: A integer, if the value can be converted to integer. Otherwise None. """ val = dictionary.get(key) try: ...
503f168ff6ecac637fde28dae3c6fc33554b5e26
694,715
from typing import Tuple def left(x: int, y: int) -> Tuple[int, int]: """Move one step to the left""" return x - 1, y
ad16a27149980c532a72970fade1b09843168a82
694,716
import re def extract_bonds_and_angle_info(force_field): """ Given a force field files, extracts the values use for equilibrium bond lengths and angles. """ info = {"bonds":{}, "angles": {}} bond_regex = r"^(.{2}-.{2})\s+\S+\w+\s+(\S+)" angle_regex = r"^(.{2}-.{2}-.{2})\s+\S+\w+\s+(\S+...
ee314b68f9e2dfecb3b94c4493594adc30668d3e
694,717
def ymd2jd(year, month, day): """ Converts a year, month, and day to a Julian Date. This function uses an algorithm from the book "Practical Astronomy with your Calculator" by Peter Duffet-Smith (Page 7) Parameters ---------- year : int A Gregorian year month : int A Gre...
7f93c1eef14d3e75764329748d4646e41ba6fea9
694,718
def _get_default_var_dicts_planetos(dataset): """ Returns dictionary mapping PlanetOS variable names to OpenOA variable names for a particular dataset Args: dataset (:obj:`string`): Dataset name ("merra2" or "era5") Returns: :obj:`dict`: Dictionary mapping reanalysis variable names fro...
b93e2b5655003ea81900e013d3c24545baae690c
694,722
from typing import Union from typing import List from typing import Any from typing import Dict def convert_to_schema(schema: Union[List[Any], Dict[str, Any], Any]) -> Dict[str, Any]: """Recursively convert a json-like object to OpenAPI example response.""" if isinstance(schema, list): return { ...
dbb5010b50f81bb86d668850b70631cad34c9407
694,723
def match_any_re(regex_list, value): """Given a list of pre-compiled regular expressions, return the first match object. Return None if there's no Match""" for regex in regex_list: match = regex.fullmatch(value) if match: return match.groupdict()
fcb1ce9530ac990dd1048eb62883adcf9a06ab6a
694,730
def get_album_from_html(self, html): """Scrapes the html parameter to get the album name of the song on a Genius page""" parse = html.findAll("span") album = '' for i in range(len(parse)): if parse[i].text == 'Album': i += 1 album = parse[i].text.strip() break...
a7cf940227dfd2dd9f2c7fe44073ef02489e6db1
694,734
def identity(mask): """ This is identity function that can be used as an argument of functions :func:`set_encoder` and :func:`set_decoder`. :param mask: input mask :type mask: numpy.ndarray :return: the same mask :rtype: numpy.ndarray Example: .. code-block:: python ...
b2082ffb09501a393776e3a1b960b4b532f3e465
694,735
import json async def assert_api_post_response(cli, path: str, payload: object = None, status: int = 200, expected_body: object = None): """ Perform a POST request with the provided http cli to the provided path with the payload, asserts that the status and data received are correct. Expectation is th...
a09185ff957446ce99cb1bcd93d5699890b72b52
694,736
def diffangles(a1, a2): """ Difference between two angles in 0-360 degrees. :param a1: angle 1 :param a2: angle 2 :return: difference """ return 180 - abs(abs(a1 - a2) - 180)
8f17b4f1bdd822082b552aa14907bcdb4b185a4f
694,737
def split_fqn(title): """ Split fully qualified name (title) in name and parent title """ fqn = title.split('/') if len(fqn) > 1: name = fqn.pop() return (name, '/'.join(fqn)) else: return (title, None)
5595cbc5bf312f4eedf1987925ed08ae0f840087
694,741
def make_dict_from_csv(fn): """ convert listing of partial permutations with multiplicity into dict input file should have one line for each "type" of ballot - first entry is number of ballots of this type - successive entries are ranked candidates (no non-votes or repeats) - all candidates are ...
2ca1dd45b7d92f036462753c5016983eea66dcd4
694,742
def _replace_special_characters(str_special_chars): """ Replaces special characters in a string with their percent-encoded counterparts ':' -> '%3A' '/' -> '%2F' ',' -> '%2C' (e.g. "1/1/9" -> "1%2F1%2F9") :param str_special_chars: string in which to substitute characters :re...
c488f10cd817673e853fce1651d6444e2fa2a97b
694,744
def bit_or(evaluator, ast, state): """Evaluates "left | right".""" res = evaluator.eval_ast(ast["left"], state) | evaluator.eval_ast(ast["right"], state) return res
c16ad4fd4daccf2d0f05785b7cc4032ff1b78c18
694,747
def is_snapshot_task_running(vm): """Return True if a PUT/POST/DELETE snapshot task is running for a VM""" snap_tasks = vm.get_tasks(match_dict={'view': 'vm_snapshot'}) snap_tasks.update(vm.get_tasks(match_dict={'view': 'vm_snapshot_list'})) return any(t.get('method', '').upper() in ('POST', 'PUT', 'DE...
26088c4583d35e5d9b069b7f5046301f5e127feb
694,750
from typing import Dict from typing import Any from typing import List def get_region_sizes(settings: Dict[str, Any]) -> List[int]: """ Compute size of each layer in network specified by `settings`. """ dim = settings["num_tasks"] + settings["obs_dim"] region_sizes = [] for region in range(settings["...
c8a1880ff67bdf3bc2658162cd6827927e9c4737
694,752
def get_classification_task(graphs): """ Given the original data, determines if the task as hand is a node or graph classification task :return: str either 'graph' or 'node' """ if isinstance(graphs, list): # We're working with a model for graph classification return "graph" else: ...
e64620b31e68631d883e8e3d635d2147fe85cf78
694,753
import unicodedata def code_points(text, normalize=None): """Return the sequence of unicode code points as integers If normalize is not None, first apply one of the unicode normalization schemes: NFC, NFD, NFKC, NFKD. More details on normalization schemes in: https://docs.python.org/3/library/u...
a01d39b2272803b75e567d190858301db9eb9251
694,754
def find_unique_name(name, names, inc_format='{name}{count:03}', sanity_count=9999999): """ Finds a unique name in a given set of names :param name: str, name to search for in the scene :param names: list<str>, set of strings to check for a unique name :param inc_format: str, used to increment the n...
6b48426df7340f88f657097bfa8d35e32cd790f6
694,756
def get_nextupsegs(graph_r, upsegs): """Get adjacent upsegs for a list of segments as a single flat list. Parameters ---------- graph_r : dict Dictionary of upstream routing connections. (keys=segments, values=adjacent upstream segments) upsegs : list List of segments ...
cc38dd78bd0af8cce2c0a96106bea58d1e9d0b17
694,757
def build_texts_from_gems(keens): """ Collects available text from each gem inside each keen in a list and returns it :param keens: dict of iid: keen_iid :return: texts: dict of iid: list of strings with text collected from each gem. """ texts = {} for keen in keens.values(): for gem...
b9b94f4a1035f03746bd3b18755c02b19a97b27b
694,759
def filterResultsByRunsetFolder(runSets, form): """ Filters out results that don't have the specified runsetFolder name """ ret = [] for runset in runSets: if runset.runsetFolder == form['runset'].value: ret.append(runset) return ret
a9416fa8f96aa2dc370c23260f65bfb53114e09a
694,760
import csv def read_list( csvFile ): """Returns a list which has been stored as a csv file""" with open( csvFile ) as csvFile: reader = csv.reader( csvFile, quotechar='|' ) out = [ ] for row in reader: out += row return out
9fcb5b01496b39915e0169d0a19efc91a779aaf1
694,762
def find_net(table_coordinates): """ Finding net coordinates, taking avg of x1 and x4 (mid points of table) """ top_x = table_coordinates[1][0] bottom_x = table_coordinates[4][0] avg = int((top_x+bottom_x)/2) return avg
e8d8821977362c641be0ca7621802e774caf5adf
694,771
def clamp(v, lo, hi): """Return v clamped to range [lo, hi]. >>> clamp(1, 2, 3) 2 >>> clamp(4, 0, 1) 1 >>> clamp(6, 5, 8) 6 """ assert lo <= hi if v < lo: return lo elif v > hi: return hi else: return v
5b2213be8f7ce24bfb3addb6c3ff436a62ff1dbd
694,776
def collatz_sequence(seed): """Given seed generates Collatz sequence""" sequence = [seed] counter = seed # pylint: disable=misplaced-comparison-constant while 1 != counter: # pylint: disable=misplaced-comparison-constant counter = (int(counter/2) if 0 == counter%2 else 3*counter+1) ...
37195042d6feae7d9ea26ebfea8c35a9436c8c11
694,777
import csv def loadFlags(file): """Takes in a filename/path and reads the data stored in the file. If it is a single column of data returns a 1D list, if it is multiple columns of data returns a 2D list. Note the first line is skipped as it assumes these are column labels. """ with op...
cfd48269ed94b47dfd2c12e6a7f66f8106253f15
694,779
def fopen(ref): """ Open a file and return a list of lines. """ return [i.split() for i in open(ref).readlines()]
689d74d626de2a84a1a28f219c634f3eb043ec76
694,783
import colorsys def hsl_to_rgb(hue, saturation, lightness): """Takes a colour in HSL format and produces an RGB string in the form #RRGGBB. :param hue: The Hue value (between 0 and 360). :param saturation: The Saturation value (between 0 and 100). :param lightness: The Lightness value (between 0 ...
a7d0ab91bc01c04f2ecf5afa8255f639e5758a6c
694,785
def is_overlapping(segment_time, previous_segments): """ Checks if the time of a segment overlaps with the times of existing segments. Arguments: segment_time -- a tuple of (segment_start, segment_end) for the new segment previous_segments -- a list of tuples of (segment_start, segment_end) for the...
27b817a76829eb7eba63d3fd22376e4164a7bf39
694,786
def gir_merge_dicts(user, default): """Girschik's dict merge from F-RCNN python implementation""" if isinstance(user, dict) and isinstance(default, dict): for k, v in default.items(): if k not in user: user[k] = v else: user[k] = gir_merge_dicts(us...
49196cc305c8acb454d9d3d8d9b6ddbabd67dff8
694,790
import json def ler_arquivo(local: str) -> list: """ Essa função serve para ler um arquivo JSON e devolver um dicionário :param local: str, local onde se encontra o arquivo JSON :return: list, lista de dicionário com os dados do arquivo JSON """ with open(local, encoding='UTF-8') as arquivo: ...
02f4f9460ad359939c120f605657bca6cf905a60
694,791
import re def get_derived_table(view_list): """ This function extracts the derived table clause from a view file, if it exists. :param view_list: view file broken down list :type view_list: list :return: a list of the derived table clause for a view file """ derived_list = [] for li...
1fe5546f387037ec393f8f4cfc4e86c09e9d74c3
694,792
import typing import ipaddress def format_address(address: typing.Optional[tuple]) -> str: """ This function accepts IPv4/IPv6 tuples and returns the formatted address string with port number """ if address is None: return "<no address>" try: host = ipaddress.ip_address(address...
28c735fd60f69f8bb0f038b136fc9b8d1b938a91
694,795
import json def refundCardTransactionPayload(amount, reason, merchant_refund_reference, refund_time): """ Function for constructing payload for refundCardTransaction API call. Note: All parameters are of type String unless otherwise stated below. :param amount: Integer - Amount to be refunded :pa...
6c54a5177acf1d79bc1d06e709ca9a81ffb6c9b7
694,797
def round_to(x, base=1, prec=2): """ Round to nearest base with precision. :param x: (scalar) - value to be rounded from :param base: (scalar) - value to be rounded to :param prec: (int) - number of decimal points :return rounded_val: (scalar) - rounded value """ try: return rou...
d8c041a99d948458ced6942f037592da225fa9e4
694,798
def select_sort(inputlist): """ 简单选择排序 :param inputlist: a list of number :return: the ascending list """ length = len(inputlist) for i in range(length): minimum = i for j in range(i, length): if inputlist[j] < inputlist[minimum]: minimum = j ...
c6163f0d7c0b5048c067d6f8d0adfd08bfb02728
694,799
def definir_orden_builtin(a: str, b: str, c: str) -> str: """Devuelve tres palabras en orden alfabético de izquierda a derecha. :param a: Primera palabra. :a type: str :param b: Segunda palabra. :b type: str :param c: Tercera palabra. :c type: str :return: Las tres palabras en orden alf...
7cb1a5916a2917b942121de52020c7323c695ba8
694,800