content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def archived_minute(dataSet, year, month, day, hour, minute): """ Input: a dataset and specific minute Output: a list of ride details at that minute or -1 if no ride during that minute """ year = str(year) month = str(month) day = str(day) #Converts hour and minute into 2 digit integers (that are strings) ho...
e550cb8ae5fbcfcc2a0b718dc2e4f3372f100015
3,637,300
def Rq(theta, vect): """Returns a 3x3 matrix representing a rotation of angle theta about vect axis. Parameters ---------- theta: float, rotation angle in radian vect: list of float or array, vector about which the rotation happens """ I = np.matrix(np.identity(3)) ...
069ef6568df170179a728b59dfb6a03dca0fbb75
3,637,301
def ExpsMaintPol(): """Maintenance expense per policy""" return asmp.ExpsMaintPol.match(prod, polt, gen).value
778d77d860378deeceee33e20a996e667430f851
3,637,302
def inputRead(c, inps): """ Reads the tokens in the input channels (Queues) given by the list inps using the token rates defined by the list c. It outputs a list where each element is a list of the read tokens. Parameters ---------- c : [int] List of token consumption rates. inp...
ea70548f7da4fae66fe5196734bbf39deb255537
3,637,303
def _split_schema_abstract(s): """ split the schema abstract into fields >>> _split_schema_abstract("a b c") ['a', 'b', 'c'] >>> _split_schema_abstract("a(a b)") ['a(a b)'] >>> _split_schema_abstract("a b[] c{a b}") ['a', 'b[]', 'c{a b}'] >>> _split_schema_abstract(" ") [] ...
ba1fba44979074b34adf87173a1277c212bd93e8
3,637,304
def myfn(n): """打印hello world 每隔一秒打印一个hello world,共n次 """ if n == 1: print("hello world!") return else: print("hello world!") return myfn(n - 1)
4405e8b4c591c435d43156283c0d8e2aa9860055
3,637,305
def name(ea, **flags): """Return the name defined at the address specified by `ea`. If `flags` is specified, then use the specified value as the flags. """ ea = interface.address.inside(ea) # figure out what default flags to use fn = idaapi.get_func(ea) # figure out which name function to...
7c0d938f5f4112f08749e1f412403d0da7ebf4d1
3,637,306
def estimate_distance( row: pd.DataFrame, agent_x: float, agent_y: float ): """ Side function to estimate distance from AGENT to the other vehicles This function should be applied by row Args: row: (pd.DataFrame) agent_x: (float) x coordinate of agent ...
c6d3dd9dbdcdde06baea95c8e0e56794d80aa0de
3,637,307
from .plot_methods import plot_spinpol_bands from .bokeh_plots import bokeh_spinpol_bands def spinpol_bands(kpath, eigenvalues_up, eigenvalues_dn, backend=None, data=None, **kwargs): """ Plot the provided data for a bandstructure (spin-polarized) Non-weighted, weighted, as a line plot or scatter plot, ...
60df91e2a06b4ff2e943efebc4ff936fb55164dd
3,637,308
def valid_config_and_get_dates(): """ 校验配置文件的参数,并返回配置文件的预约疫苗日期 :return: """ if config.global_config.getConfigSection("cookie") == "": raise Exception("请先配置登陆后的 cookie,查看方式请查看 README.MD") if config.global_config.getConfigSection("date") == "": raise Exception("请先配置登陆后的 预约日期") ...
42310c1fa60331e2ae238f4c6ab5ab23940536b3
3,637,309
import requests def check_internet_connection(): """Checks if there is a working internet connection.""" url = 'http://www.google.com/' timeout = 5 try: _ = requests.get(url, timeout=timeout) return True except requests.ConnectionError as e: return False return False
5f587e6077377196d2c89b39f5be5d6a2747e093
3,637,310
def wall_filter(points, img): """ Filters away points that are inside walls. Works by checking where the refractive index is not 1. """ deletion_mask = img[points[:, 0], points[:, 1]] != 1 filtered_points = points[~deletion_mask] return filtered_points
05a34602e8a555eb1f1739f5de910a71514a92ae
3,637,311
import requests def navigateResults(results): """Navigate all links, returning a list contaning the ulrs and corresponding pages. results:[String] - List with links to be visited Return: {list}[{tuple}({String}url, {String}content)]""" global BASE_ADDR ret = [] for i in results: ...
566da85528c7af46b29076c2b96eaf90f083becc
3,637,312
def _get_matching_signature(oper, args): """ Search the first operation signature matched by a list of arguments Args: oper: Operation where searching signature args: Candidate list of argument expressions Returns: Matching signature, None if not found """ # Search correspon...
21efb39c19f664ba0d79bcdbd1ab042bcaafffce
3,637,313
def format_size(num: int) -> str: """Format byte-sizes. :param num: Size given as number of bytes. .. seealso:: http://stackoverflow.com/a/1094933 """ for x in ['bytes', 'KB', 'MB', 'GB']: if num < 1024.0 and num > -1024.0: return "%3.1f%s" % (num, x) num /= 1024.0 ...
349649fc1ee6069b2cfba1ac8aa3745aafc9c7fc
3,637,314
def hub_payload(hub): """Create response payload for a hub.""" if hasattr(hub, "librarySectionID"): media_content_id = f"{HUB_PREFIX}{hub.librarySectionID}:{hub.hubIdentifier}" else: media_content_id = f"{HUB_PREFIX}server:{hub.hubIdentifier}" payload = { "title": hub.title, ...
e446ea607db6a665c94fab774ef46db70e1ed76f
3,637,315
def roq_transform(pressure, loading): """Rouquerol transform function.""" return loading * (1 - pressure)
b69d83579cdb904cc7e3625a371e1f6c0573e44b
3,637,316
def _cms_inmem(file_names): """ Computes mean and image_classification deviation in an offline fashion. This is possible only when the dataset can be allocated in memory. Parameters ---------- file_names: List of String List of file names of the dataset Returns ------- mean ...
88f856bbe33ec0e819b81dc7f5ad5930db45beea
3,637,317
def ddphi_spherical_zm (dd, ps_zm, r_e, lat, time_chunk=None ): """ This function calculates the gradient in meridional direction in a spherical system It takes and returns xarray.DataArrays inputs: dd data xarray.DataArray with (latitude, time, level) or (latitude, time), or combinations...
5cae237e3a1dc9646a0a288a6164880c482a82be
3,637,318
from methods import read_magmom_comp_data import os import itertools def process_group_magmom_comp( name=None, group=None, write_atoms_objects=False, verbose=False, ): """ """ #| - process_group_magmom_comp # ##################################################### group_w_o = gro...
d0e466b7282234c4dde326666ddbf1a51b3370bb
3,637,319
def precompute_dgmatrix(set_gm_minmax,res=0.1,adopt=True): """Precomputing MODIT GRID MATRIX for normalized GammaL Args: set_gm_minmax: set of gm_minmax for different parameters [Nsample, Nlayers, 2], 2=min,max res: grid resolution. res=0.1 (defaut) means a grid point per digit adopt: i...
b007c4ec9f1aec9af364abc40ed903e9db66482c
3,637,320
def get_image_urls(ids): """function to map ids to image URLS""" return [f"http://127.0.0.1:8000/{id}" for id in ids]
a70cd4eea39ea277c82ccffac2e9b7d68dd7c801
3,637,321
def partition(n: int) -> int: """Pure Python partition function, ported to Python from SageMath. A000041 implemented by Peter Luschny. @CachedFunction def A000041(n): if n == 0: return 1 S = 0; J = n-1; k = 2 while 0 <= J: T = A000041(J) S = S+T if is_odd(k//2) else S-T ...
e30279029e8fd3ec012020fcf9e088822577e3d3
3,637,322
def port_to_host_int(port: int) -> int: """Function to convert a port from network byte order to little endian Args: port (int): the big endian port to be converted Returns: int: the little endian representation of the port """ return ntohs(port)
69506efe702826ca55e013cfe7f064c61994beb9
3,637,323
def inv_median(a): """ Inverse of the median of array a. This can be used as the `scale` argument of ccdproc.combine when combining flat frames. See CCD Data Reduction Guide Sect. 4.3.1 """ return 1 / np.median(a)
3612b6b334781c44677c3be91d876b69ec6cd6d3
3,637,324
def mpdisted(dask_client, T_A, T_B, m, percentage=0.05, k=None, normalize=True): """ Compute the z-normalized matrix profile distance (MPdist) measure between any two time series with a distributed dask cluster The MPdist distance measure considers two time series to be similar if they share many s...
5ba6455228901e528909a63764a5a9d4fbdef2b3
3,637,325
def naive_pipeline_2() -> Pipeline: """Generate pipeline with NaiveModel(2).""" pipeline = Pipeline(model=NaiveModel(2), transforms=[], horizon=7) return pipeline
a14cef26c6970260435ddd5a17762e8dfa98e51a
3,637,326
import torch def caption_image_batch(encoder, decoder, images, word_map, device, max_length): """ Reads an image and captions it with beam search. :param encoder: encoder model :param decoder: decoder model :param image: image :param word_map: word map :param beam_size: number of sequences...
192def399d6b05947df7bac06e90836771a22dda
3,637,327
def wasserstein_distance(p, q, C): """Wasserstein距离计算方法, p.shape=(m,) q.shape=(n,) C.shape=(m,n) p q满足归一性概率化 """ p = np.array(p) q = np.array(q) A_eq = [] for i in range(len(p)): A = np.zeros_like(C) A[i,:] = 1.0 A_eq.append(A.reshape((-1,))) for i in ...
3a1e1836f5ec9975b30dafff06d8a4eaee90e482
3,637,328
def median_cutoff_points(ventricular_rate, ponset, toffset): """Calculate the median cutoff start and end points""" ponset = 0 if np.isnan(ponset) else int(ponset) toffset = 600 if np.isnan(toffset) else int(toffset) # limit the onset and offset to be in the range of 0-600 # take some margin of 10ms...
28de4a6ec172a052cb3a819d21ae8371ba68a469
3,637,329
def make_colormap(color_palette, N=256, gamma=1.0): """ Create a linear colormap from a color palette. Parameters ---------- color_palette : str, list, or dict A color string, list of color strings, or color palette dict Returns ------- cmap : LinearSegmentedColormap A...
78fee496532616d3d4a8d7bee6ee5ec7637750f5
3,637,330
def frac_correct(t): """Compute fraction correct and confidence interval of trials t """ assert np.all(t.outcome.values<2) frac = t.outcome.mean() conf = confidence(frac, len(t)) return frac, conf
82ed3ae7e6e9a34933ff7c07a2ca54faf563b235
3,637,331
def run_location(tokens, description): """Identifies the indices of matching text in the lines. Arguments: tokens (list): A list of strings, serialized from the GUI. description (CourseDescription): The course to be matched against. Returns: list: List of list of index positions. ...
b2f7867319620f8a46c07727494cc8dbf85d5084
3,637,332
from functools import reduce def SUM(r, expression = lambda trx:None): #todo None ok? cause error = good? """Sum expression""" if expression.func_code.co_consts==(None,) and len(r._heading)==1: #if no expression but 1 attribute, use it expression = lambda trx:trx[r._heading[0]] return reduce...
5bfba45f88d06187635c906ce4a0e1490888ed16
3,637,333
def domean(data, start, end, calculation_type): """ Gets average direction using Fisher or principal component analysis (line or plane) methods Parameters ---------- data : nest list of data: [[treatment,dec,inc,int,quality],...] start : step being used as start of fit (often temperature mi...
09e3539e4705995e8721976412977e13575add19
3,637,334
def download_data(dataset: str): """ Downloads a dataset as a .csv file. :param dataset: The name of the dataset to download. """ return send_from_directory(app.config['DATA_FOLDER'], dataset, as_attachment=True)
cc4cd03f38ecfbfc3b602a2ed323482203ef319f
3,637,335
def _split_features_target(feature_matrix, problem_name): """Split the features and labels. Args: feature_matrix (pd.DataFrame): a dataframe consists of both feature values and target values. problem_name (str): the name of the problem. Returns: tuple: ...
363dd1a9956f97c3c3520a074cca3c7c57f1517f
3,637,336
def descope_queue_name(scoped_name): """Descope Queue name with '.'. Returns the queue name from the scoped name which is of the form project-id.queue-name """ return scoped_name.split('.')[1]
24de78d12399e0894f495cd5c472b10c2315e4af
3,637,337
import os def SearchBeamPosition(DriverType=None): """A factory for SearchBeamPosition classes.""" DriverInstance = DriverFactory.Driver(DriverType) class SearchBeamPositionWrapper(DriverInstance.__class__): def __init__(self): DriverInstance.__class__.__init__(self) self...
dd2315b859b858e69ec4f90e04e852ca0c3aac62
3,637,338
from IPython.display import Image def movie(function, movie_name="movie.gif", play_range=None, loop=0, optimize=True, duration=100, embed=False, mp4=True): """ Make a movie from a function. function has signature: function(index) and should return a PIL.Image. """ frames = [] fo...
ac1705c4dae278a58af4f745d676c20570639567
3,637,339
def get_rounded_reward_2(duration: float) -> float: """ Helper function to round reward. :param duration: not rounded duration :return: rounded duration, two decimal points """ return round(get_reward(duration), 2)
ad1e97788504e6b4173853dbd7e82e9b407f7d0b
3,637,340
def fitness_order(order): """fitness function of a order of cities""" score = 0 cacher = str(order) if cacher in cache: return cache[cacher] for i in range(len(order) - 1): score += distance_map[(order[i], order[i + 1])] score += distance_map[(order[0], order[-1])] cache[cach...
e2af48535bf2219ec4cb6ddf0972c7dcc7ef363a
3,637,341
from ba import _lang from typing import Optional def get_human_readable_user_scripts_path() -> str: """Return a human readable location of user-scripts. This is NOT a valid filesystem path; may be something like "(SD Card)". """ app = _ba.app path: Optional[str] = app.python_directory_user if...
f5d78fed6db03947f1bb4135391aeeb7a130031c
3,637,342
def rotated_positive_orthogonal_basis( angle_x=np.pi / 3, angle_y=np.pi / 4, angle_z=np.pi / 5 ): """Get a rotated orthogonal basis. If X,Y,Z are the rotation matrices of the passed angles, the resulting basis is Z * Y * X. Parameters ---------- angle_x : Rotation angle around the ...
8848d1d11f3e83727ed90957f012869f27991285
3,637,343
import array def create_sequences(tokenizer, max_length, descriptions, photos_features, vocab_size): """ 从输入的图片标题list和图片特征构造LSTM的一组输入 Args: :param tokenizer: 英文单词和整数转换的工具keras.preprocessing.text.Tokenizer :param max_length: 训练数据集中最长的标题的长度 :param descriptions: dict, key 为图像的名(不带.jpg后缀), value ...
31cffba7fdce229bd264e87291e57ed386498f3f
3,637,344
def avatar_uri(instance, filename): """ upload_to handler for Channel.avatar """ return generate_filepath(filename, instance.name, "_avatar", "channel")
f880f49055fbdc30f6a045f2f7916c077d22452c
3,637,345
def readMoveBaseGoalsFromFile(poses_file): """Read and return MoveBaseGoals for the robot-station and patrol-poses. If the contents of the file do not obey the syntax rules of _readPosesFromFile(), or if no patrol-poses were found, an IOError exception is raised. """ patrol_poses, station_pose =...
09085a9bc569e78050f3f10552aa160e9a9324bb
3,637,346
import configparser def get_config(section = None): """Load local config file""" run_config = configparser.ConfigParser() run_config.read(get_repo_dir() + 'config.ini') if len(run_config) == 1: run_config = None elif section is not None: run_config = run_config[section] return ...
934dfad58fd674b58ccb4ddfeb9d62edbaba6e84
3,637,347
import os def system_info(x): """ Get system info. """ return list(os.uname())
4231e967190daee2ae7c6d9823878bcb0a957bc1
3,637,348
def get_parent(running_list, i, this_type, parent_type): """Get the description of an industry group's parent OSHA industry decriptions are provided in ordered lists; this function identifies the parent industry group based on information provided by the groups preceeding it """ prior = running...
f307900a6220f4d6f14ed0c1924d8f03a40a8a1d
3,637,349
import torch def rebalance_binary_class(label, mask=None, base_w=1.0): """Binary-class rebalancing.""" weight_factor = label.float().sum() / torch.prod(torch.tensor(label.size()).float()) weight_factor = torch.clamp(weight_factor, min=1e-2) alpha = 1.0 weight = alpha * label*(1-weight_factor)/weig...
5adf3a21e4cc4b9e7bf129ecf31cfe37ab7a305a
3,637,350
def from_base(num_base: int, dec: int) -> float: """Returns value in e.g. ETH (taking e.g. wei as input).""" return float(num_base / (10 ** dec))
447a07b3e282e5104f8dcd50639c658f3013ec7a
3,637,351
def make_auth_header(auth_token): """Make the authorization headers to communicate with endpoints which implement Auth0 authentication API. Args: auth_token (dict): a dict obtained from the Auth0 domain oauth endpoint, containing the signed JWT (JSON Web Token), its expiry, the scopes grant...
e7c9b93cfbda876668068fb871d3abaf06157204
3,637,352
import os def get_file_in_archive(relative_path, subpath, url, force_extract = False): """ Download a zip file, unpack it, and get the local address of a file within this zip (so that you can open it, etc). :param relative_path: Local name for the extracted folder. (Zip file will be named this with the ...
6ddb6d170a1ba0466594e095277bbd3a1fc71d63
3,637,353
from typing import List from typing import Optional import os import ssl async def create_nats_client(servers: List[str]) -> Optional[NatsClient]: """ Create a NATS client for any NATS server or NATS cluster configured to accept this installation's NKey. :param servers: List of one or more NATS servers i...
e74b55bf1d44353e1938f5408c5a7982adf4563f
3,637,354
from typing import Tuple def _drop_additional_columns( pdf: PandasDataFrame, column_names: Tuple, additional_columns: Tuple, ) -> PandasDataFrame: """Removes additional columns from pandas DataFrame.""" # ! columns has to be a list to_drop = list(compress(column_names, additional_columns)) ...
86a41647ae9bed9a18b428610f73af36105702b8
3,637,355
def get_cc3d(mask, top=1): """ 26-connected neighbor :param mask: :param top: top K connected components :return: """ msk = connected_components(mask.astype('uint8')) indices, counts = np.unique(msk, return_counts=True) indices = indices[1:] counts = counts[1:] if len(counts) >= ...
e91d5f2617ba526ebc27eaca93d8fed7e0145d0b
3,637,356
def dscp_class(bits_0_2, bit_3, bit_4): """ Takes values of DSCP bits and computes dscp class Bits 0-2 decide major class Bit 3-4 decide drop precedence :param bits_0_2: int: decimal value of bits 0-2 :param bit_3: int: value of bit 3 :param bit_4: int: value of bit 4 :return: DSCP cla...
79e9881e413a5fcbbbaab110e7b3346a2dbcaa53
3,637,357
def load_data(impaths_all, test=False): """ Load data with corresponding masks and segmentations :param impaths_all: Paths of images to be loaded :param test: Boolean, part of test set? :return: Numpy array of images, masks and segmentations """ # Save all images, masks and segmentations ...
b1d8f1b135eab0f122370aaa98f8cbbe6f2f1be7
3,637,358
def f_assert_seq0_gte_seq1(value_list): """检测列表中的第一个元素是否大于等于第二个元素""" if not value_list[0] >= value_list[1]: raise FeatureProcessError('%s f_assert_seq0_gte_seq1 Error' % value_list) return value_list
225e60a565ffa81ec373dea7f8097ee6619a8b01
3,637,359
import tempfile def download_file(res): """ Download file into temporary file :param res: Response object :return: downloaded file location """ LOGGER.debug("Chunked file download started") with tempfile.NamedTemporaryFile(delete=False) as file: for chunk in res.iter_content(chunk_...
84eac5fd06b3bfca6fec43eff79dcc996a2ac13d
3,637,360
def extract_units(name_andor_units): """Extracts the number of academic credit units the course is worth. Returns NaN if the number of units is variable.""" start = name_andor_units.rindex('(') + 1 end = name_andor_units.index(' ', start) units = name_andor_units[start:end] try: return f...
63a8a1e497a9840f0f351e4235dd6409230a6405
3,637,361
from typing import List def decorate_diff_with_color(contents: List[str]) -> str: """Inject the ANSI color codes to the diff.""" for i, line in enumerate(contents): if line.startswith("+++") or line.startswith("---"): line = f"\033[1;37m{line}\033[0m" # bold white, reset elif line...
55821622b1e7d7f545fa4ad34abebd108f27528d
3,637,362
from typing import Dict def _combine_multipliers(first: Dict[Text, float], second: Dict[Text, float]) -> Dict[Text, float]: """Combines operation weight multiplier dicts. Modifies the first dict.""" for name in second: first[name] = first.get(name, 1.0) * second[name] return first
e9db49daad0463e42a9231a2459fac5b4d14e181
3,637,363
def scale_to_one(iterable): """ Scale an iterable of numbers proportionally such as the highest number equals to 1 Example: >> > scale_to_one([5, 4, 3, 2, 1]) [1, 0.8, 0.6, 0.4, 0.2] """ m = max(iterable) return [v / m for v in iterable]
92cfc7ef586ecfea4300aeedabe2410a247610f7
3,637,364
def fixed_size_of_type_in_bits(type_ir, ir): """Returns the fixed, known size for the given type, in bits, or None. Arguments: type_ir: The IR of a type. ir: A complete IR, used to resolve references to types. Returns: size if the size of the type can be determined, otherwise None. """ array_mul...
a3aaf62ef37eab29011fe6bc4f17e4f694145766
3,637,365
def insecure(path): """Find an insecure path, at or above this one""" return first(search_parent_paths(path), insecure_inode)
685e66392f2adf8c9447e5cacf883de68c3bbe2d
3,637,366
import gc def n_feature_influence(estimators, n_train, n_test, n_features, percentile): """ Estimate influence of the number of features on prediction time. Parameters ---------- estimators : dict of (name (str), estimator) to benchmark n_train : nber of training instances (int) n_test :...
16d386385f4fde04670e37e76abe13b8c22a487c
3,637,367
def make_author_list(res): """Takes a list of author names and returns a cleaned list of author names.""" try: r = [", ".join([clean_txt(x['family']).capitalize(), clean_txt(x['given']).capitalize()]) for x in res['author']] except KeyError as e: print("No 'author' key, using 'Unknown Author'. You should ...
e1459514928d87a3e688b6957437452d02e50987
3,637,368
def backproject_points_np(p, fx=None, fy=None, cx=None, cy=None, K=None): """ p.shape = (nr_points,xyz) """ if not K is None: fx = K[0, 0] fy = K[1, 1] cx = K[0, 2] cy = K[1, 2] # true_divide u = ((p[:, 0] / p[:, 2]) * fx) + cx v = ((p[:, 1] / p[:, 2]) * fy) + cy return np.stack([v, u])....
a06031de2f03d6e80ae149024a5bb2bea96f6b76
3,637,369
import os import sys import platform def configure_dexter_substitutions(): """Configure substitutions for host platform and return list of dependencies """ # Produce dexter path, lldb path, and combine into the %dexter substitution # for running a test. dexter_path = os.path.join(config.cross_project_tests_...
a3d6be2c9c997af55d626b1b5e5aee0ee246466e
3,637,370
def recover(D, gamma=None): """Recover low-rank and sparse part, using Alg. 4 of [2]. Note: gamma is lambda in Alg. 4. Parameters --------- D : numpy ndarray, shape (N, D) Input data matrix. gamma : float, default = None Weight on sparse component. If 'None', then gamma = 1/s...
83a269006a7cc6c48b1db520c813929886eedf7b
3,637,371
import matplotlib.pyplot as plt def plot_Reff(Reff: dict, dates=None, ax_arg=None, truncate=None, **kwargs): """ Given summary statistics of Reff as a dictionary, plot the distribution over time """ plt.style.use("seaborn-poster") if ax_arg is None: fig, ax = plt.subplots(figsize=(12, 9)...
30db12546c6648c2e81609bd2292dc9be2fa6eea
3,637,372
def get_stylesheet(): """Generate an html link to a stylesheet""" return "{static_url}/code_pygments/css/{theme}.css".format( static_url=core_config['ASSETS_URL'], theme=module_config['PYGMENTS_THEME'])
e5f766a414d6fac32b361dfbb54da929bff4458d
3,637,373
def create_volume(ctxt, host='test_host', display_name='test_volume', display_description='this is a test volume', status='available', migration_status=None, size=1, availability_zone='fake_az',...
b638e98ab88f0e65c37503dee80bbec2250aab0e
3,637,374
def duration_of_treatment_30(): """ Real Name: b'duration of treatment 30' Original Eqn: b'10' Units: b'Day' Limits: (None, None) Type: constant b'' """ return 10
510b8e114007c9e64f866c98bfce9d2d86fa7bfe
3,637,375
def input_pkgidx(g_dim): """ Specify the parking spots index by the user return 1*pk_dim np.array 'pk_g_idx' where pk_dim is the number of spots """ #print('Please specify the num of parking spots:') pk_dim = np.int(input('Please specify the num of parking spots:')) while pk_dim >= g_dim: ...
acba8fdbeb1d0fdcb67d28b64fa313489fd597df
3,637,376
def get_total_count(data): """ Retrieves the total count from a Salesforce SOQL query. :param dict data: data from the Salesforce API :rtype: int """ return data['totalSize']
7cb8696c36449425fbcfa944f1f057d063972888
3,637,377
def _check_hex(dummy_option, opt, value): """ Checks if a value is given in a decimal integer of hexadecimal reppresentation. Returns the converted value or rises an exception on error. """ try: if value.lower().startswith("0x"): return int(value, 16) else: re...
6acf63f42b79ba30a55fc1666bdd2c1f65124fd3
3,637,378
def get_challenge(): """returns the ChallengeSetting object, from cache if cache is enabled""" challenge = cache_mgr.get_cache('challenge') if not challenge: challenge, _ = ChallengeSetting.objects.get_or_create(pk=1) # check the WattDepot URL to ensure it does't end with '/' if cha...
f874b90624bbd9c4d4fc5e18efd6363d461fab0f
3,637,379
async def get_user_from_event(event): """ Get the user from argument or replied message. """ args = event.pattern_match.group(1).split(" ", 1) extra = None if event.reply_to_msg_id: previous_message = await event.get_reply_message() user_obj = await event.client.get_entity(previous_messa...
4cd659637603e9910aa5fb00e855767ae8252c2e
3,637,380
def migrate_data(conn: redis.StrictRedis, data: dict) -> list: """ Uploads the given data to the given redis database connection """ pipe = conn.pipeline() for key, value in data.items(): command_and_formatter = TYPE_TO_PUT_COMMAND[value["type"]] command = command_and_formatter[0] ...
7e54d3bd0c5e302d3e2f173a53bf6cd6a9a6f6fb
3,637,381
def dummy_location(db, create_location): """Give you a dummy default location.""" loc = create_location(u'Test') db.session.flush() return loc
ec6ffa3b42e07c88b8224ee2aaaf000853a4169f
3,637,382
from pathlib import Path def get_resources_path() -> Path: """ Convenience method to return the `resources` directory in this project """ return alpyne._ROOT_PATH.joinpath("resources")
35b90856e00fbee8aeb373350cef77596a5f2a71
3,637,383
import subprocess import os def is_running_in_container(): # type: () -> bool """ Determines if we're running in an lxc/docker container. """ out = subprocess.check_output('cat /proc/1/sched', shell=True) out = out.decode('utf-8').lower() checks = [ 'docker' in out, '/lxc/' in out,...
5cef531a2b8bc989f5fa0aedde548ca1272bc494
3,637,384
import os def load_imagenet_val(num=None): """ Load a handful of validation images from ImageNet. Inputs: - num: Number of images to load (max of 25) Returns: - X: numpy array with shape [num, 224, 224, 3] - y: numpy array of integer image labels, shape [num] - class_names: dict mapp...
c5d94290b7df90d9abc3a76041fea72aad66e864
3,637,385
import math def sk_rot_mx(rot_vec): """ use Rodrigues' rotation formula to transform the rotation vector into rotation matrix :param rot_vec: :return: """ theta = np.linalg.norm(rot_vec) vector = np.array(rot_vec) * math.sin(theta / 2.0) / theta a = math.cos(theta / 2.0) b = -vecto...
9ba2abfd877d87423db02b224fed30ec59dc90f7
3,637,386
def split_line(line, points, tolerance=1e-9): """Split line at point or multipoint, within some tolerance """ to_split = snap_line(line, points, tolerance) return list(split(to_split, points))
46a4ae55ff655c864154d37108689d81ad77daf1
3,637,387
from pathlib import Path import os def analyze_data() -> bool: """ Read file format xml and returns name data Parameters ---------- Returns ------- True: bool Answer - whether the copy was successful """ path_to_file = Path.PATH_TO_PROGRAM + P...
4ad7ae4d5d88e976c440071c283f93ef78d424c1
3,637,388
import copy def cross_validation(docs, values, k): """ docs: Dict with text lists separate by value values: Target values texts k: Steps of cross validation """ group_size = {} confusion_matrix = [] m = {'true':{}, 'false':{}} for value in values: group_size[v...
625a45edf45dc88db6e8c3b5342604891f899ebc
3,637,389
def quote_plus(url, safe='/', encoding=None, errors=None): """Wrapper for urllib.parse.quote_plus""" return uquote_plus(url, safe=safe, encoding=encoding, errors=errors)
159a5e1e25bf35ee08b14f6dca871a4d0bb7f411
3,637,390
def averageSeriesWithWildcards(requestContext, seriesList, *position): #XXX """ Call averageSeries after inserting wildcards at the given position(s). Example: .. code-block:: none &target=averageSeriesWithWildcards(host.cpu-[0-7].cpu-{user,system}.value, 1) This would be the equivalent of ``target=...
479be75db3498a1882c8a27d1a13de85102c52a6
3,637,391
def errore_ddp_digitale(V): """ Calcola l'errore della misura di ddp del multimetro digitale supponendo che si sia scelta la scala corretta. La ddp deve essere data in Volt """ V=absolute(V) if V<0.2: return sqrt(V**2*25e-6+1e-8) if V<2: return sqrt(V**2*25e-6+1e-6) if V<20: retur...
d6504dfce600f5d9af2af33115c2e07b8033cf03
3,637,392
import subprocess import sys def run_command(cmd, get_output=False, tee=True, custom_env=None): """ Runs a command. Args: cmd (str): The command to run. get_output (bool): If true, run_command will return the stdout output. Default: False. tee (bool): If true, captures output (if ...
a7db34c9284ea6c332ff72202c4e8c64d9bdadbc
3,637,393
import os def list_profiles_in(path): """list profiles in a given root directory""" files = os.listdir(path) profiles = [] for f in files: full_path = os.path.join(path, f) if os.path.isdir(full_path) and f.startswith('profile_'): profiles.append(f.split('_',1)[-1]) ret...
1e377b2a686d3c63e569c57af7415a9604b3709e
3,637,394
def extractLine(shape, z = 0): """ Extracts a line from a shape line. """ x = shape.exteriorpoints()[0][0] - shape.exteriorpoints()[1][0] y = shape.exteriorpoints()[0][1] - shape.exteriorpoints()[1][1] return (x, y, z)
c61021b1e3dc6372d9d7554a7033bbd3ab128343
3,637,395
import logging def get_fragility_model_04(fmodel, fname): """ :param fmodel: a fragilityModel node :param fname: path of the fragility file :returns: an :class:`openquake.risklib.scientific.FragilityModel` instance """ logging.warn('Please upgrade %s to NRML 0.5', fname...
62633b156f18c6e722321cf937ea06741aa7a65f
3,637,396
def substring_in_list(substr_to_find, list_to_search): """ Returns a boolean value to indicate whether or not a given substring is located within the strings of a list. """ result = [s for s in list_to_search if substr_to_find in s] return len(result) > 0
77521a1c5d487fa110d5adecb884dd298d2515e5
3,637,397
def downsample_image(image: np.ndarray, scale: int) -> np.ndarray: """Downsamples the image by an integer factor to prevent artifacts.""" if scale == 1: return image height, width = image.shape[:2] if height % scale > 0 or width % scale > 0: raise ValueError(f'Image shape ({height},{width}) must be div...
7d011bda8dc2fccc9782e621bb61d7ab68992640
3,637,398
def getQueryString( bindings, variableName ): """ Columns a bunch of data about the bindings. Will return properly formatted strings for updating, inserting, and querying the SQLite table specified in the bindings dictionary. Will also return the table name and a string that lists the columns (properly formatted...
9cc81601cde229cc5f5bf53ef73997efc515ed2b
3,637,399