blob_id
stringlengths
40
40
bodies
listlengths
2
6
bodies_text
stringlengths
196
6.73k
class_docstring
stringlengths
0
700
class_name
stringlengths
1
86
detected_licenses
listlengths
0
45
format_version
stringclasses
1 value
full_text
stringlengths
438
7.52k
id
stringlengths
40
40
length_bytes
int64
506
50k
license_type
stringclasses
2 values
methods
listlengths
2
6
n_methods
int64
2
6
original_id
stringlengths
38
40
prompt
stringlengths
153
4.25k
prompted_full_text
stringlengths
645
10.7k
revision_id
stringlengths
40
40
skeleton
stringlengths
162
4.34k
snapshot_name
stringclasses
1 value
snapshot_source_dir
stringclasses
1 value
solution
stringlengths
302
7.33k
source
stringclasses
1 value
source_path
stringlengths
4
177
source_repo
stringlengths
6
110
split
stringclasses
1 value
star_events_count
int64
0
209k
9b13e819ac95741d8f08d05b739b2a69197160f0
[ "if root is None:\n return\nqueue = [root]\nres_list = []\nwhile queue:\n node_list = []\n res = []\n for node in queue:\n res.append(node.val)\n if node.left is not None:\n node_list.append(node.left)\n if node.right is not None:\n node_list.append(node.right)...
<|body_start_0|> if root is None: return queue = [root] res_list = [] while queue: node_list = [] res = [] for node in queue: res.append(node.val) if node.left is not None: node_list.appen...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxDepth(self, root): """广度优先,层序遍历,先求出每层的所有元素,再查看又多少层 :type root: TreeNode :rtype: int""" <|body_0|> def maxDepth2(self, root): """递归 :type root: TreeNode :rtype: int""" <|body_1|> def maxDepth3(self, root): """深度优先遍历 :type root: Tr...
stack_v2_sparse_classes_36k_train_011200
2,282
no_license
[ { "docstring": "广度优先,层序遍历,先求出每层的所有元素,再查看又多少层 :type root: TreeNode :rtype: int", "name": "maxDepth", "signature": "def maxDepth(self, root)" }, { "docstring": "递归 :type root: TreeNode :rtype: int", "name": "maxDepth2", "signature": "def maxDepth2(self, root)" }, { "docstring": "深度...
3
stack_v2_sparse_classes_30k_train_015238
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxDepth(self, root): 广度优先,层序遍历,先求出每层的所有元素,再查看又多少层 :type root: TreeNode :rtype: int - def maxDepth2(self, root): 递归 :type root: TreeNode :rtype: int - def maxDepth3(self, roo...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxDepth(self, root): 广度优先,层序遍历,先求出每层的所有元素,再查看又多少层 :type root: TreeNode :rtype: int - def maxDepth2(self, root): 递归 :type root: TreeNode :rtype: int - def maxDepth3(self, roo...
3b13b36f37eb364410b3b5b4f10a1808d8b1111e
<|skeleton|> class Solution: def maxDepth(self, root): """广度优先,层序遍历,先求出每层的所有元素,再查看又多少层 :type root: TreeNode :rtype: int""" <|body_0|> def maxDepth2(self, root): """递归 :type root: TreeNode :rtype: int""" <|body_1|> def maxDepth3(self, root): """深度优先遍历 :type root: Tr...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxDepth(self, root): """广度优先,层序遍历,先求出每层的所有元素,再查看又多少层 :type root: TreeNode :rtype: int""" if root is None: return queue = [root] res_list = [] while queue: node_list = [] res = [] for node in queue: ...
the_stack_v2_python_sparse
leetcode/104.py
yanggelinux/algorithm-data-structure
train
0
6304e3747595331bfefa440cb689f013f1bd8ba0
[ "self.dtype = 'Powerlaw'\nif isinstance(amin, u.Quantity):\n amin_um = amin.to('micron').value\nelse:\n amin_um = amin\nif isinstance(amax, u.Quantity):\n amax_um = amax.to('micron').value\nelse:\n amax_um = amax\nif log:\n self.a = np.logspace(np.log10(amin_um), np.log10(amax_um), na) * u.micron\nel...
<|body_start_0|> self.dtype = 'Powerlaw' if isinstance(amin, u.Quantity): amin_um = amin.to('micron').value else: amin_um = amin if isinstance(amax, u.Quantity): amax_um = amax.to('micron').value else: amax_um = amax if log:...
A power law grain size distribution
Powerlaw
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Powerlaw: """A power law grain size distribution""" def __init__(self, amin=AMIN, amax=AMAX, p=PDIST, na=NA, log=False): """Inputs ------ amin : astropy.units.Quantity -or- float : minimum grain radius; if a float, micron units assumed amax : astropy.units.Quantity -or- float : maxim...
stack_v2_sparse_classes_36k_train_011201
3,589
permissive
[ { "docstring": "Inputs ------ amin : astropy.units.Quantity -or- float : minimum grain radius; if a float, micron units assumed amax : astropy.units.Quantity -or- float : maximum grain radius; if a float, micron units assumed p : float : power law slope for function dn/da \\\\propto a^-p NA : int : number of a ...
3
stack_v2_sparse_classes_30k_train_014961
Implement the Python class `Powerlaw` described below. Class description: A power law grain size distribution Method signatures and docstrings: - def __init__(self, amin=AMIN, amax=AMAX, p=PDIST, na=NA, log=False): Inputs ------ amin : astropy.units.Quantity -or- float : minimum grain radius; if a float, micron units...
Implement the Python class `Powerlaw` described below. Class description: A power law grain size distribution Method signatures and docstrings: - def __init__(self, amin=AMIN, amax=AMAX, p=PDIST, na=NA, log=False): Inputs ------ amin : astropy.units.Quantity -or- float : minimum grain radius; if a float, micron units...
55d4585b3230d41472e49ea9b0fe9514e9ad29bd
<|skeleton|> class Powerlaw: """A power law grain size distribution""" def __init__(self, amin=AMIN, amax=AMAX, p=PDIST, na=NA, log=False): """Inputs ------ amin : astropy.units.Quantity -or- float : minimum grain radius; if a float, micron units assumed amax : astropy.units.Quantity -or- float : maxim...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Powerlaw: """A power law grain size distribution""" def __init__(self, amin=AMIN, amax=AMAX, p=PDIST, na=NA, log=False): """Inputs ------ amin : astropy.units.Quantity -or- float : minimum grain radius; if a float, micron units assumed amax : astropy.units.Quantity -or- float : maximum grain radi...
the_stack_v2_python_sparse
newdust/graindist/sizedist/powerlaw.py
eblur/newdust
train
5
435b2f192cd22e0af748734c701b465bcc46ee9f
[ "agent = request.user.userinfo.agent\nuserinfo = request.user.userinfo\nlogin_types = agent.login_type.split(',')\ndata = model_to_dict(agent, fields=['register_time', 'register_count', 'register_allow', 'login_allow', 'fail_count', 'fail_range_time', 'fail_ban_time', 'is_find_password', 'login_timeout'])\ndata['us...
<|body_start_0|> agent = request.user.userinfo.agent userinfo = request.user.userinfo login_types = agent.login_type.split(',') data = model_to_dict(agent, fields=['register_time', 'register_count', 'register_allow', 'login_allow', 'fail_count', 'fail_range_time', 'fail_ban_time', 'is_fi...
访问设置
Visit
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Visit: """访问设置""" def get(self, request): """获取访问设置信息 data = { 'username': True, 'email': True 'phone': True, 'wechat': True, 'fail_range_time': 180L, IP限制时间 'fail_ban_time': 60L, IP限制禁止时间 'fail_count': 10L, IP限制次数 'user_fail_count': 10L, 账号限制次数 'user_fail_range_time': 3L, 账号限制时间 'us...
stack_v2_sparse_classes_36k_train_011202
32,690
no_license
[ { "docstring": "获取访问设置信息 data = { 'username': True, 'email': True 'phone': True, 'wechat': True, 'fail_range_time': 180L, IP限制时间 'fail_ban_time': 60L, IP限制禁止时间 'fail_count': 10L, IP限制次数 'user_fail_count': 10L, 账号限制次数 'user_fail_range_time': 3L, 账号限制时间 'user_fail_ban_time': 账号限制禁止时间 'register_time': 180L, 注册限制时间...
2
null
Implement the Python class `Visit` described below. Class description: 访问设置 Method signatures and docstrings: - def get(self, request): 获取访问设置信息 data = { 'username': True, 'email': True 'phone': True, 'wechat': True, 'fail_range_time': 180L, IP限制时间 'fail_ban_time': 60L, IP限制禁止时间 'fail_count': 10L, IP限制次数 'user_fail_c...
Implement the Python class `Visit` described below. Class description: 访问设置 Method signatures and docstrings: - def get(self, request): 获取访问设置信息 data = { 'username': True, 'email': True 'phone': True, 'wechat': True, 'fail_range_time': 180L, IP限制时间 'fail_ban_time': 60L, IP限制禁止时间 'fail_count': 10L, IP限制次数 'user_fail_c...
d6e025d7e9d9e3aecfd399c77f376130edd8a2df
<|skeleton|> class Visit: """访问设置""" def get(self, request): """获取访问设置信息 data = { 'username': True, 'email': True 'phone': True, 'wechat': True, 'fail_range_time': 180L, IP限制时间 'fail_ban_time': 60L, IP限制禁止时间 'fail_count': 10L, IP限制次数 'user_fail_count': 10L, 账号限制次数 'user_fail_range_time': 3L, 账号限制时间 'us...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Visit: """访问设置""" def get(self, request): """获取访问设置信息 data = { 'username': True, 'email': True 'phone': True, 'wechat': True, 'fail_range_time': 180L, IP限制时间 'fail_ban_time': 60L, IP限制禁止时间 'fail_count': 10L, IP限制次数 'user_fail_count': 10L, 账号限制次数 'user_fail_range_time': 3L, 账号限制时间 'user_fail_ban_t...
the_stack_v2_python_sparse
soc_system/views/set_views.py
sundw2015/841
train
4
7f65df1744c71553f605286898749eb0e1510eae
[ "super().__init__()\nassert latent_size != 0 and latent_size & latent_size - 1 == 0, 'latent size not a power of 2'\nif depth >= 4:\n assert latent_size >= np.power(2, depth - 4), 'latent size will diminish to zero'\nself.use_eql = use_eql\nself.depth = depth\nself.latent_size = latent_size\nself.initial_block =...
<|body_start_0|> super().__init__() assert latent_size != 0 and latent_size & latent_size - 1 == 0, 'latent size not a power of 2' if depth >= 4: assert latent_size >= np.power(2, depth - 4), 'latent size will diminish to zero' self.use_eql = use_eql self.depth = dept...
Generator
[ "MIT", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Generator: def __init__(self, depth=7, latent_size=512, use_eql=True): """constructor for the Generator class :param depth: required depth of the Network :param latent_size: size of the latent manifold :param use_eql: whether to use equalized learning rate""" <|body_0|> def ...
stack_v2_sparse_classes_36k_train_011203
10,883
permissive
[ { "docstring": "constructor for the Generator class :param depth: required depth of the Network :param latent_size: size of the latent manifold :param use_eql: whether to use equalized learning rate", "name": "__init__", "signature": "def __init__(self, depth=7, latent_size=512, use_eql=True)" }, { ...
2
stack_v2_sparse_classes_30k_train_021471
Implement the Python class `Generator` described below. Class description: Implement the Generator class. Method signatures and docstrings: - def __init__(self, depth=7, latent_size=512, use_eql=True): constructor for the Generator class :param depth: required depth of the Network :param latent_size: size of the late...
Implement the Python class `Generator` described below. Class description: Implement the Generator class. Method signatures and docstrings: - def __init__(self, depth=7, latent_size=512, use_eql=True): constructor for the Generator class :param depth: required depth of the Network :param latent_size: size of the late...
30e7404924070f63b68e73f33f2b42ea8be22f65
<|skeleton|> class Generator: def __init__(self, depth=7, latent_size=512, use_eql=True): """constructor for the Generator class :param depth: required depth of the Network :param latent_size: size of the latent manifold :param use_eql: whether to use equalized learning rate""" <|body_0|> def ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Generator: def __init__(self, depth=7, latent_size=512, use_eql=True): """constructor for the Generator class :param depth: required depth of the Network :param latent_size: size of the latent manifold :param use_eql: whether to use equalized learning rate""" super().__init__() assert ...
the_stack_v2_python_sparse
model/pggan/utils/Networks.py
TrendingTechnology/MTV-TSA
train
0
fb1fb4c894d4500dcd26348b1275cd13bb4df206
[ "querydict = request.data\nclass_id = querydict.getlist('class_id')[0]\nclass_name = querydict.getlist('class_name')[0]\nclass_count = querydict.getlist('class_count')[0]\nprofess_name = querydict.getlist('profess_name')[0]\nprofess = profession_table.objects.filter(pname=profess_name)\nprofess_data = ProfessionSer...
<|body_start_0|> querydict = request.data class_id = querydict.getlist('class_id')[0] class_name = querydict.getlist('class_name')[0] class_count = querydict.getlist('class_count')[0] profess_name = querydict.getlist('profess_name')[0] profess = profession_table.objects.f...
班级创建/删除视图
ClassCreateDeleteView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ClassCreateDeleteView: """班级创建/删除视图""" def post(self, request): """班级创建视图 路由:POST classes/classcreatedelete/ 请求参数: class_id 班号 class_name 班名 class_count 人数 profess_name 班级对应专业""" <|body_0|> def delete(self, request): """班级删除视图 路由: DELETE /classes/classcreatedelet...
stack_v2_sparse_classes_36k_train_011204
8,225
permissive
[ { "docstring": "班级创建视图 路由:POST classes/classcreatedelete/ 请求参数: class_id 班号 class_name 班名 class_count 人数 profess_name 班级对应专业", "name": "post", "signature": "def post(self, request)" }, { "docstring": "班级删除视图 路由: DELETE /classes/classcreatedelete/", "name": "delete", "signature": "def del...
2
stack_v2_sparse_classes_30k_test_001070
Implement the Python class `ClassCreateDeleteView` described below. Class description: 班级创建/删除视图 Method signatures and docstrings: - def post(self, request): 班级创建视图 路由:POST classes/classcreatedelete/ 请求参数: class_id 班号 class_name 班名 class_count 人数 profess_name 班级对应专业 - def delete(self, request): 班级删除视图 路由: DELETE /cla...
Implement the Python class `ClassCreateDeleteView` described below. Class description: 班级创建/删除视图 Method signatures and docstrings: - def post(self, request): 班级创建视图 路由:POST classes/classcreatedelete/ 请求参数: class_id 班号 class_name 班名 class_count 人数 profess_name 班级对应专业 - def delete(self, request): 班级删除视图 路由: DELETE /cla...
0e926292d86070f6f42066e73374ea74e39ca169
<|skeleton|> class ClassCreateDeleteView: """班级创建/删除视图""" def post(self, request): """班级创建视图 路由:POST classes/classcreatedelete/ 请求参数: class_id 班号 class_name 班名 class_count 人数 profess_name 班级对应专业""" <|body_0|> def delete(self, request): """班级删除视图 路由: DELETE /classes/classcreatedelet...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ClassCreateDeleteView: """班级创建/删除视图""" def post(self, request): """班级创建视图 路由:POST classes/classcreatedelete/ 请求参数: class_id 班号 class_name 班名 class_count 人数 profess_name 班级对应专业""" querydict = request.data class_id = querydict.getlist('class_id')[0] class_name = querydict.ge...
the_stack_v2_python_sparse
ETMS/ETMS/apps/classes/views.py
17605272633/ETMS
train
1
154c66289a5308c5c47aac36785aa6564a8a891c
[ "if len(nums) <= 1:\n return 0\nn = len(nums)\ndp = [0] * n\nmax_dump = nums[0]\ndp[0] = 0\ndp[1:max_dump + 1] = [1] * max_dump\nif max_dump >= n - 1:\n return 1\nfor i in range(1, n):\n if i + nums[i] >= n - 1:\n return dp[i] + 1\n if i + nums[i] > max_dump:\n dp[max_dump + 1:i + nums[i] ...
<|body_start_0|> if len(nums) <= 1: return 0 n = len(nums) dp = [0] * n max_dump = nums[0] dp[0] = 0 dp[1:max_dump + 1] = [1] * max_dump if max_dump >= n - 1: return 1 for i in range(1, n): if i + nums[i] >= n - 1: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def jump(self, nums): """max_dump 在第i个元素最远能跳到的距离 dp[i]:跳到第i个元素最少需要多少步 :type nums: List[int] :rtype: int""" <|body_0|> def jump2(self, nums): """优化代码 与上面不同的是,这是根据i更新last,上面是根据num[i]和i的和判断是不是能跳过前面跳得最大值。 f[i]: 到达i所需要的最少步数 last: 第一次到达i时上一步的位置 根据贪心得知,令f[i]=f[las...
stack_v2_sparse_classes_36k_train_011205
2,924
no_license
[ { "docstring": "max_dump 在第i个元素最远能跳到的距离 dp[i]:跳到第i个元素最少需要多少步 :type nums: List[int] :rtype: int", "name": "jump", "signature": "def jump(self, nums)" }, { "docstring": "优化代码 与上面不同的是,这是根据i更新last,上面是根据num[i]和i的和判断是不是能跳过前面跳得最大值。 f[i]: 到达i所需要的最少步数 last: 第一次到达i时上一步的位置 根据贪心得知,令f[i]=f[last]+1后,f[i]就会是最优...
2
stack_v2_sparse_classes_30k_train_021594
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def jump(self, nums): max_dump 在第i个元素最远能跳到的距离 dp[i]:跳到第i个元素最少需要多少步 :type nums: List[int] :rtype: int - def jump2(self, nums): 优化代码 与上面不同的是,这是根据i更新last,上面是根据num[i]和i的和判断是不是能跳过前面跳得...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def jump(self, nums): max_dump 在第i个元素最远能跳到的距离 dp[i]:跳到第i个元素最少需要多少步 :type nums: List[int] :rtype: int - def jump2(self, nums): 优化代码 与上面不同的是,这是根据i更新last,上面是根据num[i]和i的和判断是不是能跳过前面跳得...
5d3574ccd282d0146c83c286ae28d8baaabd4910
<|skeleton|> class Solution: def jump(self, nums): """max_dump 在第i个元素最远能跳到的距离 dp[i]:跳到第i个元素最少需要多少步 :type nums: List[int] :rtype: int""" <|body_0|> def jump2(self, nums): """优化代码 与上面不同的是,这是根据i更新last,上面是根据num[i]和i的和判断是不是能跳过前面跳得最大值。 f[i]: 到达i所需要的最少步数 last: 第一次到达i时上一步的位置 根据贪心得知,令f[i]=f[las...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def jump(self, nums): """max_dump 在第i个元素最远能跳到的距离 dp[i]:跳到第i个元素最少需要多少步 :type nums: List[int] :rtype: int""" if len(nums) <= 1: return 0 n = len(nums) dp = [0] * n max_dump = nums[0] dp[0] = 0 dp[1:max_dump + 1] = [1] * max_dump ...
the_stack_v2_python_sparse
45_跳跃游戏 II.py
lovehhf/LeetCode
train
0
6100f1a09996674b67a958a7026ada368ae699fb
[ "nn.Module.__init__(self)\nself.P = P\nself.nu = nu\nself.eps = eps", "dist = torch.sum((input - torch.matmul(self.P, input.transpose(0, 1)).transpose(0, 1)) ** 2, dim=1)\nif self.soft_boundary:\n scores = dist - R ** 2\n loss = R ** 2 + 1 / self.nu * torch.mean(torch.max(torch.zeros_like(scores), scores))\...
<|body_start_0|> nn.Module.__init__(self) self.P = P self.nu = nu self.eps = eps <|end_body_0|> <|body_start_1|> dist = torch.sum((input - torch.matmul(self.P, input.transpose(0, 1)).transpose(0, 1)) ** 2, dim=1) if self.soft_boundary: scores = dist - R ** 2 ...
Implementation of the DeepSVDD loss proposed by Lukas Ruff et al. (2019) but with the distance of the point projected to the subspace of training samples rather than the hypersphere. It follows the mathematical derivation proposed by Arnout Devos et al. (2019).
DeepSVDDLossSubspace
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DeepSVDDLossSubspace: """Implementation of the DeepSVDD loss proposed by Lukas Ruff et al. (2019) but with the distance of the point projected to the subspace of training samples rather than the hypersphere. It follows the mathematical derivation proposed by Arnout Devos et al. (2019).""" de...
stack_v2_sparse_classes_36k_train_011206
18,386
permissive
[ { "docstring": "Constructor of the DeepSVDD loss Subspace. ---------- INPUT |---- P (torch.Tensor) The projection matrix to the subspace of normal | sample. P is a MxM matrix where M is the embedding dimension. |---- nu (float) a priory fraction of outliers. |---- eps (float) epsilon to ensure numerical stabili...
2
stack_v2_sparse_classes_30k_train_000605
Implement the Python class `DeepSVDDLossSubspace` described below. Class description: Implementation of the DeepSVDD loss proposed by Lukas Ruff et al. (2019) but with the distance of the point projected to the subspace of training samples rather than the hypersphere. It follows the mathematical derivation proposed by...
Implement the Python class `DeepSVDDLossSubspace` described below. Class description: Implementation of the DeepSVDD loss proposed by Lukas Ruff et al. (2019) but with the distance of the point projected to the subspace of training samples rather than the hypersphere. It follows the mathematical derivation proposed by...
850b6195d6290a50eee865b4d5a66f5db5260e8f
<|skeleton|> class DeepSVDDLossSubspace: """Implementation of the DeepSVDD loss proposed by Lukas Ruff et al. (2019) but with the distance of the point projected to the subspace of training samples rather than the hypersphere. It follows the mathematical derivation proposed by Arnout Devos et al. (2019).""" de...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DeepSVDDLossSubspace: """Implementation of the DeepSVDD loss proposed by Lukas Ruff et al. (2019) but with the distance of the point projected to the subspace of training samples rather than the hypersphere. It follows the mathematical derivation proposed by Arnout Devos et al. (2019).""" def __init__(se...
the_stack_v2_python_sparse
Code/src/models/optim/CustomLosses.py
antoine-spahr/X-ray-Anomaly-Detection
train
3
16f9664f34326755cc256a0606a3f32728fae5f3
[ "input1 = tf.random.stateless_normal([4, 4, 4], [234, 231])\nlayer1 = preproc_layers.Transpose(perm=perm, conjugate=conjugate)\noutput1 = layer1(input1)\nself.assertAllEqual(output1, tf.transpose(input1, perm=perm, conjugate=conjugate))", "config = dict(perm=[1, 0], conjugate=True, name='transpose', dtype='float3...
<|body_start_0|> input1 = tf.random.stateless_normal([4, 4, 4], [234, 231]) layer1 = preproc_layers.Transpose(perm=perm, conjugate=conjugate) output1 = layer1(input1) self.assertAllEqual(output1, tf.transpose(input1, perm=perm, conjugate=conjugate)) <|end_body_0|> <|body_start_1|> ...
Tests for layer `Transpose`.
TransposeTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TransposeTest: """Tests for layer `Transpose`.""" def test_result(self, perm, conjugate): """Test result shapes.""" <|body_0|> def test_serialize_deserialize(self): """Test de/serialization.""" <|body_1|> <|end_skeleton|> <|body_start_0|> input1...
stack_v2_sparse_classes_36k_train_011207
6,474
permissive
[ { "docstring": "Test result shapes.", "name": "test_result", "signature": "def test_result(self, perm, conjugate)" }, { "docstring": "Test de/serialization.", "name": "test_serialize_deserialize", "signature": "def test_serialize_deserialize(self)" } ]
2
stack_v2_sparse_classes_30k_train_018728
Implement the Python class `TransposeTest` described below. Class description: Tests for layer `Transpose`. Method signatures and docstrings: - def test_result(self, perm, conjugate): Test result shapes. - def test_serialize_deserialize(self): Test de/serialization.
Implement the Python class `TransposeTest` described below. Class description: Tests for layer `Transpose`. Method signatures and docstrings: - def test_result(self, perm, conjugate): Test result shapes. - def test_serialize_deserialize(self): Test de/serialization. <|skeleton|> class TransposeTest: """Tests for...
cfd8930ee5281e7f6dceb17c4a5acaf625fd3243
<|skeleton|> class TransposeTest: """Tests for layer `Transpose`.""" def test_result(self, perm, conjugate): """Test result shapes.""" <|body_0|> def test_serialize_deserialize(self): """Test de/serialization.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TransposeTest: """Tests for layer `Transpose`.""" def test_result(self, perm, conjugate): """Test result shapes.""" input1 = tf.random.stateless_normal([4, 4, 4], [234, 231]) layer1 = preproc_layers.Transpose(perm=perm, conjugate=conjugate) output1 = layer1(input1) ...
the_stack_v2_python_sparse
tensorflow_mri/python/layers/preproc_layers_test.py
mrphys/tensorflow-mri
train
29
9f9067b257de725c65c8a90d7dd0e34cc41bec04
[ "self.max = max\nself.num = 0\nself.condition = threading.Condition()", "with self.condition:\n while num + self.num > self.max:\n print('进货失败,请等待,进货数量%d,当前库存%d' % (num, self.num))\n self.condition.wait()\n self.num += num\n print('进货成功,进货数量%d, 当前库存%d' % (num, self.num))\n self.condition...
<|body_start_0|> self.max = max self.num = 0 self.condition = threading.Condition() <|end_body_0|> <|body_start_1|> with self.condition: while num + self.num > self.max: print('进货失败,请等待,进货数量%d,当前库存%d' % (num, self.num)) self.condition.wait() ...
Shop
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Shop: def __init__(self, max): """初始化 :param max: 最大库存 :param num: 当前库存""" <|body_0|> def stock(self, num): """进货 :param num: 进货数量 :return:""" <|body_1|> def sell(self, num): """售货 :param num: 售货数量 :return:""" <|body_2|> <|end_skeleton|>...
stack_v2_sparse_classes_36k_train_011208
2,308
no_license
[ { "docstring": "初始化 :param max: 最大库存 :param num: 当前库存", "name": "__init__", "signature": "def __init__(self, max)" }, { "docstring": "进货 :param num: 进货数量 :return:", "name": "stock", "signature": "def stock(self, num)" }, { "docstring": "售货 :param num: 售货数量 :return:", "name": ...
3
null
Implement the Python class `Shop` described below. Class description: Implement the Shop class. Method signatures and docstrings: - def __init__(self, max): 初始化 :param max: 最大库存 :param num: 当前库存 - def stock(self, num): 进货 :param num: 进货数量 :return: - def sell(self, num): 售货 :param num: 售货数量 :return:
Implement the Python class `Shop` described below. Class description: Implement the Shop class. Method signatures and docstrings: - def __init__(self, max): 初始化 :param max: 最大库存 :param num: 当前库存 - def stock(self, num): 进货 :param num: 进货数量 :return: - def sell(self, num): 售货 :param num: 售货数量 :return: <|skeleton|> clas...
b1f9eeef652812ddcfa30db33d82b077949b192a
<|skeleton|> class Shop: def __init__(self, max): """初始化 :param max: 最大库存 :param num: 当前库存""" <|body_0|> def stock(self, num): """进货 :param num: 进货数量 :return:""" <|body_1|> def sell(self, num): """售货 :param num: 售货数量 :return:""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Shop: def __init__(self, max): """初始化 :param max: 最大库存 :param num: 当前库存""" self.max = max self.num = 0 self.condition = threading.Condition() def stock(self, num): """进货 :param num: 进货数量 :return:""" with self.condition: while num + self.num > se...
the_stack_v2_python_sparse
python/06-线程/Work/exercise3.py
huiba7i/Intermediate-Course
train
1
88dc0939fa11949b7a97b6d9c1cf98d6cbc7b434
[ "good_num_count = 0\ndp = [0] * (N + 1)\nfor i in range(0, N + 1):\n if i < 10:\n if i == 2 or i == 5 or i == 6 or (i == 9):\n dp[i] = 2\n good_num_count += 1\n elif i == 0 or i == 1 or i == 8:\n dp[i] = 1\n else:\n front = dp[i / 10]\n back = dp[i ...
<|body_start_0|> good_num_count = 0 dp = [0] * (N + 1) for i in range(0, N + 1): if i < 10: if i == 2 or i == 5 or i == 6 or (i == 9): dp[i] = 2 good_num_count += 1 elif i == 0 or i == 1 or i == 8: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def rotatedDigits_dp_improved(self, N): """:type N: int :rtype: int""" <|body_0|> def rotatedDigits_dp(self, N): """:type N: int :rtype: int""" <|body_1|> def rotatedDigits(self, N): """:type N: int :rtype: int""" <|body_2|> <|...
stack_v2_sparse_classes_36k_train_011209
3,921
no_license
[ { "docstring": ":type N: int :rtype: int", "name": "rotatedDigits_dp_improved", "signature": "def rotatedDigits_dp_improved(self, N)" }, { "docstring": ":type N: int :rtype: int", "name": "rotatedDigits_dp", "signature": "def rotatedDigits_dp(self, N)" }, { "docstring": ":type N:...
3
stack_v2_sparse_classes_30k_train_018036
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rotatedDigits_dp_improved(self, N): :type N: int :rtype: int - def rotatedDigits_dp(self, N): :type N: int :rtype: int - def rotatedDigits(self, N): :type N: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rotatedDigits_dp_improved(self, N): :type N: int :rtype: int - def rotatedDigits_dp(self, N): :type N: int :rtype: int - def rotatedDigits(self, N): :type N: int :rtype: int ...
83e5dea02e99e512d2b34dac05dabebfdb66ef2a
<|skeleton|> class Solution: def rotatedDigits_dp_improved(self, N): """:type N: int :rtype: int""" <|body_0|> def rotatedDigits_dp(self, N): """:type N: int :rtype: int""" <|body_1|> def rotatedDigits(self, N): """:type N: int :rtype: int""" <|body_2|> <|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def rotatedDigits_dp_improved(self, N): """:type N: int :rtype: int""" good_num_count = 0 dp = [0] * (N + 1) for i in range(0, N + 1): if i < 10: if i == 2 or i == 5 or i == 6 or (i == 9): dp[i] = 2 g...
the_stack_v2_python_sparse
string_problem/788_rotatedDigits.py
wscheng/LeetCode
train
0
dc30df42e6ec220b20dc1c68c555d1d252300836
[ "vals = []\n\ndef build_res(root, res):\n if not root:\n res.append('#')\n return\n res.append(str(root.val))\n build_res(root.left, res)\n build_res(root.right, res)\nbuild_res(root, vals)\nprint(vals)\nreturn ','.join(vals)", "vals = iter(data.split(','))\n\ndef build_tree(vals):\n ...
<|body_start_0|> vals = [] def build_res(root, res): if not root: res.append('#') return res.append(str(root.val)) build_res(root.left, res) build_res(root.right, res) build_res(root, vals) print(vals) ...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode 12##34##5##""" <|body_1|> <|end_skeleto...
stack_v2_sparse_classes_36k_train_011210
1,630
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode 12##34##5##", "name": "deserialize", "signature": "de...
2
stack_v2_sparse_classes_30k_train_009626
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
523c11e8a5728168c4978c5a332e7e9bc4533ef7
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode 12##34##5##""" <|body_1|> <|end_skeleto...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" vals = [] def build_res(root, res): if not root: res.append('#') return res.append(str(root.val)) build_res(r...
the_stack_v2_python_sparse
297. Serialize and Deserialize Binary Tree/answer.py
LennyDuan/AlgorithmPython
train
0
daf79bd8d7e9f93793bd267bb36d7d790eeca8a6
[ "res = []\n\ndef DFS(path):\n tp = sum(path)\n if tp == target:\n res.append(path)\n return\n if tp > target:\n return\n for n in candidates:\n if path and n < path[-1]:\n continue\n DFS(path + [n])\nDFS([])\nreturn res", "res = []\ncandidates.sort()\n\nde...
<|body_start_0|> res = [] def DFS(path): tp = sum(path) if tp == target: res.append(path) return if tp > target: return for n in candidates: if path and n < path[-1]: cont...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def combinationSum(self, candidates, target): """:type candidates: List[int] :type target: int :rtype: List[List[int]]""" <|body_0|> def combinationSum_(self, candidates, target): """:type candidates: List[int] :type target: int :rtype: List[List[int]]""" ...
stack_v2_sparse_classes_36k_train_011211
3,701
no_license
[ { "docstring": ":type candidates: List[int] :type target: int :rtype: List[List[int]]", "name": "combinationSum", "signature": "def combinationSum(self, candidates, target)" }, { "docstring": ":type candidates: List[int] :type target: int :rtype: List[List[int]]", "name": "combinationSum_", ...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def combinationSum(self, candidates, target): :type candidates: List[int] :type target: int :rtype: List[List[int]] - def combinationSum_(self, candidates, target): :type candida...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def combinationSum(self, candidates, target): :type candidates: List[int] :type target: int :rtype: List[List[int]] - def combinationSum_(self, candidates, target): :type candida...
fab4c341486e872fb2926d1b6d50499d55e76a4a
<|skeleton|> class Solution: def combinationSum(self, candidates, target): """:type candidates: List[int] :type target: int :rtype: List[List[int]]""" <|body_0|> def combinationSum_(self, candidates, target): """:type candidates: List[int] :type target: int :rtype: List[List[int]]""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def combinationSum(self, candidates, target): """:type candidates: List[int] :type target: int :rtype: List[List[int]]""" res = [] def DFS(path): tp = sum(path) if tp == target: res.append(path) return if tp...
the_stack_v2_python_sparse
leetcode/39. Combination Sum.py
lunar-r/sword-to-offer-python
train
0
7650ecfebbddf9cf2df44436335096637af0a5d0
[ "super().__init__(apply_sd, apply_ls, apply_svls, apply_mask, class_weights, edge_weight)\nself.alpha = alpha\nself.gamma = gamma\nself.eps = 1e-08", "input_soft = F.softmax(yhat, dim=1) + self.eps\nnum_classes = yhat.shape[1]\ntarget_one_hot = tensor_one_hot(target, num_classes)\nassert target_one_hot.shape == y...
<|body_start_0|> super().__init__(apply_sd, apply_ls, apply_svls, apply_mask, class_weights, edge_weight) self.alpha = alpha self.gamma = gamma self.eps = 1e-08 <|end_body_0|> <|body_start_1|> input_soft = F.softmax(yhat, dim=1) + self.eps num_classes = yhat.shape[1] ...
FocalLoss
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FocalLoss: def __init__(self, alpha: float=0.5, gamma: float=2.0, apply_sd: bool=False, apply_ls: bool=False, apply_svls: bool=False, apply_mask: bool=False, edge_weight: float=None, class_weights: torch.Tensor=None, **kwargs) -> None: """Focal loss. https://arxiv.org/abs/1708.02002 Opti...
stack_v2_sparse_classes_36k_train_011212
3,788
permissive
[ { "docstring": "Focal loss. https://arxiv.org/abs/1708.02002 Optionally applies, label smoothing, spatially varying label smoothing or weights at the object edges or class weights to the loss. Parameters ---------- alpha : float, default=0.5 Weight factor b/w [0,1]. gamma : float, default=2.0 Focusing factor. a...
2
stack_v2_sparse_classes_30k_train_013241
Implement the Python class `FocalLoss` described below. Class description: Implement the FocalLoss class. Method signatures and docstrings: - def __init__(self, alpha: float=0.5, gamma: float=2.0, apply_sd: bool=False, apply_ls: bool=False, apply_svls: bool=False, apply_mask: bool=False, edge_weight: float=None, clas...
Implement the Python class `FocalLoss` described below. Class description: Implement the FocalLoss class. Method signatures and docstrings: - def __init__(self, alpha: float=0.5, gamma: float=2.0, apply_sd: bool=False, apply_ls: bool=False, apply_svls: bool=False, apply_mask: bool=False, edge_weight: float=None, clas...
7f79405012eb934b419bbdba8de23f35e840ca85
<|skeleton|> class FocalLoss: def __init__(self, alpha: float=0.5, gamma: float=2.0, apply_sd: bool=False, apply_ls: bool=False, apply_svls: bool=False, apply_mask: bool=False, edge_weight: float=None, class_weights: torch.Tensor=None, **kwargs) -> None: """Focal loss. https://arxiv.org/abs/1708.02002 Opti...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FocalLoss: def __init__(self, alpha: float=0.5, gamma: float=2.0, apply_sd: bool=False, apply_ls: bool=False, apply_svls: bool=False, apply_mask: bool=False, edge_weight: float=None, class_weights: torch.Tensor=None, **kwargs) -> None: """Focal loss. https://arxiv.org/abs/1708.02002 Optionally applies...
the_stack_v2_python_sparse
cellseg_models_pytorch/losses/criterions/focal.py
okunator/cellseg_models.pytorch
train
43
a3cd96a44fd7390abd469390a5651162a4fe4e62
[ "self.X = X\nself.y = y\nself.iterator = 0\nself.batchsize = batchsize", "start = self.iterator\nend = self.iterator + self.batchsize\nself.iterator = end if end < len(self.X) else 0\nreturn (self.X[start:end], self.y[start:end])", "r = []\nfor i in xrange(0, len(l), n):\n r.append(l[i:i + n])\nreturn r" ]
<|body_start_0|> self.X = X self.y = y self.iterator = 0 self.batchsize = batchsize <|end_body_0|> <|body_start_1|> start = self.iterator end = self.iterator + self.batchsize self.iterator = end if end < len(self.X) else 0 return (self.X[start:end], self....
a helper class to create batches given a dataset
Batcher
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Batcher: """a helper class to create batches given a dataset""" def __init__(self, X, y, batchsize=50): """:param X: array(any) : array of whole training inputs :param y: array(any) : array of correct training labels :param batchsize: integer : default = 50, :return: self""" ...
stack_v2_sparse_classes_36k_train_011213
8,798
permissive
[ { "docstring": ":param X: array(any) : array of whole training inputs :param y: array(any) : array of correct training labels :param batchsize: integer : default = 50, :return: self", "name": "__init__", "signature": "def __init__(self, X, y, batchsize=50)" }, { "docstring": "return the next tra...
3
stack_v2_sparse_classes_30k_train_016606
Implement the Python class `Batcher` described below. Class description: a helper class to create batches given a dataset Method signatures and docstrings: - def __init__(self, X, y, batchsize=50): :param X: array(any) : array of whole training inputs :param y: array(any) : array of correct training labels :param bat...
Implement the Python class `Batcher` described below. Class description: a helper class to create batches given a dataset Method signatures and docstrings: - def __init__(self, X, y, batchsize=50): :param X: array(any) : array of whole training inputs :param y: array(any) : array of correct training labels :param bat...
544e843c5430abdd58138cdf1c79dcf240168a5f
<|skeleton|> class Batcher: """a helper class to create batches given a dataset""" def __init__(self, X, y, batchsize=50): """:param X: array(any) : array of whole training inputs :param y: array(any) : array of correct training labels :param batchsize: integer : default = 50, :return: self""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Batcher: """a helper class to create batches given a dataset""" def __init__(self, X, y, batchsize=50): """:param X: array(any) : array of whole training inputs :param y: array(any) : array of correct training labels :param batchsize: integer : default = 50, :return: self""" self.X = X ...
the_stack_v2_python_sparse
scripts/study_case/ID_44/CNN_grist.py
Liang813/GRIST
train
0
8aeff0b9ef4ccbf9a8a6c374cb3566705965f099
[ "self.num_layer = num_layer\nself.unit_dim = unit_dim\nself.activation = activation\nself.dropout = dropout\nself.num_gpus = num_gpus\nself.default_gpu_id = default_gpu_id\nself.regularizer = regularizer\nself.random_seed = random_seed\nself.trainable = trainable\nself.scope = scope\nself.device_spec = get_device_s...
<|body_start_0|> self.num_layer = num_layer self.unit_dim = unit_dim self.activation = activation self.dropout = dropout self.num_gpus = num_gpus self.default_gpu_id = default_gpu_id self.regularizer = regularizer self.random_seed = random_seed sel...
stacked highway layer
StackedHighway
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StackedHighway: """stacked highway layer""" def __init__(self, num_layer, unit_dim, activation, dropout, num_gpus=1, default_gpu_id=0, regularizer=None, random_seed=0, trainable=True, scope='stacked_highway'): """initialize stacked highway layer""" <|body_0|> def __call_...
stack_v2_sparse_classes_36k_train_011214
9,944
permissive
[ { "docstring": "initialize stacked highway layer", "name": "__init__", "signature": "def __init__(self, num_layer, unit_dim, activation, dropout, num_gpus=1, default_gpu_id=0, regularizer=None, random_seed=0, trainable=True, scope='stacked_highway')" }, { "docstring": "call stacked highway layer...
2
stack_v2_sparse_classes_30k_train_004292
Implement the Python class `StackedHighway` described below. Class description: stacked highway layer Method signatures and docstrings: - def __init__(self, num_layer, unit_dim, activation, dropout, num_gpus=1, default_gpu_id=0, regularizer=None, random_seed=0, trainable=True, scope='stacked_highway'): initialize sta...
Implement the Python class `StackedHighway` described below. Class description: stacked highway layer Method signatures and docstrings: - def __init__(self, num_layer, unit_dim, activation, dropout, num_gpus=1, default_gpu_id=0, regularizer=None, random_seed=0, trainable=True, scope='stacked_highway'): initialize sta...
05fcbec15e359e3db86af6c3798c13be8a6c58ee
<|skeleton|> class StackedHighway: """stacked highway layer""" def __init__(self, num_layer, unit_dim, activation, dropout, num_gpus=1, default_gpu_id=0, regularizer=None, random_seed=0, trainable=True, scope='stacked_highway'): """initialize stacked highway layer""" <|body_0|> def __call_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StackedHighway: """stacked highway layer""" def __init__(self, num_layer, unit_dim, activation, dropout, num_gpus=1, default_gpu_id=0, regularizer=None, random_seed=0, trainable=True, scope='stacked_highway'): """initialize stacked highway layer""" self.num_layer = num_layer self....
the_stack_v2_python_sparse
sequence_labeling/layer/highway.py
stevezheng23/sequence_labeling_tf
train
18
da6a7d60e535c3193f9293d9d8af579d76aed5c1
[ "s = {}\nfor w in words:\n k = 0\n for c in w:\n k |= 1 << ord(c) - ord('a')\n s[k] = max(s.get(k, 0), len(w))\nreturn max([s[i] * s[j] for i in s for j in s if not i & j] or [0])", "import itertools\ncom = itertools.combinations(words, 2)\nres = []\nfor c in com:\n i = list(c)[0]\n j = list...
<|body_start_0|> s = {} for w in words: k = 0 for c in w: k |= 1 << ord(c) - ord('a') s[k] = max(s.get(k, 0), len(w)) return max([s[i] * s[j] for i in s for j in s if not i & j] or [0]) <|end_body_0|> <|body_start_1|> import itertools ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxProduct(self, words): """:type words: List[str] :rtype: int""" <|body_0|> def maxProduct2(self, words): """:type words: List[str] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> s = {} for w in words: ...
stack_v2_sparse_classes_36k_train_011215
1,952
no_license
[ { "docstring": ":type words: List[str] :rtype: int", "name": "maxProduct", "signature": "def maxProduct(self, words)" }, { "docstring": ":type words: List[str] :rtype: int", "name": "maxProduct2", "signature": "def maxProduct2(self, words)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProduct(self, words): :type words: List[str] :rtype: int - def maxProduct2(self, words): :type words: List[str] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProduct(self, words): :type words: List[str] :rtype: int - def maxProduct2(self, words): :type words: List[str] :rtype: int <|skeleton|> class Solution: def maxProdu...
416fed6e441612e1ad82467d07ee1b5570386a94
<|skeleton|> class Solution: def maxProduct(self, words): """:type words: List[str] :rtype: int""" <|body_0|> def maxProduct2(self, words): """:type words: List[str] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxProduct(self, words): """:type words: List[str] :rtype: int""" s = {} for w in words: k = 0 for c in w: k |= 1 << ord(c) - ord('a') s[k] = max(s.get(k, 0), len(w)) return max([s[i] * s[j] for i in s for j in s...
the_stack_v2_python_sparse
src/python/max_product_of_word_length.py
liadbiz/Leetcode-Solutions
train
1
85e574e76cdd1477e0e3e605c1e5dc1b1b322940
[ "pa, pb = (headA, headB)\nwhile pa != pb:\n pa = pa.next if pa else headB\n pb = pb.next if pb else headA\nreturn pa", "bag = set()\nwhile headA:\n bag.add(headA)\n headA = headA.next\nwhile headB:\n if headB in bag:\n return headB\n headB = headB.next\nreturn None" ]
<|body_start_0|> pa, pb = (headA, headB) while pa != pb: pa = pa.next if pa else headB pb = pb.next if pb else headA return pa <|end_body_0|> <|body_start_1|> bag = set() while headA: bag.add(headA) headA = headA.next while...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def getIntersectionNode(self, headA, headB): """:type head1, head1: ListNode :rtype: ListNode""" <|body_0|> def getIntersectionNode_v0(self, headA, headB): """:type head1, head1: ListNode :rtype: ListNode""" <|body_1|> <|end_skeleton|> <|body_star...
stack_v2_sparse_classes_36k_train_011216
3,643
no_license
[ { "docstring": ":type head1, head1: ListNode :rtype: ListNode", "name": "getIntersectionNode", "signature": "def getIntersectionNode(self, headA, headB)" }, { "docstring": ":type head1, head1: ListNode :rtype: ListNode", "name": "getIntersectionNode_v0", "signature": "def getIntersection...
2
stack_v2_sparse_classes_30k_train_020473
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getIntersectionNode(self, headA, headB): :type head1, head1: ListNode :rtype: ListNode - def getIntersectionNode_v0(self, headA, headB): :type head1, head1: ListNode :rtype: ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getIntersectionNode(self, headA, headB): :type head1, head1: ListNode :rtype: ListNode - def getIntersectionNode_v0(self, headA, headB): :type head1, head1: ListNode :rtype: ...
b5e09f24e8e96454dc99e20281e853fb9fcc85ed
<|skeleton|> class Solution: def getIntersectionNode(self, headA, headB): """:type head1, head1: ListNode :rtype: ListNode""" <|body_0|> def getIntersectionNode_v0(self, headA, headB): """:type head1, head1: ListNode :rtype: ListNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def getIntersectionNode(self, headA, headB): """:type head1, head1: ListNode :rtype: ListNode""" pa, pb = (headA, headB) while pa != pb: pa = pa.next if pa else headB pb = pb.next if pb else headA return pa def getIntersectionNode_v0(self,...
the_stack_v2_python_sparse
python/160_Intersection_of_Two_Linked_Lists.py
Moby5/myleetcode
train
2
bbda1018cacb1590e5985c5bc1588e09791c2cf5
[ "self.Wxh = torch.randn(num_hidden, num_in)\nself.Wxh = self.Wxh * math.pow(2 / (num_in + num_hidden), 0.5)\nself.Bxh = torch.zeros(num_hidden, 1)\nself.Whh = torch.randn(num_hidden, num_hidden)\nself.Whh = self.Whh * math.pow(2 / (num_hidden + num_hidden), 0.5)\nself.Bhh = torch.zeros(num_hidden, 1)\nself.paramete...
<|body_start_0|> self.Wxh = torch.randn(num_hidden, num_in) self.Wxh = self.Wxh * math.pow(2 / (num_in + num_hidden), 0.5) self.Bxh = torch.zeros(num_hidden, 1) self.Whh = torch.randn(num_hidden, num_hidden) self.Whh = self.Whh * math.pow(2 / (num_hidden + num_hidden), 0.5) ...
Consists of only input and the computed hidden states are the outputs, which will be inputs for the next such layer. The last RNN should have only one output, that is only the final hidden state, after which we would apply a Linear Layer.
MultiRNN
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiRNN: """Consists of only input and the computed hidden states are the outputs, which will be inputs for the next such layer. The last RNN should have only one output, that is only the final hidden state, after which we would apply a Linear Layer.""" def __init__(self, num_in, num_hidden...
stack_v2_sparse_classes_36k_train_011217
5,430
no_license
[ { "docstring": "num_in = size of the one-hot encoded input \"word\". One element of such a batch will have many such \"words\".", "name": "__init__", "signature": "def __init__(self, num_in, num_hidden, activation=torch.tanh)" }, { "docstring": "For transferring to GPU device", "name": "cuda...
5
stack_v2_sparse_classes_30k_train_006161
Implement the Python class `MultiRNN` described below. Class description: Consists of only input and the computed hidden states are the outputs, which will be inputs for the next such layer. The last RNN should have only one output, that is only the final hidden state, after which we would apply a Linear Layer. Metho...
Implement the Python class `MultiRNN` described below. Class description: Consists of only input and the computed hidden states are the outputs, which will be inputs for the next such layer. The last RNN should have only one output, that is only the final hidden state, after which we would apply a Linear Layer. Metho...
73e083a71ee19346be494ec7026ac82a343823bb
<|skeleton|> class MultiRNN: """Consists of only input and the computed hidden states are the outputs, which will be inputs for the next such layer. The last RNN should have only one output, that is only the final hidden state, after which we would apply a Linear Layer.""" def __init__(self, num_in, num_hidden...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultiRNN: """Consists of only input and the computed hidden states are the outputs, which will be inputs for the next such layer. The last RNN should have only one output, that is only the final hidden state, after which we would apply a Linear Layer.""" def __init__(self, num_in, num_hidden, activation=...
the_stack_v2_python_sparse
Assignment 4/MultiRNN.py
rohitrango/CS763
train
1
b98b1402b39c554aca687d3394d583fb8f475d13
[ "assert 0 < smoothing < 1, 'Smoothing factor should be in (0.0, 1.0)'\nassert reduction in {'batchmean', 'none', 'sum'}\nsuper().__init__()\nself.smoothing = smoothing\nself.ignore_index = ignore_index\nself.reduction = reduction", "target = target.view(-1, 1)\nsmoothed_target = torch.zeros(input.shape, requires_...
<|body_start_0|> assert 0 < smoothing < 1, 'Smoothing factor should be in (0.0, 1.0)' assert reduction in {'batchmean', 'none', 'sum'} super().__init__() self.smoothing = smoothing self.ignore_index = ignore_index self.reduction = reduction <|end_body_0|> <|body_start_1|...
Computes cross entropy loss with uniformly smoothed targets.
SmoothedCrossEntropyLoss
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SmoothedCrossEntropyLoss: """Computes cross entropy loss with uniformly smoothed targets.""" def __init__(self, smoothing: float=0.1, ignore_index: int=PAD_ID, reduction: str='batchmean'): """Cross entropy loss with uniformly smoothed targets. :param float smoothing: Label smoothing ...
stack_v2_sparse_classes_36k_train_011218
6,633
no_license
[ { "docstring": "Cross entropy loss with uniformly smoothed targets. :param float smoothing: Label smoothing factor, between 0 and 1 (exclusive; default is 0.1) :param int ignore_index: Index to be ignored. (PAD_ID by default) :param str reduction: Style of reduction to be done. One of 'batchmean'(default), 'non...
2
stack_v2_sparse_classes_30k_test_001033
Implement the Python class `SmoothedCrossEntropyLoss` described below. Class description: Computes cross entropy loss with uniformly smoothed targets. Method signatures and docstrings: - def __init__(self, smoothing: float=0.1, ignore_index: int=PAD_ID, reduction: str='batchmean'): Cross entropy loss with uniformly s...
Implement the Python class `SmoothedCrossEntropyLoss` described below. Class description: Computes cross entropy loss with uniformly smoothed targets. Method signatures and docstrings: - def __init__(self, smoothing: float=0.1, ignore_index: int=PAD_ID, reduction: str='batchmean'): Cross entropy loss with uniformly s...
719e6a19f42fc41f1436fc072d556f450682a890
<|skeleton|> class SmoothedCrossEntropyLoss: """Computes cross entropy loss with uniformly smoothed targets.""" def __init__(self, smoothing: float=0.1, ignore_index: int=PAD_ID, reduction: str='batchmean'): """Cross entropy loss with uniformly smoothed targets. :param float smoothing: Label smoothing ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SmoothedCrossEntropyLoss: """Computes cross entropy loss with uniformly smoothed targets.""" def __init__(self, smoothing: float=0.1, ignore_index: int=PAD_ID, reduction: str='batchmean'): """Cross entropy loss with uniformly smoothed targets. :param float smoothing: Label smoothing factor, betwe...
the_stack_v2_python_sparse
page/model/loss.py
hi-math/EPT
train
0
94f170644092d94ebfc6a2aff1e751daca41ad87
[ "y_true = self.y_test.to_numpy()\ny_pred = net.predict(self.x_test)\ny_pred = np.array([[1 - y[0], y[0]] for y in y_pred])\nif self.apply_bayes:\n y_pred = self._apply_bayes(y_pred)\ny_pred = np.argmax(y_pred, axis=1)\nloss = log_loss(y_true, y_pred)\nf1 = f1_score(y_true, y_pred, average='macro')\naccuracy = ac...
<|body_start_0|> y_true = self.y_test.to_numpy() y_pred = net.predict(self.x_test) y_pred = np.array([[1 - y[0], y[0]] for y in y_pred]) if self.apply_bayes: y_pred = self._apply_bayes(y_pred) y_pred = np.argmax(y_pred, axis=1) loss = log_loss(y_true, y_pred) ...
Base model for binary classification: htop vs background
BinaryClassifier
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BinaryClassifier: """Base model for binary classification: htop vs background""" def test(self, net: training.Model, verbose=True): """Test the networks performance :param net the trained network""" <|body_0|> def get_net(self): """Get the network. Use bas networ...
stack_v2_sparse_classes_36k_train_011219
3,597
permissive
[ { "docstring": "Test the networks performance :param net the trained network", "name": "test", "signature": "def test(self, net: training.Model, verbose=True)" }, { "docstring": "Get the network. Use bas network and append Dense(1) with sigmoid", "name": "get_net", "signature": "def get_...
6
stack_v2_sparse_classes_30k_train_014077
Implement the Python class `BinaryClassifier` described below. Class description: Base model for binary classification: htop vs background Method signatures and docstrings: - def test(self, net: training.Model, verbose=True): Test the networks performance :param net the trained network - def get_net(self): Get the ne...
Implement the Python class `BinaryClassifier` described below. Class description: Base model for binary classification: htop vs background Method signatures and docstrings: - def test(self, net: training.Model, verbose=True): Test the networks performance :param net the trained network - def get_net(self): Get the ne...
4b6c563f93e1eb7fc90f66a9a6ada16c07664d71
<|skeleton|> class BinaryClassifier: """Base model for binary classification: htop vs background""" def test(self, net: training.Model, verbose=True): """Test the networks performance :param net the trained network""" <|body_0|> def get_net(self): """Get the network. Use bas networ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BinaryClassifier: """Base model for binary classification: htop vs background""" def test(self, net: training.Model, verbose=True): """Test the networks performance :param net the trained network""" y_true = self.y_test.to_numpy() y_pred = net.predict(self.x_test) y_pred =...
the_stack_v2_python_sparse
Element2/BinaryClassification.py
AuckeBos/MLiPPaA
train
1
61b16a72ae750a1593104cb700e662b5506640b5
[ "if task_type not in task_types:\n self.abort(400)\ntask_obj, callback = task_types[task_type]\ntask = task_obj.AsyncResult(task_id)\nif task.state == 'FAILURE':\n if db:\n rec = Task.query.filter_by(uuid=task_id).first()\n if rec:\n try:\n db.session.delete(rec)\n ...
<|body_start_0|> if task_type not in task_types: self.abort(400) task_obj, callback = task_types[task_type] task = task_obj.AsyncResult(task_id) if task.state == 'FAILURE': if db: rec = Task.query.filter_by(uuid=task_id).first() if ...
The :class:`burpui.api.tasks.TaskStatus` resource allows you to follow a restore task. This resource is part of the :mod:`burpui.api.tasks` module.
TaskStatus
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TaskStatus: """The :class:`burpui.api.tasks.TaskStatus` resource allows you to follow a restore task. This resource is part of the :mod:`burpui.api.tasks` module.""" def get(self, task_type, task_id, server=None): """Returns the state of the given task""" <|body_0|> def ...
stack_v2_sparse_classes_36k_train_011220
32,795
permissive
[ { "docstring": "Returns the state of the given task", "name": "get", "signature": "def get(self, task_type, task_id, server=None)" }, { "docstring": "Cancel a given task", "name": "delete", "signature": "def delete(self, task_type, task_id, server=None)" } ]
2
stack_v2_sparse_classes_30k_train_016012
Implement the Python class `TaskStatus` described below. Class description: The :class:`burpui.api.tasks.TaskStatus` resource allows you to follow a restore task. This resource is part of the :mod:`burpui.api.tasks` module. Method signatures and docstrings: - def get(self, task_type, task_id, server=None): Returns th...
Implement the Python class `TaskStatus` described below. Class description: The :class:`burpui.api.tasks.TaskStatus` resource allows you to follow a restore task. This resource is part of the :mod:`burpui.api.tasks` module. Method signatures and docstrings: - def get(self, task_type, task_id, server=None): Returns th...
2b8c6e09a4174f2ae3545fa048f59c55c4ae7dba
<|skeleton|> class TaskStatus: """The :class:`burpui.api.tasks.TaskStatus` resource allows you to follow a restore task. This resource is part of the :mod:`burpui.api.tasks` module.""" def get(self, task_type, task_id, server=None): """Returns the state of the given task""" <|body_0|> def ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TaskStatus: """The :class:`burpui.api.tasks.TaskStatus` resource allows you to follow a restore task. This resource is part of the :mod:`burpui.api.tasks` module.""" def get(self, task_type, task_id, server=None): """Returns the state of the given task""" if task_type not in task_types: ...
the_stack_v2_python_sparse
burpui/api/tasks.py
ziirish/burp-ui
train
98
8ef151572633952c6a1f2fe4b0bc5df8a20de7c4
[ "if not head:\n return head\nrh = head\nnode = head\nwhile node:\n next = node.next\n if next:\n next_node = next.next\n next.next = node\n node.next = rh\n rh = next\n else:\n next_node = None\n node.next = rh\n rh = node\n node = next_node\nhead.next...
<|body_start_0|> if not head: return head rh = head node = head while node: next = node.next if next: next_node = next.next next.next = node node.next = rh rh = next else: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def reverseList(self, head): """:type head: ListNode :rtype: ListNode""" <|body_0|> def isPalindrome(self, head): """:type head: ListNode :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not head: return head ...
stack_v2_sparse_classes_36k_train_011221
1,293
no_license
[ { "docstring": ":type head: ListNode :rtype: ListNode", "name": "reverseList", "signature": "def reverseList(self, head)" }, { "docstring": ":type head: ListNode :rtype: bool", "name": "isPalindrome", "signature": "def isPalindrome(self, head)" } ]
2
stack_v2_sparse_classes_30k_train_017726
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseList(self, head): :type head: ListNode :rtype: ListNode - def isPalindrome(self, head): :type head: ListNode :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseList(self, head): :type head: ListNode :rtype: ListNode - def isPalindrome(self, head): :type head: ListNode :rtype: bool <|skeleton|> class Solution: def revers...
4eee28430754dd5187cd3f9e86a81be3f6664f46
<|skeleton|> class Solution: def reverseList(self, head): """:type head: ListNode :rtype: ListNode""" <|body_0|> def isPalindrome(self, head): """:type head: ListNode :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def reverseList(self, head): """:type head: ListNode :rtype: ListNode""" if not head: return head rh = head node = head while node: next = node.next if next: next_node = next.next next.next = ...
the_stack_v2_python_sparse
leetcode/python/easy/palindrom_linked_list.py
13leaf/exercises
train
0
f0fdc703bec438b7888bd3eda6197aa328da1791
[ "models = registry.models.values()\nmodels = sorted(models, key=lambda x: x.label)\nserializer = ModelSerializer(models, many=True)\nreturn Response(serializer.data)", "model = registry.models.get(pk)\nif model is None:\n raise Http404\nserializer = ModelSerializer(model)\nreturn Response(serializer.data)" ]
<|body_start_0|> models = registry.models.values() models = sorted(models, key=lambda x: x.label) serializer = ModelSerializer(models, many=True) return Response(serializer.data) <|end_body_0|> <|body_start_1|> model = registry.models.get(pk) if model is None: ...
Viewset around model information.
ModelViewSet
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ModelViewSet: """Viewset around model information.""" def list(self, request): """Get a list of models.""" <|body_0|> def retrieve(self, request, pk=None): """Get a specific model.""" <|body_1|> <|end_skeleton|> <|body_start_0|> models = registr...
stack_v2_sparse_classes_36k_train_011222
9,625
permissive
[ { "docstring": "Get a list of models.", "name": "list", "signature": "def list(self, request)" }, { "docstring": "Get a specific model.", "name": "retrieve", "signature": "def retrieve(self, request, pk=None)" } ]
2
stack_v2_sparse_classes_30k_train_002237
Implement the Python class `ModelViewSet` described below. Class description: Viewset around model information. Method signatures and docstrings: - def list(self, request): Get a list of models. - def retrieve(self, request, pk=None): Get a specific model.
Implement the Python class `ModelViewSet` described below. Class description: Viewset around model information. Method signatures and docstrings: - def list(self, request): Get a list of models. - def retrieve(self, request, pk=None): Get a specific model. <|skeleton|> class ModelViewSet: """Viewset around model...
aaab76706c8268d3ff3e87c275baee9dd4714314
<|skeleton|> class ModelViewSet: """Viewset around model information.""" def list(self, request): """Get a list of models.""" <|body_0|> def retrieve(self, request, pk=None): """Get a specific model.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ModelViewSet: """Viewset around model information.""" def list(self, request): """Get a list of models.""" models = registry.models.values() models = sorted(models, key=lambda x: x.label) serializer = ModelSerializer(models, many=True) return Response(serializer.da...
the_stack_v2_python_sparse
web/api/views.py
rcbops/FleetDeploymentReporting
train
1
46dd4e6be3f394ac89dbd6b31f5f942478641273
[ "sums = sum(nums)\nif sums & 1 == 1:\n return False\nhalf = sums // 2\ndp = [False] * (half + 1)\ndp[0] = True\nfor n in nums:\n for i in range(half, n - 1, -1):\n dp[i] |= dp[i - n]\nreturn dp[half]", "def rec(curr, nums):\n if sum(curr) == sum(nums):\n return True\n elif sum(curr) > su...
<|body_start_0|> sums = sum(nums) if sums & 1 == 1: return False half = sums // 2 dp = [False] * (half + 1) dp[0] = True for n in nums: for i in range(half, n - 1, -1): dp[i] |= dp[i - n] return dp[half] <|end_body_0|> <|bo...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def canPartition(self, nums): """:type nums: List[int] :rtype: bool""" <|body_0|> def canPartition_TLE(self, nums): """:type nums: List[int] :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> sums = sum(nums) if sums & 1 ...
stack_v2_sparse_classes_36k_train_011223
3,632
no_license
[ { "docstring": ":type nums: List[int] :rtype: bool", "name": "canPartition", "signature": "def canPartition(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: bool", "name": "canPartition_TLE", "signature": "def canPartition_TLE(self, nums)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canPartition(self, nums): :type nums: List[int] :rtype: bool - def canPartition_TLE(self, nums): :type nums: List[int] :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canPartition(self, nums): :type nums: List[int] :rtype: bool - def canPartition_TLE(self, nums): :type nums: List[int] :rtype: bool <|skeleton|> class Solution: def can...
2d5fa4cd696d5035ea8859befeadc5cc436959c9
<|skeleton|> class Solution: def canPartition(self, nums): """:type nums: List[int] :rtype: bool""" <|body_0|> def canPartition_TLE(self, nums): """:type nums: List[int] :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def canPartition(self, nums): """:type nums: List[int] :rtype: bool""" sums = sum(nums) if sums & 1 == 1: return False half = sums // 2 dp = [False] * (half + 1) dp[0] = True for n in nums: for i in range(half, n - 1, -1...
the_stack_v2_python_sparse
SourceCode/Python/Problem/00416.Partition Equal Subset Sum.py
roger6blog/LeetCode
train
0
81f5a8c856b9334baaa0a7a44c56fe5de989ec38
[ "errors = []\nif not HAS_TTP:\n errors.append(missing_required_lib('ttp'))\nreturn {'errors': errors}", "cli_output = self._task_args.get('text')\nres = self._check_reqs()\nif res.get('errors'):\n return {'errors': res.get('errors')}\ntry:\n parser = ttp(data=cli_output, template=self._task_args.get('par...
<|body_start_0|> errors = [] if not HAS_TTP: errors.append(missing_required_lib('ttp')) return {'errors': errors} <|end_body_0|> <|body_start_1|> cli_output = self._task_args.get('text') res = self._check_reqs() if res.get('errors'): return {'erro...
The ttp parser class Convert raw text to structured data using ttp
CliParser
[ "GPL-3.0-or-later", "GPL-3.0-only", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CliParser: """The ttp parser class Convert raw text to structured data using ttp""" def _check_reqs(): """Check the prerequisites for the ttp parser :return dict: A dict with errors or a template_path""" <|body_0|> def parse(self, *_args, **_kwargs): """Std entry...
stack_v2_sparse_classes_36k_train_011224
2,378
permissive
[ { "docstring": "Check the prerequisites for the ttp parser :return dict: A dict with errors or a template_path", "name": "_check_reqs", "signature": "def _check_reqs()" }, { "docstring": "Std entry point for a cli_parse parse execution :return: Errors or parsed text as structured data :rtype: di...
2
stack_v2_sparse_classes_30k_train_003439
Implement the Python class `CliParser` described below. Class description: The ttp parser class Convert raw text to structured data using ttp Method signatures and docstrings: - def _check_reqs(): Check the prerequisites for the ttp parser :return dict: A dict with errors or a template_path - def parse(self, *_args, ...
Implement the Python class `CliParser` described below. Class description: The ttp parser class Convert raw text to structured data using ttp Method signatures and docstrings: - def _check_reqs(): Check the prerequisites for the ttp parser :return dict: A dict with errors or a template_path - def parse(self, *_args, ...
2ea7d4f00212f502bc684ac257371ada73da1ca9
<|skeleton|> class CliParser: """The ttp parser class Convert raw text to structured data using ttp""" def _check_reqs(): """Check the prerequisites for the ttp parser :return dict: A dict with errors or a template_path""" <|body_0|> def parse(self, *_args, **_kwargs): """Std entry...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CliParser: """The ttp parser class Convert raw text to structured data using ttp""" def _check_reqs(): """Check the prerequisites for the ttp parser :return dict: A dict with errors or a template_path""" errors = [] if not HAS_TTP: errors.append(missing_required_lib('t...
the_stack_v2_python_sparse
intro-ansible/venv3/lib/python3.8/site-packages/ansible_collections/ansible/netcommon/plugins/cli_parsers/ttp_parser.py
SimonFangCisco/dne-dna-code
train
0
157dffc9b5668b4527b22df7076f75ed2d7d478b
[ "try:\n self.db = pymysql.connect(host=host, port=port, user=username, password=password)\n self.cursor = self.db.cursor()\nexcept pymysql.MySQLError as e:\n print(e.args)", "keys = ', '.join(data.keys())\nvalues = ', '.join(['%s'] * len(data))\nsql_query = 'insert into {table} values {keys} {values}'.fo...
<|body_start_0|> try: self.db = pymysql.connect(host=host, port=port, user=username, password=password) self.cursor = self.db.cursor() except pymysql.MySQLError as e: print(e.args) <|end_body_0|> <|body_start_1|> keys = ', '.join(data.keys()) values =...
MySQL
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MySQL: def __init__(self, host=MYSQL_HOST, port=MYSQL_PORT, username=MYSQL_USER, password=MYSQL_PASSWORD, database=MYSQL_DATABASE): """MySQL初始化 :param host: :param port: :param username: :param password: :param database:""" <|body_0|> def insert(self, table, data): "...
stack_v2_sparse_classes_36k_train_011225
1,476
no_license
[ { "docstring": "MySQL初始化 :param host: :param port: :param username: :param password: :param database:", "name": "__init__", "signature": "def __init__(self, host=MYSQL_HOST, port=MYSQL_PORT, username=MYSQL_USER, password=MYSQL_PASSWORD, database=MYSQL_DATABASE)" }, { "docstring": "插入数据 :param ta...
2
stack_v2_sparse_classes_30k_val_000404
Implement the Python class `MySQL` described below. Class description: Implement the MySQL class. Method signatures and docstrings: - def __init__(self, host=MYSQL_HOST, port=MYSQL_PORT, username=MYSQL_USER, password=MYSQL_PASSWORD, database=MYSQL_DATABASE): MySQL初始化 :param host: :param port: :param username: :param ...
Implement the Python class `MySQL` described below. Class description: Implement the MySQL class. Method signatures and docstrings: - def __init__(self, host=MYSQL_HOST, port=MYSQL_PORT, username=MYSQL_USER, password=MYSQL_PASSWORD, database=MYSQL_DATABASE): MySQL初始化 :param host: :param port: :param username: :param ...
916a3269cb3946f33bc87b289c5f20f26c265436
<|skeleton|> class MySQL: def __init__(self, host=MYSQL_HOST, port=MYSQL_PORT, username=MYSQL_USER, password=MYSQL_PASSWORD, database=MYSQL_DATABASE): """MySQL初始化 :param host: :param port: :param username: :param password: :param database:""" <|body_0|> def insert(self, table, data): "...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MySQL: def __init__(self, host=MYSQL_HOST, port=MYSQL_PORT, username=MYSQL_USER, password=MYSQL_PASSWORD, database=MYSQL_DATABASE): """MySQL初始化 :param host: :param port: :param username: :param password: :param database:""" try: self.db = pymysql.connect(host=host, port=port, user=...
the_stack_v2_python_sparse
Python3网络爬虫开发实战/chapter9/section5/mysql.py
daedalaus/practice
train
0
a9447dc8e0281bbe261e10880375e13b3b33a98e
[ "super().__init__()\nself.env = env\nself.policy = policy\nself.name = name\nself.service_interval = service_interval\nself.task_variability = task_variability\nself.terminal = terminal\nself.child = None", "token.worked_by(self)\npolicy_job = self.policy.request(self, token)\nservice_time = (yield policy_job.req...
<|body_start_0|> super().__init__() self.env = env self.policy = policy self.name = name self.service_interval = service_interval self.task_variability = task_variability self.terminal = terminal self.child = None <|end_body_0|> <|body_start_1|> t...
UserTask
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserTask: def __init__(self, env, policy, name, service_interval, task_variability, terminal=False): """Initializes a user task object. :param env: simpy environment. :param policy: assigned policy to be used by the user task. :param name: descriptive name. :param service_interval: mean ...
stack_v2_sparse_classes_36k_train_011226
6,685
no_license
[ { "docstring": "Initializes a user task object. :param env: simpy environment. :param policy: assigned policy to be used by the user task. :param name: descriptive name. :param service_interval: mean of service interval to be sampled. :param task_variability: per user task variability to be used for sampling us...
2
stack_v2_sparse_classes_30k_train_016448
Implement the Python class `UserTask` described below. Class description: Implement the UserTask class. Method signatures and docstrings: - def __init__(self, env, policy, name, service_interval, task_variability, terminal=False): Initializes a user task object. :param env: simpy environment. :param policy: assigned ...
Implement the Python class `UserTask` described below. Class description: Implement the UserTask class. Method signatures and docstrings: - def __init__(self, env, policy, name, service_interval, task_variability, terminal=False): Initializes a user task object. :param env: simpy environment. :param policy: assigned ...
9065c8e86f50f0d014e6a6159b7be379087a17c1
<|skeleton|> class UserTask: def __init__(self, env, policy, name, service_interval, task_variability, terminal=False): """Initializes a user task object. :param env: simpy environment. :param policy: assigned policy to be used by the user task. :param name: descriptive name. :param service_interval: mean ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserTask: def __init__(self, env, policy, name, service_interval, task_variability, terminal=False): """Initializes a user task object. :param env: simpy environment. :param policy: assigned policy to be used by the user task. :param name: descriptive name. :param service_interval: mean of service int...
the_stack_v2_python_sparse
elements/workflow_process_elements.py
fkocovski/optimaltaskassignment
train
0
bffdee286bb181c58149b92e91c869e82f3aa0a6
[ "self.account_name = credential.named_key.name\nself.account_key = credential.named_key.key\nself.x_ms_version = x_ms_version", "sas = _SharedAccessHelper()\nsas.add_base(permission, expiry, start, ip_address_or_range, protocol, self.x_ms_version)\nsas.add_account(services, resource_types)\nsas.add_account_signat...
<|body_start_0|> self.account_name = credential.named_key.name self.account_key = credential.named_key.key self.x_ms_version = x_ms_version <|end_body_0|> <|body_start_1|> sas = _SharedAccessHelper() sas.add_base(permission, expiry, start, ip_address_or_range, protocol, self.x_m...
Provides a factory for creating account access signature tokens with an account name and account key. Users can either use the factory or can construct the appropriate service and use the generate_*_shared_access_signature method directly. :ivar str account_name: The name of the Tables account. :ivar str account_key: T...
SharedAccessSignature
[ "LicenseRef-scancode-generic-cla", "MIT", "LGPL-2.1-or-later" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SharedAccessSignature: """Provides a factory for creating account access signature tokens with an account name and account key. Users can either use the factory or can construct the appropriate service and use the generate_*_shared_access_signature method directly. :ivar str account_name: The nam...
stack_v2_sparse_classes_36k_train_011227
11,959
permissive
[ { "docstring": ":param credential: The credential used for authenticating requests :type credential: ~azure.core.credentials.AzureNamedKeyCredential :param str x_ms_version: The service version used to generate the shared access signatures.", "name": "__init__", "signature": "def __init__(self, credenti...
2
null
Implement the Python class `SharedAccessSignature` described below. Class description: Provides a factory for creating account access signature tokens with an account name and account key. Users can either use the factory or can construct the appropriate service and use the generate_*_shared_access_signature method di...
Implement the Python class `SharedAccessSignature` described below. Class description: Provides a factory for creating account access signature tokens with an account name and account key. Users can either use the factory or can construct the appropriate service and use the generate_*_shared_access_signature method di...
c2ca191e736bb06bfbbbc9493e8325763ba990bb
<|skeleton|> class SharedAccessSignature: """Provides a factory for creating account access signature tokens with an account name and account key. Users can either use the factory or can construct the appropriate service and use the generate_*_shared_access_signature method directly. :ivar str account_name: The nam...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SharedAccessSignature: """Provides a factory for creating account access signature tokens with an account name and account key. Users can either use the factory or can construct the appropriate service and use the generate_*_shared_access_signature method directly. :ivar str account_name: The name of the Tabl...
the_stack_v2_python_sparse
sdk/tables/azure-data-tables/azure/data/tables/_shared_access_signature.py
Azure/azure-sdk-for-python
train
4,046
921dbdddf4b3add131887a38cc23c79b9e68c8d0
[ "if not link_share_id:\n link_shares = []\n for link_share in Link_Share.objects.filter(user=request.user).exclude(valid_till__lt=timezone.now()).exclude(allowed_reads__lte=0):\n link_shares.append({'id': link_share.id, 'public_title': link_share.public_title, 'allowed_reads': link_share.allowed_reads,...
<|body_start_0|> if not link_share_id: link_shares = [] for link_share in Link_Share.objects.filter(user=request.user).exclude(valid_till__lt=timezone.now()).exclude(allowed_reads__lte=0): link_shares.append({'id': link_share.id, 'public_title': link_share.public_title, '...
Check the REST Token and returns a list of all link_shares or the specified link_shares details
LinkShareView
[ "BSD-3-Clause", "MIT", "Apache-2.0", "BSD-2-Clause", "CC0-1.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LinkShareView: """Check the REST Token and returns a list of all link_shares or the specified link_shares details""" def get(self, request, link_share_id=None, *args, **kwargs): """Returns either a list of all link_shares with own access privileges or the members specified link_share...
stack_v2_sparse_classes_36k_train_011228
5,856
permissive
[ { "docstring": "Returns either a list of all link_shares with own access privileges or the members specified link_share :param request: :type request: :param link_share_id: :type link_share_id: :param args: :type args: :param kwargs: :type kwargs: :return: 200 / 403 :rtype:", "name": "get", "signature":...
4
stack_v2_sparse_classes_30k_train_012660
Implement the Python class `LinkShareView` described below. Class description: Check the REST Token and returns a list of all link_shares or the specified link_shares details Method signatures and docstrings: - def get(self, request, link_share_id=None, *args, **kwargs): Returns either a list of all link_shares with ...
Implement the Python class `LinkShareView` described below. Class description: Check the REST Token and returns a list of all link_shares or the specified link_shares details Method signatures and docstrings: - def get(self, request, link_share_id=None, *args, **kwargs): Returns either a list of all link_shares with ...
8936aa8ccdee8b9617ef7d894cb9a9a9f6f473cf
<|skeleton|> class LinkShareView: """Check the REST Token and returns a list of all link_shares or the specified link_shares details""" def get(self, request, link_share_id=None, *args, **kwargs): """Returns either a list of all link_shares with own access privileges or the members specified link_share...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LinkShareView: """Check the REST Token and returns a list of all link_shares or the specified link_shares details""" def get(self, request, link_share_id=None, *args, **kwargs): """Returns either a list of all link_shares with own access privileges or the members specified link_share :param reque...
the_stack_v2_python_sparse
psono/restapi/views/link_share.py
psono/psono-server
train
76
c1a7bcfd8a21426397955b444e0c6edbc0b0dd8d
[ "if not isinstance(wrap_layers, (list, tuple)):\n wrap_layers = [wrap_layers]\nself._wrap_layers = wrap_layers", "del state\n\ndef _sprite_to_polygons(layer, sprite):\n squared_polygons = [(sprite.vertices + np.array([i, j]), sprite.color, sprite.opacity) for i in [-1.0, 0.0, 1.0] for j in [-1.0, 0.0, 1.0]]...
<|body_start_0|> if not isinstance(wrap_layers, (list, tuple)): wrap_layers = [wrap_layers] self._wrap_layers = wrap_layers <|end_body_0|> <|body_start_1|> del state def _sprite_to_polygons(layer, sprite): squared_polygons = [(sprite.vertices + np.array([i, j]),...
Duplicates polygons at a grid of positions. Specifically, duplicates polygons at a 3x3 grid of positions centered around [0, 0] + polygon_position. This is used in torus environments to make a sprite appear to smoothly and incrementally disappear off one edge of the arena and reappear on the opposite edge.
TorusGeometry
[ "Apache-2.0", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TorusGeometry: """Duplicates polygons at a grid of positions. Specifically, duplicates polygons at a 3x3 grid of positions centered around [0, 0] + polygon_position. This is used in torus environments to make a sprite appear to smoothly and incrementally disappear off one edge of the arena and re...
stack_v2_sparse_classes_36k_train_011229
3,127
permissive
[ { "docstring": "Constructor. Args: wrap_layers: String or iterable of strings. All sprites in these layers will be rendered as if the arena is a torus.", "name": "__init__", "signature": "def __init__(self, wrap_layers)" }, { "docstring": "Get polygon modifier rendering sprites as if the arena i...
2
null
Implement the Python class `TorusGeometry` described below. Class description: Duplicates polygons at a grid of positions. Specifically, duplicates polygons at a 3x3 grid of positions centered around [0, 0] + polygon_position. This is used in torus environments to make a sprite appear to smoothly and incrementally dis...
Implement the Python class `TorusGeometry` described below. Class description: Duplicates polygons at a grid of positions. Specifically, duplicates polygons at a 3x3 grid of positions centered around [0, 0] + polygon_position. This is used in torus environments to make a sprite appear to smoothly and incrementally dis...
3e89e46a5918d59475851f9d4f1558956c110d38
<|skeleton|> class TorusGeometry: """Duplicates polygons at a grid of positions. Specifically, duplicates polygons at a 3x3 grid of positions centered around [0, 0] + polygon_position. This is used in torus environments to make a sprite appear to smoothly and incrementally disappear off one edge of the arena and re...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TorusGeometry: """Duplicates polygons at a grid of positions. Specifically, duplicates polygons at a 3x3 grid of positions centered around [0, 0] + polygon_position. This is used in torus environments to make a sprite appear to smoothly and incrementally disappear off one edge of the arena and reappear on the...
the_stack_v2_python_sparse
moog/observers/polygon_modifiers.py
hokysung/moog.github.io
train
0
60eecbc9886dc6e7e022d5c87830e49e1975c31f
[ "self.quark = quark\nself.nucleon = nucleon\nself.ip = input_dict", "self.mN = (self.ip['mproton'] + self.ip['mneutron']) / 2\nif self.nucleon == 'p':\n if self.quark == 'u':\n return self.mN ** 2 * self.ip['gA'] * self.ip['B0mu'] / self.mN\n if self.quark == 'd':\n return -self.mN ** 2 * self...
<|body_start_0|> self.quark = quark self.nucleon = nucleon self.ip = input_dict <|end_body_0|> <|body_start_1|> self.mN = (self.ip['mproton'] + self.ip['mneutron']) / 2 if self.nucleon == 'p': if self.quark == 'u': return self.mN ** 2 * self.ip['gA'] ...
FP
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FP: def __init__(self, quark, nucleon, input_dict): """The nuclear form factor FP Return the nuclear form factor FP Arguments --------- quark = 'u', 'd', 's' -- the quark flavor (up, down, strange) nucleon = 'p', 'n' -- the nucleon (proton or neutron) input_dict (optional) -- a dictionar...
stack_v2_sparse_classes_36k_train_011230
18,337
permissive
[ { "docstring": "The nuclear form factor FP Return the nuclear form factor FP Arguments --------- quark = 'u', 'd', 's' -- the quark flavor (up, down, strange) nucleon = 'p', 'n' -- the nucleon (proton or neutron) input_dict (optional) -- a dictionary of hadronic input parameters (default is Num_input().input_pa...
3
stack_v2_sparse_classes_30k_train_016282
Implement the Python class `FP` described below. Class description: Implement the FP class. Method signatures and docstrings: - def __init__(self, quark, nucleon, input_dict): The nuclear form factor FP Return the nuclear form factor FP Arguments --------- quark = 'u', 'd', 's' -- the quark flavor (up, down, strange)...
Implement the Python class `FP` described below. Class description: Implement the FP class. Method signatures and docstrings: - def __init__(self, quark, nucleon, input_dict): The nuclear form factor FP Return the nuclear form factor FP Arguments --------- quark = 'u', 'd', 's' -- the quark flavor (up, down, strange)...
4a714e4701f817fdc96e10e461eef7c4756ef71d
<|skeleton|> class FP: def __init__(self, quark, nucleon, input_dict): """The nuclear form factor FP Return the nuclear form factor FP Arguments --------- quark = 'u', 'd', 's' -- the quark flavor (up, down, strange) nucleon = 'p', 'n' -- the nucleon (proton or neutron) input_dict (optional) -- a dictionar...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FP: def __init__(self, quark, nucleon, input_dict): """The nuclear form factor FP Return the nuclear form factor FP Arguments --------- quark = 'u', 'd', 's' -- the quark flavor (up, down, strange) nucleon = 'p', 'n' -- the nucleon (proton or neutron) input_dict (optional) -- a dictionary of hadronic ...
the_stack_v2_python_sparse
directdm/num/single_nucleon_form_factors.py
DirectDM/directdm-py
train
6
e304df2450a9d6d0098cb968bcc788cd58391c9e
[ "ext = filename.split('.')[-1]\ndir_ = cls.floorplan_upload_dir\nreturn '{0}/{1}.{2}'.format(dir_, instance.id, ext)", "if self.exists(name):\n self.delete(name)\nreturn name" ]
<|body_start_0|> ext = filename.split('.')[-1] dir_ = cls.floorplan_upload_dir return '{0}/{1}.{2}'.format(dir_, instance.id, ext) <|end_body_0|> <|body_start_1|> if self.exists(name): self.delete(name) return name <|end_body_1|>
OverwriteMixin
[ "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OverwriteMixin: def upload_to(cls, instance, filename): """passed to FloorPlan.image.upload_to""" <|body_0|> def get_available_name(self, name, max_length=None): """removes file if it already exists""" <|body_1|> <|end_skeleton|> <|body_start_0|> ex...
stack_v2_sparse_classes_36k_train_011231
907
permissive
[ { "docstring": "passed to FloorPlan.image.upload_to", "name": "upload_to", "signature": "def upload_to(cls, instance, filename)" }, { "docstring": "removes file if it already exists", "name": "get_available_name", "signature": "def get_available_name(self, name, max_length=None)" } ]
2
stack_v2_sparse_classes_30k_val_000273
Implement the Python class `OverwriteMixin` described below. Class description: Implement the OverwriteMixin class. Method signatures and docstrings: - def upload_to(cls, instance, filename): passed to FloorPlan.image.upload_to - def get_available_name(self, name, max_length=None): removes file if it already exists
Implement the Python class `OverwriteMixin` described below. Class description: Implement the OverwriteMixin class. Method signatures and docstrings: - def upload_to(cls, instance, filename): passed to FloorPlan.image.upload_to - def get_available_name(self, name, max_length=None): removes file if it already exists ...
25651595ca8d67fe81853a79bf0000b0ba5cc1fd
<|skeleton|> class OverwriteMixin: def upload_to(cls, instance, filename): """passed to FloorPlan.image.upload_to""" <|body_0|> def get_available_name(self, name, max_length=None): """removes file if it already exists""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OverwriteMixin: def upload_to(cls, instance, filename): """passed to FloorPlan.image.upload_to""" ext = filename.split('.')[-1] dir_ = cls.floorplan_upload_dir return '{0}/{1}.{2}'.format(dir_, instance.id, ext) def get_available_name(self, name, max_length=None): ...
the_stack_v2_python_sparse
django_loci/storage.py
openwisp/django-loci
train
216
2574597ab6e7d9d8dc1c6ce1dc46a8ca081bc853
[ "latitude = ''\nlongitude = ''\nif latlong:\n latitude, longitude = latlong.split(',', 1)\nconfig = cherrypy.engine.publish('weather:config', latitude, longitude).pop()\napp_url = cherrypy.engine.publish('app_url').pop()\nredirect_url = ''\nif 'openweather_api_key' not in config:\n redirect_url = cherrypy.eng...
<|body_start_0|> latitude = '' longitude = '' if latlong: latitude, longitude = latlong.split(',', 1) config = cherrypy.engine.publish('weather:config', latitude, longitude).pop() app_url = cherrypy.engine.publish('app_url').pop() redirect_url = '' if ...
Controller
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Controller: def GET(latlong: str='', **_kwargs: str) -> bytes: """Display current and upcoming weather conditions.""" <|body_0|> def POST(self, subresource: str='', latlong: str='', **kwargs: str) -> None: """Dispatch to a subhandler based on the URL path.""" ...
stack_v2_sparse_classes_36k_train_011232
4,577
no_license
[ { "docstring": "Display current and upcoming weather conditions.", "name": "GET", "signature": "def GET(latlong: str='', **_kwargs: str) -> bytes" }, { "docstring": "Dispatch to a subhandler based on the URL path.", "name": "POST", "signature": "def POST(self, subresource: str='', latlon...
3
null
Implement the Python class `Controller` described below. Class description: Implement the Controller class. Method signatures and docstrings: - def GET(latlong: str='', **_kwargs: str) -> bytes: Display current and upcoming weather conditions. - def POST(self, subresource: str='', latlong: str='', **kwargs: str) -> N...
Implement the Python class `Controller` described below. Class description: Implement the Controller class. Method signatures and docstrings: - def GET(latlong: str='', **_kwargs: str) -> bytes: Display current and upcoming weather conditions. - def POST(self, subresource: str='', latlong: str='', **kwargs: str) -> N...
7129415303b94d5d10b2c29ec432f0c7d41cc651
<|skeleton|> class Controller: def GET(latlong: str='', **_kwargs: str) -> bytes: """Display current and upcoming weather conditions.""" <|body_0|> def POST(self, subresource: str='', latlong: str='', **kwargs: str) -> None: """Dispatch to a subhandler based on the URL path.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Controller: def GET(latlong: str='', **_kwargs: str) -> bytes: """Display current and upcoming weather conditions.""" latitude = '' longitude = '' if latlong: latitude, longitude = latlong.split(',', 1) config = cherrypy.engine.publish('weather:config', lati...
the_stack_v2_python_sparse
apps/weather/main.py
lovett/medley
train
6
67e1cb055f0b7e188353bed5cd752d892050c519
[ "C = self.COEFFS[imt]\nrhypo = dists.rhypo.copy()\nrhypo[rhypo < 10] = 10\nmag = rup.mag * 0.98 - 0.39 if rup.mag <= 5.5 else 2.715 - 0.277 * rup.mag + 0.127 * rup.mag * rup.mag\nf1 = np.minimum(np.log(rhypo), np.log(70.0))\nf2 = np.maximum(np.log(rhypo / 130.0), 0)\nmean = C['c1'] + C['c2'] * mag + C['c3'] * mag *...
<|body_start_0|> C = self.COEFFS[imt] rhypo = dists.rhypo.copy() rhypo[rhypo < 10] = 10 mag = rup.mag * 0.98 - 0.39 if rup.mag <= 5.5 else 2.715 - 0.277 * rup.mag + 0.127 * rup.mag * rup.mag f1 = np.minimum(np.log(rhypo), np.log(70.0)) f2 = np.maximum(np.log(rhypo / 130.0...
Implement equation used by the Geological Survey of Canada (GSC) for the 2010 Eastern Canada National Seismic Hazard Model. The equation fits the table values defined by Gail M. Atkinson and David M. Boore in "Ground-Motion Relations for Eastern North America", Bullettin of the Seismological Society of America, Vol. 85...
AtkinsonBoore1995GSCBest
[ "AGPL-3.0-only", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AtkinsonBoore1995GSCBest: """Implement equation used by the Geological Survey of Canada (GSC) for the 2010 Eastern Canada National Seismic Hazard Model. The equation fits the table values defined by Gail M. Atkinson and David M. Boore in "Ground-Motion Relations for Eastern North America", Bullet...
stack_v2_sparse_classes_36k_train_011233
7,650
permissive
[ { "docstring": "See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.", "name": "get_mean_and_stddevs", "signature": "def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types)" }, { "docstring": "Return total standa...
2
null
Implement the Python class `AtkinsonBoore1995GSCBest` described below. Class description: Implement equation used by the Geological Survey of Canada (GSC) for the 2010 Eastern Canada National Seismic Hazard Model. The equation fits the table values defined by Gail M. Atkinson and David M. Boore in "Ground-Motion Relat...
Implement the Python class `AtkinsonBoore1995GSCBest` described below. Class description: Implement equation used by the Geological Survey of Canada (GSC) for the 2010 Eastern Canada National Seismic Hazard Model. The equation fits the table values defined by Gail M. Atkinson and David M. Boore in "Ground-Motion Relat...
0da9ba5a575360081715e8b90c71d4b16c6687c8
<|skeleton|> class AtkinsonBoore1995GSCBest: """Implement equation used by the Geological Survey of Canada (GSC) for the 2010 Eastern Canada National Seismic Hazard Model. The equation fits the table values defined by Gail M. Atkinson and David M. Boore in "Ground-Motion Relations for Eastern North America", Bullet...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AtkinsonBoore1995GSCBest: """Implement equation used by the Geological Survey of Canada (GSC) for the 2010 Eastern Canada National Seismic Hazard Model. The equation fits the table values defined by Gail M. Atkinson and David M. Boore in "Ground-Motion Relations for Eastern North America", Bullettin of the Se...
the_stack_v2_python_sparse
openquake/hazardlib/gsim/atkinson_boore_1995.py
GFZ-Centre-for-Early-Warning/shakyground
train
1
18b1993b3bdf4a5ec065c9be107b3b7436bf6b33
[ "super().__init__()\nself._in_channel = in_channel\nself._out_channel = out_channel\nself._spatial_dims = spatial_dims\nif self._spatial_dims not in (2, 3):\n raise ValueError('spatial_dims must be 2 or 3.')\nconv_type = Conv[Conv.CONV, self._spatial_dims]\nself.act = get_act_layer(name=act_name)\nself.conv_1 = ...
<|body_start_0|> super().__init__() self._in_channel = in_channel self._out_channel = out_channel self._spatial_dims = spatial_dims if self._spatial_dims not in (2, 3): raise ValueError('spatial_dims must be 2 or 3.') conv_type = Conv[Conv.CONV, self._spatial_...
Down-sampling the feature by 2 using stride. The length along each spatial dimension must be a multiple of 2.
FactorizedReduceBlock
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FactorizedReduceBlock: """Down-sampling the feature by 2 using stride. The length along each spatial dimension must be a multiple of 2.""" def __init__(self, in_channel: int, out_channel: int, spatial_dims: int=3, act_name: tuple | str='RELU', norm_name: tuple | str=('INSTANCE', {'affine': T...
stack_v2_sparse_classes_36k_train_011234
9,255
permissive
[ { "docstring": "Args: in_channel: number of input channels out_channel: number of output channels. spatial_dims: number of spatial dimensions. act_name: activation layer type and arguments. norm_name: feature normalization type and arguments.", "name": "__init__", "signature": "def __init__(self, in_cha...
2
null
Implement the Python class `FactorizedReduceBlock` described below. Class description: Down-sampling the feature by 2 using stride. The length along each spatial dimension must be a multiple of 2. Method signatures and docstrings: - def __init__(self, in_channel: int, out_channel: int, spatial_dims: int=3, act_name: ...
Implement the Python class `FactorizedReduceBlock` described below. Class description: Down-sampling the feature by 2 using stride. The length along each spatial dimension must be a multiple of 2. Method signatures and docstrings: - def __init__(self, in_channel: int, out_channel: int, spatial_dims: int=3, act_name: ...
e48c3e2c741fa3fc705c4425d17ac4a5afac6c47
<|skeleton|> class FactorizedReduceBlock: """Down-sampling the feature by 2 using stride. The length along each spatial dimension must be a multiple of 2.""" def __init__(self, in_channel: int, out_channel: int, spatial_dims: int=3, act_name: tuple | str='RELU', norm_name: tuple | str=('INSTANCE', {'affine': T...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FactorizedReduceBlock: """Down-sampling the feature by 2 using stride. The length along each spatial dimension must be a multiple of 2.""" def __init__(self, in_channel: int, out_channel: int, spatial_dims: int=3, act_name: tuple | str='RELU', norm_name: tuple | str=('INSTANCE', {'affine': True})): ...
the_stack_v2_python_sparse
monai/networks/blocks/dints_block.py
Project-MONAI/MONAI
train
4,805
474e1594d755918e954ab2846e73b114e13a1f6b
[ "c = companymanage(self.driver)\nc.open_companymanage()\nself.assertEqual(c.verify(), True)\nc.add()\nself.assertEqual(c.sub_tagname(), '企业管理-新增')\nc.add_company(Data.name, Data.name, Data.name, '9999')\nc.select_trade()\nc.select_type()\nc.add_save()\nself.assertEqual(c.reason(), '您不能添加企业')\nfunction.screenshot(se...
<|body_start_0|> c = companymanage(self.driver) c.open_companymanage() self.assertEqual(c.verify(), True) c.add() self.assertEqual(c.sub_tagname(), '企业管理-新增') c.add_company(Data.name, Data.name, Data.name, '9999') c.select_trade() c.select_type() c...
Test021_Company_Add_P1
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Test021_Company_Add_P1: def test_company_add(self): """添加企业""" <|body_0|> def test_company_add_back(self): """添加企业并返回""" <|body_1|> <|end_skeleton|> <|body_start_0|> c = companymanage(self.driver) c.open_companymanage() self.assertEq...
stack_v2_sparse_classes_36k_train_011235
1,314
no_license
[ { "docstring": "添加企业", "name": "test_company_add", "signature": "def test_company_add(self)" }, { "docstring": "添加企业并返回", "name": "test_company_add_back", "signature": "def test_company_add_back(self)" } ]
2
null
Implement the Python class `Test021_Company_Add_P1` described below. Class description: Implement the Test021_Company_Add_P1 class. Method signatures and docstrings: - def test_company_add(self): 添加企业 - def test_company_add_back(self): 添加企业并返回
Implement the Python class `Test021_Company_Add_P1` described below. Class description: Implement the Test021_Company_Add_P1 class. Method signatures and docstrings: - def test_company_add(self): 添加企业 - def test_company_add_back(self): 添加企业并返回 <|skeleton|> class Test021_Company_Add_P1: def test_company_add(self...
6f42c25249fc642cecc270578a180820988d45b5
<|skeleton|> class Test021_Company_Add_P1: def test_company_add(self): """添加企业""" <|body_0|> def test_company_add_back(self): """添加企业并返回""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Test021_Company_Add_P1: def test_company_add(self): """添加企业""" c = companymanage(self.driver) c.open_companymanage() self.assertEqual(c.verify(), True) c.add() self.assertEqual(c.sub_tagname(), '企业管理-新增') c.add_company(Data.name, Data.name, Data.name, '9...
the_stack_v2_python_sparse
GlxssLive_web/TestCase/Manage_Company/Test021_company_add_P1.py
rrmiracle/GlxssLive
train
0
935962b641c19bab6b9e451960b9e92a1540669a
[ "self.timers = {}\nif items is not None:\n self.add(items)", "if isinstance(item, list):\n for i in item:\n self.timers[i] = {'name': i, 'time': 0, 'is_counting': False, 'duration': [], 'group': group}\nelif isinstance(item, str):\n self.timers[item] = {'name': item, 'time': 0, 'is_counting': Fals...
<|body_start_0|> self.timers = {} if items is not None: self.add(items) <|end_body_0|> <|body_start_1|> if isinstance(item, list): for i in item: self.timers[i] = {'name': i, 'time': 0, 'is_counting': False, 'duration': [], 'group': group} elif is...
Timer class to count time and do time analysis
Timer
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Timer: """Timer class to count time and do time analysis""" def __init__(self, items=None): """Args: items (list/str): list of items to be counted, each item is a str""" <|body_0|> def add(self, item, group=None): """add item to the timer Args: item (str/list): i...
stack_v2_sparse_classes_36k_train_011236
3,333
permissive
[ { "docstring": "Args: items (list/str): list of items to be counted, each item is a str", "name": "__init__", "signature": "def __init__(self, items=None)" }, { "docstring": "add item to the timer Args: item (str/list): item name group (str): group name of the item", "name": "add", "sign...
5
null
Implement the Python class `Timer` described below. Class description: Timer class to count time and do time analysis Method signatures and docstrings: - def __init__(self, items=None): Args: items (list/str): list of items to be counted, each item is a str - def add(self, item, group=None): add item to the timer Arg...
Implement the Python class `Timer` described below. Class description: Timer class to count time and do time analysis Method signatures and docstrings: - def __init__(self, items=None): Args: items (list/str): list of items to be counted, each item is a str - def add(self, item, group=None): add item to the timer Arg...
50e6ffa9b5164a0dfb34d3215e86cc2288df256d
<|skeleton|> class Timer: """Timer class to count time and do time analysis""" def __init__(self, items=None): """Args: items (list/str): list of items to be counted, each item is a str""" <|body_0|> def add(self, item, group=None): """add item to the timer Args: item (str/list): i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Timer: """Timer class to count time and do time analysis""" def __init__(self, items=None): """Args: items (list/str): list of items to be counted, each item is a str""" self.timers = {} if items is not None: self.add(items) def add(self, item, group=None): ...
the_stack_v2_python_sparse
libs/general/timer.py
Huangying-Zhan/DF-VO
train
494
ad5481e9b26a8ea9f9d56a19ed369ce6fad3ce59
[ "user = request.user\ncheck_user_status(user)\nuser_id = user.id\nvalidate(instance=request.data, schema=schemas.user_fav_schema)\nbody = request.data\nbody['user_id'] = user_id\nrest_id = body['restaurant']\nUserFavRestrs.field_validate(body)\nresponse = UserFavRestrs.insert(user_id, rest_id)\nreturn JsonResponse(...
<|body_start_0|> user = request.user check_user_status(user) user_id = user.id validate(instance=request.data, schema=schemas.user_fav_schema) body = request.data body['user_id'] = user_id rest_id = body['restaurant'] UserFavRestrs.field_validate(body) ...
user fav view
UserFavView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserFavView: """user fav view""" def post(self, request): """Add a new user-restaurant-favourite relation""" <|body_0|> def get(self, request): """Get all restaurants favourited by a user""" <|body_1|> <|end_skeleton|> <|body_start_0|> user = re...
stack_v2_sparse_classes_36k_train_011237
19,356
no_license
[ { "docstring": "Add a new user-restaurant-favourite relation", "name": "post", "signature": "def post(self, request)" }, { "docstring": "Get all restaurants favourited by a user", "name": "get", "signature": "def get(self, request)" } ]
2
stack_v2_sparse_classes_30k_train_012496
Implement the Python class `UserFavView` described below. Class description: user fav view Method signatures and docstrings: - def post(self, request): Add a new user-restaurant-favourite relation - def get(self, request): Get all restaurants favourited by a user
Implement the Python class `UserFavView` described below. Class description: user fav view Method signatures and docstrings: - def post(self, request): Add a new user-restaurant-favourite relation - def get(self, request): Get all restaurants favourited by a user <|skeleton|> class UserFavView: """user fav view"...
2707062c9a9a8bb4baca955e8a60ba08cc9f8953
<|skeleton|> class UserFavView: """user fav view""" def post(self, request): """Add a new user-restaurant-favourite relation""" <|body_0|> def get(self, request): """Get all restaurants favourited by a user""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserFavView: """user fav view""" def post(self, request): """Add a new user-restaurant-favourite relation""" user = request.user check_user_status(user) user_id = user.id validate(instance=request.data, schema=schemas.user_fav_schema) body = request.data ...
the_stack_v2_python_sparse
backend/restaurant/views.py
MochiTarts/Find-Dining-The-Bridge
train
1
7fcaee490e56f368faf6f64d5bb3ebd24e3837dd
[ "super().__init__(screen_width, screen_height, State.AI_MENU, screen, 0, 0, debug)\nfirst_pixel = self.screen_height // 2\nself.write(self.title_font, WHITE, 'AI modes', self.screen_width // 2, self.screen_height // 5)\nself.ai_coop = self.write(self.end_font, WHITE, 'Coop with AI', self.screen_width // 2, first_pi...
<|body_start_0|> super().__init__(screen_width, screen_height, State.AI_MENU, screen, 0, 0, debug) first_pixel = self.screen_height // 2 self.write(self.title_font, WHITE, 'AI modes', self.screen_width // 2, self.screen_height // 5) self.ai_coop = self.write(self.end_font, WHITE, 'Coop w...
AIMenuScreen
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AIMenuScreen: def __init__(self, screen_width: int, screen_height: int, screen, debug: bool=False): """Main screen for the different play modes""" <|body_0|> def check_mouse_press(self) -> State: """Check the mouse press of the user""" <|body_1|> def han...
stack_v2_sparse_classes_36k_train_011238
2,173
permissive
[ { "docstring": "Main screen for the different play modes", "name": "__init__", "signature": "def __init__(self, screen_width: int, screen_height: int, screen, debug: bool=False)" }, { "docstring": "Check the mouse press of the user", "name": "check_mouse_press", "signature": "def check_m...
3
null
Implement the Python class `AIMenuScreen` described below. Class description: Implement the AIMenuScreen class. Method signatures and docstrings: - def __init__(self, screen_width: int, screen_height: int, screen, debug: bool=False): Main screen for the different play modes - def check_mouse_press(self) -> State: Che...
Implement the Python class `AIMenuScreen` described below. Class description: Implement the AIMenuScreen class. Method signatures and docstrings: - def __init__(self, screen_width: int, screen_height: int, screen, debug: bool=False): Main screen for the different play modes - def check_mouse_press(self) -> State: Che...
6f8f2da4fd26ef1d77c0c6183230c3a5e6bf0bb9
<|skeleton|> class AIMenuScreen: def __init__(self, screen_width: int, screen_height: int, screen, debug: bool=False): """Main screen for the different play modes""" <|body_0|> def check_mouse_press(self) -> State: """Check the mouse press of the user""" <|body_1|> def han...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AIMenuScreen: def __init__(self, screen_width: int, screen_height: int, screen, debug: bool=False): """Main screen for the different play modes""" super().__init__(screen_width, screen_height, State.AI_MENU, screen, 0, 0, debug) first_pixel = self.screen_height // 2 self.write(...
the_stack_v2_python_sparse
gym_invaders/gym_game/envs/classes/Game/Screens/AIMenuScreen.py
Jh123x/Orbital
train
4
539d28bc6062121f38a7e69e44d560995d5db6d8
[ "temps = [91]\nresult = daily_temperatures(temps)\nself.assertEqual(result, [0])", "temps = [91, 99, 71, 23, 68, 100]\nresult = daily_temperatures(temps)\nself.assertEqual(result, [1, 4, 3, 1, 1, 0])", "temps = [91, 99, 71, 23, 68, 50, 44, 87, 91, 100, 101, 20, 32, 33]\nresult = daily_temperatures(temps)\nself....
<|body_start_0|> temps = [91] result = daily_temperatures(temps) self.assertEqual(result, [0]) <|end_body_0|> <|body_start_1|> temps = [91, 99, 71, 23, 68, 100] result = daily_temperatures(temps) self.assertEqual(result, [1, 4, 3, 1, 1, 0]) <|end_body_1|> <|body_start_2...
TestDailyTemperatures
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestDailyTemperatures: def test_handles_temp_list_of_length_1(self): """Takes in a temp list of length 1 and returns the correct result""" <|body_0|> def test_handles_short_temp_list(self): """Takes in a short temp list and returns the correct result""" <|bod...
stack_v2_sparse_classes_36k_train_011239
1,243
permissive
[ { "docstring": "Takes in a temp list of length 1 and returns the correct result", "name": "test_handles_temp_list_of_length_1", "signature": "def test_handles_temp_list_of_length_1(self)" }, { "docstring": "Takes in a short temp list and returns the correct result", "name": "test_handles_sho...
4
null
Implement the Python class `TestDailyTemperatures` described below. Class description: Implement the TestDailyTemperatures class. Method signatures and docstrings: - def test_handles_temp_list_of_length_1(self): Takes in a temp list of length 1 and returns the correct result - def test_handles_short_temp_list(self): ...
Implement the Python class `TestDailyTemperatures` described below. Class description: Implement the TestDailyTemperatures class. Method signatures and docstrings: - def test_handles_temp_list_of_length_1(self): Takes in a temp list of length 1 and returns the correct result - def test_handles_short_temp_list(self): ...
27ffb6b32d6d18d279c51cfa45bf305a409be5c2
<|skeleton|> class TestDailyTemperatures: def test_handles_temp_list_of_length_1(self): """Takes in a temp list of length 1 and returns the correct result""" <|body_0|> def test_handles_short_temp_list(self): """Takes in a short temp list and returns the correct result""" <|bod...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestDailyTemperatures: def test_handles_temp_list_of_length_1(self): """Takes in a temp list of length 1 and returns the correct result""" temps = [91] result = daily_temperatures(temps) self.assertEqual(result, [0]) def test_handles_short_temp_list(self): """Takes...
the_stack_v2_python_sparse
src/leetcode/medium/daily-temperatures/test_daily_temperatures.py
nwthomas/code-challenges
train
2
e0607c32cdfa7d8e04c411c513793e5a74b27a9c
[ "n = node\nwhile node.next:\n node.val = node.next.val\n if node.next.next:\n node = node.next\n else:\n node.next = None\nnode = n\nreturn node", "node.val = node.next.val\nnode.next = node.next.next\nreturn node" ]
<|body_start_0|> n = node while node.next: node.val = node.next.val if node.next.next: node = node.next else: node.next = None node = n return node <|end_body_0|> <|body_start_1|> node.val = node.next.val ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def deleteNode(self, node): """当前节点值等于next节点, 删除最后一个节点 4->5->1->9 :type node: ListNode :rtype: void Do not return anything, modify node in-place instead.""" <|body_0|> def deleteNode(self, node): """node.next节点val赋值node, 删除下一个节点, node连接node.next.next :param...
stack_v2_sparse_classes_36k_train_011240
1,882
no_license
[ { "docstring": "当前节点值等于next节点, 删除最后一个节点 4->5->1->9 :type node: ListNode :rtype: void Do not return anything, modify node in-place instead.", "name": "deleteNode", "signature": "def deleteNode(self, node)" }, { "docstring": "node.next节点val赋值node, 删除下一个节点, node连接node.next.next :param node: :return...
2
stack_v2_sparse_classes_30k_train_018980
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def deleteNode(self, node): 当前节点值等于next节点, 删除最后一个节点 4->5->1->9 :type node: ListNode :rtype: void Do not return anything, modify node in-place instead. - def deleteNode(self, node...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def deleteNode(self, node): 当前节点值等于next节点, 删除最后一个节点 4->5->1->9 :type node: ListNode :rtype: void Do not return anything, modify node in-place instead. - def deleteNode(self, node...
b1680014ce3f55ba952a1e64241c0cbb783cc436
<|skeleton|> class Solution: def deleteNode(self, node): """当前节点值等于next节点, 删除最后一个节点 4->5->1->9 :type node: ListNode :rtype: void Do not return anything, modify node in-place instead.""" <|body_0|> def deleteNode(self, node): """node.next节点val赋值node, 删除下一个节点, node连接node.next.next :param...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def deleteNode(self, node): """当前节点值等于next节点, 删除最后一个节点 4->5->1->9 :type node: ListNode :rtype: void Do not return anything, modify node in-place instead.""" n = node while node.next: node.val = node.next.val if node.next.next: node = no...
the_stack_v2_python_sparse
a_237.py
sun510001/leetcode_jianzhi_offer_2
train
0
dc874cc2b7d09809b3aeb5176ddec88074389b26
[ "record.message = record.getMessage()\nif self.usesTime():\n record.asctime = self.formatTime(record, self.datefmt)\ns = self._fmt % record.__dict__\nif record.exc_info:\n if not hasattr(record, 'exc_text_ext'):\n setattr(record, 'exc_text_ext', self.formatException(record.exc_info))\nif getattr(record...
<|body_start_0|> record.message = record.getMessage() if self.usesTime(): record.asctime = self.formatTime(record, self.datefmt) s = self._fmt % record.__dict__ if record.exc_info: if not hasattr(record, 'exc_text_ext'): setattr(record, 'exc_text_e...
ExcPlusFormatter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExcPlusFormatter: def format(self, record): """Format the specified record as text. The record's attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out....
stack_v2_sparse_classes_36k_train_011241
8,048
no_license
[ { "docstring": "Format the specified record as text. The record's attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using ...
2
null
Implement the Python class `ExcPlusFormatter` described below. Class description: Implement the ExcPlusFormatter class. Method signatures and docstrings: - def format(self, record): Format the specified record as text. The record's attribute dictionary is used as the operand to a string formatting operation which yie...
Implement the Python class `ExcPlusFormatter` described below. Class description: Implement the ExcPlusFormatter class. Method signatures and docstrings: - def format(self, record): Format the specified record as text. The record's attribute dictionary is used as the operand to a string formatting operation which yie...
c3bbadde24330fb2dff4aa2c32cc6b11e044fbc9
<|skeleton|> class ExcPlusFormatter: def format(self, record): """Format the specified record as text. The record's attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ExcPlusFormatter: def format(self, record): """Format the specified record as text. The record's attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message a...
the_stack_v2_python_sparse
Libraries/prosuite_logging.py
EAC-Technology/eApp-Builder
train
0
4d8d3f805f477ced49cb7f5179a97e087cb4a9b5
[ "button_list = [u'业务管理', u'投注卡管理', u'投注卡生成', u'展开']\nself.click_button_for_one(button_list[0])\nsleep(2)\nself.click_more_button_for_one(button_list[1:4])", "if info_list[0] != u'':\n self.input_text_message_for_inside_text(u'请输入批次', info_list[0])\nif info_list[1] != u'':\n self.open_list_menu_by_inside_tex...
<|body_start_0|> button_list = [u'业务管理', u'投注卡管理', u'投注卡生成', u'展开'] self.click_button_for_one(button_list[0]) sleep(2) self.click_more_button_for_one(button_list[1:4]) <|end_body_0|> <|body_start_1|> if info_list[0] != u'': self.input_text_message_for_inside_text(u'请...
投注卡生成页面
cardGenerationPage
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class cardGenerationPage: """投注卡生成页面""" def open_card_generation(self): """打开投注卡生成页面""" <|body_0|> def search_card_generation(self, info_list): """投注卡生成查询""" <|body_1|> def input_card_generation_add_info(self, info_list): """输入新增信息""" <|bod...
stack_v2_sparse_classes_36k_train_011242
1,775
no_license
[ { "docstring": "打开投注卡生成页面", "name": "open_card_generation", "signature": "def open_card_generation(self)" }, { "docstring": "投注卡生成查询", "name": "search_card_generation", "signature": "def search_card_generation(self, info_list)" }, { "docstring": "输入新增信息", "name": "input_card_...
3
null
Implement the Python class `cardGenerationPage` described below. Class description: 投注卡生成页面 Method signatures and docstrings: - def open_card_generation(self): 打开投注卡生成页面 - def search_card_generation(self, info_list): 投注卡生成查询 - def input_card_generation_add_info(self, info_list): 输入新增信息
Implement the Python class `cardGenerationPage` described below. Class description: 投注卡生成页面 Method signatures and docstrings: - def open_card_generation(self): 打开投注卡生成页面 - def search_card_generation(self, info_list): 投注卡生成查询 - def input_card_generation_add_info(self, info_list): 输入新增信息 <|skeleton|> class cardGenerat...
dcae68955b2857bbfe411145432865c57561c9ef
<|skeleton|> class cardGenerationPage: """投注卡生成页面""" def open_card_generation(self): """打开投注卡生成页面""" <|body_0|> def search_card_generation(self, info_list): """投注卡生成查询""" <|body_1|> def input_card_generation_add_info(self, info_list): """输入新增信息""" <|bod...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class cardGenerationPage: """投注卡生成页面""" def open_card_generation(self): """打开投注卡生成页面""" button_list = [u'业务管理', u'投注卡管理', u'投注卡生成', u'展开'] self.click_button_for_one(button_list[0]) sleep(2) self.click_more_button_for_one(button_list[1:4]) def search_card_generation(...
the_stack_v2_python_sparse
genlot_vlt2/pages/Business_management/card_balance_page/card_manage_card_generation_page.py
bbwdi/auto
train
1
74f1111f9ecdaf80c30922405f488a499f7bda05
[ "super(Net, self).__init__()\nself.input_dim = input_dim\nself.hidden_size = hidden_size\nself.output_dim = output_dim\nself.num_layers = num_layers\nself.layer_type = layer_type\nself.output_activation = output_activation\nself.internal_batch_norm = internal_batch_norm\nself.skip_connection = skip_connection\nself...
<|body_start_0|> super(Net, self).__init__() self.input_dim = input_dim self.hidden_size = hidden_size self.output_dim = output_dim self.num_layers = num_layers self.layer_type = layer_type self.output_activation = output_activation self.internal_batch_nor...
RealNVP neural network definitions.
Net
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Net: """RealNVP neural network definitions.""" def __init__(self, input_dim: int, hidden_size: int, output_dim: int=None, num_layers: int=3, layer_type: Literal['s', 't']='s', output_activation: Literal['tanh', 'lrelu']='tanh', internal_batch_norm: bool=False, skip_connection: bool=False) ->...
stack_v2_sparse_classes_36k_train_011243
8,028
permissive
[ { "docstring": "RealNVP neural network definition. :param input_dim: Data input dimension. :param hidden_size: Neural network hidden size. :param output_dim: Output dimension. :param num_layers: Number of linear layers. :param layer_type: \"s\" vs \"t\" type layer. :param output_activation: \"s\" network output...
2
stack_v2_sparse_classes_30k_train_006960
Implement the Python class `Net` described below. Class description: RealNVP neural network definitions. Method signatures and docstrings: - def __init__(self, input_dim: int, hidden_size: int, output_dim: int=None, num_layers: int=3, layer_type: Literal['s', 't']='s', output_activation: Literal['tanh', 'lrelu']='tan...
Implement the Python class `Net` described below. Class description: RealNVP neural network definitions. Method signatures and docstrings: - def __init__(self, input_dim: int, hidden_size: int, output_dim: int=None, num_layers: int=3, layer_type: Literal['s', 't']='s', output_activation: Literal['tanh', 'lrelu']='tan...
f470849d5b7b90dc5a65bab8a536de1d57c1021a
<|skeleton|> class Net: """RealNVP neural network definitions.""" def __init__(self, input_dim: int, hidden_size: int, output_dim: int=None, num_layers: int=3, layer_type: Literal['s', 't']='s', output_activation: Literal['tanh', 'lrelu']='tanh', internal_batch_norm: bool=False, skip_connection: bool=False) ->...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Net: """RealNVP neural network definitions.""" def __init__(self, input_dim: int, hidden_size: int, output_dim: int=None, num_layers: int=3, layer_type: Literal['s', 't']='s', output_activation: Literal['tanh', 'lrelu']='tanh', internal_batch_norm: bool=False, skip_connection: bool=False) -> None: ...
the_stack_v2_python_sparse
conformation/model.py
ks8/conformation
train
1
67f3c55d95928ad0b76e110373baaacfaab2a022
[ "if self.action in ['signup', 'login', 'change_password']:\n permissions = [AllowAny]\nelif self.action in ['retrieve']:\n permissions = [IsAuthenticated, IsAccountOwner]\nelif self.action in ['patients']:\n permissions = [IsAuthenticated]\nreturn [p() for p in permissions]", "if self.action == 'login':\...
<|body_start_0|> if self.action in ['signup', 'login', 'change_password']: permissions = [AllowAny] elif self.action in ['retrieve']: permissions = [IsAuthenticated, IsAccountOwner] elif self.action in ['patients']: permissions = [IsAuthenticated] retu...
User view set. Handle login and signup.
UserViewSet
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserViewSet: """User view set. Handle login and signup.""" def get_permissions(self): """Assign permission based on action.""" <|body_0|> def get_serializer_class(self): """Return serializer based on action.""" <|body_1|> def login(self, request): ...
stack_v2_sparse_classes_36k_train_011244
5,474
permissive
[ { "docstring": "Assign permission based on action.", "name": "get_permissions", "signature": "def get_permissions(self)" }, { "docstring": "Return serializer based on action.", "name": "get_serializer_class", "signature": "def get_serializer_class(self)" }, { "docstring": "User l...
6
stack_v2_sparse_classes_30k_train_012476
Implement the Python class `UserViewSet` described below. Class description: User view set. Handle login and signup. Method signatures and docstrings: - def get_permissions(self): Assign permission based on action. - def get_serializer_class(self): Return serializer based on action. - def login(self, request): User l...
Implement the Python class `UserViewSet` described below. Class description: User view set. Handle login and signup. Method signatures and docstrings: - def get_permissions(self): Assign permission based on action. - def get_serializer_class(self): Return serializer based on action. - def login(self, request): User l...
2c39ba45aa6aef37820b385c3060c83a73f8f910
<|skeleton|> class UserViewSet: """User view set. Handle login and signup.""" def get_permissions(self): """Assign permission based on action.""" <|body_0|> def get_serializer_class(self): """Return serializer based on action.""" <|body_1|> def login(self, request): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserViewSet: """User view set. Handle login and signup.""" def get_permissions(self): """Assign permission based on action.""" if self.action in ['signup', 'login', 'change_password']: permissions = [AllowAny] elif self.action in ['retrieve']: permissions =...
the_stack_v2_python_sparse
weight/users/views/users.py
SeptumDevs/lose_weightapp
train
1
68ad5214491d94b3cadddcb31441c3ba95632f6d
[ "self.sensor = gateway.api.sensors[sensor_id]\nself.gateway = gateway\nself.description = description\nself.async_add_entities = async_add_entities\nself.unsubscribe = self.sensor.subscribe(self.async_update_callback)", "if self.description.update_key in self.sensor.changed_keys:\n self.unsubscribe()\n self...
<|body_start_0|> self.sensor = gateway.api.sensors[sensor_id] self.gateway = gateway self.description = description self.async_add_entities = async_add_entities self.unsubscribe = self.sensor.subscribe(self.async_update_callback) <|end_body_0|> <|body_start_1|> if self.d...
Track sensors without a battery state and add entity when battery state exist.
DeconzBatteryTracker
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DeconzBatteryTracker: """Track sensors without a battery state and add entity when battery state exist.""" def __init__(self, sensor_id: str, gateway: DeconzGateway, description: DeconzSensorDescription, async_add_entities: AddEntitiesCallback) -> None: """Set up tracker.""" ...
stack_v2_sparse_classes_36k_train_011245
16,422
permissive
[ { "docstring": "Set up tracker.", "name": "__init__", "signature": "def __init__(self, sensor_id: str, gateway: DeconzGateway, description: DeconzSensorDescription, async_add_entities: AddEntitiesCallback) -> None" }, { "docstring": "Update the device's state.", "name": "async_update_callbac...
2
stack_v2_sparse_classes_30k_train_020979
Implement the Python class `DeconzBatteryTracker` described below. Class description: Track sensors without a battery state and add entity when battery state exist. Method signatures and docstrings: - def __init__(self, sensor_id: str, gateway: DeconzGateway, description: DeconzSensorDescription, async_add_entities: ...
Implement the Python class `DeconzBatteryTracker` described below. Class description: Track sensors without a battery state and add entity when battery state exist. Method signatures and docstrings: - def __init__(self, sensor_id: str, gateway: DeconzGateway, description: DeconzSensorDescription, async_add_entities: ...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class DeconzBatteryTracker: """Track sensors without a battery state and add entity when battery state exist.""" def __init__(self, sensor_id: str, gateway: DeconzGateway, description: DeconzSensorDescription, async_add_entities: AddEntitiesCallback) -> None: """Set up tracker.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DeconzBatteryTracker: """Track sensors without a battery state and add entity when battery state exist.""" def __init__(self, sensor_id: str, gateway: DeconzGateway, description: DeconzSensorDescription, async_add_entities: AddEntitiesCallback) -> None: """Set up tracker.""" self.sensor =...
the_stack_v2_python_sparse
homeassistant/components/deconz/sensor.py
home-assistant/core
train
35,501
9efbfe2e9645b0f8fda3240cc25956b8bc1c5196
[ "self.MAP_correct = []\nself.MAP_incorrect = []\nself.ML_correct = []\nself.ML_incorrect = []", "MAPc = len(self.MAP_correct)\nMAPi = len(self.MAP_incorrect)\ntotal = MAPc + MAPi\nreturn (MAPc, MAPi, 100.0 * (float(MAPc) / float(total)))", "MLc = len(self.ML_correct)\nMLi = len(self.ML_incorrect)\ntotal = MLc +...
<|body_start_0|> self.MAP_correct = [] self.MAP_incorrect = [] self.ML_correct = [] self.ML_incorrect = [] <|end_body_0|> <|body_start_1|> MAPc = len(self.MAP_correct) MAPi = len(self.MAP_incorrect) total = MAPc + MAPi return (MAPc, MAPi, 100.0 * (float(M...
c
Evaluation
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Evaluation: """c""" def __init__(self): """c""" <|body_0|> def get_MAP_success_rate(self): """c""" <|body_1|> def get_ML_success_rate(self): """c""" <|body_2|> <|end_skeleton|> <|body_start_0|> self.MAP_correct = [] ...
stack_v2_sparse_classes_36k_train_011246
4,127
no_license
[ { "docstring": "c", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "c", "name": "get_MAP_success_rate", "signature": "def get_MAP_success_rate(self)" }, { "docstring": "c", "name": "get_ML_success_rate", "signature": "def get_ML_success_rate(self)...
3
stack_v2_sparse_classes_30k_train_011816
Implement the Python class `Evaluation` described below. Class description: c Method signatures and docstrings: - def __init__(self): c - def get_MAP_success_rate(self): c - def get_ML_success_rate(self): c
Implement the Python class `Evaluation` described below. Class description: c Method signatures and docstrings: - def __init__(self): c - def get_MAP_success_rate(self): c - def get_ML_success_rate(self): c <|skeleton|> class Evaluation: """c""" def __init__(self): """c""" <|body_0|> de...
0a72ca9623d29998423399617b8187651de500fc
<|skeleton|> class Evaluation: """c""" def __init__(self): """c""" <|body_0|> def get_MAP_success_rate(self): """c""" <|body_1|> def get_ML_success_rate(self): """c""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Evaluation: """c""" def __init__(self): """c""" self.MAP_correct = [] self.MAP_incorrect = [] self.ML_correct = [] self.ML_incorrect = [] def get_MAP_success_rate(self): """c""" MAPc = len(self.MAP_correct) MAPi = len(self.MAP_incorrect...
the_stack_v2_python_sparse
courses/cs440/hw/hw_3/hw_3_utils.py
evanjtravis/classnotes
train
0
1982d1f1f14c08951ebd42990e0e5de9894822bc
[ "self.logger = logging.getLogger(__name__)\nself.logger.setLevel(logging.DEBUG)\nself.X = X\nself.Y = Y\nself.is_stochastic = is_stochastic\nif is_stochastic:\n self.logger.debug('Running Stochastic Perceptron...')\nself.step_size = step_size\nself.max_steps = max_steps\nself.reg_constant = reg_constant\nself.w ...
<|body_start_0|> self.logger = logging.getLogger(__name__) self.logger.setLevel(logging.DEBUG) self.X = X self.Y = Y self.is_stochastic = is_stochastic if is_stochastic: self.logger.debug('Running Stochastic Perceptron...') self.step_size = step_size ...
The Perceptron classifier, intended to be run on a dataset of two classes that are linearly separable.
Perceptron
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Perceptron: """The Perceptron classifier, intended to be run on a dataset of two classes that are linearly separable.""" def __init__(self, X, Y, is_stochastic, step_size, max_steps, reg_constant=0): """Initializes the Perceptron classifier. X and Y is the training data over which to...
stack_v2_sparse_classes_36k_train_011247
4,229
permissive
[ { "docstring": "Initializes the Perceptron classifier. X and Y is the training data over which to learn the hyperplane If is_stochastic is True then the perceptron gradient steps will be stochastic not batch. step_size is the learning rate to be used. max_steps is the maximum number of iterations to use before ...
4
stack_v2_sparse_classes_30k_train_014826
Implement the Python class `Perceptron` described below. Class description: The Perceptron classifier, intended to be run on a dataset of two classes that are linearly separable. Method signatures and docstrings: - def __init__(self, X, Y, is_stochastic, step_size, max_steps, reg_constant=0): Initializes the Perceptr...
Implement the Python class `Perceptron` described below. Class description: The Perceptron classifier, intended to be run on a dataset of two classes that are linearly separable. Method signatures and docstrings: - def __init__(self, X, Y, is_stochastic, step_size, max_steps, reg_constant=0): Initializes the Perceptr...
5d5a372f315cbd3cf8a3b2e865a8724f7cf4cc2b
<|skeleton|> class Perceptron: """The Perceptron classifier, intended to be run on a dataset of two classes that are linearly separable.""" def __init__(self, X, Y, is_stochastic, step_size, max_steps, reg_constant=0): """Initializes the Perceptron classifier. X and Y is the training data over which to...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Perceptron: """The Perceptron classifier, intended to be run on a dataset of two classes that are linearly separable.""" def __init__(self, X, Y, is_stochastic, step_size, max_steps, reg_constant=0): """Initializes the Perceptron classifier. X and Y is the training data over which to learn the hy...
the_stack_v2_python_sparse
ml_lib/perceptron.py
enerve/ml
train
0
ee8cdaf7c34941776a754f96e5c6059ffe52ad1c
[ "class S(SymbolDef):\n a\n b\n c\nself.assertIs(S.a, Symbol('a'))\nself.assertIs(S.b, Symbol('b'))\nself.assertIs(S.c, Symbol('c'))", "class S(SymbolDef):\n a = Symbol('the-a-symbol')\nself.assertIs(S.a, Symbol('the-a-symbol'))", "class S(SymbolDef):\n a = 'the-a-symbol'\nself.assertIs(S.a, Symbo...
<|body_start_0|> class S(SymbolDef): a b c self.assertIs(S.a, Symbol('a')) self.assertIs(S.b, Symbol('b')) self.assertIs(S.c, Symbol('c')) <|end_body_0|> <|body_start_1|> class S(SymbolDef): a = Symbol('the-a-symbol') self....
Tests for SymbolDef class
SymbolDefTests
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SymbolDefTests: """Tests for SymbolDef class""" def test_implicit_symbols(self): """verify that referencing names inside SymbolDef creates symbols""" <|body_0|> def test_custom_symbols(self): """verify that assigning symbols to variables works""" <|body_1...
stack_v2_sparse_classes_36k_train_011248
5,099
no_license
[ { "docstring": "verify that referencing names inside SymbolDef creates symbols", "name": "test_implicit_symbols", "signature": "def test_implicit_symbols(self)" }, { "docstring": "verify that assigning symbols to variables works", "name": "test_custom_symbols", "signature": "def test_cus...
6
stack_v2_sparse_classes_30k_train_017513
Implement the Python class `SymbolDefTests` described below. Class description: Tests for SymbolDef class Method signatures and docstrings: - def test_implicit_symbols(self): verify that referencing names inside SymbolDef creates symbols - def test_custom_symbols(self): verify that assigning symbols to variables work...
Implement the Python class `SymbolDefTests` described below. Class description: Tests for SymbolDef class Method signatures and docstrings: - def test_implicit_symbols(self): verify that referencing names inside SymbolDef creates symbols - def test_custom_symbols(self): verify that assigning symbols to variables work...
78aa82cdb35808988214329b3b1aabcc2d1a5e01
<|skeleton|> class SymbolDefTests: """Tests for SymbolDef class""" def test_implicit_symbols(self): """verify that referencing names inside SymbolDef creates symbols""" <|body_0|> def test_custom_symbols(self): """verify that assigning symbols to variables works""" <|body_1...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SymbolDefTests: """Tests for SymbolDef class""" def test_implicit_symbols(self): """verify that referencing names inside SymbolDef creates symbols""" class S(SymbolDef): a b c self.assertIs(S.a, Symbol('a')) self.assertIs(S.b, Symbol('b'...
the_stack_v2_python_sparse
venv/lib/python3.6/site-packages/plainbox/impl/test_symbol.py
utkarshyadavin/CloudMarks
train
0
8ddae3bf5fe99f8205fa68ef0a40023f39467441
[ "self.screen_width = 600\nself.screen_height = 400\nself.bg_color = (230, 30, 230)\nself.plane_limit = 3\nself.missle_width = 15\nself.missle_height = 3\nself.missle_color = (60, 60, 60)\nself.missles_allowed = 3\nself.fleet_drop_speed = 10\nself.speedup_scale = 2\nself.initialize_dynamic_settings()", "self.plane...
<|body_start_0|> self.screen_width = 600 self.screen_height = 400 self.bg_color = (230, 30, 230) self.plane_limit = 3 self.missle_width = 15 self.missle_height = 3 self.missle_color = (60, 60, 60) self.missles_allowed = 3 self.fleet_drop_speed = 10...
Класс для хранения всех настроек игры Alien Invasion
Settings
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Settings: """Класс для хранения всех настроек игры Alien Invasion""" def __init__(self): """Инициализирует настройки игры""" <|body_0|> def initialize_dynamic_settings(self): """Инициализирует настройки, изменяющиеся в ходе игры""" <|body_1|> def inc...
stack_v2_sparse_classes_36k_train_011249
1,225
no_license
[ { "docstring": "Инициализирует настройки игры", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Инициализирует настройки, изменяющиеся в ходе игры", "name": "initialize_dynamic_settings", "signature": "def initialize_dynamic_settings(self)" }, { "docstrin...
3
stack_v2_sparse_classes_30k_train_020806
Implement the Python class `Settings` described below. Class description: Класс для хранения всех настроек игры Alien Invasion Method signatures and docstrings: - def __init__(self): Инициализирует настройки игры - def initialize_dynamic_settings(self): Инициализирует настройки, изменяющиеся в ходе игры - def increas...
Implement the Python class `Settings` described below. Class description: Класс для хранения всех настроек игры Alien Invasion Method signatures and docstrings: - def __init__(self): Инициализирует настройки игры - def initialize_dynamic_settings(self): Инициализирует настройки, изменяющиеся в ходе игры - def increas...
355d117ae48f78d331ef2cfc2f92551dc857cb58
<|skeleton|> class Settings: """Класс для хранения всех настроек игры Alien Invasion""" def __init__(self): """Инициализирует настройки игры""" <|body_0|> def initialize_dynamic_settings(self): """Инициализирует настройки, изменяющиеся в ходе игры""" <|body_1|> def inc...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Settings: """Класс для хранения всех настроек игры Alien Invasion""" def __init__(self): """Инициализирует настройки игры""" self.screen_width = 600 self.screen_height = 400 self.bg_color = (230, 30, 230) self.plane_limit = 3 self.missle_width = 15 ...
the_stack_v2_python_sparse
Eric_Matthes/chapter_2/games/vertical/settings.py
rvdmtr/python
train
0
4a568831581b53f29c13b0bfcba6db435b34bc84
[ "updated_story_model = story_services.populate_story_model_fields(story_model, migrated_story)\nchange_dicts = [story_change.to_dict()]\nwith datastore_services.get_ndb_context():\n models_to_put = updated_story_model.compute_models_to_commit(feconf.MIGRATION_BOT_USERNAME, feconf.COMMIT_TYPE_EDIT, 'Update story ...
<|body_start_0|> updated_story_model = story_services.populate_story_model_fields(story_model, migrated_story) change_dicts = [story_change.to_dict()] with datastore_services.get_ndb_context(): models_to_put = updated_story_model.compute_models_to_commit(feconf.MIGRATION_BOT_USERNAME...
Job that migrates story models.
MigrateStoryJob
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MigrateStoryJob: """Job that migrates story models.""" def _update_story(story_model: story_models.StoryModel, migrated_story: story_domain.Story, story_change: story_domain.StoryChange) -> Sequence[base_models.BaseModel]: """Generates newly updated story models. Args: story_model: S...
stack_v2_sparse_classes_36k_train_011250
14,753
permissive
[ { "docstring": "Generates newly updated story models. Args: story_model: StoryModel. The story which should be updated. migrated_story: Story. The migrated story domain object. story_change: StoryChange. The story change to apply. Returns: sequence(BaseModel). Sequence of models which should be put into the dat...
3
null
Implement the Python class `MigrateStoryJob` described below. Class description: Job that migrates story models. Method signatures and docstrings: - def _update_story(story_model: story_models.StoryModel, migrated_story: story_domain.Story, story_change: story_domain.StoryChange) -> Sequence[base_models.BaseModel]: G...
Implement the Python class `MigrateStoryJob` described below. Class description: Job that migrates story models. Method signatures and docstrings: - def _update_story(story_model: story_models.StoryModel, migrated_story: story_domain.Story, story_change: story_domain.StoryChange) -> Sequence[base_models.BaseModel]: G...
d16fdf23d790eafd63812bd7239532256e30a21d
<|skeleton|> class MigrateStoryJob: """Job that migrates story models.""" def _update_story(story_model: story_models.StoryModel, migrated_story: story_domain.Story, story_change: story_domain.StoryChange) -> Sequence[base_models.BaseModel]: """Generates newly updated story models. Args: story_model: S...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MigrateStoryJob: """Job that migrates story models.""" def _update_story(story_model: story_models.StoryModel, migrated_story: story_domain.Story, story_change: story_domain.StoryChange) -> Sequence[base_models.BaseModel]: """Generates newly updated story models. Args: story_model: StoryModel. Th...
the_stack_v2_python_sparse
core/jobs/batch_jobs/story_migration_jobs.py
oppia/oppia
train
6,172
7666da9dbe697f8c775c2e1ace623a12d4954c73
[ "if not request.cache.token:\n raise Http401\nreturn request.response", "ensure_service_user(request)\nmodel = self.get_model(request)\nform = auth_form(request, model.form)\nif form.is_valid():\n model = self.get_model(request)\n auth_backend = request.cache.auth_backend\n data = form.cleaned_data\n ...
<|body_start_0|> if not request.cache.token: raise Http401 return request.response <|end_body_0|> <|body_start_1|> ensure_service_user(request) model = self.get_model(request) form = auth_form(request, model.form) if form.is_valid(): model = self....
Authentication views for Restful APIs
Authorization
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Authorization: """Authentication views for Restful APIs""" def head(self, request): """Check validity of the ``Token`` in the ``Authorization`` header. It works for both user and application tokens.""" <|body_0|> def post(self, request): """Perform a login operat...
stack_v2_sparse_classes_36k_train_011251
3,593
no_license
[ { "docstring": "Check validity of the ``Token`` in the ``Authorization`` header. It works for both user and application tokens.", "name": "head", "signature": "def head(self, request)" }, { "docstring": "Perform a login operation. The headers must contain a valid ``AUTHORIZATION`` token, signed ...
3
null
Implement the Python class `Authorization` described below. Class description: Authentication views for Restful APIs Method signatures and docstrings: - def head(self, request): Check validity of the ``Token`` in the ``Authorization`` header. It works for both user and application tokens. - def post(self, request): P...
Implement the Python class `Authorization` described below. Class description: Authentication views for Restful APIs Method signatures and docstrings: - def head(self, request): Check validity of the ``Token`` in the ``Authorization`` header. It works for both user and application tokens. - def post(self, request): P...
2ac09e31ebe54dbecd46935818b089a4b8428354
<|skeleton|> class Authorization: """Authentication views for Restful APIs""" def head(self, request): """Check validity of the ``Token`` in the ``Authorization`` header. It works for both user and application tokens.""" <|body_0|> def post(self, request): """Perform a login operat...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Authorization: """Authentication views for Restful APIs""" def head(self, request): """Check validity of the ``Token`` in the ``Authorization`` header. It works for both user and application tokens.""" if not request.cache.token: raise Http401 return request.response ...
the_stack_v2_python_sparse
venv/Lib/site-packages/lux/extensions/auth/rest/authorization.py
Sarveshr49/ProInternSML
train
0
45b6d62e3f5c4bf30c31aafe474e17ca76b49727
[ "client = Client(config, get_schema_from_catalog(configured_catalog))\nfor configured_stream in configured_catalog.streams:\n if configured_stream.destination_sync_mode == DestinationSyncMode.overwrite:\n client.delete_stream_entries(configured_stream.stream.name)\nfor message in input_messages:\n if m...
<|body_start_0|> client = Client(config, get_schema_from_catalog(configured_catalog)) for configured_stream in configured_catalog.streams: if configured_stream.destination_sync_mode == DestinationSyncMode.overwrite: client.delete_stream_entries(configured_stream.stream.name) ...
DestinationWeaviate
[ "MIT", "Elastic-2.0", "Apache-2.0", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DestinationWeaviate: def write(self, config: Mapping[str, Any], configured_catalog: ConfiguredAirbyteCatalog, input_messages: Iterable[AirbyteMessage]) -> Iterable[AirbyteMessage]: """Reads the input stream of messages, config, and catalog to write data to the destination. This method re...
stack_v2_sparse_classes_36k_train_011252
4,241
permissive
[ { "docstring": "Reads the input stream of messages, config, and catalog to write data to the destination. This method returns an iterable (typically a generator of AirbyteMessages via yield) containing state messages received in the input message stream. Outputting a state message means that every AirbyteRecord...
2
null
Implement the Python class `DestinationWeaviate` described below. Class description: Implement the DestinationWeaviate class. Method signatures and docstrings: - def write(self, config: Mapping[str, Any], configured_catalog: ConfiguredAirbyteCatalog, input_messages: Iterable[AirbyteMessage]) -> Iterable[AirbyteMessag...
Implement the Python class `DestinationWeaviate` described below. Class description: Implement the DestinationWeaviate class. Method signatures and docstrings: - def write(self, config: Mapping[str, Any], configured_catalog: ConfiguredAirbyteCatalog, input_messages: Iterable[AirbyteMessage]) -> Iterable[AirbyteMessag...
8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6
<|skeleton|> class DestinationWeaviate: def write(self, config: Mapping[str, Any], configured_catalog: ConfiguredAirbyteCatalog, input_messages: Iterable[AirbyteMessage]) -> Iterable[AirbyteMessage]: """Reads the input stream of messages, config, and catalog to write data to the destination. This method re...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DestinationWeaviate: def write(self, config: Mapping[str, Any], configured_catalog: ConfiguredAirbyteCatalog, input_messages: Iterable[AirbyteMessage]) -> Iterable[AirbyteMessage]: """Reads the input stream of messages, config, and catalog to write data to the destination. This method returns an itera...
the_stack_v2_python_sparse
dts/airbyte/airbyte-integrations/connectors/destination-weaviate/destination_weaviate/destination.py
alldatacenter/alldata
train
774
b4bb5e58b1c9704ca70eff1b76469bc510693199
[ "if isinstance(username, int):\n return super(VMMBackend, self).get_user(username)\nusers = User.objects.filter(username=username)\nif users:\n return users[0]\nelse:\n return None", "try:\n machine = Machine.objects.get(name=machine_name)\nexcept Machine.DoesNotExist:\n return False\nelse:\n if...
<|body_start_0|> if isinstance(username, int): return super(VMMBackend, self).get_user(username) users = User.objects.filter(username=username) if users: return users[0] else: return None <|end_body_0|> <|body_start_1|> try: machin...
This authentication backend mostly adds new methods to the standard :class:`ModelBackend` that ships with Django.
VMMBackend
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VMMBackend: """This authentication backend mostly adds new methods to the standard :class:`ModelBackend` that ships with Django.""" def get_user(self, username): """This overrides the *get_user* method of :class:`ModelBackend` to accept a *username* as a parameter instead of a databa...
stack_v2_sparse_classes_36k_train_011253
5,460
permissive
[ { "docstring": "This overrides the *get_user* method of :class:`ModelBackend` to accept a *username* as a parameter instead of a database *id*. :returns: User|None .. todo:: when using Client.login, apparently it doesn't work if \"get_user\" doesn't accept a user id... django bug (I don't understand why the cli...
2
stack_v2_sparse_classes_30k_train_005364
Implement the Python class `VMMBackend` described below. Class description: This authentication backend mostly adds new methods to the standard :class:`ModelBackend` that ships with Django. Method signatures and docstrings: - def get_user(self, username): This overrides the *get_user* method of :class:`ModelBackend` ...
Implement the Python class `VMMBackend` described below. Class description: This authentication backend mostly adds new methods to the standard :class:`ModelBackend` that ships with Django. Method signatures and docstrings: - def get_user(self, username): This overrides the *get_user* method of :class:`ModelBackend` ...
5418b22356b58cd9a7f3043ec21e1e728abb6b27
<|skeleton|> class VMMBackend: """This authentication backend mostly adds new methods to the standard :class:`ModelBackend` that ships with Django.""" def get_user(self, username): """This overrides the *get_user* method of :class:`ModelBackend` to accept a *username* as a parameter instead of a databa...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class VMMBackend: """This authentication backend mostly adds new methods to the standard :class:`ModelBackend` that ships with Django.""" def get_user(self, username): """This overrides the *get_user* method of :class:`ModelBackend` to accept a *username* as a parameter instead of a database *id*. :ret...
the_stack_v2_python_sparse
vpn/vpnconf/auth.py
bhyvex/vpn-management-server
train
0
07fd42ca106064ccdc698c729db604b37febb5fa
[ "rate = Rate.objects.filter(currency=currency, usd__isnull=False, btc__isnull=False).order_by('-datetime').first()\nif not rate:\n return None\nresult = {'usd': rate.usd, 'btc': rate.btc}\nreturn result", "rate = Rate.objects.filter(currency__code=currency_code, usd__isnull=False, btc__isnull=False).order_by('...
<|body_start_0|> rate = Rate.objects.filter(currency=currency, usd__isnull=False, btc__isnull=False).order_by('-datetime').first() if not rate: return None result = {'usd': rate.usd, 'btc': rate.btc} return result <|end_body_0|> <|body_start_1|> rate = Rate.objects.f...
Rate
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Rate: def get_actual_rates(currency): """Get closest currency rate for date""" <|body_0|> def get_rate_by_code(currency_code): """Get closest currency rate for date""" <|body_1|> <|end_skeleton|> <|body_start_0|> rate = Rate.objects.filter(currency=...
stack_v2_sparse_classes_36k_train_011254
4,281
no_license
[ { "docstring": "Get closest currency rate for date", "name": "get_actual_rates", "signature": "def get_actual_rates(currency)" }, { "docstring": "Get closest currency rate for date", "name": "get_rate_by_code", "signature": "def get_rate_by_code(currency_code)" } ]
2
stack_v2_sparse_classes_30k_train_018906
Implement the Python class `Rate` described below. Class description: Implement the Rate class. Method signatures and docstrings: - def get_actual_rates(currency): Get closest currency rate for date - def get_rate_by_code(currency_code): Get closest currency rate for date
Implement the Python class `Rate` described below. Class description: Implement the Rate class. Method signatures and docstrings: - def get_actual_rates(currency): Get closest currency rate for date - def get_rate_by_code(currency_code): Get closest currency rate for date <|skeleton|> class Rate: def get_actual...
601b4ccf17475e349b8d4cc1834e2c383554d165
<|skeleton|> class Rate: def get_actual_rates(currency): """Get closest currency rate for date""" <|body_0|> def get_rate_by_code(currency_code): """Get closest currency rate for date""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Rate: def get_actual_rates(currency): """Get closest currency rate for date""" rate = Rate.objects.filter(currency=currency, usd__isnull=False, btc__isnull=False).order_by('-datetime').first() if not rate: return None result = {'usd': rate.usd, 'btc': rate.btc} ...
the_stack_v2_python_sparse
src/wallet/models/currency.py
paradigm-citadel/Citadel-Backend
train
0
422b2dea41a60c93dbdd4038c9d1b9c3e1e716c8
[ "dp, all = (collections.defaultdict(int), collections.defaultdict(int))\n\ndef dfs(node):\n if node in dp:\n return dp[node]\n if not node.left and (not node.right):\n dp[node], all[node] = (1, 0)\n return 1\n if node.left:\n all[node] += dfs(node.left)\n if node.right:\n ...
<|body_start_0|> dp, all = (collections.defaultdict(int), collections.defaultdict(int)) def dfs(node): if node in dp: return dp[node] if not node.left and (not node.right): dp[node], all[node] = (1, 0) return 1 if node....
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def minCameraCover_wrong(self, root): """:type root: TreeNode :rtype: int""" <|body_0|> def minCameraCover(self, root): """:type root: TreeNode :rtype: int""" <|body_1|> def minCameraCover2(self, root): """:type root: TreeNode :rtype: i...
stack_v2_sparse_classes_36k_train_011255
4,473
no_license
[ { "docstring": ":type root: TreeNode :rtype: int", "name": "minCameraCover_wrong", "signature": "def minCameraCover_wrong(self, root)" }, { "docstring": ":type root: TreeNode :rtype: int", "name": "minCameraCover", "signature": "def minCameraCover(self, root)" }, { "docstring": "...
3
stack_v2_sparse_classes_30k_train_010828
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minCameraCover_wrong(self, root): :type root: TreeNode :rtype: int - def minCameraCover(self, root): :type root: TreeNode :rtype: int - def minCameraCover2(self, root): :type...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minCameraCover_wrong(self, root): :type root: TreeNode :rtype: int - def minCameraCover(self, root): :type root: TreeNode :rtype: int - def minCameraCover2(self, root): :type...
340ae58fb65b97aa6c6ab2daa8cbd82d1093deae
<|skeleton|> class Solution: def minCameraCover_wrong(self, root): """:type root: TreeNode :rtype: int""" <|body_0|> def minCameraCover(self, root): """:type root: TreeNode :rtype: int""" <|body_1|> def minCameraCover2(self, root): """:type root: TreeNode :rtype: i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def minCameraCover_wrong(self, root): """:type root: TreeNode :rtype: int""" dp, all = (collections.defaultdict(int), collections.defaultdict(int)) def dfs(node): if node in dp: return dp[node] if not node.left and (not node.right): ...
the_stack_v2_python_sparse
learnpythonthehardway/Binary-Tree-Cameras-968.py
dgpllc/leetcode-python
train
0
5e6502e267081cc4764c3d426c13c0c76d21c0be
[ "self.l = []\nself.helper(self.l, root, target, k)\nreturn self.l", "if not node:\n return False\nif self.helper(l, node.left, target, k):\n return True\nif len(l) == k:\n if abs(l[0] - target) < abs(node.val - target):\n return True\n else:\n l.pop(0)\nl.append(node.val)\nprint(l)\nretu...
<|body_start_0|> self.l = [] self.helper(self.l, root, target, k) return self.l <|end_body_0|> <|body_start_1|> if not node: return False if self.helper(l, node.left, target, k): return True if len(l) == k: if abs(l[0] - target) < abs(...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def closestKValues(self, root, target, k): """:type root: TreeNode :type target: float :type k: int :rtype: List[int]""" <|body_0|> def helper(self, l, node, target, k): """:type node: TreeNode :type target: float :type k: int :type l: list :rtype: bool""" ...
stack_v2_sparse_classes_36k_train_011256
1,751
no_license
[ { "docstring": ":type root: TreeNode :type target: float :type k: int :rtype: List[int]", "name": "closestKValues", "signature": "def closestKValues(self, root, target, k)" }, { "docstring": ":type node: TreeNode :type target: float :type k: int :type l: list :rtype: bool", "name": "helper",...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def closestKValues(self, root, target, k): :type root: TreeNode :type target: float :type k: int :rtype: List[int] - def helper(self, l, node, target, k): :type node: TreeNode :t...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def closestKValues(self, root, target, k): :type root: TreeNode :type target: float :type k: int :rtype: List[int] - def helper(self, l, node, target, k): :type node: TreeNode :t...
9d9e0c08992ef7dbd9ac517821faa9de17f49b0e
<|skeleton|> class Solution: def closestKValues(self, root, target, k): """:type root: TreeNode :type target: float :type k: int :rtype: List[int]""" <|body_0|> def helper(self, l, node, target, k): """:type node: TreeNode :type target: float :type k: int :type l: list :rtype: bool""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def closestKValues(self, root, target, k): """:type root: TreeNode :type target: float :type k: int :rtype: List[int]""" self.l = [] self.helper(self.l, root, target, k) return self.l def helper(self, l, node, target, k): """:type node: TreeNode :type tar...
the_stack_v2_python_sparse
272-closest-binary-search-tree-value-ii.py
floydchenchen/leetcode
train
0
848b7adca0bd5af3d073d05f318338c5c909a6ac
[ "rng = np.random.default_rng(self.seed)\nself.seeds_ = {'train_test': rng.integers(MAX_RAND_SEED), 'kfold_shuffle': rng.integers(MAX_RAND_SEED), 'kfp': rng.integers(MAX_RAND_SEED)}\nself.logger.info('Running %s', self)\nstart = time.perf_counter()\nX, y = self.load_dataset()\nself.logger.info('Dataset shape=%s, n_c...
<|body_start_0|> rng = np.random.default_rng(self.seed) self.seeds_ = {'train_test': rng.integers(MAX_RAND_SEED), 'kfold_shuffle': rng.integers(MAX_RAND_SEED), 'kfp': rng.integers(MAX_RAND_SEED)} self.logger.info('Running %s', self) start = time.perf_counter() X, y = self.load_da...
An experiment to evalute hyperparameter tuned k-FP classifier.
Experiment
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Experiment: """An experiment to evalute hyperparameter tuned k-FP classifier.""" def run(self): """Run hyperparameter tuning for the VarCNN classifier and return the prediction probabilities for the best chosen classifier.""" <|body_0|> def tune_hyperparameters(self, x_t...
stack_v2_sparse_classes_36k_train_011257
7,687
permissive
[ { "docstring": "Run hyperparameter tuning for the VarCNN classifier and return the prediction probabilities for the best chosen classifier.", "name": "run", "signature": "def run(self)" }, { "docstring": "Perform hyperparameter tuning.", "name": "tune_hyperparameters", "signature": "def ...
3
null
Implement the Python class `Experiment` described below. Class description: An experiment to evalute hyperparameter tuned k-FP classifier. Method signatures and docstrings: - def run(self): Run hyperparameter tuning for the VarCNN classifier and return the prediction probabilities for the best chosen classifier. - de...
Implement the Python class `Experiment` described below. Class description: An experiment to evalute hyperparameter tuned k-FP classifier. Method signatures and docstrings: - def run(self): Run hyperparameter tuning for the VarCNN classifier and return the prediction probabilities for the best chosen classifier. - de...
61f0ceedad70b2be7609f3a02f1fc4115265d910
<|skeleton|> class Experiment: """An experiment to evalute hyperparameter tuned k-FP classifier.""" def run(self): """Run hyperparameter tuning for the VarCNN classifier and return the prediction probabilities for the best chosen classifier.""" <|body_0|> def tune_hyperparameters(self, x_t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Experiment: """An experiment to evalute hyperparameter tuned k-FP classifier.""" def run(self): """Run hyperparameter tuning for the VarCNN classifier and return the prediction probabilities for the best chosen classifier.""" rng = np.random.default_rng(self.seed) self.seeds_ = {'...
the_stack_v2_python_sparse
workflow/scripts/evaluate_tuned_kfp.py
jpcsmith/qcsd-experiments
train
2
5e487f6d77b5629efb1084439719aca626b42be6
[ "self.profiling_parameters = {}\nself._use_default_metrics_configs = False\nself._use_one_config_for_all_metrics = False\nself._use_custom_metrics_configs = False\nself._process_trace_file_parameters(local_path, file_max_size, file_close_interval, file_open_fail_threshold)\nuse_custom_metrics_configs = self._proces...
<|body_start_0|> self.profiling_parameters = {} self._use_default_metrics_configs = False self._use_one_config_for_all_metrics = False self._use_custom_metrics_configs = False self._process_trace_file_parameters(local_path, file_max_size, file_close_interval, file_open_fail_thres...
Sets up the profiling configuration for framework metrics. Validates user inputs and fills in default values if no input is provided. There are three main profiling options to choose from: :class:`~sagemaker.debugger.metrics_config.DetailedProfilingConfig`, :class:`~sagemaker.debugger.metrics_config.DataloaderProfiling...
FrameworkProfile
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FrameworkProfile: """Sets up the profiling configuration for framework metrics. Validates user inputs and fills in default values if no input is provided. There are three main profiling options to choose from: :class:`~sagemaker.debugger.metrics_config.DetailedProfilingConfig`, :class:`~sagemaker...
stack_v2_sparse_classes_36k_train_011258
12,642
permissive
[ { "docstring": "Initialize the FrameworkProfile class object. Args: detailed_profiling_config (DetailedProfilingConfig): The configuration for detailed profiling. Configure it using the :class:`~sagemaker.debugger.metrics_config.DetailedProfilingConfig` class. Pass ``DetailedProfilingConfig()`` to use the defau...
5
stack_v2_sparse_classes_30k_train_005009
Implement the Python class `FrameworkProfile` described below. Class description: Sets up the profiling configuration for framework metrics. Validates user inputs and fills in default values if no input is provided. There are three main profiling options to choose from: :class:`~sagemaker.debugger.metrics_config.Detai...
Implement the Python class `FrameworkProfile` described below. Class description: Sets up the profiling configuration for framework metrics. Validates user inputs and fills in default values if no input is provided. There are three main profiling options to choose from: :class:`~sagemaker.debugger.metrics_config.Detai...
8d5d7fd8ae1a917ed3e2b988d5e533bce244fd85
<|skeleton|> class FrameworkProfile: """Sets up the profiling configuration for framework metrics. Validates user inputs and fills in default values if no input is provided. There are three main profiling options to choose from: :class:`~sagemaker.debugger.metrics_config.DetailedProfilingConfig`, :class:`~sagemaker...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FrameworkProfile: """Sets up the profiling configuration for framework metrics. Validates user inputs and fills in default values if no input is provided. There are three main profiling options to choose from: :class:`~sagemaker.debugger.metrics_config.DetailedProfilingConfig`, :class:`~sagemaker.debugger.met...
the_stack_v2_python_sparse
src/sagemaker/debugger/framework_profile.py
aws/sagemaker-python-sdk
train
2,050
94a91369623d8affc28d32f6a63ad54caa5c09eb
[ "self.main_path = main_path\nself.ch_list = ch_list\nself.feature_labels = []\nfor n in ch_list:\n self.feature_labels += [x.__name__ + '_' + str(n) for x in param_list]\nself.feature_labels += [x.__name__ for x in cross_ch_param_list]\nself.feature_labels = np.array(self.feature_labels)\nself.df = pd.read_csv(o...
<|body_start_0|> self.main_path = main_path self.ch_list = ch_list self.feature_labels = [] for n in ch_list: self.feature_labels += [x.__name__ + '_' + str(n) for x in param_list] self.feature_labels += [x.__name__ for x in cross_ch_param_list] self.feature_l...
MethodTest Tests different feature combinations for seizure prediction obtained from testing dataset
MethodTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MethodTest: """MethodTest Tests different feature combinations for seizure prediction obtained from testing dataset""" def __init__(self, main_path): """ThreshMetrics(main_path) Parameters ---------- input_path : Str, path to parent directory.""" <|body_0|> def multi_fol...
stack_v2_sparse_classes_36k_train_011259
7,872
permissive
[ { "docstring": "ThreshMetrics(main_path) Parameters ---------- input_path : Str, path to parent directory.", "name": "__init__", "signature": "def __init__(self, main_path)" }, { "docstring": "multi_folder(self) Loop though folder paths get seizure metrics and save to csv Parameters ---------- m...
3
stack_v2_sparse_classes_30k_train_016837
Implement the Python class `MethodTest` described below. Class description: MethodTest Tests different feature combinations for seizure prediction obtained from testing dataset Method signatures and docstrings: - def __init__(self, main_path): ThreshMetrics(main_path) Parameters ---------- input_path : Str, path to p...
Implement the Python class `MethodTest` described below. Class description: MethodTest Tests different feature combinations for seizure prediction obtained from testing dataset Method signatures and docstrings: - def __init__(self, main_path): ThreshMetrics(main_path) Parameters ---------- input_path : Str, path to p...
fd238749a8b80af1bd0902f737bc9017c4e29756
<|skeleton|> class MethodTest: """MethodTest Tests different feature combinations for seizure prediction obtained from testing dataset""" def __init__(self, main_path): """ThreshMetrics(main_path) Parameters ---------- input_path : Str, path to parent directory.""" <|body_0|> def multi_fol...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MethodTest: """MethodTest Tests different feature combinations for seizure prediction obtained from testing dataset""" def __init__(self, main_path): """ThreshMetrics(main_path) Parameters ---------- input_path : Str, path to parent directory.""" self.main_path = main_path self.ch...
the_stack_v2_python_sparse
model_selection/find_best_models.py
bhargavaganti/logic_seizedetect
train
0
2c1ce9b33fc0b7ac96c0e683692982322e64f2ae
[ "q = quantity.Mass(1.0, 'kg')\nself.assertAlmostEqual(q.value, 1.0, 6)\nself.assertAlmostEqual(q.value_si, 1.0, delta=1e-06)\nself.assertEqual(q.units, 'kg')", "q = quantity.Mass(1.0, 'g/mol')\nself.assertAlmostEqual(q.value, 1.0, 6)\nself.assertAlmostEqual(q.value_si, constants.amu, delta=1e-32)\nself.assertEqua...
<|body_start_0|> q = quantity.Mass(1.0, 'kg') self.assertAlmostEqual(q.value, 1.0, 6) self.assertAlmostEqual(q.value_si, 1.0, delta=1e-06) self.assertEqual(q.units, 'kg') <|end_body_0|> <|body_start_1|> q = quantity.Mass(1.0, 'g/mol') self.assertAlmostEqual(q.value, 1.0,...
Contains unit tests of the Mass unit type object.
TestMass
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestMass: """Contains unit tests of the Mass unit type object.""" def test_kg(self): """Test the creation of a mass quantity with units of kg.""" <|body_0|> def test_gpermol(self): """Test the creation of a mass quantity with units of g/mol. Note that g/mol is au...
stack_v2_sparse_classes_36k_train_011260
33,010
permissive
[ { "docstring": "Test the creation of a mass quantity with units of kg.", "name": "test_kg", "signature": "def test_kg(self)" }, { "docstring": "Test the creation of a mass quantity with units of g/mol. Note that g/mol is automatically coerced to amu.", "name": "test_gpermol", "signature"...
4
stack_v2_sparse_classes_30k_val_000510
Implement the Python class `TestMass` described below. Class description: Contains unit tests of the Mass unit type object. Method signatures and docstrings: - def test_kg(self): Test the creation of a mass quantity with units of kg. - def test_gpermol(self): Test the creation of a mass quantity with units of g/mol. ...
Implement the Python class `TestMass` described below. Class description: Contains unit tests of the Mass unit type object. Method signatures and docstrings: - def test_kg(self): Test the creation of a mass quantity with units of kg. - def test_gpermol(self): Test the creation of a mass quantity with units of g/mol. ...
0937b2e0a955dcf21b79674a4e89f43941c0dd85
<|skeleton|> class TestMass: """Contains unit tests of the Mass unit type object.""" def test_kg(self): """Test the creation of a mass quantity with units of kg.""" <|body_0|> def test_gpermol(self): """Test the creation of a mass quantity with units of g/mol. Note that g/mol is au...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestMass: """Contains unit tests of the Mass unit type object.""" def test_kg(self): """Test the creation of a mass quantity with units of kg.""" q = quantity.Mass(1.0, 'kg') self.assertAlmostEqual(q.value, 1.0, 6) self.assertAlmostEqual(q.value_si, 1.0, delta=1e-06) ...
the_stack_v2_python_sparse
rmgpy/quantityTest.py
vrlambert/RMG-Py
train
1
57b2ac2d6ec0bc8f8722a7e3ffe7db9c9101a175
[ "ans = []\nfor num in range(left, right + 1):\n if self.selflDividNum(num):\n ans.append(num)\nreturn ans", "num_original = num\nwhile num:\n remainder = num % 10\n if not remainder or num_original % remainder != 0:\n return False\n num = num // 10\nreturn True" ]
<|body_start_0|> ans = [] for num in range(left, right + 1): if self.selflDividNum(num): ans.append(num) return ans <|end_body_0|> <|body_start_1|> num_original = num while num: remainder = num % 10 if not remainder or num_orig...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def selfDividingNumbers(self, left, right): """:type left: int :type right: int :rtype: List[int]""" <|body_0|> def selflDividNum(self, num): """return true if num is self dividable""" <|body_1|> <|end_skeleton|> <|body_start_0|> ans = [] ...
stack_v2_sparse_classes_36k_train_011261
1,347
no_license
[ { "docstring": ":type left: int :type right: int :rtype: List[int]", "name": "selfDividingNumbers", "signature": "def selfDividingNumbers(self, left, right)" }, { "docstring": "return true if num is self dividable", "name": "selflDividNum", "signature": "def selflDividNum(self, num)" }...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def selfDividingNumbers(self, left, right): :type left: int :type right: int :rtype: List[int] - def selflDividNum(self, num): return true if num is self dividable
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def selfDividingNumbers(self, left, right): :type left: int :type right: int :rtype: List[int] - def selflDividNum(self, num): return true if num is self dividable <|skeleton|> ...
f96a2273c6831a8035e1adacfa452f73c599ae16
<|skeleton|> class Solution: def selfDividingNumbers(self, left, right): """:type left: int :type right: int :rtype: List[int]""" <|body_0|> def selflDividNum(self, num): """return true if num is self dividable""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def selfDividingNumbers(self, left, right): """:type left: int :type right: int :rtype: List[int]""" ans = [] for num in range(left, right + 1): if self.selflDividNum(num): ans.append(num) return ans def selflDividNum(self, num): ...
the_stack_v2_python_sparse
Python/SelfDividingNumbers.py
here0009/LeetCode
train
1
bb6cf1212bd8bc0bbcb2a6473677e98eac087154
[ "self._attr_name = name\nself._attr_unit_of_measurement = unit\nself._multiplier = multiplier\nself.bh1750_sensor = bh1750_sensor", "await self.hass.async_add_executor_job(self.bh1750_sensor.update)\nif self.bh1750_sensor.sample_ok and self.bh1750_sensor.light_level >= 0:\n self._attr_state = int(round(self.bh...
<|body_start_0|> self._attr_name = name self._attr_unit_of_measurement = unit self._multiplier = multiplier self.bh1750_sensor = bh1750_sensor <|end_body_0|> <|body_start_1|> await self.hass.async_add_executor_job(self.bh1750_sensor.update) if self.bh1750_sensor.sample_o...
Implementation of the BH1750 sensor.
BH1750Sensor
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BH1750Sensor: """Implementation of the BH1750 sensor.""" def __init__(self, bh1750_sensor, name, unit, multiplier=1.0): """Initialize the sensor.""" <|body_0|> async def async_update(self): """Get the latest data from the BH1750 and update the states.""" ...
stack_v2_sparse_classes_36k_train_011262
4,284
permissive
[ { "docstring": "Initialize the sensor.", "name": "__init__", "signature": "def __init__(self, bh1750_sensor, name, unit, multiplier=1.0)" }, { "docstring": "Get the latest data from the BH1750 and update the states.", "name": "async_update", "signature": "async def async_update(self)" ...
2
stack_v2_sparse_classes_30k_train_019835
Implement the Python class `BH1750Sensor` described below. Class description: Implementation of the BH1750 sensor. Method signatures and docstrings: - def __init__(self, bh1750_sensor, name, unit, multiplier=1.0): Initialize the sensor. - async def async_update(self): Get the latest data from the BH1750 and update th...
Implement the Python class `BH1750Sensor` described below. Class description: Implementation of the BH1750 sensor. Method signatures and docstrings: - def __init__(self, bh1750_sensor, name, unit, multiplier=1.0): Initialize the sensor. - async def async_update(self): Get the latest data from the BH1750 and update th...
2fee32fce03bc49e86cf2e7b741a15621a97cce5
<|skeleton|> class BH1750Sensor: """Implementation of the BH1750 sensor.""" def __init__(self, bh1750_sensor, name, unit, multiplier=1.0): """Initialize the sensor.""" <|body_0|> async def async_update(self): """Get the latest data from the BH1750 and update the states.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BH1750Sensor: """Implementation of the BH1750 sensor.""" def __init__(self, bh1750_sensor, name, unit, multiplier=1.0): """Initialize the sensor.""" self._attr_name = name self._attr_unit_of_measurement = unit self._multiplier = multiplier self.bh1750_sensor = bh17...
the_stack_v2_python_sparse
homeassistant/components/bh1750/sensor.py
BenWoodford/home-assistant
train
11
3e79601fb9582a89895752f4851208bac731fa8c
[ "self.text = ''\nself.keywords = None\nself.seg = Segmentation(stop_words_file=stop_words_file, allow_speech_tags=allow_speech_tags, delimiters=delimiters)\nself.sentences = None\nself.words_no_filter = None\nself.words_no_stop_words = None\nself.words_all_filters = None", "self.text = text\nself.word_index = {}\...
<|body_start_0|> self.text = '' self.keywords = None self.seg = Segmentation(stop_words_file=stop_words_file, allow_speech_tags=allow_speech_tags, delimiters=delimiters) self.sentences = None self.words_no_filter = None self.words_no_stop_words = None self.words_a...
TextRank4Keyword
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TextRank4Keyword: def __init__(self, allow_speech_tags, delimiters, stop_words_file=None): """Keyword arguments: stop_words_file -- str,指定停止词文件路径(一行一个停止词),若为其他类型,则使用默认停止词文件 delimiters -- 默认值是`?!;?!。;… `,用来将文本拆分为句子。 Object Var: self.words_no_filter -- 对sentences中每个句子分词而得到的两级列表。 self.words...
stack_v2_sparse_classes_36k_train_011263
20,624
no_license
[ { "docstring": "Keyword arguments: stop_words_file -- str,指定停止词文件路径(一行一个停止词),若为其他类型,则使用默认停止词文件 delimiters -- 默认值是`?!;?!。;… `,用来将文本拆分为句子。 Object Var: self.words_no_filter -- 对sentences中每个句子分词而得到的两级列表。 self.words_no_stop_words -- 去掉words_no_filter中的停止词而得到的两级列表。 self.words_all_filters -- 保留words_no_stop_words中指定词性...
4
null
Implement the Python class `TextRank4Keyword` described below. Class description: Implement the TextRank4Keyword class. Method signatures and docstrings: - def __init__(self, allow_speech_tags, delimiters, stop_words_file=None): Keyword arguments: stop_words_file -- str,指定停止词文件路径(一行一个停止词),若为其他类型,则使用默认停止词文件 delimiters...
Implement the Python class `TextRank4Keyword` described below. Class description: Implement the TextRank4Keyword class. Method signatures and docstrings: - def __init__(self, allow_speech_tags, delimiters, stop_words_file=None): Keyword arguments: stop_words_file -- str,指定停止词文件路径(一行一个停止词),若为其他类型,则使用默认停止词文件 delimiters...
ca2cf55b4dbae09a3c85689c8dae104908060c86
<|skeleton|> class TextRank4Keyword: def __init__(self, allow_speech_tags, delimiters, stop_words_file=None): """Keyword arguments: stop_words_file -- str,指定停止词文件路径(一行一个停止词),若为其他类型,则使用默认停止词文件 delimiters -- 默认值是`?!;?!。;… `,用来将文本拆分为句子。 Object Var: self.words_no_filter -- 对sentences中每个句子分词而得到的两级列表。 self.words...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TextRank4Keyword: def __init__(self, allow_speech_tags, delimiters, stop_words_file=None): """Keyword arguments: stop_words_file -- str,指定停止词文件路径(一行一个停止词),若为其他类型,则使用默认停止词文件 delimiters -- 默认值是`?!;?!。;… `,用来将文本拆分为句子。 Object Var: self.words_no_filter -- 对sentences中每个句子分词而得到的两级列表。 self.words_no_stop_words...
the_stack_v2_python_sparse
owner/吴伟/keyword_extraction.py
dxcv/GsEnv
train
0
c7f2275a1e3d02db3ee212a088ab600fbbf708ef
[ "if t < 0 or k < 0:\n return False\nall_buckets = {}\nbucket_size = t + 1\nfor i in range(len(nums)):\n bucket_num = nums[i] // bucket_size\n if bucket_num in all_buckets:\n return True\n all_buckets[bucket_num] = nums[i]\n if bucket_num - 1 in all_buckets and abs(all_buckets[bucket_num - 1] -...
<|body_start_0|> if t < 0 or k < 0: return False all_buckets = {} bucket_size = t + 1 for i in range(len(nums)): bucket_num = nums[i] // bucket_size if bucket_num in all_buckets: return True all_buckets[bucket_num] = nums[i]...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def containsNearbyAlmostDuplicate(self, nums, k, t): """:type nums: List[int] :type k: int :type t: int :rtype: bool""" <|body_0|> def containsNearbyAlmostDuplicate2(self, nums, k, t): """:type nums: List[int] :type k: int :type t: int :rtype: bool""" ...
stack_v2_sparse_classes_36k_train_011264
2,872
no_license
[ { "docstring": ":type nums: List[int] :type k: int :type t: int :rtype: bool", "name": "containsNearbyAlmostDuplicate", "signature": "def containsNearbyAlmostDuplicate(self, nums, k, t)" }, { "docstring": ":type nums: List[int] :type k: int :type t: int :rtype: bool", "name": "containsNearby...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def containsNearbyAlmostDuplicate(self, nums, k, t): :type nums: List[int] :type k: int :type t: int :rtype: bool - def containsNearbyAlmostDuplicate2(self, nums, k, t): :type nu...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def containsNearbyAlmostDuplicate(self, nums, k, t): :type nums: List[int] :type k: int :type t: int :rtype: bool - def containsNearbyAlmostDuplicate2(self, nums, k, t): :type nu...
b0f498ebe84e46b7e17e94759dd462891dcc8f85
<|skeleton|> class Solution: def containsNearbyAlmostDuplicate(self, nums, k, t): """:type nums: List[int] :type k: int :type t: int :rtype: bool""" <|body_0|> def containsNearbyAlmostDuplicate2(self, nums, k, t): """:type nums: List[int] :type k: int :type t: int :rtype: bool""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def containsNearbyAlmostDuplicate(self, nums, k, t): """:type nums: List[int] :type k: int :type t: int :rtype: bool""" if t < 0 or k < 0: return False all_buckets = {} bucket_size = t + 1 for i in range(len(nums)): bucket_num = nums[i]...
the_stack_v2_python_sparse
查找表类算法/table_5_2.py
wulinlw/leetcode_cn
train
0
a9c3ba960690756f88d22e81291e4d283be26e16
[ "self.num_params = num_params\nself.lr = lr\nself.decay_rate = decay_rate\nself.runner = [0 for _ in range(num_params)]", "new_params = []\nfor i in range(self.num_params):\n self.runner[i] = self.decay_rate * self.runner[i] + (1 - self.decay_rate) * grad_params[i] ** 2\n new_params.append(params[i] - self....
<|body_start_0|> self.num_params = num_params self.lr = lr self.decay_rate = decay_rate self.runner = [0 for _ in range(num_params)] <|end_body_0|> <|body_start_1|> new_params = [] for i in range(self.num_params): self.runner[i] = self.decay_rate * self.runne...
RMSProp
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RMSProp: def __init__(self, num_params, lr=0.00146, decay_rate=0.9): """Initializer for RMSProp optimizer inputs: num params: number of parameters which are ought to be passed lr: The learning rate with which the gradient step should be taken(integer/float), default is 0.00146 decay_rate...
stack_v2_sparse_classes_36k_train_011265
10,861
no_license
[ { "docstring": "Initializer for RMSProp optimizer inputs: num params: number of parameters which are ought to be passed lr: The learning rate with which the gradient step should be taken(integer/float), default is 0.00146 decay_rate : decay rate/moving average hyper parameter (int/float), default is 0.9", "...
2
stack_v2_sparse_classes_30k_train_005176
Implement the Python class `RMSProp` described below. Class description: Implement the RMSProp class. Method signatures and docstrings: - def __init__(self, num_params, lr=0.00146, decay_rate=0.9): Initializer for RMSProp optimizer inputs: num params: number of parameters which are ought to be passed lr: The learning...
Implement the Python class `RMSProp` described below. Class description: Implement the RMSProp class. Method signatures and docstrings: - def __init__(self, num_params, lr=0.00146, decay_rate=0.9): Initializer for RMSProp optimizer inputs: num params: number of parameters which are ought to be passed lr: The learning...
9406b21aef9b2d94091d570e809f88a752277e30
<|skeleton|> class RMSProp: def __init__(self, num_params, lr=0.00146, decay_rate=0.9): """Initializer for RMSProp optimizer inputs: num params: number of parameters which are ought to be passed lr: The learning rate with which the gradient step should be taken(integer/float), default is 0.00146 decay_rate...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RMSProp: def __init__(self, num_params, lr=0.00146, decay_rate=0.9): """Initializer for RMSProp optimizer inputs: num params: number of parameters which are ought to be passed lr: The learning rate with which the gradient step should be taken(integer/float), default is 0.00146 decay_rate : decay rate/...
the_stack_v2_python_sparse
optimizers.py
viswambhar-yasa/AuToDiFf
train
0
23f3d0ce30810504dfa03a5c3a6ff6e0eccb0f7a
[ "src_nodes = torch.tensor([2, 3, 4])\ndst_nodes = torch.tensor([1, 2, 3])\ng = dgl.graph((src_nodes, dst_nodes))\nassert g.num_nodes() == 5\nassert g.num_edges() == 3\ng = dgl.graph((src_nodes, dst_nodes), idtype=torch.int32, device='cuda:0')\nassert g.num_nodes() == 5\nassert g.num_edges() == 3", "edge_dict = {(...
<|body_start_0|> src_nodes = torch.tensor([2, 3, 4]) dst_nodes = torch.tensor([1, 2, 3]) g = dgl.graph((src_nodes, dst_nodes)) assert g.num_nodes() == 5 assert g.num_edges() == 3 g = dgl.graph((src_nodes, dst_nodes), idtype=torch.int32, device='cuda:0') assert g.n...
1. 基于Tensor构建图: 同构图: dgl.graph 异构图: dgl.heterograph 2. 随机图: 随机同构图:dgl.rand_graph 随机二部图:dgl.rand_bipartie
GraphConstructTest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GraphConstructTest: """1. 基于Tensor构建图: 同构图: dgl.graph 异构图: dgl.heterograph 2. 随机图: 随机同构图:dgl.rand_graph 随机二部图:dgl.rand_bipartie""" def test_graph(self): """签名:dgl.graph(edge_data, num_nodes=None, itype=None ...) 作用:生成一个同构图 参数说明: edge_data: 标明边, 可以取(tensor_1d, tensor_1d)以及其他的稀疏表示形式 nu...
stack_v2_sparse_classes_36k_train_011266
3,239
no_license
[ { "docstring": "签名:dgl.graph(edge_data, num_nodes=None, itype=None ...) 作用:生成一个同构图 参数说明: edge_data: 标明边, 可以取(tensor_1d, tensor_1d)以及其他的稀疏表示形式 num_nodes:node数, 从0开始 itype: 存储节点的id类型, 一般为torch.int32, touch.int64 参考:https://docs.dgl.ai/en/0.7.x/generated/dgl.graph.html", "name": "test_graph", "signature": ...
3
null
Implement the Python class `GraphConstructTest` described below. Class description: 1. 基于Tensor构建图: 同构图: dgl.graph 异构图: dgl.heterograph 2. 随机图: 随机同构图:dgl.rand_graph 随机二部图:dgl.rand_bipartie Method signatures and docstrings: - def test_graph(self): 签名:dgl.graph(edge_data, num_nodes=None, itype=None ...) 作用:生成一个同构图 参数说明...
Implement the Python class `GraphConstructTest` described below. Class description: 1. 基于Tensor构建图: 同构图: dgl.graph 异构图: dgl.heterograph 2. 随机图: 随机同构图:dgl.rand_graph 随机二部图:dgl.rand_bipartie Method signatures and docstrings: - def test_graph(self): 签名:dgl.graph(edge_data, num_nodes=None, itype=None ...) 作用:生成一个同构图 参数说明...
4f4bd55d7f0502c188976dda2f95fd25614283f3
<|skeleton|> class GraphConstructTest: """1. 基于Tensor构建图: 同构图: dgl.graph 异构图: dgl.heterograph 2. 随机图: 随机同构图:dgl.rand_graph 随机二部图:dgl.rand_bipartie""" def test_graph(self): """签名:dgl.graph(edge_data, num_nodes=None, itype=None ...) 作用:生成一个同构图 参数说明: edge_data: 标明边, 可以取(tensor_1d, tensor_1d)以及其他的稀疏表示形式 nu...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GraphConstructTest: """1. 基于Tensor构建图: 同构图: dgl.graph 异构图: dgl.heterograph 2. 随机图: 随机同构图:dgl.rand_graph 随机二部图:dgl.rand_bipartie""" def test_graph(self): """签名:dgl.graph(edge_data, num_nodes=None, itype=None ...) 作用:生成一个同构图 参数说明: edge_data: 标明边, 可以取(tensor_1d, tensor_1d)以及其他的稀疏表示形式 num_nodes:node数...
the_stack_v2_python_sparse
com.xulf.learn.ml.dgl/graph_basics/graph_construct_test.py
sankoudai/py-knowledge-center
train
0
a8090aea15462d1009ebe53c3f7ee376db9804e6
[ "self.module = module\nself.PlotCaseRuns = PlotCaseRuns\npass", "odir = os.path.join(case_path, 'json_files')\nofile = os.path.join(odir, 'figure_step.json')\nPrepare_Result = self.module(case_path)\nPrepare_Result.Interpret(step=step)\nUtilities.my_assert(os.path.isfile(pr_script), AssertionError, \"%s doesn't e...
<|body_start_0|> self.module = module self.PlotCaseRuns = PlotCaseRuns pass <|end_body_0|> <|body_start_1|> odir = os.path.join(case_path, 'json_files') ofile = os.path.join(odir, 'figure_step.json') Prepare_Result = self.module(case_path) Prepare_Result.Interpre...
A class for preparing results
PLOTTER
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PLOTTER: """A class for preparing results""" def __init__(self, module, PlotCaseRuns, **kwargs): """Initiation module (class) - class to use for generating results at each step PlotCaseRuns (list of functions) - a list of functions for generating result at a given step. kwargs(dict):...
stack_v2_sparse_classes_36k_train_011267
13,097
no_license
[ { "docstring": "Initiation module (class) - class to use for generating results at each step PlotCaseRuns (list of functions) - a list of functions for generating result at a given step. kwargs(dict):", "name": "__init__", "signature": "def __init__(self, module, PlotCaseRuns, **kwargs)" }, { "d...
4
stack_v2_sparse_classes_30k_train_007123
Implement the Python class `PLOTTER` described below. Class description: A class for preparing results Method signatures and docstrings: - def __init__(self, module, PlotCaseRuns, **kwargs): Initiation module (class) - class to use for generating results at each step PlotCaseRuns (list of functions) - a list of funct...
Implement the Python class `PLOTTER` described below. Class description: A class for preparing results Method signatures and docstrings: - def __init__(self, module, PlotCaseRuns, **kwargs): Initiation module (class) - class to use for generating results at each step PlotCaseRuns (list of functions) - a list of funct...
d919cadce2b57811351c0615d94da5c6ebfff800
<|skeleton|> class PLOTTER: """A class for preparing results""" def __init__(self, module, PlotCaseRuns, **kwargs): """Initiation module (class) - class to use for generating results at each step PlotCaseRuns (list of functions) - a list of functions for generating result at a given step. kwargs(dict):...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PLOTTER: """A class for preparing results""" def __init__(self, module, PlotCaseRuns, **kwargs): """Initiation module (class) - class to use for generating results at each step PlotCaseRuns (list of functions) - a list of functions for generating result at a given step. kwargs(dict):""" s...
the_stack_v2_python_sparse
shilofue/PlotCase.py
lhy11009/aspectLib
train
0
987ece94fee63037dda0c82508864cb6e8e996e7
[ "super(RelaxedTransformerLoss, self).__init__(fix_im)\nself.regularization_constant = regularization_constant\nself.transformation_loss = transformation_loss\nself.transform_norm_kwargs = transform_norm_kwargs or {}", "transformer = kwargs['transformer']\nassert isinstance(transformer, st.ParameterizedTransformat...
<|body_start_0|> super(RelaxedTransformerLoss, self).__init__(fix_im) self.regularization_constant = regularization_constant self.transformation_loss = transformation_loss self.transform_norm_kwargs = transform_norm_kwargs or {} <|end_body_0|> <|body_start_1|> transformer = kwar...
Relaxed version of transformer loss: assumes that the adversarial examples are of the form Y=S(X) + delta for some S in the transformation class and some small delta perturbation outside the perturbation. In this case, we just compute ||delta|| + c||S|| This saves us from having to do the inner minmization step
RelaxedTransformerLoss
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RelaxedTransformerLoss: """Relaxed version of transformer loss: assumes that the adversarial examples are of the form Y=S(X) + delta for some S in the transformation class and some small delta perturbation outside the perturbation. In this case, we just compute ||delta|| + c||S|| This saves us fr...
stack_v2_sparse_classes_36k_train_011268
22,033
permissive
[ { "docstring": "Takes in a reference fix im and a class of transformations we need to search over to compute forward.", "name": "__init__", "signature": "def __init__(self, fix_im, regularization_constant=1.0, transformation_loss=partial(utils.summed_lp_norm, lp=2), transform_norm_kwargs=None)" }, {...
2
stack_v2_sparse_classes_30k_train_009090
Implement the Python class `RelaxedTransformerLoss` described below. Class description: Relaxed version of transformer loss: assumes that the adversarial examples are of the form Y=S(X) + delta for some S in the transformation class and some small delta perturbation outside the perturbation. In this case, we just comp...
Implement the Python class `RelaxedTransformerLoss` described below. Class description: Relaxed version of transformer loss: assumes that the adversarial examples are of the form Y=S(X) + delta for some S in the transformation class and some small delta perturbation outside the perturbation. In this case, we just comp...
c030c009fcf2842d9951ced1296b0d6578cee151
<|skeleton|> class RelaxedTransformerLoss: """Relaxed version of transformer loss: assumes that the adversarial examples are of the form Y=S(X) + delta for some S in the transformation class and some small delta perturbation outside the perturbation. In this case, we just compute ||delta|| + c||S|| This saves us fr...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RelaxedTransformerLoss: """Relaxed version of transformer loss: assumes that the adversarial examples are of the form Y=S(X) + delta for some S in the transformation class and some small delta perturbation outside the perturbation. In this case, we just compute ||delta|| + c||S|| This saves us from having to ...
the_stack_v2_python_sparse
recoloradv/mister_ed/loss_functions.py
cassidylaidlaw/ReColorAdv
train
32
4c78a0e0436901a3e3325ebb2bef896e21166bbb
[ "self.name = name\nself.table_info = table_info\nself.mtype = mtype\nself.uuid = uuid", "if dictionary is None:\n return None\nname = dictionary.get('name')\ntable_info = cohesity_management_sdk.models.hbase_table.HBaseTable.from_dictionary(dictionary.get('tableInfo')) if dictionary.get('tableInfo') else None\...
<|body_start_0|> self.name = name self.table_info = table_info self.mtype = mtype self.uuid = uuid <|end_body_0|> <|body_start_1|> if dictionary is None: return None name = dictionary.get('name') table_info = cohesity_management_sdk.models.hbase_table...
Implementation of the 'HBaseProtectionSource' model. Specifies an Object representing HBase. Attributes: name (string): Specifies the instance name of the HBase entity. table_info (HBaseTable): Information of a HBase Table, only valid for an entity of type kTable. mtype (TypeHBaseProtectionSourceEnum): Specifies the ty...
HBaseProtectionSource
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HBaseProtectionSource: """Implementation of the 'HBaseProtectionSource' model. Specifies an Object representing HBase. Attributes: name (string): Specifies the instance name of the HBase entity. table_info (HBaseTable): Information of a HBase Table, only valid for an entity of type kTable. mtype ...
stack_v2_sparse_classes_36k_train_011269
2,520
permissive
[ { "docstring": "Constructor for the HBaseProtectionSource class", "name": "__init__", "signature": "def __init__(self, name=None, table_info=None, mtype=None, uuid=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representa...
2
null
Implement the Python class `HBaseProtectionSource` described below. Class description: Implementation of the 'HBaseProtectionSource' model. Specifies an Object representing HBase. Attributes: name (string): Specifies the instance name of the HBase entity. table_info (HBaseTable): Information of a HBase Table, only val...
Implement the Python class `HBaseProtectionSource` described below. Class description: Implementation of the 'HBaseProtectionSource' model. Specifies an Object representing HBase. Attributes: name (string): Specifies the instance name of the HBase entity. table_info (HBaseTable): Information of a HBase Table, only val...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class HBaseProtectionSource: """Implementation of the 'HBaseProtectionSource' model. Specifies an Object representing HBase. Attributes: name (string): Specifies the instance name of the HBase entity. table_info (HBaseTable): Information of a HBase Table, only valid for an entity of type kTable. mtype ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HBaseProtectionSource: """Implementation of the 'HBaseProtectionSource' model. Specifies an Object representing HBase. Attributes: name (string): Specifies the instance name of the HBase entity. table_info (HBaseTable): Information of a HBase Table, only valid for an entity of type kTable. mtype (TypeHBasePro...
the_stack_v2_python_sparse
cohesity_management_sdk/models/h_base_protection_source.py
cohesity/management-sdk-python
train
24
40ec335f69e287cadb29b36456a3ca93df9851cd
[ "args = movie_queue_parser.parse_args()\npage = args['page']\nmax_results = args['max']\ndownloaded = args['is_downloaded']\nsort_by = args['sort_by']\norder = args['order']\nqueue_name = args['queue_name']\nif order == 'desc':\n order = True\nelse:\n order = False\nraw_movie_queue = mq.queue_get(session=sess...
<|body_start_0|> args = movie_queue_parser.parse_args() page = args['page'] max_results = args['max'] downloaded = args['is_downloaded'] sort_by = args['sort_by'] order = args['order'] queue_name = args['queue_name'] if order == 'desc': order =...
MovieQueueAPI
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MovieQueueAPI: def get(self, session=None): """List queued movies""" <|body_0|> def post(self, session=None): """Add movies to movie queue""" <|body_1|> <|end_skeleton|> <|body_start_0|> args = movie_queue_parser.parse_args() page = args['pa...
stack_v2_sparse_classes_36k_train_011270
9,040
permissive
[ { "docstring": "List queued movies", "name": "get", "signature": "def get(self, session=None)" }, { "docstring": "Add movies to movie queue", "name": "post", "signature": "def post(self, session=None)" } ]
2
stack_v2_sparse_classes_30k_train_000157
Implement the Python class `MovieQueueAPI` described below. Class description: Implement the MovieQueueAPI class. Method signatures and docstrings: - def get(self, session=None): List queued movies - def post(self, session=None): Add movies to movie queue
Implement the Python class `MovieQueueAPI` described below. Class description: Implement the MovieQueueAPI class. Method signatures and docstrings: - def get(self, session=None): List queued movies - def post(self, session=None): Add movies to movie queue <|skeleton|> class MovieQueueAPI: def get(self, session=...
900bd353a70c5a41176eb505af68ed3fc65a796d
<|skeleton|> class MovieQueueAPI: def get(self, session=None): """List queued movies""" <|body_0|> def post(self, session=None): """Add movies to movie queue""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MovieQueueAPI: def get(self, session=None): """List queued movies""" args = movie_queue_parser.parse_args() page = args['page'] max_results = args['max'] downloaded = args['is_downloaded'] sort_by = args['sort_by'] order = args['order'] queue_nam...
the_stack_v2_python_sparse
flexget/plugins/api/movie_queue.py
ashumkin/Flexget
train
1
4c2c2e56444eeee5156c2f6f5000414182c1bc79
[ "super(DefaultStringMatcher, self).__init__(terms=vocabulary)\nself.similarity = similarity\nself.best_matches_only = best_matches_only\nself.no_match_threshold = no_match_threshold\nself._cache = dict() if cache_results else None", "if self._cache and query in self._cache:\n return self._cache[query]\nmatches...
<|body_start_0|> super(DefaultStringMatcher, self).__init__(terms=vocabulary) self.similarity = similarity self.best_matches_only = best_matches_only self.no_match_threshold = no_match_threshold self._cache = dict() if cache_results else None <|end_body_0|> <|body_start_1|> ...
Default implementation for the string matcher. This is a simple implementation that naively computes the similarity between a query string and every string in the associated vocabulary by letting the string similarity object deal with the vocabulary directly. The default matcher allows the user to control the list of r...
DefaultStringMatcher
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DefaultStringMatcher: """Default implementation for the string matcher. This is a simple implementation that naively computes the similarity between a query string and every string in the associated vocabulary by letting the string similarity object deal with the vocabulary directly. The default ...
stack_v2_sparse_classes_36k_train_011271
12,724
permissive
[ { "docstring": "Initialize the associated vocabulary, the similarity function, and the configuration parameters. Parameters ---------- vocabulary: iterable of string List of terms in the associated vocabulary agains which query strings are matched. similarity: openclean.function.matching.base.StringSimilarity S...
2
stack_v2_sparse_classes_30k_train_013441
Implement the Python class `DefaultStringMatcher` described below. Class description: Default implementation for the string matcher. This is a simple implementation that naively computes the similarity between a query string and every string in the associated vocabulary by letting the string similarity object deal wit...
Implement the Python class `DefaultStringMatcher` described below. Class description: Default implementation for the string matcher. This is a simple implementation that naively computes the similarity between a query string and every string in the associated vocabulary by letting the string similarity object deal wit...
e3d0e04f90468c49f29ca53edc2feb12465c24d5
<|skeleton|> class DefaultStringMatcher: """Default implementation for the string matcher. This is a simple implementation that naively computes the similarity between a query string and every string in the associated vocabulary by letting the string similarity object deal with the vocabulary directly. The default ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DefaultStringMatcher: """Default implementation for the string matcher. This is a simple implementation that naively computes the similarity between a query string and every string in the associated vocabulary by letting the string similarity object deal with the vocabulary directly. The default matcher allow...
the_stack_v2_python_sparse
openclean/function/matching/base.py
Denisfench/openclean-core
train
0
f4e46dbbb95d5f4c0687528df6e08c46e16dfc43
[ "if trigger.after is None or trigger.after.source_content is None or trigger.after.source_content.identifier is None:\n exc = RuntimeError('Post-event state or source package not set')\n self.fail(exc, 'Post-event state or source package not set')\n return -1\nreturn trigger.after.source_content.identifier...
<|body_start_0|> if trigger.after is None or trigger.after.source_content is None or trigger.after.source_content.identifier is None: exc = RuntimeError('Post-event state or source package not set') self.fail(exc, 'Post-event state or source package not set') return -1 ...
Provides :func:`.source_id`.
_SourceProcess
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _SourceProcess: """Provides :func:`.source_id`.""" def source_id(self, trigger: Trigger) -> int: """Get the source ID for the submission content.""" <|body_0|> def source_checksum(self, trigger: Trigger) -> Optional[str]: """Get the checksum for the submission co...
stack_v2_sparse_classes_36k_train_011272
6,358
permissive
[ { "docstring": "Get the source ID for the submission content.", "name": "source_id", "signature": "def source_id(self, trigger: Trigger) -> int" }, { "docstring": "Get the checksum for the submission content.", "name": "source_checksum", "signature": "def source_checksum(self, trigger: T...
2
null
Implement the Python class `_SourceProcess` described below. Class description: Provides :func:`.source_id`. Method signatures and docstrings: - def source_id(self, trigger: Trigger) -> int: Get the source ID for the submission content. - def source_checksum(self, trigger: Trigger) -> Optional[str]: Get the checksum ...
Implement the Python class `_SourceProcess` described below. Class description: Provides :func:`.source_id`. Method signatures and docstrings: - def source_id(self, trigger: Trigger) -> int: Get the source ID for the submission content. - def source_checksum(self, trigger: Trigger) -> Optional[str]: Get the checksum ...
6077ce4e0685d67ce7010800083a898857158112
<|skeleton|> class _SourceProcess: """Provides :func:`.source_id`.""" def source_id(self, trigger: Trigger) -> int: """Get the source ID for the submission content.""" <|body_0|> def source_checksum(self, trigger: Trigger) -> Optional[str]: """Get the checksum for the submission co...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _SourceProcess: """Provides :func:`.source_id`.""" def source_id(self, trigger: Trigger) -> int: """Get the source ID for the submission content.""" if trigger.after is None or trigger.after.source_content is None or trigger.after.source_content.identifier is None: exc = Runti...
the_stack_v2_python_sparse
agent/agent/process/legacy_filesystem_integration.py
arXiv/arxiv-submission-core
train
14
495ea9650af5820adf8a7f0505a7ae39d2714c15
[ "super(DLAUp, self).__init__()\nself.startp = startp\nif norm_func is None:\n norm_func = nn.BatchNorm2d\nif in_channels is None:\n in_channels = channels\nself.channels = channels\nchannels = list(channels)\nscales = np.array(scales, dtype=int)\nfor i in range(len(channels) - 1):\n j = -i - 2\n setattr...
<|body_start_0|> super(DLAUp, self).__init__() self.startp = startp if norm_func is None: norm_func = nn.BatchNorm2d if in_channels is None: in_channels = channels self.channels = channels channels = list(channels) scales = np.array(scales,...
DLA Up module
DLAUp
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DLAUp: """DLA Up module""" def __init__(self, startp, channels, scales, in_channels=None, norm_func=None): """DLA Up module""" <|body_0|> def forward(self, layers): """forward""" <|body_1|> <|end_skeleton|> <|body_start_0|> super(DLAUp, self).__...
stack_v2_sparse_classes_36k_train_011273
16,229
permissive
[ { "docstring": "DLA Up module", "name": "__init__", "signature": "def __init__(self, startp, channels, scales, in_channels=None, norm_func=None)" }, { "docstring": "forward", "name": "forward", "signature": "def forward(self, layers)" } ]
2
stack_v2_sparse_classes_30k_train_008901
Implement the Python class `DLAUp` described below. Class description: DLA Up module Method signatures and docstrings: - def __init__(self, startp, channels, scales, in_channels=None, norm_func=None): DLA Up module - def forward(self, layers): forward
Implement the Python class `DLAUp` described below. Class description: DLA Up module Method signatures and docstrings: - def __init__(self, startp, channels, scales, in_channels=None, norm_func=None): DLA Up module - def forward(self, layers): forward <|skeleton|> class DLAUp: """DLA Up module""" def __init...
f6f10c403763ea58aceccc0486b6e37ffa902989
<|skeleton|> class DLAUp: """DLA Up module""" def __init__(self, startp, channels, scales, in_channels=None, norm_func=None): """DLA Up module""" <|body_0|> def forward(self, layers): """forward""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DLAUp: """DLA Up module""" def __init__(self, startp, channels, scales, in_channels=None, norm_func=None): """DLA Up module""" super(DLAUp, self).__init__() self.startp = startp if norm_func is None: norm_func = nn.BatchNorm2d if in_channels is None: ...
the_stack_v2_python_sparse
PaddleCV/3d_vision/SMOKE/smoke/models/backbones/dla.py
ranchlai/models
train
2
d2cc412e30fb8ab6432776ebfa83e70e630a5bec
[ "super().__init__(cv)\nself._nextrocket = 0\nself._time = 0\nself._cv = cv\nself._pos = pos", "super().update(dt)\nself._time = self._time + dt\nif self._time > self._nextrocket:\n r = Rocket(self._cv, self._pos, 1000, ['red', 'blue', 'yellow', 'chartreuse2'], [500, 500], 3, 3)\n entities.append(r)\n sel...
<|body_start_0|> super().__init__(cv) self._nextrocket = 0 self._time = 0 self._cv = cv self._pos = pos <|end_body_0|> <|body_start_1|> super().update(dt) self._time = self._time + dt if self._time > self._nextrocket: r = Rocket(self._cv, self...
RocketLauncher
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RocketLauncher: def __init__(self, cv, pos): """Used to fire rockets into the sky at random intervals. Arguments: cv {idontknow} -- the canvas upon which this wonderful display pos {int} -- the position of the new rocket from the old rocket""" <|body_0|> def update(self, dt)...
stack_v2_sparse_classes_36k_train_011274
16,427
permissive
[ { "docstring": "Used to fire rockets into the sky at random intervals. Arguments: cv {idontknow} -- the canvas upon which this wonderful display pos {int} -- the position of the new rocket from the old rocket", "name": "__init__", "signature": "def __init__(self, cv, pos)" }, { "docstring": "Add...
2
stack_v2_sparse_classes_30k_train_019288
Implement the Python class `RocketLauncher` described below. Class description: Implement the RocketLauncher class. Method signatures and docstrings: - def __init__(self, cv, pos): Used to fire rockets into the sky at random intervals. Arguments: cv {idontknow} -- the canvas upon which this wonderful display pos {int...
Implement the Python class `RocketLauncher` described below. Class description: Implement the RocketLauncher class. Method signatures and docstrings: - def __init__(self, cv, pos): Used to fire rockets into the sky at random intervals. Arguments: cv {idontknow} -- the canvas upon which this wonderful display pos {int...
c6b6d80e9d59f5d115ca8b8fc020fcd6cb030af8
<|skeleton|> class RocketLauncher: def __init__(self, cv, pos): """Used to fire rockets into the sky at random intervals. Arguments: cv {idontknow} -- the canvas upon which this wonderful display pos {int} -- the position of the new rocket from the old rocket""" <|body_0|> def update(self, dt)...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RocketLauncher: def __init__(self, cv, pos): """Used to fire rockets into the sky at random intervals. Arguments: cv {idontknow} -- the canvas upon which this wonderful display pos {int} -- the position of the new rocket from the old rocket""" super().__init__(cv) self._nextrocket = 0 ...
the_stack_v2_python_sparse
scripts/sheet9/9.2.py
LennartElbe/PythOnline
train
0
34b89161e6ea943285243d35e422d82352f1d405
[ "self.copy = copy\nif not (axis == 0) | (axis == 1) | (axis == -1):\n raise ValueError('Axis must be 0,1, or -1')\nself.axis = axis", "if self.copy:\n if self.axis == 0:\n return A / A.sum(axis=self.axis)[None, :]\n else:\n return A / A.sum(axis=self.axis)[:, None]\nelse:\n if A.dtype !=...
<|body_start_0|> self.copy = copy if not (axis == 0) | (axis == 1) | (axis == -1): raise ValueError('Axis must be 0,1, or -1') self.axis = axis <|end_body_0|> <|body_start_1|> if self.copy: if self.axis == 0: return A / A.sum(axis=self.axis)[None,...
Normalization constraint. Parameters ---------- axis : int Which axis of input matrix A to apply normalization acorss. copy : bool Make copy of input data, A; otherwise, overwrite (if mutable)
ConstraintNorm
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConstraintNorm: """Normalization constraint. Parameters ---------- axis : int Which axis of input matrix A to apply normalization acorss. copy : bool Make copy of input data, A; otherwise, overwrite (if mutable)""" def __init__(self, axis=-1, copy=False): """Normalize along axis""" ...
stack_v2_sparse_classes_36k_train_011275
2,103
permissive
[ { "docstring": "Normalize along axis", "name": "__init__", "signature": "def __init__(self, axis=-1, copy=False)" }, { "docstring": "Apply normalization constraint", "name": "transform", "signature": "def transform(self, A)" } ]
2
stack_v2_sparse_classes_30k_train_002852
Implement the Python class `ConstraintNorm` described below. Class description: Normalization constraint. Parameters ---------- axis : int Which axis of input matrix A to apply normalization acorss. copy : bool Make copy of input data, A; otherwise, overwrite (if mutable) Method signatures and docstrings: - def __ini...
Implement the Python class `ConstraintNorm` described below. Class description: Normalization constraint. Parameters ---------- axis : int Which axis of input matrix A to apply normalization acorss. copy : bool Make copy of input data, A; otherwise, overwrite (if mutable) Method signatures and docstrings: - def __ini...
8a20e085d82c2e089dac973b4cfc5d2b73b51736
<|skeleton|> class ConstraintNorm: """Normalization constraint. Parameters ---------- axis : int Which axis of input matrix A to apply normalization acorss. copy : bool Make copy of input data, A; otherwise, overwrite (if mutable)""" def __init__(self, axis=-1, copy=False): """Normalize along axis""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ConstraintNorm: """Normalization constraint. Parameters ---------- axis : int Which axis of input matrix A to apply normalization acorss. copy : bool Make copy of input data, A; otherwise, overwrite (if mutable)""" def __init__(self, axis=-1, copy=False): """Normalize along axis""" self.c...
the_stack_v2_python_sparse
octavvs/pymcr_new/constraints.py
ctroein/octavvs
train
9
9db812d14371c47cc63cadaedf71b9d843e51e48
[ "self.arrayOne = [100, 63, 1, 6, 2, 13]\nself.X = 63\nself.Y = 63\nself.output = 5\nreturn (self.arrayOne, self.X, self.Y, self.output)", "arrayOne, X, Y, output = self.setUp()\noutput_method = solution(X, Y, arrayOne)\nself.assertEqual(output, output_method)" ]
<|body_start_0|> self.arrayOne = [100, 63, 1, 6, 2, 13] self.X = 63 self.Y = 63 self.output = 5 return (self.arrayOne, self.X, self.Y, self.output) <|end_body_0|> <|body_start_1|> arrayOne, X, Y, output = self.setUp() output_method = solution(X, Y, arrayOne) ...
Class with unittests for Codility_3_task.py
test_Codility_3_task
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class test_Codility_3_task: """Class with unittests for Codility_3_task.py""" def setUp(self): """Sets up input.""" <|body_0|> def test_user_input(self): """Checks if method works properly.""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.arrayOne...
stack_v2_sparse_classes_36k_train_011276
901
no_license
[ { "docstring": "Sets up input.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Checks if method works properly.", "name": "test_user_input", "signature": "def test_user_input(self)" } ]
2
null
Implement the Python class `test_Codility_3_task` described below. Class description: Class with unittests for Codility_3_task.py Method signatures and docstrings: - def setUp(self): Sets up input. - def test_user_input(self): Checks if method works properly.
Implement the Python class `test_Codility_3_task` described below. Class description: Class with unittests for Codility_3_task.py Method signatures and docstrings: - def setUp(self): Sets up input. - def test_user_input(self): Checks if method works properly. <|skeleton|> class test_Codility_3_task: """Class wit...
3aa62ad36c3b06b2a3b05f1f8e2a9e21d68b371f
<|skeleton|> class test_Codility_3_task: """Class with unittests for Codility_3_task.py""" def setUp(self): """Sets up input.""" <|body_0|> def test_user_input(self): """Checks if method works properly.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class test_Codility_3_task: """Class with unittests for Codility_3_task.py""" def setUp(self): """Sets up input.""" self.arrayOne = [100, 63, 1, 6, 2, 13] self.X = 63 self.Y = 63 self.output = 5 return (self.arrayOne, self.X, self.Y, self.output) def test_us...
the_stack_v2_python_sparse
Codility_algorithms/test_Codility_3_task.py
JakubKazimierski/PythonPortfolio
train
9
d289e5547441ca375772b60e966cb0cf439913fb
[ "super().__init__()\nassert size % num_heads == 0\nself.head_size = head_size = size // num_heads\nself.model_size = size\nself.num_heads = num_heads\nself.k_layer = nn.Linear(size, num_heads * head_size)\nself.v_layer = nn.Linear(size, num_heads * head_size)\nself.q_layer = nn.Linear(size, num_heads * head_size)\n...
<|body_start_0|> super().__init__() assert size % num_heads == 0 self.head_size = head_size = size // num_heads self.model_size = size self.num_heads = num_heads self.k_layer = nn.Linear(size, num_heads * head_size) self.v_layer = nn.Linear(size, num_heads * head_...
Multi-Head Attention module from "Attention is All You Need" Implementation modified from OpenNMT-py. https://github.com/OpenNMT/OpenNMT-py
MultiHeadedAttention
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiHeadedAttention: """Multi-Head Attention module from "Attention is All You Need" Implementation modified from OpenNMT-py. https://github.com/OpenNMT/OpenNMT-py""" def __init__(self, num_heads: int, size: int, dropout: float=0.1) -> None: """Create a multi-headed attention layer....
stack_v2_sparse_classes_36k_train_011277
13,169
permissive
[ { "docstring": "Create a multi-headed attention layer. :param num_heads: the number of heads :param size: hidden size (must be divisible by num_heads) :param dropout: probability of dropping a unit", "name": "__init__", "signature": "def __init__(self, num_heads: int, size: int, dropout: float=0.1) -> N...
2
stack_v2_sparse_classes_30k_train_001119
Implement the Python class `MultiHeadedAttention` described below. Class description: Multi-Head Attention module from "Attention is All You Need" Implementation modified from OpenNMT-py. https://github.com/OpenNMT/OpenNMT-py Method signatures and docstrings: - def __init__(self, num_heads: int, size: int, dropout: f...
Implement the Python class `MultiHeadedAttention` described below. Class description: Multi-Head Attention module from "Attention is All You Need" Implementation modified from OpenNMT-py. https://github.com/OpenNMT/OpenNMT-py Method signatures and docstrings: - def __init__(self, num_heads: int, size: int, dropout: f...
0968187ac0968007cabebed5e5cb6587c08dff78
<|skeleton|> class MultiHeadedAttention: """Multi-Head Attention module from "Attention is All You Need" Implementation modified from OpenNMT-py. https://github.com/OpenNMT/OpenNMT-py""" def __init__(self, num_heads: int, size: int, dropout: float=0.1) -> None: """Create a multi-headed attention layer....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultiHeadedAttention: """Multi-Head Attention module from "Attention is All You Need" Implementation modified from OpenNMT-py. https://github.com/OpenNMT/OpenNMT-py""" def __init__(self, num_heads: int, size: int, dropout: float=0.1) -> None: """Create a multi-headed attention layer. :param num_h...
the_stack_v2_python_sparse
joeynmt/transformer_layers.py
joeynmt/joeynmt
train
668
24581175401848fac323e00d17629aabd49187d7
[ "results = super(CompanyLDAP, self).get_ldap_dicts()\nldaps = self.sudo().search([('ldap_server', '!=', False)], order='sequence')\ncacert_paths = ldaps.read(['cacert_path'])\nfor i in range(len(results)):\n results[i].update(cacert_paths[i])\nreturn results", "uri = 'ldap://%s:%d' % (conf['ldap_server'], conf...
<|body_start_0|> results = super(CompanyLDAP, self).get_ldap_dicts() ldaps = self.sudo().search([('ldap_server', '!=', False)], order='sequence') cacert_paths = ldaps.read(['cacert_path']) for i in range(len(results)): results[i].update(cacert_paths[i]) return results...
CompanyLDAP
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CompanyLDAP: def get_ldap_dicts(self): """Add cacert_path to ldap_dicts""" <|body_0|> def connect(self, conf): """Override odoo connect function to fix StartTLS Connect to an LDAP server specified by an ldap configuration dictionary. :param dict conf: LDAP configurat...
stack_v2_sparse_classes_36k_train_011278
1,325
no_license
[ { "docstring": "Add cacert_path to ldap_dicts", "name": "get_ldap_dicts", "signature": "def get_ldap_dicts(self)" }, { "docstring": "Override odoo connect function to fix StartTLS Connect to an LDAP server specified by an ldap configuration dictionary. :param dict conf: LDAP configuration :retur...
2
stack_v2_sparse_classes_30k_train_009122
Implement the Python class `CompanyLDAP` described below. Class description: Implement the CompanyLDAP class. Method signatures and docstrings: - def get_ldap_dicts(self): Add cacert_path to ldap_dicts - def connect(self, conf): Override odoo connect function to fix StartTLS Connect to an LDAP server specified by an ...
Implement the Python class `CompanyLDAP` described below. Class description: Implement the CompanyLDAP class. Method signatures and docstrings: - def get_ldap_dicts(self): Add cacert_path to ldap_dicts - def connect(self, conf): Override odoo connect function to fix StartTLS Connect to an LDAP server specified by an ...
c355e18aeb3e7123fe184fcc7ec06485ab498343
<|skeleton|> class CompanyLDAP: def get_ldap_dicts(self): """Add cacert_path to ldap_dicts""" <|body_0|> def connect(self, conf): """Override odoo connect function to fix StartTLS Connect to an LDAP server specified by an ldap configuration dictionary. :param dict conf: LDAP configurat...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CompanyLDAP: def get_ldap_dicts(self): """Add cacert_path to ldap_dicts""" results = super(CompanyLDAP, self).get_ldap_dicts() ldaps = self.sudo().search([('ldap_server', '!=', False)], order='sequence') cacert_paths = ldaps.read(['cacert_path']) for i in range(len(resu...
the_stack_v2_python_sparse
auth_ldap_tls/models/res_company_ldap.py
rythe77/odoo11_customized
train
5
a5428b1a799611dac61e81dbc7ee2f8a16a80f57
[ "if str2bool(value):\n return queryset.filter(status__in=BuildStatusGroups.ACTIVE_CODES)\nelse:\n return queryset.exclude(status__in=BuildStatusGroups.ACTIVE_CODES)", "if str2bool(value):\n return queryset.filter(Build.OVERDUE_FILTER)\nelse:\n return queryset.exclude(Build.OVERDUE_FILTER)", "value =...
<|body_start_0|> if str2bool(value): return queryset.filter(status__in=BuildStatusGroups.ACTIVE_CODES) else: return queryset.exclude(status__in=BuildStatusGroups.ACTIVE_CODES) <|end_body_0|> <|body_start_1|> if str2bool(value): return queryset.filter(Build.OV...
Custom filterset for BuildList API endpoint.
BuildFilter
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BuildFilter: """Custom filterset for BuildList API endpoint.""" def filter_active(self, queryset, name, value): """Filter the queryset to either include or exclude orders which are active.""" <|body_0|> def filter_overdue(self, queryset, name, value): """Filter t...
stack_v2_sparse_classes_36k_train_011279
20,912
permissive
[ { "docstring": "Filter the queryset to either include or exclude orders which are active.", "name": "filter_active", "signature": "def filter_active(self, queryset, name, value)" }, { "docstring": "Filter the queryset to either include or exclude orders which are overdue.", "name": "filter_o...
5
stack_v2_sparse_classes_30k_train_002868
Implement the Python class `BuildFilter` described below. Class description: Custom filterset for BuildList API endpoint. Method signatures and docstrings: - def filter_active(self, queryset, name, value): Filter the queryset to either include or exclude orders which are active. - def filter_overdue(self, queryset, n...
Implement the Python class `BuildFilter` described below. Class description: Custom filterset for BuildList API endpoint. Method signatures and docstrings: - def filter_active(self, queryset, name, value): Filter the queryset to either include or exclude orders which are active. - def filter_overdue(self, queryset, n...
e88a8e99a5f0b201c67a95cba097c729f090d5e2
<|skeleton|> class BuildFilter: """Custom filterset for BuildList API endpoint.""" def filter_active(self, queryset, name, value): """Filter the queryset to either include or exclude orders which are active.""" <|body_0|> def filter_overdue(self, queryset, name, value): """Filter t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BuildFilter: """Custom filterset for BuildList API endpoint.""" def filter_active(self, queryset, name, value): """Filter the queryset to either include or exclude orders which are active.""" if str2bool(value): return queryset.filter(status__in=BuildStatusGroups.ACTIVE_CODES)...
the_stack_v2_python_sparse
InvenTree/build/api.py
inventree/InvenTree
train
3,077
b4d5f9d41d2de4f8f37d32a98b1b3037b0efa458
[ "if bits % 8 != 0:\n raise ValueError('only implemented if bits is a multiple of 8')\nself.bits = bits\nself.n = n", "generators = []\nfor _ in range(self.n):\n generators.append(int.from_bytes(os.urandom(self.bits // 8), 'little'))\nreturn generators", "del seed\ngenerators = self._Generators()\nba = byt...
<|body_start_0|> if bits % 8 != 0: raise ValueError('only implemented if bits is a multiple of 8') self.bits = bits self.n = n <|end_body_0|> <|body_start_1|> generators = [] for _ in range(self.n): generators.append(int.from_bytes(os.urandom(self.bits //...
Generates random integers as the sum of a subset of generators. Subset sums are sometimes proposed as a short cut to generate ephemeral key pairs s, g**s for public key cryptosystems or signature schemes. The idea is to use a list of precomputed pairs (x_i, g**x_i) and then generate s as sum of a subset of the values {...
SubsetSum
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SubsetSum: """Generates random integers as the sum of a subset of generators. Subset sums are sometimes proposed as a short cut to generate ephemeral key pairs s, g**s for public key cryptosystems or signature schemes. The idea is to use a list of precomputed pairs (x_i, g**x_i) and then generate...
stack_v2_sparse_classes_36k_train_011280
19,579
permissive
[ { "docstring": "Constructs a SubsetSum generator. Args: bits: the size of the generators in bits n: the number of generators", "name": "__init__", "signature": "def __init__(self, bits: int, n: int)" }, { "docstring": "Returns a new list of generators. Returns: a list of n random integers in the...
3
null
Implement the Python class `SubsetSum` described below. Class description: Generates random integers as the sum of a subset of generators. Subset sums are sometimes proposed as a short cut to generate ephemeral key pairs s, g**s for public key cryptosystems or signature schemes. The idea is to use a list of precompute...
Implement the Python class `SubsetSum` described below. Class description: Generates random integers as the sum of a subset of generators. Subset sums are sometimes proposed as a short cut to generate ephemeral key pairs s, g**s for public key cryptosystems or signature schemes. The idea is to use a list of precompute...
16e5f47fcc11f51d3fb58b50adddd075f4373bbc
<|skeleton|> class SubsetSum: """Generates random integers as the sum of a subset of generators. Subset sums are sometimes proposed as a short cut to generate ephemeral key pairs s, g**s for public key cryptosystems or signature schemes. The idea is to use a list of precomputed pairs (x_i, g**x_i) and then generate...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SubsetSum: """Generates random integers as the sum of a subset of generators. Subset sums are sometimes proposed as a short cut to generate ephemeral key pairs s, g**s for public key cryptosystems or signature schemes. The idea is to use a list of precomputed pairs (x_i, g**x_i) and then generate s as sum of ...
the_stack_v2_python_sparse
paranoid_crypto/lib/randomness_tests/rng.py
google/paranoid_crypto
train
766
be37114d2ada19f1378ea1a8ecac64b054a26240
[ "if self.request.user.is_staff:\n product_param = self.request.query_params.get('content_type')\n if product_param:\n product_param = [int(product_id) for product_id in product_param.split(',')]\n return OrderLine.objects.all().filter(content_type__id__in=product_param)\n return OrderLine.obj...
<|body_start_0|> if self.request.user.is_staff: product_param = self.request.query_params.get('content_type') if product_param: product_param = [int(product_id) for product_id in product_param.split(',')] return OrderLine.objects.all().filter(content_type_...
retrieve: Return the given order line. list: Return a list of all the existing order lines. create: Create a new order line instance.
OrderLineViewSet
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OrderLineViewSet: """retrieve: Return the given order line. list: Return a list of all the existing order lines. create: Create a new order line instance.""" def get_queryset(self): """This viewset should return owned order lines except if the currently authenticated user is an admin...
stack_v2_sparse_classes_36k_train_011281
19,173
permissive
[ { "docstring": "This viewset should return owned order lines except if the currently authenticated user is an admin (is_staff).", "name": "get_queryset", "signature": "def get_queryset(self)" }, { "docstring": "Get content_type name, id and if he can display details group by content_type in all ...
2
null
Implement the Python class `OrderLineViewSet` described below. Class description: retrieve: Return the given order line. list: Return a list of all the existing order lines. create: Create a new order line instance. Method signatures and docstrings: - def get_queryset(self): This viewset should return owned order lin...
Implement the Python class `OrderLineViewSet` described below. Class description: retrieve: Return the given order line. list: Return a list of all the existing order lines. create: Create a new order line instance. Method signatures and docstrings: - def get_queryset(self): This viewset should return owned order lin...
4188745e236eab2056fe8455d81964641301fc3c
<|skeleton|> class OrderLineViewSet: """retrieve: Return the given order line. list: Return a list of all the existing order lines. create: Create a new order line instance.""" def get_queryset(self): """This viewset should return owned order lines except if the currently authenticated user is an admin...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OrderLineViewSet: """retrieve: Return the given order line. list: Return a list of all the existing order lines. create: Create a new order line instance.""" def get_queryset(self): """This viewset should return owned order lines except if the currently authenticated user is an admin (is_staff)."...
the_stack_v2_python_sparse
store/views.py
FJNR-inc/Blitz-API
train
5
a26166cc8680a892747429c237f2b0116c14f421
[ "self.clusters = {'normal': {}, 'minimum': {}, 'maximum': {}, 'all': {}}\nalgorithms = ['meanShift', 'HDBSCAN', 'aggl', 'spectral', 'Kmeans']\nself.set_clusters(algorithms)\nself.subreddit_list = get_lexica_order(path)\nclustered_data = os.listdir(path_clusters)\nself.get_clusters(clustered_data, path_clusters)", ...
<|body_start_0|> self.clusters = {'normal': {}, 'minimum': {}, 'maximum': {}, 'all': {}} algorithms = ['meanShift', 'HDBSCAN', 'aggl', 'spectral', 'Kmeans'] self.set_clusters(algorithms) self.subreddit_list = get_lexica_order(path) clustered_data = os.listdir(path_clusters) ...
An object containing all results of the clustering algorithms in every view. Attributes: clusters: dictionary containing all labels. Access labels using view (feature matrix)as key. If the number of clusters had to be specified manually use number of clusters as second key. subreddit_list: list of subreddit feature vec...
ClusteredData
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ClusteredData: """An object containing all results of the clustering algorithms in every view. Attributes: clusters: dictionary containing all labels. Access labels using view (feature matrix)as key. If the number of clusters had to be specified manually use number of clusters as second key. subr...
stack_v2_sparse_classes_36k_train_011282
3,712
no_license
[ { "docstring": "Initialize object containing all labels of the clustering algorithms. Arguments: path: path to the folder containing results of the clustering algorithms", "name": "__init__", "signature": "def __init__(self, path, path_clusters)" }, { "docstring": "Initialize dictionary of clust...
6
stack_v2_sparse_classes_30k_train_015208
Implement the Python class `ClusteredData` described below. Class description: An object containing all results of the clustering algorithms in every view. Attributes: clusters: dictionary containing all labels. Access labels using view (feature matrix)as key. If the number of clusters had to be specified manually use...
Implement the Python class `ClusteredData` described below. Class description: An object containing all results of the clustering algorithms in every view. Attributes: clusters: dictionary containing all labels. Access labels using view (feature matrix)as key. If the number of clusters had to be specified manually use...
8e30b14d811ee345dd7ca12de4e6d26bd6a7a8c8
<|skeleton|> class ClusteredData: """An object containing all results of the clustering algorithms in every view. Attributes: clusters: dictionary containing all labels. Access labels using view (feature matrix)as key. If the number of clusters had to be specified manually use number of clusters as second key. subr...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ClusteredData: """An object containing all results of the clustering algorithms in every view. Attributes: clusters: dictionary containing all labels. Access labels using view (feature matrix)as key. If the number of clusters had to be specified manually use number of clusters as second key. subreddit_list: l...
the_stack_v2_python_sparse
examinlexica/clusteredData/clustered_data.py
HubReb/examing_socialsent_lexica
train
2
09fed4065259c21373898452e6f89bc3e74d25be
[ "tmpdir = tempfile.mkdtemp()\nbooster.save_model(os.path.join(tmpdir, cls.MODEL_FILENAME))\ncheckpoint = cls.from_directory(tmpdir)\nif preprocessor:\n checkpoint.set_preprocessor(preprocessor)\nreturn checkpoint", "with self.as_directory() as checkpoint_path:\n booster = xgboost.Booster()\n booster.load...
<|body_start_0|> tmpdir = tempfile.mkdtemp() booster.save_model(os.path.join(tmpdir, cls.MODEL_FILENAME)) checkpoint = cls.from_directory(tmpdir) if preprocessor: checkpoint.set_preprocessor(preprocessor) return checkpoint <|end_body_0|> <|body_start_1|> with...
A :py:class:`~ray.train.Checkpoint` with XGBoost-specific functionality.
XGBoostCheckpoint
[ "MIT", "BSD-3-Clause", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class XGBoostCheckpoint: """A :py:class:`~ray.train.Checkpoint` with XGBoost-specific functionality.""" def from_model(cls, booster: xgboost.Booster, *, preprocessor: Optional['Preprocessor']=None) -> 'XGBoostCheckpoint': """Create a :py:class:`~ray.air.checkpoint.Checkpoint` that stores a...
stack_v2_sparse_classes_36k_train_011283
2,054
permissive
[ { "docstring": "Create a :py:class:`~ray.air.checkpoint.Checkpoint` that stores an XGBoost model. Args: booster: The XGBoost model to store in the checkpoint. preprocessor: A fitted preprocessor to be applied before inference. Returns: An :py:class:`XGBoostCheckpoint` containing the specified ``Estimator``. Exa...
2
null
Implement the Python class `XGBoostCheckpoint` described below. Class description: A :py:class:`~ray.train.Checkpoint` with XGBoost-specific functionality. Method signatures and docstrings: - def from_model(cls, booster: xgboost.Booster, *, preprocessor: Optional['Preprocessor']=None) -> 'XGBoostCheckpoint': Create a...
Implement the Python class `XGBoostCheckpoint` described below. Class description: A :py:class:`~ray.train.Checkpoint` with XGBoost-specific functionality. Method signatures and docstrings: - def from_model(cls, booster: xgboost.Booster, *, preprocessor: Optional['Preprocessor']=None) -> 'XGBoostCheckpoint': Create a...
edba68c3e7cf255d1d6479329f305adb7fa4c3ed
<|skeleton|> class XGBoostCheckpoint: """A :py:class:`~ray.train.Checkpoint` with XGBoost-specific functionality.""" def from_model(cls, booster: xgboost.Booster, *, preprocessor: Optional['Preprocessor']=None) -> 'XGBoostCheckpoint': """Create a :py:class:`~ray.air.checkpoint.Checkpoint` that stores a...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class XGBoostCheckpoint: """A :py:class:`~ray.train.Checkpoint` with XGBoost-specific functionality.""" def from_model(cls, booster: xgboost.Booster, *, preprocessor: Optional['Preprocessor']=None) -> 'XGBoostCheckpoint': """Create a :py:class:`~ray.air.checkpoint.Checkpoint` that stores an XGBoost mod...
the_stack_v2_python_sparse
python/ray/train/xgboost/xgboost_checkpoint.py
ray-project/ray
train
29,482
605fbbae1ab1deaf47aadd96955997bf064265a4
[ "super().__init__()\nfor i, block in enumerate(blocks):\n self.add_node(i, block=block)\nfor u, v in edges:\n if u in self.nodes and v in self.nodes:\n if self.nodes[u]['block'].n_output == self.nodes[v]['block'].n_input:\n self.add_edge(u, v)", "if not self.valid:\n return []\npaths = ...
<|body_start_0|> super().__init__() for i, block in enumerate(blocks): self.add_node(i, block=block) for u, v in edges: if u in self.nodes and v in self.nodes: if self.nodes[u]['block'].n_output == self.nodes[v]['block'].n_input: self.a...
A Cell serves a Direct Acyclic Graph (DAG) which holds blocks as nodes and edges that connects operation paths between the nodes.
Cell
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Cell: """A Cell serves a Direct Acyclic Graph (DAG) which holds blocks as nodes and edges that connects operation paths between the nodes.""" def __init__(self, blocks: Block, edges: Tuple[Block, Block]) -> None: """Initialization method. Args: type: Type of the block. pointer: Any t...
stack_v2_sparse_classes_36k_train_011284
2,815
permissive
[ { "docstring": "Initialization method. Args: type: Type of the block. pointer: Any type of callable to be applied when block is called.", "name": "__init__", "signature": "def __init__(self, blocks: Block, edges: Tuple[Block, Block]) -> None" }, { "docstring": "Performs a forward pass over the c...
5
null
Implement the Python class `Cell` described below. Class description: A Cell serves a Direct Acyclic Graph (DAG) which holds blocks as nodes and edges that connects operation paths between the nodes. Method signatures and docstrings: - def __init__(self, blocks: Block, edges: Tuple[Block, Block]) -> None: Initializat...
Implement the Python class `Cell` described below. Class description: A Cell serves a Direct Acyclic Graph (DAG) which holds blocks as nodes and edges that connects operation paths between the nodes. Method signatures and docstrings: - def __init__(self, blocks: Block, edges: Tuple[Block, Block]) -> None: Initializat...
7326a887ed8e3858bc99c8815048d56d02edf88c
<|skeleton|> class Cell: """A Cell serves a Direct Acyclic Graph (DAG) which holds blocks as nodes and edges that connects operation paths between the nodes.""" def __init__(self, blocks: Block, edges: Tuple[Block, Block]) -> None: """Initialization method. Args: type: Type of the block. pointer: Any t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Cell: """A Cell serves a Direct Acyclic Graph (DAG) which holds blocks as nodes and edges that connects operation paths between the nodes.""" def __init__(self, blocks: Block, edges: Tuple[Block, Block]) -> None: """Initialization method. Args: type: Type of the block. pointer: Any type of callab...
the_stack_v2_python_sparse
opytimizer/core/cell.py
gugarosa/opytimizer
train
602
9795b15f81cefec10344680afc01b9deb34145b3
[ "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "conte...
<|body_start_0|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') <|end_body_0|> <|body_start_1|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not im...
Cloud OS Login API The Cloud OS Login API allows you to manage users and their associated SSH public keys for logging into virtual machines on Google Cloud Platform.
OsLoginServiceServicer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OsLoginServiceServicer: """Cloud OS Login API The Cloud OS Login API allows you to manage users and their associated SSH public keys for logging into virtual machines on Google Cloud Platform.""" def DeletePosixAccount(self, request, context): """Deletes a POSIX account.""" <...
stack_v2_sparse_classes_36k_train_011285
7,621
permissive
[ { "docstring": "Deletes a POSIX account.", "name": "DeletePosixAccount", "signature": "def DeletePosixAccount(self, request, context)" }, { "docstring": "Deletes an SSH public key.", "name": "DeleteSshPublicKey", "signature": "def DeleteSshPublicKey(self, request, context)" }, { ...
6
null
Implement the Python class `OsLoginServiceServicer` described below. Class description: Cloud OS Login API The Cloud OS Login API allows you to manage users and their associated SSH public keys for logging into virtual machines on Google Cloud Platform. Method signatures and docstrings: - def DeletePosixAccount(self,...
Implement the Python class `OsLoginServiceServicer` described below. Class description: Cloud OS Login API The Cloud OS Login API allows you to manage users and their associated SSH public keys for logging into virtual machines on Google Cloud Platform. Method signatures and docstrings: - def DeletePosixAccount(self,...
d897d56bce03d1fda98b79afb08264e51d46c421
<|skeleton|> class OsLoginServiceServicer: """Cloud OS Login API The Cloud OS Login API allows you to manage users and their associated SSH public keys for logging into virtual machines on Google Cloud Platform.""" def DeletePosixAccount(self, request, context): """Deletes a POSIX account.""" <...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OsLoginServiceServicer: """Cloud OS Login API The Cloud OS Login API allows you to manage users and their associated SSH public keys for logging into virtual machines on Google Cloud Platform.""" def DeletePosixAccount(self, request, context): """Deletes a POSIX account.""" context.set_co...
the_stack_v2_python_sparse
oslogin/google/cloud/oslogin_v1/proto/oslogin_pb2_grpc.py
tswast/google-cloud-python
train
1
4f6e88dd0e5d10f92d634e895a6fa98aa80b4751
[ "max_length = 0\ndp = [[False] * len(s) for _ in range(len(s))]\nfor i in range(len(s)):\n for j in range(i):\n if s[i] == s[j] and (dp[i - 1][j + 1] or i - j <= 2):\n dp[i][j] = True\n if i - j + 1 > max_length:\n max_length = i - j + 1\nreturn max_length", "max_len...
<|body_start_0|> max_length = 0 dp = [[False] * len(s) for _ in range(len(s))] for i in range(len(s)): for j in range(i): if s[i] == s[j] and (dp[i - 1][j + 1] or i - j <= 2): dp[i][j] = True if i - j + 1 > max_length: ...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def _longestPalindromeSubseq(self, s): """:type s: str :rtype: int""" <|body_0|> def __longestPalindromeSubseq(self, s): """:type s: str :rtype: int""" <|body_1|> def ___longestPalindromeSubseq(self, s): """:type s: str :rtype: int""" ...
stack_v2_sparse_classes_36k_train_011286
3,215
permissive
[ { "docstring": ":type s: str :rtype: int", "name": "_longestPalindromeSubseq", "signature": "def _longestPalindromeSubseq(self, s)" }, { "docstring": ":type s: str :rtype: int", "name": "__longestPalindromeSubseq", "signature": "def __longestPalindromeSubseq(self, s)" }, { "docst...
4
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def _longestPalindromeSubseq(self, s): :type s: str :rtype: int - def __longestPalindromeSubseq(self, s): :type s: str :rtype: int - def ___longestPalindromeSubseq(self, s): :typ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def _longestPalindromeSubseq(self, s): :type s: str :rtype: int - def __longestPalindromeSubseq(self, s): :type s: str :rtype: int - def ___longestPalindromeSubseq(self, s): :typ...
0dd67edca4e0b0323cb5a7239f02ea46383cd15a
<|skeleton|> class Solution: def _longestPalindromeSubseq(self, s): """:type s: str :rtype: int""" <|body_0|> def __longestPalindromeSubseq(self, s): """:type s: str :rtype: int""" <|body_1|> def ___longestPalindromeSubseq(self, s): """:type s: str :rtype: int""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def _longestPalindromeSubseq(self, s): """:type s: str :rtype: int""" max_length = 0 dp = [[False] * len(s) for _ in range(len(s))] for i in range(len(s)): for j in range(i): if s[i] == s[j] and (dp[i - 1][j + 1] or i - j <= 2): ...
the_stack_v2_python_sparse
516.longest-palindromic-subsequence.py
windard/leeeeee
train
0
af52a16954d4515cb5278db525982ad80d620ebd
[ "super(Dialog3DPlot, self).__init__(parent)\nself.setWindowTitle(title)\nself.setWindowFlags(self.windowFlags() & ~QtCore.Qt.WindowContextHelpButtonHint)\nself.layout = QtGui.QHBoxLayout(self)\nself.mayavi = MayaviViewer(self)\nself.layout.addWidget(self.mayavi)\nself.messenger = Messenger()", "if volume is None ...
<|body_start_0|> super(Dialog3DPlot, self).__init__(parent) self.setWindowTitle(title) self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.WindowContextHelpButtonHint) self.layout = QtGui.QHBoxLayout(self) self.mayavi = MayaviViewer(self) self.layout.addWidget(self.mayavi...
Dialog3DPlot
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Dialog3DPlot: def __init__(self, parent, title='Plot'): """Window that contains a 3D plot Args: parent (pyface.qt.QtGui.QWidget): parent widget title (str): window header""" <|body_0|> def show(self, volume=None): """Shows the plot Args: volume (numpy.ndarray): volum...
stack_v2_sparse_classes_36k_train_011287
1,120
no_license
[ { "docstring": "Window that contains a 3D plot Args: parent (pyface.qt.QtGui.QWidget): parent widget title (str): window header", "name": "__init__", "signature": "def __init__(self, parent, title='Plot')" }, { "docstring": "Shows the plot Args: volume (numpy.ndarray): volume to plot", "name...
2
stack_v2_sparse_classes_30k_train_009844
Implement the Python class `Dialog3DPlot` described below. Class description: Implement the Dialog3DPlot class. Method signatures and docstrings: - def __init__(self, parent, title='Plot'): Window that contains a 3D plot Args: parent (pyface.qt.QtGui.QWidget): parent widget title (str): window header - def show(self,...
Implement the Python class `Dialog3DPlot` described below. Class description: Implement the Dialog3DPlot class. Method signatures and docstrings: - def __init__(self, parent, title='Plot'): Window that contains a 3D plot Args: parent (pyface.qt.QtGui.QWidget): parent widget title (str): window header - def show(self,...
43c0ab07b72291ffce67e3b7088017e5654e89ca
<|skeleton|> class Dialog3DPlot: def __init__(self, parent, title='Plot'): """Window that contains a 3D plot Args: parent (pyface.qt.QtGui.QWidget): parent widget title (str): window header""" <|body_0|> def show(self, volume=None): """Shows the plot Args: volume (numpy.ndarray): volum...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Dialog3DPlot: def __init__(self, parent, title='Plot'): """Window that contains a 3D plot Args: parent (pyface.qt.QtGui.QWidget): parent widget title (str): window header""" super(Dialog3DPlot, self).__init__(parent) self.setWindowTitle(title) self.setWindowFlags(self.windowFla...
the_stack_v2_python_sparse
annotation/components/Dialog3DPlot.py
potpov/IAN_annotation_tool
train
12
19010bc22c79b4716d5467797d05bf2d7327b74e
[ "self.c = db.c\nself.connection = db.connection\nself.c.execute(\"CREATE TABLE IF NOT EXISTS 'payment_channel' (deposit_txid text unique, state text, deposit_tx text, payment_tx text, merchant_pubkey text, created_at timestamp, expires_at timestamp, amount integer, last_payment_amount integer)\")", "insert = 'INS...
<|body_start_0|> self.c = db.c self.connection = db.connection self.c.execute("CREATE TABLE IF NOT EXISTS 'payment_channel' (deposit_txid text unique, state text, deposit_tx text, payment_tx text, merchant_pubkey text, created_at timestamp, expires_at timestamp, amount integer, last_payment_amou...
SQLite3 binding for the payment channel model.
ChannelSQLite3
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ChannelSQLite3: """SQLite3 binding for the payment channel model.""" def __init__(self, db): """Instantiate SQLite3 for storing channel transaction data.""" <|body_0|> def create(self, deposit_tx, merch_pubkey, amount, expiration): """Create a payment channel ent...
stack_v2_sparse_classes_36k_train_011288
16,798
permissive
[ { "docstring": "Instantiate SQLite3 for storing channel transaction data.", "name": "__init__", "signature": "def __init__(self, db)" }, { "docstring": "Create a payment channel entry.", "name": "create", "signature": "def create(self, deposit_tx, merch_pubkey, amount, expiration)" }, ...
5
stack_v2_sparse_classes_30k_train_008538
Implement the Python class `ChannelSQLite3` described below. Class description: SQLite3 binding for the payment channel model. Method signatures and docstrings: - def __init__(self, db): Instantiate SQLite3 for storing channel transaction data. - def create(self, deposit_tx, merch_pubkey, amount, expiration): Create ...
Implement the Python class `ChannelSQLite3` described below. Class description: SQLite3 binding for the payment channel model. Method signatures and docstrings: - def __init__(self, db): Instantiate SQLite3 for storing channel transaction data. - def create(self, deposit_tx, merch_pubkey, amount, expiration): Create ...
a5e99fccf11ed75420775ae3e924c9ce94f2e86d
<|skeleton|> class ChannelSQLite3: """SQLite3 binding for the payment channel model.""" def __init__(self, db): """Instantiate SQLite3 for storing channel transaction data.""" <|body_0|> def create(self, deposit_tx, merch_pubkey, amount, expiration): """Create a payment channel ent...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ChannelSQLite3: """SQLite3 binding for the payment channel model.""" def __init__(self, db): """Instantiate SQLite3 for storing channel transaction data.""" self.c = db.c self.connection = db.connection self.c.execute("CREATE TABLE IF NOT EXISTS 'payment_channel' (deposit_...
the_stack_v2_python_sparse
two1/bitserv/models.py
shayanb/two1
train
4
fcf033ec2657dcd111d12ade654fc39b0b58c3c4
[ "self.ai_settings = ai_settings\nself.reset_stats()\nself.game_active = False\nself.read_high_score()", "self.ships_left = self.ai_settings.ship_limit\nself.score = 0\nself.level = 1", "self.high_score = 0\nfilename = 'D:\\\\learnCode\\\\pythonBook\\\\project1_alien_invasion\\\\high_score.txt'\ntry:\n with o...
<|body_start_0|> self.ai_settings = ai_settings self.reset_stats() self.game_active = False self.read_high_score() <|end_body_0|> <|body_start_1|> self.ships_left = self.ai_settings.ship_limit self.score = 0 self.level = 1 <|end_body_1|> <|body_start_2|> ...
跟踪游戏的统计信息
GameStats
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GameStats: """跟踪游戏的统计信息""" def __init__(self, ai_settings): """初始化统计信息""" <|body_0|> def reset_stats(self): """初始化在游戏运行期间可能变化的统计信息""" <|body_1|> def read_high_score(self): """读取最高分""" <|body_2|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_011289
992
no_license
[ { "docstring": "初始化统计信息", "name": "__init__", "signature": "def __init__(self, ai_settings)" }, { "docstring": "初始化在游戏运行期间可能变化的统计信息", "name": "reset_stats", "signature": "def reset_stats(self)" }, { "docstring": "读取最高分", "name": "read_high_score", "signature": "def read_h...
3
stack_v2_sparse_classes_30k_train_010556
Implement the Python class `GameStats` described below. Class description: 跟踪游戏的统计信息 Method signatures and docstrings: - def __init__(self, ai_settings): 初始化统计信息 - def reset_stats(self): 初始化在游戏运行期间可能变化的统计信息 - def read_high_score(self): 读取最高分
Implement the Python class `GameStats` described below. Class description: 跟踪游戏的统计信息 Method signatures and docstrings: - def __init__(self, ai_settings): 初始化统计信息 - def reset_stats(self): 初始化在游戏运行期间可能变化的统计信息 - def read_high_score(self): 读取最高分 <|skeleton|> class GameStats: """跟踪游戏的统计信息""" def __init__(self, a...
5c0b0577eb5dca48fa6c4cbce159302d43be0116
<|skeleton|> class GameStats: """跟踪游戏的统计信息""" def __init__(self, ai_settings): """初始化统计信息""" <|body_0|> def reset_stats(self): """初始化在游戏运行期间可能变化的统计信息""" <|body_1|> def read_high_score(self): """读取最高分""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GameStats: """跟踪游戏的统计信息""" def __init__(self, ai_settings): """初始化统计信息""" self.ai_settings = ai_settings self.reset_stats() self.game_active = False self.read_high_score() def reset_stats(self): """初始化在游戏运行期间可能变化的统计信息""" self.ships_left = self....
the_stack_v2_python_sparse
project1_alien_invasion/game_stats.py
JackKoLing/python_study_notes
train
0
6920f0585e92e6b82242fea7002d1d78d3c2c98c
[ "assert root is not None\ntail = root\nLC, RC = (root.left, root.right)\nroot.left, root.right = (None, None)\nif LC:\n thisTail = self.flattenHelper(LC)\n tail.right = LC\n tail = thisTail\nif RC:\n thisTail = self.flattenHelper(RC)\n tail.right = RC\n tail = thisTail\nreturn tail", "if not roo...
<|body_start_0|> assert root is not None tail = root LC, RC = (root.left, root.right) root.left, root.right = (None, None) if LC: thisTail = self.flattenHelper(LC) tail.right = LC tail = thisTail if RC: thisTail = self.flatt...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def flattenHelper(self, root): """return a the tail""" <|body_0|> def flatten(self, root): """:type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.""" <|body_1|> <|end_skeleton|> <|body_start_0|> assert ro...
stack_v2_sparse_classes_36k_train_011290
913
no_license
[ { "docstring": "return a the tail", "name": "flattenHelper", "signature": "def flattenHelper(self, root)" }, { "docstring": ":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.", "name": "flatten", "signature": "def flatten(self, root)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def flattenHelper(self, root): return a the tail - def flatten(self, root): :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def flattenHelper(self, root): return a the tail - def flatten(self, root): :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. <|skeleton|> ...
6e051eb554d9cf6f424f1e0a77f3072adf7f64c4
<|skeleton|> class Solution: def flattenHelper(self, root): """return a the tail""" <|body_0|> def flatten(self, root): """:type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def flattenHelper(self, root): """return a the tail""" assert root is not None tail = root LC, RC = (root.left, root.right) root.left, root.right = (None, None) if LC: thisTail = self.flattenHelper(LC) tail.right = LC ...
the_stack_v2_python_sparse
114. Flatten Binary Tree to Linked List.py
vincent-kangzhou/LeetCode-Python
train
0
7e211fd2c0414dcfea889002ba45d2d8c6c78b07
[ "ret_data = []\nenvironment_query = TestEnvironment.extend()\nname = self.get_argument('name', None)\nif name is not None:\n environment_query = environment_query.filter(TestEnvironment.name == name)\nhost = self.get_argument('router', None)\nif host is not None:\n environment_query = environment_query.filter...
<|body_start_0|> ret_data = [] environment_query = TestEnvironment.extend() name = self.get_argument('name', None) if name is not None: environment_query = environment_query.filter(TestEnvironment.name == name) host = self.get_argument('router', None) if host ...
TestEnvironmentHandler
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestEnvironmentHandler: async def get(self, *args, **kwargs): """获取测试环境列表数据""" <|body_0|> async def post(self, *args, **kwargs): """新增测试环境数据""" <|body_1|> <|end_skeleton|> <|body_start_0|> ret_data = [] environment_query = TestEnvironment.ex...
stack_v2_sparse_classes_36k_train_011291
17,374
permissive
[ { "docstring": "获取测试环境列表数据", "name": "get", "signature": "async def get(self, *args, **kwargs)" }, { "docstring": "新增测试环境数据", "name": "post", "signature": "async def post(self, *args, **kwargs)" } ]
2
stack_v2_sparse_classes_30k_train_012965
Implement the Python class `TestEnvironmentHandler` described below. Class description: Implement the TestEnvironmentHandler class. Method signatures and docstrings: - async def get(self, *args, **kwargs): 获取测试环境列表数据 - async def post(self, *args, **kwargs): 新增测试环境数据
Implement the Python class `TestEnvironmentHandler` described below. Class description: Implement the TestEnvironmentHandler class. Method signatures and docstrings: - async def get(self, *args, **kwargs): 获取测试环境列表数据 - async def post(self, *args, **kwargs): 新增测试环境数据 <|skeleton|> class TestEnvironmentHandler: as...
dc9b4c55f0b3ace180c30b7f080eb5d88bb38fdb
<|skeleton|> class TestEnvironmentHandler: async def get(self, *args, **kwargs): """获取测试环境列表数据""" <|body_0|> async def post(self, *args, **kwargs): """新增测试环境数据""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestEnvironmentHandler: async def get(self, *args, **kwargs): """获取测试环境列表数据""" ret_data = [] environment_query = TestEnvironment.extend() name = self.get_argument('name', None) if name is not None: environment_query = environment_query.filter(TestEnvironment...
the_stack_v2_python_sparse
apps/project/handlers.py
xiaoxiaolulu/MagicTestPlatform
train
5
593f0550e4ce258574a503b832db70087c9183dd
[ "if d_model % n_heads != 0:\n raise ValueError(f'the number of heads ({n_heads}) does not divide the model depth({d_model})')\nsuper(MultiHeadAttention, self).__init__()\nself.n_heads = n_heads\nself.d_model = d_model\nself.d_head = d_model // self.n_heads\nself.Wq = kl.Dense(d_model)\nself.Wk = kl.Dense(d_model...
<|body_start_0|> if d_model % n_heads != 0: raise ValueError(f'the number of heads ({n_heads}) does not divide the model depth({d_model})') super(MultiHeadAttention, self).__init__() self.n_heads = n_heads self.d_model = d_model self.d_head = d_model // self.n_heads ...
MultiHeadAttention
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiHeadAttention: def __init__(self, d_model: int, n_heads: int): """Parameters ---------- d_model : int Depth of the model. n_heads : int Number of attention heads in the model. Raises ------ ValueError n_heads does not divide d_model.""" <|body_0|> def _split_to_heads(se...
stack_v2_sparse_classes_36k_train_011292
6,463
permissive
[ { "docstring": "Parameters ---------- d_model : int Depth of the model. n_heads : int Number of attention heads in the model. Raises ------ ValueError n_heads does not divide d_model.", "name": "__init__", "signature": "def __init__(self, d_model: int, n_heads: int)" }, { "docstring": "Splits th...
4
stack_v2_sparse_classes_30k_train_012184
Implement the Python class `MultiHeadAttention` described below. Class description: Implement the MultiHeadAttention class. Method signatures and docstrings: - def __init__(self, d_model: int, n_heads: int): Parameters ---------- d_model : int Depth of the model. n_heads : int Number of attention heads in the model. ...
Implement the Python class `MultiHeadAttention` described below. Class description: Implement the MultiHeadAttention class. Method signatures and docstrings: - def __init__(self, d_model: int, n_heads: int): Parameters ---------- d_model : int Depth of the model. n_heads : int Number of attention heads in the model. ...
4b6d685ce019d847695e2d6ea5a223c5e543d0ed
<|skeleton|> class MultiHeadAttention: def __init__(self, d_model: int, n_heads: int): """Parameters ---------- d_model : int Depth of the model. n_heads : int Number of attention heads in the model. Raises ------ ValueError n_heads does not divide d_model.""" <|body_0|> def _split_to_heads(se...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultiHeadAttention: def __init__(self, d_model: int, n_heads: int): """Parameters ---------- d_model : int Depth of the model. n_heads : int Number of attention heads in the model. Raises ------ ValueError n_heads does not divide d_model.""" if d_model % n_heads != 0: raise ValueEr...
the_stack_v2_python_sparse
transformer/architecture/attention.py
elephann/TransfoTF
train
0
29f3c7555eb42af3ad24edb17ec73f6dabc4ce1f
[ "__values = cls.split_lookup_complex_value(value, maxsplit=3)\n__len_values = len(__values)\nif __len_values < 2:\n return {}\nparams = {'_geo_distance': {field: {'lat': __values[0], 'lon': __values[1]}}}\nif __len_values > 2:\n params['_geo_distance']['unit'] = __values[2]\nelse:\n params['_geo_distance']...
<|body_start_0|> __values = cls.split_lookup_complex_value(value, maxsplit=3) __len_values = len(__values) if __len_values < 2: return {} params = {'_geo_distance': {field: {'lat': __values[0], 'lon': __values[1]}}} if __len_values > 2: params['_geo_distan...
Geo-spatial ordering filter backend for Elasticsearch. Example: >>> from django_elasticsearch_dsl_drf.filter_backends import ( >>> GeoSpatialOrderingFilterBackend >>> ) >>> from django_elasticsearch_dsl_drf.viewsets import ( >>> BaseDocumentViewSet, >>> ) >>> >>> # Local article document definition >>> from .documents ...
GeoSpatialOrderingFilterBackend
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GeoSpatialOrderingFilterBackend: """Geo-spatial ordering filter backend for Elasticsearch. Example: >>> from django_elasticsearch_dsl_drf.filter_backends import ( >>> GeoSpatialOrderingFilterBackend >>> ) >>> from django_elasticsearch_dsl_drf.viewsets import ( >>> BaseDocumentViewSet, >>> ) >>> >...
stack_v2_sparse_classes_36k_train_011293
5,889
permissive
[ { "docstring": "Get params for `geo_distance` ordering. Example: /api/articles/?ordering=-location__45.3214__-34.3421__km__planes :param value: :param field: :type value: str :type field: :return: Params to be used in `geo_distance` query. :rtype: dict", "name": "get_geo_distance_params", "signature": "...
4
stack_v2_sparse_classes_30k_train_001124
Implement the Python class `GeoSpatialOrderingFilterBackend` described below. Class description: Geo-spatial ordering filter backend for Elasticsearch. Example: >>> from django_elasticsearch_dsl_drf.filter_backends import ( >>> GeoSpatialOrderingFilterBackend >>> ) >>> from django_elasticsearch_dsl_drf.viewsets import...
Implement the Python class `GeoSpatialOrderingFilterBackend` described below. Class description: Geo-spatial ordering filter backend for Elasticsearch. Example: >>> from django_elasticsearch_dsl_drf.filter_backends import ( >>> GeoSpatialOrderingFilterBackend >>> ) >>> from django_elasticsearch_dsl_drf.viewsets import...
c1e0692d42ee4935a7e1ae7fec1913ddab3054f2
<|skeleton|> class GeoSpatialOrderingFilterBackend: """Geo-spatial ordering filter backend for Elasticsearch. Example: >>> from django_elasticsearch_dsl_drf.filter_backends import ( >>> GeoSpatialOrderingFilterBackend >>> ) >>> from django_elasticsearch_dsl_drf.viewsets import ( >>> BaseDocumentViewSet, >>> ) >>> >...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GeoSpatialOrderingFilterBackend: """Geo-spatial ordering filter backend for Elasticsearch. Example: >>> from django_elasticsearch_dsl_drf.filter_backends import ( >>> GeoSpatialOrderingFilterBackend >>> ) >>> from django_elasticsearch_dsl_drf.viewsets import ( >>> BaseDocumentViewSet, >>> ) >>> >>> # Local ar...
the_stack_v2_python_sparse
lib/python3.8/site-packages/django_elasticsearch_dsl_drf/filter_backends/ordering/geo_spatial.py
ervinpepic/Kodecta_media_catalog
train
0
4cb57cab5178e80faf3156cd7422bc0a309559fe
[ "self.lmbda = lmbda\nself.phi = phi\nself.flagSTD = flagSTD\nself.eps = eps", "if lmbda == None:\n lmbda = self.lmbda\nif phi == None:\n phi = self.phi\nif flagSTD == None:\n flagSTD = self.flagSTD\nif flagSTD > 0:\n self.datascalerX = DataScaler(X)\n self.datascalerT = DataScaler(T)\n X = self....
<|body_start_0|> self.lmbda = lmbda self.phi = phi self.flagSTD = flagSTD self.eps = eps <|end_body_0|> <|body_start_1|> if lmbda == None: lmbda = self.lmbda if phi == None: phi = self.phi if flagSTD == None: flagSTD = self.fla...
Class for Least Squares (or Maximum Likelihood) Linear Regressifier with sum of squares regularization
LSRRegressifier
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LSRRegressifier: """Class for Least Squares (or Maximum Likelihood) Linear Regressifier with sum of squares regularization""" def __init__(self, lmbda=0, phi=lambda x: phi_polynomial(x, 1), flagSTD=0, eps=1e-06): """Constructor of class LSRegressifier :param lmbda: Regularization coe...
stack_v2_sparse_classes_36k_train_011294
21,971
no_license
[ { "docstring": "Constructor of class LSRegressifier :param lmbda: Regularization coefficient lambda :param phi: Basis-functions used by the linear model (default linear polynomial) :param flagSTD: If >0 then standardize data X and target values T (to mean 0 and s.d. 1) :param eps: maximal residual value to tole...
3
stack_v2_sparse_classes_30k_train_014602
Implement the Python class `LSRRegressifier` described below. Class description: Class for Least Squares (or Maximum Likelihood) Linear Regressifier with sum of squares regularization Method signatures and docstrings: - def __init__(self, lmbda=0, phi=lambda x: phi_polynomial(x, 1), flagSTD=0, eps=1e-06): Constructor...
Implement the Python class `LSRRegressifier` described below. Class description: Class for Least Squares (or Maximum Likelihood) Linear Regressifier with sum of squares regularization Method signatures and docstrings: - def __init__(self, lmbda=0, phi=lambda x: phi_polynomial(x, 1), flagSTD=0, eps=1e-06): Constructor...
de2ba4e2afdad7e2e1ba0c145edbd341f8555802
<|skeleton|> class LSRRegressifier: """Class for Least Squares (or Maximum Likelihood) Linear Regressifier with sum of squares regularization""" def __init__(self, lmbda=0, phi=lambda x: phi_polynomial(x, 1), flagSTD=0, eps=1e-06): """Constructor of class LSRegressifier :param lmbda: Regularization coe...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LSRRegressifier: """Class for Least Squares (or Maximum Likelihood) Linear Regressifier with sum of squares regularization""" def __init__(self, lmbda=0, phi=lambda x: phi_polynomial(x, 1), flagSTD=0, eps=1e-06): """Constructor of class LSRegressifier :param lmbda: Regularization coefficient lamb...
the_stack_v2_python_sparse
versuch2/src/V2A2_Regression.py
xsjad0/ias-neuronale-netze
train
1
6da28ddecb97c22ea8150fb4e61cb7c14162ff4b
[ "for k, v in self.known_values.items():\n logging.info('Checking {}: {}'.format(k, v))\n self.assertTrue(collection_in_collection.check_config(self.config, k, v))", "for k, v in self.incorrect_values.items():\n logging.info('Checking {}: {}'.format(k, v))\n self.assertFalse(collection_in_collection.ch...
<|body_start_0|> for k, v in self.known_values.items(): logging.info('Checking {}: {}'.format(k, v)) self.assertTrue(collection_in_collection.check_config(self.config, k, v)) <|end_body_0|> <|body_start_1|> for k, v in self.incorrect_values.items(): logging.info('Che...
test_collection
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class test_collection: def test_check_config_true(self): """If value is found have to return True""" <|body_0|> def test_check_config_false(self): """If value is not found, return False""" <|body_1|> def test_set_value(self): """Check updated config"""...
stack_v2_sparse_classes_36k_train_011295
2,163
no_license
[ { "docstring": "If value is found have to return True", "name": "test_check_config_true", "signature": "def test_check_config_true(self)" }, { "docstring": "If value is not found, return False", "name": "test_check_config_false", "signature": "def test_check_config_false(self)" }, { ...
3
null
Implement the Python class `test_collection` described below. Class description: Implement the test_collection class. Method signatures and docstrings: - def test_check_config_true(self): If value is found have to return True - def test_check_config_false(self): If value is not found, return False - def test_set_valu...
Implement the Python class `test_collection` described below. Class description: Implement the test_collection class. Method signatures and docstrings: - def test_check_config_true(self): If value is found have to return True - def test_check_config_false(self): If value is not found, return False - def test_set_valu...
f2a29acd2a65679753fc73145b7597b66ed4bee3
<|skeleton|> class test_collection: def test_check_config_true(self): """If value is found have to return True""" <|body_0|> def test_check_config_false(self): """If value is not found, return False""" <|body_1|> def test_set_value(self): """Check updated config"""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class test_collection: def test_check_config_true(self): """If value is found have to return True""" for k, v in self.known_values.items(): logging.info('Checking {}: {}'.format(k, v)) self.assertTrue(collection_in_collection.check_config(self.config, k, v)) def test_che...
the_stack_v2_python_sparse
CodeAbby/collection_in_collection/collection_test.py
Brenner87/Projects
train
0
183809b414cfd2110abc596c3ea1395b1820cc11
[ "assert len(img_shape) == 3, 'Three values are needed for img_shape in this class'\nassert img_shape[0] % 2 == img_shape[1] % 2, 'Height and Width sizes' + 'in img_shape should be odd.'\nif len(self.tr_masks) > 0:\n z = img_shape[2]\n z_rad = int(z / 2)\n self.train_n_slices = [self.tr_masks[i].shape[2] - ...
<|body_start_0|> assert len(img_shape) == 3, 'Three values are needed for img_shape in this class' assert img_shape[0] % 2 == img_shape[1] % 2, 'Height and Width sizes' + 'in img_shape should be odd.' if len(self.tr_masks) > 0: z = img_shape[2] z_rad = int(z / 2) ...
D3
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class D3: def create_train_valid_gens(self, batch_size, img_shape, valid_mode='random', n_labeled_train=None): """Creating sample generator from training and validation data sets. It is assumed that images are loaed through load_images(). NOTE: Although, `img_shape` has the format `[h,w,z,m]`,...
stack_v2_sparse_classes_36k_train_011296
18,043
no_license
[ { "docstring": "Creating sample generator from training and validation data sets. It is assumed that images are loaed through load_images(). NOTE: Although, `img_shape` has the format `[h,w,z,m]`, where `h=height`, `w=width`, `z=depth` and `m=#modelities`, when it is used with a CNN class, the generators should...
2
stack_v2_sparse_classes_30k_train_003567
Implement the Python class `D3` described below. Class description: Implement the D3 class. Method signatures and docstrings: - def create_train_valid_gens(self, batch_size, img_shape, valid_mode='random', n_labeled_train=None): Creating sample generator from training and validation data sets. It is assumed that imag...
Implement the Python class `D3` described below. Class description: Implement the D3 class. Method signatures and docstrings: - def create_train_valid_gens(self, batch_size, img_shape, valid_mode='random', n_labeled_train=None): Creating sample generator from training and validation data sets. It is assumed that imag...
6eb4a7f1b67d732a8d7b25991ce5145e7e6da0c6
<|skeleton|> class D3: def create_train_valid_gens(self, batch_size, img_shape, valid_mode='random', n_labeled_train=None): """Creating sample generator from training and validation data sets. It is assumed that images are loaed through load_images(). NOTE: Although, `img_shape` has the format `[h,w,z,m]`,...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class D3: def create_train_valid_gens(self, batch_size, img_shape, valid_mode='random', n_labeled_train=None): """Creating sample generator from training and validation data sets. It is assumed that images are loaed through load_images(). NOTE: Although, `img_shape` has the format `[h,w,z,m]`, where `h=heig...
the_stack_v2_python_sparse
datasets/data_holders.py
jsourati/nn-active-learning
train
2
45c282e5451e9b9c2e4ffd94629784853dfa1c92
[ "log.debug('GET request from user %s for engineering day %s' % (request.user, eday_id))\nproj = Project.objects.get(project_number=project_number)\neday = EngineeringDay.objects.get(id=eday_id)\nif not check_project_read_acl(proj, request.user):\n log.debug('Refusing GET request for project %s from user %s' % (p...
<|body_start_0|> log.debug('GET request from user %s for engineering day %s' % (request.user, eday_id)) proj = Project.objects.get(project_number=project_number) eday = EngineeringDay.objects.get(id=eday_id) if not check_project_read_acl(proj, request.user): log.debug('Refusi...
URI: /api/engineeringday/%project_number%/%eday_id%/ VERBS: GET, DELETE Handles a single instance of EngineeringDay
EngineeringDayResourceHandler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EngineeringDayResourceHandler: """URI: /api/engineeringday/%project_number%/%eday_id%/ VERBS: GET, DELETE Handles a single instance of EngineeringDay""" def read(self, request, project_number, eday_id): """View an Engineering Day""" <|body_0|> def delete(self, request, p...
stack_v2_sparse_classes_36k_train_011297
19,350
no_license
[ { "docstring": "View an Engineering Day", "name": "read", "signature": "def read(self, request, project_number, eday_id)" }, { "docstring": "Disassociate the day from the project, not actually delete it", "name": "delete", "signature": "def delete(self, request, project_number, eday_id)"...
2
stack_v2_sparse_classes_30k_train_008681
Implement the Python class `EngineeringDayResourceHandler` described below. Class description: URI: /api/engineeringday/%project_number%/%eday_id%/ VERBS: GET, DELETE Handles a single instance of EngineeringDay Method signatures and docstrings: - def read(self, request, project_number, eday_id): View an Engineering D...
Implement the Python class `EngineeringDayResourceHandler` described below. Class description: URI: /api/engineeringday/%project_number%/%eday_id%/ VERBS: GET, DELETE Handles a single instance of EngineeringDay Method signatures and docstrings: - def read(self, request, project_number, eday_id): View an Engineering D...
106a96307612318fb66246486e7226069e5508ac
<|skeleton|> class EngineeringDayResourceHandler: """URI: /api/engineeringday/%project_number%/%eday_id%/ VERBS: GET, DELETE Handles a single instance of EngineeringDay""" def read(self, request, project_number, eday_id): """View an Engineering Day""" <|body_0|> def delete(self, request, p...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EngineeringDayResourceHandler: """URI: /api/engineeringday/%project_number%/%eday_id%/ VERBS: GET, DELETE Handles a single instance of EngineeringDay""" def read(self, request, project_number, eday_id): """View an Engineering Day""" log.debug('GET request from user %s for engineering day ...
the_stack_v2_python_sparse
branches/rest-api-branch/django-project-management/wbs/api_views.py
NhaTrang/django-project-management
train
0
dc7c4413f1d548a1f9bc37b8d1810bf602d3d85e
[ "res = [0]\nfor i in xrange(1, num + 1):\n res.append((i & 1) + res[i >> 1])\nreturn res", "s = [0]\nwhile len(s) <= num:\n s.extend(map(lambda x: x + 1, s))\nreturn s[:num + 1]" ]
<|body_start_0|> res = [0] for i in xrange(1, num + 1): res.append((i & 1) + res[i >> 1]) return res <|end_body_0|> <|body_start_1|> s = [0] while len(s) <= num: s.extend(map(lambda x: x + 1, s)) return s[:num + 1] <|end_body_1|>
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def countBits(self, num): """:type num: int :rtype: List[int]""" <|body_0|> def countBits2(self, num): """:type num: int :rtype: List[int]""" <|body_1|> <|end_skeleton|> <|body_start_0|> res = [0] for i in xrange(1, num + 1): ...
stack_v2_sparse_classes_36k_train_011298
572
permissive
[ { "docstring": ":type num: int :rtype: List[int]", "name": "countBits", "signature": "def countBits(self, num)" }, { "docstring": ":type num: int :rtype: List[int]", "name": "countBits2", "signature": "def countBits2(self, num)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countBits(self, num): :type num: int :rtype: List[int] - def countBits2(self, num): :type num: int :rtype: List[int]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countBits(self, num): :type num: int :rtype: List[int] - def countBits2(self, num): :type num: int :rtype: List[int] <|skeleton|> class Solution: def countBits(self, nu...
4dc4e6642dc92f1983c13564cc0fd99917cab358
<|skeleton|> class Solution: def countBits(self, num): """:type num: int :rtype: List[int]""" <|body_0|> def countBits2(self, num): """:type num: int :rtype: List[int]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def countBits(self, num): """:type num: int :rtype: List[int]""" res = [0] for i in xrange(1, num + 1): res.append((i & 1) + res[i >> 1]) return res def countBits2(self, num): """:type num: int :rtype: List[int]""" s = [0] whil...
the_stack_v2_python_sparse
Python/counting-bits.py
kamyu104/LeetCode-Solutions
train
4,549
e8a821bc55287e5e1bffb38bebda5515c1608a55
[ "self.r_speckle = 4\nself.window_shape = (self.r_speckle * 2 + 1, self.r_speckle * 2 + 1)\np_masked = 0.3\nself.max_masked_values = self.window_shape[0] * self.window_shape[1] * p_masked\nself.r_interp = 2", "mask_windows = neighbourhood_tools.pad_and_roll(cube.data.mask, self.window_shape, mode='constant', const...
<|body_start_0|> self.r_speckle = 4 self.window_shape = (self.r_speckle * 2 + 1, self.r_speckle * 2 + 1) p_masked = 0.3 self.max_masked_values = self.window_shape[0] * self.window_shape[1] * p_masked self.r_interp = 2 <|end_body_0|> <|body_start_1|> mask_windows = neighb...
Fill in small "no data" regions in the radar composite by interpolating in log rainrate space. The log-linear transformation does not preserve non-zero rainrates of less than 0.001 mm/h. Since the radar composite encodes trace rain rates with a value of 0.03 mm/h, this should not have any effect on "real" data from the...
FillRadarHoles
[ "BSD-3-Clause", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FillRadarHoles: """Fill in small "no data" regions in the radar composite by interpolating in log rainrate space. The log-linear transformation does not preserve non-zero rainrates of less than 0.001 mm/h. Since the radar composite encodes trace rain rates with a value of 0.03 mm/h, this should n...
stack_v2_sparse_classes_36k_train_011299
16,064
permissive
[ { "docstring": "Initialise parameters of interpolation The constants defining neighbourhood size and proportion of neighbouring masked pixels for speckle identification have been empirically tuned for UK radar data. As configured, this method will flag \"holes\" of up to 24 pixels in size (30% of a 9 x 9 neighb...
3
stack_v2_sparse_classes_30k_train_016056
Implement the Python class `FillRadarHoles` described below. Class description: Fill in small "no data" regions in the radar composite by interpolating in log rainrate space. The log-linear transformation does not preserve non-zero rainrates of less than 0.001 mm/h. Since the radar composite encodes trace rain rates w...
Implement the Python class `FillRadarHoles` described below. Class description: Fill in small "no data" regions in the radar composite by interpolating in log rainrate space. The log-linear transformation does not preserve non-zero rainrates of less than 0.001 mm/h. Since the radar composite encodes trace rain rates w...
cd2c9019944345df1e703bf8f625db537ad9f559
<|skeleton|> class FillRadarHoles: """Fill in small "no data" regions in the radar composite by interpolating in log rainrate space. The log-linear transformation does not preserve non-zero rainrates of less than 0.001 mm/h. Since the radar composite encodes trace rain rates with a value of 0.03 mm/h, this should n...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FillRadarHoles: """Fill in small "no data" regions in the radar composite by interpolating in log rainrate space. The log-linear transformation does not preserve non-zero rainrates of less than 0.001 mm/h. Since the radar composite encodes trace rain rates with a value of 0.03 mm/h, this should not have any e...
the_stack_v2_python_sparse
improver/nowcasting/utilities.py
metoppv/improver
train
101