content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import typing
def with_any_role_check(
roles: collections_abc.Sequence[typing.Union[hikari.SnowflakeishOr[hikari.Role], int, str]] = [],
*,
error_message: typing.Optional[str] = "You do not have the required roles to use this command!",
halt_execution: bool = False,
) -> collections_abc.Callable[[Comm... | 69a448ed7849900d32d800dc71ad0ba79057228f | 3,615,100 |
def split_path(path):
"""
Normalise S3 path string into bucket and key.
Parameters
----------
path : string
Input path, like `s3://mybucket/path/to/file`
Examples
--------
>>> split_path("s3://mybucket/path/to/file")
['mybucket', 'path/to/file']
"""
if path.startswi... | 446f7643066864937e11b915d4ff842f21c65dd6 | 3,615,101 |
def unixtime2mjd(unixtime):
"""
Converts a UNIX time stamp in Modified Julian Day
Input: time in UNIX seconds
Output: time in MJD (fraction of a day)
"""
# unixtime gives seconds passed since "The Epoch": 1.1.1970 00:00
# MJD at that time was 40587.0
result = 40587.0 + unixtime / (2... | 670e915b7a5de8cd9ced28e6b4d32c51ac916d54 | 3,615,102 |
import pydoc
def splitdocfor(path):
"""split the docstring for a path
valid paths are::
./path/to/module.py
./path/to/module.py:SomeClass.method
returns (description, long_description) from the docstring for path
or (None, None) if there isn't a docstring.
... | cdbf516b648b57fff0e9ceec750759aa65d0626a | 3,615,103 |
def vecdist3(coord1, coord2):
"""Calculate vector between two 3d points."""
#return [i - j for i, j in zip(coord1, coord2)]
# Twice as fast for fixed 3d vectors
vec = [coord2[0] - coord1[0],
coord2[1] - coord1[1],
coord2[2] - coord1[2]]
return (vec[0]*vec[0] + vec[1]*vec[1] + ... | 0315ec921c051eb46da9f073e6bc76b2a0a448bb | 3,615,104 |
def svn_wc_get_status_editor(*args):
"""
svn_wc_get_status_editor(svn_wc_adm_access_t anchor, char target, apr_hash_t config,
svn_boolean_t recurse, svn_boolean_t get_all,
svn_boolean_t no_ignore, svn_wc_status_func_t status_func,
svn_cancel_func_t cancel_func,
svn_wc_traversal... | b0dc063e54b4ac337833edbf2220a26402a7c5d3 | 3,615,105 |
def getFORCodes(node, kw):
"""
Helper function for retrieving and organising FOR codes from the CSV file that contains them.
:param node: Node that the returnd values are for.
:param kw: Arguments that are passed to the shema's bind() method.
:return: OrderedDict of FOR codes nested appropriately.
... | 4d05fb78f47f3449d65cebd535e5f874148f6e01 | 3,615,106 |
def num_active_calls(log, ad):
"""Get the count of current active calls.
Args:
log: Log object.
ad: Android Device Object.
Returns:
Count of current active calls.
"""
calls = ad.droid.telecomCallGetCallIds()
return len(calls) if calls else 0 | a6674df1e8e539478db6ab1a640fbce1cf0b6b4c | 3,615,107 |
import os
def load_rsa(chain, data_path):
"""
func: load rsa fea array from acc file
"""
rsa_vector = {"e": [1, 0], "-": [0, 1], "b": [0, 1]}
rsa_f = os.path.join(data_path, chain, chain+".acc")
rsa_fea_arr = []
f = open(rsa_f, "r")
rsa_str = f.readlines()[-1].strip()
f.close()
... | c53dfcb1b323a05a5d1cbebf5cba35a4f648ad6f | 3,615,108 |
def module_create_from_connection_string(transportType, connectionString, caCertificate=None): # noqa: E501
"""Create a module client from a connection string
# noqa: E501
:param transportType: Transport to use
:type transportType: str
:param connectionString: connection string
:type connect... | 16df883f99e8ad3a7751fa70845fb60962bf1c02 | 3,615,109 |
def ldns_rdf_new_frm_fp_l(*args):
"""LDNS buffer."""
return _ldns.ldns_rdf_new_frm_fp_l(*args) | d4549e4ccde6b5ebb090ea9cca6ea3b05482df82 | 3,615,110 |
import math
def run_experiment(fr: int, to: int) -> (int, int):
"""Run the classical part of Shor's algorithm."""
n = get_odd_non_prime(fr, to)
a = get_coprime(n)
order = classic_order(a, n)
factor1 = math.gcd(a ** (order // 2) + 1, n)
factor2 = math.gcd(a ** (order // 2) - 1, n)
if factor1 == 1 or fa... | 04ea055743b519f4c32c853fa161877a7c5c21e2 | 3,615,111 |
def backward_prop(data, labels, params, forward_prop_func):
"""
Implement the backward propegation gradient computation step for a neural network
Args:
data: A numpy array containing the input
labels: A 2d numpy array containing the labels
params: A dictionary mapping parameter ... | f91560c56e694b08b845e26fe320f453c894d361 | 3,615,112 |
def homepage(js):
"""
Extract an URL for that researcher (if any)
"""
lst = jpath(
'person/researcher-urls/researcher-url', js, default=[])
for url in lst:
val = jpath('url/value', url)
name = jpath('url-name', url)
if name is not None and ('home' in name.lower() or '... | 64b50cf0bc1a8324b480cf4d8cd63606e5a7d95c | 3,615,113 |
import argparse
def get_args():
"""
read parser and return args (as args namespace)
"""
parser = argparse.ArgumentParser(description='Ask an host for Serial Number')
parser.add_argument('-d', '--debug', action='store_true', help='Active le debug')
parser.add_argument('-H', '--host', nargs=... | 04d3e20a1c3b743139dc9cf66a060a93611ce09e | 3,615,114 |
import os
def create_dir(ctx, param, value):
""" a command option callback to create parent directories if does not exist """
pardir = os.path.dirname(value.name) if hasattr(value, 'name') else None
if pardir:
os.makedirs(pardir, exist_ok=True)
return value | 6a573ebbc0ddc5c4a8f0f15fa0fc91566610bc28 | 3,615,115 |
def get_result(filename):
"""
This route returns the details of the analysis relative to the filename specified
along with the source code analyzed
"""
response = {
"success": True,
"data" : {
"by_context" : utils.getAnalysisResultByContext(app.config, filename),
... | 5aec0ef12070293ee4fa3d457145f650161a6afb | 3,615,116 |
def reader_mock() -> AsyncMock:
"""Cria um objeto reader mock para os testes."""
reader = AsyncMock()
return reader | f262b2d5949fd6630ed53c8879e532d39d27b399 | 3,615,117 |
def _blkidx(n_s=3):
"""Calculate indices for a 3x3x3 grid around an index of 0"""
return (np.array(np.where(np.zeros((n_s, n_s, n_s)) == 0)).T - (
(n_s - 1) / 2)).astype(int) | 04c996d2d1249fa5c36557bb4165f7193ecc4331 | 3,615,118 |
def cdsem_bend180(
width: float = 0.5,
radius: float = 10.0,
wg_length: float = LINE_LENGTH,
straight: ComponentFactory = straight_function,
bend90: ComponentFactory = bend_circular,
cross_section: CrossSectionFactory = strip,
text: ComponentFactory = text_rectangular_mini,
) -> Component:
... | e0b8b6012ca719478b73e8a9130639382b6bde44 | 3,615,119 |
def EWMA(inputs, *args, **kwargs):
"""EWMA of an inputted list, returns the weighted list. """
if "alpha" in kwargs:
alpha = kwargs.get("alpha")
if alpha > 1 or alpha < 0:
print("Alpha value cannot exced range of [0,1]!!!")
return
else:
alpha = 0.5 # init, default alpha
S1 = inputs.sum()/len(inputs)
... | fce299fea21d3bcd6d81d2a4d4d0601ed3e9b203 | 3,615,120 |
def desaturate(img_paths, percent=30, write=True):
""" desaturate(img_paths, percent=30, write=True)
Takes image(s) and desaturates them.
:type img_paths: pyifx.misc.PyifxImage, pyifx.misc.ImageVolume, list
:param img_paths: The image(s) to be desaturated.
:type percent: int
:param percent: How much the i... | 59e0a5f8618ecd3c93d5a31c5698978e77ce1bf9 | 3,615,121 |
def density_standard(components):
"""
Natural gas density at standard temperature, kg/m3
:param components: (list) List of gas components. Each item is an object of class GasComponent
:return: (float) The density of natural gas an standard parameters, kg/m3
"""
return sum([component.density_sta... | c087ce6ae1a3486dd092341286023c56606380a3 | 3,615,122 |
def get_latlongrid(dset, xindx, yindx):
"""
INPUTS
dset : xarray data set from ModelBin class
xindx : list of integers
yindx : list of integers
RETURNS
mgrid : output of numpy meshgrid function.
Two 2d arrays of latitude, longitude.
"""
llcrnr_lat = dset.attrs["Concentra... | 35c9467237be0b6853f32b099e74ff618df33529 | 3,615,123 |
def get_WOA_array_1x1_indices(lons=None, lats=None, month=9, debug=False):
"""
Get the indices for given lats and lons in 1x1 WAO files
Parameters
-------
lons (np.array): list of Longitudes to use for spatial extraction
lats (np.array): list of latitudes to use for spatial extraction
month... | cbbf26ea7c3d48a951fa175abece121e77f40581 | 3,615,124 |
def Network_RosslerSystem(Y,t, F,w, A, b, c, Nsys):
"""Defines a set of coupled Rossler Systems in a Network structure.
Coupling is done through the y variable.
The coupling and the network topology is defined by the matrix A.
The sistem is (where (i) * is multiplication element wise
... | 78dcffabd07c79b05e7c4726fe8780450e870f45 | 3,615,125 |
def plot_flux_boxplot(ENSEMBLE_DIR, sample_id, popfva_df, react_plot_list, pheno_id, obj_direction,pre_y=False,
savefig=True,whis=1.5,s_size=100,width=0.5,labelsizes=10,notch=True,jitter=True,linewidth=1,
dodge=True,palette=["#2020FF", "#FF0303"],f_scale=1.0,figSIZE=(40,5),pl... | a32f7799a080ad2d102eabe779aa468687287a3a | 3,615,126 |
def getStudentByID(studentID):
"""
根据学生ID获取学生
"""
condition = 'studentID={}'.format(studentID)
return generalGet('student', 0, condition) | 925b032a2bc74acec7b929e4fd1f56de0e52b83d | 3,615,127 |
import re
def range_address_number(num, include_last=True):
"""
'5-7' -> [5, 6, 7]
'5' -> ['5']
:param num:
:return:
"""
range_re = re.search('(\d+)-(\d+)', num)
if range_re:
min, max = list(map(
lambda i: int(i),
list(range_re.groups())
))
... | 3c67ddcba2a25915fce89c198d4d4f2a11f5ef60 | 3,615,128 |
def generate_test_uuid(tail_value=0):
"""Returns a blank uuid with the given value added to the end segment."""
return '00000000-0000-0000-0000-{value:0>{pad}}'.format(value=tail_value,
pad=12) | f113eef54eba9d8d1fb5234c87af3cb6290ea25e | 3,615,129 |
def copy_cluster_decoys(decoy_list, target_dir, create_dir=True, verbose=True, **kwargs):
"""
Copy cluster decoys specified in <decoy_list> to <target_dir>.
Args:
decoy_list (list):
| output of abinitio.get_decoy_list()
| or cluster.rank_cluster_decoys(return_path=True)
... | 44e3767179d03d84a5b174f0473cf75d23a6435b | 3,615,130 |
def download(url, destination, overwrite=False):
"""
Download a file
:param url: URL to download from
:type url: str|unicode
:param destination: target path and filename for downloaded file
:type destination: str|unicode
:param overwrite: specify whether or not an existing destination shou... | ae948f7790460c008f554ef4f8bd97b7bda1f584 | 3,615,131 |
def create_sub_graph_copy(graph: Graph, nodes_to_extract: list):
"""
Create new graph which is a sub-graph of the 'graph' that contains just nodes from 'nodes_to_extract' list. The
returned sub-graph is a deep copy of the provided graph nodes.
:param graph: graph to create a sub-graph from.
:param n... | efadb29c9bb522e448cb07079f17b4e0c51956e1 | 3,615,132 |
def descent_direction_i(X, i):
"""
Returns the 3D vector for the direction of decreasing energy at point i.
Parameters
----------
X : numpy.nadarray, with shape (N, 3)
Current configuration of points. Each row of `X` is the 3D position
vector for the corresponding point in the curre... | 0d31adb9ee65cb8f9851c2eeb24c333d3cff780b | 3,615,133 |
from typing import List
def java_args(spark: SparkSession, args: List[str]):
"""
Convert a Python list into the corresponding Java argument array.
"""
rv = SparkContext._gateway.new_array(spark._jvm.java.lang.String, len(args))
# https://stackoverflow.com/a/522578
for index, arg in enumerate(... | f02af6e73cbf9c3505b64e9568b51226c9a1cdd8 | 3,615,134 |
import os
def is_file(path: str) -> str:
"""
Returns true or false if path points to an existing file
:param path: A path to a file
:return: True if file exists and is a file, False otherwise
:raises FileNotFoundError if file does not exist
"""
if not os.path.exists(path):
raise Fi... | af63ea1fbc98b8df24990758015a31b586e50559 | 3,615,135 |
def format_revision_list(revisions, use_html=True):
"""Converts component revision list to html."""
result = ''
for revision in revisions:
if revision['component']:
result += '%s: ' % revision['component']
if 'link_url' in revision and revision['link_url'] and use_html:
result += '<a target="... | d49e91069a1f33a7ee32963e81a3e19ea768d3ea | 3,615,136 |
def order_table(headers, table, order_column, natural_order=None, limit=None):
"""
:type natural_order: list
:param natural_order: define the order for each column.
if the value in natural_order is true, the reverse is True else False
[True, False, True]
build the table
"""
if len(head... | 68b1c3fbd53799267707eb2788e9115f3fd943e2 | 3,615,137 |
import logging
def respond_to_build(slack_client, branch, build_num, build_id, thread_ts):
"""Take action on successful build results."""
logging.debug("Responding to build: Branch-%s; BuildNum-%s; BuildID-%s; ThreadID-%s", branch, build_num, build_id, thread_ts)
is_production = False
if branch == 'de... | 54f484f9e773baec7c5379136cb3569e38792c60 | 3,615,138 |
import sys
def find_new_centroids(parameters: Parameters,
data_eng: DataEng) -> DataEng:
"""Find new cluster centroids by taking the mean
of the data points in the cluster,
Take the mean of all x points: this is our x of the new centroid,
Take the mean of all y point... | 5029439d7215ecce4b639bdfa2c1379c1687a244 | 3,615,139 |
from typing import Dict
async def total() -> Dict:
"""
Sum of a list of numbers
---
tags:
- Total
get:
parameters:
- N/A
response:
200:
description: returns a dictionary with a total sum of a list of numbers
"""
retu... | 67c1d1abf6c76c533d8ea776dbb46a4184b0fca5 | 3,615,140 |
import inspect
def is_extension(cls):
""" Check if a class is a MudPi Extension.
Accepts class or instance of class
"""
if not inspect.isclass(cls):
if hasattr(cls, '__class__'):
cls = cls.__class__
else:
return False
return issubclass(cls, BaseExtensio... | ea58d6107524d1e349c06e7153d38e13c6991cb6 | 3,615,141 |
def kalman_xy(x, P, measurement, R,
motion = np.matrix('0. 0. 0. 0.').T,
Q = np.matrix(np.eye(4))):
"""
Parameters:
x: initial state 4-tuple of location and velocity: (x0, x1, x0_dot, x1_dot)
P: initial uncertainty convariance matrix
measurement: observed position
... | fcc2ae434533e281aeee619350ab9b28f09972de | 3,615,142 |
import click
def create_droplet_click(token):
"""
Creates a droplet in your DigitalOcean account.
Accepts one option (the Digital Ocean API token key).
token: [env var name | path to file | token str] Resolved in that order.
Example:
droplet -t MY_TOKEN
The above will first look at an ... | c7b5c00b59c256fda1e64c041694301a3ca18a21 | 3,615,143 |
def is_view_loaded(view):
"""returns a buf if the view is loaded in sublime and
the buf is populated by us"""
if not G.AGENT:
return
if not G.AGENT.joined_workspace:
return
if view.is_loading():
return
buf = get_buf(view)
if not buf or buf.get('buf') is None:
... | e6db647e079bb40b6dcf419ed6b2d04c9140c439 | 3,615,144 |
def linearmap(x, ymin, ymax, flag='linear'):
"""
Maps given function in the range of ymin, ymax
"""
if flag =='log':
x = np.log10(x)
ymin = np.log10(ymin)
ymax = np.log10(ymax)
xmin = Utils.mkvc(x).min()
xmax = Utils.mkvc(x).max()
y = (ymax-ymin)*(x-xmin)/(xmax-xmin) + ... | 68ddf5d9784ded1f88cca9c1f19e0b25846b7b76 | 3,615,145 |
def Log_SetRepetitionCounting(*args, **kwargs):
"""Log_SetRepetitionCounting(bool bRepetCounting=True)"""
return _misc_.Log_SetRepetitionCounting(*args, **kwargs) | 226ec96f45e40171c8b5f59c11c814c6317819b9 | 3,615,146 |
from typing import Optional
from typing import List
def get_optimal_index_keys_v2(
nb_vectors: int,
dim_vector: int,
max_index_memory_usage: str,
flat_threshold: int = 1000,
quantization_threshold: int = 10000,
force_pq: Optional[int] = None,
make_direct_map: bool = False,
should_be_me... | 90972d9f4a951dfd80bb05c48440a63676ebc047 | 3,615,147 |
import scipy
def laplacian_ij(X,hi,hj):
"""
Compute the LAPLACIAN OPERATOR of an image
"""
M,N = X.shape
D2i = (toeplitz(scipy.append(scipy.array([-2,1]),scipy.zeros((M-2,1))))/(hi**2));
D2j = (toeplitz(scipy.append(scipy.array([-2,1]),scipy.zeros((N-2,1))))/(hj**2));
D2i[0,1] =... | 60080483176071814a8603f952c706bdb282848a | 3,615,148 |
def memoize(f):
"""
A simple memoize implementation. It works by adding a .cache dictionary
to the decorated function. The cache will grow indefinitely, so it is
your responsibility to clear it, if needed.
to clear: `memoized_function.cache = {}`
"""
def _memoize(func, *args, **kw):
... | 5db3894b24017035f8f122cc09e558ee9e034607 | 3,615,149 |
import os
def tidy_concentrations():
"""
tidy the gardner_mt_catastrophe_only_tubulin.csv dataset
melts, removes nan, adds concentration_int columns
"""
# defining path for data
fname = os.path.join(data_path, "gardner_mt_catastrophe_only_tubulin.csv")
df = pd.read_csv(fname, skiprows = ... | 66f7b19fcb3417d583683707a2c73bc356fed432 | 3,615,150 |
from bs4 import BeautifulSoup
def bishijie_info_parse(parse_str:str = ''):
"""
传入一个待解析的字符串
"""
# html_info = etree.HTML(parse_str,parser=None)
soup = BeautifulSoup(parse_str,features="lxml")
info_list = soup.find_all('div',class_="content")
result_info_list = []
for info in info_list:... | e89a875f9c98b3b9cabeed2eb362ad1196b14275 | 3,615,151 |
def connect_tcp(host, port):
""" return Client connected to the TCP socket """
c = Client()
c.setup_tcp_socket(host, port)
c.connect()
return c | 7f87953d3da354c2db1675b262f196758e5bde05 | 3,615,152 |
def parse_args():
"""
Handles argument parsing for bvauto.
"""
res = {}
nargs = len(sys.argv)
if nargs < 2:
print "usage:"
print " Test build_visit on current machine:"
print " bvauto.py [bvauto.input]"
print " Test build_visit on current machine and post result... | 663dd78d98387ccb76e199113f4d77c5a4a68f86 | 3,615,153 |
def state_store(decoy: Decoy) -> StateStore:
"""Get a mocked out StateStore."""
return decoy.mock(cls=StateStore) | 3b3b69b226d884546ef1fd87c069a24faf0b783b | 3,615,154 |
def get_model_specs(model_name):
"""Return a dict with configurations required for configuring `model_name` model."""
if model_name == "lm":
return lm_wikitext2.get_model_config()
elif model_name == "seq":
return offload_seq.get_model_config()
else:
raise RuntimeError("Unrecogni... | 1c0ff40cb550ef79435ec41805daea843a7f138c | 3,615,155 |
def rbf_lmsq_error_d_wrt_ith_g(x, y, g, w, u, i):
"""
radial basis function
least mean square error derivative
with respect to the ith gamma
g : gammas
w : weights
u : centers
"""
return -2 * w[i] * np.linalg.norm(x - u[i]) * gaussian(g[i], x, u[i]) * (rbf_h(x, g, w, u) - y) | bfcbf07a2efa77b487d894c34bcc19dbd851aed9 | 3,615,156 |
def schedule_pool(outs, layout):
"""Schedule for various pooling operators.
Parameters
----------
outs: Array of Tensor
The computation graph description of pool
in the format of an array of tensors.
layout: str
Data layout.
Returns
-------
s: Schedule
... | 7d77f1260e60e0216400c2423d92013cc137470e | 3,615,157 |
def Hamiltonian(N,V):
""" Generates the 'N'-dimensional Hamiltonian matrix of
a 1-d tight binding model for an array nearest neighbor site couplings 'V'
"""
H = np.zeros((N,N))
H[0][1] = V[0]
H[N-1][N-2] = V[N-1]
for i in range(1,N-1):
H[i][i+1] = V[i]
H[i][i-1] = V[i]
... | de94262c8ebe8d2e3fd00b0b63adeef95edaa6c3 | 3,615,158 |
import os
def get_mask(mask_root, mask_paths, ignore_path, use_ignore=True):
"""
Ignore mask is set as the ignore box region \setminus the ground truth
foreground region.
Args:
mask_root: string.
mask_paths: iterable of strings.
ignore_path: string.
Returns:
mask:... | 35e81d35babca1784eaff2b7875dd88bdd3e5c6a | 3,615,159 |
from typing import Iterable
def _create_lines_for_order(
manager: "PluginsManager",
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
discounts: Iterable[DiscountInfo],
) -> Iterable[OrderLineData]:
"""Create a lines for the given order.
:raises InsufficientStock: when there... | f80a82ab022ab5375b6f0b46f4becaec4a72b4ca | 3,615,160 |
import pprint
import warnings
def single_mode(ell, m, **kwargs):
"""WaveformModes object with 1 in selected slot and 0 elsewhere
Additional keyword arguments are passed to `modes_constructor`.
Parameters
----------
ell, m : int
The (ell, m) value of the nonzero mode
"""
if kwarg... | a2f83370ae82119f3805dddc4a049f96b4db9dcc | 3,615,161 |
def files_by_date() -> Response:
"""TODO
---
responses:
'200':
description: TODO
"""
return redirect("https://explorer.ooni.org/search", 301) | a927c237e03e82820c86890518500d16f5fcf999 | 3,615,162 |
def extractAliasFromContainerName(containerName):
""" Take a compose created container name and extract the alias to which it
will be refered. For example bddtests_vp1_0 will return vp0 """
return containerName.split("_")[1] | a5ab9487ae31ee1a4b2ed9b67062817488107983 | 3,615,163 |
from datetime import datetime
def sell():
"""Sell shares of stock"""
# Retrieve current symbols and shares of stocks owned by the user
stocks = db.execute(
"SELECT stock AS symbol, SUM(CASE WHEN transaction_type='buy' THEN shares WHEN transaction_type='sell' THEN -shares ELSE NULL END) AS shares ... | 0bdab7d0b90f852324f28f0cb38c9932c1c6e888 | 3,615,164 |
def disable_fetcher():
"""arg: fetcher_id"""
disable_user_fetcher(
get_current_user_id(), request.values['fetcher_id'])
return {'success': 1} | b2026254096e5c837a8137de0d0f98a4ca55363b | 3,615,165 |
def jupyter_show_as_svg(g):
"""
Shows object as SVG (by default it is rendered as image).
@param g: digraph object
"""
return HTML(g.pipe(format='svg').decode("utf-8")) | 1f12a270f87976c1f57e24eb82fbe77bd90937e5 | 3,615,166 |
from copy import deepcopy
def parse_data(train, test):
"""Load data from train and test files respectively."""
# Scale X and Y features in train to 0 mean, unit variance
xy_scaler = StandardScaler()
xy_scaler.fit(train[["X", "Y"]])
train[["X", "Y"]] = xy_scaler.transform(train[["X", "Y"]])
tr... | 4ce2b26d04cce01e12d98a97aa1b6f1f2d8a6021 | 3,615,167 |
from typing import Sequence
def primes(n: int) -> Sequence[int]:
"""Returns the first n prime numbers in sorted order."""
_compute_primes(n)
return _prime_sequence[:n] | 54f8a552636ca74999f855a3ec2c403bb81ca794 | 3,615,168 |
import time
def _create_docstring_df():
"""creates the df used in the docstring of single_val_cols_to_dict"""
return pd.DataFrame(index=pd.date_range(time, periods=3, freq='1H'),
columns=['col1', 'col2', 'col3'], data=[[1.0, 2.0, 3.0], [1.0, 4.0, 3.0], [1.0, 6.0, 3.0]]) | 5e78f1ad8e2e50bc64ab068011490cecafa030cb | 3,615,169 |
def test_if_df(data: pd.DataFrame) -> bool:
"""Test if passed data instance is from class DataFrame
Arguments:
data {pd.DataFrame} -- This is data input
Returns:
bool -- Returns bool if passed data is data
"""
return isinstance(df, pd.DataFrame) | 1786e97f430a079635ea9e48419e96a8fc240713 | 3,615,170 |
def load_data(projection: dict) -> pd.DataFrame:
"""
Load the data from the Mongo collection and transform
into a pandas dataframe
:projection: A dictionary with the fields to load from database
:return: A pandas dataframe with the data
"""
articles = db.read_articles(
projection=pro... | 481c44364dbee99e22cd6d95dc9778a52f15c997 | 3,615,171 |
def block_to_actions(block, delete_existing=False):
"""Converts a block vector representation into actions that create the block.
The idea here is that a block with the properties of `block` will be created
when the returned actions are executed in the unity environment.
Note that if delete_existing=False, an... | ab42f2ecfe9944be30ea13d678e5562765487c9f | 3,615,172 |
def get_stack(token, stack_id):
"""
Asks OpenStack Heat for stack details
"""
url = token.get_service_url(OPENSTACK_SERVICE.HEAT)
if url is None:
raise ValueError("OpenStack Heat URL is invalid")
api_cmd = url + "/stacks/%s" % stack_id
response = rest_api_request(token, "GET", api_... | b2947caa33d6ab3232468d78818b187616c687ab | 3,615,173 |
def is_log_i18n_msg_with_mod(n):
"""LOG.xxx("Hello %s" % xyz) should be LOG.xxx("Hello %s", xyz)"""
if not isinstance(n.parent.parent, compiler.ast.Mod):
return False
n = n.parent.parent
if isinstance(n.parent, compiler.ast.CallFunc):
if isinstance(n.parent.node, compiler.ast.Getattr):
... | 51dcc456444b7332b4cc5444551b0f34fe1149f2 | 3,615,174 |
import glob
import os
def toc_dir(dir_):
"""A directory was passed to doctoc. Return bool whether any file was
modified and the number of warnings."""
files = glob.glob(os.path.join(dir_, "*.md"))
modified_any = False
warnings = 0
for file_ in files:
if "API-categories.md" in file_ or ... | c38bb1363c3b86d6bee83cb1c3dff4d4908f3aeb | 3,615,175 |
from datetime import datetime
import pytz
def _unpack_series(json_data, product):
"""Returns a list of time series from get-netcdf-data JSON."""
key = 'long_range_mem1' if product == 'long_range' else product
time_step_hrs = PRODUCTSv1_1[key]['step_hrs']
offset_hrs = PRODUCTSv1_1[key]['offset_hrs']
... | 102c234c0e590a6e50fff20b092e7f3047ba0be8 | 3,615,176 |
def HexToByte( hexStr ):
"""
Convert a string hex byte values into a byte string. The Hex Byte values may
or may not be space separated.
"""
# The list comprehension implementation is fractionally slower in this case
#
# hexStr = ''.join( hexStr.split(" ") )
# return ''.join( [... | eab4fd7ecaae10add8411cf51c03d1bf5b902700 | 3,615,177 |
def gabor(sigma, theta, Lambda, psi, gamma):
"""Gabor feature extraction."""
sigma_x = float(sigma) / gamma
sigma_y = float(sigma) / gamma
# Bounding box
nstds = 3 # Number of standard deviation sigma
xmax = max(abs(nstds * sigma_x * np.cos(theta)), abs(nstds * sigma_y * np.sin(theta)))
xm... | d5fafd33ba13a9e863b150634da6315dddda0599 | 3,615,178 |
import os
import textwrap
def build_haplotype_sequences(records, args):
"""Build consensus sequence for each seed."""
logger.info("Building building haplotype sequences...")
ref_seqs = load_fasta(REF_FILE)
base_dir = os.path.dirname(args.in_tsv)
results = {} # actually consensus seeds
for r... | 0e6d3a07b4e3b7ab2a3764f19ac53bd184f9f77f | 3,615,179 |
def brier_score_loss_for_true_class(y_true, y_proba):
"""
Calculates Brier score for from a set of class probabilities.
:param y_true: True class labels.
:type y_true: list
:param y_proba: Predicted class probabilities.
:type y_proba: array-like
:return: Brier score
"""
if y_proba is... | bc56e176bf61a5da5c7343f338d1caaf03a9229a | 3,615,180 |
def _truncate_term_length(term, taken=0):
"""truncate the length of a term string length to the maximum allowed
for xapian terms
:param term: the value of the term, that should be truncated
:type term: str
:param taken: since a term consists of the name of the term and its
actual value, thi... | 4011f1614ff79a84449fe3ac8fda48b354394e32 | 3,615,181 |
def families_sextupoles():
"""."""
return [] | 6863e887f377bc7afc8430878bf74a7c9e1d1085 | 3,615,182 |
import yaml
import warnings
def parse_config_file(conf_file):
"""
Parse a divvy configuration file.
:param str conf_file: path to divvy configuration file
:return Mapping: compute settings as declared in config file
"""
with open(conf_file, 'r') as f:
_LOGGER.info("Loading divvy confi... | 0afcb41d32f8dd697b859b32a3ac50d83023b587 | 3,615,183 |
def get_schema_from_list(schema_list):
"""
Create a bigquery schema from a list
:param schema_list: Columns definitions separate by "," character,
A column definition is NAME: TYPE
:return: bigquery schema
"""
schema = []
columns_def = schema_list.split(',')
for column_def in co... | 2b1311b1008543182a296f870fa4a3e2a20bbdc1 | 3,615,184 |
def calcError(svm, alpha_k):
"""
计算误差: E = g(X) - y
"""
g_k = float(np.multiply(svm.alphas, svm.label).T * svm.kernel_mat[:, alpha_k] + svm.b)
error_k = g_k - float(svm.label[alpha_k])
return error_k | 811d377e65fff58405bd3f52dd17bf9ef8df791e | 3,615,185 |
def ma30_cross_func(data):
"""
MA均线金叉指标
"""
MA5 = talib.MA(data.close, 5)
MA10 = talib.MA(data.close, 10)
MA30 = talib.MA(data.close, 30)
MA90 = talib.MA(data.close, 90)
MA120 = talib.MA(data.close, 120)
MA30_CROSS = pd.DataFrame(np.c_[MA5,
MA10,
... | 7e933d1d54a53ab69e59f80992ef083c3ecd1aae | 3,615,186 |
def obtain_safety_stock_vector(theta: np.ndarray,
load_ph: np.ndarray,
sigma_2_ph: np.ndarray,
state: np.ndarray,
debug_info: bool = False):
"""
Returns vector whose components are the saf... | 17eb316e56dc99a5ba08c539d547c62341fa73ea | 3,615,187 |
def get_method_from_html(html_file):
"""
Parse simulation method name from html_file
"""
input_file = open(html_file, 'r')
for line in input_file:
if line.find("Simulation Method") > 0:
line = next(input_file)
break
token = line[4:].split("<")[0]
input_file.cl... | da7e459852b5bfdf5de3d1375d23120ed5be2feb | 3,615,188 |
import copy
def make_test_problems(settings):
"""Creates test problems from settings.
Args:
settings (list[dict]): raw settings of the problems
Returns:
list[ExtensionTestProblem]
"""
problem_dicts = []
for setting in settings:
setting = add_missing_defaults(setting)... | 5eaa360e472b7ba6884dde482c449e67224963c7 | 3,615,189 |
def plot_hits(
ax,
hits_dict,
reference_length=None,
plot_range=None,
hide_missing_pairs=True,
bar_height=0.8,
bar_color="blue",
sort_key=lambda i: i,
):
""" Groups hits by query, and places above reference
hits_dict: map from query_id to list of hit objects
bar_color... | 9fd2cea23ceccb1b7703db412826ee7aa47739bc | 3,615,190 |
import re
def UserUpdate(fCallback):
"""Get User and log update requests passing to fCallback
The log will be handed to fCallback when 'ok' is received"""
def log_update_requests_and_call(self, *args, **kwargs):
cmd = args[0]
arg = args[1]
# Empty line
if cmd is None:
... | 2cf80f8ebd6a98f47bb3a220854ea9791c5d53be | 3,615,191 |
from typing import List
from typing import Tuple
def get_sub_graph_external_input_output(
predict_net: caffe2_pb2.NetDef, sub_graph_op_indices: List[int]
) -> Tuple[List[Tuple[str, int]], List[Tuple[str, int]]]:
"""
Return the list of external input/output of sub-graph,
each element is tuple of the na... | b8b6a22980ab2afb5f5ff83dd8c757740fe6bf25 | 3,615,192 |
def _butterworth(ts, low_frequency, high_factor, order, sampling_frequency):
"""Butterworth filter
Parameters
----------
ts: np.array
T numpy array, where T is the number of time samples
low_frequency: int
Low pass frequency (Hz)
high_factor: float
High pass factor (pro... | 4f68657c2686c0683a421bc7b8b4e3cd906362d4 | 3,615,193 |
import tempfile
def mk_conf_file(conf):
"""
Creates config file in temporary file.
"""
tmp_fp = tempfile.mktemp()
with open(tmp_fp, "w") as f:
print(mk_conf_str(conf), file=f)
return tmp_fp | 57fbcf4ca427455b103fe9efeee79246a35c7141 | 3,615,194 |
def get_string(request, key):
"""Returns the first value in the request args for a given key."""
if not request.args:
return None
if type(key) is not bytes:
key = key.encode()
if key not in request.args:
return None
val = request.args[key][0]
if val is not None and typ... | ae43bb3e11cf21deb8f726ed6a2321c51099e4f3 | 3,615,195 |
def char_word_tokenize(text):
"""分词器、中文单独成词,英文单词、连续数字作为一个词"""
# 大写转小写,繁体转简体
text = zhconv.convert(text.lower(), 'zh-cn')
# 全角转半角
text = full_to_half(text)
tokenized_chs = []
text_len = len(text)
i = 0
while i < text_len:
ch = text[i]
# 中文字符
if ch in all:
... | 9c788bc185f80dd9304534e30a756918389a2375 | 3,615,196 |
import json
import traceback
def anomalyService(dimValObj, dfDict, anomalyDefProps, detectionRuleType, detectionParams):
"""
Method to conduct the anomaly detection process
"""
df = pd.DataFrame(dfDict)
anomalyId = dimValObj["anomalyId"]
dimVal = dimValObj["dimVal"]
contriPercent = dimValO... | bc97fd19c804121cd6694fe907153bb1ea975121 | 3,615,197 |
def binarySearch(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if len(nums) == 0:
return -1
left, right = 0, len(nums) - 1
while left + 1 < right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif n... | 71d2077f69002ba6e554576f569f8a85a596a0ec | 3,615,198 |
def tokenize(text):
"""
Function that tokenizes an input text string
Parameters:
text (str): Input text
Returns:
list (str): List of tokens extracted from the input text
"""
tokens = word_tokenize(text)
lemmatizer = WordNetLemmatizer()
clean_tokens = []
for t... | 36ab3cc6c679f5a5a45e3559fbcd405b5c04c387 | 3,615,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.