uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1cd741a7f8e2b72d2983b57d | train | function | @pytest.mark.parametrize(
'name',
set(ALL_METRICS) - METRIC_UNDEFINED_BINARY_MULTICLASS)
def test_sample_order_invariance(name):
random_state = check_random_state(0)
y_true = random_state.randint(0, 2, size=(20, ))
y_pred = random_state.randint(0, 2, size=(20, ))
y_true_shuffle, y_pred_s... | @pytest.mark.parametrize(
'name',
set(ALL_METRICS) - METRIC_UNDEFINED_BINARY_MULTICLASS)
def test_sample_order_invariance(name):
| random_state = check_random_state(0)
y_true = random_state.randint(0, 2, size=(20, ))
y_pred = random_state.randint(0, 2, size=(20, ))
y_true_shuffle, y_pred_shuffle = shuffle(y_true, y_pred, random_state=0)
with ignore_warnings():
metric = ALL_METRICS[name]
assert_allclose(metric(y... | _equal(metric(y_true, y_pred), metric(y_pred, y_true))
cm.msg = ("%s seems to be symmetric" % name)
@pytest.mark.parametrize(
'name',
set(ALL_METRICS) - METRIC_UNDEFINED_BINARY_MULTICLASS)
def test_sample_order_invariance(name):
| 64 | 64 | 152 | 35 | 29 | lqkweb/learnMLflow | scikit-learn-master/sklearn/metrics/tests/test_common.py | Python | test_sample_order_invariance | test_sample_order_invariance | 481 | 494 | 481 | 484 | f23c2789478c29ae38e39007df458ff9813e1d7d | bigcode/the-stack | train |
4d303f5e6ad13d94d058570d | train | function | @ignore_warnings
def check_single_sample(name):
# Non-regression test: scores should work with a single sample.
# This is important for leave-one-out cross validation.
# Score functions tested are those that formerly called np.squeeze,
# which turns an array of size 1 into a 0-d array (!).
metric = ... | @ignore_warnings
def check_single_sample(name):
# Non-regression test: scores should work with a single sample.
# This is important for leave-one-out cross validation.
# Score functions tested are those that formerly called np.squeeze,
# which turns an array of size 1 into a 0-d array (!).
| metric = ALL_METRICS[name]
# assert that no exception is thrown
for i, j in product([0, 1], repeat=2):
metric([i], [j])
| @ignore_warnings
def check_single_sample(name):
# Non-regression test: scores should work with a single sample.
# This is important for leave-one-out cross validation.
# Score functions tested are those that formerly called np.squeeze,
# which turns an array of size 1 into a 0-d array (!).
| 69 | 64 | 112 | 69 | 0 | lqkweb/learnMLflow | scikit-learn-master/sklearn/metrics/tests/test_common.py | Python | check_single_sample | check_single_sample | 720 | 730 | 720 | 725 | 5667ac59cd3d50f391971379de4753a811df117d | bigcode/the-stack | train |
b65d6a3e04a6541e559a211c | train | function | @pytest.mark.parametrize('name', METRICS_WITH_AVERAGING)
def test_averaging_multiclass(name):
n_samples, n_classes = 50, 3
random_state = check_random_state(0)
y_true = random_state.randint(0, n_classes, size=(n_samples, ))
y_pred = random_state.randint(0, n_classes, size=(n_samples, ))
y_score = ra... | @pytest.mark.parametrize('name', METRICS_WITH_AVERAGING)
def test_averaging_multiclass(name):
| n_samples, n_classes = 50, 3
random_state = check_random_state(0)
y_true = random_state.randint(0, n_classes, size=(n_samples, ))
y_pred = random_state.randint(0, n_classes, size=(n_samples, ))
y_score = random_state.uniform(size=(n_samples, n_classes))
lb = LabelBinarizer().fit(y_true)
y_t... | , y_true, y_score, y_true_binarize,
y_score, is_multilabel)
else:
raise ValueError("Metric is not recorded as having an average option")
@pytest.mark.parametrize('name', METRICS_WITH_AVERAGING)
def test_averaging_multiclass(name):
| 64 | 64 | 165 | 24 | 40 | lqkweb/learnMLflow | scikit-learn-master/sklearn/metrics/tests/test_common.py | Python | test_averaging_multiclass | test_averaging_multiclass | 960 | 973 | 960 | 961 | 9cc8b6e358c47cdc6d1c6ae5e1208191923fabf3 | bigcode/the-stack | train |
6b185703638edf50546350eb | train | function | def readCSV(filename):
rows=[]
with open(filename, 'rb') as csvf:
reader = csv.reader(csvf, skipinitialspace=True)
for row in reader:
rows.append(row)
return rows
| def readCSV(filename):
| rows=[]
with open(filename, 'rb') as csvf:
reader = csv.reader(csvf, skipinitialspace=True)
for row in reader:
rows.append(row)
return rows
| #! /usr/bin/env python
from pycassa.pool import ConnectionPool
import csv
#class Util:
def getConnection():
return ConnectionPool('mastering_cassandra', ['localhost:9160'])
def readCSV(filename):
| 48 | 64 | 48 | 5 | 43 | paullewallencom/apache-cassandra-978-1-7821-6268-1 | _/2681_03_code/util.py | Python | readCSV | readCSV | 11 | 17 | 11 | 11 | 9c966e4cd7a51bdc16c06a0328596aeef7d64e31 | bigcode/the-stack | train |
e6069c56a9433d08b284d441 | train | function | def getConnection():
return ConnectionPool('mastering_cassandra', ['localhost:9160'])
| def getConnection():
| return ConnectionPool('mastering_cassandra', ['localhost:9160'])
| #! /usr/bin/env python
from pycassa.pool import ConnectionPool
import csv
#class Util:
def getConnection():
| 27 | 64 | 20 | 4 | 23 | paullewallencom/apache-cassandra-978-1-7821-6268-1 | _/2681_03_code/util.py | Python | getConnection | getConnection | 8 | 9 | 8 | 8 | 65f5d7e941aa2246637350003ffb75bf673bd819 | bigcode/the-stack | train |
88c00d2c1dca8d4226a01c83 | train | class | class VideoSearchView(views.View):
def get(self, request, *args, **kwargs):
form = VidOpenForm()
return render(request, 'vidsearch/index.html' , {"form": form})
def post(self, request, *args, **kwargs):
print(request.POST)
video = detect_backend(request.POST['url'])
cc_url = "https://www.youtube.com/api/ti... | class VideoSearchView(views.View):
| def get(self, request, *args, **kwargs):
form = VidOpenForm()
return render(request, 'vidsearch/index.html' , {"form": form})
def post(self, request, *args, **kwargs):
print(request.POST)
video = detect_backend(request.POST['url'])
cc_url = "https://www.youtube.com/api/timedtext?lang=en&v=%s" %(video.get_c... | login
from mainApp.models import *
# Create your views here.
class HomePageView(views.View):
def get(self, request, *args, **kwargs):
return render(request, 'home/index.html' , {})
home_page = HomePageView.as_view()
class VideoSearchView(views.View):
| 64 | 64 | 138 | 8 | 56 | iknoorjobs/video-search | mainApp/views.py | Python | VideoSearchView | VideoSearchView | 17 | 27 | 17 | 17 | 56e2b8f27a52e93e720ae679b8b75b81e58fd7b1 | bigcode/the-stack | train |
4083306e71a66fa1ec80de74 | train | class | class HomePageView(views.View):
def get(self, request, *args, **kwargs):
return render(request, 'home/index.html' , {})
| class HomePageView(views.View):
| def get(self, request, *args, **kwargs):
return render(request, 'home/index.html' , {})
| render, HttpResponseRedirect
from django.http import Http404
from django import views
from mainApp.forms import VidOpenForm
from embed_video.backends import detect_backend
from django.contrib.auth import authenticate, login
from mainApp.models import *
# Create your views here.
class HomePageView(views.View):
| 64 | 64 | 32 | 8 | 56 | iknoorjobs/video-search | mainApp/views.py | Python | HomePageView | HomePageView | 11 | 13 | 11 | 11 | 525a5645703fc697d28c8bafea1cdcaac971e682 | bigcode/the-stack | train |
9187b472b5a9edf54d2748ee | train | class | class LoginView(views.View):
def get(self, request, *args, **kwargs):
return render(request, "home/login.html", {})
def post(self, request, *args, **kwargs):
user = authenticate(username = request.POST['username'], password = request.POST['pass'])
if user is not None:
login(request, user)
return HttpResp... | class LoginView(views.View):
| def get(self, request, *args, **kwargs):
return render(request, "home/login.html", {})
def post(self, request, *args, **kwargs):
user = authenticate(username = request.POST['username'], password = request.POST['pass'])
if user is not None:
login(request, user)
return HttpResponseRedirect("/site/groups/")... | s" %(video.get_code())
vid_url = video.get_code()
return render(request, 'vidsearch/view.html', {"my_video": video, "cc_url": cc_url, 'vid_url': vid_url})
vid_search_page = VideoSearchView.as_view()
class LoginView(views.View):
| 64 | 64 | 98 | 7 | 57 | iknoorjobs/video-search | mainApp/views.py | Python | LoginView | LoginView | 32 | 41 | 32 | 32 | 6a5edf2685f371b9696fcff6afbff86a21a534c7 | bigcode/the-stack | train |
8f891dcb6961dfba1f5cdc50 | train | class | class GroupsView(views.View):
def get(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return HttpResponseRedirect("/site/login/")
return render(request, "home/studyGroup.html", {"objects": StudyGroup.objects.all()})
def post(self, request, *args, **kwargs):
try:
time = request.POST... | class GroupsView(views.View):
| def get(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return HttpResponseRedirect("/site/login/")
return render(request, "home/studyGroup.html", {"objects": StudyGroup.objects.all()})
def post(self, request, *args, **kwargs):
try:
time = request.POST['time']
venue = request.PO... | request.POST['username'], password = request.POST['pass'])
if user is not None:
login(request, user)
return HttpResponseRedirect("/site/groups/")
return render(request, "home/login.html", {"failed": True})
login_page = LoginView.as_view()
class GroupsView(views.View):
| 64 | 64 | 147 | 7 | 57 | iknoorjobs/video-search | mainApp/views.py | Python | GroupsView | GroupsView | 45 | 60 | 45 | 45 | 2bb18263ffc3a81b8de51e60307982bb361c53c5 | bigcode/the-stack | train |
a484d6dc7d43e6a2eeb9d70f | train | function | def test_free_fall_effective_measurement_height():
"""Test finite speed of light est correction.
"""
# g0 = 9.81570660 * u.m / u.s**2
initial_velocity = 0.4412051 * u.m / u.s
drop_duration = 0.2366589 * u.s
h_eff_ref = 0.144878 * u.m
h_eff = free_fall_effective_measurement_height(initial... | def test_free_fall_effective_measurement_height():
| """Test finite speed of light est correction.
"""
# g0 = 9.81570660 * u.m / u.s**2
initial_velocity = 0.4412051 * u.m / u.s
drop_duration = 0.2366589 * u.s
h_eff_ref = 0.144878 * u.m
h_eff = free_fall_effective_measurement_height(initial_velocity,
... |
import numpy as np
import gmeterpy.units as u
from gmeterpy.meters.freefall.effective_height import free_fall_effective_measurement_height
from gmeterpy.meters.freefall.effective_height import tod_to_t0_distance
def test_free_fall_effective_measurement_height():
| 64 | 64 | 138 | 11 | 52 | ioshchepkov/gmeterpy | gmeterpy/meters/freefall/tests/test_effective_height.py | Python | test_free_fall_effective_measurement_height | test_free_fall_effective_measurement_height | 15 | 32 | 15 | 15 | 25f1c0feda1a4cee86509d9c79fd932fc512386b | bigcode/the-stack | train |
b2ec2fa15929eaa0f435eb72 | train | function | def test_tod_to_t0_distance():
"""Test TOD to t=0 distance calculation.
"""
g0 = 9.81570660 * u.m / u.s**2
initial_velocity = 0.4412051 * u.m / u.s
h0_ref = 0.009916 * u.m
h0 = tod_to_t0_distance(initial_velocity, g0)
# test units
assert isinstance(h0, u.Quantity)
np.testing.as... | def test_tod_to_t0_distance():
| """Test TOD to t=0 distance calculation.
"""
g0 = 9.81570660 * u.m / u.s**2
initial_velocity = 0.4412051 * u.m / u.s
h0_ref = 0.009916 * u.m
h0 = tod_to_t0_distance(initial_velocity, g0)
# test units
assert isinstance(h0, u.Quantity)
np.testing.assert_array_almost_equal(h0.valu... | 878 * u.m
h_eff = free_fall_effective_measurement_height(initial_velocity,
drop_duration)
# test units
assert isinstance(h_eff, u.Quantity)
np.testing.assert_array_almost_equal(h_eff.value, h_eff_ref.value)
def test_tod_to_t0_distance():
| 64 | 64 | 118 | 9 | 55 | ioshchepkov/gmeterpy | gmeterpy/meters/freefall/tests/test_effective_height.py | Python | test_tod_to_t0_distance | test_tod_to_t0_distance | 35 | 50 | 35 | 35 | 917856cfc55e1597b041b82338fd79b0be08f345 | bigcode/the-stack | train |
3e5ec4fecaad7ecd24aedcb8 | train | function | def read_default_video_data(f_pattern):
mov_file = f_pattern
try:
mov_reader = imageio.get_reader(mov_file)
mov_iter = mov_reader.iter_data()
except:
print('Failed loading video data: ' + f_pattern)
return None
# Read in the data to return
mov_data = np.array([frame for frame in mov_iter])
mov_data = mov_... | def read_default_video_data(f_pattern):
| mov_file = f_pattern
try:
mov_reader = imageio.get_reader(mov_file)
mov_iter = mov_reader.iter_data()
except:
print('Failed loading video data: ' + f_pattern)
return None
# Read in the data to return
mov_data = np.array([frame for frame in mov_iter])
mov_data = mov_data[:,:,:,0]
# Crop the data to the sh... | import h5py
import sys, getopt, os, re, argparse
import imageio
import numpy as np
def read_default_video_data(f_pattern):
| 33 | 64 | 172 | 8 | 24 | KumarLabJax/MouseGrooming | DatasetCreators/AddVideoToHDF5.py | Python | read_default_video_data | read_default_video_data | 6 | 23 | 6 | 6 | 8bdf60a193f505b7f80fdc074d2ff368e4839ccf | bigcode/the-stack | train |
3f8059688cd91a1cf4bdccbd | train | function | def main(argv):
parser = argparse.ArgumentParser(description='Adds a video to a hdf5 grooming dataset file')
parser.add_argument('--mov_name', help='Name of movie to add', required=True)
parser.add_argument('--video_key', help='Key to assign to the video', default=None)
parser.add_argument('--input_hdf5', help='HDF... | def main(argv):
| parser = argparse.ArgumentParser(description='Adds a video to a hdf5 grooming dataset file')
parser.add_argument('--mov_name', help='Name of movie to add', required=True)
parser.add_argument('--video_key', help='Key to assign to the video', default=None)
parser.add_argument('--input_hdf5', help='HDF5 file to append... | _iter])
mov_data = mov_data[:,:,:,0]
# Crop the data to the shortest available...
data_dim = np.min([np.shape(mov_data)[0]])
mov_data = mov_data[0:data_dim,:,:]
lab_data = np.zeros([data_dim]).astype(np.uint8)
mask_data = np.zeros([data_dim]).astype(bool)
nlabs = 0
return mov_data, mask_data, lab_data, data_dim... | 100 | 100 | 334 | 4 | 95 | KumarLabJax/MouseGrooming | DatasetCreators/AddVideoToHDF5.py | Python | main | main | 25 | 57 | 25 | 25 | 251701114f323cade29b7b1c38f8208ee7c94ccb | bigcode/the-stack | train |
2ed39bb779e184d14ad74fc5 | train | function | def test_equiv():
x, y, z = map(aiger.atom, ['x', 'y', 'z'])
assert aiger_sat.are_equiv(x & y, x & y & (z | ~z))
| def test_equiv():
| x, y, z = map(aiger.atom, ['x', 'y', 'z'])
assert aiger_sat.are_equiv(x & y, x & y & (z | ~z))
| ': True}
def test_is_sat():
x, y, z = map(aiger.atom, ['x', 'y', 'z'])
assert aiger_sat.is_sat(x & y & z)
def test_is_valid():
assert aiger_sat.is_valid(aiger.atom(True))
def test_equiv():
| 64 | 64 | 48 | 5 | 59 | MarkusRabe/py-aiger-sat | aiger_sat/test_sat.py | Python | test_equiv | test_equiv | 53 | 55 | 53 | 53 | 24650d764b62fdedcea845460ee97d3356d21077 | bigcode/the-stack | train |
2d031a4a0becf2e9e192a430 | train | function | def test_solve():
x, y, z = map(aiger.atom, ['x', 'y', 'z'])
model = aiger_sat.solve(x & y & z)
assert model == {'x': True, 'y': True, 'z': True}
| def test_solve():
| x, y, z = map(aiger.atom, ['x', 'y', 'z'])
model = aiger_sat.solve(x & y & z)
assert model == {'x': True, 'y': True, 'z': True}
| assert expr(model)
assert not solver.is_sat(assumptions={
'x': False,
'z': True,
})
assert not solver.unsolved
core = solver.get_unsat_core()
assert core == {'x': False, 'z': True}
def test_solve():
| 64 | 64 | 58 | 5 | 59 | MarkusRabe/py-aiger-sat | aiger_sat/test_sat.py | Python | test_solve | test_solve | 38 | 41 | 38 | 38 | 9038620ab4675933f6a21e3f814714175d5a2260 | bigcode/the-stack | train |
5564035039eb13106e6108a5 | train | function | def test_is_sat():
x, y, z = map(aiger.atom, ['x', 'y', 'z'])
assert aiger_sat.is_sat(x & y & z)
| def test_is_sat():
| x, y, z = map(aiger.atom, ['x', 'y', 'z'])
assert aiger_sat.is_sat(x & y & z)
| }
def test_solve():
x, y, z = map(aiger.atom, ['x', 'y', 'z'])
model = aiger_sat.solve(x & y & z)
assert model == {'x': True, 'y': True, 'z': True}
def test_is_sat():
| 64 | 64 | 39 | 5 | 59 | MarkusRabe/py-aiger-sat | aiger_sat/test_sat.py | Python | test_is_sat | test_is_sat | 44 | 46 | 44 | 44 | 83bb4fbe1b7c5bdd4578c6057dddb783e10d6ad3 | bigcode/the-stack | train |
941bc4c912622e39cde23f74 | train | function | def test_is_valid():
assert aiger_sat.is_valid(aiger.atom(True))
| def test_is_valid():
| assert aiger_sat.is_valid(aiger.atom(True))
| )
assert model == {'x': True, 'y': True, 'z': True}
def test_is_sat():
x, y, z = map(aiger.atom, ['x', 'y', 'z'])
assert aiger_sat.is_sat(x & y & z)
def test_is_valid():
| 64 | 64 | 17 | 5 | 59 | MarkusRabe/py-aiger-sat | aiger_sat/test_sat.py | Python | test_is_valid | test_is_valid | 49 | 50 | 49 | 49 | 2a471c2c1d7f1e413b2eb2ef22587e319d19a163 | bigcode/the-stack | train |
488fd173e533061ac2b2017d | train | function | def test_smoke():
x, y, z = map(aiger.atom, ['x', 'y', 'z'])
solver = SolverWrapper()
expr = (x & y) | ~z
solver.add_expr(expr)
assert solver.inputs == {'x', 'y', 'z'}
assert len(solver.sym_table) == 3
assert all(v in solver.sym_table for v in 'xyz')
assert solver.unsolved
assert... | def test_smoke():
| x, y, z = map(aiger.atom, ['x', 'y', 'z'])
solver = SolverWrapper()
expr = (x & y) | ~z
solver.add_expr(expr)
assert solver.inputs == {'x', 'y', 'z'}
assert len(solver.sym_table) == 3
assert all(v in solver.sym_table for v in 'xyz')
assert solver.unsolved
assert solver.is_sat()
... | import aiger
import aiger_sat
from aiger_sat import SolverWrapper
def test_smoke():
| 22 | 64 | 192 | 5 | 16 | MarkusRabe/py-aiger-sat | aiger_sat/test_sat.py | Python | test_smoke | test_smoke | 7 | 35 | 7 | 7 | dfb7af465fac24685571243abdefaa0b592fb94d | bigcode/the-stack | train |
114b5aceb031d6c954408d94 | train | function | def php_namespace_role(typ,
rawtext,
text,
lineno,
inliner,
options={},
content=[]):
text = utils.unescape(text)
env = inliner.document.settings.env
base_url = env.app.co... | def php_namespace_role(typ,
rawtext,
text,
lineno,
inliner,
options={},
content=[]):
| text = utils.unescape(text)
env = inliner.document.settings.env
base_url = env.app.config.api_url
has_explicit_title, title, namespace = split_explicit_title(text)
try:
full_url = base_url % namespace.replace('\\', '/')
except (TypeError, ValueError):
env.warn(
env.d... | c) 2010-2012 Fabien Potencier
:license: MIT, see LICENSE for more details.
"""
from docutils import nodes, utils
from sphinx.util.nodes import split_explicit_title
def php_namespace_role(typ,
rawtext,
text,
lineno,
inliner... | 76 | 76 | 256 | 30 | 45 | greg0ire/sphinx-php | sensio/sphinx/phpcode.py | Python | php_namespace_role | php_namespace_role | 12 | 46 | 12 | 18 | 440805b502af8c32b6fe1a4c2346b13b869cde92 | bigcode/the-stack | train |
0982c95f94bd43f2b2e59e01 | train | function | def php_method_role(typ,
rawtext,
text,
lineno,
inliner,
options={},
content=[]):
text = utils.unescape(text)
env = inliner.document.settings.env
base_url = env.app.config.api_url
has_... | def php_method_role(typ,
rawtext,
text,
lineno,
inliner,
options={},
content=[]):
| text = utils.unescape(text)
env = inliner.document.settings.env
base_url = env.app.config.api_url
has_explicit_title, title, class_and_method = split_explicit_title(text)
ns = class_and_method.rfind('::')
full_class = class_and_method[:ns]
method = class_and_method[ns + 2:]
try:
... | list = [
nodes.reference(title,
title,
internal=False,
refuri=full_url,
reftitle=full_class)
]
pnode = nodes.literal('', '', *list)
return [pnode], []
def php_method_role(typ,
rawtext... | 80 | 81 | 272 | 30 | 50 | greg0ire/sphinx-php | sensio/sphinx/phpcode.py | Python | php_method_role | php_method_role | 81 | 115 | 81 | 87 | a6272de2b84054039e19dabf0266dc3c3f534fae | bigcode/the-stack | train |
bd23aa775ae4d362357855e3 | train | function | def php_phpclass_role(typ,
rawtext,
text,
lineno,
inliner,
options={},
content=[]):
text = utils.unescape(text)
has_explicit_title, title, full_class = split_explicit_title(text)
... | def php_phpclass_role(typ,
rawtext,
text,
lineno,
inliner,
options={},
content=[]):
| text = utils.unescape(text)
has_explicit_title, title, full_class = split_explicit_title(text)
full_url = 'https://www.php.net/manual/en/class.%s.php' % full_class.lower(
)
if not has_explicit_title:
title = full_class
list = [
nodes.reference(title,
tit... | full_class + '::' + method + '()')
]
pnode = nodes.literal('', '', *list)
return [pnode], []
def php_phpclass_role(typ,
rawtext,
text,
lineno,
inliner,
options={},
content=[]):... | 63 | 64 | 145 | 31 | 32 | greg0ire/sphinx-php | sensio/sphinx/phpcode.py | Python | php_phpclass_role | php_phpclass_role | 118 | 141 | 118 | 124 | 930c2c18624b93d4db9fc2957c5c63ebaf2d6b6d | bigcode/the-stack | train |
711a4d5f72a208b5eb05ca5b | train | function | def php_phpmethod_role(typ,
rawtext,
text,
lineno,
inliner,
options={},
content=[]):
text = utils.unescape(text)
has_explicit_title, title, class_and_method = split_explicit_... | def php_phpmethod_role(typ,
rawtext,
text,
lineno,
inliner,
options={},
content=[]):
| text = utils.unescape(text)
has_explicit_title, title, class_and_method = split_explicit_title(text)
ns = class_and_method.rfind('::')
full_class = class_and_method[:ns]
method = class_and_method[ns + 2:]
full_url = 'https://www.php.net/manual/en/%s.%s.php' % (
full_class.lower(), meth... | =full_url,
reftitle=full_class)
]
pnode = nodes.literal('', '', *list)
return [pnode], []
def php_phpmethod_role(typ,
rawtext,
text,
lineno,
inliner,
options={},
... | 63 | 64 | 192 | 31 | 32 | greg0ire/sphinx-php | sensio/sphinx/phpcode.py | Python | php_phpmethod_role | php_phpmethod_role | 144 | 171 | 144 | 150 | ab9ce2fc746b6e69eab3da838c175d25b02b7889 | bigcode/the-stack | train |
ca3cd141c7fb0a6ec91e7758 | train | function | def setup(app):
app.add_config_value('api_url', '', 'env')
app.add_role('namespace', php_namespace_role)
app.add_role('class', php_class_role)
app.add_role('method', php_method_role)
app.add_role('phpclass', php_phpclass_role)
app.add_role('phpmethod', php_phpmethod_role)
app.add_role('phpfu... | def setup(app):
| app.add_config_value('api_url', '', 'env')
app.add_role('namespace', php_namespace_role)
app.add_role('class', php_class_role)
app.add_role('method', php_method_role)
app.add_role('phpclass', php_phpclass_role)
app.add_role('phpmethod', php_phpmethod_role)
app.add_role('phpfunction', php_php... | _title:
title = full_function
list = [
nodes.reference(title,
title,
internal=False,
refuri=full_url,
reftitle=full_function)
]
pnode = nodes.literal('', '', *list)
return [pnode], []
def setu... | 63 | 64 | 98 | 4 | 59 | greg0ire/sphinx-php | sensio/sphinx/phpcode.py | Python | setup | setup | 200 | 209 | 200 | 200 | 960857946f417d885bf61018189fc18f731d6c39 | bigcode/the-stack | train |
af21893311bd95544846ea78 | train | function | def php_phpfunction_role(typ,
rawtext,
text,
lineno,
inliner,
options={},
content=[]):
text = utils.unescape(text)
has_explicit_title, title, full_function = spli... | def php_phpfunction_role(typ,
rawtext,
text,
lineno,
inliner,
options={},
content=[]):
| text = utils.unescape(text)
has_explicit_title, title, full_function = split_explicit_title(text)
full_url = 'https://www.php.net/manual/en/function.%s.php' % full_function.replace(
'_', '-').lower()
if not has_explicit_title:
title = full_function
list = [
nodes.reference(... | =full_url,
reftitle=full_class)
]
pnode = nodes.literal('', '', *list)
return [pnode], []
def php_phpfunction_role(typ,
rawtext,
text,
lineno,
inliner,
options... | 63 | 64 | 150 | 31 | 32 | greg0ire/sphinx-php | sensio/sphinx/phpcode.py | Python | php_phpfunction_role | php_phpfunction_role | 174 | 197 | 174 | 180 | 06e0895200f25cab7abc05fb6f0d9030d34ee0e4 | bigcode/the-stack | train |
3cc06ef797f01dfef75744a3 | train | function | def php_class_role(typ, rawtext, text, lineno, inliner, options={},
content=[]):
text = utils.unescape(text)
env = inliner.document.settings.env
base_url = env.app.config.api_url
has_explicit_title, title, full_class = split_explicit_title(text)
try:
full_url = base_url %... | def php_class_role(typ, rawtext, text, lineno, inliner, options={},
content=[]):
| text = utils.unescape(text)
env = inliner.document.settings.env
base_url = env.app.config.api_url
has_explicit_title, title, full_class = split_explicit_title(text)
try:
full_url = base_url % full_class.replace('\\', '/')
except (TypeError, ValueError):
env.warn(
env... | name
list = [
nodes.reference(title,
title,
internal=False,
refuri=full_url,
reftitle=namespace)
]
pnode = nodes.literal('', '', *list)
return [pnode], []
def php_class_role(typ, rawtext, text, linen... | 77 | 78 | 260 | 25 | 52 | greg0ire/sphinx-php | sensio/sphinx/phpcode.py | Python | php_class_role | php_class_role | 49 | 78 | 49 | 50 | 98bb1d78aa3e8cd661eb4c099848da2c75feb352 | bigcode/the-stack | train |
c9392ad3497f2f24327b8c02 | train | function | def test_get_instance_metrics_lt_92(check):
"""
check output when 9.2+
"""
check._version = VersionInfo(9, 1, 0)
res = check._get_instance_metrics(False, False)
assert res['metrics'] == util.COMMON_METRICS
| def test_get_instance_metrics_lt_92(check):
| """
check output when 9.2+
"""
check._version = VersionInfo(9, 1, 0)
res = check._get_instance_metrics(False, False)
assert res['metrics'] == util.COMMON_METRICS
| BSD License (see LICENSE)
import mock
import psycopg2
import pytest
from mock import MagicMock
from semver import VersionInfo
from six import iteritems
from datadog_checks.postgres import util
pytestmark = pytest.mark.unit
def test_get_instance_metrics_lt_92(check):
| 64 | 64 | 65 | 10 | 53 | fujigon/integrations-core | postgres/tests/test_unit.py | Python | test_get_instance_metrics_lt_92 | test_get_instance_metrics_lt_92 | 16 | 22 | 16 | 16 | d69ed57c8d06efd3a52485397cd05580c7393ef9 | bigcode/the-stack | train |
ff448bfdcaa75bf16fa11e13 | train | function | def test_get_instance_metrics_database_size_metrics(check):
"""
Test the function behaves correctly when `database_size_metrics` is passed
"""
expected = util.COMMON_METRICS
expected.update(util.NEWER_92_METRICS)
expected.update(util.DATABASE_SIZE_METRICS)
res = check._get_instance_metrics(T... | def test_get_instance_metrics_database_size_metrics(check):
| """
Test the function behaves correctly when `database_size_metrics` is passed
"""
expected = util.COMMON_METRICS
expected.update(util.NEWER_92_METRICS)
expected.update(util.DATABASE_SIZE_METRICS)
res = check._get_instance_metrics(True, False)
assert res['metrics'] == expected
| ._version = 'foo' # metrics were cached so this shouldn't be called
res = check._get_instance_metrics([], False)
assert res['metrics'] == dict(util.COMMON_METRICS, **util.NEWER_92_METRICS)
def test_get_instance_metrics_database_size_metrics(check):
| 64 | 64 | 84 | 10 | 54 | fujigon/integrations-core | postgres/tests/test_unit.py | Python | test_get_instance_metrics_database_size_metrics | test_get_instance_metrics_database_size_metrics | 45 | 53 | 45 | 45 | 5c249a1e313d096535a7524e546fa7465f3b313d | bigcode/the-stack | train |
9071445e35684861a5b3c246 | train | function | def test_get_instance_metrics_92(check):
"""
check output when <9.2
"""
check._version = VersionInfo(9, 2, 0)
res = check._get_instance_metrics(False, False)
assert res['metrics'] == dict(util.COMMON_METRICS, **util.NEWER_92_METRICS)
| def test_get_instance_metrics_92(check):
| """
check output when <9.2
"""
check._version = VersionInfo(9, 2, 0)
res = check._get_instance_metrics(False, False)
assert res['metrics'] == dict(util.COMMON_METRICS, **util.NEWER_92_METRICS)
| """
check output when 9.2+
"""
check._version = VersionInfo(9, 1, 0)
res = check._get_instance_metrics(False, False)
assert res['metrics'] == util.COMMON_METRICS
def test_get_instance_metrics_92(check):
| 64 | 64 | 76 | 9 | 54 | fujigon/integrations-core | postgres/tests/test_unit.py | Python | test_get_instance_metrics_92 | test_get_instance_metrics_92 | 25 | 31 | 25 | 25 | 967a0f7112e01e45c61b6ed337d46d934475abb6 | bigcode/the-stack | train |
397a490b2a49599ae5164759 | train | function | def test_malformed_get_custom_queries(check):
"""
Test early-exit conditions for _get_custom_queries()
"""
check.log = MagicMock()
db = MagicMock()
check.db = db
malformed_custom_query = {}
# Make sure 'metric_prefix' is defined
check._get_custom_queries([], [malformed_custom_query... | def test_malformed_get_custom_queries(check):
| """
Test early-exit conditions for _get_custom_queries()
"""
check.log = MagicMock()
db = MagicMock()
check.db = db
malformed_custom_query = {}
# Make sure 'metric_prefix' is defined
check._get_custom_queries([], [malformed_custom_query])
check.log.error.assert_called_once_with... | 'foo' # metrics were cached so this shouldn't be called
res = check._get_instance_metrics([], False)
assert res['metrics'] == dict(util.COMMON_METRICS, **util.NEWER_92_METRICS)
def test_get_instance_metrics_database_size_metrics(check):
"""
Test the function behaves correctly when `database_size_met... | 256 | 256 | 1,033 | 9 | 247 | fujigon/integrations-core | postgres/tests/test_unit.py | Python | test_malformed_get_custom_queries | test_malformed_get_custom_queries | 69 | 176 | 69 | 69 | 93c632f4e872a7ca941bb8cb52d1f482de6b1d79 | bigcode/the-stack | train |
0b3bd8288326900a717ae508 | train | function | def test_get_instance_metrics_state(check):
"""
Ensure data is consistent when the function is called more than once
"""
res = check._get_instance_metrics(False, False)
assert res['metrics'] == dict(util.COMMON_METRICS, **util.NEWER_92_METRICS)
check._version = 'foo' # metrics were cached so th... | def test_get_instance_metrics_state(check):
| """
Ensure data is consistent when the function is called more than once
"""
res = check._get_instance_metrics(False, False)
assert res['metrics'] == dict(util.COMMON_METRICS, **util.NEWER_92_METRICS)
check._version = 'foo' # metrics were cached so this shouldn't be called
res = check._get_... | """
check._version = VersionInfo(9, 2, 0)
res = check._get_instance_metrics(False, False)
assert res['metrics'] == dict(util.COMMON_METRICS, **util.NEWER_92_METRICS)
def test_get_instance_metrics_state(check):
| 64 | 64 | 120 | 8 | 56 | fujigon/integrations-core | postgres/tests/test_unit.py | Python | test_get_instance_metrics_state | test_get_instance_metrics_state | 34 | 42 | 34 | 34 | 99af586d90b4121ab16b3963f1becdf7aca6e450 | bigcode/the-stack | train |
9dace630a2600f9835c163be | train | function | @pytest.mark.parametrize(
'test_case, params',
[
('9.6.2', {'version.major': '9', 'version.minor': '6', 'version.patch': '2'}),
('10.0', {'version.major': '10', 'version.minor': '0', 'version.patch': '0'}),
(
'11nightly3',
{'version.major': '11', 'version.minor': ... | @pytest.mark.parametrize(
'test_case, params',
[
('9.6.2', {'version.major': '9', 'version.minor': '6', 'version.patch': '2'}),
('10.0', {'version.major': '10', 'version.minor': '0', 'version.patch': '0'}),
(
'11nightly3',
{'version.major': '11', 'version.minor': ... | check.check_id = 'test:123'
with mock.patch('datadog_checks.base.stubs.datadog_agent.set_check_metadata') as m:
check.set_metadata('version', test_case)
for name, value in iteritems(params):
m.assert_any_call('test:123', name, value)
m.assert_any_call('test:123', 'version.sch... | @pytest.mark.parametrize(
'test_case, params',
[
('9.6.2', {'version.major': '9', 'version.minor': '6', 'version.patch': '2'}),
('10.0', {'version.major': '10', 'version.minor': '0', 'version.patch': '0'}),
(
'11nightly3',
{'version.major': '11', 'version.minor': ... | 129 | 69 | 231 | 129 | 0 | fujigon/integrations-core | postgres/tests/test_unit.py | Python | test_version_metadata | test_version_metadata | 179 | 197 | 179 | 190 | e41f4e19d7f01b125f7f24e8dd885f7a5cb45abd | bigcode/the-stack | train |
02ed8e7873ef1ff5ebb70c79 | train | function | def test_get_instance_with_default(check):
"""
Test the contents of the query string with different `collect_default_db` values
"""
collect_default_db = False
res = check._get_instance_metrics(False, collect_default_db)
assert " AND psd.datname not ilike 'postgres'" in res['query']
collect... | def test_get_instance_with_default(check):
| """
Test the contents of the query string with different `collect_default_db` values
"""
collect_default_db = False
res = check._get_instance_metrics(False, collect_default_db)
assert " AND psd.datname not ilike 'postgres'" in res['query']
collect_default_db = True
res = check._get_ins... | """
expected = util.COMMON_METRICS
expected.update(util.NEWER_92_METRICS)
expected.update(util.DATABASE_SIZE_METRICS)
res = check._get_instance_metrics(True, False)
assert res['metrics'] == expected
def test_get_instance_with_default(check):
| 64 | 64 | 112 | 8 | 55 | fujigon/integrations-core | postgres/tests/test_unit.py | Python | test_get_instance_with_default | test_get_instance_with_default | 56 | 66 | 56 | 56 | 065fba78d047d90e3073f216cd568027ddd0fec0 | bigcode/the-stack | train |
d4812edfbb30ad473733a92f | train | class | class EndpointMetaClass(type):
def __new__(cls, name, bases, attrs):
new_class = super(EndpointMetaClass, cls).__new__(cls, name, bases, attrs)
inflector = None
processed = []
black_list = dir(BaseEndpoint)
model = getattr(new_class, 'model', None)
for base in rev... | class EndpointMetaClass(type):
| def __new__(cls, name, bases, attrs):
new_class = super(EndpointMetaClass, cls).__new__(cls, name, bases, attrs)
inflector = None
processed = []
black_list = dir(BaseEndpoint)
model = getattr(new_class, 'model', None)
for base in reversed(new_class.__mro__):
... | from collections import Iterable
import json
import os
from django.db.models.fields.related import ForeignKey
from django.conf import settings as django_settings
from django.urls import reverse
from django.utils.module_loading import import_string
from inflector import Inflector
from .factories import serializer_fac... | 175 | 180 | 602 | 6 | 169 | SupraSummus/drf-schema-adapter | drf_auto_endpoint/endpoints.py | Python | EndpointMetaClass | EndpointMetaClass | 35 | 107 | 35 | 36 | 26f92e707826b673af07d1e7128e4d1443258319 | bigcode/the-stack | train |
854a968c8b9eddac8fccf1eb | train | class | class Endpoint(BaseEndpoint, metaclass=EndpointMetaClass):
def __init__(self, model=None, **kwargs):
self.inflector = Inflector(self.inflector_language)
if model is not None:
self.model = model
arg_names = ('fields', 'serializer', 'permission_classes', 'filter_fields', 'search... | class Endpoint(BaseEndpoint, metaclass=EndpointMetaClass):
| def __init__(self, model=None, **kwargs):
self.inflector = Inflector(self.inflector_language)
if model is not None:
self.model = model
arg_names = ('fields', 'serializer', 'permission_classes', 'filter_fields', 'search_fields',
'viewset', 'read_only', 'incl... | continue
if getattr(action, 'action_type', None) == 'list':
list_action = {
'url': reverse('{}-{}'.format(self.get_url(), action.__name__.lower())),
'verb': self._verb_for_action(action),
}
list_action.update(action.act... | 100 | 100 | 335 | 12 | 87 | SupraSummus/drf-schema-adapter | drf_auto_endpoint/endpoints.py | Python | Endpoint | Endpoint | 446 | 482 | 446 | 447 | f98780a40855f77b568327557e194862ee2891db | bigcode/the-stack | train |
8e79fe98accc5c9797fee256 | train | function | def get_all_field_names(model):
return [
field.name
for field in model._meta.get_fields()
if not hasattr(field, 'field') or getattr(field, 'related_name', None) is not None
]
| def get_all_field_names(model):
| return [
field.name
for field in model._meta.get_fields()
if not hasattr(field, 'field') or getattr(field, 'related_name', None) is not None
]
|
from .utils import get_languages, get_field_dict
from .app_settings import settings
try:
from modeltranslation.translator import translator
except ImportError:
class Translator(object):
def get_registered_models(self, abstract=True):
return []
translator = Translator()
def get_all_fi... | 64 | 64 | 49 | 7 | 57 | SupraSummus/drf-schema-adapter | drf_auto_endpoint/endpoints.py | Python | get_all_field_names | get_all_field_names | 27 | 32 | 27 | 27 | abc81caf0092b212462e6ff223e03569aef1f464 | bigcode/the-stack | train |
57b686dfe38b82a6bf6c836e | train | class | class BaseEndpoint(object):
base_serializer = import_string(settings.BASE_SERIALIZER)
base_viewset = import_string(settings.BASE_VIEWSET)
base_readonly_viewset = import_string(settings.BASE_READONLY_VIEWSET)
model = None
fields = None
exclude_fields = ()
extra_fields = None
foreign_key... | class BaseEndpoint(object):
| base_serializer = import_string(settings.BASE_SERIALIZER)
base_viewset = import_string(settings.BASE_VIEWSET)
base_readonly_viewset = import_string(settings.BASE_READONLY_VIEWSET)
model = None
fields = None
exclude_fields = ()
extra_fields = None
foreign_key_as_list = False
seriali... | fieldsets = json.load(f)
value.action_kwargs['params']['fieldsets'] = \
fieldsets['{}_{}'.format(new_class.model.__name__, key)]
except FileNotFoundError:
pass
except KeyError... | 256 | 256 | 2,331 | 5 | 250 | SupraSummus/drf-schema-adapter | drf_auto_endpoint/endpoints.py | Python | BaseEndpoint | BaseEndpoint | 110 | 443 | 110 | 111 | 53fe261625656c7c3a728d02fc1e7d63bd7694fc | bigcode/the-stack | train |
4b78f378e9199e7743c59721 | train | class | class GroupLassoRegularizer(generic_regularizers.OpRegularizer):
"""A regularizer for convolutions and matmul operations, based on group-lasso.
Supported ops: Conv2D, Conv2DBackpropInput (transposed Conv2D), and MatMul
are supported. The grouping is done according to the formula:
(1 - l1_fraction) * L2(weight... | class GroupLassoRegularizer(generic_regularizers.OpRegularizer):
| """A regularizer for convolutions and matmul operations, based on group-lasso.
Supported ops: Conv2D, Conv2DBackpropInput (transposed Conv2D), and MatMul
are supported. The grouping is done according to the formula:
(1 - l1_fraction) * L2(weights) / sqrt(dim) + l1_fraction * L1(weights) / dim,
where `dim` ... | """A regularizer based on group-lasso.
All the weights that are related to a single output are grouped into one LASSO
group (https://arxiv.org/pdf/1611.06321.pdf).
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from morph_net.framework import generic_r... | 105 | 156 | 522 | 14 | 90 | nmoezzi/morph-net | morph_net/op_regularizers/group_lasso_regularizer.py | Python | GroupLassoRegularizer | GroupLassoRegularizer | 15 | 65 | 15 | 15 | 125505af5221b2f01def546144fdd2c951416895 | bigcode/the-stack | train |
e2ee85fb715b77ab5918d26c | train | function | def pad_up_to(t, max_in_dims):
s = tf.shape(t)
paddings = [[0, m - s[i]] for (i, m) in enumerate(max_in_dims)]
return tf.pad(t, paddings, 'CONSTANT', constant_values=0)
| def pad_up_to(t, max_in_dims):
| s = tf.shape(t)
paddings = [[0, m - s[i]] for (i, m) in enumerate(max_in_dims)]
return tf.pad(t, paddings, 'CONSTANT', constant_values=0)
| file.')
def length_filter(max_len):
def filter_fn(batch):
l = tf.maximum(tf.shape(batch['inputs'])[0],
tf.shape(batch['targets'])[0])
return tf.less(l, max_len + 1)
return filter_fn
def pad_up_to(t, max_in_dims):
| 64 | 64 | 59 | 10 | 53 | muell-monster/google-research | flax_models/mlperf/transformer/mlperf_input_pipeline.py | Python | pad_up_to | pad_up_to | 81 | 84 | 81 | 81 | e4992027fae06f1ca97831728be3dd2938ffd6fc | bigcode/the-stack | train |
71e423f070510e74ccf99520 | train | function | def get_wmt_dataset(batch_size, train, shuffle_size=16384):
"""Get the train or eval split of WMT as a tf.data.Dataset."""
keys = TRAIN_KEYS if train else EVAL_KEYS
def parse_function(example_proto):
return tf.io.parse_single_example(
example_proto,
{k: tf.io.FixedLenSequenceFeature([], tf.in... | def get_wmt_dataset(batch_size, train, shuffle_size=16384):
| """Get the train or eval split of WMT as a tf.data.Dataset."""
keys = TRAIN_KEYS if train else EVAL_KEYS
def parse_function(example_proto):
return tf.io.parse_single_example(
example_proto,
{k: tf.io.FixedLenSequenceFeature([], tf.int64, allow_missing=True)
for k in keys})
def cas... | .')
def length_filter(max_len):
def filter_fn(batch):
l = tf.maximum(tf.shape(batch['inputs'])[0],
tf.shape(batch['targets'])[0])
return tf.less(l, max_len + 1)
return filter_fn
def pad_up_to(t, max_in_dims):
s = tf.shape(t)
paddings = [[0, m - s[i]] for (i, m) in enumerate(max_in... | 128 | 128 | 429 | 16 | 112 | muell-monster/google-research | flax_models/mlperf/transformer/mlperf_input_pipeline.py | Python | get_wmt_dataset | get_wmt_dataset | 87 | 132 | 87 | 87 | a41f9add4bd17f0c285e927ad9e87d272cbd27ee | bigcode/the-stack | train |
5c86ea754de754063321442a | train | function | def length_filter(max_len):
def filter_fn(batch):
l = tf.maximum(tf.shape(batch['inputs'])[0],
tf.shape(batch['targets'])[0])
return tf.less(l, max_len + 1)
return filter_fn
| def length_filter(max_len):
| def filter_fn(batch):
l = tf.maximum(tf.shape(batch['inputs'])[0],
tf.shape(batch['targets'])[0])
return tf.less(l, max_len + 1)
return filter_fn
| records.')
flags.DEFINE_string(
'eval_data_path', default=EVAL_PATH,
help='Path to unpacked evaluation dataset tfrecords.')
flags.DEFINE_string(
'vocab_path', default=VOCAB_PATH,
help='Path to shared vocabulary file.')
def length_filter(max_len):
| 63 | 64 | 51 | 6 | 57 | muell-monster/google-research | flax_models/mlperf/transformer/mlperf_input_pipeline.py | Python | length_filter | length_filter | 73 | 78 | 73 | 73 | faa2b7e4d9a854432e275e68b5712b39196b1349 | bigcode/the-stack | train |
9888abe253e89db05257d3fb | train | class | class MerchSerializer(serializers.ModelSerializer):
class Meta:
model = MoringaMerch
fields = ('id','name','description','price') | class MerchSerializer(serializers.ModelSerializer):
| class Meta:
model = MoringaMerch
fields = ('id','name','description','price') | from rest_framework import serializers
from .models import MoringaMerch
class MerchSerializer(serializers.ModelSerializer):
| 23 | 64 | 32 | 7 | 15 | Kipkorir-Gideon/Tribune | news/serializer.py | Python | MerchSerializer | MerchSerializer | 5 | 8 | 5 | 5 | 8fe6a8d1d1dd4fad704e6fa6dee17a9f69e8a410 | bigcode/the-stack | train |
5e1cb3a20c5ae68c78ef7e9d | train | class | class _TstExchangeCalendar:
def __init__(self):
self.a_test_var = "initialized"
@property
def open_offset(self):
return -2
@property
def close_offset(self):
return 3
| class _TstExchangeCalendar:
| def __init__(self):
self.a_test_var = "initialized"
@property
def open_offset(self):
return -2
@property
def close_offset(self):
return 3
| mcal_iepa = get_calendar("IEPA")
ecal_iepa = ecal.get_calendar("IEPA")
start, end = ecal_iepa._closes[[0, -1]]
# No exchange_calendar has a close_offset so this class implements it for testing
class _TstExchangeCalendar:
| 64 | 64 | 53 | 7 | 56 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | _TstExchangeCalendar | _TstExchangeCalendar | 882 | 890 | 882 | 882 | a6627ca026a0c19556c0b725d926631cd69464d6 | bigcode/the-stack | train |
dd14d44e3139b896654789b7 | train | function | def test_closes_opens():
sched = mcal_iepa.schedule(start, end)
assert_same(ecal_iepa._closes, sched.market_close)
assert_same(ecal_iepa._opens, sched.market_open)
| def test_closes_opens():
| sched = mcal_iepa.schedule(start, end)
assert_same(ecal_iepa._closes, sched.market_close)
assert_same(ecal_iepa._opens, sched.market_open)
| _cal._EC_NOT_INITIALIZED
def assert_same(one, two):
assert one.shape[0] == two.shape[0], f"the shape is different {one.shape[0]} != {two.shape[0]}"
assert (one.values == two.values).all()
def test_closes_opens():
| 64 | 64 | 48 | 7 | 57 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_closes_opens | test_closes_opens | 924 | 928 | 924 | 924 | 67f1792257d1fbccda4bad1d085379918d9566ef | bigcode/the-stack | train |
58b07fa7bebd014f2e0df273 | train | function | def test_is_open_now(patch_get_current_time):
cal = FakeCalendar()
schedule = cal.schedule('2014-01-01', '2016-12-31')
assert cal.is_open_now(schedule) is True
| def test_is_open_now(patch_get_current_time):
| cal = FakeCalendar()
schedule = cal.schedule('2014-01-01', '2016-12-31')
assert cal.is_open_now(schedule) is True
| 14:00:00+00:00")) is False
with pytest.raises(ValueError):
cal.open_at_time(schedule, pd.Timestamp("2014-07-11 14:00:00+00:00"), only_rth= True)
def test_is_open_now(patch_get_current_time):
| 64 | 64 | 49 | 11 | 53 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_is_open_now | test_is_open_now | 842 | 847 | 842 | 842 | 19a3dd4618084f646035520e9300813f39c3bdfa | bigcode/the-stack | train |
fb97cd9bf815300de81ac44b | train | function | def test_custom_schedule():
cal = FakeBreakCalendar()
cal.add_time("pre", time(9))
cal.add_time("post", time(13))
# test default
schedule = cal.schedule("2016-12-23", "2016-12-31")
assert schedule.columns.tolist() == ["market_open", "break_start", "break_end", "market_close"]
# special mar... | def test_custom_schedule():
| cal = FakeBreakCalendar()
cal.add_time("pre", time(9))
cal.add_time("post", time(13))
# test default
schedule = cal.schedule("2016-12-23", "2016-12-31")
assert schedule.columns.tolist() == ["market_open", "break_start", "break_end", "market_close"]
# special market_open should take effect
... | -01', '2016-12-01')
if pd.__version__ < '1.1.0':
assert_frame_equal(actual, expected)
else:
assert_frame_equal(actual, expected, check_freq=False)
# start date after end date
with pytest.raises(ValueError):
cal.schedule('2016-02-02', '2016-01-01')
# using a different ti... | 256 | 256 | 1,277 | 5 | 251 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_custom_schedule | test_custom_schedule | 466 | 543 | 466 | 466 | d95e2e1cb49042b41da4516686536984b2d78dc6 | bigcode/the-stack | train |
a430d1cac78a61dcf638d36e | train | function | def test_special_opens():
cal = FakeCalendar()
results = cal.schedule('2012-07-01', '2012-07-06')
opens = results['market_open'].tolist()
# confirm that the day before July 4th is an 11:15 open not 11:13
assert pd.Timestamp('2012-07-02 11:13', tz='Asia/Ulaanbaatar').tz_convert('UTC') in opens
a... | def test_special_opens():
| cal = FakeCalendar()
results = cal.schedule('2012-07-01', '2012-07-06')
opens = results['market_open'].tolist()
# confirm that the day before July 4th is an 11:15 open not 11:13
assert pd.Timestamp('2012-07-02 11:13', tz='Asia/Ulaanbaatar').tz_convert('UTC') in opens
assert pd.Timestamp('2012-0... | ('2012-10-26') in days
assert pd.Timestamp('2012-10-29') not in days
assert pd.Timestamp('2012-10-30') not in days
assert pd.Timestamp('2012-10-31') in days
def test_special_opens():
| 64 | 64 | 163 | 6 | 57 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_special_opens | test_special_opens | 672 | 680 | 672 | 672 | 595c062f36d0fd68d44fe95ecedc6a4a8aa55237 | bigcode/the-stack | train |
e737046b0150eba096b9d88e | train | function | def test_holidays():
cal = FakeCalendar()
actual = cal.holidays().holidays
assert pd.Timestamp('2016-12-26') in actual
assert pd.Timestamp('2012-01-02') in actual
assert pd.Timestamp('2012-12-25') in actual
assert pd.Timestamp('2012-10-29') in actual
assert pd.Timestamp('2012-10-30') in act... | def test_holidays():
| cal = FakeCalendar()
actual = cal.holidays().holidays
assert pd.Timestamp('2016-12-26') in actual
assert pd.Timestamp('2012-01-02') in actual
assert pd.Timestamp('2012-12-25') in actual
assert pd.Timestamp('2012-10-29') in actual
assert pd.Timestamp('2012-10-30') in actual
| start == pd.Timestamp('2016-12-01')
assert end == pd.Timestamp('2016-12-31')
def test_properties():
cal = FakeCalendar()
assert cal.name == 'DMY'
assert cal.tz == timezone('Asia/Ulaanbaatar')
def test_holidays():
| 64 | 64 | 96 | 5 | 59 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_holidays | test_holidays | 384 | 392 | 384 | 384 | 8728be1b4e8a3278f85ec4ceb7ecfc031e9c4a69 | bigcode/the-stack | train |
00864c905ba8613d4a03ad67 | train | class | class FakeCalendar(MarketCalendar):
regular_market_times = {
"market_open": ((None, time(11,18)),
("1902-03-04", time(11,13))),
"market_close": ((None, time(11, 45)),
("1901-02-03", time(11,49)))
}
@property
def name(self):
return... | class FakeCalendar(MarketCalendar):
| regular_market_times = {
"market_open": ((None, time(11,18)),
("1902-03-04", time(11,13))),
"market_close": ((None, time(11, 45)),
("1901-02-03", time(11,49)))
}
@property
def name(self):
return "DMY"
@property
def tz(sel... | ings, MonTuesThursBeforeIndependenceDay,
USNationalDaysofMourning, USNewYearsDay)
from pandas_market_calendars.market_calendar import MarketCalendar #, clean_dates, days_at_time
from pandas_market_calendars.exchange_calendars_mirror import TradingCalendar
from pandas_mar... | 95 | 95 | 317 | 7 | 87 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | FakeCalendar | FakeCalendar | 35 | 73 | 35 | 35 | 9139d3d7f7117a1e6c7b75f82b9ec30da8b49a1b | bigcode/the-stack | train |
d15ce606a07e478ff10568b3 | train | function | @pytest.fixture
def patch_get_current_time(monkeypatch):
def get_fake_time():
return pd.Timestamp('2014-07-02 03:40', tz='UTC')
monkeypatch.setattr(MarketCalendar, '_get_current_time', get_fake_time)
| @pytest.fixture
def patch_get_current_time(monkeypatch):
| def get_fake_time():
return pd.Timestamp('2014-07-02 03:40', tz='UTC')
monkeypatch.setattr(MarketCalendar, '_get_current_time', get_fake_time)
| return [(time(10, 20), ['2016-12-29'])]
@property
def special_closes_adhoc(self):
return [(time(10, 40), ['2016-12-30'])]
@pytest.fixture
def patch_get_current_time(monkeypatch):
| 64 | 64 | 56 | 12 | 52 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | patch_get_current_time | patch_get_current_time | 105 | 109 | 105 | 106 | 2b54267dd9059c48e4c6af1bb2fd82181080f81e | bigcode/the-stack | train |
8bdbe434cad02b9a11c4b49f | train | function | def test_clean_dates():
cal = FakeCalendar()
start, end = cal.clean_dates('2016-12-01', '2016-12-31')
assert start == pd.Timestamp('2016-12-01')
assert end == pd.Timestamp('2016-12-31')
start, end = cal.clean_dates('2016-12-01 12:00', '2016-12-31 12:00')
assert start == pd.Timestamp('2016-12-0... | def test_clean_dates():
| cal = FakeCalendar()
start, end = cal.clean_dates('2016-12-01', '2016-12-31')
assert start == pd.Timestamp('2016-12-01')
assert end == pd.Timestamp('2016-12-31')
start, end = cal.clean_dates('2016-12-01 12:00', '2016-12-31 12:00')
assert start == pd.Timestamp('2016-12-01')
assert end == pd... | 00'
),
# ICE day after DST start
(
'1990-04-02', None, "with_offset", chicago, '1990-04-01 10:30',
),
]
for args in args_list:
dat(args[0], args[1], args[2], args[3], args[4])
def test_clean_dates():
| 81 | 81 | 271 | 5 | 76 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_clean_dates | test_clean_dates | 356 | 375 | 356 | 356 | 2743cc6e44c59fb9d13ec8d5ac2670e8ab52b8c0 | bigcode/the-stack | train |
3c71b655a76ed7f411c6c0b1 | train | function | def test_bad_dates():
cal = FakeCalendar()
empty = pd.DataFrame(columns=['market_open', 'market_close'], index=pd.DatetimeIndex([], freq='C'))
# single weekend date
schedule = cal.schedule('2018-06-30', '2018-06-30')
assert_frame_equal(schedule, empty)
# two weekend dates
schedule = cal.s... | def test_bad_dates():
| cal = FakeCalendar()
empty = pd.DataFrame(columns=['market_open', 'market_close'], index=pd.DatetimeIndex([], freq='C'))
# single weekend date
schedule = cal.schedule('2018-06-30', '2018-06-30')
assert_frame_equal(schedule, empty)
# two weekend dates
schedule = cal.schedule('2018-06-30', ... | 00:00"), only_rth= True)
def test_is_open_now(patch_get_current_time):
cal = FakeCalendar()
schedule = cal.schedule('2014-01-01', '2016-12-31')
assert cal.is_open_now(schedule) is True
def test_bad_dates():
| 64 | 64 | 175 | 5 | 58 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_bad_dates | test_bad_dates | 850 | 869 | 850 | 850 | 2ced934995620d6b4941002a1036dcc50692d9cb | bigcode/the-stack | train |
fe544310d234fb4a61b5c8db | train | function | def test_regular_holidays():
cal = FakeCalendar()
results = cal.schedule('2016-12-01', '2017-01-05')
days = results.index
# check regular holidays
# Christmas
assert pd.Timestamp('2016-12-23') in days
assert pd.Timestamp('2016-12-26') not in days
# New Years
assert pd.Timestamp('20... | def test_regular_holidays():
| cal = FakeCalendar()
results = cal.schedule('2016-12-01', '2017-01-05')
days = results.index
# check regular holidays
# Christmas
assert pd.Timestamp('2016-12-23') in days
assert pd.Timestamp('2016-12-26') not in days
# New Years
assert pd.Timestamp('2017-01-02') not in days
as... | ', 'market_close'])
# because of change in pandas in v0.24, pre-0.24 versions need object dtype
if pd.__version__ < '0.24':
expected = expected.astype(object)
assert_series_equal(results.iloc[-1], expected)
def test_regular_holidays():
| 64 | 64 | 116 | 6 | 58 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_regular_holidays | test_regular_holidays | 643 | 655 | 643 | 643 | 44b5368b72c9bb8f4d40877216efc288abe93f8c | bigcode/the-stack | train |
62f08c06e0ff470831f3a406 | train | function | def assert_same(one, two):
assert one.shape[0] == two.shape[0], f"the shape is different {one.shape[0]} != {two.shape[0]}"
assert (one.values == two.values).all()
| def assert_same(one, two):
| assert one.shape[0] == two.shape[0], f"the shape is different {one.shape[0]} != {two.shape[0]}"
assert (one.values == two.values).all()
| _NOT_INITIALIZED
assert test_cal.open_offset == -2
assert test_cal.close_offset == 3
assert test_cal["market_close", "all"] == ((None, time(23), 3),)
assert test_cal._EC_NOT_INITIALIZED
def assert_same(one, two):
| 64 | 64 | 50 | 7 | 56 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | assert_same | assert_same | 920 | 922 | 920 | 920 | d6012fa1283a995e65159446082db350dd4ea695 | bigcode/the-stack | train |
982766020380c08573940bb3 | train | function | def test_special_opens_adhoc():
cal = FakeCalendar()
results = cal.schedule('2016-12-10', '2016-12-20')
opens = results['market_open'].tolist()
# confirm that 2016-12-13 is an 11:20 open not 11:13
assert pd.Timestamp('2016-12-12 11:13', tz='Asia/Ulaanbaatar').tz_convert('UTC') in opens
assert ... | def test_special_opens_adhoc():
| cal = FakeCalendar()
results = cal.schedule('2016-12-10', '2016-12-20')
opens = results['market_open'].tolist()
# confirm that 2016-12-13 is an 11:20 open not 11:13
assert pd.Timestamp('2016-12-12 11:13', tz='Asia/Ulaanbaatar').tz_convert('UTC') in opens
assert pd.Timestamp('2016-12-13 11:20',... | -03 11:15', tz='Asia/Ulaanbaatar').tz_convert('UTC') in opens
assert pd.Timestamp('2012-07-04 11:13', tz='Asia/Ulaanbaatar').tz_convert('UTC') in opens
def test_special_opens_adhoc():
| 64 | 64 | 166 | 9 | 54 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_special_opens_adhoc | test_special_opens_adhoc | 683 | 692 | 683 | 683 | cce8154283e6acbce8cc5ccb05423d728ab7e15c | bigcode/the-stack | train |
275a99c6aaf9a19283fc0e15 | train | function | def test_protected_dictionary(cal= None):
cal = FakeCalendar() if cal is None else cal
# shouldn't be able to add
with pytest.raises(TypeError) as e:
cal.regular_market_times["market_open"] = time(12)
# nor delete
with pytest.raises(TypeError) as e:
del cal.regular_market_times["mar... | def test_protected_dictionary(cal= None):
| cal = FakeCalendar() if cal is None else cal
# shouldn't be able to add
with pytest.raises(TypeError) as e:
cal.regular_market_times["market_open"] = time(12)
# nor delete
with pytest.raises(TypeError) as e:
del cal.regular_market_times["market_open"]
| .fixture
def patch_get_current_time(monkeypatch):
def get_fake_time():
return pd.Timestamp('2014-07-02 03:40', tz='UTC')
monkeypatch.setattr(MarketCalendar, '_get_current_time', get_fake_time)
def test_protected_dictionary(cal= None):
| 64 | 64 | 81 | 9 | 55 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_protected_dictionary | test_protected_dictionary | 112 | 120 | 112 | 112 | 78b5f0f80999330085dbe350d9f96b31a260b80c | bigcode/the-stack | train |
4400e01d0b57dceb31ec07ee | train | function | def test_pickling():
for Cal in [FakeCalendar, FakeBreakCalendar, NYSEExchangeCalendar]:
# instance
cal = Cal()
pickled = pickle.dumps(cal)
unpickled = pickle.loads(pickled)
assert cal.regular_market_times == unpickled.regular_market_times
assert cal.market_times ==... | def test_pickling():
| for Cal in [FakeCalendar, FakeBreakCalendar, NYSEExchangeCalendar]:
# instance
cal = Cal()
pickled = pickle.dumps(cal)
unpickled = pickle.loads(pickled)
assert cal.regular_market_times == unpickled.regular_market_times
assert cal.market_times == unpickled.market_time... | # shouldn't be able to add
with pytest.raises(TypeError) as e:
cal.regular_market_times["market_open"] = time(12)
# nor delete
with pytest.raises(TypeError) as e:
del cal.regular_market_times["market_open"]
def test_pickling():
| 64 | 64 | 187 | 5 | 59 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_pickling | test_pickling | 122 | 144 | 122 | 123 | 420220cdab1db1177eabc910f4941f794c34c5f4 | bigcode/the-stack | train |
ae7370bfe906b1edd31da1aa | train | function | def test_schedule_w_times():
cal = FakeCalendar(time(12, 12), time(13, 13))
assert cal.open_time == time(12, 12)
assert cal.close_time == time(13, 13)
results = cal.schedule('2016-12-01', '2016-12-31')
assert len(results) == 21
expected = pd.Series({'market_open': pd.Timestamp('2016-12-01 04:... | def test_schedule_w_times():
| cal = FakeCalendar(time(12, 12), time(13, 13))
assert cal.open_time == time(12, 12)
assert cal.close_time == time(13, 13)
results = cal.schedule('2016-12-01', '2016-12-31')
assert len(results) == 21
expected = pd.Series({'market_open': pd.Timestamp('2016-12-01 04:12:00+0000', tz='UTC'),
... | =pd.DatetimeIndex([pd.Timestamp('2016-12-28')]),
columns=['market_open', 'break_start', 'break_end', 'market_close'])
actual = cal.schedule('2016-12-28', '2016-12-28', tz='America/New_York')
if pd.__version__ < '1.1.0':
assert_frame_equal(actual, expected)
else:
... | 105 | 105 | 351 | 6 | 99 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_schedule_w_times | test_schedule_w_times | 615 | 640 | 615 | 615 | 796d6f62afe7a3c58f6601dbe91567ae3cbce671 | bigcode/the-stack | train |
7142d24d3c427179128cd4e4 | train | function | def test_properties():
cal = FakeCalendar()
assert cal.name == 'DMY'
assert cal.tz == timezone('Asia/Ulaanbaatar')
| def test_properties():
| cal = FakeCalendar()
assert cal.name == 'DMY'
assert cal.tz == timezone('Asia/Ulaanbaatar')
| 09:31', tz='America/Chicago'),
pd.Timestamp('2016-12-31 16:00', tz='America/New_York'))
assert start == pd.Timestamp('2016-12-01')
assert end == pd.Timestamp('2016-12-31')
def test_properties():
| 64 | 64 | 33 | 4 | 60 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_properties | test_properties | 378 | 381 | 378 | 378 | db0ec7d1d4c33cf5619e55964fb35d26cd21f26c | bigcode/the-stack | train |
d5c7a4b7ef78c1371f48b677 | train | function | def test_ec_schedule():
mcaliepa = get_calendar("IEPA")
assert mcaliepa._EC_NOT_INITIALIZED
ours = mcaliepa.schedule(start, end)
assert mcaliepa._EC_NOT_INITIALIZED
theirs = mcaliepa.ec.schedule[["market_open", "market_close"]]
assert not mcaliepa._EC_NOT_INITIALIZED
theirs = theirs.tz_loc... | def test_ec_schedule():
| mcaliepa = get_calendar("IEPA")
assert mcaliepa._EC_NOT_INITIALIZED
ours = mcaliepa.schedule(start, end)
assert mcaliepa._EC_NOT_INITIALIZED
theirs = mcaliepa.ec.schedule[["market_open", "market_close"]]
assert not mcaliepa._EC_NOT_INITIALIZED
theirs = theirs.tz_localize(None) # our indexe... | assert not mcaliepa._EC_NOT_INITIALIZED
assert test_cal._EC_NOT_INITIALIZED
assert not hasattr(test_cal._ec, "a_test_var")
assert test_cal.ec.a_test_var == "initialized"
assert not test_cal._EC_NOT_INITIALIZED
def test_ec_schedule():
| 64 | 64 | 149 | 5 | 58 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_ec_schedule | test_ec_schedule | 943 | 954 | 943 | 943 | dd3de862dffa497d9d21686cbcf1b2a0ac9ecbbb | bigcode/the-stack | train |
c59500d659ab44fd01fffed3 | train | function | def test_special_closes_adhoc():
cal = FakeCalendar()
results = cal.schedule('2016-12-10', '2016-12-20')
closes = results['market_close'].tolist()
# confirm that 2016-12-14 is an 11:40 close not 11:49
assert pd.Timestamp('2016-12-13 11:49', tz='Asia/Ulaanbaatar').tz_convert('UTC') in closes
as... | def test_special_closes_adhoc():
| cal = FakeCalendar()
results = cal.schedule('2016-12-10', '2016-12-20')
closes = results['market_close'].tolist()
# confirm that 2016-12-14 is an 11:40 close not 11:49
assert pd.Timestamp('2016-12-13 11:49', tz='Asia/Ulaanbaatar').tz_convert('UTC') in closes
assert pd.Timestamp('2016-12-14 11:... | results['market_close'].tolist()
expected = [pd.Timestamp('2012-07-02 11:49', tz='Asia/Ulaanbaatar').tz_convert('UTC'),
pd.Timestamp('2012-07-03 11:30', tz='Asia/Ulaanbaatar').tz_convert('UTC')]
assert actual == expected
def test_special_closes_adhoc():
| 81 | 81 | 272 | 9 | 71 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_special_closes_adhoc | test_special_closes_adhoc | 721 | 736 | 721 | 721 | 86698759d3c932f36b05e51b76f6c44beb04765f | bigcode/the-stack | train |
dea580343dc7eff2938674c7 | train | class | class FakeBreakCalendar(MarketCalendar):
regular_market_times = {
"market_open": ((None, time(9, 30)),),
"market_close": ((None, time(12)),),
"break_start": ((None, time(10)),),
"break_end": ((None, time(11)),)
}
@property
def name(self):
return "BRK"
@prop... | class FakeBreakCalendar(MarketCalendar):
| regular_market_times = {
"market_open": ((None, time(9, 30)),),
"market_close": ((None, time(12)),),
"break_start": ((None, time(10)),),
"break_end": ((None, time(11)),)
}
@property
def name(self):
return "BRK"
@property
def tz(self):
return time... | 11, 30), AbstractHolidayCalendar(rules=[MonTuesThursBeforeIndependenceDay]))]
@property
def special_closes_adhoc(self):
return [(time(11, 40), ['2016-12-14'])]
class FakeBreakCalendar(MarketCalendar):
| 64 | 64 | 196 | 8 | 56 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | FakeBreakCalendar | FakeBreakCalendar | 76 | 103 | 76 | 77 | f9e69ae5c88952486a7702a279dd303033881570 | bigcode/the-stack | train |
80b9d0ac34541cff94196105 | train | function | def test_open_at_time():
cal = FakeCalendar()
schedule = cal.schedule('2014-01-01', '2016-12-31')
# regular trading day
assert cal.open_at_time(schedule, pd.Timestamp('2014-07-02 03:40', tz='UTC')) is True
# early close
assert cal.open_at_time(schedule, pd.Timestamp('2014-07-03 03:40', tz='UTC'... | def test_open_at_time():
| cal = FakeCalendar()
schedule = cal.schedule('2014-01-01', '2016-12-31')
# regular trading day
assert cal.open_at_time(schedule, pd.Timestamp('2014-07-02 03:40', tz='UTC')) is True
# early close
assert cal.open_at_time(schedule, pd.Timestamp('2014-07-03 03:40', tz='UTC')) is False
# holiday... | date
results = cal.schedule('2016-12-13', '2016-12-14')
closes = results['market_close'].tolist()
assert pd.Timestamp('2016-12-13 11:49', tz='Asia/Ulaanbaatar').tz_convert('UTC') in closes
assert pd.Timestamp('2016-12-14 11:40', tz='Asia/Ulaanbaatar').tz_convert('UTC') in closes
def test_early_closes... | 256 | 256 | 873 | 6 | 249 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_open_at_time | test_open_at_time | 756 | 805 | 756 | 756 | 06fcf31419733da1900edbfe791616943f7941a1 | bigcode/the-stack | train |
dd0ad1c43181ab2ccced26ae | train | function | def test_early_closes():
cal = FakeCalendar()
schedule = cal.schedule('2014-01-01', '2016-12-31')
results = cal.early_closes(schedule)
assert pd.Timestamp('2014-07-03') in results.index
assert pd.Timestamp('2016-12-14') in results.index
schedule = cal.schedule("1901-02-01", "1901-02-05")
a... | def test_early_closes():
| cal = FakeCalendar()
schedule = cal.schedule('2014-01-01', '2016-12-31')
results = cal.early_closes(schedule)
assert pd.Timestamp('2014-07-03') in results.index
assert pd.Timestamp('2016-12-14') in results.index
schedule = cal.schedule("1901-02-01", "1901-02-05")
assert cal.early_closes(sc... | -12-13 11:49', tz='Asia/Ulaanbaatar').tz_convert('UTC') in closes
assert pd.Timestamp('2016-12-14 11:40', tz='Asia/Ulaanbaatar').tz_convert('UTC') in closes
def test_early_closes():
| 64 | 64 | 108 | 7 | 56 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_early_closes | test_early_closes | 739 | 748 | 739 | 739 | 2b4b27012cd778936d044eeb559f0e68e97b988b | bigcode/the-stack | train |
8e58aeae9bb39afaf7a61267 | train | function | def test_mirror():
assert not hasattr(mcal_iepa, "aliases")
assert not isinstance(ecal_iepa, mcal_iepa.__class__)
assert isinstance(ecal_iepa, mcal_iepa._ec.__class__)
| def test_mirror():
| assert not hasattr(mcal_iepa, "aliases")
assert not isinstance(ecal_iepa, mcal_iepa.__class__)
assert isinstance(ecal_iepa, mcal_iepa._ec.__class__)
| def open_offset(self):
return -2
@property
def close_offset(self):
return 3
TstExchangeCalendar = type("TestExchangeCalendar", (TradingCalendar,), {'_ec_class': _TstExchangeCalendar})
test_cal = TstExchangeCalendar()
def test_mirror():
| 64 | 64 | 50 | 5 | 59 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_mirror | test_mirror | 897 | 903 | 897 | 898 | 94ff9f0fd8867813d5c2cc7ea0ed302ef255b5aa | bigcode/the-stack | train |
f5a8b2a832800307f1e0b2aa | train | function | def test_adhoc_holidays():
cal = FakeCalendar()
results = cal.schedule('2012-10-15', '2012-11-15')
days = results.index
# check adhoc holidays
# Hurricane Sandy
assert pd.Timestamp('2012-10-26') in days
assert pd.Timestamp('2012-10-29') not in days
assert pd.Timestamp('2012-10-30') not... | def test_adhoc_holidays():
| cal = FakeCalendar()
results = cal.schedule('2012-10-15', '2012-11-15')
days = results.index
# check adhoc holidays
# Hurricane Sandy
assert pd.Timestamp('2012-10-26') in days
assert pd.Timestamp('2012-10-29') not in days
assert pd.Timestamp('2012-10-30') not in days
assert pd.Time... | ') in days
assert pd.Timestamp('2016-12-26') not in days
# New Years
assert pd.Timestamp('2017-01-02') not in days
assert pd.Timestamp('2017-01-03') in days
def test_adhoc_holidays():
| 64 | 64 | 115 | 8 | 55 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_adhoc_holidays | test_adhoc_holidays | 658 | 669 | 658 | 658 | ba889ab9541a3a2c1aab1bafadab1e25a6fbd7c9 | bigcode/the-stack | train |
cbd547472ec6d5cfb18eb01e | train | function | def test_open_at_time_breaks():
cal = FakeBreakCalendar()
schedule = cal.schedule('2016-12-20', '2016-12-30')
# between open and break
assert cal.open_at_time(schedule, pd.Timestamp('2016-12-28 09:50', tz='America/New_York')) is True
# at break start
assert cal.open_at_time(schedule, pd.Timest... | def test_open_at_time_breaks():
| cal = FakeBreakCalendar()
schedule = cal.schedule('2016-12-20', '2016-12-30')
# between open and break
assert cal.open_at_time(schedule, pd.Timestamp('2016-12-28 09:50', tz='America/New_York')) is True
# at break start
assert cal.open_at_time(schedule, pd.Timestamp('2016-12-28 10:00', tz='Amer... | :00") is True
assert cal.open_at_time(schedule, "2014-07-13 06:00:00+03:00") is True
# should raise error if not all columns are in self.market_times
with pytest.raises(ValueError):
cal.open_at_time(schedule.rename(columns= {"pre": "other"}), "2014-07-02 02:55:00+00:00")
# or if the date is be... | 183 | 183 | 613 | 8 | 175 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_open_at_time_breaks | test_open_at_time_breaks | 808 | 839 | 808 | 808 | e8a6c4b621e5b7ad7f043835475b1f6d57fbb840 | bigcode/the-stack | train |
c7325e6d517aa441cc5f0858 | train | function | def test_special_closes():
cal = FakeCalendar()
results = cal.schedule('2012-07-01', '2012-07-06')
closes = results['market_close'].tolist()
# confirm that the day before July 4th is an 11:30 close not 11:49
assert pd.Timestamp('2012-07-02 11:49', tz='Asia/Ulaanbaatar').tz_convert('UTC') in closes... | def test_special_closes():
| cal = FakeCalendar()
results = cal.schedule('2012-07-01', '2012-07-06')
closes = results['market_close'].tolist()
# confirm that the day before July 4th is an 11:30 close not 11:49
assert pd.Timestamp('2012-07-02 11:49', tz='Asia/Ulaanbaatar').tz_convert('UTC') in closes
assert pd.Timestamp('2... | 20 open not 11:13
assert pd.Timestamp('2016-12-12 11:13', tz='Asia/Ulaanbaatar').tz_convert('UTC') in opens
assert pd.Timestamp('2016-12-13 11:20', tz='Asia/Ulaanbaatar').tz_convert('UTC') in opens
assert pd.Timestamp('2016-12-14 11:13', tz='Asia/Ulaanbaatar').tz_convert('UTC') in opens
def test_special_clo... | 110 | 110 | 369 | 6 | 103 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_special_closes | test_special_closes | 695 | 718 | 695 | 695 | 693eb6506ba3c9171c40f4f289b2bf3c60fd2e80 | bigcode/the-stack | train |
8f03ac29724f4bf61bbc0cb2 | train | function | def test_dunder_methods():
cal = FakeCalendar()
assert cal["market_open"] == time(11,13)
assert cal["market_open", "1900-01-01"] == time(11,18)
assert cal["market_open", "all"] == cal.regular_market_times["market_open"]
# __setitem__ is adding a time, which refuses to replace
with pytest.rais... | def test_dunder_methods():
| cal = FakeCalendar()
assert cal["market_open"] == time(11,13)
assert cal["market_open", "1900-01-01"] == time(11,18)
assert cal["market_open", "all"] == cal.regular_market_times["market_open"]
# __setitem__ is adding a time, which refuses to replace
with pytest.raises(AssertionError):
... | .is_custom("other_test")
# wrong formats
with pytest.raises(AssertionError):
cal.add_time("wrong_format", (-1, time(10)))
with pytest.raises(AssertionError):
cal.add_time("wrong_format", pd.Timedelta("5H"))
def test_dunder_methods():
| 63 | 64 | 147 | 6 | 57 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_dunder_methods | test_dunder_methods | 249 | 264 | 249 | 249 | 1286aa4432e31d8775372051d04443e4e23507a4 | bigcode/the-stack | train |
bb4c05b7ad21a90893f61b6b | train | function | def test_special_dates():
cal = FakeCalendar()
special = cal.special_dates("market_open", "2016-12-10", "2016-12-31")
assert special.astype(str).tolist() == ["2016-12-13 03:20:00+00:00"]
special = cal.special_dates("market_open", "2016-12-10", "2016-12-31", filter_holidays= False)
assert special.a... | def test_special_dates():
| cal = FakeCalendar()
special = cal.special_dates("market_open", "2016-12-10", "2016-12-31")
assert special.astype(str).tolist() == ["2016-12-13 03:20:00+00:00"]
special = cal.special_dates("market_open", "2016-12-10", "2016-12-31", filter_holidays= False)
assert special.astype(str).tolist() == ["2... |
cal.change_time("market_open", (time(10), -1))
cal.change_time("market_close", (time(10), 5))
assert cal.get_offset("market_open") == -1
assert cal.get_offset("market_close") == 5
def test_special_dates():
| 64 | 64 | 141 | 5 | 58 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_special_dates | test_special_dates | 179 | 186 | 179 | 179 | 9870549664b5ae17f43887849bad7a9647dcef42 | bigcode/the-stack | train |
f07e0a667ae870868fa00575 | train | function | def test_schedule_w_breaks():
cal = FakeBreakCalendar()
assert cal.open_time == time(9, 30)
assert cal.close_time == time(12, 00)
assert cal.break_start == time(10, 00)
assert cal.break_end == time(11, 00)
expected = pd.DataFrame({'market_open': [pd.Timestamp('2016-12-01 14:30:00', tz='UTC'),
... | def test_schedule_w_breaks():
| cal = FakeBreakCalendar()
assert cal.open_time == time(9, 30)
assert cal.close_time == time(12, 00)
assert cal.break_start == time(10, 00)
assert cal.break_end == time(11, 00)
expected = pd.DataFrame({'market_open': [pd.Timestamp('2016-12-01 14:30:00', tz='UTC'),
... | -12-23", "2016-12-31", force_special_times= None)
assert schedule.columns.tolist() == ["market_open", "break_start", "break_end", "market_close"]
# special market_open should NOT take effect anywhere
assert schedule.loc["2016-12-29"].astype(str).to_list() == ["2016-12-29 14:30:00+00:00",
... | 255 | 256 | 1,098 | 7 | 248 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_schedule_w_breaks | test_schedule_w_breaks | 546 | 612 | 546 | 546 | bf31f010db944492a81c81470afc544c32c381fc | bigcode/the-stack | train |
0e50b67ed4b801bf89584046 | train | function | def test_schedule():
cal = FakeCalendar()
assert cal.open_time == time(11, 13)
assert cal.close_time == time(11, 49)
expected = pd.DataFrame({'market_open': [pd.Timestamp('2016-12-01 03:13:00', tz='UTC'),
pd.Timestamp('2016-12-02 03:13:00', tz='UTC')],
... | def test_schedule():
| cal = FakeCalendar()
assert cal.open_time == time(11, 13)
assert cal.close_time == time(11, 49)
expected = pd.DataFrame({'market_open': [pd.Timestamp('2016-12-01 03:13:00', tz='UTC'),
pd.Timestamp('2016-12-02 03:13:00', tz='UTC')],
... | assert end == pd.Timestamp('2016-12-31')
def test_properties():
cal = FakeCalendar()
assert cal.name == 'DMY'
assert cal.tz == timezone('Asia/Ulaanbaatar')
def test_holidays():
cal = FakeCalendar()
actual = cal.holidays().holidays
assert pd.Timestamp('2016-12-26') in actual
assert pd.T... | 256 | 256 | 860 | 4 | 252 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_schedule | test_schedule | 404 | 464 | 404 | 404 | abc47a974d54ac7ce676f896aad1a4c4a64073b2 | bigcode/the-stack | train |
35de045bb1a2aaace8bc0d40 | train | function | def test_valid_dates():
cal = FakeCalendar()
expected = pd.DatetimeIndex([pd.Timestamp(x, tz='UTC') for x in ['2016-12-23', '2016-12-27', '2016-12-28',
'2016-12-29', '2016-12-30', '2017-01-03']])
actual = cal.valid_days('2016-12-23', '201... | def test_valid_dates():
| cal = FakeCalendar()
expected = pd.DatetimeIndex([pd.Timestamp(x, tz='UTC') for x in ['2016-12-23', '2016-12-27', '2016-12-28',
'2016-12-29', '2016-12-30', '2017-01-03']])
actual = cal.valid_days('2016-12-23', '2017-01-03')
assert_ind... | assert pd.Timestamp('2012-01-02') in actual
assert pd.Timestamp('2012-12-25') in actual
assert pd.Timestamp('2012-10-29') in actual
assert pd.Timestamp('2012-10-30') in actual
def test_valid_dates():
| 64 | 64 | 110 | 5 | 58 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_valid_dates | test_valid_dates | 395 | 401 | 395 | 395 | 7b5469046357377bdf2540e131c94987a8462b3b | bigcode/the-stack | train |
5d110baeaf361614cbef0b05 | train | function | def test_basic_information():
assert mcal_iepa._EC_NOT_INITIALIZED
assert mcal_iepa.tz == timezone("America/New_York") == ecal_iepa.tz
assert mcal_iepa.open_offset == -1 == ecal_iepa.open_offset
assert mcal_iepa.open_time == time(20)
assert mcal_iepa.close_time == time(18)
assert test_cal._EC_... | def test_basic_information():
| assert mcal_iepa._EC_NOT_INITIALIZED
assert mcal_iepa.tz == timezone("America/New_York") == ecal_iepa.tz
assert mcal_iepa.open_offset == -1 == ecal_iepa.open_offset
assert mcal_iepa.open_time == time(20)
assert mcal_iepa.close_time == time(18)
assert test_cal._EC_NOT_INITIALIZED
assert test... | })
test_cal = TstExchangeCalendar()
def test_mirror():
assert not hasattr(mcal_iepa, "aliases")
assert not isinstance(ecal_iepa, mcal_iepa.__class__)
assert isinstance(ecal_iepa, mcal_iepa._ec.__class__)
def test_basic_information():
| 64 | 64 | 149 | 5 | 59 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_basic_information | test_basic_information | 905 | 917 | 905 | 906 | fa47152a299327c9b4c1df83a5eb581074cee800 | bigcode/the-stack | train |
60ea3024eb8089b70b0e5139 | train | function | def test_get_offset():
cal = FakeBreakCalendar()
assert cal.open_offset == 0
assert cal.close_offset == 0
cal.change_time("market_open", (time(10), -1))
cal.change_time("market_close", (time(10), 5))
assert cal.get_offset("market_open") == -1
assert cal.get_offset("market_close") == 5
| def test_get_offset():
| cal = FakeBreakCalendar()
assert cal.open_offset == 0
assert cal.close_offset == 0
cal.change_time("market_open", (time(10), -1))
cal.change_time("market_close", (time(10), 5))
assert cal.get_offset("market_open") == -1
assert cal.get_offset("market_close") == 5
| "1900-01-01") is None
cal.remove_time("market_open")
with pytest.raises(NotImplementedError):
t = cal.open_time
with pytest.raises(KeyError):
t = cal.get_time_on("pre", "1900-01-01")
def test_get_offset():
| 64 | 64 | 88 | 5 | 59 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_get_offset | test_get_offset | 167 | 177 | 167 | 167 | e264f400f50f46f45215cd784c8903a1bf1700be | bigcode/the-stack | train |
c4d880990fc8e616df3cd735 | train | function | def test_late_opens():
cal = FakeCalendar()
schedule = cal.schedule("1902-03-01", "1902-03-06")
assert cal.late_opens(schedule).empty
| def test_late_opens():
| cal = FakeCalendar()
schedule = cal.schedule("1902-03-01", "1902-03-06")
assert cal.late_opens(schedule).empty
| -07-03') in results.index
assert pd.Timestamp('2016-12-14') in results.index
schedule = cal.schedule("1901-02-01", "1901-02-05")
assert cal.early_closes(schedule).empty
def test_late_opens():
| 64 | 64 | 45 | 7 | 56 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_late_opens | test_late_opens | 750 | 753 | 750 | 750 | f49e1ff1f652a058ddc489ec06e5471d38c6e5f7 | bigcode/the-stack | train |
312652e172a1ca74b4cf6ada | train | function | def test_default_calendars():
for name in get_calendar_names():
if name == "XKRX":
with pytest.warns(UserWarning):
assert get_calendar(name) is not None
else:
assert get_calendar(name) is not None
| def test_default_calendars():
| for name in get_calendar_names():
if name == "XKRX":
with pytest.warns(UserWarning):
assert get_calendar(name) is not None
else:
assert get_calendar(name) is not None
| AssertionError):
cal["market_open"] = time(10)
# but excplicitly deleting, makes it work
del cal["market_open"]
cal["market_open"] = time(9)
assert cal["market_open"] == time(9)
def test_default_calendars():
| 64 | 64 | 55 | 7 | 57 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_default_calendars | test_default_calendars | 268 | 274 | 268 | 268 | 42fcf7174a49268b57dadd265af4d7e76300c504 | bigcode/the-stack | train |
f01eb0833ea085c566e9b541 | train | function | def test_days_at_time():
class New_York(FakeCalendar):
@property
def tz(self): return timezone('America/New_York')
new_york = New_York()
new_york.change_time("market_open", time(12))
new_york.change_time("market_close", time(13))
class Chicago(FakeCalendar):
@property
... | def test_days_at_time():
| class New_York(FakeCalendar):
@property
def tz(self): return timezone('America/New_York')
new_york = New_York()
new_york.change_time("market_open", time(12))
new_york.change_time("market_close", time(13))
class Chicago(FakeCalendar):
@property
def tz(self): return ti... | AssertionError):
cal.add_time("wrong_format", pd.Timedelta("5H"))
def test_dunder_methods():
cal = FakeCalendar()
assert cal["market_open"] == time(11,13)
assert cal["market_open", "1900-01-01"] == time(11,18)
assert cal["market_open", "all"] == cal.regular_market_times["market_open"]
#... | 227 | 227 | 758 | 6 | 220 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_days_at_time | test_days_at_time | 277 | 353 | 277 | 277 | af8045e303eddd9f9857588262b44f47215e7e98 | bigcode/the-stack | train |
f84ffcf6ebd5a5bfda825577 | train | function | def test_get_time():
cal = FakeCalendar()
assert cal.get_time("market_open") == time(11, 13)
assert cal.get_time("break_start") is None
assert cal.get_time("break_end") is None
assert cal.get_time_on("market_close", "1900-01-01") == time(11, 45)
assert cal.get_time_on("break_start", "1900-01-0... | def test_get_time():
| cal = FakeCalendar()
assert cal.get_time("market_open") == time(11, 13)
assert cal.get_time("break_start") is None
assert cal.get_time("break_end") is None
assert cal.get_time_on("market_close", "1900-01-01") == time(11, 45)
assert cal.get_time_on("break_start", "1900-01-01") is None
cal.... | )
# class
pickled = pickle.dumps(Cal)
unpickled = pickle.loads(pickled)
assert Cal.regular_market_times == unpickled.regular_market_times
test_protected_dictionary(Cal)
test_protected_dictionary(unpickled)
def test_get_time():
| 63 | 64 | 147 | 5 | 58 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_get_time | test_get_time | 150 | 165 | 150 | 150 | 36297f26581dd65699219f2aaf515037f07106f5 | bigcode/the-stack | train |
588cb8044adb9557cadccb69 | train | function | def test_change_add_remove_time():
cal = FakeCalendar()
assert not cal.has_discontinued
assert not cal.has_custom
# change/add using the different formats that are supported
cal.change_time("market_open", time(12))
cal.add_time("test_time", (None, time(12)))
cal.add_time("other_test", ((No... | def test_change_add_remove_time():
| cal = FakeCalendar()
assert not cal.has_discontinued
assert not cal.has_custom
# change/add using the different formats that are supported
cal.change_time("market_open", time(12))
cal.add_time("test_time", (None, time(12)))
cal.add_time("other_test", ((None, time(12)),))
assert cal.ope... | cal.get_offset("market_close") == 5
def test_special_dates():
cal = FakeCalendar()
special = cal.special_dates("market_open", "2016-12-10", "2016-12-31")
assert special.astype(str).tolist() == ["2016-12-13 03:20:00+00:00"]
special = cal.special_dates("market_open", "2016-12-10", "2016-12-31", filter... | 159 | 160 | 534 | 7 | 152 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_change_add_remove_time | test_change_add_remove_time | 189 | 246 | 189 | 189 | 63e81712e5deb8935e99baf3a1039264dfb67f7b | bigcode/the-stack | train |
fe000f00d5f122936f019526 | train | function | def test_ec_property():
mcaliepa = get_calendar("IEPA")
assert mcaliepa._EC_NOT_INITIALIZED
ec = mcaliepa.ec
assert not mcaliepa._EC_NOT_INITIALIZED
assert test_cal._EC_NOT_INITIALIZED
assert not hasattr(test_cal._ec, "a_test_var")
assert test_cal.ec.a_test_var == "initialized"
assert ... | def test_ec_property():
| mcaliepa = get_calendar("IEPA")
assert mcaliepa._EC_NOT_INITIALIZED
ec = mcaliepa.ec
assert not mcaliepa._EC_NOT_INITIALIZED
assert test_cal._EC_NOT_INITIALIZED
assert not hasattr(test_cal._ec, "a_test_var")
assert test_cal.ec.a_test_var == "initialized"
assert not test_cal._EC_NOT_INI... | assert (one.values == two.values).all()
def test_closes_opens():
sched = mcal_iepa.schedule(start, end)
assert_same(ecal_iepa._closes, sched.market_close)
assert_same(ecal_iepa._opens, sched.market_open)
def test_ec_property():
| 64 | 64 | 98 | 5 | 59 | mhoene/pandas_market_calendars | tests/test_market_calendar.py | Python | test_ec_property | test_ec_property | 930 | 940 | 930 | 930 | 22766f1871d5fc954c1703700e4e9a59e43eaf49 | bigcode/the-stack | train |
9ba0b2e88bb87737fe49922e | train | function | def test_alpn_select_callback():
ctx = SSL.Context(SSL.SSLv23_METHOD)
conn = SSL.Connection(ctx)
conn.set_app_data(tlsconfig.AppData(server_alpn=b"h2", http2=True))
# Test that we try to mirror the server connection's ALPN
assert tlsconfig.alpn_select_callback(conn, [b"http/1.1", b"qux", b"h2"]) ==... | def test_alpn_select_callback():
| ctx = SSL.Context(SSL.SSLv23_METHOD)
conn = SSL.Connection(ctx)
conn.set_app_data(tlsconfig.AppData(server_alpn=b"h2", http2=True))
# Test that we try to mirror the server connection's ALPN
assert tlsconfig.alpn_select_callback(conn, [b"http/1.1", b"qux", b"h2"]) == b"h2"
# Test that we respec... |
from OpenSSL import SSL
from mitmproxy import certs
from mitmproxy.addons import tlsconfig
from mitmproxy.proxy import context
from mitmproxy.proxy.layers import tls
from mitmproxy.test import taddons
from test.mitmproxy.proxy.layers import test_tls
def test_alpn_select_callback():
| 69 | 69 | 230 | 7 | 61 | chenzhenguo/mitmproxy | test/mitmproxy/addons/test_tlsconfig.py | Python | test_alpn_select_callback | test_alpn_select_callback | 17 | 31 | 17 | 17 | b2954738cd0b8d0069629a0b45458b8e18396c1e | bigcode/the-stack | train |
74c641e8e0049f18e4f56482 | train | class | class TestTlsConfig:
def test_configure(self, tdata):
ta = tlsconfig.TlsConfig()
with taddons.context(ta) as tctx:
with pytest.raises(Exception, match="file does not exist"):
tctx.configure(ta, certs=["*=nonexistent"])
with pytest.raises(Exception, match="Inv... | class TestTlsConfig:
| def test_configure(self, tdata):
ta = tlsconfig.TlsConfig()
with taddons.context(ta) as tctx:
with pytest.raises(Exception, match="file does not exist"):
tctx.configure(ta, certs=["*=nonexistent"])
with pytest.raises(Exception, match="Invalid certificate form... | addons
from test.mitmproxy.proxy.layers import test_tls
def test_alpn_select_callback():
ctx = SSL.Context(SSL.SSLv23_METHOD)
conn = SSL.Connection(ctx)
conn.set_app_data(tlsconfig.AppData(server_alpn=b"h2", http2=True))
# Test that we try to mirror the server connection's ALPN
assert tlsconfig.a... | 256 | 256 | 2,169 | 5 | 250 | chenzhenguo/mitmproxy | test/mitmproxy/addons/test_tlsconfig.py | Python | TestTlsConfig | TestTlsConfig | 37 | 228 | 37 | 37 | 0d6e9b29a5977464dfcecc0f05bf0eb31be60416 | bigcode/the-stack | train |
dba912af5a394f3ddd58349c | train | function | def training_parameters(blob_model_info):
"""
Define json training parameters for single structure predictor
:param blob_model_info: model info
:type blob_model_info: dict
:return: training parameters
:rtype: dict
"""
return {
'method': blob_model_info['ModelCode'],
'fi... | def training_parameters(blob_model_info):
| """
Define json training parameters for single structure predictor
:param blob_model_info: model info
:type blob_model_info: dict
:return: training parameters
:rtype: dict
"""
return {
'method': blob_model_info['ModelCode'],
'fingerprints': blob_model_info['Fingerprints... | units
:type units: str
:return: property units or None if units == UNITLESS
:rtype: str
"""
corrected_units = None
if units != UNITLESS:
corrected_units = units
return corrected_units
def training_parameters(blob_model_info):
| 64 | 64 | 167 | 7 | 56 | ArqiSoft/ml-services | Source/osdr_ml_predictor/single_structure_predictor.py | Python | training_parameters | training_parameters | 359 | 379 | 359 | 359 | 01f7ee6398e5f1162dd494b68fe14213d4f525b9 | bigcode/the-stack | train |
068376e57fb2ce5a84cd154f | train | function | def dataset(blob_model_info):
"""
Define json dataset parameters for single structure predictor
:param blob_model_info: model info
:type blob_model_info: dict
:return: dataset parameters
:rtype: dict
"""
if 'Description' in blob_model_info['Dataset'].keys():
description = blob_... | def dataset(blob_model_info):
| """
Define json dataset parameters for single structure predictor
:param blob_model_info: model info
:type blob_model_info: dict
:return: dataset parameters
:rtype: dict
"""
if 'Description' in blob_model_info['Dataset'].keys():
description = blob_model_info['Dataset']['Descrip... | result(prediction):
"""
Define json prediction results for single structure predictor
:param prediction: structure prediction
:return: prediction results
:rtype: dict
"""
return {
'value': float(prediction[0][2][2])
}
def dataset(blob_model_info):
| 64 | 64 | 130 | 6 | 58 | ArqiSoft/ml-services | Source/osdr_ml_predictor/single_structure_predictor.py | Python | dataset | dataset | 300 | 320 | 300 | 300 | 1eadd94daaaf896ddfa2d3004a095228aa4cc1ef | bigcode/the-stack | train |
0fda8534ac5dfa6af7147381 | train | function | def consensus(models_data):
"""
Define consensus results for single structure predictor.
Set consensus value, mean average value of all predictions
Set consensus units, same as first model units using for prediction,
or remove units key
:param models_data: all predicted property models data
... | def consensus(models_data):
| """
Define consensus results for single structure predictor.
Set consensus value, mean average value of all predictions
Set consensus units, same as first model units using for prediction,
or remove units key
:param models_data: all predicted property models data
:type models_data: list
... | # send (publish) properties predicted message to OSDR
prediction_created_event = single_structure_property_predicted(body)
properties_predicted_publisher = PurePublisher(
SINGLE_STRUCTURE_PREDICTED)
properties_predicted_publisher.publish(prediction_created_event)
return None
def consensus(mode... | 64 | 64 | 205 | 5 | 58 | ArqiSoft/ml-services | Source/osdr_ml_predictor/single_structure_predictor.py | Python | consensus | consensus | 164 | 197 | 164 | 164 | c1f8ee9feea5d460c8b39c18b041a988eeb9d753 | bigcode/the-stack | train |
020b166edd712a7741599a97 | train | function | @MLExceptionHandler(logger=LOGGER)
def callback(body):
"""
Pika callback function used by single structure predictor.
Make list of json with prediction data for each model prediction.
:param body: RabbitMQ MT message's body
"""
# start total prediction time counter
start_prediction_total =... | @MLExceptionHandler(logger=LOGGER)
def callback(body):
| """
Pika callback function used by single structure predictor.
Make list of json with prediction data for each model prediction.
:param body: RabbitMQ MT message's body
"""
# start total prediction time counter
start_prediction_total = time()
models_data = []
oauth = get_oauth()
... | MLLogger import BaseMLLogger
from exception_handler import MLExceptionHandler
from general_helper import (
get_model_info, get_oauth, fetch_token, prepare_prediction_parameters,
molecules_from_mol_strings, logging_exception_message, cache_model,
molecules_from_smiles, prepare_prediction_files, MODELS_IN_ME... | 256 | 256 | 984 | 12 | 244 | ArqiSoft/ml-services | Source/osdr_ml_predictor/single_structure_predictor.py | Python | callback | callback | 33 | 161 | 33 | 34 | ec30eaa622dd8c717b946eef03a7d8bc9df62a49 | bigcode/the-stack | train |
ef00a363abdf1268cbac18eb | train | function | def property_parameters(blob_model_info):
"""
Define json property parameters for single structure predictor
:param blob_model_info: model info
:type blob_model_info: dict
:return: property parameters
:rtype: dict
"""
return {
'category': blob_model_info['Property']['Category']... | def property_parameters(blob_model_info):
| """
Define json property parameters for single structure predictor
:param blob_model_info: model info
:type blob_model_info: dict
:return: property parameters
:rtype: dict
"""
return {
'category': blob_model_info['Property']['Category'],
'name': blob_model_info['Propert... | Dataset']['Description']
elif 'DatasetDescription' in blob_model_info.keys():
description = blob_model_info['DatasetDescription']
else:
description = None
return {
'title': blob_model_info['Dataset']['Title'],
'description': description
}
def property_parameters(blob_mod... | 64 | 64 | 108 | 7 | 57 | ArqiSoft/ml-services | Source/osdr_ml_predictor/single_structure_predictor.py | Python | property_parameters | property_parameters | 323 | 338 | 323 | 323 | e0d65dfdc4f1bcee301a305cc6c21cfd82fa85a8 | bigcode/the-stack | train |
9280dc3a44c542203a28cf12 | train | function | def error(exception_message):
"""
Define json prediction error for single structure predictor
:param exception_message: single structure prediction error message
:type exception_message: str
:return: prediction error
:rtype: dict
"""
return {
'error': exception_message
}
| def error(exception_message):
| """
Define json prediction error for single structure predictor
:param exception_message: single structure prediction error message
:type exception_message: str
:return: prediction error
:rtype: dict
"""
return {
'error': exception_message
}
| _buckets = []
for model_ids in body['Models']:
model_id.append(model_ids['Id'])
models_blob_ids.append(model_ids['Blob']['id'])
models_buckets.append(model_ids['Blob']['bucket'])
return model_id, models_blob_ids, models_buckets
def error(exception_message):
| 64 | 64 | 64 | 5 | 58 | ArqiSoft/ml-services | Source/osdr_ml_predictor/single_structure_predictor.py | Python | error | error | 271 | 283 | 271 | 271 | 9568d7de63d86121952de16b7b6ad929fb1a15c0 | bigcode/the-stack | train |
cfbb60af4391d98e51b102a7 | train | function | def applicability_domain(prediction):
"""
Define json applicability domain parameters for single structure predictor
:param prediction: structure prediction
:return: applicability domain parameters
:rtype: dict
"""
return {
'distance': prediction[0][3][2],
'density': predic... | def applicability_domain(prediction):
| """
Define json applicability domain parameters for single structure predictor
:param prediction: structure prediction
:return: applicability domain parameters
:rtype: dict
"""
return {
'distance': prediction[0][3][2],
'density': prediction[0][4][2],
}
| ['KFold'],
'testDatasetSize': blob_model_info['TestDatasetSize'],
'subSampleSize': blob_model_info['SubSampleSize'],
'className': blob_model_info['ClassName'],
'modi': blob_model_info['Modi']
}
def applicability_domain(prediction):
| 64 | 64 | 72 | 6 | 58 | ArqiSoft/ml-services | Source/osdr_ml_predictor/single_structure_predictor.py | Python | applicability_domain | applicability_domain | 382 | 394 | 382 | 382 | 6b8128d30e9a8942058fc56265f1c9f373db501b | bigcode/the-stack | train |
0d6a1b4a57bc782aee8a636c | train | function | def correct_units(units):
"""
Method to correct property units. If property have UNITLESS units,
set units to None
:param units: property units
:type units: str
:return: property units or None if units == UNITLESS
:rtype: str
"""
corrected_units = None
if units != UNITLESS:
... | def correct_units(units):
| """
Method to correct property units. If property have UNITLESS units,
set units to None
:param units: property units
:type units: str
:return: property units or None if units == UNITLESS
:rtype: str
"""
corrected_units = None
if units != UNITLESS:
corrected_units = uni... |
"""
return {
'category': blob_model_info['Property']['Category'],
'name': blob_model_info['Property']['Name'],
'units': correct_units(blob_model_info['Property']['Units']),
'description': blob_model_info['Property']['Description']
}
def correct_units(units):
| 64 | 64 | 92 | 6 | 58 | ArqiSoft/ml-services | Source/osdr_ml_predictor/single_structure_predictor.py | Python | correct_units | correct_units | 341 | 356 | 341 | 341 | e85ddd936320e8b94a0c0987606ae2e44413d459 | bigcode/the-stack | train |
1be373facc0c6ca38202d48e | train | function | def preload_ssp_models():
"""
Method to preload all SSP models to memory, model should have SSP target.
Using to spped up predictions later
Add preloaded SSP models to MODELS_IN_MEMORY_CACHE general_helper.py module
"""
oauth = get_oauth()
# set default GET request header and parameters va... | def preload_ssp_models():
| """
Method to preload all SSP models to memory, model should have SSP target.
Using to spped up predictions later
Add preloaded SSP models to MODELS_IN_MEMORY_CACHE general_helper.py module
"""
oauth = get_oauth()
# set default GET request header and parameters values
headers = {
... | for model_data in models_data:
if 'result' in model_data.keys():
consensus_value += float(model_data['result']['value'])
counter += 1
if counter != 0:
consensus_value = consensus_value / counter
else:
return None
consensus_data = {
'value': str(cons... | 112 | 112 | 375 | 6 | 105 | ArqiSoft/ml-services | Source/osdr_ml_predictor/single_structure_predictor.py | Python | preload_ssp_models | preload_ssp_models | 200 | 246 | 200 | 200 | 078b969b734dea79131501c82daeb51154cd145d | bigcode/the-stack | train |
2698780544828724b2d5502d | train | function | def get_models_from_body_message(body):
"""
Method to get model id, model blob id, model bucket from input rabbitmq
message.
:param body: rabbitmq message body
:type body: dict
:return: models ids, models blob ids, models, buckets
"""
model_id = []
models_blob_ids = []
models_b... | def get_models_from_body_message(body):
| """
Method to get model id, model blob id, model bucket from input rabbitmq
message.
:param body: rabbitmq message body
:type body: dict
:return: models ids, models blob ids, models, buckets
"""
model_id = []
models_blob_ids = []
models_buckets = []
for model_ids in body['... | :
MODELS_IN_MEMORY_CACHE[model_blob_id] = cache_model(
prediction_parameters['ModelsFolder'])
except FileNotFoundError:
LOGGER.error(
'Cant preload SSP model with blob id: {}'.format(
model_blob_id
... | 64 | 64 | 137 | 8 | 56 | ArqiSoft/ml-services | Source/osdr_ml_predictor/single_structure_predictor.py | Python | get_models_from_body_message | get_models_from_body_message | 249 | 268 | 249 | 249 | 06fae1a4aff464477649c8844be549ab5f3b200e | bigcode/the-stack | train |
a5dce220cab982a7fbba78e0 | train | function | def format_predicted_value(value):
"""
Method to format predicted value. Currently useless
:param value: predicted value
:type value: float
:return: formatted prediction value
:rtype: str
"""
return str(value)
| def format_predicted_value(value):
| """
Method to format predicted value. Currently useless
:param value: predicted value
:type value: float
:return: formatted prediction value
:rtype: str
"""
return str(value)
| single structure predictor
:param prediction: structure prediction
:return: applicability domain parameters
:rtype: dict
"""
return {
'distance': prediction[0][3][2],
'density': prediction[0][4][2],
}
def format_predicted_value(value):
| 64 | 64 | 55 | 7 | 57 | ArqiSoft/ml-services | Source/osdr_ml_predictor/single_structure_predictor.py | Python | format_predicted_value | format_predicted_value | 397 | 407 | 397 | 397 | ebe25e582e8ab31522824215dceb681a873ae7ec | bigcode/the-stack | train |
41735269c1cecb5e3891591a | train | function | def result(prediction):
"""
Define json prediction results for single structure predictor
:param prediction: structure prediction
:return: prediction results
:rtype: dict
"""
return {
'value': float(prediction[0][2][2])
}
| def result(prediction):
| """
Define json prediction results for single structure predictor
:param prediction: structure prediction
:return: prediction results
:rtype: dict
"""
return {
'value': float(prediction[0][2][2])
}
| """
Define json prediction error for single structure predictor
:param exception_message: single structure prediction error message
:type exception_message: str
:return: prediction error
:rtype: dict
"""
return {
'error': exception_message
}
def result(prediction):
| 64 | 64 | 59 | 5 | 59 | ArqiSoft/ml-services | Source/osdr_ml_predictor/single_structure_predictor.py | Python | result | result | 286 | 297 | 286 | 286 | 7dfa401611f9cc334824e5136bc7b269477da31c | bigcode/the-stack | train |
4ecb134075cc8be645d8a018 | train | class | class Migration(migrations.Migration):
dependencies = [
('visualization', '0004_search_data_pic_type'),
]
operations = [
migrations.AddField(
model_name='search_data',
name='id_in_dashboard',
field=models.BooleanField(default=False),
),
]
| class Migration(migrations.Migration):
| dependencies = [
('visualization', '0004_search_data_pic_type'),
]
operations = [
migrations.AddField(
model_name='search_data',
name='id_in_dashboard',
field=models.BooleanField(default=False),
),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
| 31 | 64 | 61 | 7 | 23 | Madongming/admin | visualization/migrations/0005_search_data_id_in_dashboard.py | Python | Migration | Migration | 7 | 19 | 7 | 8 | a70a2b25e4bbfe0490f67aaa77c00b3486a69378 | bigcode/the-stack | train |
0af92d486e79099d57dd61f8 | train | class | class Templates:
"""Helper methods to build BGP policies"""
def __init__(self, local_as):
"""Use init as a base for BGP config"""
self.root = xml.Element("config")
self.root.set("xmlns", "urn:ietf:params:xml:ns:netconf:base:1.0")
self.root.set("xmlns:xc", "urn:ietf:para... | class Templates:
| """Helper methods to build BGP policies"""
def __init__(self, local_as):
"""Use init as a base for BGP config"""
self.root = xml.Element("config")
self.root.set("xmlns", "urn:ietf:params:xml:ns:netconf:base:1.0")
self.root.set("xmlns:xc", "urn:ietf:params:xml:ns:netconf:... | """Helper class to create configuration using ios-xe-native YANG model"""
import xml.etree.cElementTree as xml
class Templates:
| 28 | 241 | 804 | 3 | 24 | cober2019/IOS-XE-Ops | app/Modules/bgp_build.py | Python | Templates | Templates | 6 | 81 | 6 | 6 | 36b4f97802b3445c0d4bc319b69226204d21bbc4 | bigcode/the-stack | train |
43ae517e8287ef43adef8783 | train | class | class TestInputTeam(unittest.TestCase):
"""InputTeam unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testInputTeam(self):
"""Test InputTeam"""
# FIXME: construct object with mandatory attributes with example values
# model = cons3rt.models... | class TestInputTeam(unittest.TestCase):
| """InputTeam unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testInputTeam(self):
"""Test InputTeam"""
# FIXME: construct object with mandatory attributes with example values
# model = cons3rt.models.input_team.InputTeam() # noqa: E501
... | .com
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import cons3rt
from cons3rt.models.input_team import InputTeam # noqa: E501
from cons3rt.rest import ApiException
class TestInputTeam(unittest.TestCase):
| 64 | 64 | 84 | 8 | 55 | cons3rt/cons3rt-python-sdk | test/test_input_team.py | Python | TestInputTeam | TestInputTeam | 23 | 36 | 23 | 23 | c01cb9a16598049c96e86cfbc1abf88b4d25b3b2 | bigcode/the-stack | train |
bacbbfe52d541d77c6624296 | train | function | def main():
# The calculation of the boundaries of priori interval of uncertainty
# (Определение границ априорного интервала неопределенности)
p = PolynomMethods()
p.coefficients = p.coefficients_input(POLYNOM)
p.polynom = np.poly1d(p.coefficients)
segment = p.segment_calculation(32)
if not ... | def main():
# The calculation of the boundaries of priori interval of uncertainty
# (Определение границ априорного интервала неопределенности)
| p = PolynomMethods()
p.coefficients = p.coefficients_input(POLYNOM)
p.polynom = np.poly1d(p.coefficients)
segment = p.segment_calculation(32)
if not segment:
print('The function is non-unimodal (Функция неунимодальна).')
exit(0)
print('A priori segment of uncertainty '
... | ) / 4
x1 = x0 - h
x2 = x0
x3 = x0 + h
y1, y2, y3 = f(x1), f(x2), f(x3)
xmin = 0.5 * ((x2 * x2 - x3 * x3) * f(x1) + (x3 * x3 - x1 * x1) *
f(x2) + (x1 * x1 - x2 * x2) * f(x3)) / \
((x2 - x3) * f(x1) + (x3 - x1) * f(x2... | 206 | 206 | 687 | 34 | 171 | Gr33nMax/first_order_optimization_methods | finding_minimum.py | Python | main | main | 300 | 349 | 300 | 302 | 08a6520a4037cdc2ce3fbcbe9b27fe1df9fb60e8 | bigcode/the-stack | train |
de46f07136f76c0d6ea2c631 | train | class | class PolynomMethods:
@staticmethod
def f(t: float) -> float:
"""
Calculating the value of a polynomial 'p' at point t
Вычисление значения многочлена 'p' в точке t
"""
p = PolynomMethods.coefficients_input(POLYNOM)
return np.polyval(p, t)
@staticmethod
de... | class PolynomMethods:
@staticmethod
| def f(t: float) -> float:
"""
Calculating the value of a polynomial 'p' at point t
Вычисление значения многочлена 'p' в точке t
"""
p = PolynomMethods.coefficients_input(POLYNOM)
return np.polyval(p, t)
@staticmethod
def segment_calculation(n: int = 32) -> tu... | orenko Maxim
# Автор: Сидоренко Максим
# vk.com/maksim2009rus
# -----------------------------------------------------------
# Search for a priori segment of uncertainty,
# implementation of methods of division of the segment in half,
# the Golden ratio
# to find the minimum given as a polynomial function
# ------------... | 255 | 256 | 2,535 | 9 | 246 | Gr33nMax/first_order_optimization_methods | finding_minimum.py | Python | PolynomMethods | PolynomMethods | 33 | 297 | 33 | 34 | 26308f93164bc9440c26de20efffffe82499516a | bigcode/the-stack | train |
f6f4fa7876090d340d2995a7 | train | class | class ROIAlign(nn.Module):
def __init__(self, output_size, spatial_scale, sampling_ratio):
super(ROIAlign, self).__init__()
self.output_size = output_size
self.spatial_scale = spatial_scale
self.sampling_ratio = sampling_ratio
# @amp.float_function
def forward(self, input, r... | class ROIAlign(nn.Module):
| def __init__(self, output_size, spatial_scale, sampling_ratio):
super(ROIAlign, self).__init__()
self.output_size = output_size
self.spatial_scale = spatial_scale
self.sampling_ratio = sampling_ratio
# @amp.float_function
def forward(self, input, rois):
return roi_al... | rois,
spatial_scale,
output_size[0],
output_size[1],
bs,
ch,
h,
w,
sampling_ratio,
)
return grad_input, None, None, None, None
roi_align = _ROIAlign.apply
class ROIAlign(nn.Module):
| 64 | 64 | 177 | 6 | 57 | Chillee/benchmark | torchbenchmark/models/maskrcnn_benchmark/maskrcnn_benchmark/layers/roi_align.py | Python | ROIAlign | ROIAlign | 50 | 69 | 50 | 50 | 312ab6f1e25ca55bfc1c3771a0a3c577d1c9403a | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.