content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def _hasclass(context, *cls): """ Checks if the context node has all the classes passed as arguments """ node_classes = set(context.context_node.attrib.get('class', '').split()) return node_classes.issuperset(cls)
97c29ddfa209c69a7a78f71619023878e8ce833d
650,400
def serialize(func): """ Serialize Decorator: decorates query results serializing the result. :param func: Decorated function :return: The serializer function """ async def serializer(*args, **kwargs): """ Serializer: Calls the serialize method on a single beer or on every beer ...
6843f499678db4ed2769fa413cd0424f4db773b7
650,402
def merge_hierarchical_dicts(d1, dd): """ Sets values to d1 from dd which are not set """ if not isinstance(d1, dict) and not isinstance(dd, dict): #Arrived at a leaf return None elif isinstance(dd, dict) ^ isinstance(dd, dict): raise Exception("Config dictionary formed...
53c827eefd5497e43dbae167a7436dedda6b448d
650,403
def get_rank(raw): """Return the rank of the player.""" display_rank = None prefix = raw.get('prefix') rank = raw.get('rank') playerRank = raw.get('playerRank') if prefix: return prefix elif rank: return rank.replace('_', ' ') else: return playerRank.replace('_'...
d7316243858a51998236597bde0fdd5e1a581e7f
650,405
def sort_nodes(nodes): """Calling sorted(nodes) will fail because nodes may contain numbers, and we can't compre ints to strings. So always use this method instead of calling sorted(nodes).""" return sorted(nodes, key=lambda n: str(n))
70e21477c66eb949d95df9c4bbb1449b6dc95750
650,406
import csv from typing import OrderedDict def read_d10d11_file(path_d10file, path_d11file): """ Read the concatenated D10 and D11 files that contain the D10 and D11 inputs for all the cells. """ enc = 'iso-8859-1' # 'utf-8-sig', 'iso-8859-1', 'utf-8', 'utf-16' # ---- Read and Format D11 Fil...
d4ac8b8aedc72b3b9db29a9709277dfe98ed9a7a
650,407
import torch def _get_idx_worst(name, ref, hyp): """ Computes the batch indices for which the input metric value is worse than the current metric value. Parameters ---------- name : str 'mse', 'psnr', 'ssim', 'lpips', or 'fvd'. Metric to consider. For 'mse', 'fvd' and 'lpips', lower is be...
cdfee3950eb312ad05dc67d3b08d495a73602a85
650,408
def ms_to_time(x): """Converts and integer number of miliseconds to a time string.""" secs = x / 1000.0 s = secs % 60 m = int(secs / 60) % 60 h = int(secs / 3600) rtn = [] if h > 0: rtn.append("{0:02}".format(h)) if m > 0: rtn.append("{0:02}".format(m)) rtn.append("...
693204cec43c0681e027e8ba6881cca6435cf9da
650,409
def extract_ids(id_dict): """Extract the inner `ids` dict out of trakt JSON responses and insert them into the containing `dict`. Then return the input `dict` """ id_dict.update(id_dict.pop('ids', {})) return id_dict
b308ef38ba3948c33558d6eac9791dbff6d9421e
650,410
import glob import os def find_eo_bot_results(glob_format, paths, **kwargs): """Get a particular EO test result Parameters ---------- glob_format : `str` Formatting string for search path paths : `list` Search paths kwargs Passed to formatting string Returns -...
cae16d206bde0dd74ce58bc758ddae81c45b210a
650,411
import re def get_string_index_info(s): """ gets information from strings of the format title_index where index is a number """ file_idx_re = re.compile(r'^(?P<name>.+?)_(?P<idx>\d+)$') m = file_idx_re.match(s) idx = None underscore = '_' if m: s = m.group('name') idx = int(m.g...
f864b175be53eb774e13c692c45c3a605c7fa870
650,412
def max_iter_len(items): """ Determine the maximum length of an item within a collection of items. Args: items (iterable): The collection of items to inspect. Returns: num (int): The maximum length of the collection. """ num = 1 for val in items: try: it...
48f74c9fdd3d49fd6c557165b74e9a56f6c6c6c2
650,413
def setdefault2(d, key, value): """ >>> d = {} >>> setdefault2(d, 1, 2) 2 >>> len(d) 1 >>> setdefault2(d, 1, 2) 2 >>> len(d) 1 >>> l = setdefault2(d, 2, []) >>> len(d) 2 >>> l.append(1) >>> setdefault2(d, 2, []) [1] >>> len(d) 2 >>> setdefault2...
071b813a4dd63473079b7d3ce3e8f6a07d3f8256
650,414
def fixture_vcf_sample_id(sample_id: str) -> str: """Return a sample id that exists in the test VCF""" return sample_id
1e99d3e60f824fd988c39612a5708e78ceb351be
650,415
import numpy def yacht(): """ Yacht Hydrodynamics Data Set """ D = numpy.loadtxt(open("yacht_hydrodynamics.csv","rb"),delimiter=",",skiprows=1) X,Y = D[:,:-1],D[:,-1] return X,Y
5eae0f9d809aa271faf225370db965ba06b3fdbc
650,416
def new_dummy_vertex(vertex: int, key: int, biggest: int) -> int: """New dummy vertex ID Args: vertex: Vertex ID key: Edge key biggest: Biggest vertex ID Returns: ID of a new negative dummy vertex if key is greater than one. Otherwise return the same vertex ID as th...
d2cdd84d416fb33956792f9d47c043cd341ec190
650,417
import sys def _report_unexpected_items(items, msg): """If there are any `items`, report them using "msg" and return false""" if items: print(msg, file=sys.stderr) for item in sorted(items): print(' -', item, file=sys.stderr) return False return True
056ad549269bb913bf14f09d85979ac18d2c1688
650,418
import string def MakeValidFieldName(header): """Turn a header name into a valid bigquery field name. https://developers.google.com/bigquery/docs/tables Field names are any combination of uppercase and/or lowercase letters (A-Z, a-z), digits (0-9) and underscores, but no spaces. The first character must b...
0a0944ead63b15b6d3b7589fbd7b0390de7d61cb
650,419
import math def trailing_zeros_eff(n): """ Each 5! add one trailing zero. Note that 25! add 2 trailing zeros because 5*5 """ m = math.sqrt(n) return n // 5 + m -1
4e17df3b15b60b2157d383b4161424e8a4edeb87
650,420
def principal_form(disc): """Construct principal form for given discriminant. Follows Def. 5.4 from `Binary quadratic forms` by Lipa Long, 2019: https://github.com/Chia-Network/vdf-competition/blob/master/classgroups.pdf """ assert disc % 4 == 0 or disc % 4 == 1 k = disc % 2 f = (1, k, (k *...
22a38e48ba16ac2c937a4ba29c779c088dad8674
650,422
def valid_channel_list(): """Return valid channel list.""" return ["f451_mailgun", "f451_slack", "f451_twitter", "f451_twilio"]
f93be4604d63538148b8dc29750fe4c1f7afd438
650,423
import json def create_snippet(file_path): """ Creates a snippet of the original SQuAD data. Args: file_path: path to the original file Returns: string containing file contents """ with open(file_path) as data_file: data = json.load(data_file)['data'] out = { ...
ff8ddf1e9c6ef012871afe8bc418c8b50bb37ba1
650,424
def zoo(total_head, total_legs, animal_legs=[2, 4]): """ Find the number of kangaroo and tiger in a zoo. For example: zoo(6, 16) -> (4, 2) zoo(8, 20, [4, 2, 2]) -> (2, 0, 6) Parameters ---------- total_head: int Total number of animals total_legs: int ...
e24b678ebaea8ef78a93bbfb8abe1e98b560bb06
650,425
def split_inp(regex): """splits the regex""" list_of_op = ["*", "?", "+"] close_brac = 0 front, end, opr = None, None, None flag = False # if starting part is an square bracket if(regex[0] == "["): close_brac = regex.find("]") front = regex[:close_brac+1] end = rege...
8da108431ebd788d2c3e0c147fb631dbc0ba5f4b
650,426
def parse_text(text_to_parse): """ Function to load a file and the words indvidually while cleaning them up. This is shared with all students along with any data files to use """ return_words = [] # Now parse out each word words = text_to_parse.split(' ') for word in words: wor...
19fedf0d7bf1ccc926194b8561dae7b74deb6b59
650,427
def clean_name(string): """Clean entity/device name.""" return string.replace("-", " ").replace("_", " ").title()
780a9bca200696abe1e68ff3613ba17dde187c77
650,429
import os import toml import logging def load_toml(toml_file): """ Load a tmol file into nested dict""" # Check if file exists if not os.path.exists(toml_file): return {} # Load file try: with open(toml_file) as data_file: nested_dict = toml.load(data_file) except...
069f09aef9ea9e5561809e83e07d7de6623006c3
650,430
def session_user(db): """try to retrieve the user from the sessions table return usernick or None if no valid session is present""" count = 1 letter = '' cur = db.cursor() # retrieve user sessionid and usernick (username) from the sessions table rows = [row[0]for row in cur.execute("SEL...
c30252022753a35dc8af564f8992e74c2ffc1651
650,431
def _get_units_prod(array_in, array_out): """Helper method calculate units after a product operation Parameters ---------- array_in : np.ndarray Array before product operation array_out : np.ndarray, float Array after product operation Returns ------- ...
fedd517347cc37e4fa821ced4951c8cf2989f4ab
650,433
def UsersInvolvedInIssues(issues): """Return a set of all user IDs referenced in the issues' metadata.""" result = set() for issue in issues: result.update([issue.reporter_id, issue.owner_id, issue.derived_owner_id]) result.update(issue.cc_ids) result.update(issue.derived_cc_ids) result.update(fv....
0edf8dc760ccad66136c5bb8defb590ddc850685
650,434
import numpy as np import pandas as pd def RMSE_abs(meas,model): """ This function calculates the ABSOLUTE ROOT MEAN SQUARE ERROR of measured vs. modeled data and returns it as a Percentage [%]. RMSD=100∙〖[(1⁄(m)∙∑▒(y_i-x_i )^2 )]〗^(1⁄2)÷[(1⁄(m)∙∑▒〖x_i]〗) Parameters ---------- meas : nu...
651f138b71a76adb1e4b66dfa7801214398d40aa
650,435
def stepRK4(odefun, z, Phi, prob, alph, t0, t1): """ Runge-Kutta 4 integration scheme :param odefun: function to apply at every time step :param z: tensor nex-by-d+4, inputs :param Phi: Module, the Phi potential function :param alph: list, the 6 alpha values for the OC problem ...
d3dd609e883fc3677f2f078102308cff80422cc5
650,437
def filter_item(item): """Only return specified keys""" keys = ["display_name", "installed_version", "installed_size", "version_to_install", "installed", "note"] out = {} for key in keys: try: out[key] = item[key] # pylint: disable=pointless-except except...
a6eb4c395f12db8748e87b4c85ae575d6933ff45
650,438
def format_as_csv(ohlc_data, header=False): """Dummy header argument. Return CSV data.""" csv_data = 'dt,o,h,l,c,vol\n' for row in ohlc_data: csv_data += ('%s, %s, %s, %s, %s, %s\n' % (row[0], row[1], row[2], row[3], row[4], row[5] + row[6])) return csv_data
ef018bd2bd0e26ff063585704b7829dd30266e60
650,439
def precision(predict, truth, top_k=5): """ Args: predict (Tensor): shape (batch_size, items_total) truth (Tensor): shape (batch_size, items_total) top_k (int): Returns: output (float) """ _, predict_indices = predict.topk(k=top_k) predict, truth = predict.new_zer...
acb8c2cdeb327d91c99cbd378cdd5e12fc739133
650,441
def user_info(props): """Decorator to specify a list of properties requested about the current user""" def real_decorator(function): function.pi_api_user_info = props return function return real_decorator
423806a8ffd235a839562b1a9431f84d9596fdc1
650,442
import requests from bs4 import BeautifulSoup def getJobUrls(pageUrl,): """ 根据pageUrl,得到该page上的jobUrl列表 params: pageUrl:搜索结果的一页 """ # 用requests请求网页url r = requests.get(pageUrl) r.encoding = 'gb18030' htmlContents = r.text # 用beautifulsoup,找到岗位urls,并添加到pool中 ...
7cd191d6a5fc1e8b00f11890eacd4079b225d0ee
650,443
def _crt_non_coprime(running, a): """ Extension of the ``crt`` method of ``IntegerMod`` to the case of non-relatively prime modulus. EXAMPLES:: sage: from sage.rings.finite_rings.conway_polynomials import _crt_non_coprime sage: a = _crt_non_coprime(mod(14, 18), mod(20,30)); a 5...
fd1b51516c5e454dc0e5e13929b84afaffbbdd82
650,445
def base_S_ss(seq_bits,n): """Finds the number of segregating sites, number of singletons, number of doubletons, and allele frequency spectrum from bitarray n = sample size (in chromosomes)""" spec_zero = [] for g in range(n - 1): spec_zero.append(0) var_ss = 0 # Segregating sites for s...
985bbe90e7deb2dd716a1e4a1b40f905cebb8a29
650,446
def pretty_print(x, numchars): """Given an object `x`, call `str(x)` and format the returned string so that it is numchars long, padding with trailing spaces or truncating with ellipses as necessary """ s = str(x) if len(s) > numchars: return s[:(numchars - 3)] + '...' else: ...
0ad6998c62b44730fe2316dd3233f49d2905af58
650,447
import random def noun(): """Calculate a random (first or second) noun declension.""" return [random.randrange(5), random.randrange(2)]
79a3cf79805c44c6076ee183e542094b6cfaf1ee
650,450
def unixify(path): """Convert a DOS style path to Unix style path. Args: path (str): A windows style path. Returns: str: A Unix style path. """ return path.replace('\\', '/')
8caa27e657d6cbaa795aae8fc70452406e90aabb
650,451
import random def cross_validation_splits(dataset, no_splits): """Generate an array of dataset splits, each index containing a tuple with train data at 0 and test data at 1. Takes preprocessed veracity data, as generated by data_loader.load_veracity() as input. :param dataset: an array which, at each ind...
bb4ede82e90821c23a3b1cf912fb75058853c7e3
650,452
from typing import Iterable import os import fnmatch def is_exclude_file(filename: str, exclude: Iterable[str]) -> bool: """Return True if file matches exclude pattern.""" base_name = os.path.basename(filename) if base_name.startswith("."): return True for pattern in exclude: if fnma...
dac4cc67a78a6a0c85ef7bbe95a6d99cdc7606fc
650,453
def get_book(cur, book_id_name, content=False, regions=False): """Get book from DB, specifying what details are required""" out = dict() # Initial fetch from main table cur.execute("".join([ "SELECT book_id, name", ", content" if content else ", NULL AS content", " FROM book WHE...
e443e32ff8e0fc3453cf7f20b286016f0f2106d3
650,454
def d2b(decimal, Q): """ This function returns the bit sequence of decimal which is truncated by Q bits decimal: [0,1], Q: sequence length """ i = 0 if decimal == 1: return str(1).rjust(Q, '1') decimal_convert = "" while decimal != 0 and i < Q: result = int(decimal * ...
bd93f9af8dcd15093bad95b6a7b56a806efd0db4
650,455
def vector_sub(v1=[0,0,0], v2=[0,0,0]): """ v1 - v2 """ return [v1[0]-v2[0], v1[1]-v2[1], v1[2]-v2[2]]
af9a82423be13ebaaa264c9d459fc587d34d891a
650,456
def list_products(technologies): """List intermediate and final products.""" return set(i.name for t in technologies for i in t.outputs)
079ec938985cec79848ea85c8fb713f870cc8470
650,457
def choice(*args): """ Creates a choice argument type. The user will be able to choose one of given possibilities. Example: choice("quickly", "slowly") :param args: a list of string the user will be able to choose :return: a dict representing this argument type with the appropriate format t...
91270ff6223674fc9a32dae7f66adcedfde98fe6
650,458
def _getBounds(stats1, stats2): """ Gets low and high bounds that captures the interesting bits of the two pieces of data. @ In, stats1, dict, dictionary with either "low" and "high" or "mean" and "stdev" @ In, stats2, dict, dictionary with either "low" and "high" or "mean" and "stdev" @ Out, (low...
9b2ddf666f88945cb53c2be9e56c88ec284f4465
650,459
import platform import sys import os def ffmpeg(): """Executa no terminal a instalação do ffmpeg seta as permissões""" print(f'\n{"#" * 40}') ffmpeg_install = input('Deseja instalar o FFmpeg [y/n]? ') print(f'{"#" * 40}\n') # Verifica a plataforma e distro (linux) distro = platform.platform() ...
a3fd42ea0c2179f578939979818908e3d5895100
650,460
def de_median_redshift(wavelength, median_z): """De-redshifts the same way as above Parameters: wavelength (array): wavelength values to convert median_z (int): redshift to change the wavelength by Returns: wavelength_red (array): redshifted wavelength """ wavelength_red = wavelength...
5a350f68ca5cb7e821f638059bebb459cbb1556c
650,461
def continue_if(perg, *respp, separador=True): """ :param perg: é a pergunta :param respp: opções de respostas (str) :param separador: True -> separa; False -> não separa :return: a resposta DESENVOLVEDOR: Silas B. Ferreira """ while True: esta = 0 repete = input(perg)....
6e342e385280cb458a8b6b111039b7ca530a1579
650,462
def id_tree_classify_point(point, id_tree): """Uses the input ID tree (an IdentificationTreeNode) to classify the point. Returns the point's classification.""" if id_tree.is_leaf(): return id_tree.get_node_classification() else: id_tree = id_tree.apply_classifier(point) return id...
08c86e8e47ceaf0f2e058f2fbb3abdd390b938d2
650,463
def cons(a, b): """ Construct a pair. :param a: first element :param b: second element :return: a function that takes a function and activates it on the pair """ def pair(f): return f(a, b) return pair
2bdae67b7f2227241b51bd7457d1e281ce64ddd8
650,464
def findKeyD(phi,e): """ Finds the private key d using the extended Euclidean algorithm """ x = 0 old_x = 1 y = 1 old_y = 0 r = e old_r = phi while not r == 0: q = old_r // r old_r, r = r, old_r - q*r old_x, x = x, old_x - q*x old_y, y = ...
0a5c5b73dca7791e5074f76e105abb24e8fcba53
650,465
def trim(s, chars=None): """ To remove other characters when used as a filter for form fields, you can use `functools.partial`. Example: from functools import partial StringField(filters=[partial(trim, chars='/')]) """ return s.strip(chars) if isinstance(s, str) else None
03e1e96d7650d4a0445924e80e40008a1fa97e11
650,466
def make_filename(instance, filename): """Makes the filename of the users profile image nice.""" return "profile_images/" + str(instance.user.id) + "." + filename.split(".")[-1]
39f473894581ee6b56b5a9104942682d88e267d3
650,467
def padBits(bits, padding): """Pad the input bits with 0's so that it is of length padding""" return [0] * (padding-len(bits)) + bits
6a7bc593be11af7de23f84d090b3c9700ab1d87d
650,468
def attmap_type(request, entries): """An AttMapLike subtype""" return request.param
4999bd70018de768a04df29bda4c6015f9e293fc
650,469
def _clean_path(path): """Fetch `name` from the environment, or use `default`. Trim trailing /'s from the resulting path. """ while path.endswith("/"): path = path[:-1] return path
faf45fc7fadabdb7d32cbfa7e25724eeb3a20b5b
650,470
import tempfile import os def local_file(request): """ Return the path to a local dummy file. """ file = tempfile.NamedTemporaryFile(delete=False) with open(file.name, 'wb') as f: f.truncate(1024) def destroy(): os.remove(file.name) request.addfinalizer(destroy) retur...
862989c6768ec167c24c4623019f5277c7d6a47c
650,471
import os def get_job_scheduler_id(): """ Get the job scheduler id from the environment variable PANDA_JSID :return: job scheduler id (string) """ return os.environ.get("PANDA_JSID", "unknown")
d337850ecddf3491b03d10462b728bed7ab5fb60
650,472
from typing import Optional import os def get_env(variable: str) -> Optional[str]: """Get environment variable or None.""" return os.environ.get(variable, None)
05cc8c1d85ae182591546162998abec42c4f644b
650,473
import itertools def endmembers_from_interaction(configuration): """For a given configuration with possible interactions, return all the endmembers""" config = [] for c in configuration: if isinstance(c, (list, tuple)): config.append(c) else: config.append([c]) ...
189d35f295e7a880bfb9c964a31d029f04c3862f
650,474
def unprefix_schema_dict(schema_in): """Turn a.b.c into just c for every key in a nested schema dictionary - iterate through all keys and turn each one from foo.bar to just bar, and apply recursively if any of the values are dictionaries themselves.""" schema_out = {} keys = list(schema_in.keys()) ...
00a2a8f4565abea9b88db56fd115491d28fb46d7
650,476
def find_intersection_point(start_point: tuple, end_point: tuple, plane_height: float): """ Данный метод находит пересечение прямой и плоскости (плоскости, которая перпендикулярна оси) Args: start_point: точка пространства. Необходимо передать кортеж с тремя значениями (x, y, z) end_poi...
2620216b39fc22a59aa10342ef3f92137f58f35a
650,477
import smtplib def connect(smtp_server, smtp_port=25): """ Connect to the SMTP server to send emails. :param smtp_server: Hostname or IP Address of the SMTP server :param smtp_port: Port number of the SMTP server, default is 25. :returns: server instance without logging in. :raises: None ...
d813f5e3382aa9f9761caddbec30cfa5fe567bdd
650,479
def IoU(box1, box2): """ Compute the IoU of two bounding boxes. :param box1: [x, y, w, h] :param box2: [x, y, w, h] :return: """ x1, y1, w1, h1 = box1 x2, y2, w2, h2 = box2 xl1, yl1, xr1, yr1 = x1, y1, x1 + w1, y1 + h1 xl2, yl2, xr2, yr2 = x2, y2, x2 + w2, y2 + h2 overlap_w =...
1e9fe5a9bd2cc076161774edba983f40af36140d
650,480
def get_node_portion(total_size, pes, rank): # pragma: no cover """get portion of size for alloc division""" return 0
8dcd0b868bed9e9c58e2204cc523b034bcc615fa
650,481
def _CheckReadMeComplete(input_api, output_api): """Verifies that any new files have been added to the README file. Checks that if any source files were added in this CL, that they were also added to the README file. We do not warn about pre-existing errors, as that would be annoying. Args: input_api:...
d0f84cf1848eeaf2d2c23f42f4bcaf61e4d82e16
650,483
def ignore_edition(edition_data): """don't load a million editions that have no metadata""" # an isbn, we love to see it if edition_data.get("isbn_13") or edition_data.get("isbn_10"): return False # grudgingly, oclc can stay if edition_data.get("oclc_numbers"): return False # if ...
881f18f477f3d3b0ede258fa3bfcbdfffe6ccb43
650,485
import os import json from typing import OrderedDict def _prepare_json_config(queues, test_datadir): """Prepare the json configuration based on the selected queues.""" json_config_path = os.path.join(str(test_datadir.parent), "s3_config.json") with open(json_config_path) as json_config_file: expec...
5503432031fadaf1b0e58040e3a3d6ab40787036
650,486
def _parse_error_msg(err): """Parse MPD error message.""" if not err.startswith('mpd error:'): return err return err.split(':', 1)[1].strip()
d2c313b0fa2e6737265b306a3d645ce35ebe5d95
650,487
def transpose_time_to_spat(x): """Swap time and spatial dimensions. Returns ------- x: torch.Tensor tensor in which last and first dimensions are swapped """ return x.permute(0, 3, 2, 1)
6a107af4a63312db57bd3c218e70d1b8efa0b0df
650,488
from typing import Dict from typing import Optional def find_root(tree: Dict[str, Optional[str]]) -> Optional[str]: """Find tree root.""" root = None for child, parent in tree.items(): if parent is None: root = child break return root
10c430db308b95700b634cc0d62b740714d2319e
650,489
import os def calculateExtension(files): """determines a single extension""" extensions = set((os.path.splitext(f)[1].lower() for f in files)) if len(extensions) > 1: raise SystemExit("Only one extension allowed. Found: {}".format(", ".join(extensions))) return extensions.pop()
d914d2bb438652498057436ea425a8b74af6688b
650,490
import numpy as np def mapdata(map, state, data): """ computes node values for new features in matched data. Args: map: nfeature to nnode mapping state: nsamples of nfreatures data: matched nsamples of new features dim(nnewfeature, nobs) Returns: node values of dimension (nnode,n...
dd31ffdfb596d89ab88c13060e89a7ce497e10cc
650,491
import os def version(): """Return version number of the package.""" version = {} path_here = os.path.abspath(os.path.dirname(__file__)) version_path = os.path.join(path_here, "version.py") with open(version_path) as fp: exec(fp.read(), version) return(version['__version__'])
3438f1ff425c5fddeed360f784ce8397ba974b0f
650,492
def HexColorShade(hexcode, factor=0.6): """ Creates a shade of the given color as determined by <factor> """ r, g, b = tuple(int(hexcode.lstrip("#")[i:i+2], 16)*factor for i in (0, 2 ,4)) newhex = "#{0:02x}{1:02x}{2:02x}".format(int(r), int(g), int(b)).upper() return newhex
b0b5a4cb93cadf9a96c2ef7e725b5e24cb3d90af
650,493
def delete_nth_naive(array, n): """ Time complexity O(n^2) """ ans = [] for num in array: if ans.count(num) < n: ans.append(num) return ans
13ce0e1108c0ead02cc578424122c781ce40780f
650,494
def has_area(o, a, b, ndigits=None): """ :param mathutils.Vector o: origin :param mathutils.Vector a: point a :param mathutils.Vector b: point b :param int ndigits: :return: :rtype: bool """ v1 = (a - o).normalized() v2 = (b - o).normalized() return abs(round(v1.dot(v2), ndi...
83f6db01094cf9e42ca9b1910c41831f48e7921f
650,495
def clamp(number, lower, upper): """ Limits the range of a number with a specified boundary """ return max(min(number, upper), lower)
c5de54acd0ac10ebdd5919368c6cc3d3fa3e72bf
650,496
def check_force_length_constraints(force, tol=0.01, printout=False): """Checks whether target length constraints applied to the force diagrams are respected, i.e. are below the tolerance criteria. Parameters ---------- force: compas_ags.diagrams.ForceDiagram The force diagram to check deviation...
cd36d8c0b3d7fa6792ff5f5fd5c66d0536784bf8
650,497
def mass(x): #Input: Atomic mass (float) """Finds information about element by atomic mass. Returns name of element, atomic number and atomic symbol in a list. Average timecomplexity: O(1)""" data = {} with open('elemdata.txt', 'r') as file: for line in file: *values,key= l...
981cdb459bd0bb2a65dffed2478a40bda33ee19b
650,498
def is_ancestor(cls, subclass): """ @type: cls: type @type: subclass: type @rtype: bool """ try: return cls in subclass.__mro__ except AttributeError: # raise same exception as issubclass(instance, klass) raise TypeError(str.format( "argument 1 must be a c...
3e167fdcf4b1722c30f05bb83e1ba374defbe435
650,499
def _get_itemvalue(zapi, hostid, keys): """Retrieves the value for a hostid - key combination. :param zapi: the zabbix api reference :type zapi: zapi :param hostid: the id of the host :type hostid: str :param keys: keys to retrieve :type keys: str or list """ if isinstance(keys, str...
e91e07ff442706ce65ecb752bf9d8a120a6e1473
650,500
import io from PIL import Image def matplotlib_figure_to_image(fig): """ Convert a matplotlib figure to an image in RGB format, for instance to save it on disk """ buf = io.BytesIO() fig.savefig(buf) buf.seek(0) return Image.open(buf).convert("RGB")
e196817a23c772e29985f37b2af297022914dfc9
650,501
def _get_specgram_plot_extents(psx, fs=2.0, lofreq=None, hifreq=None, t0=None, t1=None): """utility funciton to figure out plot extents for a spectrogram betwee times t0 and t1 with lofreq and hifreq along y axis and power spectrum psx""" extent = [0,psx.shape[1]/float(fs), 0.0, fs/2.0] # default ex...
8e5357e870848e73573a9d8d69046481a9d7a15e
650,502
import json def set_encoding(json_config, encoding): """ 设置清洗的编码 :param json_config: 清洗配置字符串 :param encoding: 编码 :return: 清洗字符串 """ json_config = json.loads(json_config) json_config["conf"]["encoding"] = encoding return json.dumps(json_config)
5d79f092349083009f03ba270f52641257d8a926
650,503
def get_printable_hex(byte_data): """ bytearrayのデータを見やすい16進数表現の文字列に変換する :param byte_data: :return: """ data_hex_string = byte_data.hex() return '[' + ' '.join([data_hex_string[i: i + 2].upper() for i in range(0, len(data_hex_string), 2)]) + ']'
2fc07b21c07e48c1258af998fa072cf94457361d
650,504
def to_dict(object, classkey='__class__'): """ Get dict recursively from object. https://stackoverflow.com/questions/1036409/recursively-convert-python-object-graph-to-dictionary :param object: object :type object: object or dict :param classkey: save class name in this key :type classkey: ...
d521178b818708e385bf79f46bfa0ea4b642f99d
650,506
def get_expected_ploidy(gender, chrom): """ Determine expected ploidy of call based on sample's gender and chromosome. Unknown genders are processed as diploid. Args: gender (string): M,F or U chrom (string): chromosome, PAR values should be represented as XY Returns ...
ad25772c66c5fb8bc19e82dca009e2ecd6104266
650,507
import random def cxSimulatedBinary(ind1, ind2, eta): """Executes a simulated binary crossover that modify in-place the input individuals. The simulated binary crossover expects :term:`sequence` individuals of floating point numbers. :param ind1: The first individual participating in the crossover. ...
a056a041168b96d5469952d184c487c92e2d98c7
650,508
def get_lookup_dicts(pred_name): """ Create part-of-speech-specific dicts mapping lemmas to sets of indices :param pred_name: list of pred names, in order :return: {'v':verb_dict, 'n':noun_dict} """ # Initialise lookup dicts v_lookup = {} n_lookup = {} lookup = {'v':v_lookup, 'n':n_l...
9fcdba1ded172e1820288908ea7de063bdf12243
650,509
def process_entry(line: str) -> list: """Take a line from day2_input.txt and return important values""" split_index = line.index(":") split_range_index = line.index("-") password = line[split_index + 2:len(line)] return [split_index, split_range_index, password]
3eb9873533e7b52626d85d56ddb4437f924dded4
650,510
def manhattan(t1b: tuple, t2b: tuple) -> int: """For parm pair of coordinate tuples, each (x, y). Return the Manhattan distance between them.""" t1x, t1y = t1b t2x, t2y = t2b return abs(t1x - t2x) + abs(t1y - t2y)
71ad347a8a05087e861176cfcb8533646060f880
650,511
def strip_terminating_semicolon(sql: str) -> str: """Removes terminating semicolon on a SQL statement if it exists""" return sql.strip().rstrip(";").strip()
5d3b8979d63c37ea4487f7f7ade608ece3ee69c1
650,512
def tracks_max_popularity_of_epoch(df, tracks=str, col_year=str, popularity=str, year_1=int, year_2=int): """ Busca las canciones con máxima popularidad para un rango de años :param df: nombre del datafreme :param tracks: columna con el nombre de las canciones :param col_year: columna con los añ...
9790d416607d7f528f60a2d786c35daeb2e4fdeb
650,513
def add_all_numbers(n): """adds all numbers between zero and n, including n""" return sum([number for number in range(n + 1)])
dbbd561951fc54b8a95882534065f9f7a6891f85
650,514