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
a5bc728c92f6162d645e2338
train
class
@tvm._ffi.register_object("tir.BufferRegion") class BufferRegion(Object): """BufferRegion node. Parameters ---------- buffer : Buffer The buffer of the buffer region region : List[Range] The region array of the buffer region """ buffer: Buffer region: List[Range] ...
@tvm._ffi.register_object("tir.BufferRegion") class BufferRegion(Object):
"""BufferRegion node. Parameters ---------- buffer : Buffer The buffer of the buffer region region : List[Range] The region array of the buffer region """ buffer: Buffer region: List[Range] def __init__(self, buffer: Buffer, region: List[Range]): self.__in...
the source code. """ def __init__(self, buffer, bounds, span=None): self.__init_handle_by_constructor__(_ffi_api.Prefetch, buffer, bounds, span) # type: ignore @tvm._ffi.register_object("tir.BufferRegion") class BufferRegion(Object):
64
64
112
17
46
BaldLee/tvm
python/tvm/tir/stmt.py
Python
BufferRegion
BufferRegion
493
510
493
494
22db4a4196e7cce1048cc19f85f92abc50c8cdea
bigcode/the-stack
train
e17f69e43c009183de502cb4
train
class
@tvm._ffi.register_object("tir.LetStmt") class LetStmt(Stmt): """LetStmt node. Parameters ---------- var : Var The variable in the binding. value : PrimExpr The value in to be binded. body : Stmt The body statement. span : Optional[Span] The location of th...
@tvm._ffi.register_object("tir.LetStmt") class LetStmt(Stmt):
"""LetStmt node. Parameters ---------- var : Var The variable in the binding. value : PrimExpr The value in to be binded. body : Stmt The body statement. span : Optional[Span] The location of this itervar in the source code. """ def __init__(self,...
from tvm.runtime import Object, const from . import _ffi_api from .buffer import Buffer from .expr import IterVar class Stmt(Object): """Base class of all the statements.""" @tvm._ffi.register_object("tir.LetStmt") class LetStmt(Stmt):
63
64
137
19
44
BaldLee/tvm
python/tvm/tir/stmt.py
Python
LetStmt
LetStmt
45
67
45
46
31a1495e4273182de5bc95b9557a18e454bf4c34
bigcode/the-stack
train
990cf2c176e46f5530bd95e6
train
class
class ForKind(IntEnum): """The kind of the for loop. note ---- ForKind can change the control flow semantics of the loop and need to be considered in all TIR passes. """ SERIAL = 0 PARALLEL = 1 VECTORIZED = 2 UNROLLED = 3 THREAD_BINDING = 4
class ForKind(IntEnum):
"""The kind of the for loop. note ---- ForKind can change the control flow semantics of the loop and need to be considered in all TIR passes. """ SERIAL = 0 PARALLEL = 1 VECTORIZED = 2 UNROLLED = 3 THREAD_BINDING = 4
of this itervar in the source code. """ def __init__(self, condition, message, body, span=None): self.__init_handle_by_constructor__( _ffi_api.AssertStmt, condition, message, body, span # type: ignore ) class ForKind(IntEnum):
64
64
86
6
58
BaldLee/tvm
python/tvm/tir/stmt.py
Python
ForKind
ForKind
95
108
95
95
31c2ae802ed97d1fd6b61116dd1f53e0afb11838
bigcode/the-stack
train
5fc64ccc9ad651c517298b19
train
class
@tvm._ffi.register_object("tir.BlockRealize") class BlockRealize(Stmt): """BlockRealize node. Parameters ---------- iter_values : List[PrimExpr] The binding values of the block var. predicate : Union[PrimExpr, bool] The predicate of the block. block : Block The block t...
@tvm._ffi.register_object("tir.BlockRealize") class BlockRealize(Stmt):
"""BlockRealize node. Parameters ---------- iter_values : List[PrimExpr] The binding values of the block var. predicate : Union[PrimExpr, bool] The predicate of the block. block : Block The block to realize span : Optional[Span] The location of this block_...
, # type: ignore iter_vars, reads, writes, name_hint, body, init, alloc_buffers, match_buffers, annotations, span, ) # type: ignore @tvm._ffi.register_object("tir.BlockRealize") class BlockR...
69
69
230
20
48
BaldLee/tvm
python/tvm/tir/stmt.py
Python
BlockRealize
BlockRealize
617
656
617
618
78cb63f4c21538be4662fd063d7e6b11fe30639b
bigcode/the-stack
train
b46bd5d023c0361c4e09e402
train
class
@tvm._ffi.register_object("tir.Store") class Store(Stmt): """Store node. Parameters ---------- buffer_var : Var The buffer Variable. value : PrimExpr The value we want to store. index : PrimExpr The index in the store expression. predicate : PrimExpr The s...
@tvm._ffi.register_object("tir.Store") class Store(Stmt):
"""Store node. Parameters ---------- buffer_var : Var The buffer Variable. value : PrimExpr The value we want to store. index : PrimExpr The index in the store expression. predicate : PrimExpr The store predicate. span : Optional[Span] The loc...
""" def __init__(self, condition, body, span=None): self.__init_handle_by_constructor__( _ffi_api.While, # type: ignore condition, body, span, ) @tvm._ffi.register_object("tir.Store") class Store(Stmt):
64
64
175
16
48
BaldLee/tvm
python/tvm/tir/stmt.py
Python
Store
Store
192
219
192
193
e72b30ba2bf6642b8c80b7cad710441000e6cd72
bigcode/the-stack
train
a23c121493d96a855652b23b
train
class
@tvm._ffi.register_object("tir.ProducerRealize") class ProducerRealize(Stmt): """ProducerRealize node. Parameters ---------- producer : DataProducer The data producer. bounds : list of range The bound of realize condition : PrimExpr The realize condition. body : S...
@tvm._ffi.register_object("tir.ProducerRealize") class ProducerRealize(Stmt):
"""ProducerRealize node. Parameters ---------- producer : DataProducer The data producer. bounds : list of range The bound of realize condition : PrimExpr The realize condition. body : Stmt The realize body storage_scope : str The storage scop...
_key, value, body, span=None): self.__init_handle_by_constructor__( _ffi_api.AttrStmt, node, attr_key, value, body, span # type: ignore ) @tvm._ffi.register_object("tir.ProducerRealize") class ProducerRealize(Stmt):
64
64
181
21
43
BaldLee/tvm
python/tvm/tir/stmt.py
Python
ProducerRealize
ProducerRealize
371
405
371
372
55c6ecb9ba74da19883f068bd06f885c49abbaf7
bigcode/the-stack
train
1191a14552f6fdd653d98d56
train
function
def test_pad_gpu(test_case): arg_dict = OrderedDict() arg_dict["device_type"] = ["gpu"] arg_dict["flow_op"] = [flow.pad] arg_dict["tf_op"] = [tf.pad] arg_dict["input_shape"] = [(2, 2, 1, 3), (1, 1, 2, 3)] arg_dict["op_args"] = [ Args( [([0, 0], [0, 0], [1, 2], [1, 1])], ...
def test_pad_gpu(test_case):
arg_dict = OrderedDict() arg_dict["device_type"] = ["gpu"] arg_dict["flow_op"] = [flow.pad] arg_dict["tf_op"] = [tf.pad] arg_dict["input_shape"] = [(2, 2, 1, 3), (1, 1, 2, 3)] arg_dict["op_args"] = [ Args( [([0, 0], [0, 0], [1, 2], [1, 1])], tf.constant([([0, 0], ...
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 permissions and limitations under the License. """ import os from collections import OrderedDict import numpy as np import oneflow as flow import tensorflow ...
88
88
294
7
80
Sodu-Qinming/Oneflow
oneflow/python/test/ops/test_pad.py
Python
test_pad_gpu
test_pad_gpu
25
46
25
25
cd36e9a8803d68bd428a2e529176407859f7840e
bigcode/the-stack
train
9d86fe03f4227bda61f4b384
train
function
def test_pad_cpu(test_case): arg_dict = OrderedDict() arg_dict["device_type"] = ["cpu"] arg_dict["flow_op"] = [flow.pad] arg_dict["tf_op"] = [tf.pad] arg_dict["input_shape"] = [(2, 3, 4, 3), (5, 1, 1, 1)] arg_dict["op_args"] = [ Args( [([0, 0], [0, 0], [1, 2], [1, 1])], ...
def test_pad_cpu(test_case):
arg_dict = OrderedDict() arg_dict["device_type"] = ["cpu"] arg_dict["flow_op"] = [flow.pad] arg_dict["tf_op"] = [tf.pad] arg_dict["input_shape"] = [(2, 3, 4, 3), (5, 1, 1, 1)] arg_dict["op_args"] = [ Args( [([0, 0], [0, 0], [1, 2], [1, 1])], tf.constant([([0, 0], ...
Args( [([0, 0], [0, 0], [10, 20], [0, 0])], tf.constant([([0, 0], [0, 0], [10, 20], [0, 0])]), ), ] for arg in GenArgDict(arg_dict): CompareOpWithTensorFlow(**arg) def test_pad_cpu(test_case):
88
88
294
7
81
Sodu-Qinming/Oneflow
oneflow/python/test/ops/test_pad.py
Python
test_pad_cpu
test_pad_cpu
49
70
49
49
9511e0bb5f1d1d7a133d10ee87123167d2d1bf8d
bigcode/the-stack
train
8d8014fc69878424f9267a86
train
class
class HomePageTest(TestCase): def setUp(self): self.factory = RequestFactory() def test_root_url_resolves_to_home_page_view(self): request = self.factory.get(reverse('swu:home')) response = HomeView.as_view()(request) self.assertEqual(response.status_code, 200) def test_ho...
class HomePageTest(TestCase):
def setUp(self): self.factory = RequestFactory() def test_root_url_resolves_to_home_page_view(self): request = self.factory.get(reverse('swu:home')) response = HomeView.as_view()(request) self.assertEqual(response.status_code, 200) def test_home_page_returns_correct_html(se...
from django.core.urlresolvers import reverse from django.test import TestCase, RequestFactory from ..views import HomeView class HomePageTest(TestCase):
33
64
147
7
25
Sasha-P/swsite
apps/swu/tests/test_views.py
Python
HomePageTest
HomePageTest
7
23
7
8
ee02bd2398c70c5cb0ff628750ba4621209a7c0c
bigcode/the-stack
train
063825dba8c702dc4059ef3a
train
function
def get_listing_operations(service, region=None, selected_operations=()): """Return a list of API calls which (probably) list resources created by the user in the given service (in contrast to AWS-managed or default resources)""" client = get_client(service, region) operations = [] for operation in ...
def get_listing_operations(service, region=None, selected_operations=()):
"""Return a list of API calls which (probably) list resources created by the user in the given service (in contrast to AWS-managed or default resources)""" client = get_client(service, region) operations = [] for operation in client.meta.service_model.operation_names: if not any(operation.st...
the first CamelCased word in an API call""" client = get_client(service) return set(re.sub("([A-Z])", "_\\1", x).split("_")[1] for x in client.meta.method_to_api_mapping.values()) def get_listing_operations(service, region=None, selected_operations=()):
64
64
209
13
51
pwaller/aws_list_all
aws_list_all/introspection.py
Python
get_listing_operations
get_listing_operations
226
248
226
226
e7899711715b81804451eb02ae93bcf6640e9c3b
bigcode/the-stack
train
c2c79053c949b72ddae6ee7c
train
function
def get_services(): """Return a list of all service names where listable resources can be present""" return [service for service in boto3.Session().get_available_services() if service not in SERVICE_BLACKLIST]
def get_services():
"""Return a list of all service names where listable resources can be present""" return [service for service in boto3.Session().get_available_services() if service not in SERVICE_BLACKLIST]
DescribeSubscription', 'ListProtections'], 'ssm': ['DescribeAssociation', 'DescribeMaintenanceWindowSchedule', 'ListComplianceItems'], 'waf-regional': ['ListActivatedRulesInRuleGroup'], 'workdocs': ['DescribeActivities'], # need to be root } def get_services():
64
64
44
4
60
pwaller/aws_list_all
aws_list_all/introspection.py
Python
get_services
get_services
214
216
214
214
71028348328ddf96a23a7de5d21c61a780d72935
bigcode/the-stack
train
1a0d1d26be186557211b22ff
train
function
def get_verbs(service): """Return a list of "Verbs" given a boto3 service client. A "Verb" in this context is the first CamelCased word in an API call""" client = get_client(service) return set(re.sub("([A-Z])", "_\\1", x).split("_")[1] for x in client.meta.method_to_api_mapping.values())
def get_verbs(service):
"""Return a list of "Verbs" given a boto3 service client. A "Verb" in this context is the first CamelCased word in an API call""" client = get_client(service) return set(re.sub("([A-Z])", "_\\1", x).split("_")[1] for x in client.meta.method_to_api_mapping.values())
docs': ['DescribeActivities'], # need to be root } def get_services(): """Return a list of all service names where listable resources can be present""" return [service for service in boto3.Session().get_available_services() if service not in SERVICE_BLACKLIST] def get_verbs(service):
64
64
84
6
58
pwaller/aws_list_all
aws_list_all/introspection.py
Python
get_verbs
get_verbs
219
223
219
219
3bc7751c75eb7e28072785a47b21b90e276f44a6
bigcode/the-stack
train
a5a7b20e0ce0b3416384320d
train
class
class TagField(CharField): """ A "special" character field that actually works as a relationship to tags "under the hood". This exposes a space-separated string of tags, but does the splitting/reordering/etc. under the hood. """ def __init__(self, *args, **kwargs): kwargs['max_length'] =...
class TagField(CharField):
""" A "special" character field that actually works as a relationship to tags "under the hood". This exposes a space-separated string of tags, but does the splitting/reordering/etc. under the hood. """ def __init__(self, *args, **kwargs): kwargs['max_length'] = kwargs.get('max_length', 2...
""" A custom Model Field for tagging. """ from django.db.models import signals from django.db.models.fields import CharField from django.utils.translation import gettext_lazy as _ from tagging import settings from tagging.forms import TagField as TagFormField from tagging.models import Tag from tagging.utils import ed...
72
232
775
6
65
randlet/django-tagging
tagging/fields.py
Python
TagField
TagField
14
116
14
14
99f5aa40d7d7be10056e21a57267183e7fbbace9
bigcode/the-stack
train
409c5915310a1b4e38e0f6d4
train
function
def test_from_ndarray(): # See sympy/sympy#7465 assert Matrix(numpy.array([1, 2, 3])) == Matrix([1, 2, 3]) assert Matrix(numpy.array([[1, 2, 3]])) == Matrix([[1, 2, 3]]) assert Matrix(numpy.array([[1, 2, 3], [4, 5, 6]])) == \ Matrix([[1, 2, 3], [4, 5, 6]]) assert Matrix(numpy.array([x, y, z]...
def test_from_ndarray(): # See sympy/sympy#7465
assert Matrix(numpy.array([1, 2, 3])) == Matrix([1, 2, 3]) assert Matrix(numpy.array([[1, 2, 3]])) == Matrix([[1, 2, 3]]) assert Matrix(numpy.array([[1, 2, 3], [4, 5, 6]])) == \ Matrix([[1, 2, 3], [4, 5, 6]]) assert Matrix(numpy.array([x, y, z])) == Matrix([x, y, z]) pytest.raises(NotImpleme...
)])).all() def test_array_coeersion(): A = MatrixSymbol('A', 2, 2) assert numpy.array(A)[1][0] == MatrixElement(A, 1, 0) def test_from_ndarray(): # See sympy/sympy#7465
64
64
181
18
46
diofant/omg
diofant/tests/external/test_numpy.py
Python
test_from_ndarray
test_from_ndarray
285
293
285
286
322f6f04d6b1754bd55821f75dda22f5385cc9f1
bigcode/the-stack
train
34a128873dadb01d4fa110db
train
function
def test_arrays(): one = Integer(1) zero = Integer(0) X = numpy.array([one, zero, zero]) Y = one*X X = numpy.array([Symbol('a') + Rational(1, 2)]) Y = X + X assert Y == numpy.array([1 + 2*Symbol('a')]) Y = Y + 1 assert Y == numpy.array([2 + 2*Symbol('a')]) Y = X - X assert Y ...
def test_arrays():
one = Integer(1) zero = Integer(0) X = numpy.array([one, zero, zero]) Y = one*X X = numpy.array([Symbol('a') + Rational(1, 2)]) Y = X + X assert Y == numpy.array([1 + 2*Symbol('a')]) Y = Y + 1 assert Y == numpy.array([2 + 2*Symbol('a')]) Y = X - X assert Y == numpy.array([0])...
numpy.array(one + x) == numpy.array(1 + x) X = numpy.array([one, zero, zero]) assert (X == numpy.array([one, zero, zero])).all() assert (X == numpy.array([one, 0, 0])).all() def test_arrays():
64
64
120
4
60
diofant/omg
diofant/tests/external/test_numpy.py
Python
test_arrays
test_arrays
82
93
82
82
b5db89f618bbef3e59f28afc5c9b4d8e639522f4
bigcode/the-stack
train
c8ca1a177aff1efa7fab29c4
train
function
def test_sympify(): assert sympify(numpy.float128(1.1)) == Float(1.1)
def test_sympify():
assert sympify(numpy.float128(1.1)) == Float(1.1)
([x, y, z])) == Matrix([x, y, z]) pytest.raises(NotImplementedError, lambda: Matrix(numpy.array([[ [1, 2], [3, 4]], [[5, 6], [7, 8]]]))) def test_sympify():
63
64
27
6
57
diofant/omg
diofant/tests/external/test_numpy.py
Python
test_sympify
test_sympify
296
297
296
296
6eb560a304438ef6534318d7bc2e58897644ed15
bigcode/the-stack
train
d8475f806d929d3a8aa9c7d1
train
function
def test_symarray(): """Test creation of numpy arrays of diofant symbols.""" syms = symbols('_0,_1,_2') s1 = symarray('', 3) s2 = symarray('', 3) numpy.testing.assert_array_equal(s1, numpy.array(syms, dtype=object)) assert s1[0] == s2[0] a = symarray('a', 3) b = symarray('b', 3) ass...
def test_symarray():
"""Test creation of numpy arrays of diofant symbols.""" syms = symbols('_0,_1,_2') s1 = symarray('', 3) s2 = symarray('', 3) numpy.testing.assert_array_equal(s1, numpy.array(syms, dtype=object)) assert s1[0] == s2[0] a = symarray('a', 3) b = symarray('b', 3) assert not a[0] == b[0] ...
.array([[xh**2, xh*yh, xh*zh], [yh*xh, yh**2, yh*zh], [zh*xh, zh*yh, zh**2]]) actual = f(xh, yh, zh) assert numpy.allclose(actual, expected) def test_lambdify_transl(): for sym, mat in NUMPY_TRANSLATIONS.items(): assert sym in dir(diofant) ...
107
107
359
5
102
diofant/omg
diofant/tests/external/test_numpy.py
Python
test_symarray
test_symarray
245
272
245
245
6fb182dcb32447da510f21cddaf529e113ba9d07
bigcode/the-stack
train
3f69c10248bfcb452e39d296
train
function
def test_matrix2numpy_conversion(): a = Matrix([[1, 2, sin(x)], [x**2, x, Rational(1, 2)]]) b = numpy.array([[1, 2, sin(x)], [x**2, x, Rational(1, 2)]]) assert (matrix2numpy(a) == b).all() assert matrix2numpy(a).dtype == numpy.dtype('object') c = matrix2numpy(Matrix([[1, 2], [10, 20]]), dtype='int8...
def test_matrix2numpy_conversion():
a = Matrix([[1, 2, sin(x)], [x**2, x, Rational(1, 2)]]) b = numpy.array([[1, 2, sin(x)], [x**2, x, Rational(1, 2)]]) assert (matrix2numpy(a) == b).all() assert matrix2numpy(a).dtype == numpy.dtype('object') c = matrix2numpy(Matrix([[1, 2], [10, 20]]), dtype='int8') d = matrix2numpy(Matrix([[1, ...
2) assert a[0, 0] == 1 assert a[0, 1] == x**2 assert a[1, 0] == 3*sin(x) assert a[1, 1] == 0 def test_matrix2numpy_conversion():
64
64
163
7
56
diofant/omg
diofant/tests/external/test_numpy.py
Python
test_matrix2numpy_conversion
test_matrix2numpy_conversion
188
197
188
188
865bebba600879ebc06b8695a5f0be86a5057123
bigcode/the-stack
train
413bc1bdef74defce95f2625
train
function
@conserve_mpmath_dps def test_lambdify(): mpmath.mp.dps = 16 sin02 = mpmath.mpf('0.198669330795061215459412627') f = lambdify(x, sin(x), 'numpy') prec = 1e-15 assert -prec < f(0.2) - sin02 < prec with pytest.raises(TypeError): f(x)
@conserve_mpmath_dps def test_lambdify():
mpmath.mp.dps = 16 sin02 = mpmath.mpf('0.198669330795061215459412627') f = lambdify(x, sin(x), 'numpy') prec = 1e-15 assert -prec < f(0.2) - sin02 < prec with pytest.raises(TypeError): f(x)
0])).all() assert (Float('0.5') + numpy.array( [2*x, 0]) == numpy.array([2*x + Float('0.5'), Float('0.5')])).all() @conserve_mpmath_dps def test_lambdify():
64
64
100
16
48
diofant/omg
diofant/tests/external/test_numpy.py
Python
test_lambdify
test_lambdify
209
217
209
210
d4fa3e1365afa7238f16d21685c900badfcda754
bigcode/the-stack
train
de779b27e827a092df10822e
train
function
def test_Matrix_mul(): M = Matrix([[1, 2, 3], [x, y, x]]) m = numpy.array([[2, 4], [x, 6], [x, z**2]]) assert M*m == Matrix([ [ 2 + 5*x, 16 + 3*z**2], [2*x + x*y + x**2, 4*x + 6*y + x*z**2], ]) assert m*M == Matrix([ [ 2 + 4*x, 4 + 4*y, 6 + 4*x], ...
def test_Matrix_mul():
M = Matrix([[1, 2, 3], [x, y, x]]) m = numpy.array([[2, 4], [x, 6], [x, z**2]]) assert M*m == Matrix([ [ 2 + 5*x, 16 + 3*z**2], [2*x + x*y + x**2, 4*x + 6*y + x*z**2], ]) assert m*M == Matrix([ [ 2 + 4*x, 4 + 4*y, 6 + 4*x], [ 7*x, ...
2]]) assert m + M == Matrix([[3, 5, 7], [2*x, y + 5, x + 6], [2*y + x, y - 50, z*x + z**2]]) assert M + m == M.add(m) def test_Matrix_mul():
66
66
223
6
60
diofant/omg
diofant/tests/external/test_numpy.py
Python
test_Matrix_mul
test_Matrix_mul
152
167
152
152
3feeb02b77c34e99f805ba1b6f4cbcd854e2498e
bigcode/the-stack
train
4d3a399487e58208650597f4
train
function
def test_vectorize(): assert (numpy.vectorize( sin)([1, 2, 3]) == numpy.array([sin(1), sin(2), sin(3)])).all()
def test_vectorize():
assert (numpy.vectorize( sin)([1, 2, 3]) == numpy.array([sin(1), sin(2), sin(3)])).all()
_2_1') assert a3d[0, 0, 0] == a000 assert a3d[1, 2, 0] == a120 assert a3d[1, 2, 1] == a121 def test_vectorize():
64
64
43
5
58
diofant/omg
diofant/tests/external/test_numpy.py
Python
test_vectorize
test_vectorize
275
277
275
275
a3694815b1c317dda564818304fc60b4ddc8f7fb
bigcode/the-stack
train
1ac7de2aff0894e091c0ec00
train
function
def test_Matrix2(): a = numpy.array([[2, 4], [5, 1]]) assert Matrix(a) == Matrix([[2, 4], [5, 1]]) assert Matrix(a) != Matrix([[2, 4], [5, 2]]) a = numpy.array([[sin(2), 4], [5, 1]]) assert Matrix(a) == Matrix([[sin(2), 4], [5, 1]]) assert Matrix(a) != Matrix([[sin(0), 4], [5, 1]])
def test_Matrix2():
a = numpy.array([[2, 4], [5, 1]]) assert Matrix(a) == Matrix([[2, 4], [5, 1]]) assert Matrix(a) != Matrix([[2, 4], [5, 2]]) a = numpy.array([[sin(2), 4], [5, 1]]) assert Matrix(a) == Matrix([[sin(2), 4], [5, 1]]) assert Matrix(a) != Matrix([[sin(0), 4], [5, 1]])
1]])).all() m = Matrix([[sin(x), x**2], [5, 2/x]]) assert (numpy.array(m.subs({x: 2})) == numpy.array([[sin(2), 4], [5, 1]])).all() def test_Matrix2():
64
64
122
6
58
diofant/omg
diofant/tests/external/test_numpy.py
Python
test_Matrix2
test_Matrix2
135
141
135
135
bb4e99f62de9855ce4a4ac79250e5d16615aff11
bigcode/the-stack
train
9fccea8ef24ff57b49166c5d
train
function
def test_conversion2(): a = 2*list2numpy([x**2, x]) b = list2numpy([2*x**2, 2*x]) assert (a == b).all() one = Integer(1) zero = Integer(0) X = list2numpy([one, zero, zero]) Y = one*X X = list2numpy([Symbol('a') + Rational(1, 2)]) Y = X + X assert Y == numpy.array([1 + 2*Symbol('...
def test_conversion2():
a = 2*list2numpy([x**2, x]) b = list2numpy([2*x**2, 2*x]) assert (a == b).all() one = Integer(1) zero = Integer(0) X = list2numpy([one, zero, zero]) Y = one*X X = list2numpy([Symbol('a') + Rational(1, 2)]) Y = X + X assert Y == numpy.array([1 + 2*Symbol('a')]) Y = Y + 1 ...
([x**2, x]) # looks like an array? assert isinstance(a, numpy.ndarray) assert a[0] == x**2 assert a[1] == x assert len(a) == 2 # yes, it's the array def test_conversion2():
64
64
164
5
58
diofant/omg
diofant/tests/external/test_numpy.py
Python
test_conversion2
test_conversion2
106
121
106
106
5ba623195a5093415e4f70d945d28d76464b1471
bigcode/the-stack
train
8b18ff394d7468675a655ea4
train
function
def test_array_coeersion(): A = MatrixSymbol('A', 2, 2) assert numpy.array(A)[1][0] == MatrixElement(A, 1, 0)
def test_array_coeersion():
A = MatrixSymbol('A', 2, 2) assert numpy.array(A)[1][0] == MatrixElement(A, 1, 0)
d[1, 2, 1] == a121 def test_vectorize(): assert (numpy.vectorize( sin)([1, 2, 3]) == numpy.array([sin(1), sin(2), sin(3)])).all() def test_array_coeersion():
64
64
42
7
57
diofant/omg
diofant/tests/external/test_numpy.py
Python
test_array_coeersion
test_array_coeersion
280
282
280
280
2f74410447b020fac86a1b9cbdfaa7a28c4d619e
bigcode/the-stack
train
da7dd7066a660d01457d6b41
train
function
def test_basics(): one = Integer(1) zero = Integer(0) assert numpy.array(1) == numpy.array(one) assert numpy.array([one]) == numpy.array([one]) assert numpy.array([x]) == numpy.array([x]) assert numpy.array(x) == numpy.array(Symbol('x')) assert numpy.array(one + x) == numpy.array(1 + x) ...
def test_basics():
one = Integer(1) zero = Integer(0) assert numpy.array(1) == numpy.array(one) assert numpy.array([one]) == numpy.array([one]) assert numpy.array([x]) == numpy.array([x]) assert numpy.array(x) == numpy.array(Symbol('x')) assert numpy.array(one + x) == numpy.array(1 + x) X = numpy.array([o...
*sin(y), 5, Integer(5)]), ] for x in diofant_objs: for y in numpy_objs: s(x, y) # now some random tests, that test particular problems and that also # check that the results of the operations are correct def test_basics():
64
64
132
5
58
diofant/omg
diofant/tests/external/test_numpy.py
Python
test_basics
test_basics
68
79
68
68
e676b6369a53645e955d5ee2abe0572f13f7fb36
bigcode/the-stack
train
35c8f7d568e6e9750005ae4d
train
function
def test_systematic_basic(): def s(diofant_object, numpy_array): # pylint: disable=pointless-statement diofant_object + numpy_array numpy_array + diofant_object diofant_object - numpy_array numpy_array - diofant_object diofant_object * numpy_array numpy_array ...
def test_systematic_basic():
def s(diofant_object, numpy_array): # pylint: disable=pointless-statement diofant_object + numpy_array numpy_array + diofant_object diofant_object - numpy_array numpy_array - diofant_object diofant_object * numpy_array numpy_array * diofant_object diof...
.matexpr import MatrixElement from diofant.utilities.decorator import conserve_mpmath_dps from diofant.utilities.lambdify import NUMPY_TRANSLATIONS __all__ = () numpy = pytest.importorskip('numpy') # first, systematically check, that all operations are implemented and don't # raise an exception def test_systematic...
74
74
249
6
67
diofant/omg
diofant/tests/external/test_numpy.py
Python
test_systematic_basic
test_systematic_basic
30
62
30
30
16146c50e2aa3f2f4c930091fb55ef9a3dba2985
bigcode/the-stack
train
e325e4c9af98e1d052525232
train
function
def test_matrix2numpy(): a = matrix2numpy(Matrix([[1, x**2], [3*sin(x), 0]])) assert isinstance(a, numpy.ndarray) assert a.shape == (2, 2) assert a[0, 0] == 1 assert a[0, 1] == x**2 assert a[1, 0] == 3*sin(x) assert a[1, 1] == 0
def test_matrix2numpy():
a = matrix2numpy(Matrix([[1, x**2], [3*sin(x), 0]])) assert isinstance(a, numpy.ndarray) assert a.shape == (2, 2) assert a[0, 0] == 1 assert a[0, 1] == x**2 assert a[1, 0] == 3*sin(x) assert a[1, 1] == 0
5, 6], [7, 8, 9]]) matarr = MatArray() assert Matrix(matarr) == Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) def test_matrix2numpy():
63
64
103
6
57
diofant/omg
diofant/tests/external/test_numpy.py
Python
test_matrix2numpy
test_matrix2numpy
178
185
178
178
5d1e18cbf6414024b730c6bda84e03182a2a13ca
bigcode/the-stack
train
1a57fcc88aa3e2678e7ef89a
train
function
def test_Matrix1(): m = Matrix([[x, x**2], [5, 2/x]]) assert (numpy.array(m.subs({x: 2})) == numpy.array([[2, 4], [5, 1]])).all() m = Matrix([[sin(x), x**2], [5, 2/x]]) assert (numpy.array(m.subs({x: 2})) == numpy.array([[sin(2), 4], [5, 1]])).all()
def test_Matrix1():
m = Matrix([[x, x**2], [5, 2/x]]) assert (numpy.array(m.subs({x: 2})) == numpy.array([[2, 4], [5, 1]])).all() m = Matrix([[sin(x), x**2], [5, 2/x]]) assert (numpy.array(m.subs({x: 2})) == numpy.array([[sin(2), 4], [5, 1]])).all()
([2 + 2*Symbol('a')]) Y = X - X assert Y == numpy.array([0]) def test_list2numpy(): assert (numpy.array([x**2, x]) == list2numpy([x**2, x])).all() def test_Matrix1():
64
64
109
6
58
diofant/omg
diofant/tests/external/test_numpy.py
Python
test_Matrix1
test_Matrix1
128
132
128
128
79dc2c22877d5dedf693bc5b0193ef19a6483d4a
bigcode/the-stack
train
6dacf021d8543fe3f315255a
train
function
def test_sympyissue_3728(): assert (Rational(1, 2)*numpy.array([2*x, 0]) == numpy.array([x, 0])).all() assert (Rational(1, 2) + numpy.array( [2*x, 0]) == numpy.array([2*x + Rational(1, 2), Rational(1, 2)])).all() assert (Float('0.5')*numpy.array([2*x, 0]) == numpy.array([Float('1.0')*x, 0])).all() ...
def test_sympyissue_3728():
assert (Rational(1, 2)*numpy.array([2*x, 0]) == numpy.array([x, 0])).all() assert (Rational(1, 2) + numpy.array( [2*x, 0]) == numpy.array([2*x + Rational(1, 2), Rational(1, 2)])).all() assert (Float('0.5')*numpy.array([2*x, 0]) == numpy.array([Float('1.0')*x, 0])).all() assert (Float('0.5') + nu...
20]]), dtype='int8') d = matrix2numpy(Matrix([[1, 2], [10, 20]]), dtype='float64') assert c.dtype == numpy.dtype('int8') assert d.dtype == numpy.dtype('float64') def test_sympyissue_3728():
64
64
167
9
55
diofant/omg
diofant/tests/external/test_numpy.py
Python
test_sympyissue_3728
test_sympyissue_3728
200
206
200
200
357b665aa68175a5a4378bbc2ee19eee901681fc
bigcode/the-stack
train
7a8ba534c8dcfb8972b0c81a
train
function
def test_lambdify_matrix_multi_input(): M = Matrix([[x**2, x*y, x*z], [y*x, y**2, y*z], [z*x, z*y, z**2]]) f = lambdify((x, y, z), M, [{'ImmutableMatrix': numpy.array}, 'numpy']) xh, yh, zh = 1.0, 2.0, 3.0 expected = numpy.array([[xh**2, xh*yh, xh*zh], ...
def test_lambdify_matrix_multi_input():
M = Matrix([[x**2, x*y, x*z], [y*x, y**2, y*z], [z*x, z*y, z**2]]) f = lambdify((x, y, z), M, [{'ImmutableMatrix': numpy.array}, 'numpy']) xh, yh, zh = 1.0, 2.0, 3.0 expected = numpy.array([[xh**2, xh*yh, xh*zh], [yh*xh, yh**2, yh*zh], ...
dify(x, Matrix([[x, 2*x], [1, 2]]), [{'ImmutableMatrix': numpy.array}, 'numpy']) assert (f(1) == numpy.array([[1, 2], [1, 2]])).all() def test_lambdify_matrix_multi_input():
64
64
165
10
54
diofant/omg
diofant/tests/external/test_numpy.py
Python
test_lambdify_matrix_multi_input
test_lambdify_matrix_multi_input
225
236
225
225
ca73ea5212a6b824e317593271556ae0ff2047da
bigcode/the-stack
train
888ff928d10d9bd3772e3d4b
train
function
def test_Matrix_sum(): M = Matrix([[1, 2, 3], [x, y, x], [2*y, -50, z*x]]) m = numpy.array([[2, 3, 4], [x, 5, 6], [x, y, z**2]]) assert M + m == Matrix([[3, 5, 7], [2*x, y + 5, x + 6], [2*y + x, y - 50, z*x + z**2]]) assert m + M == Matrix([[3, 5, 7], [2*x, y + 5, x + 6], [2*y + x, y - 50, z*x + z**2]])...
def test_Matrix_sum():
M = Matrix([[1, 2, 3], [x, y, x], [2*y, -50, z*x]]) m = numpy.array([[2, 3, 4], [x, 5, 6], [x, y, z**2]]) assert M + m == Matrix([[3, 5, 7], [2*x, y + 5, x + 6], [2*y + x, y - 50, z*x + z**2]]) assert m + M == Matrix([[3, 5, 7], [2*x, y + 5, x + 6], [2*y + x, y - 50, z*x + z**2]]) assert M + m == M....
.array([[sin(2), 4], [5, 1]]) assert Matrix(a) == Matrix([[sin(2), 4], [5, 1]]) assert Matrix(a) != Matrix([[sin(0), 4], [5, 1]]) def test_Matrix_sum():
63
64
174
6
57
diofant/omg
diofant/tests/external/test_numpy.py
Python
test_Matrix_sum
test_Matrix_sum
144
149
144
144
675130653180700819a99dc444e3c010ac02fd64
bigcode/the-stack
train
5ef9dda424fa2e4e0debe547
train
function
def test_lambdify_transl(): for sym, mat in NUMPY_TRANSLATIONS.items(): assert sym in dir(diofant) assert mat in dir(numpy)
def test_lambdify_transl():
for sym, mat in NUMPY_TRANSLATIONS.items(): assert sym in dir(diofant) assert mat in dir(numpy)
h, xh*zh], [yh*xh, yh**2, yh*zh], [zh*xh, zh*yh, zh**2]]) actual = f(xh, yh, zh) assert numpy.allclose(actual, expected) def test_lambdify_transl():
64
64
38
9
55
diofant/omg
diofant/tests/external/test_numpy.py
Python
test_lambdify_transl
test_lambdify_transl
239
242
239
239
4a7cb0051ea9eb2d5ed4fa815493825b5d0fea17
bigcode/the-stack
train
9f45dee3451caeddfbbdd5f0
train
function
def test_list2numpy(): assert (numpy.array([x**2, x]) == list2numpy([x**2, x])).all()
def test_list2numpy():
assert (numpy.array([x**2, x]) == list2numpy([x**2, x])).all()
assert Y == numpy.array([1 + 2*Symbol('a')]) Y = Y + 1 assert Y == numpy.array([2 + 2*Symbol('a')]) Y = X - X assert Y == numpy.array([0]) def test_list2numpy():
64
64
31
6
58
diofant/omg
diofant/tests/external/test_numpy.py
Python
test_list2numpy
test_list2numpy
124
125
124
124
8a7dc9b6def26163b3c71077819575bc27fcec37
bigcode/the-stack
train
6bf200eb7b2f61b8bd2921fd
train
function
def test_conversion1(): a = list2numpy([x**2, x]) # looks like an array? assert isinstance(a, numpy.ndarray) assert a[0] == x**2 assert a[1] == x assert len(a) == 2
def test_conversion1():
a = list2numpy([x**2, x]) # looks like an array? assert isinstance(a, numpy.ndarray) assert a[0] == x**2 assert a[1] == x assert len(a) == 2
assert Y == numpy.array([1 + 2*Symbol('a')]) Y = Y + 1 assert Y == numpy.array([2 + 2*Symbol('a')]) Y = X - X assert Y == numpy.array([0]) def test_conversion1():
64
64
62
5
59
diofant/omg
diofant/tests/external/test_numpy.py
Python
test_conversion1
test_conversion1
96
102
96
96
de13d455c20fa52e5c9ecee23674dcb11366dc53
bigcode/the-stack
train
1ca8806c66308307583f5d6f
train
function
def test_lambdify_numpy_matrix(): f = lambdify(x, Matrix([[x, 2*x], [1, 2]]), [{'ImmutableMatrix': numpy.array}, 'numpy']) assert (f(1) == numpy.array([[1, 2], [1, 2]])).all()
def test_lambdify_numpy_matrix():
f = lambdify(x, Matrix([[x, 2*x], [1, 2]]), [{'ImmutableMatrix': numpy.array}, 'numpy']) assert (f(1) == numpy.array([[1, 2], [1, 2]])).all()
459412627') f = lambdify(x, sin(x), 'numpy') prec = 1e-15 assert -prec < f(0.2) - sin02 < prec with pytest.raises(TypeError): f(x) def test_lambdify_numpy_matrix():
64
64
67
9
55
diofant/omg
diofant/tests/external/test_numpy.py
Python
test_lambdify_numpy_matrix
test_lambdify_numpy_matrix
220
222
220
220
ce4a9143dbcdca9687cee79f33f61710e3709f09
bigcode/the-stack
train
2ce4fce270cb6fdf9ee0d9b1
train
function
def test_Matrix_numpy_array(): class MatArray: def __array__(self): return numpy.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) matarr = MatArray() assert Matrix(matarr) == Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
def test_Matrix_numpy_array():
class MatArray: def __array__(self): return numpy.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) matarr = MatArray() assert Matrix(matarr) == Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
, 2*x + y*z**2, 3*x + x*z**2], ]) a = numpy.array([2]) assert a[0] * M == 2 * M assert M * a[0] == 2 * M def test_Matrix_numpy_array():
64
64
92
7
56
diofant/omg
diofant/tests/external/test_numpy.py
Python
test_Matrix_numpy_array
test_Matrix_numpy_array
170
175
170
170
77fef73be9209350bc2aa4a1ebe995bcdbe2b015
bigcode/the-stack
train
084b61adf1d491332ce546b7
train
function
def get_all(): coins = bithumb.get_tickers() print("[%s] - # of remote : %d \t|\t # in Cache : %d" % (datetime.now(), len(coins), len(coin_cache))) return coins
def get_all():
coins = bithumb.get_tickers() print("[%s] - # of remote : %d \t|\t # in Cache : %d" % (datetime.now(), len(coins), len(coin_cache))) return coins
% datetime.now()) else: print("[%s] - a coin disappear... .. from checking job" % datetime.now()) for coin in coin_cache: if coin not in recent: coin_cache.remove(coin) # 사라진 코인 제거 ######################################################################################...
64
64
54
4
60
kimmikimmi/python-asyncio-coin
coin_service.py
Python
get_all
get_all
42
46
42
42
f44d686654719bcbca47356907076ddfc01cfed2
bigcode/the-stack
train
658b38a1a610e13e17b8428b
train
function
def make_a_deal(): if len(bucket) == 0: return for coin in list(bucket): # thread - safe print("[%s] - there is a coin to deal \t bucket : %s" % (datetime.now(), bucket)) balance = bithumb.get_balance(coin) if balance[0] == 0: # 신규 coin 개수가 0 -> 아직 구입하지 않음. buy_if...
def make_a_deal():
if len(bucket) == 0: return for coin in list(bucket): # thread - safe print("[%s] - there is a coin to deal \t bucket : %s" % (datetime.now(), bucket)) balance = bithumb.get_balance(coin) if balance[0] == 0: # 신규 coin 개수가 0 -> 아직 구입하지 않음. buy_if_possible(balance[2...
def get_all(): coins = bithumb.get_tickers() print("[%s] - # of remote : %d \t|\t # in Cache : %d" % (datetime.now(), len(coins), len(coin_cache))) return coins ############################################################################################################################## def make_a_deal()...
64
64
116
6
58
kimmikimmi/python-asyncio-coin
coin_service.py
Python
make_a_deal
make_a_deal
50
62
50
50
eaddc6b76eef9dc2e54d7e8a8d4ec37d5762040b
bigcode/the-stack
train
c78f8df543f5e0246051317c
train
function
def buy_if_possible(total_krw, coin): recent_price = bithumb.get_current_price(coin) price_to_buy = times_for_buy * bucket[coin] if recent_price >= price_to_buy and total_krw >= price_to_buy: unit = total_krw / recent_price print("[%s] - buy\tname: %s, unit %d" % (datetime.now(), coin, unit...
def buy_if_possible(total_krw, coin):
recent_price = bithumb.get_current_price(coin) price_to_buy = times_for_buy * bucket[coin] if recent_price >= price_to_buy and total_krw >= price_to_buy: unit = total_krw / recent_price print("[%s] - buy\tname: %s, unit %d" % (datetime.now(), coin, unit)) return bithumb.buy_market_o...
0] == 0: # 신규 coin 개수가 0 -> 아직 구입하지 않음. buy_if_possible(balance[2], coin) else: sell_if_possible(balance[0], coin) ## BUYING FUNCTION############################################################################################################################ def buy_if_possible(total_...
64
64
103
11
52
kimmikimmi/python-asyncio-coin
coin_service.py
Python
buy_if_possible
buy_if_possible
67
74
67
67
6880677a5de34f8c2a13746ecd242452f59e19e6
bigcode/the-stack
train
45b4f943ad8fd65607f32f19
train
function
def check_new_coin(): recent = get_all() if len(recent) > len(coin_cache): for coin in recent: if coin not in coin_cache: print("[%s] - there is a new coin !! .. from checking job \tcoin : %s" % (datetime.now(), coin)) bucket[coin] = bithumb.get_current_price...
def check_new_coin():
recent = get_all() if len(recent) > len(coin_cache): for coin in recent: if coin not in coin_cache: print("[%s] - there is a new coin !! .. from checking job \tcoin : %s" % (datetime.now(), coin)) bucket[coin] = bithumb.get_current_price(coin) ...
umb.Bithumb(con_key, sec_key) coin_cache = bithumb.get_tickers() #coin_cache.remove("BTC") #change coin_cache if u wanna test it bucket = {} times_for_sell = 2 times_for_buy = 1.2 ############################################################################################################################## def check...
64
64
177
5
59
kimmikimmi/python-asyncio-coin
coin_service.py
Python
check_new_coin
check_new_coin
21
38
21
21
0760ef24a399af756a2869a8fb5928bfe834a08b
bigcode/the-stack
train
f3b28c9249b0f73ed8cb94c0
train
function
def sell_if_possible(unit, coin): recent_price = bithumb.get_current_price(coin) if recent_price >= times_for_sell * bucket[coin]: # 코인 값이 상장가의 2배가 되는 경우 매도. print("[%s] - sell\tname : %s unit : %d" % (datetime.now(), coin, unit)) bithumb.sell_market_order(coin, unit) bucket.clear() #...
def sell_if_possible(unit, coin):
recent_price = bithumb.get_current_price(coin) if recent_price >= times_for_sell * bucket[coin]: # 코인 값이 상장가의 2배가 되는 경우 매도. print("[%s] - sell\tname : %s unit : %d" % (datetime.now(), coin, unit)) bithumb.sell_market_order(coin, unit) bucket.clear() # clear bucket after
unit = total_krw / recent_price print("[%s] - buy\tname: %s, unit %d" % (datetime.now(), coin, unit)) return bithumb.buy_market_order(coin, unit) ## SELLING FUNCTIONS##################################################################################################################### def sell_if_possi...
64
64
99
8
55
kimmikimmi/python-asyncio-coin
coin_service.py
Python
sell_if_possible
sell_if_possible
78
84
78
78
76d12753ee49345e04e4f421d5705fb2cec9b904
bigcode/the-stack
train
1d0450261844bddff148fa3f
train
class
class AsyncSm: def __init__(self, session): super().__init__() self._session = session def createNetworkSmBypassActivationLockAttempt(self, networkId: str, ids: list): """ **Bypass activation lock attempt** https://developer.cisco.com/meraki/api-v1/#!create-network-sm-by...
class AsyncSm:
def __init__(self, session): super().__init__() self._session = session def createNetworkSmBypassActivationLockAttempt(self, networkId: str, ids: list): """ **Bypass activation lock attempt** https://developer.cisco.com/meraki/api-v1/#!create-network-sm-bypass-activation...
class AsyncSm:
4
256
8,098
4
0
sambyers/dashboard-api-python
meraki_v1/aio/api/sm.py
Python
AsyncSm
AsyncSm
1
714
1
1
e3474e0d7867597696050f110d7b02487183fc95
bigcode/the-stack
train
e758dfde5eb9bf927852d1d4
train
function
def moveFWP(wp, pos, act): mlp = int(d[i][1:]) return pos + mlp*wp[:2]
def moveFWP(wp, pos, act):
mlp = int(d[i][1:]) return pos + mlp*wp[:2]
% 360)*np.pi/180 rot = np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]) return np.concatenate([rot.dot(pos[:2]),[0]]) def moveFWP(wp, pos, act):
63
64
34
11
52
seblars/AdventOfCode2020
day12.py
Python
moveFWP
moveFWP
38
41
38
38
9df895e7fb499ffff92ec1418ff2fb954c66d3bb
bigcode/the-stack
train
d226663bfa14d5522bf9c0e5
train
function
def manhattenDist(pos): return np.abs(pos[0]) + np.abs(pos[1])
def manhattenDist(pos):
return np.abs(pos[0]) + np.abs(pos[1])
elif act[0] == 'R': move[2] = -int(act[1:]) elif act[0] == 'F': return moveF(pos, act) else: raise ValueError('Unknown act.') return pos + move def manhattenDist(pos):
64
64
22
7
56
seblars/AdventOfCode2020
day12.py
Python
manhattenDist
manhattenDist
28
29
28
28
917a01d96ddac6d8d94f4a08e08cbef454d7a8e5
bigcode/the-stack
train
f424debcc92c75c756b7a8cd
train
function
def moveF(pos, act): rot = pos[2] % 360 if rot == 0: act = 'E' + act[1:] elif rot == 90: act = 'N' + act[1:] elif rot == 180: act = 'W' + act[1:] elif rot == 270: act = 'S' + act[1:] else: raise ValueError('Unknown dir.') return moveBoat(pos, act)
def moveF(pos, act):
rot = pos[2] % 360 if rot == 0: act = 'E' + act[1:] elif rot == 90: act = 'N' + act[1:] elif rot == 180: act = 'W' + act[1:] elif rot == 270: act = 'S' + act[1:] else: raise ValueError('Unknown dir.') return moveBoat(pos, act)
import fileinput import numpy as np def moveF(pos, act):
16
64
110
7
8
seblars/AdventOfCode2020
day12.py
Python
moveF
moveF
4
12
4
4
42e1921e2df58ee2ee5143f53817adb78c27a913
bigcode/the-stack
train
6b6369eea95011dfc672610d
train
function
def moveBoat(pos, act): # pos - (x, y, dir) move = np.zeros(3,) if act[0] == 'N': move[1] = int(act[1:]) elif act[0] == 'S': move[1] = -int(act[1:]) elif act[0] == 'E': move[0] = int(act[1:]) elif act[0] == 'W': move[0] = -int(act[1:]) elif act[0] == 'L': move[2] = int(act[1:]) e...
def moveBoat(pos, act): # pos - (x, y, dir)
move = np.zeros(3,) if act[0] == 'N': move[1] = int(act[1:]) elif act[0] == 'S': move[1] = -int(act[1:]) elif act[0] == 'E': move[0] = int(act[1:]) elif act[0] == 'W': move[0] = -int(act[1:]) elif act[0] == 'L': move[2] = int(act[1:]) elif act[0] == 'R': move[2] = -int(act[1:]) el...
W' + act[1:] elif rot == 270: act = 'S' + act[1:] else: raise ValueError('Unknown dir.') return moveBoat(pos, act) def moveBoat(pos, act): # pos - (x, y, dir)
64
64
191
18
46
seblars/AdventOfCode2020
day12.py
Python
moveBoat
moveBoat
14
26
14
15
553305c1f15afaa2548656d53b637732fd4415e2
bigcode/the-stack
train
0df9a2f18ee625430ecdd7cb
train
function
def rotMat(pos): theta = (pos[2] % 360)*np.pi/180 rot = np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]) return np.concatenate([rot.dot(pos[:2]),[0]])
def rotMat(pos):
theta = (pos[2] % 360)*np.pi/180 rot = np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]) return np.concatenate([rot.dot(pos[:2]),[0]])
:]) elif act[0] == 'F': return moveF(pos, act) else: raise ValueError('Unknown act.') return pos + move def manhattenDist(pos): return np.abs(pos[0]) + np.abs(pos[1]) def rotMat(pos):
64
64
66
5
59
seblars/AdventOfCode2020
day12.py
Python
rotMat
rotMat
31
36
31
31
820c02da2c5564c7753956ed405cd82a91945e66
bigcode/the-stack
train
0ad2f1911c675da3023993ba
train
function
@pytest.mark.generator @pytest.mark.integration @pytest.mark.parametrize("document_store", ["memory"], indirect=True) @pytest.mark.parametrize("retriever", ["embedding_sbert"], indirect=True) def test_pseudo_label_generator( document_store: BaseDocumentStore, retriever: EmbeddingRetriever, question_generato...
@pytest.mark.generator @pytest.mark.integration @pytest.mark.parametrize("document_store", ["memory"], indirect=True) @pytest.mark.parametrize("retriever", ["embedding_sbert"], indirect=True) def test_pseudo_label_generator( document_store: BaseDocumentStore, retriever: EmbeddingRetriever, question_generato...
document_store.write_documents(docs_with_true_emb) psg = PseudoLabelGenerator(question_generator, retriever) train_examples = [] output, _ = psg.run(documents=document_store.get_all_documents()) assert "gpl_labels" in output for item in output["gpl_labels"]: assert "question" in item and...
@pytest.mark.generator @pytest.mark.integration @pytest.mark.parametrize("document_store", ["memory"], indirect=True) @pytest.mark.parametrize("retriever", ["embedding_sbert"], indirect=True) def test_pseudo_label_generator( document_store: BaseDocumentStore, retriever: EmbeddingRetriever, question_generato...
77
64
187
77
0
deepset-ai/Haystack
test/nodes/test_label_generator.py
Python
test_pseudo_label_generator
test_pseudo_label_generator
11
30
11
20
0f844238849ff7b1d5e00abf560092250e07e188
bigcode/the-stack
train
4db758fb739cadf315997f5a
train
function
@pytest.mark.generator @pytest.mark.integration @pytest.mark.parametrize("document_store", ["memory"], indirect=True) @pytest.mark.parametrize("retriever", ["embedding_sbert"], indirect=True) def test_pseudo_label_generator_using_question_document_pairs( document_store: BaseDocumentStore, retriever: EmbeddingRetrie...
@pytest.mark.generator @pytest.mark.integration @pytest.mark.parametrize("document_store", ["memory"], indirect=True) @pytest.mark.parametrize("retriever", ["embedding_sbert"], indirect=True) def test_pseudo_label_generator_using_question_document_pairs( document_store: BaseDocumentStore, retriever: EmbeddingRetrie...
document_store.write_documents(docs_with_true_emb) docs = [ { "question": "What is the capital of Germany?", "document": "Berlin is the capital and largest city of Germany by both area and population.", }, { "question": "What is the largest city in Ger...
(train_examples) > 0 @pytest.mark.generator @pytest.mark.integration @pytest.mark.parametrize("document_store", ["memory"], indirect=True) @pytest.mark.parametrize("retriever", ["embedding_sbert"], indirect=True) def test_pseudo_label_generator_using_question_document_pairs( document_store: BaseDocumentStore, retri...
79
79
265
72
6
deepset-ai/Haystack
test/nodes/test_label_generator.py
Python
test_pseudo_label_generator_using_question_document_pairs
test_pseudo_label_generator_using_question_document_pairs
56
82
56
62
6190478062e616c284f9c0de6adc71c8d166a877
bigcode/the-stack
train
644f3a0c89c33b422afe6167
train
function
@pytest.mark.generator @pytest.mark.integration @pytest.mark.parametrize("document_store", ["memory"], indirect=True) @pytest.mark.parametrize("retriever", ["embedding_sbert"], indirect=True) def test_pseudo_label_generator_using_question_document_pairs_batch( document_store: BaseDocumentStore, retriever: Embedding...
@pytest.mark.generator @pytest.mark.integration @pytest.mark.parametrize("document_store", ["memory"], indirect=True) @pytest.mark.parametrize("retriever", ["embedding_sbert"], indirect=True) def test_pseudo_label_generator_using_question_document_pairs_batch( document_store: BaseDocumentStore, retriever: Embedding...
document_store.write_documents(docs_with_true_emb) docs = [ { "question": "What is the capital of Germany?", "document": "Berlin is the capital and largest city of Germany by both area and population.", }, { "question": "What is the largest city in Ger...
(train_examples) > 0 @pytest.mark.generator @pytest.mark.integration @pytest.mark.parametrize("document_store", ["memory"], indirect=True) @pytest.mark.parametrize("retriever", ["embedding_sbert"], indirect=True) def test_pseudo_label_generator_using_question_document_pairs_batch( document_store: BaseDocumentStore,...
80
80
267
73
6
deepset-ai/Haystack
test/nodes/test_label_generator.py
Python
test_pseudo_label_generator_using_question_document_pairs_batch
test_pseudo_label_generator_using_question_document_pairs_batch
85
112
85
91
e0beac29ed76bb5815f9f0f55c608051bd67564a
bigcode/the-stack
train
275648a488758ee22f56e96d
train
function
@pytest.mark.generator @pytest.mark.integration @pytest.mark.parametrize("document_store", ["memory"], indirect=True) @pytest.mark.parametrize("retriever", ["embedding_sbert"], indirect=True) def test_pseudo_label_generator_batch( document_store: BaseDocumentStore, retriever: EmbeddingRetriever, question_ge...
@pytest.mark.generator @pytest.mark.integration @pytest.mark.parametrize("document_store", ["memory"], indirect=True) @pytest.mark.parametrize("retriever", ["embedding_sbert"], indirect=True) def test_pseudo_label_generator_batch( document_store: BaseDocumentStore, retriever: EmbeddingRetriever, question_ge...
document_store.write_documents(docs_with_true_emb) psg = PseudoLabelGenerator(question_generator, retriever) train_examples = [] output, _ = psg.run_batch(documents=document_store.get_all_documents()) assert "gpl_labels" in output for item in output["gpl_labels"]: assert "question" in i...
@pytest.mark.generator @pytest.mark.integration @pytest.mark.parametrize("document_store", ["memory"], indirect=True) @pytest.mark.parametrize("retriever", ["embedding_sbert"], indirect=True) def test_pseudo_label_generator_batch( document_store: BaseDocumentStore, retriever: EmbeddingRetriever, question_ge...
78
64
189
78
0
deepset-ai/Haystack
test/nodes/test_label_generator.py
Python
test_pseudo_label_generator_batch
test_pseudo_label_generator_batch
33
53
33
42
f06d571137129fca000eef31699100acdec174dd
bigcode/the-stack
train
a735455d08631d00fe16de77
train
function
@pytest.mark.generator @pytest.mark.integration @pytest.mark.parametrize("document_store", ["memory"], indirect=True) @pytest.mark.parametrize("retriever", ["embedding_sbert"], indirect=True) def test_training_and_save(retriever: EmbeddingRetriever, tmp_path: Path): train_examples = [ { "questio...
@pytest.mark.generator @pytest.mark.integration @pytest.mark.parametrize("document_store", ["memory"], indirect=True) @pytest.mark.parametrize("retriever", ["embedding_sbert"], indirect=True) def test_training_and_save(retriever: EmbeddingRetriever, tmp_path: Path):
train_examples = [ { "question": "What is the capital of Germany?", "pos_doc": "Berlin is the capital and largest city of Germany by both area and population.", "neg_doc": "The capital of Germany is the city state of Berlin.", "score": -2.2788997, }, ...
assert len(train_examples) > 0 @pytest.mark.generator @pytest.mark.integration @pytest.mark.parametrize("document_store", ["memory"], indirect=True) @pytest.mark.parametrize("retriever", ["embedding_sbert"], indirect=True) def test_training_and_save(retriever: EmbeddingRetriever, tmp_path: Path):
64
64
210
54
9
deepset-ai/Haystack
test/nodes/test_label_generator.py
Python
test_training_and_save
test_training_and_save
115
135
115
119
0760de3adecc41f2d5e3fc2d6ef7e2153d96cf03
bigcode/the-stack
train
d6f07e9cf73d46edda870e21
train
class
class Sorting: """ Class for keeping sorting methods for the also_likes functionnality together """ @staticmethod def freq_ascending_sort(data): # Data as : , returns ['<DOC_ID>', '<DOC_ID>'...] """ Description : Returns the document list sorted in ascending order of frequency Parameters...
class Sorting:
""" Class for keeping sorting methods for the also_likes functionnality together """ @staticmethod def freq_ascending_sort(data): # Data as : , returns ['<DOC_ID>', '<DOC_ID>'...] """ Description : Returns the document list sorted in ascending order of frequency Parameters : Document li...
return lines """ Exceptions """ class InvalidViewInterfaceError(AttributeError): def __init__(self, view): logger.critical("View {0} isn't valid !".format(view)) raise CriticalRunError class InvalidArgumentError(AttributeError): def __init__(self, msg): logger.critical(msg...
162
163
544
3
159
MrNeocore/Python-web-browser
utils.py
Python
Sorting
Sorting
76
122
76
76
1a8611c6131250dbd365f127ac0018d542447c71
bigcode/the-stack
train
1a1340af531eee54d199c0ec
train
class
class InvalidArgumentError(AttributeError): def __init__(self, msg): logger.critical(msg) raise CriticalRunError
class InvalidArgumentError(AttributeError):
def __init__(self, msg): logger.critical(msg) raise CriticalRunError
fd.close() logger.debug("Done") return lines """ Exceptions """ class InvalidViewInterfaceError(AttributeError): def __init__(self, view): logger.critical("View {0} isn't valid !".format(view)) raise CriticalRunError class InvalidArgumentError(AttributeError):
64
64
28
7
56
MrNeocore/Python-web-browser
utils.py
Python
InvalidArgumentError
InvalidArgumentError
54
57
54
54
0019067f031405acedb3ba59eb39392dcf822062
bigcode/the-stack
train
5cace13a78bcbf6b5cf823a6
train
function
def start_logging(level, log_file=None): """ Description : Initializes logging module for both stdout and file if requested. /!\ Handling with quiet flag not really perfect... Parameters : Verbosity level [level], variable to store logg and optional log_file """ global logger ...
def start_logging(level, log_file=None):
""" Description : Initializes logging module for both stdout and file if requested. /!\ Handling with quiet flag not really perfect... Parameters : Verbosity level [level], variable to store logg and optional log_file """ global logger logging.RESULTS = 25 logging.a...
axes.grid(False) axes.yaxis.set_visible(False) axes.xaxis.set_visible(False) def reset_plot(axes): """ Show the axis again after displaying a also_likes graph""" #axes.axis('on') axes.grid(True) axes.yaxis.set_visible(True) axes.xaxis.set_visibl...
86
87
291
9
77
MrNeocore/Python-web-browser
utils.py
Python
start_logging
start_logging
184
218
184
184
a716967524682db535404208bb95b7a7cabfd195
bigcode/the-stack
train
03cc67eb1d51932caea7e4b0
train
class
class MissingFileError(Exception): def __init__self(self, msg): logger.critical(msg) raise CriticalRunError
class MissingFileError(Exception):
def __init__self(self, msg): logger.critical(msg) raise CriticalRunError
def __init__(self, view): logger.critical("View {0} isn't valid !".format(view)) raise CriticalRunError class InvalidArgumentError(AttributeError): def __init__(self, msg): logger.critical(msg) raise CriticalRunError class MissingFileError(Exception):
64
64
28
6
57
MrNeocore/Python-web-browser
utils.py
Python
MissingFileError
MissingFileError
59
62
59
59
92dc4ec43de2b4b8556571b165d83c951d20041b
bigcode/the-stack
train
ba89071bc16500c982d996b4
train
class
class Plotting: """ Class to gathers all plotting / image display related methods """ @staticmethod def plot(axes, data): """ Description : Plots a given dataset on given axes along the first variable of this dataset Parameters : axes [axes] to plot data [data] on. Data is a Pandas Data...
class Plotting:
""" Class to gathers all plotting / image display related methods """ @staticmethod def plot(axes, data): """ Description : Plots a given dataset on given axes along the first variable of this dataset Parameters : axes [axes] to plot data [data] on. Data is a Pandas DataFrame and the fi...
es = [{"lower":1, "upper":999, "suffix":""}, {"lower":999, "upper":999999, "suffix":"K"}, {"lower":999999, "upper":999999999, "suffix":"M"}] for suffix in suffixes: if line_count > suffix["lower"] and line_count < suffix["upper"]: return "{0} {1}".format(roun...
111
111
370
4
107
MrNeocore/Python-web-browser
utils.py
Python
Plotting
Plotting
147
181
147
147
15a00947245a99c94d616b4ce6bf4de3f59db4e6
bigcode/the-stack
train
ae1da0c21ee043375b688445
train
function
def arg_parser(): """ Returns an initialized ArgumentParser object """ parser = argparse.ArgumentParser(description='Issuu data analytics software') gui_group = parser.add_mutually_exclusive_group() verbosity_group = parser.add_mutually_exclusive_group() gui_group.add_argument('--gui', action='st...
def arg_parser():
""" Returns an initialized ArgumentParser object """ parser = argparse.ArgumentParser(description='Issuu data analytics software') gui_group = parser.add_mutually_exclusive_group() verbosity_group = parser.add_mutually_exclusive_group() gui_group.add_argument('--gui', action='store_true',\ ...
atter('[%(levelname)s] : %(message)s') stream_h.setFormatter(formatter) if log_file is not None: #os.access(os.path.dirname(log_file), os.W_OK): try: file_h = logging.FileHandler(log_file) except PermissionError: logger.wa...
117
118
396
4
113
MrNeocore/Python-web-browser
utils.py
Python
arg_parser
arg_parser
220
262
220
220
74ab943110092f1f90168082a9ea2dcd3752abeb
bigcode/the-stack
train
e8f287987f2388b49e676e6f
train
class
class InvalidViewInterfaceError(AttributeError): def __init__(self, view): logger.critical("View {0} isn't valid !".format(view)) raise CriticalRunError
class InvalidViewInterfaceError(AttributeError):
def __init__(self, view): logger.critical("View {0} isn't valid !".format(view)) raise CriticalRunError
x: x, (fd.raw.read(1024*1024) for _ in repeat(None))) lines = sum(buf.count(b'\n') for buf in bufgen) fd.close() logger.debug("Done") return lines """ Exceptions """ class InvalidViewInterfaceError(AttributeError):
63
64
39
8
55
MrNeocore/Python-web-browser
utils.py
Python
InvalidViewInterfaceError
InvalidViewInterfaceError
49
52
49
49
34917985e377caf8d65a37fca93d846050a0abc9
bigcode/the-stack
train
08810b30151ef0bc51b8eebf
train
class
class InvalidTaskError(Exception): def __init__self(self, msg): logger.critical(msg) raise CriticalRunError
class InvalidTaskError(Exception):
def __init__self(self, msg): logger.critical(msg) raise CriticalRunError
Error class InvalidArgumentError(AttributeError): def __init__(self, msg): logger.critical(msg) raise CriticalRunError class MissingFileError(Exception): def __init__self(self, msg): logger.critical(msg) raise CriticalRunError class InvalidTaskError(Exception):
64
64
28
6
57
MrNeocore/Python-web-browser
utils.py
Python
InvalidTaskError
InvalidTaskError
64
67
64
64
e99d03e418c6203100d67465f62e317b28586ddf
bigcode/the-stack
train
1df0a62b5cca5f377bd621e0
train
class
class CriticalRunError(Exception): def __init__(self): logger.critical("Critical error - exiting") sys.exit(1)
class CriticalRunError(Exception):
def __init__(self): logger.critical("Critical error - exiting") sys.exit(1)
Error class MissingFileError(Exception): def __init__self(self, msg): logger.critical(msg) raise CriticalRunError class InvalidTaskError(Exception): def __init__self(self, msg): logger.critical(msg) raise CriticalRunError class CriticalRunError(Exception):
64
64
29
6
57
MrNeocore/Python-web-browser
utils.py
Python
CriticalRunError
CriticalRunError
69
72
69
69
0e7ff183bd84557b8d59cec9382ffbb338e4303e
bigcode/the-stack
train
344cecdc722f1cbb393a7b17
train
function
def check_doc_id(txt): """ Quickly checks if a document_id is likely to be valid. Return True / False depending on result """ if len(txt) == 45 and txt[12] == '-' and all(letter in ['a','b','c','d','e','f','0','1','2','3','4','5','6','7','8','9','-'] for letter in txt): return True else: ret...
def check_doc_id(txt):
""" Quickly checks if a document_id is likely to be valid. Return True / False depending on result """ if len(txt) == 45 and txt[12] == '-' and all(letter in ['a','b','c','d','e','f','0','1','2','3','4','5','6','7','8','9','-'] for letter in txt): return True else: return False
data: sorted_docs.append((doc_id, doc_weights.get(doc_id, freq))) # If we have no bias toward this document, simply use its frequency sorted_docs = sorted(sorted_docs, key=lambda x:x[1], reverse=True) return sorted_docs def check_doc_id(txt):
64
64
98
6
57
MrNeocore/Python-web-browser
utils.py
Python
check_doc_id
check_doc_id
125
130
125
125
4a737e112cbe97216fa971575511a303c1caa84f
bigcode/the-stack
train
37ebf18de1dc31d1ecce2038
train
function
def get_file_size(line_count): """ Description : Returns a human readable file line count. 38734 lines -> 39K Parameters : Raw line count [line_count] Returns : Human readable file line count (ex : 12M) """ suffixes = [{"lower":1, "upper":999, "suffix":""}, {"lower":999,...
def get_file_size(line_count):
""" Description : Returns a human readable file line count. 38734 lines -> 39K Parameters : Raw line count [line_count] Returns : Human readable file line count (ex : 12M) """ suffixes = [{"lower":1, "upper":999, "suffix":""}, {"lower":999, "upper":999999, "suffix":"K"},...
== '-' and all(letter in ['a','b','c','d','e','f','0','1','2','3','4','5','6','7','8','9','-'] for letter in txt): return True else: return False def get_file_size(line_count):
64
64
166
7
56
MrNeocore/Python-web-browser
utils.py
Python
get_file_size
get_file_size
132
145
132
132
57f373bad43d3728a9c5579d22df678c00e6de72
bigcode/the-stack
train
7db3333c7625e815d01b12fe
train
class
class ChatLink(mongoengine.Document): source_chat_id = mongoengine.LongField(required=True, null=False) target_chat_id = mongoengine.LongField(null=True) first_name = mongoengine.StringField() user_id = mongoengine.LongField(required=True, null=False) date_added = mongoengine.DateTimeField(default...
class ChatLink(mongoengine.Document):
source_chat_id = mongoengine.LongField(required=True, null=False) target_chat_id = mongoengine.LongField(null=True) first_name = mongoengine.StringField() user_id = mongoengine.LongField(required=True, null=False) date_added = mongoengine.DateTimeField(default=localized_date) @classmethod ...
import mongoengine from marvinbot.utils import localized_date class ChatLink(mongoengine.Document):
21
79
266
8
12
BotDevGroup/save_plugin
save_plugin/models.py
Python
ChatLink
ChatLink
5
46
5
6
b7d1445e4d96d2c8d1daabe487b74114cdb21d60
bigcode/the-stack
train
f3a006dbd474572e46568a1c
train
class
class AstMatchLexer(): def __init__(self, data=""): self.lexdata = "" self.lineno = 0 self.lexpos = 0 self.bracketstates = {} self.tokens = [] self.cur = 0 self.input(data) def input(self, data): self.lexdata = data self.bracketstates = {"{": [0], "[": [0], "<": [0], "(...
class AstMatchLexer():
def __init__(self, data=""): self.lexdata = "" self.lineno = 0 self.lexpos = 0 self.bracketstates = {} self.tokens = [] self.cur = 0 self.input(data) def input(self, data): self.lexdata = data self.bracketstates = {"{": [0], "[": [0], "<": [0], "(": [0]} self.bracke...
import sys, traceback from js_global import glob import ply.yacc as yacc import ply.lex as lex from ply.lex import TOKEN, LexToken # List of token names. This is always required from js_lex import LexWithPrev from js_regexpr_parse import parser as rparser from types import BuiltinMethodType as PyMethodType, Built...
246
256
1,349
5
240
joeedh/webblender
tools/extjs_cc/js_ast_match_lex.py
Python
AstMatchLexer
AstMatchLexer
48
257
48
48
555efd13ce4c12fc44427fef73f24161588846a4
bigcode/the-stack
train
efa6092b7f02bf3a6575e185
train
function
def is_word_char(cc): return re_word_pat.match(cc) != None
def is_word_char(cc):
return re_word_pat.match(cc) != None
", "OR", "CODE", "NOT", "COMMA", "SPECIAL", "STAR", ) + tuple(reserved_lst) re_word_pat = re.compile(r'[a-zA-Z_]+[a-zA-Z0-9_]*') def is_word_char(cc):
64
64
17
6
58
joeedh/webblender
tools/extjs_cc/js_ast_match_lex.py
Python
is_word_char
is_word_char
45
46
45
45
e49d2867184c33f13fad2eaaadadd822dd7deaf5
bigcode/the-stack
train
9961359d7f06117c420da80c
train
function
def Main(): host = '0.0.0.0' port = 8080 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, port)) print("socket binded to port", port) print(socket.gethostbyname(host)) s.listen(5) print("socket is listening") # a forever loop until client wants to exit while...
def Main():
host = '0.0.0.0' port = 8080 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, port)) print("socket binded to port", port) print(socket.gethostbyname(host)) s.listen(5) print("socket is listening") # a forever loop until client wants to exit while True: ...
lock released on exit print_lock.release() break # reverse the given string from client print(str(data.decode('ascii'))) data = data[::1] # send back reversed string to client c.send(data) # connection closed c.close() def Main():
64
64
161
3
61
TacPhoto/Learning
Python/StandaloneExercises/TCP_Server.py
Python
Main
Main
35
58
35
35
3d7fbb2d771edaba729fadf99a3052b7c705a6fb
bigcode/the-stack
train
acbb225c36e9ce1ca655faf7
train
function
def threaded(c): while True: # data received from client data = c.recv(1024) if not data: print("No data received") # lock released on exit print_lock.release() break # reverse the given string from client print(str(data.deco...
def threaded(c):
while True: # data received from client data = c.recv(1024) if not data: print("No data received") # lock released on exit print_lock.release() break # reverse the given string from client print(str(data.decode('ascii'))) ...
# import socket programming library import socket # import thread module from _thread import * import threading print_lock = threading.Lock() # thread function def threaded(c):
36
64
99
4
31
TacPhoto/Learning
Python/StandaloneExercises/TCP_Server.py
Python
threaded
threaded
12
32
12
12
73112aaaf43f80a7dd3ba6379d37eb87cbfadb9e
bigcode/the-stack
train
dedf11d3fdf247a9bc4cb334
train
class
class BaseWptScriptAdapter(common.BaseIsolatedScriptArgsAdapter): """The base class for script adapters that use wptrunner to execute web platform tests. This contains any code shared between these scripts, such as integrating output with the results viewer. Subclasses contain other (usually platform-sp...
class BaseWptScriptAdapter(common.BaseIsolatedScriptArgsAdapter):
"""The base class for script adapters that use wptrunner to execute web platform tests. This contains any code shared between these scripts, such as integrating output with the results viewer. Subclasses contain other (usually platform-specific) logic.""" def __init__(self): super(BaseWptSc...
# Copyright 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import base64 import json import os import shutil import sys import common BLINK_TOOLS_DIR = os.path.join(common.SRC_DIR, 'third_party', 'blink', 'tools') ...
157
256
1,894
14
142
mghgroup/Glide-Browser
testing/scripts/wpt_common.py
Python
BaseWptScriptAdapter
BaseWptScriptAdapter
22
218
22
22
19f171b3cafc53ed1bb83d8f10d36964512007ec
bigcode/the-stack
train
e809ff0ad30be6a76f5826a4
train
class
class ProfileAdapter(): """ The profile adapter class. This class needs to cotain various methods. It is loaded dynamically by the UMS during startup. Then the methods are used during the runtime. """ def get_api_definition_registration(self, std_string_size: int) -> Dict[str, fields.Raw]: ...
class ProfileAdapter():
""" The profile adapter class. This class needs to cotain various methods. It is loaded dynamically by the UMS during startup. Then the methods are used during the runtime. """ def get_api_definition_registration(self, std_string_size: int) -> Dict[str, fields.Raw]: """ Get ...
""" This module contains the skeleton for the profile adapter class. The real implementation is loaded at runtime by the profil_adapter_loader """ from typing import Dict, Tuple from flask_restplus import fields class ProfileAdapter():
44
73
246
4
39
c-hack/ums-api
ums_api/profile_adapter_skel.py
Python
ProfileAdapter
ProfileAdapter
9
37
9
9
9eed75176f7ab9eae3561cf2efad388d25e2c12c
bigcode/the-stack
train
674e079aac2619a5e5f18988
train
function
def getResponse(word): negativeKeyWords = ["bad","wasn't","not","sucks"] positiveKeyWords = ["good","great","awesome","alright","well"] if word in negativeKeyWords: return "I'm sorry about that." elif word in positiveKeyWords: return "That's great to hear!"
def getResponse(word):
negativeKeyWords = ["bad","wasn't","not","sucks"] positiveKeyWords = ["good","great","awesome","alright","well"] if word in negativeKeyWords: return "I'm sorry about that." elif word in positiveKeyWords: return "That's great to hear!"
userInput = raw_input("How is your day going? ") #get input userInput = userInput.lower() #make all characters lowercase def getResponse(word):
35
64
70
5
29
berkeleyhackclub/BeginnerPython
Week 6 Oct 17,18/simpleChatBox1.py
Python
getResponse
getResponse
4
11
4
4
94e9f20a3962fd9908e01592c33bb0c71a7eb3ff
bigcode/the-stack
train
98c36b9712ef7590c41d24ef
train
function
def searchInput(input): listInput = input.split(" ") response = "Well, life is life." for word in listInput: if getResponse(word): #If the word matches our key words response = getResponse(word) print(response)
def searchInput(input):
listInput = input.split(" ") response = "Well, life is life." for word in listInput: if getResponse(word): #If the word matches our key words response = getResponse(word) print(response)
","wasn't","not","sucks"] positiveKeyWords = ["good","great","awesome","alright","well"] if word in negativeKeyWords: return "I'm sorry about that." elif word in positiveKeyWords: return "That's great to hear!" def searchInput(input):
63
64
56
5
58
berkeleyhackclub/BeginnerPython
Week 6 Oct 17,18/simpleChatBox1.py
Python
searchInput
searchInput
14
21
14
14
75059d15a26d190498ec43db2a5a7eb7489c7848
bigcode/the-stack
train
b5a10f413b9ac56abf9d2912
train
function
def green(_): green = [0, 128, 0] writeToLux(green)
def green(_):
green = [0, 128, 0] writeToLux(green)
menu.append(cmd_exit) menu.show_all() return menu def lightOff(_): off = [0, 0, 0] writeToLux(off) def red(_): red = [255, 0, 0] writeToLux(red) def green(_):
63
64
22
4
59
Trustmega/luxatray
luxatray.py
Python
green
green
49
51
49
49
1b3bce2a1ba66d62dda7aa2c471c38bc2eba5119
bigcode/the-stack
train
015fa461a2bc9fb3d6b20e04
train
function
def lightOff(_): off = [0, 0, 0] writeToLux(off)
def lightOff(_):
off = [0, 0, 0] writeToLux(off)
cmd_blue = gtk.MenuItem('Blue') cmd_blue.connect('activate', blue) menu.append(cmd_blue) cmd_exit = gtk.MenuItem('Exit') cmd_exit.connect('activate', quit) menu.append(cmd_exit) menu.show_all() return menu def lightOff(_):
64
64
22
5
58
Trustmega/luxatray
luxatray.py
Python
lightOff
lightOff
41
43
41
41
697879048cc9492dabcc0f023e96151082f34f14
bigcode/the-stack
train
3b251bbb45b8c15b4b3ffc99
train
function
def main(): indicator = appindicator.Indicator.new("luxatray", "starred-symbolic", appindicator.IndicatorCategory.APPLICATION_STATUS) indicator.set_status(appindicator.IndicatorStatus.ACTIVE) indicator.set_menu(menu()) gtk.main()
def main():
indicator = appindicator.Indicator.new("luxatray", "starred-symbolic", appindicator.IndicatorCategory.APPLICATION_STATUS) indicator.set_status(appindicator.IndicatorStatus.ACTIVE) indicator.set_menu(menu()) gtk.main()
import os import hid from gi.repository import Gtk as gtk, AppIndicator3 as appindicator def main():
24
64
53
3
20
Trustmega/luxatray
luxatray.py
Python
main
main
6
11
6
6
fe8e5d962035af0d1ebaccb228fc57e08499a69b
bigcode/the-stack
train
a7dc05c0f5c3ee9140034e6a
train
function
def writeToLux(color): device = hid.device() device.open(0x04D8, 0xF372) device.write([2] + [0x41] + color + [10]) device.close()
def writeToLux(color):
device = hid.device() device.open(0x04D8, 0xF372) device.write([2] + [0x41] + color + [10]) device.close()
(red) def green(_): green = [0, 128, 0] writeToLux(green) def blue(_): blue = [0, 0, 255] writeToLux(blue) def quit(_): gtk.main_quit() def writeToLux(color):
63
64
46
6
57
Trustmega/luxatray
luxatray.py
Python
writeToLux
writeToLux
60
64
60
60
2c5d9a1eb5059f4b8422e1677b8ed55557f211c2
bigcode/the-stack
train
84dcff44787d8e1227f19d97
train
function
def quit(_): gtk.main_quit()
def quit(_):
gtk.main_quit()
= [255, 0, 0] writeToLux(red) def green(_): green = [0, 128, 0] writeToLux(green) def blue(_): blue = [0, 0, 255] writeToLux(blue) def quit(_):
64
64
10
4
60
Trustmega/luxatray
luxatray.py
Python
quit
quit
57
58
57
57
8933fe2f6ab7861ce4a7046d612eba560ccc5d22
bigcode/the-stack
train
4f43db24e23b4696b37cb175
train
function
def blue(_): blue = [0, 0, 255] writeToLux(blue)
def blue(_):
blue = [0, 0, 255] writeToLux(blue)
= [0, 0, 0] writeToLux(off) def red(_): red = [255, 0, 0] writeToLux(red) def green(_): green = [0, 128, 0] writeToLux(green) def blue(_):
64
64
22
4
60
Trustmega/luxatray
luxatray.py
Python
blue
blue
53
55
53
53
0f28ae65096ce470aa1fc39743017fb88ca83ec8
bigcode/the-stack
train
049c6f7768cd0b8ebc61d0c8
train
function
def menu(): menu = gtk.Menu() cmd_off = gtk.MenuItem('Off') cmd_off.connect('activate', lightOff) menu.append(cmd_off) cmd_red = gtk.MenuItem('Red') cmd_red.connect('activate', red) menu.append(cmd_red) cmd_green = gtk.MenuItem('Green') cmd_green.connect('activate', green)...
def menu():
menu = gtk.Menu() cmd_off = gtk.MenuItem('Off') cmd_off.connect('activate', lightOff) menu.append(cmd_off) cmd_red = gtk.MenuItem('Red') cmd_red.connect('activate', red) menu.append(cmd_red) cmd_green = gtk.MenuItem('Green') cmd_green.connect('activate', green) menu.ap...
, AppIndicator3 as appindicator def main(): indicator = appindicator.Indicator.new("luxatray", "starred-symbolic", appindicator.IndicatorCategory.APPLICATION_STATUS) indicator.set_status(appindicator.IndicatorStatus.ACTIVE) indicator.set_menu(menu()) gtk.main...
64
64
148
3
61
Trustmega/luxatray
luxatray.py
Python
menu
menu
14
38
14
14
915fb2ad86d4c9722082fe21d10f8339981e5f4b
bigcode/the-stack
train
918aae76a9ea00a1e17b63a5
train
function
def red(_): red = [255, 0, 0] writeToLux(red)
def red(_):
red = [255, 0, 0] writeToLux(red)
_blue) cmd_exit = gtk.MenuItem('Exit') cmd_exit.connect('activate', quit) menu.append(cmd_exit) menu.show_all() return menu def lightOff(_): off = [0, 0, 0] writeToLux(off) def red(_):
63
64
21
4
59
Trustmega/luxatray
luxatray.py
Python
red
red
45
47
45
45
792577f44fd6102c5fefadb791f85ef6a9b758ae
bigcode/the-stack
train
a85c49380dd496ae1ad368c7
train
class
class Epoch(DataObject): ''' Array of epochs. *Usage*:: >>> from neo.core import Epoch >>> from quantities import s, ms >>> import numpy as np >>> >>> epc = Epoch(times=np.arange(0, 30, 10)*s, ... durations=[10, 5, 7]*ms, ... ...
class Epoch(DataObject):
''' Array of epochs. *Usage*:: >>> from neo.core import Epoch >>> from quantities import s, ms >>> import numpy as np >>> >>> epc = Epoch(times=np.arange(0, 30, 10)*s, ... durations=[10, 5, 7]*ms, ... labels=np.array(['btn0', ...
# -*- coding: utf-8 -*- ''' This module defines :class:`Epoch`, an array of epochs. :class:`Epoch` derives from :class:`BaseNeo`, from :module:`neo.core.baseneo`. ''' # needed for python 3 compatibility from __future__ import absolute_import, division, print_function import sys from copy import deepcopy, copy impor...
251
256
2,811
5
245
bjoern1001001/python-neo
neo/core/epoch.py
Python
Epoch
Epoch
38
360
38
38
fb07d8a1e968baf5b39c6cc42c8a71fdd66b0e31
bigcode/the-stack
train
3865bb397c92c67e9ef8958f
train
function
def _new_epoch(cls, times=None, durations=None, labels=None, units=None, name=None, description=None, file_origin=None, array_annotations=None, annotations=None, segment=None): ''' A function to map epoch.__new__ to function that does not do the unit checking. This is needed fo...
def _new_epoch(cls, times=None, durations=None, labels=None, units=None, name=None, description=None, file_origin=None, array_annotations=None, annotations=None, segment=None):
''' A function to map epoch.__new__ to function that does not do the unit checking. This is needed for pickle to work. ''' e = Epoch(times=times, durations=durations, labels=labels, units=units, name=name, file_origin=file_origin, description=description, array_annotation...
merge_annotations from neo.core.dataobject import DataObject, ArrayDict PY_VER = sys.version_info[0] def _new_epoch(cls, times=None, durations=None, labels=None, units=None, name=None, description=None, file_origin=None, array_annotations=None, annotations=None, segment=None):
64
64
126
40
24
bjoern1001001/python-neo
neo/core/epoch.py
Python
_new_epoch
_new_epoch
24
35
24
26
fd9df30d454d67f36f8d92741d1bf861cdf2454f
bigcode/the-stack
train
1b0d295aacb17683c77d3984
train
function
def compute_fd(motpars): # compute absolute displacement dmotpars=N.zeros(motpars.shape) dmotpars[1:,:]=N.abs(motpars[1:,:] - motpars[:-1,:]) # convert rotation to displacement on a 50 mm sphere # mcflirt returns rotation in radians # from Jonathan Power: #The conversion is simple...
def compute_fd(motpars): # compute absolute displacement
dmotpars=N.zeros(motpars.shape) dmotpars[1:,:]=N.abs(motpars[1:,:] - motpars[:-1,:]) # convert rotation to displacement on a 50 mm sphere # mcflirt returns rotation in radians # from Jonathan Power: #The conversion is simple - you just want the length of an arc that a rotational # ...
#!/usr/bin/env python """ implement the frame displacement measure described by Power et al. (2011) """ import numpy as N import os,sys # load the datafile def compute_fd(motpars): # compute absolute displacement
52
65
219
13
38
poldrack/poldracklab-base
fmri/compute_fd.py
Python
compute_fd
compute_fd
11
33
11
13
ca9f410690108e05bbe1917a1a3ab0eb89347349
bigcode/the-stack
train
c430e48d2db17e83abf46f0b
train
function
def download_centos_package(package): logging.info("Searching for CentOS package '%s'", package) # "Enterprise Linux' aka CentOS. # Current releases are available from mirror, historic from vault, # debuginfo from debuginfo. if 'debuginfo' in package: return try_download_from_url('http://deb...
def download_centos_package(package):
logging.info("Searching for CentOS package '%s'", package) # "Enterprise Linux' aka CentOS. # Current releases are available from mirror, historic from vault, # debuginfo from debuginfo. if 'debuginfo' in package: return try_download_from_url('http://debuginfo.centos.org/7/x86_64', ...
base_url + "/" + filename response = requests.get(url, stream=True) if response.status_code == 200: logging.info("Found at {}".format(url)) with open(filename, 'wb') as rpm_file: response.raw.decode_content = True shutil.copyfileobj(response.raw, rpm_file) re...
82
82
276
7
74
rohansuri/kv_engine
scripts/sync_rpms.py
Python
download_centos_package
download_centos_package
66
88
66
66
259caa8b625a5b8279f5549ae09a25e3f018f5b8
bigcode/the-stack
train
78c0f2c1b2c89087e86deefc
train
function
def download_couchbase_package(package): logging.info("Searching for Couchbase package '%s'", package) # GA'd versions available from packages.couchbase.com, pre-release from # latestbuilds (requires VPN). (name, version, build_arch) = package.rsplit('-', 2) (build, arch) = build_arch.split('.') ...
def download_couchbase_package(package):
logging.info("Searching for Couchbase package '%s'", package) # GA'd versions available from packages.couchbase.com, pre-release from # latestbuilds (requires VPN). (name, version, build_arch) = package.rsplit('-', 2) (build, arch) = build_arch.split('.') version_to_dir = {'7.0.0': 'http://lates...
_64/Packages', 'updates/x86_64/Packages') for host, versions in repos.iteritems(): for version in versions: for subdir in subdirs: base_url = host + '/' + version + '/' + subdir filename = try_download_from_url(base_url, package) if filename: ...
84
84
281
8
75
rohansuri/kv_engine
scripts/sync_rpms.py
Python
download_couchbase_package
download_couchbase_package
91
112
91
91
475b38191fc15836ee7158e5fa6bc535dec11261
bigcode/the-stack
train
8abd1530233eaac13d3ff08e
train
function
def try_download_from_url(base_url, package): filename = package + ".rpm" if os.path.isfile(filename): print(("Skipping download of {} as file already " + "exists.").format(filename), file=sys.stderr) return filename url = base_url + "/" + filename response = requests.get(...
def try_download_from_url(base_url, package):
filename = package + ".rpm" if os.path.isfile(filename): print(("Skipping download of {} as file already " + "exists.").format(filename), file=sys.stderr) return filename url = base_url + "/" + filename response = requests.get(url, stream=True) if response.status_code ...
it was downloaded to. Returns None if package could not be located. """ if '.el' in package: return download_centos_package(package) if package.startswith('couchbase-server'): return download_couchbase_package(package) def try_download_from_url(base_url, package):
64
64
131
10
54
rohansuri/kv_engine
scripts/sync_rpms.py
Python
try_download_from_url
try_download_from_url
49
63
49
49
77b76c7d76477f9e09cea5c44fe7e1117e95cd42
bigcode/the-stack
train
f7089a6f896b926e43ba3dec
train
function
def download_package(package): """Given a package name+version string, attempt to locate the file from the appropriate package repository; downloads it and returns the name of the local file it was downloaded to. Returns None if package could not be located. """ if '.el' in package: re...
def download_package(package):
"""Given a package name+version string, attempt to locate the file from the appropriate package repository; downloads it and returns the name of the local file it was downloaded to. Returns None if package could not be located. """ if '.el' in package: return download_centos_package(pa...
Config(level=logging.INFO) logging.getLogger('urllib3').setLevel(logging.ERROR) def is_package_installed(package): with open(os.devnull, 'w') as devnull: return subprocess.call(["rpm", "-q", package], stdout=devnull) == 0 def download_package(package):
64
64
94
5
58
rohansuri/kv_engine
scripts/sync_rpms.py
Python
download_package
download_package
36
46
36
36
a79ca3b8574b6731678d7b8cd38808c3d8228327
bigcode/the-stack
train
97980c671b6c55cd14cef7f4
train
function
def install_packages(packages): subprocess.check_call(["rpm", "-Uvh", "--oldpackage"] + packages)
def install_packages(packages):
subprocess.check_call(["rpm", "-Uvh", "--oldpackage"] + packages)
_to_file[name] # Insert the distribution name # TODO: derive this from current system filename = (name + '-' + version + '-' + build + '-centos7.' + arch) return try_download_from_url(base_url, filename) return None def install_packages(packages):
64
64
24
6
57
rohansuri/kv_engine
scripts/sync_rpms.py
Python
install_packages
install_packages
115
116
115
115
5a70337003d2f243ad619e7fee70c1d0a1392774
bigcode/the-stack
train
428349debb8d2eaba031a644
train
function
def is_package_installed(package): with open(os.devnull, 'w') as devnull: return subprocess.call(["rpm", "-q", package], stdout=devnull) == 0
def is_package_installed(package):
with open(os.devnull, 'w') as devnull: return subprocess.call(["rpm", "-q", package], stdout=devnull) == 0
./sync_rpms.py """ from __future__ import print_function import fileinput import logging import os import requests import shutil import subprocess import sys logging.basicConfig(level=logging.INFO) logging.getLogger('urllib3').setLevel(logging.ERROR) def is_package_installed(package):
64
64
42
7
57
rohansuri/kv_engine
scripts/sync_rpms.py
Python
is_package_installed
is_package_installed
31
33
31
31
9172138affde06027378d5d7068cdffb5e902808
bigcode/the-stack
train
32120beb7b6877d4594b2714
train
class
class V1alpha1VolumeAttachment(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribu...
class V1alpha1VolumeAttachment(object):
"""NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The...
# coding: utf-8 """ Kubernetes No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: release-1.17 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import si...
99
256
1,698
9
89
carloscastrojumo/python
kubernetes/client/models/v1alpha1_volume_attachment.py
Python
V1alpha1VolumeAttachment
V1alpha1VolumeAttachment
21
229
21
21
a164070d21770cc3c9abaf23016e10a7ccb1a2d0
bigcode/the-stack
train
9c6e980cdc1373d15de47484
train
function
def diff(arr1, arr2): arr1 = normalize(arr1) arr2 = normalize(arr2) distance = arr1 - arr2 return np.max(np.sum(np.square(distance).reshape(arr1.shape[0], -1), axis=1))
def diff(arr1, arr2):
arr1 = normalize(arr1) arr2 = normalize(arr2) distance = arr1 - arr2 return np.max(np.sum(np.square(distance).reshape(arr1.shape[0], -1), axis=1))
net50_weights_tf_dim_ordering_tf_kernels.h5") prediction.loadModel() BASE_IMAGE = np.asarray(Image.open("car.jpg")) def normalize(arr): rng = arr.max()-arr.min() amin = arr.min() return (arr-amin)/rng def diff(arr1, arr2):
64
64
57
8
55
mihaid-b/CyberSakura
Gathered CTF writeups/2019-12-01-ctfzone-quals/classifier9000/server.py
Python
diff
diff
24
28
24
24
04afa79f56e428f90e49228ad7e80b59490f27ee
bigcode/the-stack
train
9fda42d69e9038883f69dc3f
train
function
def normalize(arr): rng = arr.max()-arr.min() amin = arr.min() return (arr-amin)/rng
def normalize(arr):
rng = arr.max()-arr.min() amin = arr.min() return (arr-amin)/rng
Heard that these kind of models are vulnerable to adversarial attacks prediction = ImagePrediction() prediction.setModelTypeAsResNet() prediction.setModelPath("resnet50_weights_tf_dim_ordering_tf_kernels.h5") prediction.loadModel() BASE_IMAGE = np.asarray(Image.open("car.jpg")) def normalize(arr):
64
64
28
4
60
mihaid-b/CyberSakura
Gathered CTF writeups/2019-12-01-ctfzone-quals/classifier9000/server.py
Python
normalize
normalize
18
21
18
18
33d994d3f4ebaabeadd9e72b3662c2b3f4bf1864
bigcode/the-stack
train
fcec7d8dd89ee6cb9d364a65
train
function
@app.route('/task/upload/', methods=['POST',]) def hello_world(): answer = { "status": "fail to recognize image" } if request.method == 'POST': f = request.files['file'] I = np.asarray(Image.open(f)) if I.shape != (224,224, 3): return redirect(os.getenv("base_url"...
@app.route('/task/upload/', methods=['POST',]) def hello_world():
answer = { "status": "fail to recognize image" } if request.method == 'POST': f = request.files['file'] I = np.asarray(Image.open(f)) if I.shape != (224,224, 3): return redirect(os.getenv("base_url", "http://0.0.0.0:8000") + "/fail.html") if diff(I, BASE_I...
arr2): arr1 = normalize(arr1) arr2 = normalize(arr2) distance = arr1 - arr2 return np.max(np.sum(np.square(distance).reshape(arr1.shape[0], -1), axis=1)) @app.route('/task/upload/', methods=['POST',]) def hello_world():
67
68
229
15
52
mihaid-b/CyberSakura
Gathered CTF writeups/2019-12-01-ctfzone-quals/classifier9000/server.py
Python
hello_world
hello_world
32
48
32
33
8ee416f5f5e7c5bdfe75b03a12e73119e29f1beb
bigcode/the-stack
train
15e4ac96a50bdeab90df2f9f
train
class
class Tests(unittest.TestCase): def writeFile(self, path, fileName, content): handle = open(os.path.join(path, fileName), mode="w", encoding="utf-8") handle.write(content) handle.close() def readFile(self, path, fileName): return open(os.path.join(path, fileName), mode="r", enc...
class Tests(unittest.TestCase):
def writeFile(self, path, fileName, content): handle = open(os.path.join(path, fileName), mode="w", encoding="utf-8") handle.write(content) handle.close() def readFile(self, path, fileName): return open(os.path.join(path, fileName), mode="r", encoding="utf-8").read() def cr...
#!/usr/bin/env python3 import sys, os, unittest, logging, tempfile # Extend PYTHONPATH with local 'lib' folder jasyroot = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir, os.pardir)) sys.path.insert(0, jasyroot) import jasy.core.Project as Project import jasy.core.Session as Session ...
96
256
1,230
6
89
zynga/jasy
jasy/test/requirements.py
Python
Tests
Tests
13
166
13
14
1c75cb15fc15d9d78df0790073395faaa849ef6b
bigcode/the-stack
train
ef57d842aae8f99d4a82e6e7
train
function
def uncertainty_estimate(values): """ Creates an estimate for the uncertainty to apply to each value base on the separation of the entries that make up the distribution. This is used in cases where no uncertainty was described in the measurements, but the measurement population is fairly large, so t...
def uncertainty_estimate(values):
""" Creates an estimate for the uncertainty to apply to each value base on the separation of the entries that make up the distribution. This is used in cases where no uncertainty was described in the measurements, but the measurement population is fairly large, so that the quantization of the me...
, 'mstats.ValueUncertainty', float], float] many: typing.Callable[[float, np.array, np.array], np.array] GAUSSIAN_KERNEL = Kernel( single=gaussians.gaussian, many=gaussians.gaussian_many ) def uncertainty_estimate(values):
64
64
191
6
58
sernst/RefinedStatistics
measurement_stats/distributions/kernels/__init__.py
Python
uncertainty_estimate
uncertainty_estimate
22
46
22
22
bed0dd2c27ec661e9d73373fefa35c05dbe05c0c
bigcode/the-stack
train
459badac9ff31b78cfce2a8d
train
class
class Kernel(typing.NamedTuple): """Data structure for Kernel objects.""" single: typing.Callable[[float, 'mstats.ValueUncertainty', float], float] many: typing.Callable[[float, np.array, np.array], np.array]
class Kernel(typing.NamedTuple):
"""Data structure for Kernel objects.""" single: typing.Callable[[float, 'mstats.ValueUncertainty', float], float] many: typing.Callable[[float, np.array, np.array], np.array]
import typing import numpy as np import measurement_stats as mstats from measurement_stats.distributions.kernels import gaussians class Kernel(typing.NamedTuple):
34
64
53
7
26
sernst/RefinedStatistics
measurement_stats/distributions/kernels/__init__.py
Python
Kernel
Kernel
9
13
9
9
7727c04aeefa1725fda588c48a27407ba2c00c2e
bigcode/the-stack
train
32810fd837e038aedfc4b34f
train
class
class ProbClassificationPerformanceAnalyzer(Analyzer): def calculate(self, reference_data: pd.DataFrame, current_data: pd.DataFrame, column_mapping): columns = process_columns(reference_data, column_mapping) result = columns.as_dict() target_column = columns.utility_columns.target p...
class ProbClassificationPerformanceAnalyzer(Analyzer):
def calculate(self, reference_data: pd.DataFrame, current_data: pd.DataFrame, column_mapping): columns = process_columns(reference_data, column_mapping) result = columns.as_dict() target_column = columns.utility_columns.target prediction_column = columns.utility_columns.prediction ...
#!/usr/bin/env python # coding: utf-8 import pandas as pd import numpy as np from sklearn import metrics, preprocessing from evidently.analyzers.base_analyzer import Analyzer from .utils import process_columns class ProbClassificationPerformanceAnalyzer(Analyzer):
56
256
3,112
8
47
jim-fun/evidently
evidently/analyzers/prob_classification_performance_analyzer.py
Python
ProbClassificationPerformanceAnalyzer
ProbClassificationPerformanceAnalyzer
12
276
12
12
d78ae6c8537896a89a6832eff5ef8c53373ea94d
bigcode/the-stack
train
85afe3e6b40ccb85c5cf507f
train
class
class SigninForm(BaseForm): telephone = StringField(validators=[Regexp(r"1[345789]\d{9}", message="请输入正确格式的手机号码")]) password = StringField(validators=[Regexp(r"[0-9a-zA-Z_\.]{6,20}", message="请输入正确格式的密码")]) # 记住我这个input不需要验证 remember = StringField()
class SigninForm(BaseForm):
telephone = StringField(validators=[Regexp(r"1[345789]\d{9}", message="请输入正确格式的手机号码")]) password = StringField(validators=[Regexp(r"[0-9a-zA-Z_\.]{6,20}", message="请输入正确格式的密码")]) # 记住我这个input不需要验证 remember = StringField()
= StringField(validators=[Regexp(r"[0-9a-zA-Z_\.]{6,20}", message="请输入正确格式的密码")]) password2 = StringField(validators=[EqualTo("password1", message="两次输入的密码不一致")]) class SigninForm(BaseForm):
64
64
88
7
57
zy0851/get-news
aminute/apps/front/forms.py
Python
SigninForm
SigninForm
30
34
30
30
c8fd6c47bccbfbcb9f0a16169c9720dc4ffe4567
bigcode/the-stack
train
c20281066ffb06f292d2c646
train
class
class SignupForm(BaseForm): telephone = StringField(validators=[Regexp(r"1[345789]\d{9}", message="请输入正确格式的手机号码")]) username = StringField(validators=[Regexp(r".{2,20}", message="请输入正确格式的用户名")]) password1 = StringField(validators=[Regexp(r"[0-9a-zA-Z_\.]{6,20}", message="请输入正确格式的密码")]) password2 = StringField(valid...
class SignupForm(BaseForm):
telephone = StringField(validators=[Regexp(r"1[345789]\d{9}", message="请输入正确格式的手机号码")]) username = StringField(validators=[Regexp(r".{2,20}", message="请输入正确格式的用户名")]) password1 = StringField(validators=[Regexp(r"[0-9a-zA-Z_\.]{6,20}", message="请输入正确格式的密码")]) password2 = StringField(validators=[EqualTo("password1", ...
forms.py @time: 2018/7/24 20:53 @description:TODO """ from ..forms import BaseForm from wtforms import StringField, ValidationError, IntegerField from wtforms.validators import Regexp, EqualTo, InputRequired class SignupForm(BaseForm):
64
64
119
6
57
zy0851/get-news
aminute/apps/front/forms.py
Python
SignupForm
SignupForm
23
27
23
23
e36f735ee1c6bfad22e96a04cef1085d7e83eff0
bigcode/the-stack
train
5968e8f9f23d622c32d5d640
train
class
class ChainReader(object): """Base class for reading chains files.""" def __init__(self, root): self.root = root def paramnames(self): """Parameter names mapping.""" return None, {} def limits(self): """Parameter limits mapping.""" return {} def samples(se...
class ChainReader(object):
"""Base class for reading chains files.""" def __init__(self, root): self.root = root def paramnames(self): """Parameter names mapping.""" return None, {} def limits(self): """Parameter limits mapping.""" return {} def samples(self): """Read sample...
"""Tools for reading from chains files.""" class ChainReader(object):
13
64
78
5
8
EthanCarragher/anesthetic
anesthetic/read/chainreader.py
Python
ChainReader
ChainReader
4
20
4
4
c383e1a585d6fff23589fcde9511724170b4e466
bigcode/the-stack
train