content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def scsplit(*args, stratify, test_size = 0.3, train_size = 0.7, continuous = True, random_state = None): """ Create stratfied splits for based on categoric or continuous column. For categoric target stratification raw sklearn is used, for continuous target stratification binning of the target variable ...
ac2dabfa2a069d48714ab5d10f4bf3886a87cd33
3,602,500
def cache_function(length=settings.CACHE_TIMEOUT): """ A variant of the snippet posted by Jeff Wheeler at http://www.djangosnippets.org/snippets/109/ Caches a function, using the function and its arguments as the key, and the return value as the value saved. It passes all arguments on to the functi...
52b235dcadf0a8bc63ada71c31fad13b6d6d6664
3,602,501
def is_prime(num: int) -> bool: """Determines whether the given number is prime or not""" if num == 2: return True elif num % 2 == 0: return False else: sq = int(sqrt(num)) + 1 for i in range(3, sq, 2): if num % i == 0: return False return ...
382dc191d603eff1acbc734d60f68c90198a6279
3,602,502
def maybe_future(x): """Converts ``x`` into a `.Future`. If ``x`` is already a `.Future`, it is simply returned; otherwise it is wrapped in a new `.Future`. This is suitable for use as ``result = yield gen.maybe_future(f())`` when you don't know whether ``f()`` returns a `.Future` or not. """ ...
1ad320d6aa57005e62987f211977eac2c8481d6c
3,602,503
from typing import List def tile(op_name: str, expr: Expr, in_xlayers: List[XLayer]) -> XLayer: """ TVM tile to XLayer Relay ----- Type: tvm.relay.tile Ref: https://tvm.apache.org/docs/api/python/relay/index.html#tvm.relay.tile Parameters: - reps The number of times re...
9e8fbf4e06accbefb034b570f091686dfd69b8fd
3,602,504
from typing import Dict def truvari_precision( logits: np.ndarray, one_hot_targets: np.ndarray, ) -> Dict[str, float]: """Computes genotype-level precision. Reference events are not considered. Args: logits: float array; Output of model in shape [batch, ..., num_classes]. one_hot_targets: Mult...
ed0c4e9c2be81b0e80c158d8f514e44fb1ad1f4d
3,602,505
import re def _applyReplacements(cfile, replacements): """ Applies custom replacements. @param str cfile @param list replacements - list of dicts with keys "match", "replacement", and (optional) "is_regex" """ for rep in replacements: if not rep.get('with_extension', False): ...
82797c5388f1aaf3d5983e2e938ef4f075ccaf97
3,602,506
def face_by_point3d(point3d_data): """Find a face with given serialized point3d that sits on that face""" point_on_face = point3d(point3d_data) app = adsk.core.Application.get() design = adsk.fusion.Design.cast(app.activeProduct) for component in design.allComponents: try: entiti...
8d571bbb932151a70d744f11860c371950e01736
3,602,507
def fwhm(*columns): """Calculate an estimate of full width at half maximum. The search starts a the 'left' end of the data. Returns a tuple ``(fwhm, xpeak, ymax, ymin)``: * fwhm - full width half maximum * xpeak - x value at y = ymax * ymax - maximum y-value * ymin - minimum y-value "...
53dbabb74e0d85f445d2d80456ba82c4637f00a3
3,602,508
def diff_argsort(matrices, x, sigma=0.1, softmax=softmax, transpose=False): """Return the smoothed, differentiable ranking of each element of x. Sigma specifies the smoothing of the ranking. Note that this function is deceptively named, and in the default setting returns the *ranking*, not the argsort. ...
91a80bcda3d964379d3efd0034a80c86ba6de911
3,602,509
import os import functools def create_vkitti_datasets(args, test_seed_offset=0): """ Gets training and test datasets. """ # Load formatted clouds testlist, trainlist = [], [] for n in range(1,7): if n != args.cvfold: path = '{}/features_supervision/0{:d}/'.format(args.ROOT_PATH, n)...
468c580d52749d9760b1bb23bee2d21c5baa1e81
3,602,510
def adjust(cep, diarization): """ Moves the border of segment of *diarization* into lowest energy region and split segments greater than 30s :todo: change numpy.convolve to the panada version :param cep: a numpy.ndarray containing MFCC :param diarization: a Diarization object :return: a Di...
17e1f88123a8427d4ac761202ea8043f6dddea60
3,602,511
from datetime import datetime def roundTime(dt, roundTo=5 * 60): """Round a datetime object to any time laps in seconds dt : datetime.datetime object, default now. roundTo : Closest number of seconds to round to, default 5 minutes. """ seconds = (dt - dt.min).seconds # '//' is a floor division...
4d965988864118efa07e993797f188b5fcdf9986
3,602,512
def create_psf_3d( psf, true_energy_bins, source_offset_bins, fov_offset_bins, ): """ Create a ``gammapy.irf.PSF3D`` from pyirf outputs. Parameters ---------- psf: astropy.units.Quantity[(solid angle)^-1] Point spread function array, must have shape (n_energy_bins, n...
67f3142b4fbf62535fdfc94b83691485ca1c352c
3,602,513
def meta_nonempty_object(x): """Create a nonempty pandas object from the given metadata. Returns a pandas DataFrame, Series, or Index that contains two rows of fake data. """ if is_scalar(x): return _nonempty_scalar(x) else: raise TypeError( "Expected Pandas-like Ind...
a9d6c6581dad4a3e87b9928796769dd6baf8113c
3,602,514
import pathlib def get_project_root() -> pathlib.Path: """Returns project root folder.""" return pathlib.Path(__file__).parent
0870689f7933b4e4d765b7ea66f0e457f3bee542
3,602,515
def sortDepsNew(timeOutWOBailick): """ codependency= list of all zones that the timeout NSes depend timeOutWOBailick =dictionary with Authority objects goal : iterate over codependency and return a dict like timeOutWithoutBailick """ # dict with the new created Authority objects newAuth = ...
543274593ac3195c1ac21a79cc1e392f07690c06
3,602,516
def pourier_tarantola(V, E0, B0, B1, V0): """Pourier-Tarantola equation from PRB 70, 224107""" eta = (V/V0)**(1./3.) squiggle = -3.*np.log(eta) E = E0 + B0*V0*squiggle**2/6.*(3. + squiggle*(B1 - 2)) return E
7462748a674450ebe689406c173b28a3b88a6676
3,602,517
def polarization_decomp(bx,by, flipz=False): """ INPUTS bx, by (Float arrays) Transverse field components flipz (Boolean) If False, wave is assumed to be propagating along the z direction defined by the given x and y directions and the right-hand rule. If True, the wave is assumed t...
46f128b245b2e69d6898626185f711f27f1e0f64
3,602,518
import click from typing import Mapping import requests import re def get_prs(ctx: click.Context, color: bool, headers: Mapping[str, str]) -> RepoDict: """Get all Github PRs assigned to user.""" username = ctx.obj.get_value("username") logger.debug(f"Fetching PRs for {username} from github.com \n") ur...
7fec24fbae4ceb57bf53ed96ab617b1a492eacce
3,602,519
import json def meeting_log_version_from_file(file_object): """ returns version number for a given file object (or None, if version cannot be identified) :param file_object: :return: """ last_pos = file_object.tell() # keep current position first_line = file_object.readline() ...
821c310a7e50f679ef2d27f3ea4e56b4b5b4e54d
3,602,520
def write_tx(sql: str, data: any): """ 写事务 """ connection = connection_pool.connection() cursor = connection.cursor() result = cursor.execute(sql, data) try: connection.commit() except RuntimeError as error: connection.rollback() log.error('事务提交失败!已回滚') raise err...
cb157d7993d78336c52654c241d16117c7cc5d2c
3,602,521
def recall_board(state, boards_played, p1=1, p2=2): """Determine if board (or equvialent) has been seen before.""" # Check if the board (or eqivalent) has been seen before. for trans_number in range(8): trans_state = board_transform(state, trans_number) key = nd3_to_tuple(trans_state) ...
35f3cd31d22a15a814d8b746635fa54bb32e3bb4
3,602,522
def cd_task(mode, window, mouse, slots, slot_size, targets, prechange, fillers, items_per_array, trials, prechange_dur, ISI): """ Present the 6AFC memory task or a change detection task. :param mode: A string indicating what kind of trial to run. All modes but "unstudied" use a familiar object in ...
1edfd46ead1e81c35ba3d8f96b01ded7a30c9af3
3,602,523
def handler(store, default=True, internal=False, passive=False): """ Decorator for setting up a handler. This puts the handler into the handler store which can then be used to look up all handlers and information about them such as which are default, passive, etc. Currently there are two handler s...
cf7c4c8847539be57c5680d87f80414bb6ab0164
3,602,524
def BFS_dist2(source, sink, maxLen, data): """ returns bfs search distance, no more than maxLen squares returns infinity if all paths exhausted before finding TODO: return error instead of infinity? """ if source == sink: return 0 dangerSquares = danger_squares(data)...
c326dedac45ed2066f34f7685118e8bd7bc94802
3,602,525
from typing import IO def give_cmd(file: IO[str], force: str, interactionId: int = 0, where: Range = None, expr: str = ''): """Fill a goal. """ return ('give', {'file': file, 'interactionId': interactionId, 'where': where})
53eab593f2983b012f7859325e58101d896547ba
3,602,526
from typing import List from datetime import datetime def get_current_time_info( epm: Epm, sec_elapsed: float) -> List[int]: """Returns the current day, month and hour given the seconds elapsed since the simulation started. Args: epm (opyplus.Epm): EnergyPlus model object. sec_elapsed...
f1cc87fa0f68ca50bceaa5c132c7f56c92d41468
3,602,527
import sys def ref_c_2(obj): """+ 2""" return sys.getrefcount(obj)
aafb6caded13abcf9a3c72f5f932e4215556b2ea
3,602,528
def isTreeKey(key): """ Return True if the object, corresponding to the key, inherits from TTree """ classname = key.GetClassName() cl = ROOT.gROOT.GetClass(classname) return cl.InheritsFrom(ROOT.TTree.Class())
3f44e341f11fdd3be184300805f0fa60f54adcff
3,602,529
def virtual_interface_get_by_uuid(context, vif_uuid): """Gets a virtual interface from the table. :param vif_uuid: the uuid of the interface you're looking to get """ vif_ref = _virtual_interface_query(context).\ filter_by(uuid=vif_uuid).\ first() return ...
f1042df9dd21ff362eafda4c06245f11504aafce
3,602,530
def human_readable_filesize(size): """Convert file size in bytes to human readable format Args: size (int): Size in bytes Returns: str: Human readable file-size, i.e. 567.4 KB (580984 bytes) """ if size < 1024: return "{} bytes".format(size) remain = float(size) fo...
c8eefdf9145bfb5c937b740fec9e6b437704aa5b
3,602,531
def interchanging_key_and_value(x): """creating a function for interchanging key and value""" return(x[1],x[0])
6478d48d698bb741ff2a24634b5b833ef624f79f
3,602,532
def random_d14_psd(request): """ Create a random instance of the D14 PSD. """ boundaries = {"intercept_parameter" : (6, 12), "mass_weighted_diameter" : (-2, -4), "mass_density" : (-12, -2)} cls = request.param psd = cls(1.0, 1.0, 917.0) low, high = boun...
e455a7bdf5277070205e6e173147d47c3fedfdfb
3,602,533
def _encrypt(key,block,n=32,endian="!"): """Encrypt one single block of data. Only use if you know what to do. Keyword arguments: key -- the key for encrypting (and decrypting) block -- one block plaintext n -- cycles, one cycle is two rounds, more cycles -> more security and slowne...
46694170a6a4aeabad16516480958a4b1632141e
3,602,534
def read_system(path, ignore_resnames=(), ignh=None, modelidx=None): """ Read a system from a PDB or GRO file. This function guesses the file type based on the file extension. The resulting system does not have a force field and may not have edges. """ system = System() file_extension = pa...
31c5ba7256d69a92b4f0109e2b0878cf9fc43e32
3,602,535
import math def unifDiag(matrix, tol = 1e-4): """ Parameters: -matrix: square and symmetric matrix (should be checker outside) -tol: tolerance parameter to be equal to a certain value This function makes uniform the diagonal of the symmetric square matrix in parameter. It returns...
f3a1f8c76d997493617a0b5dc341a7ae01015f96
3,602,536
def main(input, output): """ input : str - such as open("Example.class", "r").read() output : file - such as stdout or anything with a method write(str) """ # this is a bound variable :| index = [0] def str2hex(string): return "".join(hex(ord(c))[2:].zfill(2) + " " for c i...
773ccfb419347a6e4f3306d61ba7ab3808c4732b
3,602,537
import time def stash_all_items(items: list = None): """ Stashing all items in inventory. Stash UI must be open when calling the function. """ global messenger if items is None: Logger.debug("No items to stash, skip") return None center_mouse() # Wait for stash to fully loa...
c23c3ca39420efe7ce8f4dec398f05d0400fa3db
3,602,538
def position_by_contract_id(account_id: str, contract_id: str) -> dict: """Returns a list of all positions matching the conid. For portfolio models the conid could be in more than one model, returning an array with the name of model it belongs to. /portfolio/accounts or /portfolio/subaccounts must ...
efecb102888d38fae862693f4a972c85c6dba8b9
3,602,539
import re def tokenize(s): """ tokenize """ #数字替换为<num> s = re.sub('\d+', '<num>', s).lower() tokens = s.split(' ') return tokens
0f76b68c75c474a4f4ee692ae1124127b93ebf6e
3,602,540
def category(id): """ """ category = Category.query.get(id) pitch = Pitch.get_pitch(id) form = PitchForm() title = 'pitches' return render_template('category.html', category = category, pitch = pitch, title = title, pitch_form = form)
ca50cdc22e993f077d0ffc03db14dad204407caa
3,602,541
def uuid(value): """Return true if UUID is valid, otherwise - false.""" return const.UUID_RE.match(value) is not None
61aa3f12b289c79ec8e7d64e1f2b694c3f4e6480
3,602,542
import dateutil def convert_datetime(string): """Converts a string into a date object""" the_date = dateutil.parser.parse(string).replace(tzinfo=utc) return the_date
aeca0be4a53c6950735cd77875021729ace259dc
3,602,543
import argparse def make_parser(inheritable=False): """Expose parser for ``main``. Parameters ---------- inheritable: bool whether the parser can be inherited from (default False). if True, sets ``add_help=False`` and ``conflict_hander='resolve'`` Returns ------- parser: ...
fe5ac87aec15d1e8a6f3498e39a51592f782f694
3,602,544
def get_pipes(): """Get pipes from settings.""" # TODO: If settings does not have PROVIDED_DECORATORS assign it. # we should return default decorators in this case. # TODO: PROVIDED_DECORATORS seems to be not used right now. if PIPES: return PIPES for c in settings.DYNAMIC_DECORATO...
bf18abe8770a635ea8c7890a95b3cf6bc4dee2c5
3,602,545
import glob def loadImages(dataPath): """ load all Images in the folder and transfer a list of tuples. The first element is the numpy array of shape (m, n) representing the image. The second element is its classification (1 or 0) Parameters: dataPath: The folder path. Returns: ...
978c6fdaa42ec98402cc81dd03fc2d378b421fd3
3,602,546
import re def tokenize(text): """ Funnction tokenize the input text. Input--> text: text to be tokenized, as string Output--> lemmatized: List of words of cleaned text, as list """ stop_words = stopwords.words("english") lemmatizer = WordNetLemmatizer() # Norma...
57cd766ce65224793ac573658ec360635fb8297c
3,602,547
import numpy def get_axes(projection='rectangular', frame='icrs', ylim=None): """Returns axes for a particular projection. Parameters ---------- projection : str The type of projection of the axes returned. Either ``'rectangular'`` for a normal, cartesian, projection, or `moll...
a050b897e836be9cb69905a74b2281c14d4128c4
3,602,548
def join_game(request): """ Proccess data that a user sends when they want to join a game. """ LOG.debug('enter') # Send all non-POSTs to the index. if request.method != 'POST': LOG.info(__('attempted non-supported method {0}', request.method)) request.session['error_title'] = '...
0e10eca77b44d03e112f329204b1f193d6b429ac
3,602,549
import sys def get_outputfile(argument): """ Gets the outputfile from the raw argument. """ if argument != None: return open(argument, 'w') return sys.stdout
173428cd10bdbae812ea29aed42b92155f567db3
3,602,550
import time def is_auth_token_valid(token: Secret, jitter: int = 0) -> bool: """Returns if the token is still valid (within some jitter window)""" if token.token_life == -1: return True now = int(time.time()) latest_token_life = token.token_created + token.token_life - jitter return latest...
53f769b9ba91450ef342cc5ec7e3cab419facaf8
3,602,551
def make_generic_function_spec(abi_array): """ Generates ETHFunctionSpec for each function found in ABI. :param abi_array: contract Ethereum ABI :return: list of ETHFunctionSpec """ def obj_type(obj_name): for type_ in ['actions', 'tables']: for curr_obj in abi_array[type_]:...
5633d7faf081fea5b3fa2d49e026fa1dff00f89f
3,602,552
import unittest def createUnitTest(pkg, test_file): """ Unit test factory. Constructs a unittest class based on the roslaunch @param pkg: package name @type pkg: str @param test_file: rostest filename @type test_file: str """ # parse the config to find the test files config = ro...
55aaa38b878c0fa3f9a44728be99079a6354569f
3,602,553
def is_initialized(): """ Checking if bagua global communication state has been initialized """ global _global_state return _global_state is not None
8a5ecfbefdde903dc52e7c3aab9343d16bcb678c
3,602,554
from typing import Generator def to_list(x, repeat=1): """convert x to list object Args: x: any object to convert repeat: if x is to make as [x], repeat `repeat` elements in the list """ if isinstance(x, (Generator, tuple, set)): return list(x) elif isinstance(x, list): return x e...
79841d76cd0eba5a2e92fc0992516f59113c3f9b
3,602,555
import json import urllib3 import traceback import sys import requests import time def handle(): """ Handles a request to the function Returns: Object: HTTP response object """ global vchost, bearer_token # Load the Events that function gets from vCenter through the Event Router ...
cc0f4e1472c0e18651ace9ab1c1ebd9e99489235
3,602,556
def normalize_path(path, omit_empty=True, case_sensitive=True, case_normalization="lower", sep=None, force=False): """ Split and normalize generic path into individual path entries. Args: path: Generic path. Lists and tuples (possible nested) are flattened; strings are split accordi...
9eaf10de3a9b374ce8f87eceafe8a88750a81a80
3,602,557
def try_key(dict_to_try, key_for_dict): """Either returns key value or empty string.""" if key_for_dict not in dict_to_try: return '' return dict_to_try[key_for_dict]
a7486bd4933301278941fb7ee2001890221fcbd9
3,602,558
from typing import Union def parse_statement( source: str, config: PartialParserConfig = _DEFAULT_PARTIAL_PARSER_CONFIG ) -> Union[SimpleStatementLine, BaseCompoundStatement]: """ Accepts a statement followed by a trailing newline. If a trailing newline is not provided, one will be added. :func:`parse...
6030b6c19120539735dcc17449240ccf890dc4d1
3,602,559
import sys def utf8_replace(txt): """ Replace unsupported characters in unicode string, returns unicode. """ sse = sys.stdout.encoding txt = txt.encode(sse, "replace").decode("utf8", "ignore") return txt
935731ba5d5b5cb42958ff2b79649a9641fcbc13
3,602,560
import json def iblinds_v2_state_fixture(): """Load the iBlinds v2 node state fixture data.""" return json.loads(load_fixture("zwave_js/cover_iblinds_v2_state.json"))
beed8a829e26252257beafe25c7a9cab0e21725c
3,602,561
import os import filecmp def filescmp(f1, f2, shallow=True): """只有两个存在且是同类型的文件或文件夹,内容相同才会返回True,否则均返回False :param f1: 待比较的第1个文件(文件夹) :param f2: 待比较的第2个文件(文件夹) :param shallow: 默认True,即是利用os.stat()返回的基本信息进行比较 例如其中的文件大小,但修改时间等是不影响差异判断的 如果设为False,则会打开比较具体内容,速度会慢一点 """ if os.path.is...
86f0c3f246370fc6fe9b0728140e85b7e978a45c
3,602,562
def compare_lr_test(model_result, restricted_result): """ Likelihood ratio test to test whether restricted model is correct Parameters ---------- model_result : Result instance restricted : Result instance The restricted model is assumed to be nested in the current model. The r...
3169cc7c8d1f18176a2ed744409649ec0a14a045
3,602,563
def vgg13_bn(num_classes=1000, pretrained='imagenet'): """VGG 13-layer model (configuration "B") with batch normalization """ model = models.vgg13_bn(pretrained=False) if pretrained is not None: settings = pretrained_settings['vgg13_bn'][pretrained] model = load_pretrained(model, num_cla...
935ff120fbee9319840f270412ae262266bb2aec
3,602,564
def absolute(operand: ValueOrExpression) -> Expression: """ Constructs an absolute value expression. """ return ArithmeticUnary(operators.ArithmeticUnaryOperator.ABS, ensure_expr(operand))
39888a9108d1cabbe45cad58c11c1ba39912ba8a
3,602,565
def covariance_matrix(X): """ Args: X (ndarray) (m, n) Return: cov_mat (ndarray) (n, n): covariance matrix of X """ m = X.shape[0] return (X.T @ X) / m
128d9bfe12169cb344c150bf9f8f05565b5a8831
3,602,566
import operator def filter(array, *args, foos_filtering=[operator.gt, operator.lt], **kwargs): """general filter function for escape arrays. checking for 1D arrays, applies arbitrary number of filter functions that take one argument as input and""" if not np.prod(np.asarray(array.shape)) == array.shap...
825290fa49ae66455e6b8c5edd840c3d6d51d996
3,602,567
def sigmoid_deriv(x): """ Calculates the sigmoid derivative for the given value. :param x: Values whose derivatives should be calculated :return: Derivatives for given values """ return x * (1. - x)
8a7a1005fafb1b34c17c6ce4a8a04f80334e396a
3,602,568
from typing import Mapping def UpdateDict( target, override ): """Apply the updates in |override| to the dict |target|. This is like dict.update, but recursive. i.e. if the existing element is a dict, then override elements of the sub-dict rather than wholesale replacing. e.g. UpdateDict( { 'outer...
a07a3d7989e227ff1759271248777e167b7e5467
3,602,569
def calculate_propensity(kinetic_rates, lattice_state): """ Calculate the propensity for each event type Parameters ---------- kinetic_rates : list kinetic rates as defined in sim_parameters.py lattice : numpy.ndarray current lattice state Returns ------ event_propensit...
d689a5cd09930eaa881ce11d37c3ec006a20b37d
3,602,570
def filter_out_brews(applications: tuple, brews: list) -> tuple: """Returns a tuple (app_name, version) Finds installable application candidates with brew.""" print("getting installable casks from HOMEBREW...") candidates = [] search_list = [] for app in applications: # app_name = norm...
ea3e37a95c9ab177aa2ccb202761f9af1b11ae77
3,602,571
def fib(n): """calculate fibonanchi""" if mem[n] != 0: return mem[n] if (n <= 1): return n mem[n] = (fib(n - 1) + fib(n - 2)) return mem[n]
c9b5976411143f4e5be93cf3849c651b521ba6d9
3,602,572
def calc_cutoff_from_reverse_sorted_readlength_counts(rl_counts, target): """Return first read_len which gives at least 'target' bases. """ total = sum(pair[0] * pair[1] for pair in rl_counts) subtotal = 0 if target > total: msg = f"Not enough reads available for desired genome coverage (bas...
857828ee8f83630a54fc320fbacbfda628271a90
3,602,573
def calc_sharp_v_scan(t, v, res_points=10): """Calculate the discontinuous rate of change of v with respect to t Args: t (np.array): the data of the independent variable, typically time v (np.array): the data of the dependent variable res_points (int): the resolution in data points, i.e...
cac85ac0a6a1ad9fcd13e83569b21dcfb01370d0
3,602,574
def traer_mayor_24_doge(): """ This function returns the highest price of the last 24 hours """ newxd = MySQLdb.connect(host=MY_H, user=MY_U, passwd=MY_P, db=MY_D) consulta = newxd.cursor() consulta.execute("SELECT price FROM history_coin WHERE name='DOGE' ORDER BY price DESC LIMIT 1;") resultado =...
ae093cf25290aee5eedaf14bdb18431b57910efb
3,602,575
def berawgn(EbNodB, mod_type, M, mod_index=None, Kmin=None): """ Bit error rate (BER) for additive white Gaussian noise channels ber = berawgn(EbNodB, mod_type, M) returns the theoretical BER of various modulation types over an additive white Gaussian noise channel. The input, EbNodb, is the bit en...
3750bb987103ccf9ff47931549e4035b09e535de
3,602,576
import os import html from datetime import datetime def Tweets(ticker, graphDate,default=False): """ Returns the tweets section. :param ticker: string of the ticker :param graphDate: the date of the tweets :param default: default flag, True if section is in default :return news: html.Div ...
3857e26b56f427c044176f7d3ec05c4e84ec751f
3,602,577
def run_adaptive_grid(gdf, rtree, G, params, types, topk_regions, start_time, updates): """Executes the AdaptiveGrid algorithm. Employs a top-tier grid to identify promising cells and then applies ExpandBest over seeds that may be chosen using Bayesian optimization within those cells. Args: gdf: A...
ccf7d65302f9b59d14ef1dd65c896092c3a25b2c
3,602,578
from pathlib import Path import uuid def get_filename(filename): """CKEditor - Filename Generator""" extension = Path(filename).suffix return '{0}{1}'.format(uuid.uuid4(), extension)
50988191c0145e686b38306a6f1bfd686d4dff25
3,602,579
def NewtonRaphson(funcion, tolerancia, maxIteraciones, semilla): """ La tolerancia y numero de iteraciones tienen que ser positivos. La semilla debe de estar cerca del intervalo, caso contrario no va a converger. """ historia = np.zeros((maxIteraciones, 3)) if tolerancia < 0 or maxIteraciones < ...
1bb85b2663d732cb094e90645ed27252fb53fdcb
3,602,580
def IntToStr(input_bvv): """ Returns the string representation of the integer expressed in the BitVector :param input_bvv: the integer expressed as a BitVector we want to convert as a string :return: the string representation of the integer """ return StringV(str(input_bvv.value))
e92961fa876fd5047dc0715db40de13e2d5f89c5
3,602,581
def tee(cmd, cwd=None): """ executes a command, echoing output and buffering it for later use by the program. returns (exit_code, output) """ pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=cwd, shell=True) output = [] while True: if pipe.poll() i...
8be56162728cda2711803251e441f35c8a993e6d
3,602,582
def dss_target(request): """ This is a parameterized fixture. Its value will be set with the different DSS target (DSS7, DSS8 ...) that are specified in the configuration file. It returns the value of the considered DSS target for the test. Here it is only used by other fixtures, but one could use it a...
0aa9f85160280032dfdea872b7c9a147a5717523
3,602,583
from typing import Tuple def get_contours_iou(contour1, contour2, image_size: Tuple = None, plot=False): """ 计算两个轮廓(多边形)交并比(Intersection-over-Union,IoU) :param contour1: 多边形1 (num_points,2),由num_points个点构成的封闭多边形 :param contour2: 多边形2 (num_points,2),由num_points个点构成的封闭多边形 :param image_size: (W,H) im...
11b307f984b467eaacfe11042b4e5056d1eca0cc
3,602,584
import argparse def _parse_args(cmd_args): """ Parse command line parameters. Args: cmd_args ([str]): command line parameters as list of strings Returns: :obj:`argparse.Namespace`: command line parameters namespace """ parser = argparse.ArgumentParser( description=""" ...
7abc8d3afff97befc067d1c7227526cc10df6b96
3,602,585
from typing import Dict import uuid def cancel_run( config: Dict, celery_app: Celery, run_id: str, *args, **kwargs ) -> Dict: """Cancels running workflow.""" collection_runs = get_conf(config, 'database', 'collections', 'runs') document = collection_runs.find_one( filter={'run_...
bb112b763c47328c247102a9485d20b4982b76c6
3,602,586
import re def _clean_name(name): """ This function sets the name of a recipe to the standard naming convention specified """ name = re.sub(r'\s', "_", name) return name.lower()
940792220aa6eabfcf067c6450f30bca66d1b214
3,602,587
def get_base_dict(): """Get basic dictionary containing special tokens.""" return { TOKEN_PAD: 0, TOKEN_UNK: 1, TOKEN_CLS: 2, TOKEN_SEP: 3, TOKEN_MASK: 4, }
166f420317455c14045911d84acf18cbac3d9070
3,602,588
def label_data(dictionary, images): """ Labels the data depending on patient's diagnosis Parameters ---------- dictionary: Dict with patient information images: Names of images to label Returns ------- Labeled data """ data = [] last_patient = '' aux = [] for img...
01eb965d4cff7a8d4242eeb57e43fe3d72ee74f9
3,602,589
from pathlib import Path import csv def save_csv(csvpath, data, header): """Save data & header as a csv output file in the path provided. Args: csvpath (Path): The csv file-path where the output data will be saved data (list of list): list of list with the same number of elements that can be ...
d9e592842a7c428f1165e290e51b17d959a76bd9
3,602,590
def gym_size(gym): """Returns the size of the gym.""" return len(gym)
b31a46a7b56e973da8dfa0cac9950fad14b48622
3,602,591
def is_houdini_paste_event(uievent: KeyboardEvent) -> bool: """Check whether or not the event is an item paste event. :param uievent: The occurring keyboard event. :return: Whether or not the event is a paste event (h.paste). """ return setKeyPrompt(uievent.editor, uievent.key, "h.paste", uievent....
84c2c60369b790546755f2d31a39950ad6f68ac0
3,602,592
import json def get_outputs(file_name, pretty_quotes=False): """Read outputs from notebook.""" with open(file_name) as file: saved_cell_outputs = defaultdict(lambda: None) nb_cells = json.load(file)["cells"] for cell_index, cell in enumerate(nb_cells): if "outputs" not in cell: continue ...
69c116b1f63890f476a835a2d0682ac65af71735
3,602,593
import os def GetFileList(root): """Gets a normalized list of files under |root|.""" assert not os.path.isabs(root) assert os.path.normpath(root) == root file_list = [] for base, _, files in os.walk(root): paths = [os.path.join(base, f) for f in files] file_list.extend(x.lower() for x in paths) re...
2a81659a26683f7118dfa18e93c1ee18e03ee59f
3,602,594
def dump(obj, file=None, file_format=None, **kwargs): """Dump data to json/yaml/pickle strings or files. This method provides a unified api for dumping data as strings or to files, and also supports custom arguments for each file format. Args: obj (any): The python object to be dumped. ...
16068381f3f1fa1a80b2f8c8b31702dbdbfcb08a
3,602,595
def is_call_id_in_video_state(log, ad, call_id, video_state): """Return is the call_id is in expected video_state Args: log: logger object ad: android_device object call_id: call id video_state: valid VIDEO_STATE Returns: True is call_id in expected video_state; Fal...
d0da323a21a23d461fc2aec06ac5d0bebac7cbef
3,602,596
def call_torch(func, arg, *args, dtype=None, device=None, batch_size=64): """Call a torch function with numpy arguments and numpy results.""" args = (arg, *args) index, values = flatten_with_index(args) result_batches = [] for start in it.count(0, batch_size): end = start + batch_size ...
75f3b6d62b374e3c3fff1e3f5db1d60faf05b7d5
3,602,597
import time def gstat_elapsed(metric): """ decorator that logs the elapsed time spent in the decorated method """ def wrap(f): def wrapped_f(*args, **kwargs): start_time = time.time() ret = f(*args, **kwargs) gstat(metric, time.time() - start_time) ...
b1ad90f1004f66d5f3a6694104d2b62eb6550eb8
3,602,598
def interpolate_points( line: "shapely.geometry.linestring.LineString", num_pts=5) -> list: """ Create a list of multipoints for the interpolated points along each linestring Arguments: ----------- line: "shapely.geometry.linestring.LineString" shapely.geometry.linestring.Lin...
4f5142d325b228602654806ed8aef8f54ffd15a6
3,602,599