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
8fb73aae1cd06081a801a5cd
train
class
class TestSetup(object): """Requests test cases.""" # It goes to eleven. _multiprocess_can_split_ = True def setUp(self): global _httpbin if (not 'HTTPBIN_URL' in os.environ) and not _httpbin: # c = envoy.connect('httpbin %s' % (PORT)) # time.sleep(1) ...
class TestSetup(object):
"""Requests test cases.""" # It goes to eleven. _multiprocess_can_split_ = True def setUp(self): global _httpbin if (not 'HTTPBIN_URL' in os.environ) and not _httpbin: # c = envoy.connect('httpbin %s' % (PORT)) # time.sleep(1) _httpbin = True
http://httpbin.org/' HTTPBIN_URL = os.environ.get('HTTPBIN_URL') def httpbin(*suffix): """Returns url for HTTPBIN resource.""" return HTTPBIN_URL + '/'.join(suffix) SERVICES = (httpbin, ) _httpbin = False class TestSetup(object):
64
64
89
5
58
tzuryby/requests
tests/test_requests.py
Python
TestSetup
TestSetup
39
52
39
39
2fea1b2e21d5e3122982b23a6aab792560ee2ae9
bigcode/the-stack
train
ee68f5a1558184a9e704bb14
train
class
class RequestsTestSuite(TestSetup, TestBaseMixin, unittest.TestCase): """Requests test cases.""" def test_entry_points(self): requests.session requests.session().get requests.session().head requests.get requests.head requests.put requests.patch r...
class RequestsTestSuite(TestSetup, TestBaseMixin, unittest.TestCase):
"""Requests test cases.""" def test_entry_points(self): requests.session requests.session().get requests.session().head requests.get requests.head requests.put requests.patch requests.post def test_invalid_url(self): self.assertRaise...
['HTTPBIN_URL'] = 'http://httpbin.org/' HTTPBIN_URL = os.environ.get('HTTPBIN_URL') def httpbin(*suffix): """Returns url for HTTPBIN resource.""" return HTTPBIN_URL + '/'.join(suffix) SERVICES = (httpbin, ) _httpbin = False class TestSetup(object): """Requests test cases.""" # It goes to eleven...
256
256
6,852
15
241
tzuryby/requests
tests/test_requests.py
Python
RequestsTestSuite
RequestsTestSuite
63
914
63
63
1d3ce1224c9378043c73203d8aa9eb69360fadfe
bigcode/the-stack
train
9062fc40301df288a87c8df0
train
function
def run_simulation( gamma_boost, show ): """ Run a simulation with a relativistic electron bunch crosses a laser Parameters ---------- gamma_boost: float The Lorentz factor of the frame in which the simulation is carried out. show: bool Whether to show a plot of the angular dist...
def run_simulation( gamma_boost, show ):
""" Run a simulation with a relativistic electron bunch crosses a laser Parameters ---------- gamma_boost: float The Lorentz factor of the frame in which the simulation is carried out. show: bool Whether to show a plot of the angular distribution """ # Boosted frame ...
min_lab = -20.e-6 # Left end of the simulation box (meters) Nr = 50 # Number of gridpoints along r rmax = 20.e-6 # Length of the box along r (meters) Nm = 2 # Number of modes used # The electron bunch (in the lab frame) Q_bunch = 2080.5031144200598 * 30000 * e N_bunch = 300000 # Number of mac...
256
256
1,551
11
244
fractional-ray/fbpic
tests/test_compton.py
Python
run_simulation
run_simulation
62
197
62
62
84418c0b18943f4e1b49cc25847f481e2264501d
bigcode/the-stack
train
8d57bcddf2cd67554fe7df54
train
function
def check_photon_fraction( simulated_frac ): """Check that the photon fraction is close (within 10%) to the esimate, based on the Klein-Nishina formula""" # Calculate the expected photon fraction # - Total Klein-Nishina cross section in electron rest frame: beta_bunch_mean = np.sqrt(1-1./gamma_bunch...
def check_photon_fraction( simulated_frac ):
"""Check that the photon fraction is close (within 10%) to the esimate, based on the Klein-Nishina formula""" # Calculate the expected photon fraction # - Total Klein-Nishina cross section in electron rest frame: beta_bunch_mean = np.sqrt(1-1./gamma_bunch_mean**2) photon_p_rest = gamma_bunch_mea...
1.e-9*abs(pz_init) assert np.allclose( px_init, elec_px + photons_delta_px, atol=atol ) assert np.allclose( py_init, elec_py + photons_delta_py, atol=atol ) assert np.allclose( pz_init, elec_pz + photons_delta_pz, atol=atol ) def check_photon_fraction( simulated_frac ):
89
89
299
9
80
fractional-ray/fbpic
tests/test_compton.py
Python
check_photon_fraction
check_photon_fraction
221
240
221
221
50b3e84a28f46930b189a51542154c2e24a83b49
bigcode/the-stack
train
40220c6ebf3a95c254d86d96
train
function
def test_compton_labframe( show=False ): print('\nTest Compton scattering in lab frame') print('------------------------------------') run_simulation(gamma_boost=1., show=show)
def test_compton_labframe( show=False ):
print('\nTest Compton scattering in lab frame') print('------------------------------------') run_simulation(gamma_boost=1., show=show)
) expected_frac = sigma * nphoton_per_surface # Automatically check that the obtained fraction is within 10% assert abs(simulated_frac-expected_frac) < 0.1*expected_frac print( 'Test passed.' ) def test_compton_labframe( show=False ):
63
64
43
10
53
fractional-ray/fbpic
tests/test_compton.py
Python
test_compton_labframe
test_compton_labframe
244
247
244
244
d3b0ac5e8b56ec2244d4752e0ef3dac8ab76ea8d
bigcode/the-stack
train
8a2364e1fb8d0a472dbecd99
train
function
def test_compton_boostedframe( show=False ): print('\nTest Compton scattering in boosted frame') print('----------------------------------------') run_simulation(gamma_boost=16.6, show=show)
def test_compton_boostedframe( show=False ):
print('\nTest Compton scattering in boosted frame') print('----------------------------------------') run_simulation(gamma_boost=16.6, show=show)
print( 'Test passed.' ) def test_compton_labframe( show=False ): print('\nTest Compton scattering in lab frame') print('------------------------------------') run_simulation(gamma_boost=1., show=show) def test_compton_boostedframe( show=False ):
64
64
47
12
52
fractional-ray/fbpic
tests/test_compton.py
Python
test_compton_boostedframe
test_compton_boostedframe
249
252
249
249
5dc8c86507ab75428f691d88d5adccf2fa42f7de
bigcode/the-stack
train
52b794f77c4c78642508a988
train
function
def check_momentum_conservation( gamma_boost, photons, elec, px_init, py_init, pz_init ): """Check conservation of momentum, i.e. that the current momentum of the electrons + the change in momentum of the photons is equal to the initial momentum of the electrons""" elec...
def check_momentum_conservation( gamma_boost, photons, elec, px_init, py_init, pz_init ):
"""Check conservation of momentum, i.e. that the current momentum of the electrons + the change in momentum of the photons is equal to the initial momentum of the electrons""" elec_px = (elec.w*elec.ux).sum() * m_e * c elec_py = (elec.w*elec.uy).sum() * m_e * c elec_pz = (elec.w*elec.uz).sum() ...
plt.ylabel(r'$\gamma \theta$' ) plt.colorbar() # Plot theory plt.plot( 1./( 1 + gammatheta_bins**2), gammatheta_bins, color='r' ) plt.show() plt.clf() def check_momentum_conservation( gamma_boost, photons, elec, px_init, py_init, pz_init ):
85
85
284
27
58
fractional-ray/fbpic
tests/test_compton.py
Python
check_momentum_conservation
check_momentum_conservation
200
218
200
201
ee21b76dc6cbf9704fba24df31dcacd96b6d0a28
bigcode/the-stack
train
fc30c8ce42447f410562ddd7
train
class
class User(UserMixin,db.Model): __tablename__= 'users' id = db.Column(db.Integer,primary_key = True) username = db.Column(db.String(255)) email = db.Column(db.String(255) ,unique=True,index = True) pass_secure = db.Column(db.String(255)) pitch = db.relationship('Pitch', backref='user', lazy='dy...
class User(UserMixin,db.Model):
__tablename__= 'users' id = db.Column(db.Integer,primary_key = True) username = db.Column(db.String(255)) email = db.Column(db.String(255) ,unique=True,index = True) pass_secure = db.Column(db.String(255)) pitch = db.relationship('Pitch', backref='user', lazy='dynamic') # comment = db.relati...
from . import db from . import login_Manager from flask_login import UserMixin, current_user from werkzeug.security import generate_password_hash,check_password_hash @login_Manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) class User(UserMixin,db.Model):
62
66
222
8
54
Patrick322/pitch
app/models.py
Python
User
User
15
40
15
16
04eb5808fc2223414d174cd4ec59e82a78a0c174
bigcode/the-stack
train
85bd76b9529baac5dccc96df
train
class
class Comment(db.Model): __tablename__='comments' id = db.Column(db.Integer, primary_key = True) pitch_id = db.Column(db.Integer, db.ForeignKey('pitches.id'), nullable = False) user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable = False) description = db.Column(db.Text) def __...
class Comment(db.Model):
__tablename__='comments' id = db.Column(db.Integer, primary_key = True) pitch_id = db.Column(db.Integer, db.ForeignKey('pitches.id'), nullable = False) user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable = False) description = db.Column(db.Text) def __repr__(self): ret...
= 'pitch', lazy = 'dynamic') @classmethod def get_pitches(cls, id): pitches = Pitch.query.order_by(pitch_id=id).desc().all() return pitches def __repr__(self): return f'pitch {self.description}' class Comment(db.Model):
63
64
99
5
58
Patrick322/pitch
app/models.py
Python
Comment
Comment
69
79
69
69
fe2d03a89434975e79c659f4bcee9c85782f9a54
bigcode/the-stack
train
6d383fe8f8915a360fd5915f
train
class
class Pitch(db.Model): ''' ''' __tablename__='pitches' id = db.Column(db.Integer, primary_key = True) owner_id = db.Column(db.Integer,db.ForeignKey('users.id')) description = db.Column(db.String(), index = True) title = db.Column(db.String()) category = db.Column(db.String(255), nullabl...
class Pitch(db.Model):
''' ''' __tablename__='pitches' id = db.Column(db.Integer, primary_key = True) owner_id = db.Column(db.Integer,db.ForeignKey('users.id')) description = db.Column(db.String(), index = True) title = db.Column(db.String()) category = db.Column(db.String(255), nullable = False) comments...
the password attribute') @password.setter def password(self, password): self.pass_secure = generate_password_hash(password) def verify_password(self, password): return check_password_hash(self.pass_secure,password) def __repr__(self): return f'{self.username}' class Pitch(db....
63
64
193
5
58
Patrick322/pitch
app/models.py
Python
Pitch
Pitch
44
65
44
44
2b25f49b09a6729ea1db4335c434a95807e7102e
bigcode/the-stack
train
e1e9354a99cb73de3dc7df72
train
function
@login_Manager.user_loader def load_user(user_id): return User.query.get(int(user_id))
@login_Manager.user_loader def load_user(user_id):
return User.query.get(int(user_id))
from . import db from . import login_Manager from flask_login import UserMixin, current_user from werkzeug.security import generate_password_hash,check_password_hash @login_Manager.user_loader def load_user(user_id):
45
64
20
11
33
Patrick322/pitch
app/models.py
Python
load_user
load_user
9
11
9
10
e81e024b94c5878bc9e8b494b3b39d902d921932
bigcode/the-stack
train
e216b27a243b6a89fcac069e
train
function
def test_nnregress(paul15_proc, paul15_reference): adata = paul15_proc.copy() reference = paul15_reference[0].copy() refumap = paul15_reference[1] cp.project_cells(adata, reference, scale_data=True, k=10, obs_columns=[...
def test_nnregress(paul15_proc, paul15_reference):
adata = paul15_proc.copy() reference = paul15_reference[0].copy() refumap = paul15_reference[1] cp.project_cells(adata, reference, scale_data=True, k=10, obs_columns=['leiden'], umap_ref=refumap) ...
cp.project_cells(adata, reference, scale_data=True, k=10, obs_columns=['leiden', 'paul15_clusters'], umap_ref=refumap, categorical_how='distribution') # Checking label transfer leiden_...
103
103
344
14
88
Iwo-K/cellproject
cellproject/tests/test_main.py
Python
test_nnregress
test_nnregress
106
142
106
107
06d633e065160f8bbfe3bbc2bf6fa0548270a12e
bigcode/the-stack
train
7e1b0f17b69847af0fa27f0e
train
function
def scale_comb_and_separate(adata): adata1 = adata.copy() sc.pp.scale(adata1) adata2 = adata.copy() adata2 = cp.custom_scale(adata2, mean=adata1.var['mean'].values, std=adata1.var['std'].values) return(adata1, adata2)
def scale_comb_and_separate(adata):
adata1 = adata.copy() sc.pp.scale(adata1) adata2 = adata.copy() adata2 = cp.custom_scale(adata2, mean=adata1.var['mean'].values, std=adata1.var['std'].values) return(adata1, adata2)
'''Cellproject testing''' import numpy as np import scanpy as sc import cellproject as cp from anndata import AnnData from scipy.sparse import csr_matrix import pytest def scale_comb_and_separate(adata):
49
64
78
9
39
Iwo-K/cellproject
cellproject/tests/test_main.py
Python
scale_comb_and_separate
scale_comb_and_separate
11
19
11
12
d92250b520caf934e8452315726cb0c79db189d9
bigcode/the-stack
train
432c78d48f30f882cd691b4c
train
function
@pytest.fixture def paul15_proc(): adata = sc.datasets.paul15() sc.pp.normalize_per_cell(adata, counts_per_cell_after=10000) sc.pp.log1p(adata) adata.var['highly_variable'] = True return(adata)
@pytest.fixture def paul15_proc():
adata = sc.datasets.paul15() sc.pp.normalize_per_cell(adata, counts_per_cell_after=10000) sc.pp.log1p(adata) adata.var['highly_variable'] = True return(adata)
(adata1) adata2 = adata.copy() adata2 = cp.custom_scale(adata2, mean=adata1.var['mean'].values, std=adata1.var['std'].values) return(adata1, adata2) @pytest.fixture def paul15_proc():
64
64
61
8
56
Iwo-K/cellproject
cellproject/tests/test_main.py
Python
paul15_proc
paul15_proc
22
29
22
24
cbb4a06e521fd04ff13e5ec68664e1018cf16af8
bigcode/the-stack
train
d94a62321381f700672ef368
train
function
def test_run_seuratCCA(paul15_proc): '''Just bare testing if the code works. Need to figure testing if the results are correct''' adata = paul15_proc.copy() adata1 = adata[1:500, :].copy() adata2 = adata[1000:1500, :].copy() comb = adata1.concatenate(adata2, batch_key='batch', batch_categories=['...
def test_run_seuratCCA(paul15_proc):
'''Just bare testing if the code works. Need to figure testing if the results are correct''' adata = paul15_proc.copy() adata1 = adata[1:500, :].copy() adata2 = adata[1000:1500, :].copy() comb = adata1.concatenate(adata2, batch_key='batch', batch_categories=['batchA', 'batchB']) corrected = ...
.corrcoef(adata.obsm['X_umap'][:, 1], reference.obsm['X_umap'][:, 1])[0, 1] assert u1_r > 0.975 and u2_r > 0.975 def test_run_seuratCCA(paul15_proc):
64
64
138
11
52
Iwo-K/cellproject
cellproject/tests/test_main.py
Python
test_run_seuratCCA
test_run_seuratCCA
145
160
145
145
e0b6e3fde43a9a2119ad7d7639f023f2000dc779
bigcode/the-stack
train
88946cb3b8628d94b20aca53
train
function
@pytest.fixture def paul15_reference(paul15_proc): adata = paul15_proc.copy() adata.var['highly_variable'] = True sc.pp.scale(adata) sc.pp.pca(adata, n_comps=20) sc.pp.neighbors(adata) sc.tl.leiden(adata) umapref = cp.quick_umap(adata) return(adata, umapref)
@pytest.fixture def paul15_reference(paul15_proc):
adata = paul15_proc.copy() adata.var['highly_variable'] = True sc.pp.scale(adata) sc.pp.pca(adata, n_comps=20) sc.pp.neighbors(adata) sc.tl.leiden(adata) umapref = cp.quick_umap(adata) return(adata, umapref)
adata = sc.datasets.paul15() sc.pp.normalize_per_cell(adata, counts_per_cell_after=10000) sc.pp.log1p(adata) adata.var['highly_variable'] = True return(adata) @pytest.fixture def paul15_reference(paul15_proc):
64
64
92
12
52
Iwo-K/cellproject
cellproject/tests/test_main.py
Python
paul15_reference
paul15_reference
32
42
32
34
b3ecedc5132c233d60bf4aad42a743439c4ed501
bigcode/the-stack
train
a8998e8cc165f3e1931c9b68
train
function
def test_custom_scale(paul15_proc): adata = paul15_proc.copy() out = scale_comb_and_separate(adata) assert np.array_equal(out[0].X, out[1].X) # Repeating for sparse matrix adata.X = csr_matrix(adata.X) out = scale_comb_and_separate(adata) assert np.array_equal(out[0].X, out[1].X)
def test_custom_scale(paul15_proc):
adata = paul15_proc.copy() out = scale_comb_and_separate(adata) assert np.array_equal(out[0].X, out[1].X) # Repeating for sparse matrix adata.X = csr_matrix(adata.X) out = scale_comb_and_separate(adata) assert np.array_equal(out[0].X, out[1].X)
(adata) sc.pp.pca(adata, n_comps=20) sc.pp.neighbors(adata) sc.tl.leiden(adata) umapref = cp.quick_umap(adata) return(adata, umapref) def test_custom_scale(paul15_proc):
64
64
93
9
55
Iwo-K/cellproject
cellproject/tests/test_main.py
Python
test_custom_scale
test_custom_scale
44
54
44
45
92160d667f910effe25f54907a8f038be84fc419
bigcode/the-stack
train
5b0d095886874944d5a7678d
train
function
def test_project_cells_distribution(paul15_proc, paul15_reference): adata = paul15_proc.copy() reference = paul15_reference[0].copy() refumap = paul15_reference[1] cp.project_cells(adata, reference, scale_data=True, k=10, ...
def test_project_cells_distribution(paul15_proc, paul15_reference):
adata = paul15_proc.copy() reference = paul15_reference[0].copy() refumap = paul15_reference[1] cp.project_cells(adata, reference, scale_data=True, k=10, obs_columns=['leiden', 'paul15_clusters'], u...
(adata.obsm['X_umap'][:, 1], reference.obsm['X_umap'][:, 1])[0, 1] assert u1_r > 0.975 and u2_r > 0.975 def test_project_cells_distribution(paul15_proc, paul15_reference):
64
64
135
14
49
Iwo-K/cellproject
cellproject/tests/test_main.py
Python
test_project_cells_distribution
test_project_cells_distribution
87
103
87
88
070915d6719877d15985cb18654d80b5fcf60264
bigcode/the-stack
train
8c78baf8730aeb06a22e4ae7
train
function
def test_project_cells(paul15_proc, paul15_reference): # Projecting the same data onto itself should produce consistent results adata = paul15_proc.copy() reference = paul15_reference[0].copy() refumap = paul15_reference[1] cp.project_cells(adata, reference, ...
def test_project_cells(paul15_proc, paul15_reference): # Projecting the same data onto itself should produce consistent results
adata = paul15_proc.copy() reference = paul15_reference[0].copy() refumap = paul15_reference[1] cp.project_cells(adata, reference, scale_data=True, k=10, obs_columns=['leiden', 'paul15_clusters'], u...
) assert np.array_equal(out[0].X, out[1].X) # Repeating for sparse matrix adata.X = csr_matrix(adata.X) out = scale_comb_and_separate(adata) assert np.array_equal(out[0].X, out[1].X) def test_project_cells(paul15_proc, paul15_reference): # Projecting the same data onto itself should produce con...
92
92
309
27
65
Iwo-K/cellproject
cellproject/tests/test_main.py
Python
test_project_cells
test_project_cells
57
84
57
59
0bd8a0dc3b9e891b7bf1904c7acc45529fad3a59
bigcode/the-stack
train
5c80ec43b7da0711125c1a6c
train
class
class N_Grams_LM: """ N-gram language model. Initialize with N-grams from a collection of documents. Can generate random sentences. """ def reset(self): # ... over whole corpus ... self.sents = [] # Sentences self.tokens = [] # Wor...
class N_Grams_LM:
""" N-gram language model. Initialize with N-grams from a collection of documents. Can generate random sentences. """ def reset(self): # ... over whole corpus ... self.sents = [] # Sentences self.tokens = [] # Word tokens s...
""" NEU CS6120 Assignment 1 Problem 3 Language Modeling 3.1 Report 4-gram counts in the Gutenberg data extract. 3.2 Calculate average perplexity in news articles and imdb reviews. Sig Nin 21 Sep 2018 """ import nltk import numpy as np import os import re from collections import defaultdict pathToyData = r'D:/Document...
178
256
3,444
8
170
sigfredonin/NEU_CS6120
assignment_1/n_grams_lm.py
Python
N_Grams_LM
N_Grams_LM
21
384
21
21
374de5ea91f2ed12fdccc9f6421acd1e2b8e90dd
bigcode/the-stack
train
0eb4c891bfa68bf469224ea2
train
class
class CategoricalCorrelation(object): def __init__(self): self.Y = None self.gamma = None def load_result(self, path): ctime = time.time() print("Loading result...",) self.Y = np.load(path + "Y.npy") self.gamma = 1.0 + 1.0 / np.mean(np.log(1.0 + self.Y[s...
class CategoricalCorrelation(object):
def __init__(self): self.Y = None self.gamma = None def load_result(self, path): ctime = time.time() print("Loading result...",) self.Y = np.load(path + "Y.npy") self.gamma = 1.0 + 1.0 / np.mean(np.log(1.0 + self.Y[self.Y > 0])) print("Done. Elap...
import time import numpy as np class CategoricalCorrelation(object):
14
95
318
6
7
heitor57/poi-rss
algorithms/library/methods/geosoca/CategoricalCorrelation.py
Python
CategoricalCorrelation
CategoricalCorrelation
5
39
5
5
5fea3239c1054b12e03122b9c5ff0aa2f39e38c2
bigcode/the-stack
train
1c78eaa52825a1e181af5931
train
class
class TestSolveFailure(VscTestCase): def test_fail_enum(self): class my_e(IntEnum): A = auto() B = auto() C = auto() @vsc.randobj class my_c(object): def __init__(self): self.e = vsc.rand_...
class TestSolveFailure(VscTestCase):
def test_fail_enum(self): class my_e(IntEnum): A = auto() B = auto() C = auto() @vsc.randobj class my_c(object): def __init__(self): self.e = vsc.rand_enum_t(my_e) self.a = vsc....
''' Created on Oct 25, 2020 @author: ballance ''' from enum import IntEnum, auto import vsc from vsc_test_case import VscTestCase class TestSolveFailure(VscTestCase):
50
64
185
10
39
edcote/pyvsc
ve/unit/test_solve_failure.py
Python
TestSolveFailure
TestSolveFailure
12
41
12
13
2285455d2e9488700b4557d1e00bae3200476d72
bigcode/the-stack
train
d59c17d965ff34825f8cd5c4
train
function
def get_module_filename(module): """ Retrieve filename from an imported pywikibot module. It uses the __file__ attribute of the module. If it's file extension ends with py and another character the last character is discarded when the py file exist. @param module: The module instance. @typ...
def get_module_filename(module):
""" Retrieve filename from an imported pywikibot module. It uses the __file__ attribute of the module. If it's file extension ends with py and another character the last character is discarded when the py file exist. @param module: The module instance. @type module: module @return: The...
: The module instance. @type module: module @return: The version hash without the surrounding text. If not present None. @rtype: str or None """ if hasattr(module, '__version__'): return module.__version__[5:-1] def get_module_filename(module):
64
64
177
6
58
jimmytsang/WikipediaTech
pywikibot/version.py
Python
get_module_filename
get_module_filename
432
451
432
432
45e0f7d5fe739d984537b43527e1bd108e980c71
bigcode/the-stack
train
184a9eb08a94bf1ffb747dd2
train
class
class ParseError(Exception): """Parsing went wrong."""
class ParseError(Exception):
"""Parsing went wrong."""
e: svn_utils = e import pywikibot from pywikibot import config2 as config from pywikibot.tools import deprecated, PY2 if not PY2: basestring = (str, ) cache = None _logger = 'version' class ParseError(Exception):
64
64
11
5
59
jimmytsang/WikipediaTech
pywikibot/version.py
Python
ParseError
ParseError
48
50
48
49
94def28b2b3756141a28f6becc965071051ec78f
bigcode/the-stack
train
d818124b65b384174bf707a4
train
function
def github_svn_rev2hash(tag, rev): """Convert a Subversion revision to a Git hash using Github. @param tag: name of the Subversion repo on Github @param rev: Subversion revision identifier @return: the git hash @rtype: str """ from pywikibot.comms import http uri = 'https://github.com/...
def github_svn_rev2hash(tag, rev):
"""Convert a Subversion revision to a Git hash using Github. @param tag: name of the Subversion repo on Github @param rev: Subversion revision identifier @return: the git hash @rtype: str """ from pywikibot.comms import http uri = 'https://github.com/wikimedia/%s/!svn/vcc/default' % ta...
desc""") name, tag, rev, date, checksum = cur.fetchone() cur.execute("select root from repository") tag, = cur.fetchone() con.close() tag = os.path.split(tag)[1] date = time.gmtime(date / 1000000) return tag, rev, date def github_svn_rev2hash(tag, rev):
79
79
264
11
67
jimmytsang/WikipediaTech
pywikibot/version.py
Python
github_svn_rev2hash
github_svn_rev2hash
184
205
184
184
e14912e753abeb5aeda642e2fee9ce5d5102b918
bigcode/the-stack
train
a83cbe61cf54b63e98d79f3c
train
function
def package_versions(modules=None, builtins=False, standard_lib=None): """Retrieve package version information. When builtins or standard_lib are None, they will be included only if a version was found in the package. @param modules: Modules to inspect @type modules: list of strings @param bui...
def package_versions(modules=None, builtins=False, standard_lib=None):
"""Retrieve package version information. When builtins or standard_lib are None, they will be included only if a version was found in the package. @param modules: Modules to inspect @type modules: list of strings @param builtins: Include builtins @type builtins: Boolean, or None for automa...
@return: The filename if it's a pywikibot module otherwise None. @rtype: str or None """ if hasattr(module, '__file__') and os.path.exists(module.__file__): filename = module.__file__ if filename[-4:-1] == '.py' and os.path.exists(filename[:-1]): filename = filename[:-1] ...
208
208
695
15
193
jimmytsang/WikipediaTech
pywikibot/version.py
Python
package_versions
package_versions
468
558
468
468
214af8eb1abb760868a8cc5227432d447935b67e
bigcode/the-stack
train
a695b5b7427359eae3145999
train
function
@deprecated('getversion_svn_setuptools') def svn_rev_info(path): """Fetch information about the current revision of an Subversion checkout. @param path: directory of the Subversion checkout @return: - tag (name for the repository), - rev (current Subversion revision identifier), - d...
@deprecated('getversion_svn_setuptools') def svn_rev_info(path):
"""Fetch information about the current revision of an Subversion checkout. @param path: directory of the Subversion checkout @return: - tag (name for the repository), - rev (current Subversion revision identifier), - date (date of current revision), @rtype: C{tuple} of two C{str...
wikibot.debug('version algorithm exceptions:\n%r' % exceptions, _logger) if isinstance(date, basestring): datestring = date elif isinstance(date, time.struct_time): datestring = time.strftime('%Y/%m/%d, %H:%M:%S', date) else: warn('Unable to detect package da...
136
136
456
16
119
jimmytsang/WikipediaTech
pywikibot/version.py
Python
svn_rev_info
svn_rev_info
133
181
133
134
0cc0598d95e39c932117964586b6fdc779e2530e
bigcode/the-stack
train
6630f6f43dcad93381901eb8
train
function
def getversion_onlinerepo(repo=None): """Retrieve current framework revision number from online repository. @param repo: (optional) Online repository location @type repo: URL or string """ from pywikibot.comms import http url = repo or 'https://git.wikimedia.org/feed/pywikibot/core' buf = ...
def getversion_onlinerepo(repo=None):
"""Retrieve current framework revision number from online repository. @param repo: (optional) Online repository location @type repo: URL or string """ from pywikibot.comms import http url = repo or 'https://git.wikimedia.org/feed/pywikibot/core' buf = http.fetch(uri=url, ...
ibot) date = get_module_mtime(pywikibot).timetuple() tag = 'pywikibot/__init__.py' rev = '-1 (unknown)' return (tag, rev, date, hsh) def getversion_onlinerepo(repo=None):
64
64
146
10
54
jimmytsang/WikipediaTech
pywikibot/version.py
Python
getversion_onlinerepo
getversion_onlinerepo
367
382
367
367
5d267fbf56ab12a352bc88e093d86f29a9eec717
bigcode/the-stack
train
d847a0c21f2bd5ef7f78cf47
train
function
def getversion_git(path=None): """Get version info for a Git clone. @param path: directory of the Git checkout @return: - tag (name for the repository), - rev (current revision identifier), - date (date of current revision), - hash (git hash for the current revision) @rt...
def getversion_git(path=None):
"""Get version info for a Git clone. @param path: directory of the Git checkout @return: - tag (name for the repository), - rev (current revision identifier), - date (date of current revision), - hash (git hash for the current revision) @rtype: C{tuple} of three C{str} a...
(_program_dir) hsh, date2 = github_svn_rev2hash(tag, rev) if date.tm_isdst >= 0 and date2.tm_isdst >= 0: assert date == date2, 'Date of version is not consistent' # date.tm_isdst is -1 means unknown state # compare its contents except daylight saving time status else: for i in range(...
162
162
542
7
155
jimmytsang/WikipediaTech
pywikibot/version.py
Python
getversion_git
getversion_git
268
320
268
268
25a2d8332ea4fb7647a3e2f071a1d6ea054789db
bigcode/the-stack
train
a56ccb62492827cac9cf2325
train
function
@deprecated('get_module_version, get_module_filename and get_module_mtime') def getfileversion(filename): """Retrieve revision number of file. Extracts __version__ variable containing Id tag, without importing it. (thus can be done for any file) The version variable containing the Id tag is read and ...
@deprecated('get_module_version, get_module_filename and get_module_mtime') def getfileversion(filename):
"""Retrieve revision number of file. Extracts __version__ variable containing Id tag, without importing it. (thus can be done for any file) The version variable containing the Id tag is read and returned. Because it doesn't import it, the version can be retrieved from any file. @param file...
': '{pwb}'}).content.splitlines() try: hsh = buf[13].split('/')[5][:-1] return hsh except Exception as e: raise ParseError(repr(e) + ' while parsing ' + repr(buf)) @deprecated('get_module_version, get_module_filename and get_module_mtime') def getfileversion(filename):
80
80
269
22
58
jimmytsang/WikipediaTech
pywikibot/version.py
Python
getfileversion
getfileversion
385
416
385
386
2dd557c586a19ae5e47e755a4bd145d289443a38
bigcode/the-stack
train
227b532bb4902aa52f5247d4
train
function
def _get_program_dir(): _program_dir = os.path.normpath(os.path.split(os.path.dirname(__file__))[0]) return _program_dir
def _get_program_dir():
_program_dir = os.path.normpath(os.path.split(os.path.dirname(__file__))[0]) return _program_dir
from pywikibot import config2 as config from pywikibot.tools import deprecated, PY2 if not PY2: basestring = (str, ) cache = None _logger = 'version' class ParseError(Exception): """Parsing went wrong.""" def _get_program_dir():
63
64
33
6
57
jimmytsang/WikipediaTech
pywikibot/version.py
Python
_get_program_dir
_get_program_dir
53
55
53
53
fdaa73d7a72befd64d7fbef9ca7ba86302b72c2b
bigcode/the-stack
train
debc2e3ab06d170c0f993026
train
function
def getversiondict(): """Get version info for the package. @return: - tag (name for the repository), - rev (current revision identifier), - date (date of current revision), - hash (git hash for the current revision) @rtype: C{dict} of four C{str} """ global cache ...
def getversiondict():
"""Get version info for the package. @return: - tag (name for the repository), - rev (current revision identifier), - date (date of current revision), - hash (git hash for the current revision) @rtype: C{dict} of four C{str} """ global cache if cache: ret...
data['cmp_ver'] = 'n/a' if online: try: hsh2 = getversion_onlinerepo() hsh1 = data['hsh'] data['cmp_ver'] = 'OUTDATED' if hsh1 != hsh2 else 'ok' except Exception: pass data['hsh'] = data['hsh'][:7] # make short hash from full hash return '%...
126
126
420
5
120
jimmytsang/WikipediaTech
pywikibot/version.py
Python
getversiondict
getversiondict
78
130
78
78
7518be3f11752b06c6bc119f1fe185f6dc6f7e9a
bigcode/the-stack
train
fbab08b0d7888395c3ebb0eb
train
function
def getversion_package(path=None): # pylint: disable=unused-argument """Get version info for an installed package. @param path: Unused argument @return: - tag: 'pywikibot/__init__.py' - rev: '-1 (unknown)' - date (date the package was installed locally), - hash (git hash fo...
def getversion_package(path=None): # pylint: disable=unused-argument
"""Get version info for an installed package. @param path: Unused argument @return: - tag: 'pywikibot/__init__.py' - rev: '-1 (unknown)' - date (date the package was installed locally), - hash (git hash for the current revision of 'pywikibot/__init__.py') @rtype: C{tuple...
.strptime(date[:19], '%Y-%m-%dT%H:%M:%S') if not date or not tag or not rev: raise ParseError return (tag, rev, date, hsh) def getversion_package(path=None): # pylint: disable=unused-argument
64
64
175
17
47
jimmytsang/WikipediaTech
pywikibot/version.py
Python
getversion_package
getversion_package
347
364
347
347
2b31adafc974ffe53bf300635e9c638403df91d6
bigcode/the-stack
train
a0fffc7c488b5743adaeadb2
train
function
def getversion(online=True): """Return a pywikibot version string. @param online: (optional) Include information obtained online """ data = dict(getversiondict()) # copy dict to prevent changes in 'cache' data['cmp_ver'] = 'n/a' if online: try: hsh2 = getversion_onlinerepo...
def getversion(online=True):
"""Return a pywikibot version string. @param online: (optional) Include information obtained online """ data = dict(getversiondict()) # copy dict to prevent changes in 'cache' data['cmp_ver'] = 'n/a' if online: try: hsh2 = getversion_onlinerepo() hsh1 = data['h...
str, ) cache = None _logger = 'version' class ParseError(Exception): """Parsing went wrong.""" def _get_program_dir(): _program_dir = os.path.normpath(os.path.split(os.path.dirname(__file__))[0]) return _program_dir def getversion(online=True):
64
64
174
7
56
jimmytsang/WikipediaTech
pywikibot/version.py
Python
getversion
getversion
58
75
58
58
a758f139ad38e1e7925a7915df5088b4f9c91cb3
bigcode/the-stack
train
b94c3e293fab658a514601b7
train
function
def get_module_version(module): """ Retrieve __version__ variable from an imported module. @param module: The module instance. @type module: module @return: The version hash without the surrounding text. If not present None. @rtype: str or None """ if hasattr(module, '__version__'): ...
def get_module_version(module):
""" Retrieve __version__ variable from an imported module. @param module: The module instance. @type module: module @return: The version hash without the surrounding text. If not present None. @rtype: str or None """ if hasattr(module, '__version__'): return module.__version__[5...
mtime = datetime.datetime.fromtimestamp(stat.st_mtime).isoformat(' ') if mtime and __version__: return u'%s %s %s' % (filename, __version__[5:-1][:7], mtime) else: return None def get_module_version(module):
64
64
81
6
57
jimmytsang/WikipediaTech
pywikibot/version.py
Python
get_module_version
get_module_version
419
429
419
419
364c2b97854875206e502ee0664dffb1744b6bac
bigcode/the-stack
train
0a48df2f73a6393aa4ef4c10
train
function
def getversion_nightly(path=None): """Get version info for a nightly release. @param path: directory of the uncompressed nightly. @return: - tag (name for the repository), - rev (current revision identifier), - date (date of current revision), - hash (git hash for the curren...
def getversion_nightly(path=None):
"""Get version info for a nightly release. @param path: directory of the uncompressed nightly. @return: - tag (name for the repository), - rev (current revision identifier), - date (date of current revision), - hash (git hash for the current revision) @rtype: C{tuple} of...
lines()) hsh = info[3] # also stored in '.git/refs/heads/master' if (not date or not tag or not rev) and not path: raise ParseError return (tag, rev, date, hsh) def getversion_nightly(path=None):
64
64
188
8
56
jimmytsang/WikipediaTech
pywikibot/version.py
Python
getversion_nightly
getversion_nightly
323
344
323
323
d7c3366374fbe9c58b6f8dc7238a6491f19958bf
bigcode/the-stack
train
efb9d469c8d89f2bf7e7b1a9
train
function
def getversion_svn_setuptools(path=None): """Get version info for a Subversion checkout using setuptools. @param path: directory of the Subversion checkout @return: - tag (name for the repository), - rev (current Subversion revision identifier), - date (date of current revision), ...
def getversion_svn_setuptools(path=None):
"""Get version info for a Subversion checkout using setuptools. @param path: directory of the Subversion checkout @return: - tag (name for the repository), - rev (current Subversion revision identifier), - date (date of current revision), - hash (git hash for the Subversion ...
(request.raw)) hsh = dom.getElementsByTagName("C:git-commit")[0].firstChild.nodeValue date = dom.getElementsByTagName("S:date")[0].firstChild.nodeValue date = time.strptime(date[:19], '%Y-%m-%dT%H:%M:%S') return hsh, date def getversion_svn_setuptools(path=None):
88
88
295
10
77
jimmytsang/WikipediaTech
pywikibot/version.py
Python
getversion_svn_setuptools
getversion_svn_setuptools
208
236
208
208
355d52c8ae6318269ff89f9d17bb4ff6706c514b
bigcode/the-stack
train
e42b4dfc9e559090759a86cd
train
function
def get_module_mtime(module): """ Retrieve the modification time from an imported module. @param module: The module instance. @type module: module @return: The modification time if it's a pywikibot module otherwise None. @rtype: datetime or None """ filename = get_module_filename(module...
def get_module_mtime(module):
""" Retrieve the modification time from an imported module. @param module: The module instance. @type module: module @return: The modification time if it's a pywikibot module otherwise None. @rtype: datetime or None """ filename = get_module_filename(module) if filename: ret...
= module.__file__ if filename[-4:-1] == '.py' and os.path.exists(filename[:-1]): filename = filename[:-1] program_dir = _get_program_dir() if filename[:len(program_dir)] == program_dir: return filename def get_module_mtime(module):
64
64
89
7
56
jimmytsang/WikipediaTech
pywikibot/version.py
Python
get_module_mtime
get_module_mtime
454
465
454
454
d98096799789afbc74f6d4183da8a8ef3c3423af
bigcode/the-stack
train
6fe2b981bb755462fc2883c7
train
function
@deprecated('getversion_svn_setuptools') def getversion_svn(path=None): """Get version info for a Subversion checkout. @param path: directory of the Subversion checkout @return: - tag (name for the repository), - rev (current Subversion revision identifier), - date (date of current ...
@deprecated('getversion_svn_setuptools') def getversion_svn(path=None):
"""Get version info for a Subversion checkout. @param path: directory of the Subversion checkout @return: - tag (name for the repository), - rev (current Subversion revision identifier), - date (date of current revision), - hash (git hash for the Subversion revision) @rt...
_revision() returned %d' % rev) if rev == 0: raise ParseError('SvnInfo: invalid workarea') hsh, date = github_svn_rev2hash(tag, rev) rev = 's%s' % rev return (tag, rev, date, hsh) @deprecated('getversion_svn_setuptools') def getversion_svn(path=None):
85
85
286
18
67
jimmytsang/WikipediaTech
pywikibot/version.py
Python
getversion_svn
getversion_svn
239
265
239
240
aea1c9382bb403b25b0264468afbd457c1a4c116
bigcode/the-stack
train
59d1e373152dfe3ccce9fa0b
train
class
class Engine(object): """Contains training and evaluation procedures """ def __init__(self): self.hooks = {} self.epoch = 0 self.dataset = None self.model = None self.optimizer = None self.view = None self.best_out = {} # generate_view will b...
class Engine(object):
"""Contains training and evaluation procedures """ def __init__(self): self.hooks = {} self.epoch = 0 self.dataset = None self.model = None self.optimizer = None self.view = None self.best_out = {} # generate_view will be executed at the end ...
import os import math import time import torch import datetime import threading import numpy as np from ..lib import utils from ..lib.options import Options from ..lib.logger import Logger class Engine(object):
47
256
3,545
4
42
jbegaint/bootstrap.pytorch
bootstrap/engines/engine.py
Python
Engine
Engine
13
423
13
13
ccf46f3288d928983d32c387e77bdb92cabe2693
bigcode/the-stack
train
bfbdc1db56c429182bcdf30e
train
function
def fib3(term): if term <= 2: return max(1, term) else: return fib3(term - 1) + fib3(term - 2) + fib3(term - 3)
def fib3(term):
if term <= 2: return max(1, term) else: return fib3(term - 1) + fib3(term - 2) + fib3(term - 3)
3) diffs = [] for i in range(len(output_jolts) - 1): diffs.append(output_jolts[i + 1] - output_jolts[i]) print("answer 1:", Counter(diffs)[1] * Counter(diffs)[3]) def fib3(term):
64
64
48
5
59
gregarendse/adventofcode
2020/10/sample.py
Python
fib3
fib3
12
16
12
12
36e654d3cbd869f08d841187aef7f53e195754ad
bigcode/the-stack
train
83fb79c2365713911f0046aa
train
class
@tf_export("data.experimental.TFRecordWriter") class TFRecordWriter(object): """Writes data to a TFRecord file.""" def __init__(self, filename, compression_type=None): self._filename = ops.convert_to_tensor( filename, dtypes.string, name="filename") self._compression_type = convert.optional_param_t...
@tf_export("data.experimental.TFRecordWriter") class TFRecordWriter(object):
"""Writes data to a TFRecord file.""" def __init__(self, filename, compression_type=None): self._filename = ops.convert_to_tensor( filename, dtypes.string, name="filename") self._compression_type = convert.optional_param_to_tensor( "compression_type", compression_type, argum...
from __future__ import division from __future__ import print_function from tensorflow.python.data.ops import dataset_ops from tensorflow.python.data.util import convert from tensorflow.python.data.util import structure from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tens...
93
93
311
17
75
PaulWang1905/tensorflow
tensorflow/python/data/experimental/ops/writers.py
Python
TFRecordWriter
TFRecordWriter
29
61
29
30
fc31f36dcf991387f8f06ff0a1553ded1b700891
bigcode/the-stack
train
250bfacb59738a52d89da736
train
function
def generate_alt_2(num_to_generate): return map( lambda x: ( { "name": str(uuid.uuid4()), "dob": datetime.utcnow(), "friends": [ { "name": str(uuid.uuid4()), "dob": datetime.utcnow...
def generate_alt_2(num_to_generate):
return map( lambda x: ( { "name": str(uuid.uuid4()), "dob": datetime.utcnow(), "friends": [ { "name": str(uuid.uuid4()), "dob": datetime.utcnow(), "friends"...
_generate): yield { "name": str(uuid.uuid4()), "dob": datetime.utcnow(), "friends": [ { "name": str(uuid.uuid4()), "dob": datetime.utcnow(), "friends": [] } ] } def...
64
64
85
9
55
mr-uuid/perfpy
perfpy/picking_data_model/using_dicts.py
Python
generate_alt_2
generate_alt_2
22
38
22
22
5baec73c37459d224592ec0531e8985609440656
bigcode/the-stack
train
debf00170a7f3a8cdefd7978
train
function
def generate_alt_1(num_to_generate): for x in range(num_to_generate): yield { "name": str(uuid.uuid4()), "dob": datetime.utcnow(), "friends": [ { "name": str(uuid.uuid4()), "dob": datetime.utcnow(), ...
def generate_alt_1(num_to_generate):
for x in range(num_to_generate): yield { "name": str(uuid.uuid4()), "dob": datetime.utcnow(), "friends": [ { "name": str(uuid.uuid4()), "dob": datetime.utcnow(), "friends": [] } ...
# https://pydantic-docs.helpmanual.io/ import numpy as np import uuid from datetime import datetime def generate_alt_1(num_to_generate):
34
64
71
9
24
mr-uuid/perfpy
perfpy/picking_data_model/using_dicts.py
Python
generate_alt_1
generate_alt_1
7
19
7
7
9361fe155ace0cc502b3710845715737e5710966
bigcode/the-stack
train
024374490a21fa2f594334e3
train
class
class OLDA(Estimator): """ Estimator computing the olda novelty from McFee 2014 Implementation from msaf """ def __init__(self, inputSamples="normalizedBarMSE", outputNovelty="noveltyMSE", cachingLevel=2, forceRefreshCache=False): self.parameters = {} self.inputs = [inputSamples] ...
class OLDA(Estimator):
""" Estimator computing the olda novelty from McFee 2014 Implementation from msaf """ def __init__(self, inputSamples="normalizedBarMSE", outputNovelty="noveltyMSE", cachingLevel=2, forceRefreshCache=False): self.parameters = {} self.inputs = [inputSamples] self.outputs = [o...
from msaf.algorithms.olda import segmenter import numpy as np from automix.featureExtraction.estimator import Estimator, Parameter from automix.model.classes.signal import Signal class OLDA(Estimator):
44
75
253
6
37
MZehren/Automix
automix/featureExtraction/novelty/spectralClustering.py
Python
OLDA
OLDA
8
34
8
8
8a62e2f8f29f7f60b6a6bb4bd065053655124a9b
bigcode/the-stack
train
7aab11e947d75a7093512846
train
function
def handle_args(): parser = argparse.ArgumentParser(description='Mjpeg streaming server: mjpegsw -p 8080 --camera 2') parser.add_argument('-p', '--port', help='http listening port, default 5001', type=int, default=5001) parser.add_argument('-c', '--camera', help='opencv camera number, ex. -c 1', type=int, d...
def handle_args():
parser = argparse.ArgumentParser(description='Mjpeg streaming server: mjpegsw -p 8080 --camera 2') parser.add_argument('-p', '--port', help='http listening port, default 5001', type=int, default=5001) parser.add_argument('-c', '--camera', help='opencv camera number, ex. -c 1', type=int, default=0) parse...
html><head></head><body>') self.wfile.write(b'<img src="/cam.mjpg"/>') self.wfile.write(b'</body></html>') return class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): """Handle requests in a separate thread.""" def handle_args():
63
64
138
4
59
meska/mjpeg_stream_webcam
mjpegsw.py
Python
handle_args
handle_args
89
96
89
89
de0703465b1155cd752503539ccc7dfb28a80502
bigcode/the-stack
train
97e918ee79634fb6f9414796
train
class
class CamHandler(BaseHTTPRequestHandler): # noinspection PyPep8Naming def do_GET(self): if self.path == '/favicon.ico': return print(f"{self.path}") if '.mjpg' in self.path.lower(): # send video stream self.send_response(200) self.send_head...
class CamHandler(BaseHTTPRequestHandler): # noinspection PyPep8Naming
def do_GET(self): if self.path == '/favicon.ico': return print(f"{self.path}") if '.mjpg' in self.path.lower(): # send video stream self.send_response(200) self.send_header('Content-type', 'multipart/x-mixed-replace; boundary=--jpgboundary') ...
#!/usr/bin/python """ Author: Marco Mescalchin Mjpg stream Server for Mac Webcam """ import argparse import time from http.server import BaseHTTPRequestHandler, HTTPServer from io import BytesIO from socketserver import ThreadingMixIn import cv2 from PIL import Image capture = None class CamHandler(BaseHTTPRequestHa...
83
147
493
16
66
meska/mjpeg_stream_webcam
mjpegsw.py
Python
CamHandler
CamHandler
19
82
19
20
36552cea6d10b2c43be95978370318f8ed04501c
bigcode/the-stack
train
854481c654d1f63c7e9c33f1
train
function
def main(): global capture params = handle_args() capture = cv2.VideoCapture(params['camera']) server = ThreadedHTTPServer((params['ipaddress'], params['port']), CamHandler) try: print(f"Mjpeg server started on http://{params['ipaddress']}:{params['port']}") server.serve_forever() ...
def main():
global capture params = handle_args() capture = cv2.VideoCapture(params['camera']) server = ThreadedHTTPServer((params['ipaddress'], params['port']), CamHandler) try: print(f"Mjpeg server started on http://{params['ipaddress']}:{params['port']}") server.serve_forever() except K...
. -c 1', type=int, default=0) parser.add_argument('-i', '--ipaddress', help='listening ip address, default all ips', type=str, default='0.0.0.0') params = vars(parser.parse_args()) return params def main():
64
64
90
3
60
meska/mjpeg_stream_webcam
mjpegsw.py
Python
main
main
99
111
99
99
bae43e9af424abaf09faf9862f902264de532438
bigcode/the-stack
train
81e3d420e9bffc3497b41019
train
class
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): """Handle requests in a separate thread."""
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
"""Handle requests in a separate thread."""
/html') self.end_headers() self.wfile.write(b'<html><head></head><body>') self.wfile.write(b'<img src="/cam.mjpg"/>') self.wfile.write(b'</body></html>') return class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
64
64
22
13
50
meska/mjpeg_stream_webcam
mjpegsw.py
Python
ThreadedHTTPServer
ThreadedHTTPServer
85
86
85
85
e853560905f001e668444ec0ba877d47a62838ca
bigcode/the-stack
train
914c612210ddcf1957462ab6
train
function
def test_single_env_single_cpu_reset(): env = VectorizedEnvironment(make_env, 1, ray_kwargs={'num_cpus': 1}) # check env ref = env.actors[0].environment.remote() e = ray.get(ref) assert isinstance(e, gym.Env) obs = env.reset() print('obs', obs) assert isinstance(obs, np.ndarray) # 4...
def test_single_env_single_cpu_reset():
env = VectorizedEnvironment(make_env, 1, ray_kwargs={'num_cpus': 1}) # check env ref = env.actors[0].environment.remote() e = ray.get(ref) assert isinstance(e, gym.Env) obs = env.reset() print('obs', obs) assert isinstance(obs, np.ndarray) # 4 is CartPole obs space size assert o...
VectorizedEnvironment(env, 1, ray_kwargs={'num_cpus': 1}) assert len(env.actors) == 1 ref = env.actors[0].environment.remote() env = ray.get(ref) assert isinstance(env, gym.Env) def test_single_env_single_cpu_reset():
64
64
105
8
56
NickLucche/avalanche
tests/test_vectorized_env.py
Python
test_single_env_single_cpu_reset
test_single_env_single_cpu_reset
43
54
43
43
4850a2c0f57c731aaea3559830dc99e42fd837b9
bigcode/the-stack
train
99a74eb5a10a56ddb35cc148
train
function
def test_auto_reset(): env = VectorizedEnvironment(make_env, 4, auto_reset=True) env.reset() while True: actions = np.asarray([env.action_space.sample() for _ in range(4)]) obs, _, done, info = env.step(actions) # get envs which are done dones_idx = done.reshape(-1, 1).nonzer...
def test_auto_reset():
env = VectorizedEnvironment(make_env, 4, auto_reset=True) env.reset() while True: actions = np.asarray([env.action_space.sample() for _ in range(4)]) obs, _, done, info = env.step(actions) # get envs which are done dones_idx = done.reshape(-1, 1).nonzero()[0] assert l...
_ in range(n_envs)]) obs, r, done, _ = env.step(actions) assert obs.shape == (n_envs, 4) assert r.shape == (n_envs, ) assert done.shape == (n_envs, ) env.close() def test_auto_reset():
64
64
190
5
59
NickLucche/avalanche
tests/test_vectorized_env.py
Python
test_auto_reset
test_auto_reset
86
108
86
86
0994cf878235415aa586e88e99a70fe8e14e9a6b
bigcode/the-stack
train
76aed9349248ccbc41dc3651
train
function
def test_env_different(): try: env = gym.make('PongDeterministic-v4') except Exception as e: pytest.skip( "Install `pip install gym[atari]` to run this test + download atari ROMs as explained here https://github.com/openai/atari-py#roms.") env = VectorizedEnvironment(env, 3, auto...
def test_env_different():
try: env = gym.make('PongDeterministic-v4') except Exception as e: pytest.skip( "Install `pip install gym[atari]` to run this test + download atari ROMs as explained here https://github.com/openai/atari-py#roms.") env = VectorizedEnvironment(env, 3, auto_reset=True) # init ob...
() for _ in range(2)]) vobs, r, dones, _ = venv.step(actions) obs, r, done, _ = env.step(actions[0]) assert vobs.shape[1:] == obs.shape assert type(vobs) is torch.Tensor def test_env_different():
66
66
221
6
59
NickLucche/avalanche
tests/test_vectorized_env.py
Python
test_env_different
test_env_different
143
160
143
143
2656a02a751caf7c8f2fe6b079ac711954fa9e6e
bigcode/the-stack
train
c5a14f9c1417a50bb3a3d31f
train
function
def test_env_wrapping(): try: env = gym.make('Pong-v4') except Exception as e: pytest.skip( "Install `pip install gym[atari]` to run this test + download atari ROMs as explained here https://github.com/openai/atari-py#roms.") env = RGB2GrayWrapper(env) env = CropObservationWr...
def test_env_wrapping():
try: env = gym.make('Pong-v4') except Exception as e: pytest.skip( "Install `pip install gym[atari]` to run this test + download atari ROMs as explained here https://github.com/openai/atari-py#roms.") env = RGB2GrayWrapper(env) env = CropObservationWrapper(env, resize_shape=(...
(4): if idx in dones_idx: assert 'terminal_observation' in info[idx] assert info[idx]['terminal_observation'].shape == obs[idx].shape # terminal obs different from initial one assert sum(info[idx]['terminal_observation'] - obs[idx]) != 0 ...
97
97
325
6
91
NickLucche/avalanche
tests/test_vectorized_env.py
Python
test_env_wrapping
test_env_wrapping
111
140
111
111
a3ba5212207a4936449ebc7e13db460699fa6c1d
bigcode/the-stack
train
a5bde576c43a34385f426298
train
class
class CustomTestEnv(Env): def __init__(self): self.observation_space = gym.spaces.Discrete(1) self.action_space = gym.spaces.Discrete(10) def step(self, action): return np.float32(float(action)), action, 0., {'action': action} def reset(self): return np.float32(1.)
class CustomTestEnv(Env):
def __init__(self): self.observation_space = gym.spaces.Discrete(1) self.action_space = gym.spaces.Discrete(10) def step(self, action): return np.float32(float(action)), action, 0., {'action': action} def reset(self): return np.float32(1.)
VectorizedEnvironment import numpy as np import ray from avalanche.training.strategies.reinforcement_learning.env_wrappers import Array2Tensor, FrameStackingWrapper, RGB2GrayWrapper, CropObservationWrapper import torch from gym import Env import gym.spaces class CustomTestEnv(Env):
64
64
79
7
56
NickLucche/avalanche
tests/test_vectorized_env.py
Python
CustomTestEnv
CustomTestEnv
12
22
12
13
b63c43a3de6717b6e115f63f0ac0eb2d8c801880
bigcode/the-stack
train
8310e5c4f344e233246ff6f7
train
function
def make_env(kwargs=dict()): return gym.make('CartPole-v1', **kwargs)
def make_env(kwargs=dict()):
return gym.make('CartPole-v1', **kwargs)
aces.Discrete(1) self.action_space = gym.spaces.Discrete(10) def step(self, action): return np.float32(float(action)), action, 0., {'action': action} def reset(self): return np.float32(1.) def make_env(kwargs=dict()):
63
64
19
6
57
NickLucche/avalanche
tests/test_vectorized_env.py
Python
make_env
make_env
25
26
25
25
33f69d3eb85974be3d41d8aebe4d42f79a47496e
bigcode/the-stack
train
624bb76ea1bdc059f2903452
train
function
def test_atari_wrapped(): try: env = gym.make('PongNoFrameskip-v4') except Exception as e: pytest.skip( "Install `pip install gym[atari]` to run this test + download atari ROMs as explained here https://github.com/openai/atari-py#roms.") wrappers = [AtariPreprocessing, FrameStack...
def test_atari_wrapped():
try: env = gym.make('PongNoFrameskip-v4') except Exception as e: pytest.skip( "Install `pip install gym[atari]` to run this test + download atari ROMs as explained here https://github.com/openai/atari-py#roms.") wrappers = [AtariPreprocessing, FrameStackingWrapper] env = Vect...
pong actions ['NOOP', 'FIRE', 'RIGHT', 'LEFT', 'RIGHTFIRE', 'LEFTFIRE'] actions = np.array([0, 2, 3], dtype=np.int32).reshape(3, 1) obs, _, done, info = env.step(actions) for i in range(obs.shape[0]-1): for j in range(i+1, obs.shape[0]): assert np.abs(np.sum(obs[i]-o...
117
117
392
7
110
NickLucche/avalanche
tests/test_vectorized_env.py
Python
test_atari_wrapped
test_atari_wrapped
163
197
163
163
df037aa4968263121f7849c69a0fe62decb3e880
bigcode/the-stack
train
e773bac839df49e6914e698a
train
function
def test_with_env_object(): env = gym.make('CartPole-v1') env = VectorizedEnvironment(env, 1, ray_kwargs={'num_cpus': 1}) assert len(env.actors) == 1 ref = env.actors[0].environment.remote() env = ray.get(ref) assert isinstance(env, gym.Env)
def test_with_env_object():
env = gym.make('CartPole-v1') env = VectorizedEnvironment(env, 1, ray_kwargs={'num_cpus': 1}) assert len(env.actors) == 1 ref = env.actors[0].environment.remote() env = ray.get(ref) assert isinstance(env, gym.Env)
def reset(self): return np.float32(1.) def make_env(kwargs=dict()): return gym.make('CartPole-v1', **kwargs) def test_no_env(): with pytest.raises(AssertionError): env = VectorizedEnvironment(make_env, 0) def test_with_env_object():
64
64
76
6
58
NickLucche/avalanche
tests/test_vectorized_env.py
Python
test_with_env_object
test_with_env_object
34
40
34
34
d1ba89b351a21aeac2f5af9a3a5b7b25d1bd4184
bigcode/the-stack
train
ab67521f33532d27ff96b684
train
function
def test_no_env(): with pytest.raises(AssertionError): env = VectorizedEnvironment(make_env, 0)
def test_no_env():
with pytest.raises(AssertionError): env = VectorizedEnvironment(make_env, 0)
) def step(self, action): return np.float32(float(action)), action, 0., {'action': action} def reset(self): return np.float32(1.) def make_env(kwargs=dict()): return gym.make('CartPole-v1', **kwargs) def test_no_env():
64
64
25
5
59
NickLucche/avalanche
tests/test_vectorized_env.py
Python
test_no_env
test_no_env
29
31
29
29
cd36541a81d063d829954f8fa61eff916ca73fcc
bigcode/the-stack
train
03cea035368ef85381ce1341
train
function
@pytest.mark.parametrize('n_envs', [1, 2, 3]) def test_multiple_envs_loop(n_envs: int): env = VectorizedEnvironment(make_env, n_envs, auto_reset=False) obs = env.reset() assert obs.shape == (n_envs, 4) done = [False] while not any(done): actions = np.asarray([env.action_space.sample() fo...
@pytest.mark.parametrize('n_envs', [1, 2, 3]) def test_multiple_envs_loop(n_envs: int):
env = VectorizedEnvironment(make_env, n_envs, auto_reset=False) obs = env.reset() assert obs.shape == (n_envs, 4) done = [False] while not any(done): actions = np.asarray([env.action_space.sample() for _ in range(n_envs)]) obs, r, done, _ = env.step(actions) assert obs.shape ...
, ray_kwargs={'num_cpus': n_cpu}) obs = env.reset() assert obs.shape == (n_envs, 4) env.close() @pytest.mark.parametrize('n_envs', [1, 2, 3]) def test_multiple_envs_loop(n_envs: int):
64
64
149
30
34
NickLucche/avalanche
tests/test_vectorized_env.py
Python
test_multiple_envs_loop
test_multiple_envs_loop
70
83
70
71
816d619d2ccaee7babab9c4f02f490c226974d7c
bigcode/the-stack
train
d885f4f785a9d2d3c68a0096
train
function
@pytest.mark.parametrize('shuffle', [True, False]) def test_custom_env_rollout(shuffle: bool): from avalanche.training.strategies.reinforcement_learning.buffers import Step, Rollout n_steps = 10 n_envs = 7 env = CustomTestEnv() env = VectorizedEnvironment(env, n_envs, auto_reset=True) steps = ...
@pytest.mark.parametrize('shuffle', [True, False]) def test_custom_env_rollout(shuffle: bool):
from avalanche.training.strategies.reinforcement_learning.buffers import Step, Rollout n_steps = 10 n_envs = 7 env = CustomTestEnv() env = VectorizedEnvironment(env, n_envs, auto_reset=True) steps = [] action = np.arange(n_envs).reshape(-1, 1) obs, r, done, _ = env.step(action) obs...
assert torch.sum(obs[0]-obs[1]).item() != 0 and torch.sum(obs[0]-obs[2] ).item() != 0 and torch.sum(obs[1]-obs[2]).item() != 0 env.close() @pytest.mark.parametrize('shuffle', [True, False]) def test_custom_env_rollout(shuffle: bool):
79
79
266
22
57
NickLucche/avalanche
tests/test_vectorized_env.py
Python
test_custom_env_rollout
test_custom_env_rollout
200
226
200
201
3782ecf1e44d648432a2472a437fcd92fe4e33d8
bigcode/the-stack
train
7c5b0892d83cb8f8735b9cc4
train
function
@pytest.mark.parametrize(['n_envs', 'n_cpu'], [[2, 3], [1, 2]]) def test_multiple_envs_reset(n_envs: int, n_cpu: int): env = VectorizedEnvironment( make_env, n_envs, ray_kwargs={'num_cpus': n_cpu}) obs = env.reset() assert obs.shape == (n_envs, 4) env.close()
@pytest.mark.parametrize(['n_envs', 'n_cpu'], [[2, 3], [1, 2]]) def test_multiple_envs_reset(n_envs: int, n_cpu: int):
env = VectorizedEnvironment( make_env, n_envs, ray_kwargs={'num_cpus': n_cpu}) obs = env.reset() assert obs.shape == (n_envs, 4) env.close()
.ndarray) # assert obs.shape[0] == 1 and obs.shape[-1] == 3 @pytest.mark.parametrize(['n_envs', 'n_cpu'], [[2, 3], [1, 2]]) def test_multiple_envs_reset(n_envs: int, n_cpu: int):
64
64
89
41
22
NickLucche/avalanche
tests/test_vectorized_env.py
Python
test_multiple_envs_reset
test_multiple_envs_reset
61
67
61
62
95792b4295a9e25ff6bbc88bc94a41d4e43f0f70
bigcode/the-stack
train
5e0208a16416e4021c26b1b4
train
class
class GeneralizedNormal(distribution.Distribution): """The Generalized Normal distribution. The Generalized Normal (or Generalized Gaussian) generalizes the Normal distribution with an additional shape parameter. It is parameterized by location `loc`, scale `scale` and shape `power`. #### Mathematical detai...
class GeneralizedNormal(distribution.Distribution):
"""The Generalized Normal distribution. The Generalized Normal (or Generalized Gaussian) generalizes the Normal distribution with an additional shape parameter. It is parameterized by location `loc`, scale `scale` and shape `power`. #### Mathematical details The probability density function (pdf) is, ...
# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing ...
256
256
2,370
9
247
bourov/probability
tensorflow_probability/python/distributions/generalized_normal.py
Python
GeneralizedNormal
GeneralizedNormal
44
286
44
44
fa204451d16c636ad7a224b4a1489252e6187521
bigcode/the-stack
train
483b8a82e78838f757c62121
train
class
class CostOverTime(DynamicPlugin): def __init__(self): super().__init__() @staticmethod def id(): return "cost_over_time" @staticmethod def name(): return "Cost Over Time" @staticmethod def position(): return 10 @staticmethod def category(): ...
class CostOverTime(DynamicPlugin):
def __init__(self): super().__init__() @staticmethod def id(): return "cost_over_time" @staticmethod def name(): return "Cost Over Time" @staticmethod def position(): return 10 @staticmethod def category(): return "Performance Analysis" ...
import numpy as np from dash import dcc, html from dash.exceptions import PreventUpdate import dash_bootstrap_components as dbc import plotly.graph_objs as go from deepcave.plugins.dynamic_plugin import DynamicPlugin from deepcave.utils.logs import get_logger from deepcave.utils.styled_plotty import get_color from deep...
109
256
1,395
8
101
PhMueller/DeepCAVE
deepcave/plugins/cost_over_time.py
Python
CostOverTime
CostOverTime
15
239
15
15
86197634582283e1acaccb6e4ff7b3d9bdc1430c
bigcode/the-stack
train
f314211ec44f2104fe9629ea
train
function
def get_weather(query, **kwargs): f = urllib2.urlopen(URL) json_string = f.read() f.close() location = json.loads(json_string) location_city = location['city'] place = 'location[\'city\']' + ", " + location['country_code'] owm = pyowm.OWM(API_KEY) w = owm.weather_at_place(place).get_weat...
def get_weather(query, **kwargs):
f = urllib2.urlopen(URL) json_string = f.read() f.close() location = json.loads(json_string) location_city = location['city'] place = 'location[\'city\']' + ", " + location['country_code'] owm = pyowm.OWM(API_KEY) w = owm.weather_at_place(place).get_weather() temp = w.get_temperatur...
import pyowm URL = "http://freegeoip.net/json/" API_KEY = "70e52321050523bb149227183e2ec5e5" FEEDBACK_FORMAT = "The temperature today is %d degrees fahrenheit, with %s" def get_weather(query, **kwargs):
64
64
133
8
56
elc1798/alice
app/commands/get_weather/__init__.py
Python
get_weather
get_weather
14
27
14
14
fcadfce4549c65b9d2dc2dcde594fa5786956c46
bigcode/the-stack
train
7172772cb1a3832c109d5752
train
class
class cae(object): def __init__(self, params): params = self.add_params(params) self.params = params self.make_dirs() self.construct_graph() """Adds additional parameters that can be computed from given parameters""" def add_params(self, params): params["weight_save_filename"]...
class cae(object):
def __init__(self, params): params = self.add_params(params) self.params = params self.make_dirs() self.construct_graph() """Adds additional parameters that can be computed from given parameters""" def add_params(self, params): params["weight_save_filename"] = params["output_l...
import tensorflow as tf import numpy as np import os import utils.get_data as get_data import utils.mem_utils as mem_utils import utils.entropy_funcs as ef class cae(object):
41
256
4,947
4
36
rzarcone/CAEs
cae_model.py
Python
cae
cae
8
377
8
8
9b6a648a4764fc64133837874d2acbc52fafba47
bigcode/the-stack
train
fa3fe9770cfbd85fbe47305f
train
function
def asset_pairs(args): """Get available asset pairs.""" # Parameters to pass to the API api_params = {} res = query_api('public', 'AssetPairs', api_params, args) # initialize a list to store the parsed assets pairs assetlist = [] for assetpair in res: if assetpair.endswith('.d'):...
def asset_pairs(args):
"""Get available asset pairs.""" # Parameters to pass to the API api_params = {} res = query_api('public', 'AssetPairs', api_params, args) # initialize a list to store the parsed assets pairs assetlist = [] for assetpair in res: if assetpair.endswith('.d'): continue ...
Apache License, Version 2.0. See the LICENSE file. """ from collections import OrderedDict from clikraken.api.api_utils import query_api from clikraken.clikraken_utils import _tabulate as tabulate from clikraken.clikraken_utils import csv def asset_pairs(args):
64
64
183
5
58
summatix/clikraken
src/clikraken/api/public/asset_pairs.py
Python
asset_pairs
asset_pairs
19
44
19
19
10e06a1c722733fa1654b913c614bd33e7e5bdab
bigcode/the-stack
train
a367a0104039a2e74406a40f
train
function
def merge(arr, temp_arr, left, mid, right): i = left # Starting index of left subarray j = mid + 1 # Starting index of right subarray k = left # Starting index of to be sorted subarray inv_count = 0 # Conditions are checked to make sure that # i and j don't exceed their # ...
def merge(arr, temp_arr, left, mid, right):
i = left # Starting index of left subarray j = mid + 1 # Starting index of right subarray k = left # Starting index of to be sorted subarray inv_count = 0 # Conditions are checked to make sure that # i and j don't exceed their # subarray limits. while i <= mid and j...
subarray inv_count += _mergeSort(arr, temp_arr, mid + 1, right) # It will merge two subarrays in # a sorted subarray inv_count += merge(arr, temp_arr, left, mid, right) return inv_count # This function will merge two subarrays ...
96
96
323
13
82
abhishek-parashar/Right-From-Scratch
python-dsa/count inversions.py
Python
merge
merge
56
99
56
56
46d906015cb1f8792d83a23eaa11e8a47888e1e9
bigcode/the-stack
train
a3d38e80dba4f09e794ef55b
train
function
def mergeSort(arr, n): # A temp_arr is created to store # sorted array in merge function temp_arr = [0]*n return _mergeSort(arr, temp_arr, 0, n-1)
def mergeSort(arr, n): # A temp_arr is created to store # sorted array in merge function
temp_arr = [0]*n return _mergeSort(arr, temp_arr, 0, n-1)
21:32 2020 @author: Abhishek Parashar """ # Python 3 program to count inversions in an array # Function to Use Inversion Count def mergeSort(arr, n): # A temp_arr is created to store # sorted array in merge function
64
64
51
25
38
abhishek-parashar/Right-From-Scratch
python-dsa/count inversions.py
Python
mergeSort
mergeSort
11
15
11
13
5f2f3658c7add1064d0353e0c65efac1c183f7fc
bigcode/the-stack
train
ffa8bb85b0d6a2e75d8340a5
train
function
def _mergeSort(arr, temp_arr, left, right): # A variable inv_count is used to store # inversion counts in each recursive call inv_count = 0 # We will make a recursive call if and only if # we have more than one elements if left < right: # mid is calculated to divide...
def _mergeSort(arr, temp_arr, left, right): # A variable inv_count is used to store # inversion counts in each recursive call
inv_count = 0 # We will make a recursive call if and only if # we have more than one elements if left < right: # mid is calculated to divide the array into two subarrays # Floor division is must in case of python mid = (left + right)//2 # It will cal...
return _mergeSort(arr, temp_arr, 0, n-1) # This Function will use MergeSort to count inversions def _mergeSort(arr, temp_arr, left, right): # A variable inv_count is used to store # inversion counts in each recursive call
65
66
223
35
29
abhishek-parashar/Right-From-Scratch
python-dsa/count inversions.py
Python
_mergeSort
_mergeSort
19
52
19
23
360d0025a7dffbfc7a8227d636589889c8af6862
bigcode/the-stack
train
e340139c5b889f47bd90c5cf
train
class
class NFCTransactionDialog(Factory.AnimatedPopup): mode = OptionProperty('send', options=('send','receive')) scanner = ObjectProperty(None) def __init__(self, **kwargs): # Delayed Init global NFCSCanner if NFCSCanner is None: from electrum_xazab.gui.kivy.nfc_scanner im...
class NFCTransactionDialog(Factory.AnimatedPopup):
mode = OptionProperty('send', options=('send','receive')) scanner = ObjectProperty(None) def __init__(self, **kwargs): # Delayed Init global NFCSCanner if NFCSCanner is None: from electrum_xazab.gui.kivy.nfc_scanner import NFCScanner self.scanner = NFCSCanner ...
from kivy.properties import ObjectProperty, OptionProperty from kivy.factory import Factory class NFCTransactionDialog(Factory.AnimatedPopup):
28
69
230
10
17
nunumichael/electrum-xazab
electrum_xazab/gui/kivy/uix/dialogs/nfc_transaction.py
Python
NFCTransactionDialog
NFCTransactionDialog
5
36
5
6
e771b6c706aa4b947d320c4f760851f21f32dc0b
bigcode/the-stack
train
3b8a02c4b8585375e1067508
train
function
def prune(photons): return photons[(photons['probability'] > 0) & (photons['mirror_shell'] == 0)]
def prune(photons):
return photons[(photons['probability'] > 0) & (photons['mirror_shell'] == 0)]
.0002, 'order_selector': gratingeff}) hrmafile = os.path.join(os.path.dirname(marxs.optics.__file__), 'hrma.par') marxm = MarxMirror(hrmafile, position=np.array([0., 0, 0])) def prune(photons):
63
64
32
6
57
hamogu/x-raysurveyor
xraysurveyor.py
Python
prune
prune
37
38
37
37
e317bd5c037b853b0cd99f7b547976f4ae27337a
bigcode/the-stack
train
5a87c085778d6af5e15394c1
train
class
class State(StateBase): # pylint: disable=too-many-instance-attributes def __init__(self, root_dir=None, tmp_dir=None, dvcignore=None): from .cache import Cache super().__init__() self.tmp_dir = tmp_dir self.root_dir = root_dir self.dvcignore = dvcignore if not tm...
class State(StateBase): # pylint: disable=too-many-instance-attributes
def __init__(self, root_dir=None, tmp_dir=None, dvcignore=None): from .cache import Cache super().__init__() self.tmp_dir = tmp_dir self.root_dir = root_dir self.dvcignore = dvcignore if not tmp_dir: return config = {"eviction_policy": "least-r...
"""Manages state database used for checksum caching.""" import logging import os from abc import ABC, abstractmethod from dvc.fs.local import LocalFileSystem from dvc.fs.system import inode as get_inode from dvc.fs.utils import relpath from .hash_info import HashInfo from .utils import get_mtime_and_size logger = l...
239
256
877
17
221
dtrifiro/dvc
dvc/objects/state.py
Python
State
State
49
181
49
49
e5b79e86751c2f58daaa4cbe8db8845a343d9f70
bigcode/the-stack
train
61af5ee90a40f59cf9573496
train
class
class StateNoop(StateBase): def close(self): pass def save(self, path, fs, hash_info): pass def get(self, path, fs): # pylint: disable=unused-argument return None, None def save_link(self, path, fs): pass
class StateNoop(StateBase):
def close(self): pass def save(self, path, fs, hash_info): pass def get(self, path, fs): # pylint: disable=unused-argument return None, None def save_link(self, path, fs): pass
pass @abstractmethod def save(self, path, fs, hash_info): pass @abstractmethod def get(self, path, fs): pass @abstractmethod def save_link(self, path, fs): pass class StateNoop(StateBase):
64
64
68
7
56
dtrifiro/dvc
dvc/objects/state.py
Python
StateNoop
StateNoop
35
46
35
35
d28f0190ede66b563adff58e878745019408f4f3
bigcode/the-stack
train
d750489a8c23ed6470fa5759
train
class
class StateBase(ABC): @abstractmethod def close(self): pass @abstractmethod def save(self, path, fs, hash_info): pass @abstractmethod def get(self, path, fs): pass @abstractmethod def save_link(self, path, fs): pass
class StateBase(ABC): @abstractmethod
def close(self): pass @abstractmethod def save(self, path, fs, hash_info): pass @abstractmethod def get(self, path, fs): pass @abstractmethod def save_link(self, path, fs): pass
.fs.local import LocalFileSystem from dvc.fs.system import inode as get_inode from dvc.fs.utils import relpath from .hash_info import HashInfo from .utils import get_mtime_and_size logger = logging.getLogger(__name__) class StateBase(ABC): @abstractmethod
64
64
74
11
53
dtrifiro/dvc
dvc/objects/state.py
Python
StateBase
StateBase
17
32
17
18
32271dc64f0493942e6c9c38e741540527c94960
bigcode/the-stack
train
4e8f463e0b11ccc01af40c08
train
class
class DialogReportCodes(QtWidgets.QDialog): """ Get reports on coded text/images/audio/video using a range of variables: Files, Cases, Coders, text limiters, Attribute limiters. Export reports as plain text, ODT, html or csv. Text context of a coded text portion is shown in the thord splitt...
class DialogReportCodes(QtWidgets.QDialog):
""" Get reports on coded text/images/audio/video using a range of variables: Files, Cases, Coders, text limiters, Attribute limiters. Export reports as plain text, ODT, html or csv. Text context of a coded text portion is shown in the thord splitter pan in a text edit. Case matrix i...
.treeWidget.addTopLevelItem(top_item) remove_items.append(c) for item in remove_items: codes.remove(item) # add codes as children for c in codes: it = QtWidgets.QTreeWidgetItemIterator(self.ui.treeWidget) item = it.value() while it...
256
256
14,434
9
247
WPFilmmaker/QualCoder
qualcoder/reports.py
Python
DialogReportCodes
DialogReportCodes
780
2,184
780
780
96a443c26f2cc817674b5704fb37d99370da390b
bigcode/the-stack
train
8564879455c60552fda23905
train
class
class ToolTip_EventFilter(QtCore.QObject): """ Used to add a dynamic tooltip for the textEdit. wording to left click for context of text in the original file are displayed in the tooltip. """ text_results = None def setTextResults(self, text_results): self.text_results = text_results ...
class ToolTip_EventFilter(QtCore.QObject):
""" Used to add a dynamic tooltip for the textEdit. wording to left click for context of text in the original file are displayed in the tooltip. """ text_results = None def setTextResults(self, text_results): self.text_results = text_results def eventFilter(self, receiver, event): ...
0: self.case_ids = tmp_ids[1:] self.ui.pushButton_caseselect.setToolTip(tooltip) self.ui.label_selections.setText(tooltip) else: self.ui.label_selections.setText(_("Cases selected: All")) self.display_counts() class ToolTip_EventFilter...
70
70
234
10
60
WPFilmmaker/QualCoder
qualcoder/reports.py
Python
ToolTip_EventFilter
ToolTip_EventFilter
2,187
2,211
2,187
2,187
a7d02521cbed90e8b569f46dfcdf1a29f047414f
bigcode/the-stack
train
55b4e90e2df7c8876c3a4d33
train
function
def exception_handler(exception_type, value, tb_obj): """ Global exception handler useful in GUIs. tb_obj: exception.__traceback__ """ tb = '\n'.join(traceback.format_tb(tb_obj)) text = 'Traceback (most recent call last):\n' + tb + '\n' + exception_type.__name__ + ': ' + str(value) print(text) l...
def exception_handler(exception_type, value, tb_obj):
""" Global exception handler useful in GUIs. tb_obj: exception.__traceback__ """ tb = '\n'.join(traceback.format_tb(tb_obj)) text = 'Traceback (most recent call last):\n' + tb + '\n' + exception_type.__name__ + ': ' + str(value) print(text) logger.error(_("Uncaught exception: ") + text) QtWi...
from GUI.ui_dialog_report_code_frequencies import Ui_Dialog_reportCodeFrequencies from report_attributes import DialogSelectAttributeParameters from select_items import DialogSelectItems path = os.path.abspath(os.path.dirname(__file__)) logger = logging.getLogger(__name__) def exception_handler(exception_type, value, ...
64
64
112
11
53
WPFilmmaker/QualCoder
qualcoder/reports.py
Python
exception_handler
exception_handler
53
60
53
53
b6aec4299225fb1a96d73910500ec2ce8d4d9009
bigcode/the-stack
train
658e857ae1963d938bf34318
train
class
class DialogReportCoderComparisons(QtWidgets.QDialog): """ Compare coded text sequences between coders using Cohen's Kappa. """ app = None parent_textEdit = None coders = [] selected_coders = [] categories = [] code_names = [] file_summaries = [] comparisons = "" def __init__(s...
class DialogReportCoderComparisons(QtWidgets.QDialog):
""" Compare coded text sequences between coders using Cohen's Kappa. """ app = None parent_textEdit = None coders = [] selected_coders = [] categories = [] code_names = [] file_summaries = [] comparisons = "" def __init__(self, app, parent_textEdit): sys.excepthook = e...
_items.append(c) for item in remove_items: codes.remove(item) # add codes as children for c in codes: it = QtWidgets.QTreeWidgetItemIterator(self.ui.treeWidget) item = it.value() while item: #logger.debug("for c in codes, item:" + ...
256
256
3,723
11
245
WPFilmmaker/QualCoder
qualcoder/reports.py
Python
DialogReportCoderComparisons
DialogReportCoderComparisons
460
777
460
460
6c4a71442ee39e881c5f9ff777e0e9c49d422ebb
bigcode/the-stack
train
f5b26d33aa91f7bab6df4685
train
class
class DialogReportCodeFrequencies(QtWidgets.QDialog): """ Show code and category frequencies, overall and for each coder. This is for text, image and av coding. """ app = None dialog_list = None parent_textEdit = None coders = [] categories = [] codes = [] coded = [] # to refactor ...
class DialogReportCodeFrequencies(QtWidgets.QDialog):
""" Show code and category frequencies, overall and for each coder. This is for text, image and av coding. """ app = None dialog_list = None parent_textEdit = None coders = [] categories = [] codes = [] coded = [] # to refactor name file_ids = [] def __init__(self, app, pa...
import traceback from PyQt5 import QtGui, QtWidgets, QtCore from PyQt5.Qt import QHelpEvent from PyQt5.QtCore import Qt, QTextCodec from PyQt5.QtGui import QBrush from GUI.ui_dialog_report_codings import Ui_Dialog_reportCodings from GUI.ui_dialog_report_comparisons import Ui_Dialog_reportComparisons from GUI.ui_dialo...
256
256
3,763
11
245
WPFilmmaker/QualCoder
qualcoder/reports.py
Python
DialogReportCodeFrequencies
DialogReportCodeFrequencies
63
457
63
63
5d2b839a942edcb6da4134cd13918c4dfdafeac1
bigcode/the-stack
train
b5d3e13299c289a4279d432d
train
class
class AlarmError(threading.Thread): def __init__(self, q_errors,): super(AlarmError, self).__init__() self.q_errors = q_errors self.msgs = [] self.names = [] def run(self): while True: if not ALARM_ON_OFF: break if len(self.msgs)...
class AlarmError(threading.Thread):
def __init__(self, q_errors,): super(AlarmError, self).__init__() self.q_errors = q_errors self.msgs = [] self.names = [] def run(self): while True: if not ALARM_ON_OFF: break if len(self.msgs) >= 1000: self.msgs....
b >= DEAD_SECONDS and self.last_platform: # 超过100s没收到心跳 for to in to_list: sendTemplateSMS(to, [get_ip(), self.last_platform], BLOCK_TEMPLATE_ID) break if self.q_hb.qsize(): msg = self.q_hb.get() self.last_hb = msg['hb'] # ...
109
110
369
7
102
benno0810/CryptoArbitrage
Arbitrage_Spot/dquant/common/alarms.py
Python
AlarmError
AlarmError
73
132
73
73
03f161b647e64c0d710865f3275136056f1adaa8
bigcode/the-stack
train
832983cb367b84faff00d678
train
class
class BlockAlarm(threading.Thread): def __init__(self, q_hb, last_hb=int(time.time())): super(BlockAlarm, self).__init__() self.last_hb = last_hb self.last_platform = None self.q_hb = q_hb def run(self): '''记录上一次心跳的时间。如果100s没收到心跳,报警''' while True: i...
class BlockAlarm(threading.Thread):
def __init__(self, q_hb, last_hb=int(time.time())): super(BlockAlarm, self).__init__() self.last_hb = last_hb self.last_platform = None self.q_hb = q_hb def run(self): '''记录上一次心跳的时间。如果100s没收到心跳,报警''' while True: if not ALARM_ON_OFF: ...
', 'HuoBiPro': 'hb', "SpotDiff": 'maker2', } def deal_name(name_list): txt = '' for name in set(name_list): txt = '{}_{}'.format(NAMES[name], txt) return txt[:-1] class BlockAlarm(threading.Thread):
65
65
217
7
58
benno0810/CryptoArbitrage
Arbitrage_Spot/dquant/common/alarms.py
Python
BlockAlarm
BlockAlarm
44
70
44
44
4aaf274549dba7c54aad651ebddb1193e4130ce2
bigcode/the-stack
train
e4dc9d3ac93c2656e566a2c4
train
function
def deal_name(name_list): txt = '' for name in set(name_list): txt = '{}_{}'.format(NAMES[name], txt) return txt[:-1]
def deal_name(name_list):
txt = '' for name in set(name_list): txt = '{}_{}'.format(NAMES[name], txt) return txt[:-1]
ALARM_ON_OFF = True NAMES = { 'Binance': 'bin', 'Bitfinex': 'bfx', 'OKEX': 'ok', 'HuoBiPro': 'hb', "SpotDiff": 'maker2', } def deal_name(name_list):
64
64
37
6
58
benno0810/CryptoArbitrage
Arbitrage_Spot/dquant/common/alarms.py
Python
deal_name
deal_name
36
41
36
37
263b1dd50a52fde465e7e4fd8a1005cbcefed73c
bigcode/the-stack
train
943693ca678212f07c7e5504
train
function
def timeout_alarm(ip, platform, api): ''' 【深浅科技】ip: {1},平台:{2},接口:{3},超时了。 ''' if not ALARM_ON_OFF: return for to in to_list: sendTemplateSMS(to, [ip, platform, api], TIMEOUT_TEMPLATE_ID)
def timeout_alarm(ip, platform, api):
''' 【深浅科技】ip: {1},平台:{2},接口:{3},超时了。 ''' if not ALARM_ON_OFF: return for to in to_list: sendTemplateSMS(to, [ip, platform, api], TIMEOUT_TEMPLATE_ID)
_price)/baoCang_price <= 0.3: for to in to_list: sendTemplateSMS(to, ['{}.{}'.format(get_ip(), current_price), baoCang_price], BAOCANG_TEMPLATE_ID) success = True return success def timeout_alarm(ip, platform, api):
64
64
77
9
54
benno0810/CryptoArbitrage
Arbitrage_Spot/dquant/common/alarms.py
Python
timeout_alarm
timeout_alarm
153
162
153
153
3bf0e4dfa85bd3593f28530e9778a26fb6fd6996
bigcode/the-stack
train
781a7e3627599a1d04701c91
train
function
def alarm_of_stock(current_price, baoCang_price, ttype): print('alarm_of_stock args: ', current_price, baoCang_price, ttype) success = False if ttype == 'long': if (current_price - baoCang_price)/current_price <= 0.3: for to in to_list: sendTemplateSMS(to, ['{}.{}'.forma...
def alarm_of_stock(current_price, baoCang_price, ttype):
print('alarm_of_stock args: ', current_price, baoCang_price, ttype) success = False if ttype == 'long': if (current_price - baoCang_price)/current_price <= 0.3: for to in to_list: sendTemplateSMS(to, ['{}.{}'.format(get_ip(), current_price), baoCang_price], BAOCANG_TEMPLA...
1 self.names.clear() self.names.append(times[i]['name']) if tmp > max: max = tmp if max >= MAX_ERROR: print(self.msgs) return True return False def alarm_of_stock(current_price, baoCang_price, ttype):
64
64
178
15
48
benno0810/CryptoArbitrage
Arbitrage_Spot/dquant/common/alarms.py
Python
alarm_of_stock
alarm_of_stock
135
150
135
136
1feb14d51ccd1aa211538d4dcca8e8ba010f580f
bigcode/the-stack
train
4d29ff3f3cfd7261438d60b7
train
class
class GetoptTests(unittest.TestCase): def setUp(self): self.old_posixly_correct = os.environ.get("POSIXLY_CORRECT", sentinel) if self.old_posixly_correct is not sentinel: del os.environ["POSIXLY_CORRECT"] def tearDown(self): if self.old_posixly_correct is sentinel: ...
class GetoptTests(unittest.TestCase):
def setUp(self): self.old_posixly_correct = os.environ.get("POSIXLY_CORRECT", sentinel) if self.old_posixly_correct is not sentinel: del os.environ["POSIXLY_CORRECT"] def tearDown(self): if self.old_posixly_correct is sentinel: os.environ.pop("POSIXLY_CORRECT", N...
# test_getopt.py # David Goodger <dgoodger@bigfoot.com> 2000-08-19 from test.support import verbose, run_doctest, run_unittest import unittest import getopt import os sentinel = object() class GetoptTests(unittest.TestCase):
64
256
1,714
8
56
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-3.0/Lib/test/test_getopt.py
Python
GetoptTests
GetoptTests
12
172
12
12
911bd68bdf203f27101fe70c0fab0e0ce321d07d
bigcode/the-stack
train
86f5dbadd05af64caf288722
train
function
def test_main(): run_unittest(GetoptTests)
def test_main():
run_unittest(GetoptTests)
', ''), ('--output-file', 'abc.def'), ('-x', '')] >>> args ['a1', 'a2'] """ import types m = types.ModuleType("libreftest", s) run_doctest(m, verbose) def test_main():
64
64
12
4
60
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-3.0/Lib/test/test_getopt.py
Python
test_main
test_main
175
176
175
175
5de64a219b916a377f9acb59d275799631a4d744
bigcode/the-stack
train
ed3fbbb60945115c118c1c23
train
class
class InvalidPhaseResultError(Exception): """Raised when PhaseExecutionOutcome is created with invalid phase result."""
class InvalidPhaseResultError(Exception):
"""Raised when PhaseExecutionOutcome is created with invalid phase result."""
_traceback_string(), } def get_traceback_string(self) -> Text: return ''.join( traceback.format_exception(self.exc_type, self.exc_val, self.exc_tb)) def __str__(self) -> Text: return self.exc_type.__name__ class InvalidPhaseResultError(Exception):
63
64
21
7
56
frankalicious/openhtf
openhtf/core/phase_executor.py
Python
InvalidPhaseResultError
InvalidPhaseResultError
91
92
91
91
e805335ccc16778797c025402a339677f4b58297
bigcode/the-stack
train
acc73fc8e290f977e5c2d4ac
train
class
class PhaseExecutorThread(threads.KillableThread): """Handles the execution and result of a single test phase. The phase outcome will be stored in the _phase_execution_outcome attribute once it is known (_phase_execution_outcome is None until then), and it will be a PhaseExecutionOutcome instance. """ daem...
class PhaseExecutorThread(threads.KillableThread):
"""Handles the execution and result of a single test phase. The phase outcome will be stored in the _phase_execution_outcome attribute once it is known (_phase_execution_outcome is None until then), and it will be a PhaseExecutionOutcome instance. """ daemon = True def __init__(self, phase_desc: phase_d...
is_fail_subtest(self): return self.phase_result is phase_descriptor.PhaseResult.FAIL_SUBTEST @property def is_repeat(self): return self.phase_result is phase_descriptor.PhaseResult.REPEAT @property def is_skip(self): return self.phase_result is phase_descriptor.PhaseResult.SKIP @property def...
197
197
659
11
186
frankalicious/openhtf
openhtf/core/phase_executor.py
Python
PhaseExecutorThread
PhaseExecutorThread
157
226
157
157
6928c6afacc28adb2ea74577d577ebe56529771e
bigcode/the-stack
train
375e5bb3d1f90a63c111fbbb
train
class
@attr.s(slots=True, frozen=True) class ExceptionInfo(object): """Wrap the description of a raised exception and its traceback.""" exc_type = attr.ib(type=Type[Exception]) exc_val = attr.ib(type=Exception) exc_tb = attr.ib(type=types.TracebackType) def as_base_types(self) -> Dict[Text, Text]: return { ...
@attr.s(slots=True, frozen=True) class ExceptionInfo(object):
"""Wrap the description of a raised exception and its traceback.""" exc_type = attr.ib(type=Type[Exception]) exc_val = attr.ib(type=Exception) exc_tb = attr.ib(type=types.TracebackType) def as_base_types(self) -> Dict[Text, Text]: return { 'exc_type': str(self.exc_type), 'exc_val': str(s...
action=argv.StoreInModule, target='%s.DEFAULT_PHASE_TIMEOUT_S' % __name__, help='Test phase timeout in seconds') # TODO(arsharma): Use the test state logger. _LOG = logging.getLogger(__name__) @attr.s(slots=True, frozen=True) class ExceptionInfo(object):
64
64
163
15
49
frankalicious/openhtf
openhtf/core/phase_executor.py
Python
ExceptionInfo
ExceptionInfo
68
88
68
69
db7e3abffc1cdb6b288e07c6179ed49a16ee82b4
bigcode/the-stack
train
d0eface3bdd1e6d1b3570708
train
class
@attr.s(slots=True, frozen=True) class PhaseExecutionOutcome(object): """Provide some utility and sanity around phase return values. This should not be confused with openhtf.PhaseResult. PhaseResult is an enumeration to provide user-facing valid phase return values. This tuple is used internally to track oth...
@attr.s(slots=True, frozen=True) class PhaseExecutionOutcome(object):
"""Provide some utility and sanity around phase return values. This should not be confused with openhtf.PhaseResult. PhaseResult is an enumeration to provide user-facing valid phase return values. This tuple is used internally to track other possible outcomes (timeout, exception), and to perform some sanit...
= attr.ib(type=types.TracebackType) def as_base_types(self) -> Dict[Text, Text]: return { 'exc_type': str(self.exc_type), 'exc_val': str(self.exc_val), 'exc_tb': self.get_traceback_string(), } def get_traceback_string(self) -> Text: return ''.join( traceback.format_exc...
148
149
497
16
132
frankalicious/openhtf
openhtf/core/phase_executor.py
Python
PhaseExecutionOutcome
PhaseExecutionOutcome
95
154
95
96
233f74a6f65b56079125fa6efb90e2fd986e1d14
bigcode/the-stack
train
5ab3e320287399dfcd655e59
train
class
class PhaseExecutor(object): """Encompasses the execution of the phases of a test.""" def __init__(self, test_state: 'htf_test_state.TestState'): self.test_state = test_state # This lock exists to prevent stop() calls from being ignored if called when # _execute_phase_once is setting up the next phase ...
class PhaseExecutor(object):
"""Encompasses the execution of the phases of a test.""" def __init__(self, test_state: 'htf_test_state.TestState'): self.test_state = test_state # This lock exists to prevent stop() calls from being ignored if called when # _execute_phase_once is setting up the next phase thread. self._current_pha...
def _thread_exception(self, *args) -> bool: self._phase_execution_outcome = PhaseExecutionOutcome(ExceptionInfo(*args)) self._log_exception('Phase %s raised an exception', self._phase_desc.name) return True # Never propagate exceptions upward. def join_or_die(self) -> PhaseExecutionOutcome: """Wait...
256
256
1,778
5
251
frankalicious/openhtf
openhtf/core/phase_executor.py
Python
PhaseExecutor
PhaseExecutor
229
414
229
229
01f02dd510dd106feba399ccac107553ddf2179d
bigcode/the-stack
train
1c06901b640349f0662f1089
train
function
def lazy_import(): from intersight.model.asset_subscription import AssetSubscription globals()['AssetSubscription'] = AssetSubscription
def lazy_import():
from intersight.model.asset_subscription import AssetSubscription globals()['AssetSubscription'] = AssetSubscription
ApiTypeError, ModelComposed, ModelNormal, ModelSimple, cached_property, change_keys_js_to_python, convert_js_args_to_python_args, date, datetime, file_type, none_type, validate_get_composed_info, ) def lazy_import():
64
64
26
4
60
CiscoDevNet/intersight-python
intersight/model/asset_subscription_list_all_of.py
Python
lazy_import
lazy_import
30
32
30
30
df97a4a991d909d9b9fcc0ab56e34fac4e487c9d
bigcode/the-stack
train
7f237d9b514a13510725a149
train
class
class AssetSubscriptionListAllOf(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var...
class AssetSubscriptionListAllOf(ModelNormal):
"""NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict with a c...
these properties are explicitly defined in the OpenAPI document. However, when a client uses an older version of the Intersight OpenAPI document, the server may send additional properties because the software is more recent than the client. In that case, the client may receive properties that it does not know about. S...
256
256
1,215
9
246
CiscoDevNet/intersight-python
intersight/model/asset_subscription_list_all_of.py
Python
AssetSubscriptionListAllOf
AssetSubscriptionListAllOf
35
175
35
35
00072039722cdb9f2e4b413e21b9e99e951b1d2e
bigcode/the-stack
train
6f293919662de109bc35c73f
train
function
def create_app(settings_override=None): """ Create a Flask application using the app factory pattern. :param settings_override: Override settings :return: Flask app """ app = Flask(__name__, instance_relative_config=True) app.config.from_object('config.settings') app.config.from_pyfile...
def create_app(settings_override=None):
""" Create a Flask application using the app factory pattern. :param settings_override: Override settings :return: Flask app """ app = Flask(__name__, instance_relative_config=True) app.config.from_object('config.settings') app.config.from_pyfile('settings.py', silent=True) if set...
from flask import Flask, render_template from blueprints.pages import pages def create_app(settings_override=None):
22
64
122
7
14
benhoyle/alicewebsite
alicehoyle/app.py
Python
create_app
create_app
5
29
5
5
ced21618a9c5c2eb777eba54621d187d42efb4ed
bigcode/the-stack
train
7dca8c478fbbc27b985a296e
train
function
def error_templates(app): """ Register 0 or more custom error pages (mutates the app passed in). :param app: Flask application instance :return: None """ def render_status(status): """ Render a custom template for a specific status. Source: http://stackoverflow.com/...
def error_templates(app):
""" Register 0 or more custom error pages (mutates the app passed in). :param app: Flask application instance :return: None """ def render_status(status): """ Render a custom template for a specific status. Source: http://stackoverflow.com/a/30108946 :para...
) app.register_blueprint(pages) extensions(app) return app def extensions(app): """ Register 0 or more extensions (mutates the app passed in). :param app: Flask application instance :return: None """ return None def error_templates(app):
64
64
183
5
58
benhoyle/alicewebsite
alicehoyle/app.py
Python
error_templates
error_templates
42
67
42
42
7c6f0ab83e85bcbbfdba6052eac0c88e2460c660
bigcode/the-stack
train
c09f544f1817c081750435ce
train
function
def extensions(app): """ Register 0 or more extensions (mutates the app passed in). :param app: Flask application instance :return: None """ return None
def extensions(app):
""" Register 0 or more extensions (mutates the app passed in). :param app: Flask application instance :return: None """ return None
.from_pyfile('settings.py', silent=True) if settings_override: app.config.update(settings_override) app.logger.setLevel(app.config['LOG_LEVEL']) error_templates(app) # Register blueprint(s) app.register_blueprint(pages) extensions(app) return app def extensions(app):
64
64
42
4
59
benhoyle/alicewebsite
alicehoyle/app.py
Python
extensions
extensions
32
40
32
32
430cb8f63059dad4a96237d849e7d4ab99fc17d1
bigcode/the-stack
train
7b3aea3651a1120b65a9a250
train
function
def _remove_propagation_from_route_table_item(context, route_table, gateway_id): vgws = route_table['propagating_gateways'] vgws.remove(gateway_id) if not vgws: del route_table['propagating_gateways'] db_api.update_item(context, route_table)
def _remove_propagation_from_route_table_item(context, route_table, gateway_id):
vgws = route_table['propagating_gateways'] vgws.remove(gateway_id) if not vgws: del route_table['propagating_gateways'] db_api.update_item(context, route_table)
_to_route_table_item(context, route_table, gateway_id): vgws = route_table.setdefault('propagating_gateways', []) vgws.append(gateway_id) db_api.update_item(context, route_table) def _remove_propagation_from_route_table_item(context, route_table, gateway_id):
64
64
67
19
45
NeCTAR-RC/ec2-api
ec2api/api/route_table.py
Python
_remove_propagation_from_route_table_item
_remove_propagation_from_route_table_item
680
686
680
681
b159dd334e531e740237f80f7b72fdfb26b5b123
bigcode/the-stack
train
85f62ec2ce7304b2b5b1df3d
train
function
def _get_route_target(route): if ec2utils.get_ec2_id_kind(route.get('gateway_id') or '') == 'vgw': return VPN_TARGET else: return HOST_TARGET
def _get_route_target(route):
if ec2utils.get_ec2_id_kind(route.get('gateway_id') or '') == 'vgw': return VPN_TARGET else: return HOST_TARGET
'nexthop': gateway_ip}) # NOTE(ft): gateway_ip is set to None to allow correct handling # of 0.0.0.0/0 route by Neutron. gateway_ip = None return host_routes, gateway_ip def _get_route_target(route):
64
64
43
7
56
NeCTAR-RC/ec2-api
ec2api/api/route_table.py
Python
_get_route_target
_get_route_target
652
656
652
652
1f4d930680f1d01699f21180dd6086223437d115
bigcode/the-stack
train
0961ded221824175093bb109
train
function
def enable_vgw_route_propagation(context, route_table_id, gateway_id): route_table = ec2utils.get_db_item(context, route_table_id) # NOTE(ft): AWS returns GatewayNotAttached for all invalid cases of # gateway_id value vpn_gateway = ec2utils.get_db_item(context, gateway_id) if vpn_gateway['vpc_id'] !...
def enable_vgw_route_propagation(context, route_table_id, gateway_id):
route_table = ec2utils.get_db_item(context, route_table_id) # NOTE(ft): AWS returns GatewayNotAttached for all invalid cases of # gateway_id value vpn_gateway = ec2utils.get_db_item(context, gateway_id) if vpn_gateway['vpc_id'] != route_table['vpc_id']: raise exception.GatewayNotAttached(gw_...
cleaner.addCleanup(db_api.update_item, context, rollback_route_table_state) if update_target: _update_routes_in_associated_subnets( context, cleaner, route_table, update_target=update_target) return True def enable_vgw_route_propagation(context, rout...
66
66
222
17
48
NeCTAR-RC/ec2-api
ec2api/api/route_table.py
Python
enable_vgw_route_propagation
enable_vgw_route_propagation
106
124
106
106
456599b0bcd3bd42937332eb5fcf9c99084adc09
bigcode/the-stack
train
3c11e06b74b47afc9973717a
train
function
def _create_route_table(context, vpc): route_table = {'vpc_id': vpc['id'], 'routes': [{'destination_cidr_block': vpc['cidr_block'], 'gateway_id': None}]} route_table = db_api.add_item(context, 'rtb', route_table) return route_table
def _create_route_table(context, vpc):
route_table = {'vpc_id': vpc['id'], 'routes': [{'destination_cidr_block': vpc['cidr_block'], 'gateway_id': None}]} route_table = db_api.add_item(context, 'rtb', route_table) return route_table
get_db_items() def describe_route_tables(context, route_table_id=None, filter=None): formatted_route_tables = RouteTableDescriber().describe( context, ids=route_table_id, filter=filter) return {'routeTableSet': formatted_route_tables} def _create_route_table(context, vpc):
64
64
71
10
54
NeCTAR-RC/ec2-api
ec2api/api/route_table.py
Python
_create_route_table
_create_route_table
304
309
304
304
532517d59d08ccddb76100c410605430fde1b94e
bigcode/the-stack
train