content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def parse_oauth_callback(url: str): """Parse the URL to which an OAuth login redirected to obtain two tokens: an access token for API credentials, and a refresh token for getting updated access tokens. """ params = parse_qs(urlparse(url).query) return {k: v[0] for k, v in params.items()}
32c86c635440283538c40f6051dc57bfa61ddeb8
3,604,881
from operator import and_ def unfollow(id): """ Unfollow a user. """ user = session['user'] if user == None: abort(404) followed = User.query.get(id) if followed == None: abort(404) if followed.id == user.id: # don't follow self return redirect(url_for...
7fde25cee21b92388f575de3eca18b5429d33cc6
3,604,882
def giscube_search_get_app_modules(): """Return the Python module for each installed app""" return [i.module for i in apps.get_app_configs()]
c71b05590b0cda84a150e82a32ae5c88a23dd50c
3,604,883
def parse_search_result_data(api_response): """ Parse the search result data from the given raw json by following the response style of tokopedia Arg: - api_response (list): list of products Returns: - product_list (list): list of compiled product properties """ product_list =...
ee1314589e1599f2d4a58523077abc8a7f270f88
3,604,884
def emc_status(hardware, emc, dgtype): """ Make a EMC diagnostic message Fields: - 'val': 0 """ # Make EMC diagnostic status d_emc = DiagnosticStatus(name='jetson_stats {type} emc'.format(type=dgtype), message='{val}%'.format(val=emc['val']), ...
9176e5bd2cce9f6da2954b3b770a281853ccda30
3,604,885
def check_bal_of_tree(node): """.""" if node is None: return True to_visit = [node] while to_visit: curr_node = to_visit.pop(0) if check_bal_of_node(curr_node) > 1: return False if curr_node.left: to_visit.append(curr_node.left) if curr_n...
081a352d7870a551e44f4404a929fc4bd961d250
3,604,886
from typing import Optional def combine_masks( mask1: Optional[np.ndarray], mask2: Optional[np.ndarray] ) -> Optional[np.ndarray]: """Combine two masks as mask1 AND mask2. Ignore any missing mask argument. """ if mask1 is None: if mask2 is None: return None else: ...
15bf7898a5aff7428c11ac534a406a03cb168009
3,604,887
import io from pathlib import Path def _integrate( poni_file: str, img_file: str, bg_img_file: str = None, mask_file: str = None, output_dir: str = ".", bg_scale: float = None, mask_setting: tp.Union[dict, str] = None, integ_setting: dict = None, plot_setting: tp.Union[dict, str] = Non...
73ee451f9c3b365c9773e79385692918797697c7
3,604,888
def magnify_heatmap(df,cm=sns.diverging_palette(5, 250, as_cmap=True)): """Color negative and positive vals for each column to display overall trends per column and row and provide hover function for inspecting individual values.""" cmap = cm bigdf = df.style.background_gradient(cmap, axis=1)\ ...
a55c2aeb8ba06230db878f750e014ad19122ccdb
3,604,890
import torch from datetime import datetime import time def trainning(model: GCN_Class or GCN_Reg, criterion: torch.nn.modules.loss.NLLLoss or torch.nn.modules.loss.MSELoss, train: torch.utils.data.dataloader.DataLoader, test: torch.utils.data.dataloader.DataLoader, ...
05b090f5a735ca4e16f35f94cdfbd1218f5792c5
3,604,891
def check_annulus(args): """ Checks and formats the annulus values. :param args: The command-line arguments. :type args: argparse.ArgumentParser Namespace :returns: argparse.ArgumentParser Namespace -- The updated command-line arguments. """ if not (args.annulus1 and args.annulus...
cd99b7200d226d9e36c644351d8e696a25a1a81d
3,604,892
def computeSignalValueInFrame(startbit, ln, fmt, value): """ compute the signal value in the frame """ frame = 0 if fmt == 1: # Intel # using "sawtooth bit counting policy" here pos = ((7 - (startbit % 8)) + 8*(int(startbit/8))) while ln > 0: # How many bits can we ...
f35a63ea4811b248430ee457c64fda98ea17134d
3,604,893
def submit(): """ Process form's data or redirect if data is not correct. Also redirects if methods!=POST """ if request.method != 'POST': return redirect('/form') if request.form['name'] and request.form['address'] and request.form['postcode'] and request.form['city'] and request.form...
fa241589b7eb7e87e551b90a6d255763415f4dc5
3,604,894
def faceOrientation2Euler(r: np.ndarray, degrees:bool=True) -> np.ndarray: """Converts rodriguez representation of a rotation to euler angles Args: r (np.ndarray): The rodriguez representation vector (angle*u in form x,y,z) degrees (bool): If True, the outputs will be in degrees otherwize in ra...
1576114004127484f91fd7bc8138b9eb1dfc8754
3,604,895
def image_data(xr, x_range, y_range): """Create a tile""" canvas = datashader.Canvas(plot_width=256, plot_height=256, x_range=x_range, y_range=y_range) xri = canvas.quadmesh(xr) image = np.ma.masked_array(xri.va...
a2daa2b493b537e66058ba0eba74086e354431d4
3,604,896
import re def parse_show_spanning_tree_mst_config(raw_result): """ Parse the 'show spanning-tree mst-config' command raw output. :param str raw_result: vtysh raw result string. :rtype: dict :return: The parsed result of the show spanning-tree \ mst-config command in a dictionary of the for...
2f07e13ff7f79e4c15e0fe5111cbc18fb638dae8
3,604,897
from numpy_sugar.linalg import economic_qs from numpy import pi, var, diag from glimix_core.glmm import GLMMExpFam from glimix_core.lmm import LMM def estimate(y, lik, K, M=None, verbose=True): """ Estimate the so-called narrow-sense heritability. It supports Normal, Bernoulli, Probit, Binomial, and Pois...
2c41e519fb9c5adefb01c8d38a62da1b87d1992d
3,604,899
def do_logout(user): """ logout of Google """ return None
2d8b719c2f22de87bc2bdc6f0f6a27eb57ff4982
3,604,900
import torch def astensors(*xs, dtype=None, device=None, escape=None): """Convert input matrices to Tensor(s) or SparseTensor(s). Parameters: ---------- xs: one or a list of python object(s) dtype: The type of Tensor 'x', if not specified, it will automatically use appropriate data type. ...
bccb2337dfa00d32582bd86f7a6732e435b3247d
3,604,901
def system_action(name): """Make a decoractor to register a system action function See `do_system_action` docs for expected function signature. System actions should be submitted with `system_action.submit(...)`. See `submit_system_action` docs for more details. :param name: A unique name to be e...
173d9f3b77da8453ee1f2dd18692b774764e850e
3,604,902
def create_text_covid_symptom_annotations(text_covid_symptom_annotation_request=None): # noqa: E501 """Annotate COVID symptoms in a clinical note Return the COVID symptom annotations found in a clinical note # noqa: E501 :param text_covid_symptom_annotation_request: :type text_covid_symptom_annotatio...
0ad144a54e745a5f799e9fb639f571e35b42b977
3,604,903
def pixel_to_icrs_coords(x, y, wcs): """ Convert pixel coordinates to ICRS Right Ascension and Declination. This is merely a convenience function to extract RA and Dec. from a `~astropy.coordinates.SkyCoord` instance so they can be put in separate columns in a `~astropy.table.Table`. Parameter...
3e9182ada63da17b48ab30683cad1e90eb61f367
3,604,904
def read_sql_file(filename, encoding='utf-8') -> str: """Read SQL file, remove comments, and return a list of sql statements as a string""" with open(filename, encoding=encoding) as f: file = f.read() statements = file.split('\n') return '\n'.join(filter(lambda line: not line.startswith('--'), s...
bd29c1080b2fd95d690b4696bf63c92932616964
3,604,905
def random_shear(x, intensity, row_axis=1, col_axis=2, channel_axis=0, fill_mode='nearest', cval=0.): """Performs a random spatial shear of a Numpy image tensor. # Arguments x: Input tensor. Must be 3D. intensity: Transformation intensity in degrees. row_axis: Index of ...
b6521c6fd1e4a3c223a110704bdf56ed7cfa7e37
3,604,906
def scenegraphLocationString(dataPacket): """ Given a datapacket, return a string representing its location in the scenegraph. (::UUID:OUTPUT) """ return "::"+str(dataPacket.sourceNode.uuid)+":"+dataPacket.sourceOutputName
027a69984acac4454e27a149ad822864751a0983
3,604,908
def lastsample(df): """ Return the last sample in the data frame. >>> lastsample(empty) nan >>> lastsample(sample) 8.0 """ if len(df) == 0: return nan else: return df.iloc[-1, 0]
2ab385dbc89f5520da1827265a6c65a6ab94dcce
3,604,909
def selu(x): """Scaled Exponential Linear Unit. (Klambauer et al., 2017) # Arguments x: A tensor or variable to compute the activation function for. # References - [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515) - Taken from keras.activations (selu got included o...
cd09b405fe19515f3a66dd10e51e136d9b577217
3,604,910
def eeg(): """ EEG information """ # If they clicked on the submit button if request.method == "POST": return render_template("transportation.html", transportation_csv=transportation_csv[session["language"]], layout=layout[session["language"]]) else: language_set() return...
c11d0d9a50c0655d9a246e9a53252fb2d5294cb2
3,604,911
def lightness_Fairchild2010(Y, epsilon=1.836): """ Computes *Lightness* :math:`L_{hdr}` of given *luminance* :math:`Y` using *Fairchild and Wyble (2010)* method according to *Michealis-Menten* kinetics. Parameters ---------- Y : array_like *luminance* :math:`Y`. epsilon : numeri...
aa68d927087edd3ba8930fabd020ee2a21424e0c
3,604,913
def resolve(data, ind, pos, sig, geo, comp, shift=0): """Resolves depth information.""" # Pack arguments as list and run pos = partition(pos, comp['workers']) sig = partition(sig, comp['workers']) data = partition(data, comp['workers']) ind = partition(ind, comp['workers']) shift = [shift] ...
8db7a5264af473a6665a12dad04e1bd706df3c0f
3,604,914
def fitness_f(x): """the fitness function compares the position of each gene with the optimal""" n = 0 for i in range(len(x.genes)): if word[i] == x.genes[i]: n += 1 return n
106fd2c709fe25d0e192ba87d375b4ae6c5761bb
3,604,915
def quaternion2euler(quaternion, degrees=False): """Converts scipy quaternion into euler angle representation. Euler angles have degeneracies, so the output might different from the Euler angles that might have been used to generate the input quaternion. Euler angles representation also has a sing...
4342a4e8e316334b1f95ac9674a76f58c5f3e2b7
3,604,916
def get_data_to_update_from_broker(file_type, database_columns, broker_table, fiscal_year, fy_start, fy_end, unique_identifier): """ Generates SQL script to pull data from broker and compare it with website table Creates Temporary table of the rows that differ ...
675ccbce6e58e62568479c905a36b046e74e2399
3,604,917
def toggle_monitor(self, user=None): """Toggles monitor and returns the newly created monitor, or None if an existing monitor was deleted.""" if not user: user = get_current_user() if self.has_direct_monitor(): self.has_direct_monitor().delete() if hasattr(self, '__monitor'): del...
499f320d10bbbd4172cbd24caef82dd570c58ec6
3,604,918
import copy def get( key, default="", delimiter=":", merge=None, omit_opts=False, omit_pillar=False, omit_master=False, omit_grains=False, ): """ .. versionadded:: 0.14.0 Attempt to retrieve the named value from the minion config file, pillar, grains or the master conf...
794a7bbb1fe3129ff4bc81322c4c3449cc8a509e
3,604,919
from bs4 import BeautifulSoup def extract_paragraphs(txt: str) -> list: """ Extracts the paragraphs from HTML code as defined by the <p> anchor. :param txt: String of the content to derive an embedding for. :return: List of all the paragraphs. """ soup = BeautifulSoup(txt, features='html5lib'...
9f8e1cd43420c27a65ececaba2efb8d16ceb357d
3,604,921
import time def get_epoch(year, month='01'): """ calculate the epoch of first day of a year-month """ pattern = '%Y.%m.%d %H:%M:%S' return int(time.mktime(time.strptime(str(year) + '.' + str(month) + '.01 00:00:00', pattern)))
4126b720dedb0c91ec18f5198740896035da07e7
3,604,922
def get_directive_type(directive): """Given a dict containing a directive, return the directive type Directives have the form {'<directive type>' : <dict of stuff>} Example: {'#requirement': {...}} --> '#requirement' """ keys = list(directive.keys()) if len(keys) != 1: raise ValueError(...
584c1f22fc120815e79c781fc7ace69940c0f651
3,604,923
def process_articles_results(source_articles_list): """ Function that processes source articles result and transfroms them into a list of Objects Args: source_articles_list : A list of dictionaries that contain source articles details Returns: source_articles_results : A list of source ...
644f3da03f61639ce3312d45014a4a69b55f41c3
3,604,924
import torch def MaskedNLL(target, probs, balance_weights=None): # adapted from https://gist.github.com/jihunchoi/f1434a77df9db1bb337417854b398df1 """ Args: target: A Variable containing a LongTensor of size (batch, ) which contains the index of the true class for each corr...
17132ad088b00ae096f16946f5026ed2133c8eeb
3,604,926
def set_log_level(level): """set_log_level(std::string level)""" return _RMF.set_log_level(level)
a3cd680429fbda53fb9e7238d02a0cfd5c80aaf8
3,604,927
import json def get_notebook_cells(path): """获取ipynb文档的cells""" with open(path, "r", encoding="utf-8") as f: data = json.load(f) return data["cells"]
a7f4c9b45b1c58bdcf049c0834199f1a36402fa0
3,604,928
def jacobi(n, alpha, beta, monic=0): """Returns the nth order Jacobi polynomial, P^(alpha,beta)_n(x) orthogonal over [-1,1] with weighting function (1-x)**alpha (1+x)**beta with alpha,beta > -1. """ if n < 0: raise ValueError("n must be nonnegative.") wfunc = lambda x: (1-x)**alpha * (1...
8dbbe468c0322d23c7605595305becccc55e10b6
3,604,929
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Async setup hass config entry.""" hass.data[DOMAIN] = {entry.entry_id: {TUYA_HA_TUYA_MAP: {}, TUYA_HA_DEVICES: set()}} success = await _init_tuya_sdk(hass, entry) if not success: return False return True
9cb3b8b09f879fc8b1466c7bc083e15a138ead1b
3,604,930
def _get_vasprun(args): """ Internal method to support multiprocessing. """ return Vasprun(args[0], ionic_step_skip=args[1], parse_dos=False, parse_eigen=False)
3626be15c816e4987f910fa187b17d7a7dcf03c2
3,604,931
def get_state_dependencies(state): """ Returns all of the states that this state depends on """ return states[:states.index(state)]
e67e40fb78b90f306d1a22b15872203d3253fbc9
3,604,932
def grover_circuit(): """ Builds a QuantumCircuit of the qiskit aqua implementation of grover's algorithm with set parameters. Args: Returns: Resuling circuit of the qiskit aqua implementation of Grover's algorithm after adding measures on every qubit. """ sat_cnf = """ c E...
f35bb3c553696801bb2be4c160db6c1ad5969390
3,604,933
def u8(x: int) -> bytes: """ Encode an 8-bit unsigned integer. """ assert 0 <= x < 256 return x.to_bytes(1, byteorder='little')
c23bb4b6ea6bb610da5c3ecd281129e0bcc40bb7
3,604,934
def state() -> str: """Return the state of the sensor.""" for item in FEED.entries: last_updated = str(item.guid).replace("Country ", "") last_updated = str(dt.strptime(last_updated, "%a, %d %b %Y %H:%M:%S GMT")) return last_updated
021cc6ad4b2c2407f80cbabd6b295917c5500203
3,604,935
def ultimate_answer(question): """Provides an answer to the ultimate question. Returns '42' if the question is 'What is the meaning of Life, The Universe, Everything?' otherwise returns 'That is not much of a question' args: question (str): The question to be answered. returns...
5fc1c51c3901d3005adc78468668317f86e54d5c
3,604,936
def find_class_args(klass): """ Find all class arguments (parameters) which can be passed in ``__init__``. """ args = set() for i in klass.mro(): if i is object or not hasattr(i, '__init__'): continue args |= set(find_function_args(i.__init__)) return list(args)
37e6c8f75ed2f04ed6dd9301b2944a8cdf4bab0f
3,604,937
from .internal.domain import gt_domain def transliterate(text, source_language="auto"): """ Returns the transliteration provided by Google Translate (if available)\n i.e Ohayou --> おはよう / おはよう --> Ohayou """ if driver is None: raise BrowserError("Browser is not set yet.\n Please set it wit...
d4d85f80e25f22ceb118d16ee367c7c5b4306ef7
3,604,938
def last(s): """Return a word string sorted alpha-ly by last char in each word. input = string, words output = string, sorted words alphabetically by last char ex: "man i need a taxi up to ubud") ==>["a", "need", "ubud", "i", "taxi", "man", "to", "up"] """ alpha = list(map(chr, range(97, 123))...
ed1fc01420d1b89e6b52a54e7413e54fbc8ed691
3,604,940
from pathlib import Path from typing import Dict def git_find_remotes(p: Path) -> Dict[str, str]: """从git项目中找到远端仓库url. Args: p (Path): 目标地址 Raises: AttributeError: 如果路径不是git项目则会抛出 Returns: Dict[str, str]: 远程仓库的本地命名和对应地址 """ d = make_repod(p) if not is_git_dir(d)...
2fdc884bc2bdd5943f6fd753563d3e3ed6efb152
3,604,941
def _vectorize_intersection(f): """Vectorize a function f(DAG, node) for one or more nodes, return set intersection.""" def wrapper(DAG, nodes): return set.intersection(*(set(f(DAG, node)) for node in _set(nodes))) return wrapper
0aa1bdaebd97429f09f8a09aa9b57f68bfa3680a
3,604,942
from datetime import datetime def register(email, password, confirmed=True, next_action_uri=None, _invoke_handler=True): """ Register new user in traditional way Args: email: user email password: user password confirmed: if no, e...
b829f0032e0fea2dfbef98cd77df451ed9a0dd3c
3,604,943
def get_u_for_capture(searchers: dict, V: list, v: int): """Return a list with the all searchers vertex u that could capture the target placed at v""" my_list = [] for s_id in searchers.keys(): s = searchers[s_id] for u in V: # get capture matrix C = s.get_capture_mat...
c3265082d9db032f343118e29dc3d4a844298932
3,604,944
def get_name_color(*args): """ get_name_color(_from, ea) -> color_t Calculate flags for 'get_ea_name()' function. Get name color. @param _from: linear address where the name is used. if not applicable, then should be BADADDR . The kernel returns a local name color if t...
c3a431eae9c3ca05cd584eafc24874d76efa95ff
3,604,945
def spectral_moment(k, matrix): """ Return k-th spectral moment of a matrix parameters: matrix """ return np.sum(np.power(spectrum(matrix), k))
821634a2b02017d3a8c027fec5718e7f2001820a
3,604,946
from typing import Dict async def authentication_token_from_email( *, client: AsyncClient, email: str, db_session: AsyncSession ) -> Dict[str, str]: """ Return a valid token for the user with the provided email. If the user doesn't exist, it is created first. """ password = random_lower_stri...
5f68a9dc4d74152382e972e076fae24fdeaa959a
3,604,948
def fit_O2_Ar(df, length): """ fit O2 and Ar signal to a linear line for O2 correction Parameters ---------- df : DataFrame DESCRIPTION. length : int The index of DataFrame of how far the dataset is fitting. Returns ------- slope, intercept and r_square. """ ...
372f911fc83f216d17a4044d5b43b35b508a1f1f
3,604,949
def compare_score(path_region, path_full, score_str, conf_interval=True, return_stat=False): """This function is used to compare the region-based calibration score and full-image based calibration score """ score_region, percent_pixel_region = load_score(path_region, score_str, "region") score_full,...
8a37b3e6738312d65ea0268d019a7e7415245c97
3,604,950
import requests def post_through_spectre(path, data=None, extra_headers=None): """This simulates a client POSTing to a service proxied through Spectre. """ headers = HAPROXY_ADDED_HEADERS.copy() if extra_headers is not None: headers.update(extra_headers) return requests.post(SPECTRE_BA...
a941c85070ed1d6c75b2e38f70ebb483d7e626e8
3,604,952
def rule_confidence(rule: IndexRule, binary_data: np.ndarray) -> float: """ Confidence of a rule (x -> y) in the transactions represented by binary_data :param rule: a tuple where the first element is the set of indexes for the left side of the rule (x) and the second element is the set of indexes for t...
572c4425a98b875593b0b2a2fa73a0db94524ac2
3,604,953
def evaluate_poly(poly, x): """ Computes the polynomial function for a given value x. Returns that value. Example: >>> poly = (0.0, 0.0, 5.0, 9.3, 7.0) # f(x) = 7x^4 + 9.3x^3 + 5x^2 >>> x = -13 >>> print evaluate_poly(poly, x) # f(-13) = 7(-13)^4 + 9.3(-13)^3 + 5(-13)^2 180339.9 po...
2705dbdaa937c564454078dc2cbc8dd4a9bd56e8
3,604,954
def currency_format(currency="USD", suffix=""): """Currency formatter for matplotlib. :param currency: Name of the currency, e.g. 'USD', 'GBP'. :param suffix: Suffix to append, e.g. 'B'. Defaults to ''. :returns: FuncFormatter. """ prefix = { "USD": "$", "GBP": "£" }[curre...
65d4e1739d92bf93736269579ee6369d46b3ab4a
3,604,955
import base64 def json_to_numpy(obj): """Decodes a dict from json into a numpy array""" dtype = obj['dtype'] if dtype == 'string': dtype = 'str' if 'data' in obj: return np.array(obj['data'], dtype).reshape(obj['shape']) data_bytes = base64.decodebytes(obj['dataEnc'].encode()) ...
313b2a9b4df7393cd3da10492b2b553482f7ef04
3,604,956
from ase import Atoms from ase.calculators.lj import LennardJones from pinn.io import load_numpy, sparse_batch from pinn.models import potential_model import tempfile def test_potential_model(): """A simple example to test training and using a potential""" def three_body_sample(atoms, a, r): x = a * n...
b57be7be108f41fd617f408f8835b735723369a0
3,604,957
def get_segm_by_name(*args): """ get_segm_by_name(name) -> segment_t Get pointer to segment by its name. If there are several segments with the same name, returns the first of them. @param name: segment name. may be NULL. (C++: const char *) @return: NULL or pointer to segment structure """ return ...
bce51941886f5ceaa22e9d75e2e4352193582666
3,604,959
def assign_pt_to_grid(XYs, grid, distance_metric='euclidean', random_state=None): """ Spatial join pts to grids. Reassign border points to nearest grid based on centroid distance. """ np.random.seed(random_state) XYs = convert_geodataframe(XYs) # Equate spatial reference systems if defined ...
ae893fb99a68158104c96ba2812e65e80dc256fa
3,604,960
def svn_diff_contains_conflicts(*args): """svn_diff_contains_conflicts(svn_diff_t diff) -> svn_boolean_t""" return _diff.svn_diff_contains_conflicts(*args)
b0eb8d8555700326d522a6eb370aa03b2a3e9d38
3,604,961
import re def ask_for_droplet_name() -> str: """ Present a prompt for the user to enter a name for the droplet. Valid droplet name characters: a-z, A-Z, 0-9, . and - :return: str (the preferred name) """ pattern = re.compile("^[a-zA-Z0-9]+[-.a-zA-Z0-9]*$") q = question( message="E...
014d3c1af4deef37f42b697b4c01a4978da9abb1
3,604,962
def applyIncidenceFilter(image, bandNames, classDictionary, numChangesCutoff = 8, connectedPixelCutoff=6): """ Function to apply an incidence filter. The incidence filter finds all pixels that changed more than numChangesCutoff times and is connected to less than connectedPixelCutoff pixels, then replaces ...
fe481ba5342b4e40c8a75b9c59bfe393dd9ad3dc
3,604,963
def loadJsonConfig(jsonobj_or_fn): """Loads the visualization options from a JSON object or file. jsonobj_or_fn can either by a dict (previously obtained by saveJsonConfig or a str indicating a filename (previously saved using saveJsonConfig.) """ return scene().loadJsonConfig(jsonobj_or_fn)
3955ae668078a776eaf16ae209b777aa1e74babc
3,604,964
def load_expected_whitelist(filename, logger): """ **Purpose** Load the expected whitelist and output a set """ expected_whitelist = [] oh = open(filename, 'rt') for line in oh: expected_whitelist.append(line.strip()) oh.close() expected_whitelist = set(expected_whiteli...
097981e4d7e2c44931cdeebd935e6ba2b8f78e38
3,604,965
def split(string_to_split, separator): """Returns the list of strings divided by the separator.""" return string_to_split.split(separator)
c96d4ed6e3128617925c7d52c19d607cbfe1ece1
3,604,966
def create_user( username: str, password: str, is_admin: bool = False, is_manager: bool = False, is_active: bool = True, ) -> str: # pragma: no cover """ Create User Params: * **username** String, required. * **password** String, required, will be set through `set_password`....
10abff306b5243b87557d8369dc37a9c0059cd88
3,604,968
def _find_biggest_value(list): """ Get the intex of the largest value in list of values :return: -1 if list empty, otherwise index of biggest value """ if len(list) < 1: return -1 max = 0 for idx, val in enumerate(list): if val > list[max]: max = idx return ...
e4c4267ac2bfe73ad3bdb11433935805f4859e95
3,604,970
def open_file(experiment_id='piControl', source_id='BCC-CSM2-MR', path='/glade/u/home/molina/CMIP6_pathnames.csv'): """ Parameters ---------- Input: experiment_id = type of experiment (e.g., piControl, ssp585, historical) """ data_list = pd.read_csv(path) if source_id...
db723fa2d1be274800cfeab698610e9f9aa27e3f
3,604,971
def populate_index(dataset_loader, module_dea_index): """ Index populated with example datasets. Assumes our tests wont modify the data! It's module-scoped as it's expensive to populate. """ loaded = dataset_loader( "s2a_ard_granule", TEST_DATA_DIR / "s2a_ard_granule.yaml.gz" ) asse...
8a0e2570e019554b8da1557209b3bae4b14e6807
3,604,972
from typing import List from typing import Union def solve_sudoku_CSP(sudoku: List[List[int]], k: int) -> Union[List[List[int]], None]: """Solve a k-by-k block Sudoku puzzle by encoding the problem as a collection of constraints and using a constraint satisfaction problem (CSP) solver :param sudoku: A...
0a15743a38a93b15f271f3c68a164ca4e3cc0267
3,604,973
def calculate_direct_distance(route): """calculate distance between start and end point of route. input: route = list of paths, which are lists of points in route. output: direct distance, in meters """ starting_pt = route[0][0] destination_pt = route[-1][-1] return haversine(*starting...
83465f8e78a1a588717567f9a86e72da1847f03a
3,604,974
def test_search_url_callbacks_not_found(tmpconfig): """Test search_url_callbacks when pattern does not match.""" sopel = bot.Sopel(tmpconfig, daemon=False) results = sopel.search_url_callbacks('https://example.com') assert not list(results), 'No handler registered; must return an empty list' def ur...
99230b8f331eedb8b110646eae66c2ae20428b8d
3,604,975
def calculate_cohens_d(values_1: np.ndarray, values_2: np.ndarray) -> float: """Calculate Cohen's d using pooled standard deviation. :param values_1: First array of values :type values_1: np.ndarray :param values_2: Second array of values :type values_2: np.ndarray :returns: Cohen's d effect ...
9ccc07effa125c3b5026866f2e2c13373801eb00
3,604,976
def generate_image(session, pg_gan_model, tl_gan_model, features, feature_names): """ Converts a feature vector into an image. """ # Create rescaled feature vector feature_values = np.array([features[name] for name in feature_names]) feature_values = (feature_values - 50) / 250 # Multiply by...
0b422b999956e60f937d3e863eca8e169a5bc150
3,604,977
from datetime import datetime def validate_date_input(requested_date): """ date validation. Args: requested_date (date) - date requested for forecast. Returns: (bool) - validate ended in success or not. (str) - error message. """ if isinstance(requested_date, datetime.date)...
0f96f0c61407061180d18ae841065c57cda7bdbc
3,604,978
import numpy def haversine(coord1, coord2, to_radians=True, earth_radius=6371): """ slightly modified version: of http://stackoverflow.com/a/29546836/2901002 Calculate the great circle distance between two points on the earth (specified in decimal degrees or in radians) All (lat, lon) coordinate...
46d073421bed55e0ccd11f995dbcbfdaf5124720
3,604,979
def inline(s, fmt): """Wrap string with inline escape""" return "`\u200B{}\u200B`".format(fmt.format(s))
3f07a4f55e60c763a10956c9ac52314b6958eca8
3,604,980
def has_row_check(table, conn): """Check if there is any row in table. Args: table(str): Name of the table conn: connection to the database Returns: True if row count > 0, else False """ row_count = pd.read_sql(sql=row_count_check.format(table=table), con=conn).loc[0, 'count...
ac99ab1c4c593d8c2015d5f285b3ec2b65c925f3
3,604,982
from typing import Optional import cgi def format_download_filename(content_disposition: Optional[str], download_url: str) -> str: """Uses RFC-6266 'Content-Disposition' header to get file name""" value, params = cgi.parse_header(content_disposition or '') download_filename = params.get('filename') ...
0abd0d17db1b92afff1fc5163aadd6450dac7e1c
3,604,983
def ct_vpeak(Zb,Ip,N): """ ct_vpeak Function Simple formula to calculate the Peak Voltage of a CT. Parameters ---------- Zb: float The burden impedance magnitude (in ohms). Ip: float The peak current for the CT. N: float ...
56ce939e7e7507f27577d115f326027e9ea0253b
3,604,984
from typing import Sequence from typing import Optional from typing import Dict def calculate_prensors( expressions: Sequence[expression.Expression], options: Optional[calculate_options.Options] = None, feed_dict: Optional[Dict[expression.Expression, prensor.Prensor]] = None ) -> Sequence[prensor.Prensor]...
2dc8dc131c9d87947b40021264ab5a51c86fcee2
3,604,985
def network_matched_filter_snr(IFO_matched_filter_snrs, IFO_optimal_snrs): """Return the network matched filter SNR for a given detector network. Code adapted from Christopher Berry's python notebook Parameters ---------- IFO_matched_filter_snrs: list list of matched filter SNRs for each IF...
d9ec28ab4f988e48f20ac29ec7d4fa74b2e754a7
3,604,986
def scale(df: pd.DataFrame, scale: dict): """ apply a z-transformation (centering) to some dataframe""" return (df - scale['mean']) / scale['sd']
c832dc5535f1db597e83e8872d9d8fec3b11fec1
3,604,988
import types def new_coverage(*args, **kwargs): """ xml_report """ r = orig_coverage(*args, **kwargs) r.orig_xml_report = r.xml_report r.xml_report = types.MethodType(new_xml_report, r) return r
e1a0f01191fdb9b10c29a3a69b4eb8755afac2d6
3,604,989
def delete_ticket(request): """ Delete a ticket :param request: ticket.id the ticket id :return: """ # Get actual user actual_user = User.objects.filter(username__iexact=request.user.username)[0] ticket_id = request.GET.get("ticket_id", None) ticket_to_delete = Ticket.objects.filter...
590f41b64ab1294b17bc1c90565d3da5a0c2f360
3,604,990
def cov(a, b): """ Computes covariance only between terms of a and terms of b, not within a and b. Parameters ---------- a, b: 2darray, features x samples Returns ------- Covariance between features in x and features in y """ demeaned_a = a - np.mean(a, axis=1, keepdims=Tru...
aba834a654df2415cadd3a7579247c0b333d1dcd
3,604,991
def _compute_cultural_score_building(building_geometry, historical_elements_gdf, historical_elements_gdf_sindex, score = None): """ Compute pragmatic for a single building. It supports the function "pragmatic_meaning" Parameters ---------- buildings_geometry: Polygon building_land_use: s...
743be39a3c100f53787df8195298c43affac8b4d
3,604,994
def extract_footprint_location(footprint): """ Constructs a location from a building footprint. :param footprint: pandas row representing a building footprint. """ type_ = extract_location_type(footprint) if not type_: return polygon = footprint["geometry"] point = polygon.cen...
38da1ec0da9c51186d8540e55a3fab298300e115
3,604,995
def _rule_spec_from_path(path): """Turn a sequence of path components into a rule spec Args: path (sequence[unicode]): the URL path components. Returns: dict: rule spec dict, containing scope/template/rule_id entries, and possibly attr. Raises: UnrecognizedRequestE...
b8f1bad2e4eb2df4b3343211c87b273f5944c537
3,604,996