content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def wpr(c_close, c_high, c_low, period): """ William %R :type c_close: np.ndarray :type c_high: np.ndarray :type c_low: np.ndarray :type period: int :rtype: (np.ndarray, np.ndarray) """ size = len(c_close) out = np.array([np.nan] * size) for i in range(period - 1, size): ...
0f1d8d46464be81daa6308df97a7a8d12a90274b
17,400
def delete_action_log(request, log_id): """ View for delete the action log. This view can only access by superuser and staff. """ action = get_object_or_404(ActionLog, id=log_id) if action.status == 0 or action.status == 1: messages.error(request, "Cannot delete the Action log that is r...
8560e5280a57ddc8158b811fac29763bbaa8ef37
17,401
def hsla_to_rgba(h, s, l, a): """ 0 <= H < 360, 0 <= s,l,a < 1 """ h = h % 360 s = max(0, min(1, s)) l = max(0, min(1, l)) a = max(0, min(1, a)) c = (1 - abs(2*l - 1)) * s x = c * (1 - abs(h/60%2 - 1)) m = l - c/2 if h<60: r, g, b = c, x, 0 elif h<120: r, g,...
55e546756d4dd2a49581a5f950beb286dd73f3f9
17,402
from typing import Dict from pathlib import Path from typing import Optional def prioritize(paths: Dict[int, Path], purpose: str) -> Optional[Path]: """Returns highest-priority and existing filepath from ``paths``. Finds existing configuration or data file in ``paths`` with highest priority and returns i...
2c00d0bfe696040c2c19dc1d8b3393b7be124e11
17,403
def traverse(d, path): """Return the value at the given path from the given nested dict/list""" for k in path.split('.'): if k.isdigit(): k = int(k) d = d[k] return d
ba832a008073da5d97ba0a237a8e0ded17e4694e
17,404
def _bundle_name_with_extension(ctx): """Returns the name of the bundle with its extension. Args: ctx: The Skylark context. Returns: The bundle name with its extension. """ return _bundle_name(ctx) + _bundle_extension(ctx)
51f9c84fa2dd0ef9c5736a59ca2cd3c2d76aa108
17,405
import subprocess def call(args): """ Call args in a subprocess and display output on the fly. Return or raise stdout, stderr, returncode """ if TRACE: print('Calling:', ' '.join(args)) with subprocess.Popen( args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ...
7837a8e807bc7e3cda56b1f5e8625f936cc4bee0
17,406
def cvt_axisang_t_o2i(axisang, trans): """-correction: t_r, R_rt_r. outer to inner""" trans -= get_offset(axisang) return axisang, trans
ef263052e91ecc2fb8e668bca89a9d5622b75ff2
17,407
import pytz import numpy import dateutil def processData(dict, valuename, timename='Aika', multiplier=1.0): """Process "raw" OData dict and strip only the time and value. Also convert time to UTC and hydrodynamics model (COHERENS) format. Parameters ---------- dict: dictionary Data dictionary a...
df452a703a3afface12dc76abb647a5e38b808c3
17,408
from datetime import datetime def get_current_year(): """Returns current year """ return str(datetime.date.today().year)
f019e7f2462a4d8db0db294fade6ca737e87a24c
17,409
def parse_ans(text): """ Parses the given text as an answer set, i.e., a sequence of predicate statements. Returns a (possibly empty) tuple of Predicate objects. """ return parser.parse_completely( text, parser.Rep(PredicateStatement), devour=devour_asp )
44479668629b142115c27476242cbdf23b6657cc
17,410
def get_xyz(data): """ :param data: 3D data :return: 3D data coordinates 第1,2,3维数字依次递增 """ nim = data.ndim if nim == 3: size_x, size_y, size_z = data.shape x_arange = np.arange(1, size_x+1) y_arange = np.arange(1, size_y+1) z_arange = np.arange(1, size_z+1) ...
b1bd78fee6ca4a8fc2a33430c4ea5e922d696381
17,411
def wc_proximal_gradient(L, mu, gamma, n, verbose=1): """ Consider the composite convex minimization problem .. math:: F_\\star \\triangleq \\min_x \\{F(x) \\equiv f_1(x) + f_2(x)\\}, where :math:`f_1` is :math:`L`-smooth and :math:`\\mu`-strongly convex, and where :math:`f_2` is closed convex and...
ff8b67b963a2301e9b49870ffa9b6736a23420a4
17,412
import re import os def basic_output_filter( filtered_prefixes=None, filtered_patterns=None, ): """ Create a line filtering function to help output testing. :param filtered_prefixes: A list of byte strings representing prefixes that will cause output lines to be ignored if they start with one...
8db044d7d9d94ad7c4137762336d7a4b80f7a53c
17,413
def all_asset_types_for_shot(shot, client=default): """ Args: shot (str / dict): The shot dict or the shot ID. Returns: list: Asset types from assets casted in given shot. """ path = "shots/%s/asset-types" % shot["id"] return sort_by_name(raw.fetch_all(path, client=client))
a7d06e49d564dbd294636e29f488703f5027026e
17,414
from typing import Iterable def train(x_mat: ndarray, k: int, *, max_iters: int = 10, initial_centroids: Iterable = None, history: bool = False): """ 进行k均值训练 :param x_mat: 特征向量组,行数 m 表示样本数,列数 n 表示特征数 :param k: 聚类数目 :param max_iters: 最大迭代次数 :param initial_centroids: 初始聚类中心,不提供别的话将随机挑选聚类中心 ...
3a27cb709d6b267c8da19312f634f6003e2ba9a3
17,415
def download4(url, user_agent='wswp', num_retries=2): """Download function that includes user agent support""" # wswp: web scraping with python print 'Downloading:', url headers = {'User-agent': user_agent} request = urllib2.Request(url, headers=headers) try: html = urllib2.urlopen(reque...
1381e64e93b373e68a1a07eaab1688462f905374
17,416
import unittest def testv1(): """Runs the unit tests without test coverage.""" tests = unittest.TestLoader().discover('./tests/api/v1', pattern='test*.py') result = unittest.TextTestRunner(verbosity=2).run(tests) if result.wasSuccessful(): return 0 return 1
519835d59ce7d370e8099e94a48b1e7309274d99
17,417
def get_third_order_displacements(cell, symmetry, is_plusminus='auto', is_diagonal=False): """Create dispalcement dataset Note ---- Atoms 1, 2, and 3 are defined as follows: Atom 1: The first disp...
6ae03dbd10ffec75bc274b4a4115b81d28cefc40
17,418
def get_result_type(action): """Gets the corresponding ROS action result type. Args: action: ROS action name. Returns: Result message type. None if not found. """ msg_type = rostopic.get_topic_type("{}/result".format(action))[0] # Replace 'ActionResult' with 'Result'. retu...
f5612ac116357000106f7ff24f0d2bebb6789547
17,419
import statistics import math def get_turbulence(sequence): """ Computes turbulence for a given sequence, based on `Elzinga & Liefbroer's 2007 definition <https://www.researchgate.net/publication/225402919_De-standardization_of_Family-Life_Trajectories_of_Young_Adults_A_Cross-National_Comparison_Using_Sequence_An...
9900d377240b609de1cb7a5284752457947ef6c3
17,420
def reflect(array, holder=1): """ Reflects a np array across the y-axis Args: array: array to be reflected holder: a holder variable so the function can be used in optimization algorithms. If <0.5, does not reflect. Returns: Reflected array """ c = array.copy() if ...
c39cbf0bb3a949254e4f0c35b20bdf84766d2084
17,421
import os from datetime import datetime import time import logging import sys def create_and_return_logger(logger_name, filename="log"): """ Function to create a custom logger that will print to terminal as well as write to a log file Accepts: Logger name for script that is calling logger, and fil...
5860e00fe3fd52e11afd4daa27554c2e070afe06
17,422
from sys import path def _get_all_entries(entry_list, keep_top_dir): """ Returns a list of all entries (files, directories) that should be copied. The main purpose of this function is to evaluate 'keep_top_dir' and in case it should not be kept use all the entries below the top-level directories. ...
fbd12ef87cdc21307908ad7013167559da6fc051
17,423
import os def process_exclude_items(exclude_items=[]): """ Process the exclude items to get list of directories to NOT be scanned :return: a list of directories to not be scanned if any, otherwise an empty list """ logger.debug("Parsing exclude items ...") parsed_list = [] for item in excl...
36374faa3182aa1db0ba0d12b6a4f3ce23a69a95
17,424
def absolute_name_scope(scope, reuse=tf.AUTO_REUSE): """Builds an absolute tf.name_scope relative to the current_scope. This is helpful to reuse nested name scopes. E.g. The following will happen when using regular tf.name_scope: with tf.name_scope('outer'): with tf.name_scope('inner'): prin...
b9bd9e801603472c3e7e1db7a8768387b9942f3c
17,425
def regina_edge_orientation_agrees(tet, vert_pair): """ Given tet and an ordered pair of (regina) vert nums of that tet, does this ordering agree with regina's ordering of the verts of that edge of the triangulation """ edge_num = vert_pair_to_edge_num[tuple(vert_pair)] mapping = tet.faceMapping...
a70f08f56754eee24b9c4c71d5b6b537388a4ca4
17,426
from typing import Optional from datetime import datetime async def populate_challenge( challenge_status: str = "process", is_public: bool = True, user_id: Optional[UUID] = USER_UUID, challenge_id: UUID = POPULATE_CHALLENGE_ID, ) -> Challenge: """Populate challenge for routes testi...
fa47e65c7615af8dfebed4dd66fd92141d50e130
17,427
from typing import List def is_common_prefix(words: List[str], length: int) -> bool: """Binary Search""" word: str = words[0][:length] for next_word in words[1:]: if not next_word.startswith(word): return False return True
f57c7309f725baba0b65c92181a6f1ab2827558a
17,428
def freq_upsample(s, upsample): """ padding in frequency domain, should be used with ifft so that signal is upsampled in time-domain. Args: s : frequency domain signal upsample : an integer indicating factor of upsampling. Returns: padded signal """ if upsample =...
78377f6c552fe4f6d764a33b3e6ee555b4aabe71
17,429
def streaming_parsing_covering(groundtruth_categories, groundtruth_instances, predicted_categories, predicted_instances, num_classes, max_instances_per_category, ...
7c41f5b0c1111287759cc03cdc2a0c8a932aba11
17,430
from typing import Union def get_rxn_lookup(medObj:Union[m.Medication, m.LocalMed, m.NDC]): """ DEPRECATED Lookup RxCUI for codes from a different source :param medObj: :return: """ if isinstance(medObj, m.RxCUI): smores_error('TBD') return 0, [] success_count, errors ...
bba03aa380666b13db89497c720a62570a2918d0
17,431
def identity(dims): """ Create an identity linear operator :param dims: array of dimensions """ dims = expand_dims(dims) return identity_create(dims)
4d57c5a0da628c8f24de4f621728176714a4ab54
17,432
def _gen_samples_2d(enn_sampler: testbed_base.EpistemicSampler, x: chex.Array, num_samples: int, categorical: bool = False) -> pd.DataFrame: """Generate posterior samples at x (not implemented for all posterior).""" # Generate the samples data = [] rng...
19fc06700ae42b015694fc9389c05ad0caebf54d
17,433
def rules(r_index, c_index, lives, some_board, duplicate_board): """Apply Conway's Rules to a board Args: r_index (int): Current row index c_index (int): Current column index lives (int): Number of ALIVE cells around current position some_board (List of lists of strings): Board ...
f654a134be3eccad122720cd58f577a2d7e580d8
17,434
def get_describe_tasks(cluster_name, tasks_arns): """Get information about a list of tasks.""" return ( ecs_client() .describe_tasks(cluster=cluster_name, tasks=tasks_arns) .get("tasks", []) )
663cc2d2241aa3d75c8f2de35780ebe9a5d4ae31
17,435
def make_bcc110(latconst=1.0): """ Make a cell of bcc structure with z along [110]. """ s= NAPSystem(specorder=_default_specorder) #...lattice a1= np.array([ 1.0, 0.0, 0.0 ]) a2= np.array([ 0.0, 1.414, 0.0 ]) a3= np.array([ 0.0, 0.0, 1.41...
187556e30b4e89718d4c8d1179579ba498062d26
17,436
def mode_mods_to_int(mode: str) -> int: """Converts mode_mods (str) to mode_mods (int).""" # NOTE: This is a temporary function to convert the leaderboard mode to an int. # It will be removed when the site is fully converted to use the new # stats table. for mode_num, mode_str in enumerate(( ...
0bfaa8cf04bcee9395dff719067be9753be075c4
17,437
def ntu_tranform_skeleton(test): """ :param test: frames of skeleton within a video sample """ remove_frame = False test = np.asarray(test) transform_test = [] d = test[0, 0:3] v1 = test[0, 1 * 3:1 * 3 + 3] - test[0, 0 * 3:0 * 3 + 3] v1 = v1 / np.linalg.norm(v1) v2_ = test[0, ...
6f8e9e3ff0b6fa95b5f3b8c22aef2de05730a78c
17,438
import random import time import requests def request_to_dataframe(UF): """Recebe string do estado, retona DataFrame com faixa de CEP do estado""" #Try to load the proxy list. If after several attempts it still doesn't work, raise an exception and quit. proxy_pool = proxy_list_to_cycle() #Set i...
f71de0ec169f375fff1fba87d55aa8021b851990
17,439
import csv def read_sto_mot_file(filename): """ Read sto or mot file from Opensim ---------- filename: path Path of the file witch have to be read Returns ------- Data Dictionary with file informations """ data = {} data_row = [] first_li...
584cff26cb217d5fadfcea025ad58e431f46676a
17,440
def verify_cef_labels(device, route, expected_first_label, expected_last_label=None, max_time=90, check_interval=10): """ Verify first and last label on route Args: device ('obj'): Device object route ('str'): Route address expected_first_label ('str'): Expected fir...
c082920d0c93ec0c2897dc5a06c9d9d9452151af
17,441
def fcat(*fs): """Concatenate a sequence of farrays. The variadic *fs* input is a homogeneous sequence of functions or arrays. """ items = list() for f in fs: if isinstance(f, boolfunc.Function): items.append(f) elif isinstance(f, farray): items.extend(f.flat...
440a850ed17b8fc844cafaa765b24620a29fa0fd
17,442
def get_path_to_spix( name: str, data_directory: str, thermal: bool, error: bool = False, file_ending: str = "_6as.fits", ) -> str: """Get the path to the spectral index Args: name (str): Name of the galaxy data_directory (str): dr2 data directory thermal (bool): non...
bf8fdff001049ed0738ed856e8234c43ce4511b7
17,443
def hexpos (nfibres,diam) : """ Returns a list of [x,y] positions for a classic packed hex IFU configuration. """ positions = [[np.nan,np.nan] for i in range(nfibres)] # FIND HEX SIDE LENGTH nhex = 1 lhex = 1 while nhex < nfibres : lhex += 1 nhex = 3*lhex**2-3*lhex+1 if nhex != nfibres: lhex -= 1 nhex ...
4dbf1209d7021c6a4defd1c58e420b362bdbf84c
17,444
from bs4 import BeautifulSoup def parse_object_properties(html): """ Extract key-value pairs from the HTML markup. """ if isinstance(html, bytes): html = html.decode('utf-8') page = BeautifulSoup(html, "html5lib") propery_ps = page.find_all('p', {'class': "list-group-item-text"}) o...
8eb2d15cb5f46075ec44ff61265a8f70123a8646
17,445
def rgb2hex(r, g, b, normalised=False): """Convert RGB to hexadecimal color :param: can be a tuple/list/set of 3 values (R,G,B) :return: a hex vesion ofthe RGB 3-tuple .. doctest:: >>> from colormap.colors import rgb2hex >>> rgb2hex(0,0,255, normalised=False) '#0000FF' ...
03afd09cc280d7731ca6b28098cf3f5605fddda7
17,446
def test_hookrelay_registry(pm): """Verify hook caller instances are registered by name onto the relay and can be likewise unregistered.""" class Api: @hookspec def hello(self, arg): "api hook 1" pm.add_hookspecs(Api) hook = pm.hook assert hasattr(hook, "hello") ...
5f7733efbdbaf193b483c108838d2571ff686e52
17,447
def model_choices_from_protobuf_enum(protobuf_enum): """Protobufs Enum "items" is the opposite order djagno requires""" return [(x[1], x[0]) for x in protobuf_enum.items()]
d3f5431293a9ab3fdf9a92794b1225a0beec40cc
17,448
import os def load_boxes_and_labels(cfg, mode): """ Loading boxes and labels from csv files. Args: cfg (CfgNode): config. mode (str): 'train', 'val', or 'test' mode. Returns: all_boxes (dict): a dict which maps from `video_name` and `frame_sec` to a list of `box`. ...
9ea7f476474f834fcfb70700cc269b4abf8d5c33
17,449
def kmeans(boxes, k): """ Group into k clusters the BB in boxes. http://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html#sklearn.cluster.KMeans :param boxes: The BB in format Nx4 where (x1,y1,x2,y2) :param k: the number of clusters. :return: k clusters with the element in...
0d2bcfb2fb7d5639f95db92ac5aa5e73b1b27498
17,450
def observation_min_max_in_hex_grid_json(request: HttpRequest): """Return the min, max observations count per hexagon, according to the zoom level. JSON format. This can be useful to dynamically color the grid according to the count """ zoom = extract_int_request(request, "zoom") species_ids, datas...
24a3f4846aceea2df0b724d6bada88315b815ee2
17,451
import os def is_path(value, default="", expand=None): """Parse a value as a path Parameters ---------- expand: expandvars and expandhome on loaded path **Warning: expand currently can't work with interpolation** """ # TODO: fix interpolation and expand ! if str(value) == "No...
d2d369f35e6cc71dbdc3cd955456aeecb375fee6
17,452
import subprocess import os def find_suites(): """ Return a dict of suitename and path, e.g. {"heat_equation": /home/safl/bechpress/suites/cpu/heat_equation.py"} """ p = subprocess.Popen( ["bp-info", "--suites"], stdout = subprocess.PIPE, stderr = subprocess.PIPE ) ...
f3303f48b79d3ca4d172f272b7243629557bb9cc
17,453
from bs4 import BeautifulSoup def parseHtml(html): """ BeautifulSoup でパースする Parameters ---------- html : str HTML ソース文字列 Returns ------- soup : BeautifulSoup BeautifulSoup オブジェクト """ soup = BeautifulSoup(html, 'html.parser') return soup
e8d7a39a9881606d1dfee810ab1c2cecd11eaba2
17,454
def am_score(probs_data, probs_gen): """ Calculate AM Score """ mean_data = np.mean(probs_data, axis=0) mean_gen = np.mean(probs_gen, axis=0) entropy_gen = np.mean(entropy(probs_gen, axis=1)) am_score = entropy(mean_data, mean_gen) + entropy_gen return am_score
5e3c3f42ed2402dd2e48ab1ff4f9ff13754d5c31
17,455
import torch def load_image(path_image, size=None, bgr_mean=[103.939, 116.779, 123.68]): """ Loads and pre-process the image for SalGAN model. args: path_image: abs path to image size: size to input to the network (it not specified, uses SalGAN predifined) bgr_mean: mean values (B...
3a9ca220bb48f26d76ae35fd58897c8e59cdae0c
17,456
def GetWsdlNamespace(version): """ Get wsdl namespace from version """ return "urn:" + serviceNsMap[version]
bc75fa0e45c4ce4750898db75571de84aa302fc2
17,457
def is_PC(parcels): """ Dummy for Pinal County. """ return (parcels.county == 'PC').astype(int)
60aa7dcc7adaefee177406c7e6bb963a5a4567d9
17,458
import hashlib import requests def check_password(password: str) -> int: """Use Have I Been Pwned to determine whether a password is bad. If the request fails, this function will assume the password is fine, but log an error so that administrators can diagnose it later. :param password: The password...
609dd29ee2b252452e31d64b18e835a39e1cbf22
17,459
def rqpos(A): """ RQ decomp. of A, with phase convention such that R has only positive elements on the main diagonal. If A is an MPS tensor (d, chiL, chiR), it is reshaped and transposed appropriately before the throughput begins. In that case, Q will be a tensor of the same size, while R ...
026629b6638265daee83e8d8b5ab5b47b61e64d8
17,460
import torch from typing import OrderedDict def load_checkpoint(model, filename, map_location=None, strict=False, logger=None, show_model_arch=True, print_keys=True): """ Note that official pre-...
1d948f45f81c93af73394c891dc7e692c24378b3
17,461
def basic_image_2(): """ A 10x10 array with a square (3x3) feature Equivalent to results of rasterizing basic_geometry with all_touched=True. Borrowed from rasterio/tests/conftest.py Returns ------- numpy ndarray """ image = np.zeros((20, 20), dtype=np.uint8) image[2:5, 2:5] = 1...
8e83070721b38f2a886c7affb4aadc9a053f1748
17,462
def download(url, verbose, user_agent='wswp', num_retries=2, decoding_format='utf-8', timeout=5): """ Function to download contents from a given url Input: url: str string with the url to download from user_agent: str Default 'wswp' num_retries:...
31592018b6f6f62154444dfc44b723efc1bd7f47
17,463
from typing import Union from typing import List def _write_deform(model: Union[BDF, OP2Geom], name: str, loads: List[AEROS], ncards: int, op2_file, op2_ascii, endian: bytes, nastran_format: str='nx') -> int: """ (104, 1, 81) NX 2019.2 Word Name Type Description ...
55f2cb18336a940c550ee68bd5148c8d74f5bb93
17,464
def polygonize(geometries, **kwargs): """Creates polygons formed from the linework of a set of Geometries. Polygonizes an array of Geometries that contain linework which represents the edges of a planar graph. Any type of Geometry may be provided as input; only the constituent lines and rings will be u...
20b883734a1acedb1df3241e1815687640cac8cd
17,465
def slerp(input_latent1, input_latent2, interpolation_frames=100): """Spherical linear interpolation ("slerp", amazingly enough). Parameters ---------- input_latent1, input_latent2 : NumPy arrays Two arrays which will be interpolated between. interpolation_frames : int, optional ...
392b2e61f3369cf1e4038fac4240dca36f848dce
17,466
from datetime import datetime def parent_version_config(): """Return a configuration for an experiment.""" config = dict( _id="parent_config", name="old_experiment", version=1, algorithms="random", metadata={ "user": "corneauf", "datetime": datet...
ff1f123ce06d687eb3b0031d6bc82c808918c46e
17,467
import re def sanitize_k8s_name(name): """From _make_kubernetes_name sanitize_k8s_name cleans and converts the names in the workflow. """ return re.sub('-+', '-', re.sub('[^-0-9a-z]+', '-', name.lower())).lstrip('-').rstrip('-')
edaf6dc3083f0b57aeb1d95a66b5a7f8c1347b55
17,468
def main(): """ Process command line arguments and run x86 """ run = X86Run() result = run.Run() return result
7de61875207aa17bcf2ef87ff138540626fc7d2b
17,469
def gen_key(uid, section='s'): """ Generate store key for own user """ return f'cs:{section}:{uid}'.encode()
5e6386650f6bbaef681636424fd813f2df93fe58
17,470
def convert_atom_to_voxel(coordinates: np.ndarray, atom_index: int, box_width: float, voxel_width: float) -> np.ndarray: """Converts atom coordinates to an i,j,k grid index. This function offsets molecular atom coordinates by (box_width/2, box_width/2, box_width/2) and then divides by ...
6f08b594f2012aa0ba4a7985d5f4e2049c4629d3
17,471
import platform import sys def get_toolset_url(): """URL of a platform specific Go toolset archive.""" # TODO(vadimsh): Support toolset for cross-compilation. arch = { 'amd64': 'x86-64', 'x86_64': 'x86-64', 'i386': 'x86-32', 'x86': 'x86-32', }.get(platform.machine().lower()) variant = TOOLSE...
d88d8407775e9d0ca1ee80fee076046ae7ca7e44
17,472
def plot_det_curve(y_true_arr, y_pred_proba_arr, labels_arr, pos_label=None, plot_thres_for_idx=None, log_wandb=False): """Function for plotting DET curve Args: y_true_arr (list/np.array): list of all GT arrays y_pred_proba_arr (list/np.array): list of all predicted probabili...
0437d700a9555b48b84cbb6e225bc88f1a57e34d
17,473
def harmonic_separation(audio, margin=3.0): """ Wraps librosa's `harmonic` function, and returns a new Audio object. Note that this folds to mono. Parameters --------- audio : Audio The Audio object to act on. margin : float The larger the margin, the larger the separation....
3ac3e0d87f719814ca021f594a21dde08e9fd02f
17,474
def merge( left, right, how: str = "inner", on=None, left_on=None, right_on=None, left_index: bool = False, right_index: bool = False, sort: bool = False, suffixes=("_x", "_y"), copy: bool = True, indicator: bool = False, validate=None, ): # noqa: PR01, RT01, D200 ...
da07b44fb80ee28cc8320c071876ef6ad573d974
17,475
def generate_modal(title, callback_id, blocks): """ Generate a modal view object using Slack's BlockKit :param title: Title to display at the top of the modal view :param callback_id: Identifier used to help determine the type of modal view in future responses :param blocks: Blocks to add to the mo...
e0caeec1ab1cf82ed6f02ec77a984dcb25e329f5
17,476
def dir_thresh(img, sobel_kernel=3, thresh=(0.7, 1.3)): """ #--------------------- # This function applies Sobel x and y, # then computes the direction of the gradient, # and then applies a threshold. # """ # Take the gradient in x and y separately sobelx = cv2.Sobel(img, cv2.CV_64F...
0f5aefdbc9ffbe8e3678145e2926a4fbd7e01629
17,477
from datetime import datetime, timedelta def seconds_to_time( time ): """ Get a datetime object or a int() Epoch timestamp and return a pretty string like 'an hour ago', 'Yesterday', '3 months ago', 'just now', etc """ if not time: return "0s" if isinstance( time, timedelta ) or is...
407fa93f782c8cff142be1ab721969d3e4c2b42f
17,478
import os def bq_use_legacy_sql(): """ Returns BIGQUERY_LEGACY_SQL if env is set """ return os.environ.get('BIGQUERY_LEGACY_SQL', 'TRUE')
53d51c5eb1caa9b6041e9b2d29bde068199bba52
17,479
def load_txt_into_set(path, skip_first_line=True): """Load a txt file (one value per line) into a set.""" result = set() file = open_file_dir_safe(path) with file: if skip_first_line: file.readline() for line in file: line = line.strip() result.add(li...
17ad3c15820595b72254dbe4c9097a8857511599
17,480
def failed(obj): """Returns True if ``obj`` is an instance of ``Fail``.""" return isinstance(obj, Fail)
715fe3ae1154e3e5712b6f4535021b44e8020146
17,481
def linkCount(tupleOfLists, listNumber, lowerBound, upperBound): """Counts the number of links in one of the lists passed. This function is a speciality function to aid in calculating statistics involving the number of links that lie in a given range. It is primarily intended as a private helper functi...
239fd8d3c01fe6c88444cfa7369459e3c76005dc
17,482
def encode_md5(plain_text): """ Encode the plain text by md5 :param plain_text: :return: cipher text """ plain_text = plain_text + EXT_STRING encoder = md5() encoder.update(plain_text.encode('utf-8')) return encoder.hexdigest()
ad88ebc12334c9438c38719cd7c836edb9736d3c
17,483
import warnings def delta(x, y, assume_normal=True, percentiles=[2.5, 97.5], min_observations=20, nruns=10000, relative=False, x_weights=1, y_weights=1): """ Calculates the difference of means between the samples (x-y) in a statistical sense, i.e. with confidence intervals. NaNs are ignored...
37b742775777b5a0bd26f7e8fdf7a189a69b199f
17,484
def CircleCircumference(curve_id, segment_index=-1): """Returns the circumference of a circle curve object Parameters: curve_id = identifier of a curve object segment_index [opt] = identifies the curve segment if curve_id identifies a polycurve Returns: The circumference of the circl...
7a9200b089cebab93cbea387a4dd92590157dc45
17,485
def generate_handshake(info_hash, peer_id): """ The handshake is a required message and must be the first message transmitted by the client. It is (49+len(pstr)) bytes long in the form: <pstrlen><pstr><reserved><info_hash><peer_id> Where: pstrlen: string length of <pstr>, as a single raw byte ...
ae13462608f3e2ec47abdb12e87a3bc08faa1cba
17,486
def tokenizer_decorator(func, **kwargs): """ This decorator wraps around a tokenizer function. It adds the token to the info dict and removes the found token from the given name. """ if not callable(func): raise TypeError(f"func {func} not callable") @wraps(func) def wrapper(name, i...
d1827ab75a12f923c6da69927323d9c5013124c0
17,487
def reverse_complement( seq ): """ Biological reverse complementation. Case in sequences are retained, and IUPAC codes are supported. Code modified from: http://shootout.alioth.debian.org/u32/program.php?test=revcomp&lang=python3&id=4 """ return seq.translate(_nt_comp_table)[::-1]
86229dfeceecb7e0d2e1215b25074c35fbd38792
17,488
def computeLPS(s, n): """ Sol with better comle """ prev = 0 # length of the previous longest prefix suffix lps = [0]*(n) i = 1 # the loop calculates lps[i] for i = 1 to n-1 while i < n: if s[i] == s[prev]: prev += 1 lps[i] = prev i += 1 ...
8b4374c9ac29f59cf1f4b0e6e07628776828c11a
17,489
def roundedCorner(pc, p1, p2, r): """ Based on Stackoverflow C# rounded corner post https://stackoverflow.com/questions/24771828/algorithm-for-creating-rounded-corners-in-a-polygon """ def GetProportionPoint(pt, segment, L, dx, dy): factor = float(segment) / L if L != 0 else segment ...
e77497918025deba211469616d210c23483e2152
17,490
def synthetic_data(n_points=1000, noise=0.05, random_state=None, kind="unit_cube", n_classes=None, n_occur=1, legacy_labels=False, **kwargs): """Make a synthetic dataset A sample dataset generators in the style of sklearn's `sample_generators`. This adds other function...
740b5d2f708e177ce703f2124806ab7bd0079a09
17,491
import argparse def parse_args(): """ Argument Parser """ parser = argparse.ArgumentParser(description="Wiki Text Extractor") parser.add_argument("-i", "--input_dir", dest="input_dir", type=str, metavar="PATH", default="./extracted",help="Input directory path ") ...
af9149f893bb652c7e86a731749b3e2a5e4c1c8f
17,492
def _load_default_profiles(): # type: () -> Dict[str, Any] """Load all the profiles installed on the system.""" profiles = {} for path in _iter_default_profile_file_paths(): name = _get_profile_name(path) if _is_abstract_profile(name): continue definition = _read_p...
b53411dce6bdf3baba876a626b023a2b93e48c99
17,493
import torch def train_model(model, train_loader, valid_loader, learning_rate, device, epochs): """Trains a model with train_loader and validates it with valid_loader Arguments: model -- Model to train train_loader -- Data to train valid_loader -- Data to validate the ...
3addd258adddcbb43d846dae09d943d9a7016b69
17,494
def get_weapon_techs(fighter=None): """If fighter is None, return list of all weapon techs. If fighter is given, return list of weapon techs fighter has.""" if fighter is None: return weapon_tech_names else: return [t for t in fighter.techs if get_tech_obj(t).is_weapon_tech]
bbda76e55fdbe80e9883ff05746256fb56767136
17,495
def xml_to_values(l): """ Return a list of values from a list of XML data potentially including null values. """ new = [] for element in l: if isinstance(element, dict): new.append(None) else: new.append(to_float(element)) return new
30b6af4101f45697e0f074ddedcd051aba37cb99
17,496
def _get_options(raw_options, apply_config): """Return parsed options.""" if not raw_options: return parse_args([''], apply_config=apply_config) if isinstance(raw_options, dict): options = parse_args([''], apply_config=apply_config) for name, value in raw_options.items(): ...
e88014f0f5497e72973afbdf669cf14bf4537051
17,497
def csvdir_equities(tframes=None, csvdir=None): """ Generate an ingest function for custom data bundle This function can be used in ~/.zipline/extension.py to register bundle with custom parameters, e.g. with a custom trading calendar. Parameters ---------- tframes: tuple, optional ...
6dc4b76e52f7512074eb044d5505c904a323eb69
17,498
def normalize_skeleton(joints): """Normalizes joint positions (NxMx2 or NxMx3, where M is 14 or 16) from parent to child order. Each vector from parent to child is normalized with respect to it's length. :param joints: Position of joints (NxMx2) or (NxMx3) :type joints: numpy.ndarray :retur...
579862d05814eaa9b04f3e1a4812e727b02175aa
17,499