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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f5e6b47ccceaaa36d09ebf7b000782ecdff8399d | [
"binning = '1,1' if hdu is None else f\"{hdu[0].header['CCDXBIN']},{hdu[0].header['CCDYBIN']}\"\ndetector_dict = dict(binning=binning, det=1, dataext=0, specaxis=0, specflip=True, spatflip=False, platescale=0.12, darkcurr=0.5, saturation=65535.0, nonlinear=0.99, mincounts=-10000000000.0, numamplifiers=4, gain=np.at... | <|body_start_0|>
binning = '1,1' if hdu is None else f"{hdu[0].header['CCDXBIN']},{hdu[0].header['CCDYBIN']}"
detector_dict = dict(binning=binning, det=1, dataext=0, specaxis=0, specflip=True, spatflip=False, platescale=0.12, darkcurr=0.5, saturation=65535.0, nonlinear=0.99, mincounts=-10000000000.0, nu... | Child to handle LBT/MODS1R specific code | LBTMODS1BSpectrograph | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LBTMODS1BSpectrograph:
"""Child to handle LBT/MODS1R specific code"""
def get_detector_par(self, det, hdu=None):
"""Return metadata for the selected detector. Args: det (:obj:`int`): 1-indexed detector number. hdu (`astropy.io.fits.HDUList`_, optional): The open fits file with the ra... | stack_v2_sparse_classes_36k_train_013800 | 35,372 | permissive | [
{
"docstring": "Return metadata for the selected detector. Args: det (:obj:`int`): 1-indexed detector number. hdu (`astropy.io.fits.HDUList`_, optional): The open fits file with the raw image of interest. If not provided, frame-dependent parameters are set to a default. Returns: :class:`~pypeit.images.detector_... | 4 | stack_v2_sparse_classes_30k_train_005835 | Implement the Python class `LBTMODS1BSpectrograph` described below.
Class description:
Child to handle LBT/MODS1R specific code
Method signatures and docstrings:
- def get_detector_par(self, det, hdu=None): Return metadata for the selected detector. Args: det (:obj:`int`): 1-indexed detector number. hdu (`astropy.io.... | Implement the Python class `LBTMODS1BSpectrograph` described below.
Class description:
Child to handle LBT/MODS1R specific code
Method signatures and docstrings:
- def get_detector_par(self, det, hdu=None): Return metadata for the selected detector. Args: det (:obj:`int`): 1-indexed detector number. hdu (`astropy.io.... | 0d2e2196afc6904050b1af4d572f5c643bb07e38 | <|skeleton|>
class LBTMODS1BSpectrograph:
"""Child to handle LBT/MODS1R specific code"""
def get_detector_par(self, det, hdu=None):
"""Return metadata for the selected detector. Args: det (:obj:`int`): 1-indexed detector number. hdu (`astropy.io.fits.HDUList`_, optional): The open fits file with the ra... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LBTMODS1BSpectrograph:
"""Child to handle LBT/MODS1R specific code"""
def get_detector_par(self, det, hdu=None):
"""Return metadata for the selected detector. Args: det (:obj:`int`): 1-indexed detector number. hdu (`astropy.io.fits.HDUList`_, optional): The open fits file with the raw image of in... | the_stack_v2_python_sparse | pypeit/spectrographs/lbt_mods.py | pypeit/PypeIt | train | 136 |
472186c9bce40eb4289aa161f8a94a7e4958ec6b | [
"if not agave_client and (not user):\n raise TypeError(\"Must specify one of 'agave_client' or 'user'.\")\nself.user = user\nself._ac = agave_client\nif not self._ac and self.user:\n self._ac = self.user.agave_oauth.client",
"metas = self._ac.meta.listMetadata(q=json.dumps({'value.projectId': project_id}))\... | <|body_start_0|>
if not agave_client and (not user):
raise TypeError("Must specify one of 'agave_client' or 'user'.")
self.user = user
self._ac = agave_client
if not self._ac and self.user:
self._ac = self.user.agave_oauth.client
<|end_body_0|>
<|body_start_1|>
... | Base projects manager. | ProjectsManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectsManager:
"""Base projects manager."""
def __init__(self, agave_client=None, user=None):
"""Initialize base projects manager. Can be initialized with a custom agave client or with a Django user object. :param agave_client: Cusotm agave client :param user: Django user object.""... | stack_v2_sparse_classes_36k_train_013801 | 2,547 | no_license | [
{
"docstring": "Initialize base projects manager. Can be initialized with a custom agave client or with a Django user object. :param agave_client: Cusotm agave client :param user: Django user object.",
"name": "__init__",
"signature": "def __init__(self, agave_client=None, user=None)"
},
{
"docs... | 3 | stack_v2_sparse_classes_30k_train_000760 | Implement the Python class `ProjectsManager` described below.
Class description:
Base projects manager.
Method signatures and docstrings:
- def __init__(self, agave_client=None, user=None): Initialize base projects manager. Can be initialized with a custom agave client or with a Django user object. :param agave_clien... | Implement the Python class `ProjectsManager` described below.
Class description:
Base projects manager.
Method signatures and docstrings:
- def __init__(self, agave_client=None, user=None): Initialize base projects manager. Can be initialized with a custom agave client or with a Django user object. :param agave_clien... | 040e0d88eac6037703a6128d6f4644b5a99ea11b | <|skeleton|>
class ProjectsManager:
"""Base projects manager."""
def __init__(self, agave_client=None, user=None):
"""Initialize base projects manager. Can be initialized with a custom agave client or with a Django user object. :param agave_client: Cusotm agave client :param user: Django user object.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectsManager:
"""Base projects manager."""
def __init__(self, agave_client=None, user=None):
"""Initialize base projects manager. Can be initialized with a custom agave client or with a Django user object. :param agave_client: Cusotm agave client :param user: Django user object."""
if ... | the_stack_v2_python_sparse | designsafe/apps/projects/managers/base.py | DesignSafe-CI/portal | train | 12 |
bcfb1a77b9b4f59df2796eeb5e0842c7f399f6b5 | [
"arr = collections.Counter(nums)\naa = sorted(arr.items(), key=lambda item: item[0])\npre = 0\ndic = collections.defaultdict(lambda: 0)\nfor i in range(len(aa)):\n k, v = aa[i]\n dic[k] = pre\n pre += v\nres = []\nfor num in nums:\n res.append(dic[num])\nreturn res",
"arr = [0] * 101\nfor num in nums:... | <|body_start_0|>
arr = collections.Counter(nums)
aa = sorted(arr.items(), key=lambda item: item[0])
pre = 0
dic = collections.defaultdict(lambda: 0)
for i in range(len(aa)):
k, v = aa[i]
dic[k] = pre
pre += v
res = []
for num in... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def smallerNumbersThanCurrent1(self, nums: List[int]) -> List[int]:
"""思路:排序+前缀和+哈希 时间复杂度:O(NlogN)"""
<|body_0|>
def smallerNumbersThanCurrent2(self, nums: List[int]) -> List[int]:
"""思路:桶排序 1、由于样本数据不大,且是整数,可以采用桶排序 2、对应值的下标为小于其值的个数"""
<|body_1|>
<|... | stack_v2_sparse_classes_36k_train_013802 | 2,319 | no_license | [
{
"docstring": "思路:排序+前缀和+哈希 时间复杂度:O(NlogN)",
"name": "smallerNumbersThanCurrent1",
"signature": "def smallerNumbersThanCurrent1(self, nums: List[int]) -> List[int]"
},
{
"docstring": "思路:桶排序 1、由于样本数据不大,且是整数,可以采用桶排序 2、对应值的下标为小于其值的个数",
"name": "smallerNumbersThanCurrent2",
"signature": "d... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def smallerNumbersThanCurrent1(self, nums: List[int]) -> List[int]: 思路:排序+前缀和+哈希 时间复杂度:O(NlogN)
- def smallerNumbersThanCurrent2(self, nums: List[int]) -> List[int]: 思路:桶排序 1、由于样... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def smallerNumbersThanCurrent1(self, nums: List[int]) -> List[int]: 思路:排序+前缀和+哈希 时间复杂度:O(NlogN)
- def smallerNumbersThanCurrent2(self, nums: List[int]) -> List[int]: 思路:桶排序 1、由于样... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def smallerNumbersThanCurrent1(self, nums: List[int]) -> List[int]:
"""思路:排序+前缀和+哈希 时间复杂度:O(NlogN)"""
<|body_0|>
def smallerNumbersThanCurrent2(self, nums: List[int]) -> List[int]:
"""思路:桶排序 1、由于样本数据不大,且是整数,可以采用桶排序 2、对应值的下标为小于其值的个数"""
<|body_1|>
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def smallerNumbersThanCurrent1(self, nums: List[int]) -> List[int]:
"""思路:排序+前缀和+哈希 时间复杂度:O(NlogN)"""
arr = collections.Counter(nums)
aa = sorted(arr.items(), key=lambda item: item[0])
pre = 0
dic = collections.defaultdict(lambda: 0)
for i in range(len... | the_stack_v2_python_sparse | LeetCode/排序算法(sort)/1365. 有多少小于当前数字的数字.py | yiming1012/MyLeetCode | train | 2 | |
0504396c672adf8c76f0899828d9d03eab5c282d | [
"food_dict = {}\nfor food in orm.Food.objects.all():\n con = Consumption()\n con.in_event = Event(food.in_event.id)\n con.order = food.order\n con.quantity = food.quantity\n if food.name not in food_dict:\n en = Energy()\n en.name = food.name\n en.kcal = food.kcal\n en.kca... | <|body_start_0|>
food_dict = {}
for food in orm.Food.objects.all():
con = Consumption()
con.in_event = Event(food.in_event.id)
con.order = food.order
con.quantity = food.quantity
if food.name not in food_dict:
en = Energy()
... | Migration | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Migration:
def forwards(self, orm):
"""Write your forwards migration here"""
<|body_0|>
def backwards(self, orm):
"""Write your backwards migration here"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
food_dict = {}
for food in orm.Food.obje... | stack_v2_sparse_classes_36k_train_013803 | 3,153 | permissive | [
{
"docstring": "Write your forwards migration here",
"name": "forwards",
"signature": "def forwards(self, orm)"
},
{
"docstring": "Write your backwards migration here",
"name": "backwards",
"signature": "def backwards(self, orm)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000779 | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(self, orm): Write your forwards migration here
- def backwards(self, orm): Write your backwards migration here | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(self, orm): Write your forwards migration here
- def backwards(self, orm): Write your backwards migration here
<|skeleton|>
class Migration:
def forwards(sel... | af535fda8e113e9dcdac31216852e35a01d3b950 | <|skeleton|>
class Migration:
def forwards(self, orm):
"""Write your forwards migration here"""
<|body_0|>
def backwards(self, orm):
"""Write your backwards migration here"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Migration:
def forwards(self, orm):
"""Write your forwards migration here"""
food_dict = {}
for food in orm.Food.objects.all():
con = Consumption()
con.in_event = Event(food.in_event.id)
con.order = food.order
con.quantity = food.quantity... | the_stack_v2_python_sparse | kcal/migrations/0003_load_energy_model.py | ftrain/django-ftrain | train | 2 | |
33520546e08f4c4dc928d33015c257ecdab23ba1 | [
"if not nums:\n return []\nresults = []\nnums.sort()\nfor i in range(len(nums) - 3):\n if i > 0 and nums[i] == nums[i - 1]:\n continue\n threeSum = self.threeSum(nums, i + 1, target - nums[i])\n results += [[nums[i]] + t for t in threeSum]\nreturn results",
"if not nums or startInd >= len(nums)... | <|body_start_0|>
if not nums:
return []
results = []
nums.sort()
for i in range(len(nums) - 3):
if i > 0 and nums[i] == nums[i - 1]:
continue
threeSum = self.threeSum(nums, i + 1, target - nums[i])
results += [[nums[i]] + t ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def fourSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]]"""
<|body_0|>
def threeSum(self, nums, startInd, target):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_36k_train_013804 | 1,610 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[List[int]]",
"name": "fourSum",
"signature": "def fourSum(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum",
"signature": "def threeSum(self, nums, startInd, targ... | 2 | stack_v2_sparse_classes_30k_train_006910 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fourSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[List[int]]
- def threeSum(self, nums, startInd, target): :type nums: List[int] :rtype: List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fourSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[List[int]]
- def threeSum(self, nums, startInd, target): :type nums: List[int] :rtype: List[... | e2837f3d6c23f012148a2d1f9d0ef6d34d4e6912 | <|skeleton|>
class Solution:
def fourSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]]"""
<|body_0|>
def threeSum(self, nums, startInd, target):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def fourSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]]"""
if not nums:
return []
results = []
nums.sort()
for i in range(len(nums) - 3):
if i > 0 and nums[i] == nums[i - 1]:
c... | the_stack_v2_python_sparse | TwoPointers/4sum.py | wttttt-wang/leetcode_withTopics | train | 0 | |
e9062bd10746abe29fd4cb983724687550ae9df3 | [
"super(MDNRNN, self).__init__()\nself.inpt_size = z_dim + action_dim\nself.hidden_size = hidden_size\nself.n_mixture = n_mixture\nself.z_dim = z_dim\nself.rnn = nn.LSTM(input_size=self.inpt_size, hidden_size=hidden_size, batch_first=True)\nself.mdn = nn.Linear(hidden_size, n_mixture * z_dim * 2 + n_mixture)\nself.t... | <|body_start_0|>
super(MDNRNN, self).__init__()
self.inpt_size = z_dim + action_dim
self.hidden_size = hidden_size
self.n_mixture = n_mixture
self.z_dim = z_dim
self.rnn = nn.LSTM(input_size=self.inpt_size, hidden_size=hidden_size, batch_first=True)
self.mdn = nn.... | MDNRNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MDNRNN:
def __init__(self, z_dim=32, action_dim=3, hidden_size=256, n_mixture=5, temperature=0.0):
""":param z_dim: the dimension of VAE latent variable :param hidden_size: hidden size of RNN :param n_mixture: number of Gaussian Mixture Models to be used :param temperature: controls the ... | stack_v2_sparse_classes_36k_train_013805 | 7,346 | no_license | [
{
"docstring": ":param z_dim: the dimension of VAE latent variable :param hidden_size: hidden size of RNN :param n_mixture: number of Gaussian Mixture Models to be used :param temperature: controls the randomness of the model MDNRNN stands for Mixture Density Network - RNN. The output of this model is [mean, si... | 2 | null | Implement the Python class `MDNRNN` described below.
Class description:
Implement the MDNRNN class.
Method signatures and docstrings:
- def __init__(self, z_dim=32, action_dim=3, hidden_size=256, n_mixture=5, temperature=0.0): :param z_dim: the dimension of VAE latent variable :param hidden_size: hidden size of RNN :... | Implement the Python class `MDNRNN` described below.
Class description:
Implement the MDNRNN class.
Method signatures and docstrings:
- def __init__(self, z_dim=32, action_dim=3, hidden_size=256, n_mixture=5, temperature=0.0): :param z_dim: the dimension of VAE latent variable :param hidden_size: hidden size of RNN :... | e4b4b49bee7e7e3843c6874717779ce8d619bd02 | <|skeleton|>
class MDNRNN:
def __init__(self, z_dim=32, action_dim=3, hidden_size=256, n_mixture=5, temperature=0.0):
""":param z_dim: the dimension of VAE latent variable :param hidden_size: hidden size of RNN :param n_mixture: number of Gaussian Mixture Models to be used :param temperature: controls the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MDNRNN:
def __init__(self, z_dim=32, action_dim=3, hidden_size=256, n_mixture=5, temperature=0.0):
""":param z_dim: the dimension of VAE latent variable :param hidden_size: hidden size of RNN :param n_mixture: number of Gaussian Mixture Models to be used :param temperature: controls the randomness of ... | the_stack_v2_python_sparse | world-models-pytorch/CMA-ES/cma_es_simple_onerun.py | humorbeing/python_github | train | 0 | |
40321697c67d4f48ca700104bf730960e489037c | [
"result = 0\nfor index, value in enumerate(nums):\n if value == val:\n continue\n if result != index:\n nums[result] = value\n result += 1\nreturn result",
"start, end = (0, len(nums) - 1)\nwhile start <= end:\n if nums[start] == val:\n nums[start], nums[end], end = (nums[end], nu... | <|body_start_0|>
result = 0
for index, value in enumerate(nums):
if value == val:
continue
if result != index:
nums[result] = value
result += 1
return result
<|end_body_0|>
<|body_start_1|>
start, end = (0, len(nums) - ... | 给出一个列表和一个值,从列表中删除给定的值,返回最终的数组长度 Given an array nums and a value val, remove all instances of that value in-place and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. The order of elements can be changed. It doesn't matte... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""给出一个列表和一个值,从列表中删除给定的值,返回最终的数组长度 Given an array nums and a value val, remove all instances of that value in-place and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. The order of eleme... | stack_v2_sparse_classes_36k_train_013806 | 3,154 | no_license | [
{
"docstring": ":type nums: List[int] :type val: int :rtype: int",
"name": "symb",
"signature": "def symb(self, nums, val)"
},
{
"docstring": "从左开始往右移动,每碰到一个目标值,就将其交换到列表尾部 Starting from the left every time we find a value that is the target value we swap it out with an item starting from the rig... | 2 | stack_v2_sparse_classes_30k_val_000741 | Implement the Python class `Solution` described below.
Class description:
给出一个列表和一个值,从列表中删除给定的值,返回最终的数组长度 Given an array nums and a value val, remove all instances of that value in-place and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place wit... | Implement the Python class `Solution` described below.
Class description:
给出一个列表和一个值,从列表中删除给定的值,返回最终的数组长度 Given an array nums and a value val, remove all instances of that value in-place and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place wit... | 7a6de1767eaabb6464ea4c90756606d59b868d7c | <|skeleton|>
class Solution:
"""给出一个列表和一个值,从列表中删除给定的值,返回最终的数组长度 Given an array nums and a value val, remove all instances of that value in-place and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. The order of eleme... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""给出一个列表和一个值,从列表中删除给定的值,返回最终的数组长度 Given an array nums and a value val, remove all instances of that value in-place and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. The order of elements can be ch... | the_stack_v2_python_sparse | demo/27.RemoveElement.py | symbooo/LeetCodeSymb | train | 0 |
635c5bee25dbb5c2f14c3e1cb6c16f805c9dc727 | [
"Company = self.old_state.apps.get_model('company', 'company')\nPurchaseOrder = self.old_state.apps.get_model('order', 'purchaseorder')\nPart = self.old_state.apps.get_model('part', 'part')\nSupplierpart = self.old_state.apps.get_model('company', 'supplierpart')\nsupplier = Company.objects.create(name='Supplier A',... | <|body_start_0|>
Company = self.old_state.apps.get_model('company', 'company')
PurchaseOrder = self.old_state.apps.get_model('order', 'purchaseorder')
Part = self.old_state.apps.get_model('part', 'part')
Supplierpart = self.old_state.apps.get_model('company', 'supplierpart')
supp... | Test entire schema migration. | TestAdditionalLineMigration | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAdditionalLineMigration:
"""Test entire schema migration."""
def prepare(self):
"""Create initial data set."""
<|body_0|>
def test_po_migration(self):
"""Test that the the PO lines where converted correctly."""
<|body_1|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_36k_train_013807 | 7,688 | permissive | [
{
"docstring": "Create initial data set.",
"name": "prepare",
"signature": "def prepare(self)"
},
{
"docstring": "Test that the the PO lines where converted correctly.",
"name": "test_po_migration",
"signature": "def test_po_migration(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009360 | Implement the Python class `TestAdditionalLineMigration` described below.
Class description:
Test entire schema migration.
Method signatures and docstrings:
- def prepare(self): Create initial data set.
- def test_po_migration(self): Test that the the PO lines where converted correctly. | Implement the Python class `TestAdditionalLineMigration` described below.
Class description:
Test entire schema migration.
Method signatures and docstrings:
- def prepare(self): Create initial data set.
- def test_po_migration(self): Test that the the PO lines where converted correctly.
<|skeleton|>
class TestAdditi... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class TestAdditionalLineMigration:
"""Test entire schema migration."""
def prepare(self):
"""Create initial data set."""
<|body_0|>
def test_po_migration(self):
"""Test that the the PO lines where converted correctly."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestAdditionalLineMigration:
"""Test entire schema migration."""
def prepare(self):
"""Create initial data set."""
Company = self.old_state.apps.get_model('company', 'company')
PurchaseOrder = self.old_state.apps.get_model('order', 'purchaseorder')
Part = self.old_state.ap... | the_stack_v2_python_sparse | InvenTree/order/test_migrations.py | inventree/InvenTree | train | 3,077 |
32f4b0e53532b01b357b04326a10d2c7f81188e6 | [
"super().__init__(*args, **kwargs)\nself.DBconnect = DBconnect\nself.mainLayout = QVBoxLayout(self)\nself.formLayout = QFormLayout()\nself.emailLayout = QHBoxLayout()\nself.passwordLayout = QHBoxLayout()\nself.email = QLineEdit()\nself.password = QLineEdit()\nself.password.setEchoMode(QLineEdit.Password)\nself.subm... | <|body_start_0|>
super().__init__(*args, **kwargs)
self.DBconnect = DBconnect
self.mainLayout = QVBoxLayout(self)
self.formLayout = QFormLayout()
self.emailLayout = QHBoxLayout()
self.passwordLayout = QHBoxLayout()
self.email = QLineEdit()
self.password = ... | QWidget that takes in email, password, and allow user to submit. Parameters: Parent Window, Database connection Shows email input, password input, and a submit button. When submit is clicked, the Widget calls a validator function in parent window of type LogInWindow. | LogInWidget | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogInWidget:
"""QWidget that takes in email, password, and allow user to submit. Parameters: Parent Window, Database connection Shows email input, password input, and a submit button. When submit is clicked, the Widget calls a validator function in parent window of type LogInWindow."""
def _... | stack_v2_sparse_classes_36k_train_013808 | 3,687 | no_license | [
{
"docstring": "Initializes object's database connection, email field, password field, and submit connection",
"name": "__init__",
"signature": "def __init__(self, DBconnect, *args, **kwargs)"
},
{
"docstring": "Checks if given email is valid (not related to DB) through checking domain and check... | 3 | stack_v2_sparse_classes_30k_train_000523 | Implement the Python class `LogInWidget` described below.
Class description:
QWidget that takes in email, password, and allow user to submit. Parameters: Parent Window, Database connection Shows email input, password input, and a submit button. When submit is clicked, the Widget calls a validator function in parent wi... | Implement the Python class `LogInWidget` described below.
Class description:
QWidget that takes in email, password, and allow user to submit. Parameters: Parent Window, Database connection Shows email input, password input, and a submit button. When submit is clicked, the Widget calls a validator function in parent wi... | 2951b90a8380b78bbc8afaedd4cf7c983dfcb269 | <|skeleton|>
class LogInWidget:
"""QWidget that takes in email, password, and allow user to submit. Parameters: Parent Window, Database connection Shows email input, password input, and a submit button. When submit is clicked, the Widget calls a validator function in parent window of type LogInWindow."""
def _... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogInWidget:
"""QWidget that takes in email, password, and allow user to submit. Parameters: Parent Window, Database connection Shows email input, password input, and a submit button. When submit is clicked, the Widget calls a validator function in parent window of type LogInWindow."""
def __init__(self,... | the_stack_v2_python_sparse | GUI/logInWidget.py | jotk/GHAR | train | 0 |
8e085268f34cc56ce856a7edbb494a08f45ae7a8 | [
"if not root:\n return []\nstack = [root]\nresult = []\nwhile stack:\n node = stack.pop()\n if not node:\n continue\n result.append(node.val)\n for each_node in reversed(node.children):\n stack.append(each_node)\nreturn result",
"result = []\n\ndef helper(node):\n if not node:\n ... | <|body_start_0|>
if not root:
return []
stack = [root]
result = []
while stack:
node = stack.pop()
if not node:
continue
result.append(node.val)
for each_node in reversed(node.children):
stack.app... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def preorder(self, root):
""":type root: Node :rtype: List[int]"""
<|body_0|>
def preorder_recursive(self, root):
""":type root: Node :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return []
... | stack_v2_sparse_classes_36k_train_013809 | 1,397 | no_license | [
{
"docstring": ":type root: Node :rtype: List[int]",
"name": "preorder",
"signature": "def preorder(self, root)"
},
{
"docstring": ":type root: Node :rtype: List[int]",
"name": "preorder_recursive",
"signature": "def preorder_recursive(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012901 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def preorder(self, root): :type root: Node :rtype: List[int]
- def preorder_recursive(self, root): :type root: Node :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def preorder(self, root): :type root: Node :rtype: List[int]
- def preorder_recursive(self, root): :type root: Node :rtype: List[int]
<|skeleton|>
class Solution:
def preor... | 643df908343b38fa758f9dbcbbadd03ae8dbed74 | <|skeleton|>
class Solution:
def preorder(self, root):
""":type root: Node :rtype: List[int]"""
<|body_0|>
def preorder_recursive(self, root):
""":type root: Node :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def preorder(self, root):
""":type root: Node :rtype: List[int]"""
if not root:
return []
stack = [root]
result = []
while stack:
node = stack.pop()
if not node:
continue
result.append(node.val)
... | the_stack_v2_python_sparse | LeetCode/week_42/589_N叉树的前序遍历.py | Colaplusice/algorithm_and_data_structure | train | 0 | |
7056c392e1cc968478abc6bc8d08158146e3608b | [
"super(MultiHeadedAttention, self).__init__()\nassert d_model % h == 0\nself.d_k = d_model // h\nself.h = h\nself.linears = clones(nn.Linear(d_model, d_model), 3)\nself.attn = None\nself.dropout = nn.Dropout(p=dropout)\nself.rep = FCNet([d_model, d_model])",
"if mask is not None:\n mask = mask.unsqueeze(1)\nnb... | <|body_start_0|>
super(MultiHeadedAttention, self).__init__()
assert d_model % h == 0
self.d_k = d_model // h
self.h = h
self.linears = clones(nn.Linear(d_model, d_model), 3)
self.attn = None
self.dropout = nn.Dropout(p=dropout)
self.rep = FCNet([d_model, ... | MultiHeadedAttention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadedAttention:
def __init__(self, h, d_model, dropout=0.1):
"""Take in model size and number of heads."""
<|body_0|>
def forward(self, query, key, value, mask=None):
"""Implements Figure 2"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super... | stack_v2_sparse_classes_36k_train_013810 | 12,326 | permissive | [
{
"docstring": "Take in model size and number of heads.",
"name": "__init__",
"signature": "def __init__(self, h, d_model, dropout=0.1)"
},
{
"docstring": "Implements Figure 2",
"name": "forward",
"signature": "def forward(self, query, key, value, mask=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012078 | Implement the Python class `MultiHeadedAttention` described below.
Class description:
Implement the MultiHeadedAttention class.
Method signatures and docstrings:
- def __init__(self, h, d_model, dropout=0.1): Take in model size and number of heads.
- def forward(self, query, key, value, mask=None): Implements Figure ... | Implement the Python class `MultiHeadedAttention` described below.
Class description:
Implement the MultiHeadedAttention class.
Method signatures and docstrings:
- def __init__(self, h, d_model, dropout=0.1): Take in model size and number of heads.
- def forward(self, query, key, value, mask=None): Implements Figure ... | 0e4bf3f7f301570b652490f697758361c866f3c1 | <|skeleton|>
class MultiHeadedAttention:
def __init__(self, h, d_model, dropout=0.1):
"""Take in model size and number of heads."""
<|body_0|>
def forward(self, query, key, value, mask=None):
"""Implements Figure 2"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiHeadedAttention:
def __init__(self, h, d_model, dropout=0.1):
"""Take in model size and number of heads."""
super(MultiHeadedAttention, self).__init__()
assert d_model % h == 0
self.d_k = d_model // h
self.h = h
self.linears = clones(nn.Linear(d_model, d_mo... | the_stack_v2_python_sparse | model_td_noun_selfatt.py | thilinicooray/mac-network-pytorch | train | 0 | |
0a76dda96da294e4b6a991576766591671bb12ed | [
"self.snmp_object = snmp_object\ntest_oid = '.1.3.6.1.4.1.9.9.128.1.1.1.1.3'\nsuper().__init__(snmp_object, test_oid, tags=['layer1'])",
"final = defaultdict(lambda: defaultdict(dict))\nvalues = self.cviroutedvlanifindex()\nfor key, value in values.items():\n final[key]['cviRoutedVlanIfIndex'] = value\nreturn ... | <|body_start_0|>
self.snmp_object = snmp_object
test_oid = '.1.3.6.1.4.1.9.9.128.1.1.1.1.3'
super().__init__(snmp_object, test_oid, tags=['layer1'])
<|end_body_0|>
<|body_start_1|>
final = defaultdict(lambda: defaultdict(dict))
values = self.cviroutedvlanifindex()
for ke... | Class interacts with CISCO-VLAN-IFTABLE-RELATIONSHIP-MIB. Args: None Returns: None Key Methods: supported: Queries the device to determine whether the MIB is supported using a known OID defined in the MIB. Returns True if the device returns a response to the OID, False if not. layer1: Returns all needed layer 1 MIB inf... | CiscoVlanIftableRelationshipQuery | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CiscoVlanIftableRelationshipQuery:
"""Class interacts with CISCO-VLAN-IFTABLE-RELATIONSHIP-MIB. Args: None Returns: None Key Methods: supported: Queries the device to determine whether the MIB is supported using a known OID defined in the MIB. Returns True if the device returns a response to the ... | stack_v2_sparse_classes_36k_train_013811 | 2,856 | permissive | [
{
"docstring": "Function for intializing the class. Args: snmp_object: SNMP Interact class object from snmp_manager.py Returns: None",
"name": "__init__",
"signature": "def __init__(self, snmp_object)"
},
{
"docstring": "Get layer 1 data from device. Args: None Returns: final: Final results",
... | 3 | stack_v2_sparse_classes_30k_train_016662 | Implement the Python class `CiscoVlanIftableRelationshipQuery` described below.
Class description:
Class interacts with CISCO-VLAN-IFTABLE-RELATIONSHIP-MIB. Args: None Returns: None Key Methods: supported: Queries the device to determine whether the MIB is supported using a known OID defined in the MIB. Returns True i... | Implement the Python class `CiscoVlanIftableRelationshipQuery` described below.
Class description:
Class interacts with CISCO-VLAN-IFTABLE-RELATIONSHIP-MIB. Args: None Returns: None Key Methods: supported: Queries the device to determine whether the MIB is supported using a known OID defined in the MIB. Returns True i... | ae82589fbbab77fef6d6be09c1fcca5846f595a8 | <|skeleton|>
class CiscoVlanIftableRelationshipQuery:
"""Class interacts with CISCO-VLAN-IFTABLE-RELATIONSHIP-MIB. Args: None Returns: None Key Methods: supported: Queries the device to determine whether the MIB is supported using a known OID defined in the MIB. Returns True if the device returns a response to the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CiscoVlanIftableRelationshipQuery:
"""Class interacts with CISCO-VLAN-IFTABLE-RELATIONSHIP-MIB. Args: None Returns: None Key Methods: supported: Queries the device to determine whether the MIB is supported using a known OID defined in the MIB. Returns True if the device returns a response to the OID, False if... | the_stack_v2_python_sparse | switchmap/snmp/cisco/mib_ciscovlaniftablerelationship.py | PalisadoesFoundation/switchmap-ng | train | 8 |
ab1404c89e2cb29916ff17c846c265680edc7670 | [
"n = len(s)\nfor i in range(n):\n is_unique = True\n for j in range(n):\n if s[i] == s[j] and i != j:\n is_unique = False\n break\n if is_unique:\n return i\nreturn -1",
"look = {}\nfor ch in s:\n look[ch] = look.get(ch, 0) + 1\nfor i, ch in enumerate(s):\n if lo... | <|body_start_0|>
n = len(s)
for i in range(n):
is_unique = True
for j in range(n):
if s[i] == s[j] and i != j:
is_unique = False
break
if is_unique:
return i
return -1
<|end_body_0|>
<|bo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def firstUniqChar0(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def firstUniqChar1(self, s):
""":type s: str :rtype: int"""
<|body_1|>
def firstUniqChar(self, s):
""":type s: str :rtype: int"""
<|body_2|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_013812 | 1,126 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "firstUniqChar0",
"signature": "def firstUniqChar0(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "firstUniqChar1",
"signature": "def firstUniqChar1(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"na... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstUniqChar0(self, s): :type s: str :rtype: int
- def firstUniqChar1(self, s): :type s: str :rtype: int
- def firstUniqChar(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstUniqChar0(self, s): :type s: str :rtype: int
- def firstUniqChar1(self, s): :type s: str :rtype: int
- def firstUniqChar(self, s): :type s: str :rtype: int
<|skeleton|>... | b365ba85036e51f7a9e018767914ef22314a6780 | <|skeleton|>
class Solution:
def firstUniqChar0(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def firstUniqChar1(self, s):
""":type s: str :rtype: int"""
<|body_1|>
def firstUniqChar(self, s):
""":type s: str :rtype: int"""
<|body_2|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def firstUniqChar0(self, s):
""":type s: str :rtype: int"""
n = len(s)
for i in range(n):
is_unique = True
for j in range(n):
if s[i] == s[j] and i != j:
is_unique = False
break
if is_... | the_stack_v2_python_sparse | easy/字符串中的第一个唯一字符.py | f1amingo/leetcode-python | train | 1 | |
ed2e07a76bfac34836053d5b79eaf2386e0fe269 | [
"if output_image_topic is not None:\n self.image_publisher = rospy.Publisher(output_image_topic, ROS_Image, queue_size=10)\nelse:\n self.image_publisher = None\nrospy.Subscriber(input_image_topic, ROS_Image, self.callback)\nself.bridge = ROSBridge()\nself.ID = 0\nself.parser = argparse.ArgumentParser()\nself.... | <|body_start_0|>
if output_image_topic is not None:
self.image_publisher = rospy.Publisher(output_image_topic, ROS_Image, queue_size=10)
else:
self.image_publisher = None
rospy.Subscriber(input_image_topic, ROS_Image, self.callback)
self.bridge = ROSBridge()
... | Synthetic_Data_Generation | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Synthetic_Data_Generation:
def __init__(self, input_image_topic='/usb_cam/image_raw', output_image_topic='/opendr/synthetic_facial_images', device='cuda'):
"""Creates a ROS Node for SyntheticDataGeneration :param input_image_topic: Topic from which we are reading the input image :type in... | stack_v2_sparse_classes_36k_train_013813 | 5,315 | permissive | [
{
"docstring": "Creates a ROS Node for SyntheticDataGeneration :param input_image_topic: Topic from which we are reading the input image :type input_image_topic: str :param output_image_topic: Topic to which we are publishing the synthetic facial image (if None, we are not publishing any image) :type output_ima... | 3 | stack_v2_sparse_classes_30k_train_001560 | Implement the Python class `Synthetic_Data_Generation` described below.
Class description:
Implement the Synthetic_Data_Generation class.
Method signatures and docstrings:
- def __init__(self, input_image_topic='/usb_cam/image_raw', output_image_topic='/opendr/synthetic_facial_images', device='cuda'): Creates a ROS N... | Implement the Python class `Synthetic_Data_Generation` described below.
Class description:
Implement the Synthetic_Data_Generation class.
Method signatures and docstrings:
- def __init__(self, input_image_topic='/usb_cam/image_raw', output_image_topic='/opendr/synthetic_facial_images', device='cuda'): Creates a ROS N... | b3d6ce670cdf63469fc5766630eb295d67b3d788 | <|skeleton|>
class Synthetic_Data_Generation:
def __init__(self, input_image_topic='/usb_cam/image_raw', output_image_topic='/opendr/synthetic_facial_images', device='cuda'):
"""Creates a ROS Node for SyntheticDataGeneration :param input_image_topic: Topic from which we are reading the input image :type in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Synthetic_Data_Generation:
def __init__(self, input_image_topic='/usb_cam/image_raw', output_image_topic='/opendr/synthetic_facial_images', device='cuda'):
"""Creates a ROS Node for SyntheticDataGeneration :param input_image_topic: Topic from which we are reading the input image :type input_image_topi... | the_stack_v2_python_sparse | projects/opendr_ws/src/opendr_data_generation/scripts/synthetic_facial_generation_node.py | opendr-eu/opendr | train | 535 | |
0ce70d8d6b5dbb413321f983f5a5549843998376 | [
"self.font = font or 'TNR.ttf'\nself.font_size = font_size or 52\nself.symbol_size = symbol_size or (50, 50)\nself.symbol_list = symbols\nself.symbol_characteristics = {}\nself.create_symbol_images()",
"for sym in self.symbol_list:\n im = Image.new('L', self.symbol_size, color='white')\n d = ImageDraw.Draw(... | <|body_start_0|>
self.font = font or 'TNR.ttf'
self.font_size = font_size or 52
self.symbol_size = symbol_size or (50, 50)
self.symbol_list = symbols
self.symbol_characteristics = {}
self.create_symbol_images()
<|end_body_0|>
<|body_start_1|>
for sym in self.symb... | Класс создающий набор признаков для букв заданного алфавита | FontCharacteristics | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FontCharacteristics:
"""Класс создающий набор признаков для букв заданного алфавита"""
def __init__(self, symbols: list or tuple or str, font=None, font_size=None, symbol_size=None):
"""Инициализация объекта класса FontCharacteristics :param symbols: алфавит :type symbols: str or Non... | stack_v2_sparse_classes_36k_train_013814 | 6,836 | no_license | [
{
"docstring": "Инициализация объекта класса FontCharacteristics :param symbols: алфавит :type symbols: str or None :param image: экземпляр класса LabImage :type image: LabImage or None :param font: путь до файла шрифта :type font: str or None :param font_size: размер шрифта :type font_size: int :param symbol_s... | 4 | stack_v2_sparse_classes_30k_train_014833 | Implement the Python class `FontCharacteristics` described below.
Class description:
Класс создающий набор признаков для букв заданного алфавита
Method signatures and docstrings:
- def __init__(self, symbols: list or tuple or str, font=None, font_size=None, symbol_size=None): Инициализация объекта класса FontCharacte... | Implement the Python class `FontCharacteristics` described below.
Class description:
Класс создающий набор признаков для букв заданного алфавита
Method signatures and docstrings:
- def __init__(self, symbols: list or tuple or str, font=None, font_size=None, symbol_size=None): Инициализация объекта класса FontCharacte... | c3a1228f8caf555fb640895b54be25ee8fe87ab2 | <|skeleton|>
class FontCharacteristics:
"""Класс создающий набор признаков для букв заданного алфавита"""
def __init__(self, symbols: list or tuple or str, font=None, font_size=None, symbol_size=None):
"""Инициализация объекта класса FontCharacteristics :param symbols: алфавит :type symbols: str or Non... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FontCharacteristics:
"""Класс создающий набор признаков для букв заданного алфавита"""
def __init__(self, symbols: list or tuple or str, font=None, font_size=None, symbol_size=None):
"""Инициализация объекта класса FontCharacteristics :param symbols: алфавит :type symbols: str or None :param imag... | the_stack_v2_python_sparse | library/SymbolImage.py | Myasnikova/OCRLibrary | train | 0 |
ad2cf5ed5bf84c172cb0aa1eaac2f3cd983f6298 | [
"super().__init__()\nself.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)\nself.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)\nself.sru = SRUCell(d_model, dim_feedforward, dropout, sru_dropout or dropout, bidirectional=False, has_skip_term=False, **kwargs)\nself.linear2 ... | <|body_start_0|>
super().__init__()
self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
self.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
self.sru = SRUCell(d_model, dim_feedforward, dropout, sru_dropout or dropout, bidirectional=False, has_... | A TransformerSRUDecoderLayer with an SRU replacing the FFN. | TransformerSRUDecoderLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerSRUDecoderLayer:
"""A TransformerSRUDecoderLayer with an SRU replacing the FFN."""
def __init__(self, d_model: int, nhead: int, dim_feedforward: int=2048, dropout: float=0.1, sru_dropout: Optional[float]=None, **kwargs: Dict[str, Any]) -> None:
"""Initialize a TransformerD... | stack_v2_sparse_classes_36k_train_013815 | 23,050 | permissive | [
{
"docstring": "Initialize a TransformerDecoder. Parameters ---------- d_model : int The number of expected features in the input. n_head : int The number of heads in the multiheadattention models. dim_feedforward : int, optional The dimension of the feedforward network (default=2048). dropout : float, optional... | 2 | null | Implement the Python class `TransformerSRUDecoderLayer` described below.
Class description:
A TransformerSRUDecoderLayer with an SRU replacing the FFN.
Method signatures and docstrings:
- def __init__(self, d_model: int, nhead: int, dim_feedforward: int=2048, dropout: float=0.1, sru_dropout: Optional[float]=None, **k... | Implement the Python class `TransformerSRUDecoderLayer` described below.
Class description:
A TransformerSRUDecoderLayer with an SRU replacing the FFN.
Method signatures and docstrings:
- def __init__(self, d_model: int, nhead: int, dim_feedforward: int=2048, dropout: float=0.1, sru_dropout: Optional[float]=None, **k... | 0dc2f5b2b286694defe8abf450fe5be9ae12c097 | <|skeleton|>
class TransformerSRUDecoderLayer:
"""A TransformerSRUDecoderLayer with an SRU replacing the FFN."""
def __init__(self, d_model: int, nhead: int, dim_feedforward: int=2048, dropout: float=0.1, sru_dropout: Optional[float]=None, **kwargs: Dict[str, Any]) -> None:
"""Initialize a TransformerD... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransformerSRUDecoderLayer:
"""A TransformerSRUDecoderLayer with an SRU replacing the FFN."""
def __init__(self, d_model: int, nhead: int, dim_feedforward: int=2048, dropout: float=0.1, sru_dropout: Optional[float]=None, **kwargs: Dict[str, Any]) -> None:
"""Initialize a TransformerDecoder. Param... | the_stack_v2_python_sparse | flambe/nn/transformer_sru.py | cle-ros/flambe | train | 1 |
9557afc36f0ea2af39a7aaacd0de8ae90de74e12 | [
"super().__init__('opendr_video_human_activity_recognition_node')\nassert model in {'cox3d-s', 'cox3d-m', 'cox3d-l', 'x3d-xs', 'x3d-s', 'x3d-m', 'x3d-l'}\nmodel_name, model_size = model.split('-')\nLearner = {'cox3d': CoX3DLearner, 'x3d': X3DLearner}[model_name]\nself.learner = Learner(device=device, backbone=model... | <|body_start_0|>
super().__init__('opendr_video_human_activity_recognition_node')
assert model in {'cox3d-s', 'cox3d-m', 'cox3d-l', 'x3d-xs', 'x3d-s', 'x3d-m', 'x3d-l'}
model_name, model_size = model.split('-')
Learner = {'cox3d': CoX3DLearner, 'x3d': X3DLearner}[model_name]
self... | HumanActivityRecognitionNode | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HumanActivityRecognitionNode:
def __init__(self, input_rgb_image_topic='image_raw', output_category_topic='/opendr/human_activity_recognition', output_category_description_topic='/opendr/human_activity_recognition_description', device='cuda', model='cox3d-m'):
"""Creates a ROS2 Node for ... | stack_v2_sparse_classes_36k_train_013816 | 9,444 | permissive | [
{
"docstring": "Creates a ROS2 Node for video-based human activity recognition. :param input_rgb_image_topic: Topic from which we are reading the input image :type input_rgb_image_topic: str :param output_category_topic: Topic to which we are publishing the recognized activity (if None, we are not publishing th... | 2 | null | Implement the Python class `HumanActivityRecognitionNode` described below.
Class description:
Implement the HumanActivityRecognitionNode class.
Method signatures and docstrings:
- def __init__(self, input_rgb_image_topic='image_raw', output_category_topic='/opendr/human_activity_recognition', output_category_descript... | Implement the Python class `HumanActivityRecognitionNode` described below.
Class description:
Implement the HumanActivityRecognitionNode class.
Method signatures and docstrings:
- def __init__(self, input_rgb_image_topic='image_raw', output_category_topic='/opendr/human_activity_recognition', output_category_descript... | b3d6ce670cdf63469fc5766630eb295d67b3d788 | <|skeleton|>
class HumanActivityRecognitionNode:
def __init__(self, input_rgb_image_topic='image_raw', output_category_topic='/opendr/human_activity_recognition', output_category_description_topic='/opendr/human_activity_recognition_description', device='cuda', model='cox3d-m'):
"""Creates a ROS2 Node for ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HumanActivityRecognitionNode:
def __init__(self, input_rgb_image_topic='image_raw', output_category_topic='/opendr/human_activity_recognition', output_category_description_topic='/opendr/human_activity_recognition_description', device='cuda', model='cox3d-m'):
"""Creates a ROS2 Node for video-based hu... | the_stack_v2_python_sparse | projects/opendr_ws_2/src/opendr_perception/opendr_perception/video_activity_recognition_node.py | opendr-eu/opendr | train | 535 | |
e0a05eefd0fa0485116cdaafc7be800bf6e082e8 | [
"samples_lims = []\nfor sample in samples:\n LOG.debug(f\"{sample['name']}: prepare LIMS input\")\n samples_lims.append({'name': sample['name'], 'container': sample.get('container') or 'Tube', 'container_name': sample.get('container_name'), 'well_position': sample.get('well_position'), 'index_sequence': sampl... | <|body_start_0|>
samples_lims = []
for sample in samples:
LOG.debug(f"{sample['name']}: prepare LIMS input")
samples_lims.append({'name': sample['name'], 'container': sample.get('container') or 'Tube', 'container_name': sample.get('container_name'), 'well_position': sample.get('w... | LimsHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LimsHandler:
def to_lims(customer: str, samples: List[dict]) -> List[dict]:
"""Convert order input to lims interface input."""
<|body_0|>
def process_lims(self, data: dict, samples: List[dict]):
"""Process samples to add them to LIMS."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k_train_013817 | 3,155 | no_license | [
{
"docstring": "Convert order input to lims interface input.",
"name": "to_lims",
"signature": "def to_lims(customer: str, samples: List[dict]) -> List[dict]"
},
{
"docstring": "Process samples to add them to LIMS.",
"name": "process_lims",
"signature": "def process_lims(self, data: dict... | 2 | stack_v2_sparse_classes_30k_train_018816 | Implement the Python class `LimsHandler` described below.
Class description:
Implement the LimsHandler class.
Method signatures and docstrings:
- def to_lims(customer: str, samples: List[dict]) -> List[dict]: Convert order input to lims interface input.
- def process_lims(self, data: dict, samples: List[dict]): Proce... | Implement the Python class `LimsHandler` described below.
Class description:
Implement the LimsHandler class.
Method signatures and docstrings:
- def to_lims(customer: str, samples: List[dict]) -> List[dict]: Convert order input to lims interface input.
- def process_lims(self, data: dict, samples: List[dict]): Proce... | 987b422511ff0299712a59bfe523e9a35dbd3171 | <|skeleton|>
class LimsHandler:
def to_lims(customer: str, samples: List[dict]) -> List[dict]:
"""Convert order input to lims interface input."""
<|body_0|>
def process_lims(self, data: dict, samples: List[dict]):
"""Process samples to add them to LIMS."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LimsHandler:
def to_lims(customer: str, samples: List[dict]) -> List[dict]:
"""Convert order input to lims interface input."""
samples_lims = []
for sample in samples:
LOG.debug(f"{sample['name']}: prepare LIMS input")
samples_lims.append({'name': sample['name']... | the_stack_v2_python_sparse | cg/meta/orders/lims.py | dnil/cg | train | 2 | |
c8b91741cfda4db64443c31db7ddb22d221e3d68 | [
"self.name = name\nself.code = code\nself.netValue = netValue\nself.netMarketCap = netValue\nself.positions = int(cash / netValue)\npass",
"self.netMarketCap = netValue\nnewNetValue = netValue\nnewPositions = int(cash / netValue)\nprint('买入价格:{0} 操作仓位:{1}'.format(round(newNetValue, 2), newPositions))\nself.netVal... | <|body_start_0|>
self.name = name
self.code = code
self.netValue = netValue
self.netMarketCap = netValue
self.positions = int(cash / netValue)
pass
<|end_body_0|>
<|body_start_1|>
self.netMarketCap = netValue
newNetValue = netValue
newPositions = ... | fund | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class fund:
def __init__(self, name, code, netValue, cash):
"""初始化一只基金"""
<|body_0|>
def buy(self, netValue, cash):
"""买入一定金额"""
<|body_1|>
def sell(self, netValue, cash):
"""卖出一定金额"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
self... | stack_v2_sparse_classes_36k_train_013818 | 3,340 | no_license | [
{
"docstring": "初始化一只基金",
"name": "__init__",
"signature": "def __init__(self, name, code, netValue, cash)"
},
{
"docstring": "买入一定金额",
"name": "buy",
"signature": "def buy(self, netValue, cash)"
},
{
"docstring": "卖出一定金额",
"name": "sell",
"signature": "def sell(self, net... | 3 | stack_v2_sparse_classes_30k_train_003585 | Implement the Python class `fund` described below.
Class description:
Implement the fund class.
Method signatures and docstrings:
- def __init__(self, name, code, netValue, cash): 初始化一只基金
- def buy(self, netValue, cash): 买入一定金额
- def sell(self, netValue, cash): 卖出一定金额 | Implement the Python class `fund` described below.
Class description:
Implement the fund class.
Method signatures and docstrings:
- def __init__(self, name, code, netValue, cash): 初始化一只基金
- def buy(self, netValue, cash): 买入一定金额
- def sell(self, netValue, cash): 卖出一定金额
<|skeleton|>
class fund:
def __init__(self,... | 6837259cf3a0a174022e3052c00c4d289a7e2d19 | <|skeleton|>
class fund:
def __init__(self, name, code, netValue, cash):
"""初始化一只基金"""
<|body_0|>
def buy(self, netValue, cash):
"""买入一定金额"""
<|body_1|>
def sell(self, netValue, cash):
"""卖出一定金额"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class fund:
def __init__(self, name, code, netValue, cash):
"""初始化一只基金"""
self.name = name
self.code = code
self.netValue = netValue
self.netMarketCap = netValue
self.positions = int(cash / netValue)
pass
def buy(self, netValue, cash):
"""买入一定金额""... | the_stack_v2_python_sparse | MockTradeSystem/portfolio.py | klq26/finance-data | train | 5 | |
377aa05d2969f0b05dadbe738af09245b9d8181e | [
"p1 = ListNode(None)\np1.next = l1\np2 = ListNode(None)\np2.next = l2\nr = rp = ListNode(None)\nwhile p1.next != None or p2.next != None:\n if p1.next != None and p2.next != None:\n if p1.next.val < p2.next.val:\n r.val = p1.next.val\n r.next = ListNode(None)\n r = r.next\... | <|body_start_0|>
p1 = ListNode(None)
p1.next = l1
p2 = ListNode(None)
p2.next = l2
r = rp = ListNode(None)
while p1.next != None or p2.next != None:
if p1.next != None and p2.next != None:
if p1.next.val < p2.next.val:
r.val... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_013819 | 2,047 | no_license | [
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "mergeTwoLists",
"signature": "def mergeTwoLists(self, l1, l2)"
},
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "mergeTwoLists",
"signature": "def mergeTwoLists(self, l1, ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
... | ef1c3bae0f6b1087df51530ba2322cfc9c970cde | <|skeleton|>
class Solution:
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
p1 = ListNode(None)
p1.next = l1
p2 = ListNode(None)
p2.next = l2
r = rp = ListNode(None)
while p1.next != None or p2.next != None:
if p1.... | the_stack_v2_python_sparse | Leetcode/LeetCode0/21. Merge Two Sorted Lists.py | liugingko/LeetCode-Python | train | 0 | |
95af0aa063e4c6244ebe1646bfec51d387e0642e | [
"payment_form = MakePaymentForm({'stripe_id': '1234567890'})\nself.assertTrue(payment_form.is_valid())\norder_form = OrderForm({'full_name': 'testuser', 'phone_number': '123456789', 'country': 'Test', 'town_or_city': 'Test', 'street_address1': 'street1', 'street_address2': 'street2', 'county': 'Test'})\nself.assert... | <|body_start_0|>
payment_form = MakePaymentForm({'stripe_id': '1234567890'})
self.assertTrue(payment_form.is_valid())
order_form = OrderForm({'full_name': 'testuser', 'phone_number': '123456789', 'country': 'Test', 'town_or_city': 'Test', 'street_address1': 'street1', 'street_address2': 'street2... | test MakePaymentForm | TestMakePaymentForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMakePaymentForm:
"""test MakePaymentForm"""
def test_form_is_valid(self):
"""test if the forms is valid"""
<|body_0|>
def test_form_not_valid(self):
"""Test that our forms are not valid with empty required fields"""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_36k_train_013820 | 1,571 | no_license | [
{
"docstring": "test if the forms is valid",
"name": "test_form_is_valid",
"signature": "def test_form_is_valid(self)"
},
{
"docstring": "Test that our forms are not valid with empty required fields",
"name": "test_form_not_valid",
"signature": "def test_form_not_valid(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012764 | Implement the Python class `TestMakePaymentForm` described below.
Class description:
test MakePaymentForm
Method signatures and docstrings:
- def test_form_is_valid(self): test if the forms is valid
- def test_form_not_valid(self): Test that our forms are not valid with empty required fields | Implement the Python class `TestMakePaymentForm` described below.
Class description:
test MakePaymentForm
Method signatures and docstrings:
- def test_form_is_valid(self): test if the forms is valid
- def test_form_not_valid(self): Test that our forms are not valid with empty required fields
<|skeleton|>
class TestM... | b0d37ba8476f334d864a4e9b9f2820efc6a54934 | <|skeleton|>
class TestMakePaymentForm:
"""test MakePaymentForm"""
def test_form_is_valid(self):
"""test if the forms is valid"""
<|body_0|>
def test_form_not_valid(self):
"""Test that our forms are not valid with empty required fields"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestMakePaymentForm:
"""test MakePaymentForm"""
def test_form_is_valid(self):
"""test if the forms is valid"""
payment_form = MakePaymentForm({'stripe_id': '1234567890'})
self.assertTrue(payment_form.is_valid())
order_form = OrderForm({'full_name': 'testuser', 'phone_numbe... | the_stack_v2_python_sparse | checkout/tests_forms.py | alnibo/milestone-project-4-help-others | train | 0 |
2918e1bc7e74f33e74b858a0c0518aa6e75abbfd | [
"if n == 1:\n return 1\nugly = [0] * n\nugly[0] = 1\nnext_ugly_2 = 2\nnext_ugly_3 = 3\nnext_ugly_5 = 5\ni2 = i3 = i5 = 0\nfor i in range(1, n):\n next_ugly = min(next_ugly_2, next_ugly_3, next_ugly_5)\n ugly[i] = next_ugly\n if next_ugly == next_ugly_2:\n i2 += 1\n next_ugly_2 = ugly[i2] *... | <|body_start_0|>
if n == 1:
return 1
ugly = [0] * n
ugly[0] = 1
next_ugly_2 = 2
next_ugly_3 = 3
next_ugly_5 = 5
i2 = i3 = i5 = 0
for i in range(1, n):
next_ugly = min(next_ugly_2, next_ugly_3, next_ugly_5)
ugly[i] = next... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nthUglyNumber(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def nthSuperUglyNumber(self, n, primes):
""":type n: int :type primes: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n == 1:
retur... | stack_v2_sparse_classes_36k_train_013821 | 3,254 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "nthUglyNumber",
"signature": "def nthUglyNumber(self, n)"
},
{
"docstring": ":type n: int :type primes: List[int] :rtype: int",
"name": "nthSuperUglyNumber",
"signature": "def nthSuperUglyNumber(self, n, primes)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011509 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nthUglyNumber(self, n): :type n: int :rtype: int
- def nthSuperUglyNumber(self, n, primes): :type n: int :type primes: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nthUglyNumber(self, n): :type n: int :rtype: int
- def nthSuperUglyNumber(self, n, primes): :type n: int :type primes: List[int] :rtype: int
<|skeleton|>
class Solution:
... | 8731e2ccfbda9323ea5c8629599806cd1c37c3bf | <|skeleton|>
class Solution:
def nthUglyNumber(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def nthSuperUglyNumber(self, n, primes):
""":type n: int :type primes: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def nthUglyNumber(self, n):
""":type n: int :rtype: int"""
if n == 1:
return 1
ugly = [0] * n
ugly[0] = 1
next_ugly_2 = 2
next_ugly_3 = 3
next_ugly_5 = 5
i2 = i3 = i5 = 0
for i in range(1, n):
next_ugly =... | the_stack_v2_python_sparse | problems/dynamicProgramming/UglyNumber.py | jonu4u/DataStructuresInPython | train | 0 | |
2d67dbd646dbd41f71029d8bdb1b574fa247a7f5 | [
"old_policy_list = self.policy_query_biz.new_policy_list(system_id, Subject(type=SubjectType.USER.value, id=applicant))\ndiff_policy_list = policy_list.sub(old_policy_list)\ndiff_policy_list.check_resource_name()\napplication_policies = []\nfor p in policy_list.policies:\n old_policy = old_policy_list.get(p.acti... | <|body_start_0|>
old_policy_list = self.policy_query_biz.new_policy_list(system_id, Subject(type=SubjectType.USER.value, id=applicant))
diff_policy_list = policy_list.sub(old_policy_list)
diff_policy_list.check_resource_name()
application_policies = []
for p in policy_list.polici... | 用于将申请请求里的Dict转换为调用ApplicationBiz模块创建申请单所需的数据结构 | ApplicationDataTrans | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApplicationDataTrans:
"""用于将申请请求里的Dict转换为调用ApplicationBiz模块创建申请单所需的数据结构"""
def _gen_need_apply_policy_list(self, applicant: str, system_id: str, policy_list: PolicyBeanList) -> PolicyBeanList:
"""生成需要申请的策略 由于前端提交时会将已有权限的资源实例也提交,所以需要剔除掉"""
<|body_0|>
def _check_applicatio... | stack_v2_sparse_classes_36k_train_013822 | 8,112 | permissive | [
{
"docstring": "生成需要申请的策略 由于前端提交时会将已有权限的资源实例也提交,所以需要剔除掉",
"name": "_gen_need_apply_policy_list",
"signature": "def _gen_need_apply_policy_list(self, applicant: str, system_id: str, policy_list: PolicyBeanList) -> PolicyBeanList"
},
{
"docstring": "检查申请策略的资源实例限制",
"name": "_check_application_... | 3 | null | Implement the Python class `ApplicationDataTrans` described below.
Class description:
用于将申请请求里的Dict转换为调用ApplicationBiz模块创建申请单所需的数据结构
Method signatures and docstrings:
- def _gen_need_apply_policy_list(self, applicant: str, system_id: str, policy_list: PolicyBeanList) -> PolicyBeanList: 生成需要申请的策略 由于前端提交时会将已有权限的资源实例也提交... | Implement the Python class `ApplicationDataTrans` described below.
Class description:
用于将申请请求里的Dict转换为调用ApplicationBiz模块创建申请单所需的数据结构
Method signatures and docstrings:
- def _gen_need_apply_policy_list(self, applicant: str, system_id: str, policy_list: PolicyBeanList) -> PolicyBeanList: 生成需要申请的策略 由于前端提交时会将已有权限的资源实例也提交... | 33c8f4ffe8697081abcfc5771b98a88c0578059f | <|skeleton|>
class ApplicationDataTrans:
"""用于将申请请求里的Dict转换为调用ApplicationBiz模块创建申请单所需的数据结构"""
def _gen_need_apply_policy_list(self, applicant: str, system_id: str, policy_list: PolicyBeanList) -> PolicyBeanList:
"""生成需要申请的策略 由于前端提交时会将已有权限的资源实例也提交,所以需要剔除掉"""
<|body_0|>
def _check_applicatio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ApplicationDataTrans:
"""用于将申请请求里的Dict转换为调用ApplicationBiz模块创建申请单所需的数据结构"""
def _gen_need_apply_policy_list(self, applicant: str, system_id: str, policy_list: PolicyBeanList) -> PolicyBeanList:
"""生成需要申请的策略 由于前端提交时会将已有权限的资源实例也提交,所以需要剔除掉"""
old_policy_list = self.policy_query_biz.new_policy... | the_stack_v2_python_sparse | saas/backend/trans/application.py | robert871126/bk-iam-saas | train | 0 |
40f1eab4a770acfd7045bd836ae6533f061e3c66 | [
"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... | ImageService defines the public APIs for managing images. | ImageServiceServicer | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageServiceServicer:
"""ImageService defines the public APIs for managing images."""
def ListImages(self, request, context):
"""ListImages lists existing images."""
<|body_0|>
def ImageStatus(self, request, context):
"""ImageStatus returns the status of the imag... | stack_v2_sparse_classes_36k_train_013823 | 45,927 | permissive | [
{
"docstring": "ListImages lists existing images.",
"name": "ListImages",
"signature": "def ListImages(self, request, context)"
},
{
"docstring": "ImageStatus returns the status of the image. If the image is not present, returns a response with ImageStatusResponse.Image set to nil.",
"name":... | 5 | stack_v2_sparse_classes_30k_train_015621 | Implement the Python class `ImageServiceServicer` described below.
Class description:
ImageService defines the public APIs for managing images.
Method signatures and docstrings:
- def ListImages(self, request, context): ListImages lists existing images.
- def ImageStatus(self, request, context): ImageStatus returns t... | Implement the Python class `ImageServiceServicer` described below.
Class description:
ImageService defines the public APIs for managing images.
Method signatures and docstrings:
- def ListImages(self, request, context): ListImages lists existing images.
- def ImageStatus(self, request, context): ImageStatus returns t... | f825fde287f4eb2089aba2225ca73eeab3888040 | <|skeleton|>
class ImageServiceServicer:
"""ImageService defines the public APIs for managing images."""
def ListImages(self, request, context):
"""ListImages lists existing images."""
<|body_0|>
def ImageStatus(self, request, context):
"""ImageStatus returns the status of the imag... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageServiceServicer:
"""ImageService defines the public APIs for managing images."""
def ListImages(self, request, context):
"""ListImages lists existing images."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImp... | the_stack_v2_python_sparse | src/nodemgr/common/cri/api_pb2_grpc.py | tungstenfabric/tf-controller | train | 55 |
337ac9a51ff1c8506c95b440714a68cdce250e14 | [
"pay_url = 'http://www.zhifu.com'\ndata = {'card': card, 'amout': amout}\nresponse = requests.post(pay_url, data=data)\nreturn response",
"response = self.auth(card, amount)\ntry:\n if response['status_code'] == '200':\n print('用户{}支付金额{}成功'.format(user_id, amount))\n return '支付成功'\n elif resp... | <|body_start_0|>
pay_url = 'http://www.zhifu.com'
data = {'card': card, 'amout': amout}
response = requests.post(pay_url, data=data)
return response
<|end_body_0|>
<|body_start_1|>
response = self.auth(card, amount)
try:
if response['status_code'] == '200':
... | PayAPI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PayAPI:
def auth(card, amout):
"""第三方支付接口 :param card:卡号 :param amout: 金额 :return:"""
<|body_0|>
def pay(self, user_id, card, amount):
"""我们自己的支付接口 :param user_id:用户id :param card: 卡号 :param amount: 支付金额 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_013824 | 1,283 | no_license | [
{
"docstring": "第三方支付接口 :param card:卡号 :param amout: 金额 :return:",
"name": "auth",
"signature": "def auth(card, amout)"
},
{
"docstring": "我们自己的支付接口 :param user_id:用户id :param card: 卡号 :param amount: 支付金额 :return:",
"name": "pay",
"signature": "def pay(self, user_id, card, amount)"
}
] | 2 | null | Implement the Python class `PayAPI` described below.
Class description:
Implement the PayAPI class.
Method signatures and docstrings:
- def auth(card, amout): 第三方支付接口 :param card:卡号 :param amout: 金额 :return:
- def pay(self, user_id, card, amount): 我们自己的支付接口 :param user_id:用户id :param card: 卡号 :param amount: 支付金额 :ret... | Implement the Python class `PayAPI` described below.
Class description:
Implement the PayAPI class.
Method signatures and docstrings:
- def auth(card, amout): 第三方支付接口 :param card:卡号 :param amout: 金额 :return:
- def pay(self, user_id, card, amount): 我们自己的支付接口 :param user_id:用户id :param card: 卡号 :param amount: 支付金额 :ret... | 2bc66d80acefdd835331b29c5fea35aedd5ed42d | <|skeleton|>
class PayAPI:
def auth(card, amout):
"""第三方支付接口 :param card:卡号 :param amout: 金额 :return:"""
<|body_0|>
def pay(self, user_id, card, amount):
"""我们自己的支付接口 :param user_id:用户id :param card: 卡号 :param amount: 支付金额 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PayAPI:
def auth(card, amout):
"""第三方支付接口 :param card:卡号 :param amout: 金额 :return:"""
pay_url = 'http://www.zhifu.com'
data = {'card': card, 'amout': amout}
response = requests.post(pay_url, data=data)
return response
def pay(self, user_id, card, amount):
"... | the_stack_v2_python_sparse | case/tool/mock/URLRequest.py | duanbibo/test_demo | train | 0 | |
3b56d87b9d29763ff31a68208d0ea029ffc88a1b | [
"if not email:\n raise ValueError('Mandate fileld: should have an email address')\nif not password:\n raise ValueError('User must have a password')\nif not username:\n raise ValueError('User must have a full name')\nelse:\n email = self.normalize_email(email)\n first_name = str(first_name).lower()\n ... | <|body_start_0|>
if not email:
raise ValueError('Mandate fileld: should have an email address')
if not password:
raise ValueError('User must have a password')
if not username:
raise ValueError('User must have a full name')
else:
email = sel... | Custome Manager for User Profiles Overiding the System defined parameters, which makes Django to interact with the fields | UserProfileManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserProfileManager:
"""Custome Manager for User Profiles Overiding the System defined parameters, which makes Django to interact with the fields"""
def create_user(self, email, username, password, first_name, last_name):
"""Create a new user Profile"""
<|body_0|>
def cre... | stack_v2_sparse_classes_36k_train_013825 | 4,917 | no_license | [
{
"docstring": "Create a new user Profile",
"name": "create_user",
"signature": "def create_user(self, email, username, password, first_name, last_name)"
},
{
"docstring": "Create a new super user",
"name": "create_superuser",
"signature": "def create_superuser(self, email, username, pas... | 2 | stack_v2_sparse_classes_30k_val_001046 | Implement the Python class `UserProfileManager` described below.
Class description:
Custome Manager for User Profiles Overiding the System defined parameters, which makes Django to interact with the fields
Method signatures and docstrings:
- def create_user(self, email, username, password, first_name, last_name): Cre... | Implement the Python class `UserProfileManager` described below.
Class description:
Custome Manager for User Profiles Overiding the System defined parameters, which makes Django to interact with the fields
Method signatures and docstrings:
- def create_user(self, email, username, password, first_name, last_name): Cre... | e0b514f0685bc2dafd61384aedd2d19b3fa0950b | <|skeleton|>
class UserProfileManager:
"""Custome Manager for User Profiles Overiding the System defined parameters, which makes Django to interact with the fields"""
def create_user(self, email, username, password, first_name, last_name):
"""Create a new user Profile"""
<|body_0|>
def cre... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserProfileManager:
"""Custome Manager for User Profiles Overiding the System defined parameters, which makes Django to interact with the fields"""
def create_user(self, email, username, password, first_name, last_name):
"""Create a new user Profile"""
if not email:
raise Valu... | the_stack_v2_python_sparse | WebApplication/Django/UserAuthApp/profiles_api/models.py | knagadevara/PythonScripts | train | 7 |
dc1c516755136ad695e486e31155bc537afa8e0f | [
"for algorithm, expected in {'md5': ('698d51a19d8a121ce581499d7b701668', '8980c988edc2c78cc43ccb718c06efd5', '53fd88c84ff8a285eb6e0a687e55b8c7'), 'sha1': ('6216f8a75fd5bb3d5f22b6f9958cdede3fc086c2', '42eda1b5dcb3586bccfb1c69f22f923145271d97', '2eb2f7be4e883ebe52034281d818c91e1cf16256'), 'sha256': ('f6e0a1e2ac41945a... | <|body_start_0|>
for algorithm, expected in {'md5': ('698d51a19d8a121ce581499d7b701668', '8980c988edc2c78cc43ccb718c06efd5', '53fd88c84ff8a285eb6e0a687e55b8c7'), 'sha1': ('6216f8a75fd5bb3d5f22b6f9958cdede3fc086c2', '42eda1b5dcb3586bccfb1c69f22f923145271d97', '2eb2f7be4e883ebe52034281d818c91e1cf16256'), 'sha256'... | HashTestCase | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HashTestCase:
def test_collect(self) -> None:
"""Test collecting a list of signatures into a new signature value"""
<|body_0|>
def test_MD5signature(self) -> None:
"""Test generating a signature"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for al... | stack_v2_sparse_classes_36k_train_013826 | 44,672 | permissive | [
{
"docstring": "Test collecting a list of signatures into a new signature value",
"name": "test_collect",
"signature": "def test_collect(self) -> None"
},
{
"docstring": "Test generating a signature",
"name": "test_MD5signature",
"signature": "def test_MD5signature(self) -> None"
}
] | 2 | stack_v2_sparse_classes_30k_train_001001 | Implement the Python class `HashTestCase` described below.
Class description:
Implement the HashTestCase class.
Method signatures and docstrings:
- def test_collect(self) -> None: Test collecting a list of signatures into a new signature value
- def test_MD5signature(self) -> None: Test generating a signature | Implement the Python class `HashTestCase` described below.
Class description:
Implement the HashTestCase class.
Method signatures and docstrings:
- def test_collect(self) -> None: Test collecting a list of signatures into a new signature value
- def test_MD5signature(self) -> None: Test generating a signature
<|skel... | b2a7d7066a2b854460a334a5fe737ea389655e6e | <|skeleton|>
class HashTestCase:
def test_collect(self) -> None:
"""Test collecting a list of signatures into a new signature value"""
<|body_0|>
def test_MD5signature(self) -> None:
"""Test generating a signature"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HashTestCase:
def test_collect(self) -> None:
"""Test collecting a list of signatures into a new signature value"""
for algorithm, expected in {'md5': ('698d51a19d8a121ce581499d7b701668', '8980c988edc2c78cc43ccb718c06efd5', '53fd88c84ff8a285eb6e0a687e55b8c7'), 'sha1': ('6216f8a75fd5bb3d5f22b6f... | the_stack_v2_python_sparse | SCons/UtilTests.py | SCons/scons | train | 1,827 | |
96ea1b0f83042643120e6de3b4ad6dfad98bd448 | [
"text = ''\nfor label, value in self.descriptors:\n pad = '\\n' + ' ' * 14\n formatted = textwrap.fill(textwrap.dedent(value).strip(), width=66).replace('\\n', pad)\n text += '%12s: %s\\n' % (label, formatted)\nreturn text[:-1]",
"content = html.Div(className='vtype')\nfor label, value in self.descriptor... | <|body_start_0|>
text = ''
for label, value in self.descriptors:
pad = '\n' + ' ' * 14
formatted = textwrap.fill(textwrap.dedent(value).strip(), width=66).replace('\n', pad)
text += '%12s: %s\n' % (label, formatted)
return text[:-1]
<|end_body_0|>
<|body_star... | A self-describing type mixin Types that use this mixin are responsible for filling an array cls.descriptors of tuples (label,value) in their constructor. | Descriptive | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Descriptive:
"""A self-describing type mixin Types that use this mixin are responsible for filling an array cls.descriptors of tuples (label,value) in their constructor."""
def describe(self):
"""Returns a plain-text multi-line description The final newline character is omitted so th... | stack_v2_sparse_classes_36k_train_013827 | 19,705 | no_license | [
{
"docstring": "Returns a plain-text multi-line description The final newline character is omitted so that the return value can be printed. The description is indented with spaces assuming a fixed-width font.",
"name": "describe",
"signature": "def describe(self)"
},
{
"docstring": "Returns a de... | 2 | null | Implement the Python class `Descriptive` described below.
Class description:
A self-describing type mixin Types that use this mixin are responsible for filling an array cls.descriptors of tuples (label,value) in their constructor.
Method signatures and docstrings:
- def describe(self): Returns a plain-text multi-line... | Implement the Python class `Descriptive` described below.
Class description:
A self-describing type mixin Types that use this mixin are responsible for filling an array cls.descriptors of tuples (label,value) in their constructor.
Method signatures and docstrings:
- def describe(self): Returns a plain-text multi-line... | fe5578ba978e8a9cd81c08be271c2ef874a84927 | <|skeleton|>
class Descriptive:
"""A self-describing type mixin Types that use this mixin are responsible for filling an array cls.descriptors of tuples (label,value) in their constructor."""
def describe(self):
"""Returns a plain-text multi-line description The final newline character is omitted so th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Descriptive:
"""A self-describing type mixin Types that use this mixin are responsible for filling an array cls.descriptors of tuples (label,value) in their constructor."""
def describe(self):
"""Returns a plain-text multi-line description The final newline character is omitted so that the return... | the_stack_v2_python_sparse | python/opscore/protocols/types.py | Subaru-PFS/tron_actorcore | train | 3 |
2be5aaedec134dfb0ec8bf5a54cc52652ad19cf8 | [
"self.pair_file_loc = pair_file_loc\nself.r1 = pair_file_loc + '_R1_001.fastq.gz'\nself.r2 = pair_file_loc + '_R2_001.fastq.gz'\nself.lane = re.search('L[0-9]{3}', pair_file_loc)\nself.id = re.search('^[0-9]{6}', pair_file_loc)\nself.prefix = pair_file_loc\nself.home_dir = home_dir\nself.hisat2_idx = hisat2_idx\nse... | <|body_start_0|>
self.pair_file_loc = pair_file_loc
self.r1 = pair_file_loc + '_R1_001.fastq.gz'
self.r2 = pair_file_loc + '_R2_001.fastq.gz'
self.lane = re.search('L[0-9]{3}', pair_file_loc)
self.id = re.search('^[0-9]{6}', pair_file_loc)
self.prefix = pair_file_loc
... | Create a FastQ pair object. | fq_pair | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class fq_pair:
"""Create a FastQ pair object."""
def __init__(self, pair_file_loc, home_dir, hisat2_idx, star_idx, n):
"""Create an object for the FASTQ file."""
<|body_0|>
def RunHISAT2(self):
"""Run HISAT2. Manual: https://ccb.jhu.edu/software/hisat2/manual.shtml Not... | stack_v2_sparse_classes_36k_train_013828 | 5,699 | no_license | [
{
"docstring": "Create an object for the FASTQ file.",
"name": "__init__",
"signature": "def __init__(self, pair_file_loc, home_dir, hisat2_idx, star_idx, n)"
},
{
"docstring": "Run HISAT2. Manual: https://ccb.jhu.edu/software/hisat2/manual.shtml Notes on HISAT2: -p is number of cores to use",
... | 3 | stack_v2_sparse_classes_30k_test_000033 | Implement the Python class `fq_pair` described below.
Class description:
Create a FastQ pair object.
Method signatures and docstrings:
- def __init__(self, pair_file_loc, home_dir, hisat2_idx, star_idx, n): Create an object for the FASTQ file.
- def RunHISAT2(self): Run HISAT2. Manual: https://ccb.jhu.edu/software/hi... | Implement the Python class `fq_pair` described below.
Class description:
Create a FastQ pair object.
Method signatures and docstrings:
- def __init__(self, pair_file_loc, home_dir, hisat2_idx, star_idx, n): Create an object for the FASTQ file.
- def RunHISAT2(self): Run HISAT2. Manual: https://ccb.jhu.edu/software/hi... | eb84ab40dcd2915b09a3126948e83ebdf981ec3d | <|skeleton|>
class fq_pair:
"""Create a FastQ pair object."""
def __init__(self, pair_file_loc, home_dir, hisat2_idx, star_idx, n):
"""Create an object for the FASTQ file."""
<|body_0|>
def RunHISAT2(self):
"""Run HISAT2. Manual: https://ccb.jhu.edu/software/hisat2/manual.shtml Not... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class fq_pair:
"""Create a FastQ pair object."""
def __init__(self, pair_file_loc, home_dir, hisat2_idx, star_idx, n):
"""Create an object for the FASTQ file."""
self.pair_file_loc = pair_file_loc
self.r1 = pair_file_loc + '_R1_001.fastq.gz'
self.r2 = pair_file_loc + '_R2_001.fa... | the_stack_v2_python_sparse | code_variants/align_qc_class.py | frichter/embryo_rnaseq | train | 2 |
12f6e29760ce34ffb34cd1c3b0145dab21358ca9 | [
"min1 = min2 = 134217727\nfor n in nums:\n if n < min1:\n min1 = n\n elif min1 < n < min2:\n min2 = n\n elif n > min2:\n return True\nreturn False",
"if not nums or len(nums) < 3:\n return False\nn = len(nums)\nforwards = [float('inf')] * n\nbackwards = [float('-inf')] * n\nfor i ... | <|body_start_0|>
min1 = min2 = 134217727
for n in nums:
if n < min1:
min1 = n
elif min1 < n < min2:
min2 = n
elif n > min2:
return True
return False
<|end_body_0|>
<|body_start_1|>
if not nums or len(num... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def increasingTriplet(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def increasingTriplet_range(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
min1 = min2 = 134217727
... | stack_v2_sparse_classes_36k_train_013829 | 1,964 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "increasingTriplet",
"signature": "def increasingTriplet(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "increasingTriplet_range",
"signature": "def increasingTriplet_range(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def increasingTriplet(self, nums): :type nums: List[int] :rtype: bool
- def increasingTriplet_range(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 increasingTriplet(self, nums): :type nums: List[int] :rtype: bool
- def increasingTriplet_range(self, nums): :type nums: List[int] :rtype: bool
<|skeleton|>
class Solution:
... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def increasingTriplet(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def increasingTriplet_range(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 increasingTriplet(self, nums):
""":type nums: List[int] :rtype: bool"""
min1 = min2 = 134217727
for n in nums:
if n < min1:
min1 = n
elif min1 < n < min2:
min2 = n
elif n > min2:
return Tr... | the_stack_v2_python_sparse | src/lt_334.py | oxhead/CodingYourWay | train | 0 | |
4d4cc436fa8f2879a95af087499b7e241e0f9ae3 | [
"masks = {}\nfor (x, y), value in np.ndenumerate(mask_array):\n if value != 0:\n if value not in masks:\n masks[value] = np.zeros(mask_array.shape)\n dummy_array = masks[value]\n dummy_array[x, y] = 1\n masks[value] = dummy_array\nreturn masks",
"self.add_class('cells', 1... | <|body_start_0|>
masks = {}
for (x, y), value in np.ndenumerate(mask_array):
if value != 0:
if value not in masks:
masks[value] = np.zeros(mask_array.shape)
dummy_array = masks[value]
dummy_array[x, y] = 1
ma... | Generates a cells dataset for training. Dataset consists of microscope images. | CellsDataset | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CellsDataset:
"""Generates a cells dataset for training. Dataset consists of microscope images."""
def generate_masks(mask_array):
"""Generate a dictionary of masks. The keys are instance numbers from the numpy stack and the values are the corresponding binary masks. Args: mask_array... | stack_v2_sparse_classes_36k_train_013830 | 15,173 | permissive | [
{
"docstring": "Generate a dictionary of masks. The keys are instance numbers from the numpy stack and the values are the corresponding binary masks. Args: mask_array: numpy array of size [H,W]. 0 represents the background. Any non zero integer represents a individual instance Returns: Mask dictionary {instance... | 5 | stack_v2_sparse_classes_30k_train_020994 | Implement the Python class `CellsDataset` described below.
Class description:
Generates a cells dataset for training. Dataset consists of microscope images.
Method signatures and docstrings:
- def generate_masks(mask_array): Generate a dictionary of masks. The keys are instance numbers from the numpy stack and the va... | Implement the Python class `CellsDataset` described below.
Class description:
Generates a cells dataset for training. Dataset consists of microscope images.
Method signatures and docstrings:
- def generate_masks(mask_array): Generate a dictionary of masks. The keys are instance numbers from the numpy stack and the va... | 2f825cbcba92ff2fdffac60de56604578f31e937 | <|skeleton|>
class CellsDataset:
"""Generates a cells dataset for training. Dataset consists of microscope images."""
def generate_masks(mask_array):
"""Generate a dictionary of masks. The keys are instance numbers from the numpy stack and the values are the corresponding binary masks. Args: mask_array... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CellsDataset:
"""Generates a cells dataset for training. Dataset consists of microscope images."""
def generate_masks(mask_array):
"""Generate a dictionary of masks. The keys are instance numbers from the numpy stack and the values are the corresponding binary masks. Args: mask_array: numpy array... | the_stack_v2_python_sparse | framework-nucleus-segmentation/mrcnn/samples/cell/cell.py | CBIIT/nci-hitif | train | 1 |
6878095230e86e0819b024a719f45323017af3f0 | [
"c = Client()\nc.login(username='admin', password='admin1')\nresp = c.post('/roles/crear/', {'name': 'Rol 1'}, follow=True)\nself.assertEqual(resp.status_code, 200)\nresp = c.post('/roles/crear/', {'name': 'Rol 1'})\nself.assertEqual(resp.status_code, 200)",
"c = Client()\nc.login(username='admin', password='admi... | <|body_start_0|>
c = Client()
c.login(username='admin', password='admin1')
resp = c.post('/roles/crear/', {'name': 'Rol 1'}, follow=True)
self.assertEqual(resp.status_code, 200)
resp = c.post('/roles/crear/', {'name': 'Rol 1'})
self.assertEqual(resp.status_code, 200)
<|en... | PMSTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PMSTestCase:
def test_crear_rol(self):
"""Test para la creacion de un rol"""
<|body_0|>
def test_listar_roles(self):
"""Test para crear un rol y ver si lo lista correctamente"""
<|body_1|>
def test_detalle(self):
"""Test para crear un rol y ver s... | stack_v2_sparse_classes_36k_train_013831 | 3,680 | no_license | [
{
"docstring": "Test para la creacion de un rol",
"name": "test_crear_rol",
"signature": "def test_crear_rol(self)"
},
{
"docstring": "Test para crear un rol y ver si lo lista correctamente",
"name": "test_listar_roles",
"signature": "def test_listar_roles(self)"
},
{
"docstring"... | 6 | stack_v2_sparse_classes_30k_train_015012 | Implement the Python class `PMSTestCase` described below.
Class description:
Implement the PMSTestCase class.
Method signatures and docstrings:
- def test_crear_rol(self): Test para la creacion de un rol
- def test_listar_roles(self): Test para crear un rol y ver si lo lista correctamente
- def test_detalle(self): Te... | Implement the Python class `PMSTestCase` described below.
Class description:
Implement the PMSTestCase class.
Method signatures and docstrings:
- def test_crear_rol(self): Test para la creacion de un rol
- def test_listar_roles(self): Test para crear un rol y ver si lo lista correctamente
- def test_detalle(self): Te... | 101017990bbddc7e52174ec2a439f563f98febb9 | <|skeleton|>
class PMSTestCase:
def test_crear_rol(self):
"""Test para la creacion de un rol"""
<|body_0|>
def test_listar_roles(self):
"""Test para crear un rol y ver si lo lista correctamente"""
<|body_1|>
def test_detalle(self):
"""Test para crear un rol y ver s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PMSTestCase:
def test_crear_rol(self):
"""Test para la creacion de un rol"""
c = Client()
c.login(username='admin', password='admin1')
resp = c.post('/roles/crear/', {'name': 'Rol 1'}, follow=True)
self.assertEqual(resp.status_code, 200)
resp = c.post('/roles/cr... | the_stack_v2_python_sparse | roles/tests.py | Grupo-Ughelli-Lisnichuk-IS2/PMS | train | 0 | |
f5469352519fc949a9e52d3113b1a17a9e364e89 | [
"jwt_decode_handler = api_settings.JWT_DECODE_HANDLER\ncookies = self.strategy.request.COOKIES\nif api_settings.JWT_AUTH_COOKIE not in cookies:\n raise AuthException(self, 'Authorization header not present')\nauth = cookies.get(api_settings.JWT_AUTH_COOKIE)\ntry:\n return jwt_decode_handler(auth)\nexcept jwt.... | <|body_start_0|>
jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
cookies = self.strategy.request.COOKIES
if api_settings.JWT_AUTH_COOKIE not in cookies:
raise AuthException(self, 'Authorization header not present')
auth = cookies.get(api_settings.JWT_AUTH_COOKIE)
... | Base implementation for JWT-based authentication | BaseJwtAuth | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseJwtAuth:
"""Base implementation for JWT-based authentication"""
def user_data(self):
"""Returns user data from the JWT"""
<|body_0|>
def auth_complete(self, *args, **kwargs):
"""Perform the authentication"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_013832 | 1,238 | permissive | [
{
"docstring": "Returns user data from the JWT",
"name": "user_data",
"signature": "def user_data(self)"
},
{
"docstring": "Perform the authentication",
"name": "auth_complete",
"signature": "def auth_complete(self, *args, **kwargs)"
}
] | 2 | null | Implement the Python class `BaseJwtAuth` described below.
Class description:
Base implementation for JWT-based authentication
Method signatures and docstrings:
- def user_data(self): Returns user data from the JWT
- def auth_complete(self, *args, **kwargs): Perform the authentication | Implement the Python class `BaseJwtAuth` described below.
Class description:
Base implementation for JWT-based authentication
Method signatures and docstrings:
- def user_data(self): Returns user data from the JWT
- def auth_complete(self, *args, **kwargs): Perform the authentication
<|skeleton|>
class BaseJwtAuth:
... | ba7442482da97d463302658c0aac989567ee1241 | <|skeleton|>
class BaseJwtAuth:
"""Base implementation for JWT-based authentication"""
def user_data(self):
"""Returns user data from the JWT"""
<|body_0|>
def auth_complete(self, *args, **kwargs):
"""Perform the authentication"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseJwtAuth:
"""Base implementation for JWT-based authentication"""
def user_data(self):
"""Returns user data from the JWT"""
jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
cookies = self.strategy.request.COOKIES
if api_settings.JWT_AUTH_COOKIE not in cookies:
... | the_stack_v2_python_sparse | authentication/backends/base_jwt.py | mitodl/open-discussions | train | 13 |
0a8ac351d92f30d2694341ff6977d3a26435cef4 | [
"q1 = [node]\nans = Node(node.val, [])\nq2 = [ans]\nvisited = set()\nwhile q1:\n cur1 = q1.pop()\n cur2 = q2.pop()\n visited.add(cur1)\n for neighbor in cur1.neighbors:\n if neighbor in visited:\n continue\n if neighbor not in q1:\n q1.append(neighbor)\n ne... | <|body_start_0|>
q1 = [node]
ans = Node(node.val, [])
q2 = [ans]
visited = set()
while q1:
cur1 = q1.pop()
cur2 = q2.pop()
visited.add(cur1)
for neighbor in cur1.neighbors:
if neighbor in visited:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
"""bfs"""
<|body_0|>
def cloneGraph1(self, node: 'Node') -> 'Node':
"""dfs"""
<|body_1|>
def cloneGraph2(self, node: 'Node') -> 'Node':
"""非递归 dfs"""
<|body_2|>
def cloneGraph3(... | stack_v2_sparse_classes_36k_train_013833 | 2,567 | no_license | [
{
"docstring": "bfs",
"name": "cloneGraph",
"signature": "def cloneGraph(self, node: 'Node') -> 'Node'"
},
{
"docstring": "dfs",
"name": "cloneGraph1",
"signature": "def cloneGraph1(self, node: 'Node') -> 'Node'"
},
{
"docstring": "非递归 dfs",
"name": "cloneGraph2",
"signat... | 4 | stack_v2_sparse_classes_30k_train_004683 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def cloneGraph(self, node: 'Node') -> 'Node': bfs
- def cloneGraph1(self, node: 'Node') -> 'Node': dfs
- def cloneGraph2(self, node: 'Node') -> 'Node': 非递归 dfs
- def cloneGraph3(... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def cloneGraph(self, node: 'Node') -> 'Node': bfs
- def cloneGraph1(self, node: 'Node') -> 'Node': dfs
- def cloneGraph2(self, node: 'Node') -> 'Node': 非递归 dfs
- def cloneGraph3(... | e2fecd266bfced6208694b19a2d81182b13dacd6 | <|skeleton|>
class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
"""bfs"""
<|body_0|>
def cloneGraph1(self, node: 'Node') -> 'Node':
"""dfs"""
<|body_1|>
def cloneGraph2(self, node: 'Node') -> 'Node':
"""非递归 dfs"""
<|body_2|>
def cloneGraph3(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
"""bfs"""
q1 = [node]
ans = Node(node.val, [])
q2 = [ans]
visited = set()
while q1:
cur1 = q1.pop()
cur2 = q2.pop()
visited.add(cur1)
for neighbor in cur1.nei... | the_stack_v2_python_sparse | cloneGraph.py | HuipengXu/leetcode | train | 0 | |
d1ca596e514723b26bfe68050ee2bb7c658ba4b1 | [
"self.dic = {}\nself.ele = []\nself.pre_stamp = None",
"if self.pre_stamp == None:\n self.pre_stamp = timestamp\n self.dic[timestamp] = 0\n self.ele.append(1)\nelif self.pre_stamp == timestamp:\n self.ele[-1] += 1\nelse:\n self.dic[timestamp] = len(self.ele)\n self.pre_time = timestamp\n self... | <|body_start_0|>
self.dic = {}
self.ele = []
self.pre_stamp = None
<|end_body_0|>
<|body_start_1|>
if self.pre_stamp == None:
self.pre_stamp = timestamp
self.dic[timestamp] = 0
self.ele.append(1)
elif self.pre_stamp == timestamp:
s... | HitCounter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HitCounter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def hit(self, timestamp: int) -> None:
"""Record a hit. @param timestamp - The current timestamp (in seconds granularity)."""
<|body_1|>
def getHits(self, timestamp: in... | stack_v2_sparse_classes_36k_train_013834 | 1,830 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Record a hit. @param timestamp - The current timestamp (in seconds granularity).",
"name": "hit",
"signature": "def hit(self, timestamp: int) -> None"
},
{
... | 3 | null | Implement the Python class `HitCounter` described below.
Class description:
Implement the HitCounter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def hit(self, timestamp: int) -> None: Record a hit. @param timestamp - The current timestamp (in seconds granulari... | Implement the Python class `HitCounter` described below.
Class description:
Implement the HitCounter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def hit(self, timestamp: int) -> None: Record a hit. @param timestamp - The current timestamp (in seconds granulari... | 90fd00246707b23d60a5d13b5a89d5b5f64ad008 | <|skeleton|>
class HitCounter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def hit(self, timestamp: int) -> None:
"""Record a hit. @param timestamp - The current timestamp (in seconds granularity)."""
<|body_1|>
def getHits(self, timestamp: in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HitCounter:
def __init__(self):
"""Initialize your data structure here."""
self.dic = {}
self.ele = []
self.pre_stamp = None
def hit(self, timestamp: int) -> None:
"""Record a hit. @param timestamp - The current timestamp (in seconds granularity)."""
if sel... | the_stack_v2_python_sparse | python_solution/0362.py | Dongzi-dq394/leetcode | train | 0 | |
dcd8d65ff873bedee1a4836b846545edb78fe588 | [
"image1 = np.random.randn(256, 256, 3).astype('float32')\nimage2 = np.random.randn(256, 256, 3).astype('float32')\nsmurf_model = smurf_net.SMURFNet()\nflow = smurf_model.infer(image1, image2)\ncorrect_shape = np.equal(flow.shape, [256, 256, 2]).all()\nself.assertTrue(correct_shape)",
"ds = tf.data.Dataset.from_te... | <|body_start_0|>
image1 = np.random.randn(256, 256, 3).astype('float32')
image2 = np.random.randn(256, 256, 3).astype('float32')
smurf_model = smurf_net.SMURFNet()
flow = smurf_model.infer(image1, image2)
correct_shape = np.equal(flow.shape, [256, 256, 2]).all()
self.asse... | Run some checks to see if loading pretrained weights works correctly. | SMURFNetTest | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SMURFNetTest:
"""Run some checks to see if loading pretrained weights works correctly."""
def test_inference(self):
"""Test that inference runs and produces output of the right size."""
<|body_0|>
def test_train_step(self):
"""Test a single training step."""
... | stack_v2_sparse_classes_36k_train_013835 | 4,035 | permissive | [
{
"docstring": "Test that inference runs and produces output of the right size.",
"name": "test_inference",
"signature": "def test_inference(self)"
},
{
"docstring": "Test a single training step.",
"name": "test_train_step",
"signature": "def test_train_step(self)"
},
{
"docstrin... | 5 | null | Implement the Python class `SMURFNetTest` described below.
Class description:
Run some checks to see if loading pretrained weights works correctly.
Method signatures and docstrings:
- def test_inference(self): Test that inference runs and produces output of the right size.
- def test_train_step(self): Test a single t... | Implement the Python class `SMURFNetTest` described below.
Class description:
Run some checks to see if loading pretrained weights works correctly.
Method signatures and docstrings:
- def test_inference(self): Test that inference runs and produces output of the right size.
- def test_train_step(self): Test a single t... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class SMURFNetTest:
"""Run some checks to see if loading pretrained weights works correctly."""
def test_inference(self):
"""Test that inference runs and produces output of the right size."""
<|body_0|>
def test_train_step(self):
"""Test a single training step."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SMURFNetTest:
"""Run some checks to see if loading pretrained weights works correctly."""
def test_inference(self):
"""Test that inference runs and produces output of the right size."""
image1 = np.random.randn(256, 256, 3).astype('float32')
image2 = np.random.randn(256, 256, 3).a... | the_stack_v2_python_sparse | smurf/smurf_net_test.py | Jimmy-INL/google-research | train | 1 |
c9b26b95d1890e17806162f3c42619bfc8f4636c | [
"header('Access-Control-Allow-Origin', ctx.env.get('HTTP_ORIGIN'))\nheader('Access-Control-Allow-Headers', ctx.env.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS'))\nheader('Access-Control-Allow-Methods', '*')\nheader('Access-Control-Allow-Credentials', 'true')\nheader('Access-Control-Expose-Headers', 'X-Rucio-Auth-Token... | <|body_start_0|>
header('Access-Control-Allow-Origin', ctx.env.get('HTTP_ORIGIN'))
header('Access-Control-Allow-Headers', ctx.env.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS'))
header('Access-Control-Allow-Methods', '*')
header('Access-Control-Allow-Credentials', 'true')
header('Acc... | Request a challenge token for SSH authentication | SSHChallengeToken | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SSHChallengeToken:
"""Request a challenge token for SSH authentication"""
def OPTIONS(self):
"""HTTP Success: 200 OK Allow cross-site scripting. Explicit for Authentication."""
<|body_0|>
def GET(self):
"""HTTP Success: 200 OK HTTP Error: 401 Unauthorized :param ... | stack_v2_sparse_classes_36k_train_013836 | 18,732 | permissive | [
{
"docstring": "HTTP Success: 200 OK Allow cross-site scripting. Explicit for Authentication.",
"name": "OPTIONS",
"signature": "def OPTIONS(self)"
},
{
"docstring": "HTTP Success: 200 OK HTTP Error: 401 Unauthorized :param Rucio-Account: Account identifier as a string. :param Rucio-AppID: Appli... | 2 | null | Implement the Python class `SSHChallengeToken` described below.
Class description:
Request a challenge token for SSH authentication
Method signatures and docstrings:
- def OPTIONS(self): HTTP Success: 200 OK Allow cross-site scripting. Explicit for Authentication.
- def GET(self): HTTP Success: 200 OK HTTP Error: 401... | Implement the Python class `SSHChallengeToken` described below.
Class description:
Request a challenge token for SSH authentication
Method signatures and docstrings:
- def OPTIONS(self): HTTP Success: 200 OK Allow cross-site scripting. Explicit for Authentication.
- def GET(self): HTTP Success: 200 OK HTTP Error: 401... | 355a997a5ea213c427a5d841ab151ceb01073eb4 | <|skeleton|>
class SSHChallengeToken:
"""Request a challenge token for SSH authentication"""
def OPTIONS(self):
"""HTTP Success: 200 OK Allow cross-site scripting. Explicit for Authentication."""
<|body_0|>
def GET(self):
"""HTTP Success: 200 OK HTTP Error: 401 Unauthorized :param ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SSHChallengeToken:
"""Request a challenge token for SSH authentication"""
def OPTIONS(self):
"""HTTP Success: 200 OK Allow cross-site scripting. Explicit for Authentication."""
header('Access-Control-Allow-Origin', ctx.env.get('HTTP_ORIGIN'))
header('Access-Control-Allow-Headers',... | the_stack_v2_python_sparse | lib/rucio/web/rest/webpy/v1/authentication.py | pujanm/rucio | train | 1 |
3cbc59f3a8831e69fcadabc56560c909c2c1fcea | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ObjectMapping()",
"from .attribute_mapping import AttributeMapping\nfrom .filter import Filter\nfrom .object_flow_types import ObjectFlowTypes\nfrom .object_mapping_metadata_entry import ObjectMappingMetadataEntry\nfrom .attribute_mapp... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ObjectMapping()
<|end_body_0|>
<|body_start_1|>
from .attribute_mapping import AttributeMapping
from .filter import Filter
from .object_flow_types import ObjectFlowTypes
... | ObjectMapping | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectMapping:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ObjectMapping:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns... | stack_v2_sparse_classes_36k_train_013837 | 5,553 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ObjectMapping",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value... | 3 | null | Implement the Python class `ObjectMapping` described below.
Class description:
Implement the ObjectMapping class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ObjectMapping: Creates a new instance of the appropriate class based on discriminator value... | Implement the Python class `ObjectMapping` described below.
Class description:
Implement the ObjectMapping class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ObjectMapping: Creates a new instance of the appropriate class based on discriminator value... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ObjectMapping:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ObjectMapping:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ObjectMapping:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ObjectMapping:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ObjectMappin... | the_stack_v2_python_sparse | msgraph/generated/models/object_mapping.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
60a1ad2e36a83e0f5995929704b546265c445937 | [
"if context is None:\n context = {}\nrma_obj = self.pool.get('crm.rma')\nrma = rma_obj.browse(cr, uid, rma_id, context=context)\nmsg_ids = []\nif rma.message_ids:\n msg_ids += [msg.id for msg in rma.message_ids]\nmsg_vals = {'name': notes, 'user_id': uid}\nmsg_id = self.create(cr, uid, msg_vals, context=conte... | <|body_start_0|>
if context is None:
context = {}
rma_obj = self.pool.get('crm.rma')
rma = rma_obj.browse(cr, uid, rma_id, context=context)
msg_ids = []
if rma.message_ids:
msg_ids += [msg.id for msg in rma.message_ids]
msg_vals = {'name': notes, '... | crm_rma_message | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class crm_rma_message:
def historize_message(self, cr, uid, notes, rma_id, context=None):
"""Method to create a message in the history when a user updates notes in RMA Order Line. @param self: The object pointer. @param cr: A database cursor @param uid: Current Logged in User's Identifier. @pa... | stack_v2_sparse_classes_36k_train_013838 | 8,931 | no_license | [
{
"docstring": "Method to create a message in the history when a user updates notes in RMA Order Line. @param self: The object pointer. @param cr: A database cursor @param uid: Current Logged in User's Identifier. @param notes: Notes to be updated in the history. @param rma_id : Identifier of the RMA Order @par... | 2 | null | Implement the Python class `crm_rma_message` described below.
Class description:
Implement the crm_rma_message class.
Method signatures and docstrings:
- def historize_message(self, cr, uid, notes, rma_id, context=None): Method to create a message in the history when a user updates notes in RMA Order Line. @param sel... | Implement the Python class `crm_rma_message` described below.
Class description:
Implement the crm_rma_message class.
Method signatures and docstrings:
- def historize_message(self, cr, uid, notes, rma_id, context=None): Method to create a message in the history when a user updates notes in RMA Order Line. @param sel... | 85611a86a0e1522fd88b5e6fbb217f425c4ae12d | <|skeleton|>
class crm_rma_message:
def historize_message(self, cr, uid, notes, rma_id, context=None):
"""Method to create a message in the history when a user updates notes in RMA Order Line. @param self: The object pointer. @param cr: A database cursor @param uid: Current Logged in User's Identifier. @pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class crm_rma_message:
def historize_message(self, cr, uid, notes, rma_id, context=None):
"""Method to create a message in the history when a user updates notes in RMA Order Line. @param self: The object pointer. @param cr: A database cursor @param uid: Current Logged in User's Identifier. @param notes: Not... | the_stack_v2_python_sparse | addons-extra-crm/npg_rma_additions/rma.py | slevenhagen/addons-extra7.0 | train | 0 | |
f6b1e71ade3babfa4e6a0ca4f0478177dddbdc0a | [
"if float(mult) == 0:\n self.mult = 1.0\nelse:\n self.mult = float(mult)\nsuper(sw, self).__init__(var, bad_val)",
"rawval = self.variable\nadjustedval = rawval * self.mult\nif abs(self.variable) >= 6999:\n self.result = self.bad_value\n return\nelif adjustedval < 0.0 and adjustedval > -40.0:\n sel... | <|body_start_0|>
if float(mult) == 0:
self.mult = 1.0
else:
self.mult = float(mult)
super(sw, self).__init__(var, bad_val)
<|end_body_0|>
<|body_start_1|>
rawval = self.variable
adjustedval = rawval * self.mult
if abs(self.variable) >= 6999:
... | This class corrects shortwave radiation data to 0 at night when it just a bit below 0 and should read 0. | sw | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class sw:
"""This class corrects shortwave radiation data to 0 at night when it just a bit below 0 and should read 0."""
def __init__(self, var, bad_val=6999, mult=1.0):
"""Class initializer Arguments: var: (convertible to float) the domain value bad_val: (convertible to int) the value to ... | stack_v2_sparse_classes_36k_train_013839 | 17,830 | no_license | [
{
"docstring": "Class initializer Arguments: var: (convertible to float) the domain value bad_val: (convertible to int) the value to indicate a bad data item",
"name": "__init__",
"signature": "def __init__(self, var, bad_val=6999, mult=1.0)"
},
{
"docstring": "Calculates the polynomial function... | 2 | stack_v2_sparse_classes_30k_train_014875 | Implement the Python class `sw` described below.
Class description:
This class corrects shortwave radiation data to 0 at night when it just a bit below 0 and should read 0.
Method signatures and docstrings:
- def __init__(self, var, bad_val=6999, mult=1.0): Class initializer Arguments: var: (convertible to float) the... | Implement the Python class `sw` described below.
Class description:
This class corrects shortwave radiation data to 0 at night when it just a bit below 0 and should read 0.
Method signatures and docstrings:
- def __init__(self, var, bad_val=6999, mult=1.0): Class initializer Arguments: var: (convertible to float) the... | 95d0c102d649c5b028d262f5254106f997a7c77a | <|skeleton|>
class sw:
"""This class corrects shortwave radiation data to 0 at night when it just a bit below 0 and should read 0."""
def __init__(self, var, bad_val=6999, mult=1.0):
"""Class initializer Arguments: var: (convertible to float) the domain value bad_val: (convertible to int) the value to ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class sw:
"""This class corrects shortwave radiation data to 0 at night when it just a bit below 0 and should read 0."""
def __init__(self, var, bad_val=6999, mult=1.0):
"""Class initializer Arguments: var: (convertible to float) the domain value bad_val: (convertible to int) the value to indicate a ba... | the_stack_v2_python_sparse | csv_lib/equations.py | rwspicer/csv_utilities | train | 1 |
2da6cb965ab51ba0afb0232d51e91849485b4ca1 | [
"params = {} if params is None else params\nself.time = None\nself.timestep = None\nself.level_number = None\nself.iteration = None\nself.node = None\nself.problem_pos = None\nself.bit = None\nself.rank = None\nself.target = 0\nself.when = 'after'\nfor k, v in params.items():\n setattr(self, k, v)\nself._freeze"... | <|body_start_0|>
params = {} if params is None else params
self.time = None
self.timestep = None
self.level_number = None
self.iteration = None
self.node = None
self.problem_pos = None
self.bit = None
self.rank = None
self.target = 0
... | Class for storing all the data that belongs to a fault, i.e. when and where it happens | Fault | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fault:
"""Class for storing all the data that belongs to a fault, i.e. when and where it happens"""
def __init__(self, params=None):
"""Initialization routine for faults Args: params (dict): Parameters regarding when the fault will be inserted"""
<|body_0|>
def random(cl... | stack_v2_sparse_classes_36k_train_013840 | 22,259 | permissive | [
{
"docstring": "Initialization routine for faults Args: params (dict): Parameters regarding when the fault will be inserted",
"name": "__init__",
"signature": "def __init__(self, params=None)"
},
{
"docstring": "Classmethod to initialize a random fault Args: args (dict): Supply variables that wi... | 3 | stack_v2_sparse_classes_30k_val_001125 | Implement the Python class `Fault` described below.
Class description:
Class for storing all the data that belongs to a fault, i.e. when and where it happens
Method signatures and docstrings:
- def __init__(self, params=None): Initialization routine for faults Args: params (dict): Parameters regarding when the fault ... | Implement the Python class `Fault` described below.
Class description:
Class for storing all the data that belongs to a fault, i.e. when and where it happens
Method signatures and docstrings:
- def __init__(self, params=None): Initialization routine for faults Args: params (dict): Parameters regarding when the fault ... | 1a51834bedffd4472e344bed28f4d766614b1537 | <|skeleton|>
class Fault:
"""Class for storing all the data that belongs to a fault, i.e. when and where it happens"""
def __init__(self, params=None):
"""Initialization routine for faults Args: params (dict): Parameters regarding when the fault will be inserted"""
<|body_0|>
def random(cl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Fault:
"""Class for storing all the data that belongs to a fault, i.e. when and where it happens"""
def __init__(self, params=None):
"""Initialization routine for faults Args: params (dict): Parameters regarding when the fault will be inserted"""
params = {} if params is None else params
... | the_stack_v2_python_sparse | pySDC/projects/Resilience/fault_injection.py | Parallel-in-Time/pySDC | train | 30 |
5921326e3a36218c3c37822de5eb911fbdd8a9e4 | [
"dummy = ListNode(0)\ndummy.next = head\npre = dummy\ncur_lst = self.generate_lst(pre.next, k)\nwhile pre and (not None in cur_lst):\n temp = cur_lst[-1].next\n pre.next = cur_lst[-1]\n for i in reversed(xrange(k)):\n if i == 0:\n cur_lst[i].next = temp\n else:\n cur_lst... | <|body_start_0|>
dummy = ListNode(0)
dummy.next = head
pre = dummy
cur_lst = self.generate_lst(pre.next, k)
while pre and (not None in cur_lst):
temp = cur_lst[-1].next
pre.next = cur_lst[-1]
for i in reversed(xrange(k)):
if i =... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseKGroup(self, head, k):
"""List O(k*n) :param head: a ListNode :param k: an integer :return: ListNode"""
<|body_0|>
def generate_lst(self, node, k):
"""Helpder :param node: ListNode :param k: integer :return: list"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k_train_013841 | 1,813 | permissive | [
{
"docstring": "List O(k*n) :param head: a ListNode :param k: an integer :return: ListNode",
"name": "reverseKGroup",
"signature": "def reverseKGroup(self, head, k)"
},
{
"docstring": "Helpder :param node: ListNode :param k: integer :return: list",
"name": "generate_lst",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_016706 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseKGroup(self, head, k): List O(k*n) :param head: a ListNode :param k: an integer :return: ListNode
- def generate_lst(self, node, k): Helpder :param node: ListNode :par... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseKGroup(self, head, k): List O(k*n) :param head: a ListNode :param k: an integer :return: ListNode
- def generate_lst(self, node, k): Helpder :param node: ListNode :par... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class Solution:
def reverseKGroup(self, head, k):
"""List O(k*n) :param head: a ListNode :param k: an integer :return: ListNode"""
<|body_0|>
def generate_lst(self, node, k):
"""Helpder :param node: ListNode :param k: integer :return: list"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseKGroup(self, head, k):
"""List O(k*n) :param head: a ListNode :param k: an integer :return: ListNode"""
dummy = ListNode(0)
dummy.next = head
pre = dummy
cur_lst = self.generate_lst(pre.next, k)
while pre and (not None in cur_lst):
... | the_stack_v2_python_sparse | 024 Reverse Nodes in k-Group.py | Aminaba123/LeetCode | train | 1 | |
e9cccba0675c62448d83b5c9399b318575224ef2 | [
"property_user = False\nres = super(LandlordPartner, self).create(vals)\nif self._context.get('is_owner'):\n password = self.env['res.company'].browse(vals.get('company_id', False)).default_password\n if not password:\n password = ''\n create_user = self.env['res.users'].create({'login': vals.get('e... | <|body_start_0|>
property_user = False
res = super(LandlordPartner, self).create(vals)
if self._context.get('is_owner'):
password = self.env['res.company'].browse(vals.get('company_id', False)).default_password
if not password:
password = ''
cr... | LandlordPartner | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LandlordPartner:
def create(self, vals):
"""This Method is used to override orm create method. @param self: The object pointer @param vals: dictionary of fields value."""
<|body_0|>
def unlink(self):
"""Overrides orm unlink method. @param self: The object pointer @re... | stack_v2_sparse_classes_36k_train_013842 | 2,867 | no_license | [
{
"docstring": "This Method is used to override orm create method. @param self: The object pointer @param vals: dictionary of fields value.",
"name": "create",
"signature": "def create(self, vals)"
},
{
"docstring": "Overrides orm unlink method. @param self: The object pointer @return: True/Fals... | 2 | null | Implement the Python class `LandlordPartner` described below.
Class description:
Implement the LandlordPartner class.
Method signatures and docstrings:
- def create(self, vals): This Method is used to override orm create method. @param self: The object pointer @param vals: dictionary of fields value.
- def unlink(sel... | Implement the Python class `LandlordPartner` described below.
Class description:
Implement the LandlordPartner class.
Method signatures and docstrings:
- def create(self, vals): This Method is used to override orm create method. @param self: The object pointer @param vals: dictionary of fields value.
- def unlink(sel... | 163136f382faa8607db8fb6cda42a5ba07c4076b | <|skeleton|>
class LandlordPartner:
def create(self, vals):
"""This Method is used to override orm create method. @param self: The object pointer @param vals: dictionary of fields value."""
<|body_0|>
def unlink(self):
"""Overrides orm unlink method. @param self: The object pointer @re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LandlordPartner:
def create(self, vals):
"""This Method is used to override orm create method. @param self: The object pointer @param vals: dictionary of fields value."""
property_user = False
res = super(LandlordPartner, self).create(vals)
if self._context.get('is_owner'):
... | the_stack_v2_python_sparse | property_landlord_management_ee/models/res_partner.py | maarejsys/Roya | train | 0 | |
dff4eaac37a28fdf0fbb671a61dfcde33e94586c | [
"self._template_name = template_name\nself._bound_variable = bound_variable\nself._caller_variable = caller_variable",
"template_path = os.path.join(context['template_dir'], self._template_name)\ntry:\n old_value = django_template.resolve_variable(self._bound_variable, context)\nexcept django_template.Variable... | <|body_start_0|>
self._template_name = template_name
self._bound_variable = bound_variable
self._caller_variable = caller_variable
<|end_body_0|>
<|body_start_1|>
template_path = os.path.join(context['template_dir'], self._template_name)
try:
old_value = django_templ... | Django template Node holding data for writing a per language template. The TemplateNode is a variation of an include template that allows for per language lookup. The node * Looks up the template name w.r.t. the template_dir variable of the current context. The calling application must make sure template_dir is valid. ... | TemplateNode | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TemplateNode:
"""Django template Node holding data for writing a per language template. The TemplateNode is a variation of an include template that allows for per language lookup. The node * Looks up the template name w.r.t. the template_dir variable of the current context. The calling applicatio... | stack_v2_sparse_classes_36k_train_013843 | 30,278 | permissive | [
{
"docstring": "Construct the TemplateNode. Args: template_name: (str) the name of the template file. This will be resolved relative to the 'template_dir' element of the context. bound_variable: (str) the name of a variable to set in the context when we invoke the template. caller_variable: (str) the variable t... | 3 | stack_v2_sparse_classes_30k_train_000181 | Implement the Python class `TemplateNode` described below.
Class description:
Django template Node holding data for writing a per language template. The TemplateNode is a variation of an include template that allows for per language lookup. The node * Looks up the template name w.r.t. the template_dir variable of the ... | Implement the Python class `TemplateNode` described below.
Class description:
Django template Node holding data for writing a per language template. The TemplateNode is a variation of an include template that allows for per language lookup. The node * Looks up the template name w.r.t. the template_dir variable of the ... | 7dfbb468ea3d2fe3a8601bcbe9d1be5d411a825d | <|skeleton|>
class TemplateNode:
"""Django template Node holding data for writing a per language template. The TemplateNode is a variation of an include template that allows for per language lookup. The node * Looks up the template name w.r.t. the template_dir variable of the current context. The calling applicatio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TemplateNode:
"""Django template Node holding data for writing a per language template. The TemplateNode is a variation of an include template that allows for per language lookup. The node * Looks up the template name w.r.t. the template_dir variable of the current context. The calling application must make s... | the_stack_v2_python_sparse | google-apis-client-generator/src/googleapis/codegen/template_helpers.py | pombredanne/io-wraps | train | 0 |
e375ca820035a4f2d78c038878b1426bb4954552 | [
"if not root:\n return []\nlist = []\nq = queue.Queue()\nq.put(root)\nwhile not q.empty():\n node = q.get()\n list.append(node.val if node else None)\n if node:\n q.put(node.left)\n q.put(node.right)\nwhile list[-1] is None:\n list = list[:-1]\nreturn list",
"if len(data) == 0:\n r... | <|body_start_0|>
if not root:
return []
list = []
q = queue.Queue()
q.put(root)
while not q.empty():
node = q.get()
list.append(node.val if node else None)
if node:
q.put(node.left)
q.put(node.right)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str out = [] def helper(node): if node is None: out.append("null") return out.append(node.val) helper(node.left) helper(node.right) helper(root) return out"""
<|body_0|>
d... | stack_v2_sparse_classes_36k_train_013844 | 2,745 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str out = [] def helper(node): if node is None: out.append(\"null\") return out.append(node.val) helper(node.left) helper(node.right) helper(root) return out",
"name": "serialize",
"signature": "def serialize(self, root)"
... | 2 | stack_v2_sparse_classes_30k_train_018259 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str out = [] def helper(node): if node is None: out.append("null") return out.append(no... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str out = [] def helper(node): if node is None: out.append("null") return out.append(no... | 85128e7d26157b3c36eb43868269de42ea2fcb98 | <|skeleton|>
class Solution:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str out = [] def helper(node): if node is None: out.append("null") return out.append(node.val) helper(node.left) helper(node.right) helper(root) return out"""
<|body_0|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str out = [] def helper(node): if node is None: out.append("null") return out.append(node.val) helper(node.left) helper(node.right) helper(root) return out"""
if not root:
return... | the_stack_v2_python_sparse | src/SerializationTree.py | jsdiuf/leetcode | train | 1 | |
717d28b7767734427a0e20e7bbe61c1534c5098e | [
"try:\n result = f1_precision_recall(sm.graph, karma_sm.graph, DataNodeMode.IGNORE_LABEL_DATA_NODE)\nexcept PermutationExploding as e:\n logging.error('PermutationExploding at source: %s', sm.id)\n raise\nbijection = result['_bijection']\ntry:\n assert result['f1'] == 1.0 and None not in bijection.prime... | <|body_start_0|>
try:
result = f1_precision_recall(sm.graph, karma_sm.graph, DataNodeMode.IGNORE_LABEL_DATA_NODE)
except PermutationExploding as e:
logging.error('PermutationExploding at source: %s', sm.id)
raise
bijection = result['_bijection']
try:
... | SemanticModelAlignment | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SemanticModelAlignment:
def __init__(self, sm: SemanticModel, karma_sm: KarmaModel):
"""Our semantic model and karma semantic model represent same semantic structure, but only name of data nodes are changed. We want to build a mapping from data node id in karma_sm to data node id in our ... | stack_v2_sparse_classes_36k_train_013845 | 5,026 | permissive | [
{
"docstring": "Our semantic model and karma semantic model represent same semantic structure, but only name of data nodes are changed. We want to build a mapping from data node id in karma_sm to data node id in our sm, such that if we replace names of data nodes in karma_sm by name of data nodes in our sm; the... | 3 | null | Implement the Python class `SemanticModelAlignment` described below.
Class description:
Implement the SemanticModelAlignment class.
Method signatures and docstrings:
- def __init__(self, sm: SemanticModel, karma_sm: KarmaModel): Our semantic model and karma semantic model represent same semantic structure, but only n... | Implement the Python class `SemanticModelAlignment` described below.
Class description:
Implement the SemanticModelAlignment class.
Method signatures and docstrings:
- def __init__(self, sm: SemanticModel, karma_sm: KarmaModel): Our semantic model and karma semantic model represent same semantic structure, but only n... | b387584502ba1daa6abd6b7573828416f6426b49 | <|skeleton|>
class SemanticModelAlignment:
def __init__(self, sm: SemanticModel, karma_sm: KarmaModel):
"""Our semantic model and karma semantic model represent same semantic structure, but only name of data nodes are changed. We want to build a mapping from data node id in karma_sm to data node id in our ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SemanticModelAlignment:
def __init__(self, sm: SemanticModel, karma_sm: KarmaModel):
"""Our semantic model and karma semantic model represent same semantic structure, but only name of data nodes are changed. We want to build a mapping from data node id in karma_sm to data node id in our sm, such that ... | the_stack_v2_python_sparse | pysm/experiments/previous_work/mohsen_jws2015/app_extra.py | binh-vu/semantic-modeling | train | 5 | |
35df0c5c5822582db60793288d1af0332795c447 | [
"if definition is None:\n definition = RectDrawingBoxDefinition()\ndefinition = replace(definition, on_start=self.cache_selectable_boxes, on_change=self.handle_incomplete_selection_change, on_complete=self.handle_complete_selection)\nsuper(SelectionDrawingBox, self).__init__(definition, rect)\nself._cache: Set[S... | <|body_start_0|>
if definition is None:
definition = RectDrawingBoxDefinition()
definition = replace(definition, on_start=self.cache_selectable_boxes, on_change=self.handle_incomplete_selection_change, on_complete=self.handle_complete_selection)
super(SelectionDrawingBox, self).__ini... | A box that within its boundaries, any SelectableBox can be selected. This allows the user to drag to highlight or select many boxes at once. For example, this allows creation of a unit selection system. | SelectionDrawingBox | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelectionDrawingBox:
"""A box that within its boundaries, any SelectableBox can be selected. This allows the user to drag to highlight or select many boxes at once. For example, this allows creation of a unit selection system."""
def __init__(self, definition: Optional[RectDrawingBoxDefiniti... | stack_v2_sparse_classes_36k_train_013846 | 11,725 | permissive | [
{
"docstring": "Create a new SelectionDrawingBox. :param definition: Definition of this drawing box. The callbacks will be overridden. :param rect: Definition of the rectangle that a drag selection can be made within. If None, defaults to the entire window.",
"name": "__init__",
"signature": "def __init... | 4 | stack_v2_sparse_classes_30k_train_010369 | Implement the Python class `SelectionDrawingBox` described below.
Class description:
A box that within its boundaries, any SelectableBox can be selected. This allows the user to drag to highlight or select many boxes at once. For example, this allows creation of a unit selection system.
Method signatures and docstrin... | Implement the Python class `SelectionDrawingBox` described below.
Class description:
A box that within its boundaries, any SelectableBox can be selected. This allows the user to drag to highlight or select many boxes at once. For example, this allows creation of a unit selection system.
Method signatures and docstrin... | 541247482748300bbebf9bdec5ecdc19339fe665 | <|skeleton|>
class SelectionDrawingBox:
"""A box that within its boundaries, any SelectableBox can be selected. This allows the user to drag to highlight or select many boxes at once. For example, this allows creation of a unit selection system."""
def __init__(self, definition: Optional[RectDrawingBoxDefiniti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SelectionDrawingBox:
"""A box that within its boundaries, any SelectableBox can be selected. This allows the user to drag to highlight or select many boxes at once. For example, this allows creation of a unit selection system."""
def __init__(self, definition: Optional[RectDrawingBoxDefinition]=None, rec... | the_stack_v2_python_sparse | shimmer/components/selection.py | MartinHowarth/shimmer | train | 3 |
e8f5f83d0decce308c64fc03be1410deab912a39 | [
"super().__init__()\nself.models: dict[str, Any] = {}\nself.node_models: dict[int, str] = {}",
"model_class = self.models.get(model_name)\nif not model_class:\n raise ValueError(f'{model_name} is an invalid model')\nmodel_config = self.get_model_config(node_id, model_name)\nif not config:\n config = {}\nfor... | <|body_start_0|>
super().__init__()
self.models: dict[str, Any] = {}
self.node_models: dict[int, str] = {}
<|end_body_0|>
<|body_start_1|>
model_class = self.models.get(model_name)
if not model_class:
raise ValueError(f'{model_name} is an invalid model')
mode... | Helps handle setting models for nodes and managing their model configurations. | ModelManager | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelManager:
"""Helps handle setting models for nodes and managing their model configurations."""
def __init__(self) -> None:
"""Creates a ModelManager object."""
<|body_0|>
def set_model_config(self, node_id: int, model_name: str, config: dict[str, str]=None) -> None:
... | stack_v2_sparse_classes_36k_train_013847 | 11,690 | permissive | [
{
"docstring": "Creates a ModelManager object.",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Set configuration data for a model. :param node_id: node id to set model configuration for :param model_name: model to set configuration for :param config: configurat... | 5 | null | Implement the Python class `ModelManager` described below.
Class description:
Helps handle setting models for nodes and managing their model configurations.
Method signatures and docstrings:
- def __init__(self) -> None: Creates a ModelManager object.
- def set_model_config(self, node_id: int, model_name: str, config... | Implement the Python class `ModelManager` described below.
Class description:
Helps handle setting models for nodes and managing their model configurations.
Method signatures and docstrings:
- def __init__(self) -> None: Creates a ModelManager object.
- def set_model_config(self, node_id: int, model_name: str, config... | 20071eed2e73a2287aa385698dd604f4933ae7ff | <|skeleton|>
class ModelManager:
"""Helps handle setting models for nodes and managing their model configurations."""
def __init__(self) -> None:
"""Creates a ModelManager object."""
<|body_0|>
def set_model_config(self, node_id: int, model_name: str, config: dict[str, str]=None) -> None:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModelManager:
"""Helps handle setting models for nodes and managing their model configurations."""
def __init__(self) -> None:
"""Creates a ModelManager object."""
super().__init__()
self.models: dict[str, Any] = {}
self.node_models: dict[int, str] = {}
def set_model_... | the_stack_v2_python_sparse | daemon/core/config.py | coreemu/core | train | 606 |
f6a7f300706a53bca5b4ad4711ab8b6ec2d46f42 | [
"if kwargs.get('handler', 0) == 0:\n return (f'{url}', ComponentHandler, self.get_dict(**kwargs))\nelse:\n return (f'{url}', kwargs['handler'], self.get_dict(**kwargs))",
"result = kwargs\nif not kwargs.get('kind'):\n result['kind'] = 'default'\nreturn result"
] | <|body_start_0|>
if kwargs.get('handler', 0) == 0:
return (f'{url}', ComponentHandler, self.get_dict(**kwargs))
else:
return (f'{url}', kwargs['handler'], self.get_dict(**kwargs))
<|end_body_0|>
<|body_start_1|>
result = kwargs
if not kwargs.get('kind'):
... | ComponentFactory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComponentFactory:
def get_handler(self, url, **kwargs):
"""Return a handler to be packaged with tornado app"""
<|body_0|>
def get_dict(self, **kwargs):
"""Default values if desired"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if kwargs.get('handl... | stack_v2_sparse_classes_36k_train_013848 | 2,456 | no_license | [
{
"docstring": "Return a handler to be packaged with tornado app",
"name": "get_handler",
"signature": "def get_handler(self, url, **kwargs)"
},
{
"docstring": "Default values if desired",
"name": "get_dict",
"signature": "def get_dict(self, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003571 | Implement the Python class `ComponentFactory` described below.
Class description:
Implement the ComponentFactory class.
Method signatures and docstrings:
- def get_handler(self, url, **kwargs): Return a handler to be packaged with tornado app
- def get_dict(self, **kwargs): Default values if desired | Implement the Python class `ComponentFactory` described below.
Class description:
Implement the ComponentFactory class.
Method signatures and docstrings:
- def get_handler(self, url, **kwargs): Return a handler to be packaged with tornado app
- def get_dict(self, **kwargs): Default values if desired
<|skeleton|>
cla... | f70def8691c84150818c40ccc9d4cdceeb276d46 | <|skeleton|>
class ComponentFactory:
def get_handler(self, url, **kwargs):
"""Return a handler to be packaged with tornado app"""
<|body_0|>
def get_dict(self, **kwargs):
"""Default values if desired"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ComponentFactory:
def get_handler(self, url, **kwargs):
"""Return a handler to be packaged with tornado app"""
if kwargs.get('handler', 0) == 0:
return (f'{url}', ComponentHandler, self.get_dict(**kwargs))
else:
return (f'{url}', kwargs['handler'], self.get_dict... | the_stack_v2_python_sparse | peak/component.py | connorjrice/OSS | train | 1 | |
da64cd4a22491cf7765136aa96937e86b259cb61 | [
"dates = Balance.objects.filter(port_code__valid=True).values('date').order_by('date').distinct()\ndates = [x['date'] for x in dates]\ndates = quarter_end_in_date_series(dates)\nasset = Balance.objects.filter(port_code__valid=True, date__in=dates).values('date').annotate(s=Sum('asset'), c=Count('asset'))\nasset = [... | <|body_start_0|>
dates = Balance.objects.filter(port_code__valid=True).values('date').order_by('date').distinct()
dates = [x['date'] for x in dates]
dates = quarter_end_in_date_series(dates)
asset = Balance.objects.filter(port_code__valid=True, date__in=dates).values('date').annotate(s=S... | 全部sma产品盈亏分布情况 | ProfitAttribute | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfitAttribute:
"""全部sma产品盈亏分布情况"""
def quarter(request):
"""每季度增加资金 Args: request: Django request object Returns: 季度末新增资金"""
<|body_0|>
def profit(request):
"""全部sma产品盈亏分布情况 Args: request: Django request object Returns:"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_013849 | 7,448 | no_license | [
{
"docstring": "每季度增加资金 Args: request: Django request object Returns: 季度末新增资金",
"name": "quarter",
"signature": "def quarter(request)"
},
{
"docstring": "全部sma产品盈亏分布情况 Args: request: Django request object Returns:",
"name": "profit",
"signature": "def profit(request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017856 | Implement the Python class `ProfitAttribute` described below.
Class description:
全部sma产品盈亏分布情况
Method signatures and docstrings:
- def quarter(request): 每季度增加资金 Args: request: Django request object Returns: 季度末新增资金
- def profit(request): 全部sma产品盈亏分布情况 Args: request: Django request object Returns: | Implement the Python class `ProfitAttribute` described below.
Class description:
全部sma产品盈亏分布情况
Method signatures and docstrings:
- def quarter(request): 每季度增加资金 Args: request: Django request object Returns: 季度末新增资金
- def profit(request): 全部sma产品盈亏分布情况 Args: request: Django request object Returns:
<|skeleton|>
class ... | 99462cea1f8b027bc9e38d79a99e9194d1e72548 | <|skeleton|>
class ProfitAttribute:
"""全部sma产品盈亏分布情况"""
def quarter(request):
"""每季度增加资金 Args: request: Django request object Returns: 季度末新增资金"""
<|body_0|>
def profit(request):
"""全部sma产品盈亏分布情况 Args: request: Django request object Returns:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProfitAttribute:
"""全部sma产品盈亏分布情况"""
def quarter(request):
"""每季度增加资金 Args: request: Django request object Returns: 季度末新增资金"""
dates = Balance.objects.filter(port_code__valid=True).values('date').order_by('date').distinct()
dates = [x['date'] for x in dates]
dates = quarte... | the_stack_v2_python_sparse | investment/views/basic_info.py | rexcorp01/inv | train | 1 |
e2f84bba8734237973eac00fe8c80177bc20cf5d | [
"self.logger = logging.getLogger(base_logger + '.' + self.__class__.__name__)\nself.mount_point = mount_point\nself.auth_config = auth_config\nself.vault_client = vault_client\nself.auth_config_default = {'bind_secret_id': True, 'bound_cidr_list': [], 'local_secret_ids': False, 'period': 0, 'policies': [], 'secret_... | <|body_start_0|>
self.logger = logging.getLogger(base_logger + '.' + self.__class__.__name__)
self.mount_point = mount_point
self.auth_config = auth_config
self.vault_client = vault_client
self.auth_config_default = {'bind_secret_id': True, 'bound_cidr_list': [], 'local_secret_id... | Template configuration specific class | AuthMethodAppRole | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthMethodAppRole:
"""Template configuration specific class"""
def __init__(self, base_logger, mount_point, auth_config, vault_client):
""":param base_logger: main class name :type base_logger: string :param mount_point: auth method mount point :type mount_point: str :param auth_conf... | stack_v2_sparse_classes_36k_train_013850 | 5,331 | permissive | [
{
"docstring": ":param base_logger: main class name :type base_logger: string :param mount_point: auth method mount point :type mount_point: str :param auth_config: auth method specific configuration :type auth_config: dict",
"name": "__init__",
"signature": "def __init__(self, base_logger, mount_point,... | 6 | stack_v2_sparse_classes_30k_train_014315 | Implement the Python class `AuthMethodAppRole` described below.
Class description:
Template configuration specific class
Method signatures and docstrings:
- def __init__(self, base_logger, mount_point, auth_config, vault_client): :param base_logger: main class name :type base_logger: string :param mount_point: auth m... | Implement the Python class `AuthMethodAppRole` described below.
Class description:
Template configuration specific class
Method signatures and docstrings:
- def __init__(self, base_logger, mount_point, auth_config, vault_client): :param base_logger: main class name :type base_logger: string :param mount_point: auth m... | 3457e8c2487a0d9cba8362208df91b77024d7782 | <|skeleton|>
class AuthMethodAppRole:
"""Template configuration specific class"""
def __init__(self, base_logger, mount_point, auth_config, vault_client):
""":param base_logger: main class name :type base_logger: string :param mount_point: auth method mount point :type mount_point: str :param auth_conf... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuthMethodAppRole:
"""Template configuration specific class"""
def __init__(self, base_logger, mount_point, auth_config, vault_client):
""":param base_logger: main class name :type base_logger: string :param mount_point: auth method mount point :type mount_point: str :param auth_config: auth meth... | the_stack_v2_python_sparse | vaultmanager/lib/AuthMethods/AuthMethodAppRole.py | manuelaguilar/vault-manager | train | 0 |
8d00f6f2379b4c050501c270cd78756fa3737ac7 | [
"filters = filters or {}\nif not is_user_action_allowed('manage_others_tokens'):\n filters['_user_fk'] = current_user.id\nsm = get_storage_manager()\nresult = sm.list(models.Token, filters=filters, pagination=pagination, sort=sort)\nreturn result",
"_purge_expired_user_tokens()\nrequest_dict = get_json_and_ver... | <|body_start_0|>
filters = filters or {}
if not is_user_action_allowed('manage_others_tokens'):
filters['_user_fk'] = current_user.id
sm = get_storage_manager()
result = sm.list(models.Token, filters=filters, pagination=pagination, sort=sort)
return result
<|end_body_... | Tokens | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tokens:
def get(self, filters=None, pagination=None, sort=None):
"""Get a list of tokens."""
<|body_0|>
def post(self):
"""Create a new token."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
filters = filters or {}
if not is_user_action_allo... | stack_v2_sparse_classes_36k_train_013851 | 3,246 | permissive | [
{
"docstring": "Get a list of tokens.",
"name": "get",
"signature": "def get(self, filters=None, pagination=None, sort=None)"
},
{
"docstring": "Create a new token.",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005475 | Implement the Python class `Tokens` described below.
Class description:
Implement the Tokens class.
Method signatures and docstrings:
- def get(self, filters=None, pagination=None, sort=None): Get a list of tokens.
- def post(self): Create a new token. | Implement the Python class `Tokens` described below.
Class description:
Implement the Tokens class.
Method signatures and docstrings:
- def get(self, filters=None, pagination=None, sort=None): Get a list of tokens.
- def post(self): Create a new token.
<|skeleton|>
class Tokens:
def get(self, filters=None, pagi... | c0de6442e1d7653fad824d75e571802a74eee605 | <|skeleton|>
class Tokens:
def get(self, filters=None, pagination=None, sort=None):
"""Get a list of tokens."""
<|body_0|>
def post(self):
"""Create a new token."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Tokens:
def get(self, filters=None, pagination=None, sort=None):
"""Get a list of tokens."""
filters = filters or {}
if not is_user_action_allowed('manage_others_tokens'):
filters['_user_fk'] = current_user.id
sm = get_storage_manager()
result = sm.list(mode... | the_stack_v2_python_sparse | rest-service/manager_rest/rest/resources_v3_1/tokens.py | cloudify-cosmo/cloudify-manager | train | 146 | |
aadb23d90c0116aea1942077501b7d5fa726839f | [
"if not nums:\n return 0\ncurrSum = nums[0]\nmaxSum = nums[0]\nfor i in range(1, len(nums)):\n currSum = max(nums[i], nums[i] + currSum)\n maxSum = max(maxSum, currSum)\nreturn maxSum",
"if not nums:\n return []\ncurrSum = nums[0]\ncurrIdx = [0, 0]\nmaxSum = nums[0]\nres = [0, 0]\nstart = 0\nfor i in ... | <|body_start_0|>
if not nums:
return 0
currSum = nums[0]
maxSum = nums[0]
for i in range(1, len(nums)):
currSum = max(nums[i], nums[i] + currSum)
maxSum = max(maxSum, currSum)
return maxSum
<|end_body_0|>
<|body_start_1|>
if not nums:
... | Solution2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution2:
def maxSubArray(self, nums):
"""i, max local currSum ending at i update golbal maxSum"""
<|body_0|>
def maxSubArray_index(self, nums):
"""start: the start index of currSum ending at i currSum: [start, i]"""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_36k_train_013852 | 2,233 | no_license | [
{
"docstring": "i, max local currSum ending at i update golbal maxSum",
"name": "maxSubArray",
"signature": "def maxSubArray(self, nums)"
},
{
"docstring": "start: the start index of currSum ending at i currSum: [start, i]",
"name": "maxSubArray_index",
"signature": "def maxSubArray_inde... | 2 | stack_v2_sparse_classes_30k_test_000540 | Implement the Python class `Solution2` described below.
Class description:
Implement the Solution2 class.
Method signatures and docstrings:
- def maxSubArray(self, nums): i, max local currSum ending at i update golbal maxSum
- def maxSubArray_index(self, nums): start: the start index of currSum ending at i currSum: [... | Implement the Python class `Solution2` described below.
Class description:
Implement the Solution2 class.
Method signatures and docstrings:
- def maxSubArray(self, nums): i, max local currSum ending at i update golbal maxSum
- def maxSubArray_index(self, nums): start: the start index of currSum ending at i currSum: [... | 63120dbaabd7c3c19633ebe952bcee4cf826b0e0 | <|skeleton|>
class Solution2:
def maxSubArray(self, nums):
"""i, max local currSum ending at i update golbal maxSum"""
<|body_0|>
def maxSubArray_index(self, nums):
"""start: the start index of currSum ending at i currSum: [start, i]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution2:
def maxSubArray(self, nums):
"""i, max local currSum ending at i update golbal maxSum"""
if not nums:
return 0
currSum = nums[0]
maxSum = nums[0]
for i in range(1, len(nums)):
currSum = max(nums[i], nums[i] + currSum)
maxSu... | the_stack_v2_python_sparse | 53. Maximum Subarray _ divide and conquer.py | CaizhiXu/LeetCode-Python-Solutions | train | 0 | |
396eaeace6c7022357e6e014ffe3947b8fc36954 | [
"type_id = self.data.resource_type_id or -1\nquery = Query(ResourceType.collection, service_id=self._client.service_id)\nquery.add_term(field=ResourceType.id_field, value=type_id)\nreturn InstanceProxy(ResourceType, query, client=self._client)",
"query = Query(AbilityType.collection, service_id=self._client.servi... | <|body_start_0|>
type_id = self.data.resource_type_id or -1
query = Query(ResourceType.collection, service_id=self._client.service_id)
query.add_term(field=ResourceType.id_field, value=type_id)
return InstanceProxy(ResourceType, query, client=self._client)
<|end_body_0|>
<|body_start_1|... | An ability triggered by a character or vehicle. See the corresponding :class:`~auraxium.ps2.AbilityType` instance via the :meth:`Ability.type` method for information on generic parameters. .. note:: The in-game mechanics these abilities correspond to is currently undocumented due to the lack of links between abilities ... | Ability | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ability:
"""An ability triggered by a character or vehicle. See the corresponding :class:`~auraxium.ps2.AbilityType` instance via the :meth:`Ability.type` method for information on generic parameters. .. note:: The in-game mechanics these abilities correspond to is currently undocumented due to t... | stack_v2_sparse_classes_36k_train_013853 | 9,409 | permissive | [
{
"docstring": "Return the resource type used by this ability, if any. This returns an :class:`auraxium.InstanceProxy`.",
"name": "resource_type",
"signature": "def resource_type(self) -> InstanceProxy[ResourceType]"
},
{
"docstring": "Return the ability type of this ability. This returns an :cl... | 2 | stack_v2_sparse_classes_30k_train_019761 | Implement the Python class `Ability` described below.
Class description:
An ability triggered by a character or vehicle. See the corresponding :class:`~auraxium.ps2.AbilityType` instance via the :meth:`Ability.type` method for information on generic parameters. .. note:: The in-game mechanics these abilities correspon... | Implement the Python class `Ability` described below.
Class description:
An ability triggered by a character or vehicle. See the corresponding :class:`~auraxium.ps2.AbilityType` instance via the :meth:`Ability.type` method for information on generic parameters. .. note:: The in-game mechanics these abilities correspon... | 23dcf927a199c8d7c917d89fe96b470a34cf4bba | <|skeleton|>
class Ability:
"""An ability triggered by a character or vehicle. See the corresponding :class:`~auraxium.ps2.AbilityType` instance via the :meth:`Ability.type` method for information on generic parameters. .. note:: The in-game mechanics these abilities correspond to is currently undocumented due to t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ability:
"""An ability triggered by a character or vehicle. See the corresponding :class:`~auraxium.ps2.AbilityType` instance via the :meth:`Ability.type` method for information on generic parameters. .. note:: The in-game mechanics these abilities correspond to is currently undocumented due to the lack of li... | the_stack_v2_python_sparse | auraxium/ps2/_ability.py | leonhard-s/auraxium | train | 29 |
a8c11570b94193c8370ebadd8141b264e19949c7 | [
"super(Application, self).__init__(master)\nself.grid()\nself.create_widgets()",
"bttn1 = Button(self, text='I am doing nothing!')\nbttn1.grid()\nbttn2 = Button(self)\nbttn2.grid()\nbttn2.configure(text='Me too')\nbttn3 = Button(self)\nbttn3.grid()\nbttn3['text'] = 'And me!'"
] | <|body_start_0|>
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
<|end_body_0|>
<|body_start_1|>
bttn1 = Button(self, text='I am doing nothing!')
bttn1.grid()
bttn2 = Button(self)
bttn2.grid()
bttn2.configure(text='Me too')
... | GUI app with 3 buttons | Application | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Application:
"""GUI app with 3 buttons"""
def __init__(self, master):
"""Frame initiation"""
<|body_0|>
def create_widgets(self):
"""Creates 3 useless buttons"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(Application, self).__init__(mast... | stack_v2_sparse_classes_36k_train_013854 | 726 | no_license | [
{
"docstring": "Frame initiation",
"name": "__init__",
"signature": "def __init__(self, master)"
},
{
"docstring": "Creates 3 useless buttons",
"name": "create_widgets",
"signature": "def create_widgets(self)"
}
] | 2 | null | Implement the Python class `Application` described below.
Class description:
GUI app with 3 buttons
Method signatures and docstrings:
- def __init__(self, master): Frame initiation
- def create_widgets(self): Creates 3 useless buttons | Implement the Python class `Application` described below.
Class description:
GUI app with 3 buttons
Method signatures and docstrings:
- def __init__(self, master): Frame initiation
- def create_widgets(self): Creates 3 useless buttons
<|skeleton|>
class Application:
"""GUI app with 3 buttons"""
def __init__... | 19343c985f368770dc01ce415506506d62a23285 | <|skeleton|>
class Application:
"""GUI app with 3 buttons"""
def __init__(self, master):
"""Frame initiation"""
<|body_0|>
def create_widgets(self):
"""Creates 3 useless buttons"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Application:
"""GUI app with 3 buttons"""
def __init__(self, master):
"""Frame initiation"""
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
"""Creates 3 useless buttons"""
bttn1 = Button(self, text... | the_stack_v2_python_sparse | gui/lazy_buttons_class.py | gofr1/python-learning | train | 0 |
d3c4973ebb4599aae04a88b822e28d65139846dc | [
"active_object = context.active_object\nif active_object and active_object.type == 'ARMATURE' and active_object.animation_data:\n action = active_object.animation_data.action\n if action:\n _animation_utils.set_fps_for_preview(context.scene, self.length, self.anim_start, self.anim_end)",
"active_obje... | <|body_start_0|>
active_object = context.active_object
if active_object and active_object.type == 'ARMATURE' and active_object.animation_data:
action = active_object.animation_data.action
if action:
_animation_utils.set_fps_for_preview(context.scene, self.length, ... | Animation property inventory, which gets saved into *.blend file. | ObjectAnimationInventoryItem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectAnimationInventoryItem:
"""Animation property inventory, which gets saved into *.blend file."""
def length_update(self, context):
"""If the total time for animation is tweaked, FPS value is recalculated to keep the playback speed as close as possible to the resulting playback s... | stack_v2_sparse_classes_36k_train_013855 | 48,834 | no_license | [
{
"docstring": "If the total time for animation is tweaked, FPS value is recalculated to keep the playback speed as close as possible to the resulting playback speed in the game engine. :param context: Blender Context :type context: bpy.types.Context",
"name": "length_update",
"signature": "def length_u... | 3 | stack_v2_sparse_classes_30k_train_018057 | Implement the Python class `ObjectAnimationInventoryItem` described below.
Class description:
Animation property inventory, which gets saved into *.blend file.
Method signatures and docstrings:
- def length_update(self, context): If the total time for animation is tweaked, FPS value is recalculated to keep the playba... | Implement the Python class `ObjectAnimationInventoryItem` described below.
Class description:
Animation property inventory, which gets saved into *.blend file.
Method signatures and docstrings:
- def length_update(self, context): If the total time for animation is tweaked, FPS value is recalculated to keep the playba... | 7b796d30dfd22b7706a93e4419ed913d18d29a44 | <|skeleton|>
class ObjectAnimationInventoryItem:
"""Animation property inventory, which gets saved into *.blend file."""
def length_update(self, context):
"""If the total time for animation is tweaked, FPS value is recalculated to keep the playback speed as close as possible to the resulting playback s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ObjectAnimationInventoryItem:
"""Animation property inventory, which gets saved into *.blend file."""
def length_update(self, context):
"""If the total time for animation is tweaked, FPS value is recalculated to keep the playback speed as close as possible to the resulting playback speed in the g... | the_stack_v2_python_sparse | All_In_One/addons/io_scs_tools/properties/object.py | 2434325680/Learnbgame | train | 0 |
74b1fa3e9a976311979e1c49b3659036856f89ab | [
"database.drop_tables([Customer])\ndatabase.create_tables([Customer])\nLOGGER.info('test setup complete')",
"pass\nadd_customer(self.customer_111[0], self.customer_111[1], self.customer_111[2], self.customer_111[3], self.customer_111[4], self.customer_111[5], self.customer_111[6], self.customer_111[7])\ncustomer ... | <|body_start_0|>
database.drop_tables([Customer])
database.create_tables([Customer])
LOGGER.info('test setup complete')
<|end_body_0|>
<|body_start_1|>
pass
add_customer(self.customer_111[0], self.customer_111[1], self.customer_111[2], self.customer_111[3], self.customer_111[4],... | testing basic operation | SuiteOfTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SuiteOfTests:
"""testing basic operation"""
def setUp(self):
"""sets up the database"""
<|body_0|>
def test_add_customer(self):
"""test add customer"""
<|body_1|>
def test_search_customer(self):
"""test search customer"""
<|body_2|>
... | stack_v2_sparse_classes_36k_train_013856 | 5,744 | no_license | [
{
"docstring": "sets up the database",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "test add customer",
"name": "test_add_customer",
"signature": "def test_add_customer(self)"
},
{
"docstring": "test search customer",
"name": "test_search_customer",
... | 6 | stack_v2_sparse_classes_30k_train_018409 | Implement the Python class `SuiteOfTests` described below.
Class description:
testing basic operation
Method signatures and docstrings:
- def setUp(self): sets up the database
- def test_add_customer(self): test add customer
- def test_search_customer(self): test search customer
- def test_delete_customer(self): test... | Implement the Python class `SuiteOfTests` described below.
Class description:
testing basic operation
Method signatures and docstrings:
- def setUp(self): sets up the database
- def test_add_customer(self): test add customer
- def test_search_customer(self): test search customer
- def test_delete_customer(self): test... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class SuiteOfTests:
"""testing basic operation"""
def setUp(self):
"""sets up the database"""
<|body_0|>
def test_add_customer(self):
"""test add customer"""
<|body_1|>
def test_search_customer(self):
"""test search customer"""
<|body_2|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SuiteOfTests:
"""testing basic operation"""
def setUp(self):
"""sets up the database"""
database.drop_tables([Customer])
database.create_tables([Customer])
LOGGER.info('test setup complete')
def test_add_customer(self):
"""test add customer"""
pass
... | the_stack_v2_python_sparse | students/mmancini/lesson03/test_basic_operations.py | JavaRod/SP_Python220B_2019 | train | 1 |
e3f1e91a022165a526299378047d7249c65a6eaa | [
"username = request.GET.get('username', None)\nif username is not None:\n tutor = get_object_or_404(Tutor, user__username=username)\n serializer = TutorSerializer(tutor)\n return JsonResponse({'tutors': [serializer.data]}, safe=False)\nelse:\n tutors = Tutor.objects.all()\n serializer = TutorSerializ... | <|body_start_0|>
username = request.GET.get('username', None)
if username is not None:
tutor = get_object_or_404(Tutor, user__username=username)
serializer = TutorSerializer(tutor)
return JsonResponse({'tutors': [serializer.data]}, safe=False)
else:
... | 导员view | Tutors | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tutors:
"""导员view"""
def get(self, request):
"""查询导员"""
<|body_0|>
def post(self, request):
"""增加导员"""
<|body_1|>
def delete(self, request):
"""删除导员"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
username = request.GET.get(... | stack_v2_sparse_classes_36k_train_013857 | 16,053 | permissive | [
{
"docstring": "查询导员",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "增加导员",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "删除导员",
"name": "delete",
"signature": "def delete(self, request)"
}
] | 3 | stack_v2_sparse_classes_30k_train_006432 | Implement the Python class `Tutors` described below.
Class description:
导员view
Method signatures and docstrings:
- def get(self, request): 查询导员
- def post(self, request): 增加导员
- def delete(self, request): 删除导员 | Implement the Python class `Tutors` described below.
Class description:
导员view
Method signatures and docstrings:
- def get(self, request): 查询导员
- def post(self, request): 增加导员
- def delete(self, request): 删除导员
<|skeleton|>
class Tutors:
"""导员view"""
def get(self, request):
"""查询导员"""
<|body_... | 7aaa1be773718de1beb3ce0080edca7c4114b7ad | <|skeleton|>
class Tutors:
"""导员view"""
def get(self, request):
"""查询导员"""
<|body_0|>
def post(self, request):
"""增加导员"""
<|body_1|>
def delete(self, request):
"""删除导员"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Tutors:
"""导员view"""
def get(self, request):
"""查询导员"""
username = request.GET.get('username', None)
if username is not None:
tutor = get_object_or_404(Tutor, user__username=username)
serializer = TutorSerializer(tutor)
return JsonResponse({'tut... | the_stack_v2_python_sparse | user/views.py | MIXISAMA/MIS-backend | train | 0 |
286e80eca3e0fb101c9fb512381f2c6b3533f827 | [
"memo = {}\n\ndef rec(node: TreeNode, parent_covered: bool, covered: bool) -> int:\n key = (id(node), parent_covered, covered)\n if key in memo:\n return memo[key]\n if not node:\n return 0\n if not node.left and (not node.right) and (not covered):\n return 1\n ret = 1 + rec(node... | <|body_start_0|>
memo = {}
def rec(node: TreeNode, parent_covered: bool, covered: bool) -> int:
key = (id(node), parent_covered, covered)
if key in memo:
return memo[key]
if not node:
return 0
if not node.left and (not node... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minCameraCover(self, root: TreeNode) -> int:
"""06/05/2021 19:46 Top down Time complexity: O(3*n) Space complexity: O(3*n)"""
<|body_0|>
def minCameraCover(self, root: TreeNode) -> int:
"""06/05/2021 19:58 Greedy bottom up Time complexity: O(n) Space co... | stack_v2_sparse_classes_36k_train_013858 | 11,670 | no_license | [
{
"docstring": "06/05/2021 19:46 Top down Time complexity: O(3*n) Space complexity: O(3*n)",
"name": "minCameraCover",
"signature": "def minCameraCover(self, root: TreeNode) -> int"
},
{
"docstring": "06/05/2021 19:58 Greedy bottom up Time complexity: O(n) Space complexity: O(logn) (call stack)"... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minCameraCover(self, root: TreeNode) -> int: 06/05/2021 19:46 Top down Time complexity: O(3*n) Space complexity: O(3*n)
- def minCameraCover(self, root: TreeNode) -> int: 06/... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minCameraCover(self, root: TreeNode) -> int: 06/05/2021 19:46 Top down Time complexity: O(3*n) Space complexity: O(3*n)
- def minCameraCover(self, root: TreeNode) -> int: 06/... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def minCameraCover(self, root: TreeNode) -> int:
"""06/05/2021 19:46 Top down Time complexity: O(3*n) Space complexity: O(3*n)"""
<|body_0|>
def minCameraCover(self, root: TreeNode) -> int:
"""06/05/2021 19:58 Greedy bottom up Time complexity: O(n) Space co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minCameraCover(self, root: TreeNode) -> int:
"""06/05/2021 19:46 Top down Time complexity: O(3*n) Space complexity: O(3*n)"""
memo = {}
def rec(node: TreeNode, parent_covered: bool, covered: bool) -> int:
key = (id(node), parent_covered, covered)
... | the_stack_v2_python_sparse | leetcode/solved/1008_Binary_Tree_Cameras/solution.py | sungminoh/algorithms | train | 0 | |
7ae12fa8ca362aec23f93f4a71963e3a11f407bb | [
"self.count = count\nself.day = day\nself.time = time",
"if dictionary is None:\n return None\ncount = dictionary.get('count')\nday = dictionary.get('day')\ntime = cohesity_management_sdk.models.time.Time.from_dictionary(dictionary.get('time')) if dictionary.get('time') else None\nreturn cls(count, day, time)"... | <|body_start_0|>
self.count = count
self.day = day
self.time = time
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
count = dictionary.get('count')
day = dictionary.get('day')
time = cohesity_management_sdk.models.time.Time.from_dic... | Implementation of the 'BackupPolicyProto_MonthlySchedule' model. TODO: type description here. Attributes: count (int): Count of the day on which to perform the backup (look above for a more detailed description). day (int): The day of the month the backup is to be performed. time (Time): Time when the monthly backup sh... | BackupPolicyProto_MonthlySchedule | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BackupPolicyProto_MonthlySchedule:
"""Implementation of the 'BackupPolicyProto_MonthlySchedule' model. TODO: type description here. Attributes: count (int): Count of the day on which to perform the backup (look above for a more detailed description). day (int): The day of the month the backup is ... | stack_v2_sparse_classes_36k_train_013859 | 1,934 | permissive | [
{
"docstring": "Constructor for the BackupPolicyProto_MonthlySchedule class",
"name": "__init__",
"signature": "def __init__(self, count=None, day=None, time=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation o... | 2 | null | Implement the Python class `BackupPolicyProto_MonthlySchedule` described below.
Class description:
Implementation of the 'BackupPolicyProto_MonthlySchedule' model. TODO: type description here. Attributes: count (int): Count of the day on which to perform the backup (look above for a more detailed description). day (in... | Implement the Python class `BackupPolicyProto_MonthlySchedule` described below.
Class description:
Implementation of the 'BackupPolicyProto_MonthlySchedule' model. TODO: type description here. Attributes: count (int): Count of the day on which to perform the backup (look above for a more detailed description). day (in... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class BackupPolicyProto_MonthlySchedule:
"""Implementation of the 'BackupPolicyProto_MonthlySchedule' model. TODO: type description here. Attributes: count (int): Count of the day on which to perform the backup (look above for a more detailed description). day (int): The day of the month the backup is ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BackupPolicyProto_MonthlySchedule:
"""Implementation of the 'BackupPolicyProto_MonthlySchedule' model. TODO: type description here. Attributes: count (int): Count of the day on which to perform the backup (look above for a more detailed description). day (int): The day of the month the backup is to be perform... | the_stack_v2_python_sparse | cohesity_management_sdk/models/backup_policy_proto_monthly_schedule.py | cohesity/management-sdk-python | train | 24 |
40efd793900f976491d2e15b2e892cc8d253cdf0 | [
"list_id = [[None, 'All']]\nfor firm in Firm.objects.all():\n list_id.append([firm.pk, firm.name])\nreturn list_id",
"if self.value() is None:\n return queryset.all()\nreturn queryset.filter(firm__pk=self.value())"
] | <|body_start_0|>
list_id = [[None, 'All']]
for firm in Firm.objects.all():
list_id.append([firm.pk, firm.name])
return list_id
<|end_body_0|>
<|body_start_1|>
if self.value() is None:
return queryset.all()
return queryset.filter(firm__pk=self.value())
<|e... | FirmFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FirmFilter:
def lookups(self, request, model_admin):
"""Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar."""
... | stack_v2_sparse_classes_36k_train_013860 | 12,508 | no_license | [
{
"docstring": "Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar.",
"name": "lookups",
"signature": "def lookups(self, request,... | 2 | stack_v2_sparse_classes_30k_train_017084 | Implement the Python class `FirmFilter` described below.
Class description:
Implement the FirmFilter class.
Method signatures and docstrings:
- def lookups(self, request, model_admin): Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The se... | Implement the Python class `FirmFilter` described below.
Class description:
Implement the FirmFilter class.
Method signatures and docstrings:
- def lookups(self, request, model_admin): Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The se... | fa31fa82505c3d0fbc54bd8436cfc0e49c896f3e | <|skeleton|>
class FirmFilter:
def lookups(self, request, model_admin):
"""Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FirmFilter:
def lookups(self, request, model_admin):
"""Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar."""
list_id ... | the_stack_v2_python_sparse | main/admin.py | WealthCity/django-project | train | 0 | |
afbf66a95c0e03a7cf7c62ee46ac455342b62150 | [
"self.a = a.copy()\nself.ind = ind.copy()\nself.a_low = a_low\nself.ang_thr = ang_thr\nself.step_sz = step_sz\nself.length_thr = length_thr\nself.total_weight = total_weight\nself.max_points = max_points\nif len(self.a.shape) == 3:\n self.a.shape = self.a.shape + (1,)\n self.ind.shape = self.ind.shape + (1,)\... | <|body_start_0|>
self.a = a.copy()
self.ind = ind.copy()
self.a_low = a_low
self.ang_thr = ang_thr
self.step_sz = step_sz
self.length_thr = length_thr
self.total_weight = total_weight
self.max_points = max_points
if len(self.a.shape) == 3:
... | Euler Delta Crossings Generates tracks with termination criteria defined by a delta function [1]_ and it has similarities with FACT algorithm [2]_ and Basser's method but uses trilinear interpolation. Can be used with any reconstruction method as DTI, DSI, QBI, GQI which can calculate an orientation distribution functi... | EuDX | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EuDX:
"""Euler Delta Crossings Generates tracks with termination criteria defined by a delta function [1]_ and it has similarities with FACT algorithm [2]_ and Basser's method but uses trilinear interpolation. Can be used with any reconstruction method as DTI, DSI, QBI, GQI which can calculate an... | stack_v2_sparse_classes_36k_train_013861 | 6,850 | permissive | [
{
"docstring": "Euler integration with multiple stopping criteria and supporting multiple multiple fibres in crossings [1]. [1] E. Garyfallidis (2012), \"Towards an accurate brain tractography\", PhD thesis, University of Cambridge, UK. Parameters ------------ a : array, shape(x,y,z,Np) magnitude of the peak of... | 2 | stack_v2_sparse_classes_30k_train_006143 | Implement the Python class `EuDX` described below.
Class description:
Euler Delta Crossings Generates tracks with termination criteria defined by a delta function [1]_ and it has similarities with FACT algorithm [2]_ and Basser's method but uses trilinear interpolation. Can be used with any reconstruction method as DT... | Implement the Python class `EuDX` described below.
Class description:
Euler Delta Crossings Generates tracks with termination criteria defined by a delta function [1]_ and it has similarities with FACT algorithm [2]_ and Basser's method but uses trilinear interpolation. Can be used with any reconstruction method as DT... | 4341b734995d6f51ac9c16df26a7de00c46f57ef | <|skeleton|>
class EuDX:
"""Euler Delta Crossings Generates tracks with termination criteria defined by a delta function [1]_ and it has similarities with FACT algorithm [2]_ and Basser's method but uses trilinear interpolation. Can be used with any reconstruction method as DTI, DSI, QBI, GQI which can calculate an... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EuDX:
"""Euler Delta Crossings Generates tracks with termination criteria defined by a delta function [1]_ and it has similarities with FACT algorithm [2]_ and Basser's method but uses trilinear interpolation. Can be used with any reconstruction method as DTI, DSI, QBI, GQI which can calculate an orientation ... | the_stack_v2_python_sparse | dipy/tracking/eudx.py | Garyfallidis/dipy | train | 7 |
29bee96d22ebc987e0b9d825a56b48e619d833bf | [
"self._miner = miner\nself._analyst = analyst\nself._logger = logger",
"self._logger.info('Get query.')\nurl = json_obj[Token.URL]\ndoc_id = self._miner.get_doc_identity_by_url(url)\nif doc_id.idid < 0:\n return {}\nrel_doc_ids = self._analyst.get_doc_rel_info(doc_id)\nf = lambda x: {Token.URL: self._miner.get... | <|body_start_0|>
self._miner = miner
self._analyst = analyst
self._logger = logger
<|end_body_0|>
<|body_start_1|>
self._logger.info('Get query.')
url = json_obj[Token.URL]
doc_id = self._miner.get_doc_identity_by_url(url)
if doc_id.idid < 0:
return {... | Handler handles the query json question and return the result. Attributes: _miner: An instane of `miner.Miner`. _analyst: An instance of `article_analyst.ArticleAnalyst`. _logger: The logger. | MainHandler | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MainHandler:
"""Handler handles the query json question and return the result. Attributes: _miner: An instane of `miner.Miner`. _analyst: An instance of `article_analyst.ArticleAnalyst`. _logger: The logger."""
def __init__(self, miner, analyst, logger):
"""Constructor. Args: miner: ... | stack_v2_sparse_classes_36k_train_013862 | 2,170 | permissive | [
{
"docstring": "Constructor. Args: miner: An instane of `miner.Miner`. analyst: An instance of `article_analyst.ArticleAnalyst`. logger: The logger.",
"name": "__init__",
"signature": "def __init__(self, miner, analyst, logger)"
},
{
"docstring": "Handles the json query and returns the result. A... | 2 | null | Implement the Python class `MainHandler` described below.
Class description:
Handler handles the query json question and return the result. Attributes: _miner: An instane of `miner.Miner`. _analyst: An instance of `article_analyst.ArticleAnalyst`. _logger: The logger.
Method signatures and docstrings:
- def __init__(... | Implement the Python class `MainHandler` described below.
Class description:
Handler handles the query json question and return the result. Attributes: _miner: An instane of `miner.Miner`. _analyst: An instance of `article_analyst.ArticleAnalyst`. _logger: The logger.
Method signatures and docstrings:
- def __init__(... | 4ee5cf9dbc6d28b9b08f648a05705a0ac82d7aad | <|skeleton|>
class MainHandler:
"""Handler handles the query json question and return the result. Attributes: _miner: An instane of `miner.Miner`. _analyst: An instance of `article_analyst.ArticleAnalyst`. _logger: The logger."""
def __init__(self, miner, analyst, logger):
"""Constructor. Args: miner: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MainHandler:
"""Handler handles the query json question and return the result. Attributes: _miner: An instane of `miner.Miner`. _analyst: An instance of `article_analyst.ArticleAnalyst`. _logger: The logger."""
def __init__(self, miner, analyst, logger):
"""Constructor. Args: miner: An instane of... | the_stack_v2_python_sparse | src/app_server/modules/main_handler.py | cathook/PTTArticleRecommender | train | 0 |
d060e1950999fca46935be19d9df5ef6d72d169b | [
"super().__init__()\nself.in_channels = in_channels // 2\nself.out_channels = out_channels // 2\nself.kernel_size = kernel_size\nself.stride = stride\nself.padding = padding\nself.groups = groups\nself.dilation = dilation\nself.real_conv = nn.Conv2d(self.in_channels, self.out_channels, kernel_size=self.kernel_size,... | <|body_start_0|>
super().__init__()
self.in_channels = in_channels // 2
self.out_channels = out_channels // 2
self.kernel_size = kernel_size
self.stride = stride
self.padding = padding
self.groups = groups
self.dilation = dilation
self.real_conv = ... | ComplexConv2d | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComplexConv2d:
def __init__(self, in_channels: int, out_channels: int, kernel_size: Tuple[int, int]=(1, 1), stride: Tuple[int, int]=(1, 1), padding: Tuple[int, int]=(0, 0), groups: int=1, dilation: int=1):
"""Complex Conv2d (non-causal)"""
<|body_0|>
def forward(self, input)... | stack_v2_sparse_classes_36k_train_013863 | 28,878 | no_license | [
{
"docstring": "Complex Conv2d (non-causal)",
"name": "__init__",
"signature": "def __init__(self, in_channels: int, out_channels: int, kernel_size: Tuple[int, int]=(1, 1), stride: Tuple[int, int]=(1, 1), padding: Tuple[int, int]=(0, 0), groups: int=1, dilation: int=1)"
},
{
"docstring": "comple... | 2 | null | Implement the Python class `ComplexConv2d` described below.
Class description:
Implement the ComplexConv2d class.
Method signatures and docstrings:
- def __init__(self, in_channels: int, out_channels: int, kernel_size: Tuple[int, int]=(1, 1), stride: Tuple[int, int]=(1, 1), padding: Tuple[int, int]=(0, 0), groups: in... | Implement the Python class `ComplexConv2d` described below.
Class description:
Implement the ComplexConv2d class.
Method signatures and docstrings:
- def __init__(self, in_channels: int, out_channels: int, kernel_size: Tuple[int, int]=(1, 1), stride: Tuple[int, int]=(1, 1), padding: Tuple[int, int]=(0, 0), groups: in... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class ComplexConv2d:
def __init__(self, in_channels: int, out_channels: int, kernel_size: Tuple[int, int]=(1, 1), stride: Tuple[int, int]=(1, 1), padding: Tuple[int, int]=(0, 0), groups: int=1, dilation: int=1):
"""Complex Conv2d (non-causal)"""
<|body_0|>
def forward(self, input)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ComplexConv2d:
def __init__(self, in_channels: int, out_channels: int, kernel_size: Tuple[int, int]=(1, 1), stride: Tuple[int, int]=(1, 1), padding: Tuple[int, int]=(0, 0), groups: int=1, dilation: int=1):
"""Complex Conv2d (non-causal)"""
super().__init__()
self.in_channels = in_chann... | the_stack_v2_python_sparse | generated/test_shahules786_mayavoz.py | jansel/pytorch-jit-paritybench | train | 35 | |
5f854f0d5fe399a709df7b00302570419ede7069 | [
"stack = []\ni = 0\nwhile i < len(pushV) and pushV[i] != popV[0]:\n stack.append(pushV[i])\n i += 1\ni += 1\nfor j in range(1, len(popV)):\n if popV[j] > popV[j - 1]:\n while pushV[i] != popV[j]:\n stack.append(pushV[i])\n i += 1\n i += 1\n else:\n element = st... | <|body_start_0|>
stack = []
i = 0
while i < len(pushV) and pushV[i] != popV[0]:
stack.append(pushV[i])
i += 1
i += 1
for j in range(1, len(popV)):
if popV[j] > popV[j - 1]:
while pushV[i] != popV[j]:
stack.ap... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def IsPopOrder(self, pushV, popV):
""":param pushV: :param popV: :return:"""
<|body_0|>
def IsPopOrder_concise(self, pushV, popV):
"""time O(n) space O(n) :param pushV: :param popV: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_013864 | 1,826 | no_license | [
{
"docstring": ":param pushV: :param popV: :return:",
"name": "IsPopOrder",
"signature": "def IsPopOrder(self, pushV, popV)"
},
{
"docstring": "time O(n) space O(n) :param pushV: :param popV: :return:",
"name": "IsPopOrder_concise",
"signature": "def IsPopOrder_concise(self, pushV, popV)... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def IsPopOrder(self, pushV, popV): :param pushV: :param popV: :return:
- def IsPopOrder_concise(self, pushV, popV): time O(n) space O(n) :param pushV: :param popV: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def IsPopOrder(self, pushV, popV): :param pushV: :param popV: :return:
- def IsPopOrder_concise(self, pushV, popV): time O(n) space O(n) :param pushV: :param popV: :return:
<|sk... | 85f71621c54f6b0029f3a2746f022f89dd7419d9 | <|skeleton|>
class Solution:
def IsPopOrder(self, pushV, popV):
""":param pushV: :param popV: :return:"""
<|body_0|>
def IsPopOrder_concise(self, pushV, popV):
"""time O(n) space O(n) :param pushV: :param popV: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def IsPopOrder(self, pushV, popV):
""":param pushV: :param popV: :return:"""
stack = []
i = 0
while i < len(pushV) and pushV[i] != popV[0]:
stack.append(pushV[i])
i += 1
i += 1
for j in range(1, len(popV)):
if popV[j... | the_stack_v2_python_sparse | LeetCode/Offer/栈的压入弹出序列.py | XyK0907/for_work | train | 0 | |
3ef81a0d6c870bb318567c05f2377cf0b50ff0a4 | [
"super(DerivativeDetector, self).__init__(self.__class__.__name__, time_series, baseline_time_series)\nself.smoothing_factor = smoothing_factor or DEFAULT_DERI_SMOOTHING_FACTOR\nself.time_series_items = self.time_series.items()",
"derivatives = []\nfor i, (timestamp, value) in enumerate(self.time_series_items):\n... | <|body_start_0|>
super(DerivativeDetector, self).__init__(self.__class__.__name__, time_series, baseline_time_series)
self.smoothing_factor = smoothing_factor or DEFAULT_DERI_SMOOTHING_FACTOR
self.time_series_items = self.time_series.items()
<|end_body_0|>
<|body_start_1|>
derivatives =... | Derivative Algorithm. This method is the derivative version of Method 1. Instead of data point value, it uses the derivative of the data point. | DerivativeDetector | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DerivativeDetector:
"""Derivative Algorithm. This method is the derivative version of Method 1. Instead of data point value, it uses the derivative of the data point."""
def __init__(self, time_series, baseline_time_series=None, smoothing_factor=None):
"""Initializer :param TimeSerie... | stack_v2_sparse_classes_36k_train_013865 | 2,965 | permissive | [
{
"docstring": "Initializer :param TimeSeries time_series: a TimeSeries object. :param TimeSeries baseline_time_series: baseline TimeSeries. :param float smoothing_factor: smoothing factor.",
"name": "__init__",
"signature": "def __init__(self, time_series, baseline_time_series=None, smoothing_factor=No... | 3 | stack_v2_sparse_classes_30k_train_004734 | Implement the Python class `DerivativeDetector` described below.
Class description:
Derivative Algorithm. This method is the derivative version of Method 1. Instead of data point value, it uses the derivative of the data point.
Method signatures and docstrings:
- def __init__(self, time_series, baseline_time_series=N... | Implement the Python class `DerivativeDetector` described below.
Class description:
Derivative Algorithm. This method is the derivative version of Method 1. Instead of data point value, it uses the derivative of the data point.
Method signatures and docstrings:
- def __init__(self, time_series, baseline_time_series=N... | b0dc7df586394578d29389d306223523dc99c827 | <|skeleton|>
class DerivativeDetector:
"""Derivative Algorithm. This method is the derivative version of Method 1. Instead of data point value, it uses the derivative of the data point."""
def __init__(self, time_series, baseline_time_series=None, smoothing_factor=None):
"""Initializer :param TimeSerie... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DerivativeDetector:
"""Derivative Algorithm. This method is the derivative version of Method 1. Instead of data point value, it uses the derivative of the data point."""
def __init__(self, time_series, baseline_time_series=None, smoothing_factor=None):
"""Initializer :param TimeSeries time_series... | the_stack_v2_python_sparse | src/luminol/algorithms/anomaly_detector_algorithms/derivative_detector.py | linkedin/luminol | train | 1,159 |
3a2ab2a624617dc54a5a954bf54162fb7ab6897d | [
"super().__init__(header, raw_data)\nself.status, self.length, *self.values = unpack_from(f'<{self.header.params_count}I', raw_data)\nself.data = raw_data[8:8 + self.length] if self.length > 0 else b''",
"tag = ResponseTag.name(self.header.tag)\nstatus = StatusCode.get(self.status, f'Unknown[0x{self.status:08X}]'... | <|body_start_0|>
super().__init__(header, raw_data)
self.status, self.length, *self.values = unpack_from(f'<{self.header.params_count}I', raw_data)
self.data = raw_data[8:8 + self.length] if self.length > 0 else b''
<|end_body_0|>
<|body_start_1|>
tag = ResponseTag.name(self.header.tag)... | McuBoot flash read once response format class. | FlashReadOnceResponse | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlashReadOnceResponse:
"""McuBoot flash read once response format class."""
def __init__(self, header: CmdHeader, raw_data: bytes) -> None:
"""Initialize the Flash-Read-Once response object. :param header: Header for the response :param raw_data: Response data"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_013866 | 14,747 | permissive | [
{
"docstring": "Initialize the Flash-Read-Once response object. :param header: Header for the response :param raw_data: Response data",
"name": "__init__",
"signature": "def __init__(self, header: CmdHeader, raw_data: bytes) -> None"
},
{
"docstring": "Get object info.",
"name": "info",
... | 2 | stack_v2_sparse_classes_30k_train_017893 | Implement the Python class `FlashReadOnceResponse` described below.
Class description:
McuBoot flash read once response format class.
Method signatures and docstrings:
- def __init__(self, header: CmdHeader, raw_data: bytes) -> None: Initialize the Flash-Read-Once response object. :param header: Header for the respon... | Implement the Python class `FlashReadOnceResponse` described below.
Class description:
McuBoot flash read once response format class.
Method signatures and docstrings:
- def __init__(self, header: CmdHeader, raw_data: bytes) -> None: Initialize the Flash-Read-Once response object. :param header: Header for the respon... | 4a31fb091f95fb035bc66241ee4e02dabb580072 | <|skeleton|>
class FlashReadOnceResponse:
"""McuBoot flash read once response format class."""
def __init__(self, header: CmdHeader, raw_data: bytes) -> None:
"""Initialize the Flash-Read-Once response object. :param header: Header for the response :param raw_data: Response data"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FlashReadOnceResponse:
"""McuBoot flash read once response format class."""
def __init__(self, header: CmdHeader, raw_data: bytes) -> None:
"""Initialize the Flash-Read-Once response object. :param header: Header for the response :param raw_data: Response data"""
super().__init__(header, ... | the_stack_v2_python_sparse | spsdk/mboot/commands.py | AdrianCano-01/spsdk | train | 0 |
6b7b878c6d116084a6d0db11eb25f635f85c3c56 | [
"self.summary_type = ''\nself.source_ip = ''\nself.username = ''\nself.domain = ''\nself.first_seen = 0\nself.last_seen = 0\nself.first_auth = None\nself.successful_logins = []\nself.success_source_ips = set()\nself.success_usernames = set()\nself.summary = {}\nself.distinct_source_ip_count = 0\nself.distinct_usern... | <|body_start_0|>
self.summary_type = ''
self.source_ip = ''
self.username = ''
self.domain = ''
self.first_seen = 0
self.last_seen = 0
self.first_auth = None
self.successful_logins = []
self.success_source_ips = set()
self.success_usernames... | Class for storing authentication summary. Attributes: summary_type (str): The keyword used in generating summary. Valid values are "source_ip" or "username". source_ip (str): IP address of the client. username (str): Username used in authentication. domain (str): Domain name. Only relevant for Windows. first_seen (int)... | AuthSummary | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthSummary:
"""Class for storing authentication summary. Attributes: summary_type (str): The keyword used in generating summary. Valid values are "source_ip" or "username". source_ip (str): IP address of the client. username (str): Username used in authentication. domain (str): Domain name. Only... | stack_v2_sparse_classes_36k_train_013867 | 33,481 | permissive | [
{
"docstring": "Initialize AuthSummary.",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Convert and return dict. Returns: dict: A dictionary of selected fields in AuthSummary object.",
"name": "to_dict",
"signature": "def to_dict(self) -> dict"
}
] | 2 | null | Implement the Python class `AuthSummary` described below.
Class description:
Class for storing authentication summary. Attributes: summary_type (str): The keyword used in generating summary. Valid values are "source_ip" or "username". source_ip (str): IP address of the client. username (str): Username used in authenti... | Implement the Python class `AuthSummary` described below.
Class description:
Class for storing authentication summary. Attributes: summary_type (str): The keyword used in generating summary. Valid values are "source_ip" or "username". source_ip (str): IP address of the client. username (str): Username used in authenti... | 24f471b58ca4a87cb053961b5f05c07a544ca7b8 | <|skeleton|>
class AuthSummary:
"""Class for storing authentication summary. Attributes: summary_type (str): The keyword used in generating summary. Valid values are "source_ip" or "username". source_ip (str): IP address of the client. username (str): Username used in authentication. domain (str): Domain name. Only... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuthSummary:
"""Class for storing authentication summary. Attributes: summary_type (str): The keyword used in generating summary. Valid values are "source_ip" or "username". source_ip (str): IP address of the client. username (str): Username used in authentication. domain (str): Domain name. Only relevant for... | the_stack_v2_python_sparse | timesketch/lib/analyzers/authentication/utils.py | google/timesketch | train | 2,263 |
34a22d5c6f31ddb24cecfd01378d0ff7f0fcff76 | [
"self.input_fn = dataloader.InputReader(FLAGS.file_pattern, is_training=not FLAGS.eval, use_fake_data=False, max_instances_per_image=config.max_instances_per_image)\nself.params = dict(config.as_dict(), batch_size=FLAGS.samples, model_name=FLAGS.model_name)\nlogging.info(self.params)\nself.cls_to_label = config.lab... | <|body_start_0|>
self.input_fn = dataloader.InputReader(FLAGS.file_pattern, is_training=not FLAGS.eval, use_fake_data=False, max_instances_per_image=config.max_instances_per_image)
self.params = dict(config.as_dict(), batch_size=FLAGS.samples, model_name=FLAGS.model_name)
logging.info(self.param... | Inspection Class. | RecordInspect | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecordInspect:
"""Inspection Class."""
def __init__(self, config):
"""Initializes RecordInspect with passed config. Args: config: config file to initialize input_fn."""
<|body_0|>
def visualize(self):
"""save tfrecords images with bounding boxes."""
<|bod... | stack_v2_sparse_classes_36k_train_013868 | 4,566 | permissive | [
{
"docstring": "Initializes RecordInspect with passed config. Args: config: config file to initialize input_fn.",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "save tfrecords images with bounding boxes.",
"name": "visualize",
"signature": "def visualize... | 2 | stack_v2_sparse_classes_30k_train_016402 | Implement the Python class `RecordInspect` described below.
Class description:
Inspection Class.
Method signatures and docstrings:
- def __init__(self, config): Initializes RecordInspect with passed config. Args: config: config file to initialize input_fn.
- def visualize(self): save tfrecords images with bounding bo... | Implement the Python class `RecordInspect` described below.
Class description:
Inspection Class.
Method signatures and docstrings:
- def __init__(self, config): Initializes RecordInspect with passed config. Args: config: config file to initialize input_fn.
- def visualize(self): save tfrecords images with bounding bo... | c7392f2bab3165244d1c565b66409fa11fa82367 | <|skeleton|>
class RecordInspect:
"""Inspection Class."""
def __init__(self, config):
"""Initializes RecordInspect with passed config. Args: config: config file to initialize input_fn."""
<|body_0|>
def visualize(self):
"""save tfrecords images with bounding boxes."""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RecordInspect:
"""Inspection Class."""
def __init__(self, config):
"""Initializes RecordInspect with passed config. Args: config: config file to initialize input_fn."""
self.input_fn = dataloader.InputReader(FLAGS.file_pattern, is_training=not FLAGS.eval, use_fake_data=False, max_instance... | the_stack_v2_python_sparse | efficientdet/dataset/inspect_tfrecords.py | google/automl | train | 6,415 |
9f75a49d92e089e64bcbe77b2587becc1d28a79e | [
"super(FileObjectInputReader, self).__init__(encoding=encoding)\nself._errors = 'strict'\nself._file_object = file_object",
"input_string = self._file_object.readline()\nif isinstance(input_string, bytes):\n try:\n input_string = codecs.decode(input_string, self._encoding, self._errors)\n except Unic... | <|body_start_0|>
super(FileObjectInputReader, self).__init__(encoding=encoding)
self._errors = 'strict'
self._file_object = file_object
<|end_body_0|>
<|body_start_1|>
input_string = self._file_object.readline()
if isinstance(input_string, bytes):
try:
... | File object command line interface input reader. This input reader relies on the file-like object having a readline method. | FileObjectInputReader | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileObjectInputReader:
"""File object command line interface input reader. This input reader relies on the file-like object having a readline method."""
def __init__(self, file_object, encoding='utf-8'):
"""Initializes a file object input reader. Args: file_object (file): file-like o... | stack_v2_sparse_classes_36k_train_013869 | 29,440 | permissive | [
{
"docstring": "Initializes a file object input reader. Args: file_object (file): file-like object to read from. encoding (Optional[str]): input encoding.",
"name": "__init__",
"signature": "def __init__(self, file_object, encoding='utf-8')"
},
{
"docstring": "Reads a string from the input. Retu... | 2 | null | Implement the Python class `FileObjectInputReader` described below.
Class description:
File object command line interface input reader. This input reader relies on the file-like object having a readline method.
Method signatures and docstrings:
- def __init__(self, file_object, encoding='utf-8'): Initializes a file o... | Implement the Python class `FileObjectInputReader` described below.
Class description:
File object command line interface input reader. This input reader relies on the file-like object having a readline method.
Method signatures and docstrings:
- def __init__(self, file_object, encoding='utf-8'): Initializes a file o... | 28756d910e951a22c5f0b2bcf5184f055a19d544 | <|skeleton|>
class FileObjectInputReader:
"""File object command line interface input reader. This input reader relies on the file-like object having a readline method."""
def __init__(self, file_object, encoding='utf-8'):
"""Initializes a file object input reader. Args: file_object (file): file-like o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileObjectInputReader:
"""File object command line interface input reader. This input reader relies on the file-like object having a readline method."""
def __init__(self, file_object, encoding='utf-8'):
"""Initializes a file object input reader. Args: file_object (file): file-like object to read... | the_stack_v2_python_sparse | dfvfs/helpers/command_line.py | log2timeline/dfvfs | train | 197 |
99c30cd7b0cb1df24b0abbe2eb57412783c6f106 | [
"url = reverse('forgot-password')\npayload = simplejson.dumps({'email': self.email})\nrequest = self.c.put(path=url, data=payload, content_type='application/json')\nself.assertEqual(request.status_code, status.HTTP_200_OK)",
"url = reverse('forgot-username')\npayload = simplejson.dumps({'email': self.email})\nreq... | <|body_start_0|>
url = reverse('forgot-password')
payload = simplejson.dumps({'email': self.email})
request = self.c.put(path=url, data=payload, content_type='application/json')
self.assertEqual(request.status_code, status.HTTP_200_OK)
<|end_body_0|>
<|body_start_1|>
url = rever... | UserForgotTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserForgotTestCase:
def test_forgot_my_password(self):
"""Forgot my password"""
<|body_0|>
def test_forgot_username(self):
"""Forgot Username"""
<|body_1|>
def test_forgot_password_email_invalid(self):
"""email invalid"""
<|body_2|>
... | stack_v2_sparse_classes_36k_train_013870 | 6,849 | no_license | [
{
"docstring": "Forgot my password",
"name": "test_forgot_my_password",
"signature": "def test_forgot_my_password(self)"
},
{
"docstring": "Forgot Username",
"name": "test_forgot_username",
"signature": "def test_forgot_username(self)"
},
{
"docstring": "email invalid",
"name... | 4 | stack_v2_sparse_classes_30k_train_020144 | Implement the Python class `UserForgotTestCase` described below.
Class description:
Implement the UserForgotTestCase class.
Method signatures and docstrings:
- def test_forgot_my_password(self): Forgot my password
- def test_forgot_username(self): Forgot Username
- def test_forgot_password_email_invalid(self): email ... | Implement the Python class `UserForgotTestCase` described below.
Class description:
Implement the UserForgotTestCase class.
Method signatures and docstrings:
- def test_forgot_my_password(self): Forgot my password
- def test_forgot_username(self): Forgot Username
- def test_forgot_password_email_invalid(self): email ... | b8ba25fdde5d4ee92a3f73cb42ff892ed436d3f2 | <|skeleton|>
class UserForgotTestCase:
def test_forgot_my_password(self):
"""Forgot my password"""
<|body_0|>
def test_forgot_username(self):
"""Forgot Username"""
<|body_1|>
def test_forgot_password_email_invalid(self):
"""email invalid"""
<|body_2|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserForgotTestCase:
def test_forgot_my_password(self):
"""Forgot my password"""
url = reverse('forgot-password')
payload = simplejson.dumps({'email': self.email})
request = self.c.put(path=url, data=payload, content_type='application/json')
self.assertEqual(request.stat... | the_stack_v2_python_sparse | chatproject/apps/auth/tests.py | QilinGu/chat-project | train | 0 | |
413da3f117131cd80471598193bbd29c1ed008d8 | [
"Drawable.__init__(self, RIDE_SPRITE)\nself.start, self.end = (start, end)\nself.start_time, self.end_time = (times[0], times[1])",
"initial_longitude = self.start.location[0]\ninitial_latitude = self.start.location[1]\nfinal_longitude = self.end.location[0]\nfinal_latitude = self.end.location[1]\ntime_difference... | <|body_start_0|>
Drawable.__init__(self, RIDE_SPRITE)
self.start, self.end = (start, end)
self.start_time, self.end_time = (times[0], times[1])
<|end_body_0|>
<|body_start_1|>
initial_longitude = self.start.location[0]
initial_latitude = self.start.location[1]
final_long... | A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end_time | Ride | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ride:
"""A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end_time"""
def __init__(self, start:... | stack_v2_sparse_classes_36k_train_013871 | 4,858 | no_license | [
{
"docstring": "Initialize a ride object with the given start and end information.",
"name": "__init__",
"signature": "def __init__(self, start: Station, end: Station, times: Tuple[datetime, datetime]) -> None"
},
{
"docstring": "Return the (long, lat) position of this ride for the given time. A... | 2 | stack_v2_sparse_classes_30k_train_002053 | Implement the Python class `Ride` described below.
Class description:
A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end... | Implement the Python class `Ride` described below.
Class description:
A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end... | 01185e1eab994b42d7e0ec33223eed742b83233e | <|skeleton|>
class Ride:
"""A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end_time"""
def __init__(self, start:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ride:
"""A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end_time"""
def __init__(self, start: Station, end... | the_stack_v2_python_sparse | CSC148/assignments/a1/backup/bikeshare - backup.py | rcase31/UofTCourses | train | 1 |
db2fcfb9dd22a0c95257e664c210e646c702a9ff | [
"self.n = n\nself.n1 = 0\nself.discount = discount / 100.0\nself.prices = {}\nfor i in range(len(products)):\n self.prices[products[i]] = prices[i]",
"self.n1 += 1\ndiscount = 0\nif self.n1 == self.n:\n self.n1 = 0\n discount = self.discount\ntotal = 0\nfor i in range(len(product)):\n product_id = pro... | <|body_start_0|>
self.n = n
self.n1 = 0
self.discount = discount / 100.0
self.prices = {}
for i in range(len(products)):
self.prices[products[i]] = prices[i]
<|end_body_0|>
<|body_start_1|>
self.n1 += 1
discount = 0
if self.n1 == self.n:
... | Cashier | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cashier:
def __init__(self, n, discount, products, prices):
""":type n: int :type discount: int :type products: List[int] :type prices: List[int]"""
<|body_0|>
def getBill(self, product, amount):
""":type product: List[int] :type amount: List[int] :rtype: float"""
... | stack_v2_sparse_classes_36k_train_013872 | 4,017 | no_license | [
{
"docstring": ":type n: int :type discount: int :type products: List[int] :type prices: List[int]",
"name": "__init__",
"signature": "def __init__(self, n, discount, products, prices)"
},
{
"docstring": ":type product: List[int] :type amount: List[int] :rtype: float",
"name": "getBill",
... | 2 | null | Implement the Python class `Cashier` described below.
Class description:
Implement the Cashier class.
Method signatures and docstrings:
- def __init__(self, n, discount, products, prices): :type n: int :type discount: int :type products: List[int] :type prices: List[int]
- def getBill(self, product, amount): :type pr... | Implement the Python class `Cashier` described below.
Class description:
Implement the Cashier class.
Method signatures and docstrings:
- def __init__(self, n, discount, products, prices): :type n: int :type discount: int :type products: List[int] :type prices: List[int]
- def getBill(self, product, amount): :type pr... | 1211eac167f33084f536007468ea10c1a0ceab08 | <|skeleton|>
class Cashier:
def __init__(self, n, discount, products, prices):
""":type n: int :type discount: int :type products: List[int] :type prices: List[int]"""
<|body_0|>
def getBill(self, product, amount):
""":type product: List[int] :type amount: List[int] :rtype: float"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Cashier:
def __init__(self, n, discount, products, prices):
""":type n: int :type discount: int :type products: List[int] :type prices: List[int]"""
self.n = n
self.n1 = 0
self.discount = discount / 100.0
self.prices = {}
for i in range(len(products)):
... | the_stack_v2_python_sparse | 1357_ApplyDiscountEverynOrders.py | renukadeshmukh/Leetcode_Solutions | train | 3 | |
e6ff53bff27b35e43a06890daca6ebf07ebf4140 | [
"super(ListMemberActivity, self).__init__(*args, **kwargs)\nself.endpoint = 'lists'\nself.list_id = None\nself.subscriber_hash = None",
"subscriber_hash = check_subscriber_hash(subscriber_hash)\nself.list_id = list_id\nself.subscriber_hash = subscriber_hash\nreturn self._mc_client._get(url=self._build_path(list_i... | <|body_start_0|>
super(ListMemberActivity, self).__init__(*args, **kwargs)
self.endpoint = 'lists'
self.list_id = None
self.subscriber_hash = None
<|end_body_0|>
<|body_start_1|>
subscriber_hash = check_subscriber_hash(subscriber_hash)
self.list_id = list_id
self... | Get details about subscribers’ recent activity. | ListMemberActivity | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListMemberActivity:
"""Get details about subscribers’ recent activity."""
def __init__(self, *args, **kwargs):
"""Initialize the endpoint"""
<|body_0|>
def all(self, list_id, subscriber_hash, **queryparams):
"""Get the last 50 events of a member’s activity on a s... | stack_v2_sparse_classes_36k_train_013873 | 2,636 | permissive | [
{
"docstring": "Initialize the endpoint",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Get the last 50 events of a member’s activity on a specific list, including opens, clicks, and unsubscribes. :param list_id: The unique id for the list. :type list_... | 3 | null | Implement the Python class `ListMemberActivity` described below.
Class description:
Get details about subscribers’ recent activity.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize the endpoint
- def all(self, list_id, subscriber_hash, **queryparams): Get the last 50 events of a mem... | Implement the Python class `ListMemberActivity` described below.
Class description:
Get details about subscribers’ recent activity.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize the endpoint
- def all(self, list_id, subscriber_hash, **queryparams): Get the last 50 events of a mem... | bf61cd602dc44cbff32fbf6f6dcdd33cf6f782e8 | <|skeleton|>
class ListMemberActivity:
"""Get details about subscribers’ recent activity."""
def __init__(self, *args, **kwargs):
"""Initialize the endpoint"""
<|body_0|>
def all(self, list_id, subscriber_hash, **queryparams):
"""Get the last 50 events of a member’s activity on a s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ListMemberActivity:
"""Get details about subscribers’ recent activity."""
def __init__(self, *args, **kwargs):
"""Initialize the endpoint"""
super(ListMemberActivity, self).__init__(*args, **kwargs)
self.endpoint = 'lists'
self.list_id = None
self.subscriber_hash =... | the_stack_v2_python_sparse | mailchimp3/entities/listmemberactivity.py | VingtCinq/python-mailchimp | train | 190 |
e31d047bb56e0d5acc7fd09b5b8372e7e0b8fa43 | [
"ipo = IPConfigPage(self.driver)\nlpo = LoginPage(self.driver)\nlpo.click_ip_btn()\nipo.ipconfig_action('172.16.12.223')\nlpo.login_action('', '')\nresult = driverwait.find_toast(self.driver, u'账号为空')\nprint(u'用户名和密码为空校验结果%s' % result)\nfunction.insert_image(self.driver, 'login_user_null.jpg')",
"ipo = IPConfigPa... | <|body_start_0|>
ipo = IPConfigPage(self.driver)
lpo = LoginPage(self.driver)
lpo.click_ip_btn()
ipo.ipconfig_action('172.16.12.223')
lpo.login_action('', '')
result = driverwait.find_toast(self.driver, u'账号为空')
print(u'用户名和密码为空校验结果%s' % result)
function.i... | LoginTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoginTest:
def test_login_user_null(self):
"""用户名为空"""
<|body_0|>
def test_login_pwd_null(self):
"""密码为空"""
<|body_1|>
def test_login_user_pwd_error(self):
"""用户名或者密码错误"""
<|body_2|>
def test_login_sucess(self):
"""用户名和密码正常""... | stack_v2_sparse_classes_36k_train_013874 | 2,365 | no_license | [
{
"docstring": "用户名为空",
"name": "test_login_user_null",
"signature": "def test_login_user_null(self)"
},
{
"docstring": "密码为空",
"name": "test_login_pwd_null",
"signature": "def test_login_pwd_null(self)"
},
{
"docstring": "用户名或者密码错误",
"name": "test_login_user_pwd_error",
... | 4 | stack_v2_sparse_classes_30k_val_000095 | Implement the Python class `LoginTest` described below.
Class description:
Implement the LoginTest class.
Method signatures and docstrings:
- def test_login_user_null(self): 用户名为空
- def test_login_pwd_null(self): 密码为空
- def test_login_user_pwd_error(self): 用户名或者密码错误
- def test_login_sucess(self): 用户名和密码正常 | Implement the Python class `LoginTest` described below.
Class description:
Implement the LoginTest class.
Method signatures and docstrings:
- def test_login_user_null(self): 用户名为空
- def test_login_pwd_null(self): 密码为空
- def test_login_user_pwd_error(self): 用户名或者密码错误
- def test_login_sucess(self): 用户名和密码正常
<|skeleton... | fd692b9fe9e42d4fc46445b2c887cc515516ee76 | <|skeleton|>
class LoginTest:
def test_login_user_null(self):
"""用户名为空"""
<|body_0|>
def test_login_pwd_null(self):
"""密码为空"""
<|body_1|>
def test_login_user_pwd_error(self):
"""用户名或者密码错误"""
<|body_2|>
def test_login_sucess(self):
"""用户名和密码正常""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoginTest:
def test_login_user_null(self):
"""用户名为空"""
ipo = IPConfigPage(self.driver)
lpo = LoginPage(self.driver)
lpo.click_ip_btn()
ipo.ipconfig_action('172.16.12.223')
lpo.login_action('', '')
result = driverwait.find_toast(self.driver, u'账号为空')
... | the_stack_v2_python_sparse | android_project/test_case/login_case.py | KKKY3/page_object_test | train | 0 | |
25ef1810a8467e40ce9d8392172d9eec9d5db51c | [
"super(SDPOSMenu, self).__init__(location, use_cache)\nself._location = location\nself.items = []\nself.categories = swagger_pos_menu\nself._item_name_dict = {}\nself._item_id_dict = {}\nself._category_name_dict = {}\nself._category_id_dict = {}\nfor category in swagger_pos_menu:\n for index, item in enumerate(c... | <|body_start_0|>
super(SDPOSMenu, self).__init__(location, use_cache)
self._location = location
self.items = []
self.categories = swagger_pos_menu
self._item_name_dict = {}
self._item_id_dict = {}
self._category_name_dict = {}
self._category_id_dict = {}
... | SDPOSMenu | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SDPOSMenu:
def __init__(self, location, swagger_pos_menu, use_cache=True):
""":param location: :param swagger_menu: :param use_cache:"""
<|body_0|>
def get_category(self, category_id=None, category_name=None):
""":param category_id: :param category_name: :return:"""
... | stack_v2_sparse_classes_36k_train_013875 | 2,292 | permissive | [
{
"docstring": ":param location: :param swagger_menu: :param use_cache:",
"name": "__init__",
"signature": "def __init__(self, location, swagger_pos_menu, use_cache=True)"
},
{
"docstring": ":param category_id: :param category_name: :return:",
"name": "get_category",
"signature": "def ge... | 3 | stack_v2_sparse_classes_30k_test_000370 | Implement the Python class `SDPOSMenu` described below.
Class description:
Implement the SDPOSMenu class.
Method signatures and docstrings:
- def __init__(self, location, swagger_pos_menu, use_cache=True): :param location: :param swagger_menu: :param use_cache:
- def get_category(self, category_id=None, category_name... | Implement the Python class `SDPOSMenu` described below.
Class description:
Implement the SDPOSMenu class.
Method signatures and docstrings:
- def __init__(self, location, swagger_pos_menu, use_cache=True): :param location: :param swagger_menu: :param use_cache:
- def get_category(self, category_id=None, category_name... | 7c24492dcc06b66aea3fd040c82152d2c3fdf719 | <|skeleton|>
class SDPOSMenu:
def __init__(self, location, swagger_pos_menu, use_cache=True):
""":param location: :param swagger_menu: :param use_cache:"""
<|body_0|>
def get_category(self, category_id=None, category_name=None):
""":param category_id: :param category_name: :return:"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SDPOSMenu:
def __init__(self, location, swagger_pos_menu, use_cache=True):
""":param location: :param swagger_menu: :param use_cache:"""
super(SDPOSMenu, self).__init__(location, use_cache)
self._location = location
self.items = []
self.categories = swagger_pos_menu
... | the_stack_v2_python_sparse | subtledata/sd_pos_menu.py | jakeharding/subtledata_python | train | 0 | |
440fa2c0cfcf6e5b4875dc700c31c61af8210bf7 | [
"context = super(EditAccountFormView, self).get_context_data(**kwargs)\ncontext['title'] = 'Edit Account'\nreturn context",
"image = form.cleaned_data['image']\nemail = form.cleaned_data['email']\nuser = self.request.user\nif image:\n info = UserInfos.objects.get(user=user)\n os.remove(info.image.path)\n ... | <|body_start_0|>
context = super(EditAccountFormView, self).get_context_data(**kwargs)
context['title'] = 'Edit Account'
return context
<|end_body_0|>
<|body_start_1|>
image = form.cleaned_data['image']
email = form.cleaned_data['email']
user = self.request.user
... | A class of LoginRequiredMixin and FormView to allow users to change some of theirs infos ... Attributes ---------- login_url : str The url of the login page template_name : str the name of the template form_class : EditAccountForm Form of the view success_url : str url of the success page Methods ------- get_context_da... | EditAccountFormView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EditAccountFormView:
"""A class of LoginRequiredMixin and FormView to allow users to change some of theirs infos ... Attributes ---------- login_url : str The url of the login page template_name : str the name of the template form_class : EditAccountForm Form of the view success_url : str url of ... | stack_v2_sparse_classes_36k_train_013876 | 9,386 | no_license | [
{
"docstring": "Call the original method of the view and add the title on the context Parameters ---------- kwargs : str Some argument that Django are passing, need when call the original method of the view Returns ------- dict a dict of the context of the page",
"name": "get_context_data",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_007847 | Implement the Python class `EditAccountFormView` described below.
Class description:
A class of LoginRequiredMixin and FormView to allow users to change some of theirs infos ... Attributes ---------- login_url : str The url of the login page template_name : str the name of the template form_class : EditAccountForm For... | Implement the Python class `EditAccountFormView` described below.
Class description:
A class of LoginRequiredMixin and FormView to allow users to change some of theirs infos ... Attributes ---------- login_url : str The url of the login page template_name : str the name of the template form_class : EditAccountForm For... | 939245d046974fabf33fa540b4c3b6d077100ff5 | <|skeleton|>
class EditAccountFormView:
"""A class of LoginRequiredMixin and FormView to allow users to change some of theirs infos ... Attributes ---------- login_url : str The url of the login page template_name : str the name of the template form_class : EditAccountForm Form of the view success_url : str url of ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EditAccountFormView:
"""A class of LoginRequiredMixin and FormView to allow users to change some of theirs infos ... Attributes ---------- login_url : str The url of the login page template_name : str the name of the template form_class : EditAccountForm Form of the view success_url : str url of the success p... | the_stack_v2_python_sparse | purebeurre/views/user.py | M0l42/P08_PureBeurre | train | 1 |
08216f9097b7aed0157cdbf5e1281eadd10bae66 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('jgrishey', 'jgrishey')\nurl = 'http://realtime.mbta.com/developer/api/v2/stopsbyroute?api_key=%s&route=Red&format=json' % dml.auth['services']['mbtadeveloperportal']['token']\nresponse = urllib.request.u... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('jgrishey', 'jgrishey')
url = 'http://realtime.mbta.com/developer/api/v2/stopsbyroute?api_key=%s&route=Red&format=json' % dml.auth['services']['mbtadevelop... | getRedLine | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class getRedLine:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything ha... | stack_v2_sparse_classes_36k_train_013877 | 4,060 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | null | Implement the Python class `getRedLine` described below.
Class description:
Implement the getRedLine class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime... | Implement the Python class `getRedLine` described below.
Class description:
Implement the getRedLine class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime... | 0df485d0469c5451ebdcd684bed2a0960ba3ab84 | <|skeleton|>
class getRedLine:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything ha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class getRedLine:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('jgrishey', 'jgrishey')
url = 'ht... | the_stack_v2_python_sparse | jgrishey/getRedLine.py | lingyigu/course-2017-spr-proj | train | 0 | |
2fdbd8b09696bb92c311fa12630af1dfab9d55de | [
"string_to_sign = '%s\\n%s\\n' % (verb, path)\nparams['signature_method'] = self.algorithm()\nkeys = sorted(params.keys())\npairs = []\nfor key in keys:\n val = get_utf8_value(params[key])\n if is_python3:\n key = key.encode()\n pairs.append(urllib.quote(key, safe='') + '=' + urllib.quote(val, safe=... | <|body_start_0|>
string_to_sign = '%s\n%s\n' % (verb, path)
params['signature_method'] = self.algorithm()
keys = sorted(params.keys())
pairs = []
for key in keys:
val = get_utf8_value(params[key])
if is_python3:
key = key.encode()
... | Provides Query Signature Authentication. | QuerySignatureAuthHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuerySignatureAuthHandler:
"""Provides Query Signature Authentication."""
def _calc_signature(self, params, verb, path):
"""calc signature for request"""
<|body_0|>
def add_auth(self, req, **kwargs):
"""add authorize information for request"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_013878 | 11,346 | permissive | [
{
"docstring": "calc signature for request",
"name": "_calc_signature",
"signature": "def _calc_signature(self, params, verb, path)"
},
{
"docstring": "add authorize information for request",
"name": "add_auth",
"signature": "def add_auth(self, req, **kwargs)"
}
] | 2 | null | Implement the Python class `QuerySignatureAuthHandler` described below.
Class description:
Provides Query Signature Authentication.
Method signatures and docstrings:
- def _calc_signature(self, params, verb, path): calc signature for request
- def add_auth(self, req, **kwargs): add authorize information for request | Implement the Python class `QuerySignatureAuthHandler` described below.
Class description:
Provides Query Signature Authentication.
Method signatures and docstrings:
- def _calc_signature(self, params, verb, path): calc signature for request
- def add_auth(self, req, **kwargs): add authorize information for request
... | 70992bf676983a0b1a5e9c80b453dec4ea0c2370 | <|skeleton|>
class QuerySignatureAuthHandler:
"""Provides Query Signature Authentication."""
def _calc_signature(self, params, verb, path):
"""calc signature for request"""
<|body_0|>
def add_auth(self, req, **kwargs):
"""add authorize information for request"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuerySignatureAuthHandler:
"""Provides Query Signature Authentication."""
def _calc_signature(self, params, verb, path):
"""calc signature for request"""
string_to_sign = '%s\n%s\n' % (verb, path)
params['signature_method'] = self.algorithm()
keys = sorted(params.keys())
... | the_stack_v2_python_sparse | qingcloud/conn/auth.py | yunify/qingcloud-sdk-python | train | 56 |
21e2f7847a80b7a7154f17bc89f9540a211dad8f | [
"n = len(graph)\ncolor = [0] * n\n\ndef dfs(cur, col):\n if color[cur] != 0:\n return color[cur] == col\n color[cur] = col\n for i in graph[cur]:\n if not dfs(i, -1 * col):\n return False\n return True\nfor i in range(n):\n if color[i] == 0 and (not dfs(i, 1)):\n retur... | <|body_start_0|>
n = len(graph)
color = [0] * n
def dfs(cur, col):
if color[cur] != 0:
return color[cur] == col
color[cur] = col
for i in graph[cur]:
if not dfs(i, -1 * col):
return False
return ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isBipartite(self, graph):
""":type graph: List[List[int]] :rtype: bool"""
<|body_0|>
def isBipartiteBFS(self, graph):
""":type graph: List[List[int]] :rtype: bool"""
<|body_1|>
def isBipartiteUF(self, graph):
""":type graph: List[Li... | stack_v2_sparse_classes_36k_train_013879 | 3,648 | no_license | [
{
"docstring": ":type graph: List[List[int]] :rtype: bool",
"name": "isBipartite",
"signature": "def isBipartite(self, graph)"
},
{
"docstring": ":type graph: List[List[int]] :rtype: bool",
"name": "isBipartiteBFS",
"signature": "def isBipartiteBFS(self, graph)"
},
{
"docstring":... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isBipartite(self, graph): :type graph: List[List[int]] :rtype: bool
- def isBipartiteBFS(self, graph): :type graph: List[List[int]] :rtype: bool
- def isBipartiteUF(self, gra... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isBipartite(self, graph): :type graph: List[List[int]] :rtype: bool
- def isBipartiteBFS(self, graph): :type graph: List[List[int]] :rtype: bool
- def isBipartiteUF(self, gra... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def isBipartite(self, graph):
""":type graph: List[List[int]] :rtype: bool"""
<|body_0|>
def isBipartiteBFS(self, graph):
""":type graph: List[List[int]] :rtype: bool"""
<|body_1|>
def isBipartiteUF(self, graph):
""":type graph: List[Li... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isBipartite(self, graph):
""":type graph: List[List[int]] :rtype: bool"""
n = len(graph)
color = [0] * n
def dfs(cur, col):
if color[cur] != 0:
return color[cur] == col
color[cur] = col
for i in graph[cur]:
... | the_stack_v2_python_sparse | I/IsGraphBipartite.py | bssrdf/pyleet | train | 2 | |
6d002536f47944e1e102818008de788c339f2e37 | [
"with open(filename, 'rb') as reader:\n logger.info('Importing file %s', filename)\n timer = Timer()\n reader = csv.reader(reader)\n titles = reader.next()\n all_records = []\n for row in reader:\n row = self.uniform(row, titles)\n if row:\n all_records.append(row)\n se... | <|body_start_0|>
with open(filename, 'rb') as reader:
logger.info('Importing file %s', filename)
timer = Timer()
reader = csv.reader(reader)
titles = reader.next()
all_records = []
for row in reader:
row = self.uniform(row, ... | Original data was saved in CSV file. | MixinFromCSV | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MixinFromCSV:
"""Original data was saved in CSV file."""
def import_csv(self, filename):
"""Import a csv file"""
<|body_0|>
def init_db(self, folder):
"""Refresh the source folder to check in new data"""
<|body_1|>
def refresh(self, folder):
... | stack_v2_sparse_classes_36k_train_013880 | 24,895 | no_license | [
{
"docstring": "Import a csv file",
"name": "import_csv",
"signature": "def import_csv(self, filename)"
},
{
"docstring": "Refresh the source folder to check in new data",
"name": "init_db",
"signature": "def init_db(self, folder)"
},
{
"docstring": "Refresh the source folder to ... | 3 | stack_v2_sparse_classes_30k_train_015976 | Implement the Python class `MixinFromCSV` described below.
Class description:
Original data was saved in CSV file.
Method signatures and docstrings:
- def import_csv(self, filename): Import a csv file
- def init_db(self, folder): Refresh the source folder to check in new data
- def refresh(self, folder): Refresh the ... | Implement the Python class `MixinFromCSV` described below.
Class description:
Original data was saved in CSV file.
Method signatures and docstrings:
- def import_csv(self, filename): Import a csv file
- def init_db(self, folder): Refresh the source folder to check in new data
- def refresh(self, folder): Refresh the ... | 07bca1d199565cea0bf1917cb8d8a2e242f24f26 | <|skeleton|>
class MixinFromCSV:
"""Original data was saved in CSV file."""
def import_csv(self, filename):
"""Import a csv file"""
<|body_0|>
def init_db(self, folder):
"""Refresh the source folder to check in new data"""
<|body_1|>
def refresh(self, folder):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MixinFromCSV:
"""Original data was saved in CSV file."""
def import_csv(self, filename):
"""Import a csv file"""
with open(filename, 'rb') as reader:
logger.info('Importing file %s', filename)
timer = Timer()
reader = csv.reader(reader)
titl... | the_stack_v2_python_sparse | orca/ocean.py | HopHill/orca | train | 0 |
ac0fefb11ed062e57ec99e511263ce673013f683 | [
"self._logger = logging.getLogger(__name__).getChild(self.__class__.__name__)\nself._api_base_url = api_base_url\nself._schema = schema\nself._token = access_token",
"headers = {}\nif self._token and self._schema == GitSchema.GITHUB:\n headers.update({'Authorization': 'token %s' % self._token})\nelif self._tok... | <|body_start_0|>
self._logger = logging.getLogger(__name__).getChild(self.__class__.__name__)
self._api_base_url = api_base_url
self._schema = schema
self._token = access_token
<|end_body_0|>
<|body_start_1|>
headers = {}
if self._token and self._schema == GitSchema.GITH... | Base Git Listing Service. | GitListingBase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GitListingBase:
"""Base Git Listing Service."""
def __init__(self, api_base_url='https://api.github.com/repos', schema=GitSchema.GITHUB, access_token=''):
"""Initialise. Args: api_base_url (str): The base url for the cloud hosted git API. If using LOCAL schema, This should be the pat... | stack_v2_sparse_classes_36k_train_013881 | 12,196 | permissive | [
{
"docstring": "Initialise. Args: api_base_url (str): The base url for the cloud hosted git API. If using LOCAL schema, This should be the path to the directory containing locally checked out git repos with structure: api_base_url/owner/repo. schema (GitSchema): The type of schema to use. access_token (str): Th... | 2 | stack_v2_sparse_classes_30k_train_004305 | Implement the Python class `GitListingBase` described below.
Class description:
Base Git Listing Service.
Method signatures and docstrings:
- def __init__(self, api_base_url='https://api.github.com/repos', schema=GitSchema.GITHUB, access_token=''): Initialise. Args: api_base_url (str): The base url for the cloud host... | Implement the Python class `GitListingBase` described below.
Class description:
Base Git Listing Service.
Method signatures and docstrings:
- def __init__(self, api_base_url='https://api.github.com/repos', schema=GitSchema.GITHUB, access_token=''): Initialise. Args: api_base_url (str): The base url for the cloud host... | 43225a155a985a7a56402df23dd550e48e22b436 | <|skeleton|>
class GitListingBase:
"""Base Git Listing Service."""
def __init__(self, api_base_url='https://api.github.com/repos', schema=GitSchema.GITHUB, access_token=''):
"""Initialise. Args: api_base_url (str): The base url for the cloud hosted git API. If using LOCAL schema, This should be the pat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GitListingBase:
"""Base Git Listing Service."""
def __init__(self, api_base_url='https://api.github.com/repos', schema=GitSchema.GITHUB, access_token=''):
"""Initialise. Args: api_base_url (str): The base url for the cloud hosted git API. If using LOCAL schema, This should be the path to the dire... | the_stack_v2_python_sparse | productionsystem/webapp/services/GitListing.py | alexanderrichards/ProductionSystem | train | 0 |
20625469cafa2277557128136b04f4a20c578797 | [
"self.__parser = parser\nparser.add_argument('mapOrProtareFileName', help='The path to a map or protare file. If it is a map file then option \"--tid\" (and maybe \"--pid\") is required.')\nparser.add_argument('--pid', action='store', default=IDsModule.neutron, help='The PoPs id for the projectile. Only used if the... | <|body_start_0|>
self.__parser = parser
parser.add_argument('mapOrProtareFileName', help='The path to a map or protare file. If it is a map file then option "--tid" (and maybe "--pid") is required.')
parser.add_argument('--pid', action='store', default=IDsModule.neutron, help='The PoPs id for th... | SingleProtareArguments | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingleProtareArguments:
def __init__(self, parser):
""":param parser: An argparse.ArgumentParser instance which will be updated with parameters for accessing a profile from a file."""
<|body_0|>
def protare(self, args, verbosity=0, lazyParsing=True):
"""Returns a pro... | stack_v2_sparse_classes_36k_train_013882 | 2,913 | permissive | [
{
"docstring": ":param parser: An argparse.ArgumentParser instance which will be updated with parameters for accessing a profile from a file.",
"name": "__init__",
"signature": "def __init__(self, parser)"
},
{
"docstring": "Returns a protare (i.e., \"reactionSuite\") instance that has been read... | 2 | null | Implement the Python class `SingleProtareArguments` described below.
Class description:
Implement the SingleProtareArguments class.
Method signatures and docstrings:
- def __init__(self, parser): :param parser: An argparse.ArgumentParser instance which will be updated with parameters for accessing a profile from a fi... | Implement the Python class `SingleProtareArguments` described below.
Class description:
Implement the SingleProtareArguments class.
Method signatures and docstrings:
- def __init__(self, parser): :param parser: An argparse.ArgumentParser instance which will be updated with parameters for accessing a profile from a fi... | 6ba80855ae47cb32c37f635d065b228fadb03412 | <|skeleton|>
class SingleProtareArguments:
def __init__(self, parser):
""":param parser: An argparse.ArgumentParser instance which will be updated with parameters for accessing a profile from a file."""
<|body_0|>
def protare(self, args, verbosity=0, lazyParsing=True):
"""Returns a pro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SingleProtareArguments:
def __init__(self, parser):
""":param parser: An argparse.ArgumentParser instance which will be updated with parameters for accessing a profile from a file."""
self.__parser = parser
parser.add_argument('mapOrProtareFileName', help='The path to a map or protare ... | the_stack_v2_python_sparse | LUPY/argumentsForScripts.py | LLNL/fudge | train | 21 | |
4c58f6ce4f5f92e69fa53334ce11acbf1e113b63 | [
"entity = self.entities.find_entity_by_id(event.entity_id)\nskill = self.entities.find_entity_by_id(event.skill_entity_id)\nskill_target_component = skill.components.get('point_ranged_targeted_skill', None)\nif not skill_target_component:\n return\ntarget_point = entity.components['input'].input[EntityInput.TARG... | <|body_start_0|>
entity = self.entities.find_entity_by_id(event.entity_id)
skill = self.entities.find_entity_by_id(event.skill_entity_id)
skill_target_component = skill.components.get('point_ranged_targeted_skill', None)
if not skill_target_component:
return
target_po... | Point ranged targeted skill system. | PointRangedTargetedSkillSystem | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PointRangedTargetedSkillSystem:
"""Point ranged targeted skill system."""
def on_entity_skill_usage_attempt(self, event):
"""Handle an entity skill usage attempt."""
<|body_0|>
def on_entity_skill_usage(self, event):
"""Handle an entity skill usage."""
<|... | stack_v2_sparse_classes_36k_train_013883 | 21,180 | permissive | [
{
"docstring": "Handle an entity skill usage attempt.",
"name": "on_entity_skill_usage_attempt",
"signature": "def on_entity_skill_usage_attempt(self, event)"
},
{
"docstring": "Handle an entity skill usage.",
"name": "on_entity_skill_usage",
"signature": "def on_entity_skill_usage(self,... | 2 | stack_v2_sparse_classes_30k_train_007196 | Implement the Python class `PointRangedTargetedSkillSystem` described below.
Class description:
Point ranged targeted skill system.
Method signatures and docstrings:
- def on_entity_skill_usage_attempt(self, event): Handle an entity skill usage attempt.
- def on_entity_skill_usage(self, event): Handle an entity skill... | Implement the Python class `PointRangedTargetedSkillSystem` described below.
Class description:
Point ranged targeted skill system.
Method signatures and docstrings:
- def on_entity_skill_usage_attempt(self, event): Handle an entity skill usage attempt.
- def on_entity_skill_usage(self, event): Handle an entity skill... | 1d84c2869a242a112e57c6cafc6da7329f9d0808 | <|skeleton|>
class PointRangedTargetedSkillSystem:
"""Point ranged targeted skill system."""
def on_entity_skill_usage_attempt(self, event):
"""Handle an entity skill usage attempt."""
<|body_0|>
def on_entity_skill_usage(self, event):
"""Handle an entity skill usage."""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PointRangedTargetedSkillSystem:
"""Point ranged targeted skill system."""
def on_entity_skill_usage_attempt(self, event):
"""Handle an entity skill usage attempt."""
entity = self.entities.find_entity_by_id(event.entity_id)
skill = self.entities.find_entity_by_id(event.skill_entit... | the_stack_v2_python_sparse | akurra/skills.py | multatronic/akurra | train | 0 |
35eb14f18f7d14b130427e4c9492aa8f7a77a4b4 | [
"if nmax < 0:\n return ValueError('nmax must be >= 0')\nsuper().__init__(self._Lx, nf=nmax + 1, nx=1, maxderiv=None, zlevel=None)\nself.nmax = nmax\nself.alpha = alpha\nreturn",
"nd, nvar = dfun.ndnvar(deriv, var, self.nx)\nif out is None:\n base_shape = X.shape[1:]\n out = np.ndarray((nd, self.nf) + bas... | <|body_start_0|>
if nmax < 0:
return ValueError('nmax must be >= 0')
super().__init__(self._Lx, nf=nmax + 1, nx=1, maxderiv=None, zlevel=None)
self.nmax = nmax
self.alpha = alpha
return
<|end_body_0|>
<|body_start_1|>
nd, nvar = dfun.ndnvar(deriv, var, self.n... | Generalized Laguerre polynomials of a given order, :math:`\\alpha`. .. math:: L_n^{(\\alpha)}(x) Attributes ---------- nmax : int The maximum degree. alpha : float The associated Legendre function order index. | LaguerreL | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LaguerreL:
"""Generalized Laguerre polynomials of a given order, :math:`\\alpha`. .. math:: L_n^{(\\alpha)}(x) Attributes ---------- nmax : int The maximum degree. alpha : float The associated Legendre function order index."""
def __init__(self, alpha, nmax):
"""Create associated Leg... | stack_v2_sparse_classes_36k_train_013884 | 39,055 | permissive | [
{
"docstring": "Create associated Legendre basis DFuns Parameters ---------- m : float The real order parameter. nmax : int The maximum degree.",
"name": "__init__",
"signature": "def __init__(self, alpha, nmax)"
},
{
"docstring": "basis evaluation function Use recursion relations for generalize... | 2 | stack_v2_sparse_classes_30k_train_011749 | Implement the Python class `LaguerreL` described below.
Class description:
Generalized Laguerre polynomials of a given order, :math:`\\alpha`. .. math:: L_n^{(\\alpha)}(x) Attributes ---------- nmax : int The maximum degree. alpha : float The associated Legendre function order index.
Method signatures and docstrings:... | Implement the Python class `LaguerreL` described below.
Class description:
Generalized Laguerre polynomials of a given order, :math:`\\alpha`. .. math:: L_n^{(\\alpha)}(x) Attributes ---------- nmax : int The maximum degree. alpha : float The associated Legendre function order index.
Method signatures and docstrings:... | c6341a58331deef3728cc43c627c556139deb673 | <|skeleton|>
class LaguerreL:
"""Generalized Laguerre polynomials of a given order, :math:`\\alpha`. .. math:: L_n^{(\\alpha)}(x) Attributes ---------- nmax : int The maximum degree. alpha : float The associated Legendre function order index."""
def __init__(self, alpha, nmax):
"""Create associated Leg... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LaguerreL:
"""Generalized Laguerre polynomials of a given order, :math:`\\alpha`. .. math:: L_n^{(\\alpha)}(x) Attributes ---------- nmax : int The maximum degree. alpha : float The associated Legendre function order index."""
def __init__(self, alpha, nmax):
"""Create associated Legendre basis D... | the_stack_v2_python_sparse | nitrogen/special.py | bchangala/nitrogen | train | 11 |
20a5a400a07bca00fa139aaa674f9ae90529efe5 | [
"self.logger_id = ''\nself.path_to_files = ''\nself.filenames = []\nself.file_format = ''\nself.first_col_data = ''\nself.delim = ''\nself.datetime_format = ''\nself.header_rows = 0\nself.skip_rows = []\nself.channel_names = []\nself.channel_units = []\nself.set_logger(logger)",
"self.logger_id = logger.logger_id... | <|body_start_0|>
self.logger_id = ''
self.path_to_files = ''
self.filenames = []
self.file_format = ''
self.first_col_data = ''
self.delim = ''
self.datetime_format = ''
self.header_rows = 0
self.skip_rows = []
self.channel_names = []
... | RawDataRead | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RawDataRead:
def __init__(self, logger=LoggerProperties()):
"""Set the logger filenames to be assessed and required read file properties. :param logger: LoggerProperties instance"""
<|body_0|>
def set_logger(self, logger):
"""Set the logger filenames and required rea... | stack_v2_sparse_classes_36k_train_013885 | 11,699 | no_license | [
{
"docstring": "Set the logger filenames to be assessed and required read file properties. :param logger: LoggerProperties instance",
"name": "__init__",
"signature": "def __init__(self, logger=LoggerProperties())"
},
{
"docstring": "Set the logger filenames and required read file properties.",
... | 4 | null | Implement the Python class `RawDataRead` described below.
Class description:
Implement the RawDataRead class.
Method signatures and docstrings:
- def __init__(self, logger=LoggerProperties()): Set the logger filenames to be assessed and required read file properties. :param logger: LoggerProperties instance
- def set... | Implement the Python class `RawDataRead` described below.
Class description:
Implement the RawDataRead class.
Method signatures and docstrings:
- def __init__(self, logger=LoggerProperties()): Set the logger filenames to be assessed and required read file properties. :param logger: LoggerProperties instance
- def set... | 78cae181f85a3cd2b6b6c1f1a57f62bbe5fbbda4 | <|skeleton|>
class RawDataRead:
def __init__(self, logger=LoggerProperties()):
"""Set the logger filenames to be assessed and required read file properties. :param logger: LoggerProperties instance"""
<|body_0|>
def set_logger(self, logger):
"""Set the logger filenames and required rea... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RawDataRead:
def __init__(self, logger=LoggerProperties()):
"""Set the logger filenames to be assessed and required read file properties. :param logger: LoggerProperties instance"""
self.logger_id = ''
self.path_to_files = ''
self.filenames = []
self.file_format = ''
... | the_stack_v2_python_sparse | src/main/python/core/raw_data_plot_properties.py | craigdickinson/DataLab | train | 1 | |
18f32e2252a26b1e73345ef621ed073d28fd329a | [
"self._dsets_info_file = dsets_info_filename\nself._root = ET.parse(self._dsets_info_file).getroot()\nself._hps = self._root.findall('hard_process')",
"for hp in self._hps:\n for dset in hp.findall('dset'):\n if dset.get('dtag') in filename:\n return (hp, dset.get('dtag'))\nreturn None"
] | <|body_start_0|>
self._dsets_info_file = dsets_info_filename
self._root = ET.parse(self._dsets_info_file).getroot()
self._hps = self._root.findall('hard_process')
<|end_body_0|>
<|body_start_1|>
for hp in self._hps:
for dset in hp.findall('dset'):
if dset.get... | DsetsInfo handles the access to the dsets_info.xml file from Python | DsetsInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DsetsInfo:
"""DsetsInfo handles the access to the dsets_info.xml file from Python"""
def __init__(self, dsets_info_filename='dsets_info_3.xml'):
"""__init__(self, dsets_info_filename='dsets_info_3.xml') dsets_info_filename -- the path to the XML file"""
<|body_0|>
def ma... | stack_v2_sparse_classes_36k_train_013886 | 2,676 | no_license | [
{
"docstring": "__init__(self, dsets_info_filename='dsets_info_3.xml') dsets_info_filename -- the path to the XML file",
"name": "__init__",
"signature": "def __init__(self, dsets_info_filename='dsets_info_3.xml')"
},
{
"docstring": "match_hp_by_dtag(self, filename) filename is a string that con... | 2 | null | Implement the Python class `DsetsInfo` described below.
Class description:
DsetsInfo handles the access to the dsets_info.xml file from Python
Method signatures and docstrings:
- def __init__(self, dsets_info_filename='dsets_info_3.xml'): __init__(self, dsets_info_filename='dsets_info_3.xml') dsets_info_filename -- t... | Implement the Python class `DsetsInfo` described below.
Class description:
DsetsInfo handles the access to the dsets_info.xml file from Python
Method signatures and docstrings:
- def __init__(self, dsets_info_filename='dsets_info_3.xml'): __init__(self, dsets_info_filename='dsets_info_3.xml') dsets_info_filename -- t... | 5d410679b6db48df664737a7f613d9434f8434f2 | <|skeleton|>
class DsetsInfo:
"""DsetsInfo handles the access to the dsets_info.xml file from Python"""
def __init__(self, dsets_info_filename='dsets_info_3.xml'):
"""__init__(self, dsets_info_filename='dsets_info_3.xml') dsets_info_filename -- the path to the XML file"""
<|body_0|>
def ma... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DsetsInfo:
"""DsetsInfo handles the access to the dsets_info.xml file from Python"""
def __init__(self, dsets_info_filename='dsets_info_3.xml'):
"""__init__(self, dsets_info_filename='dsets_info_3.xml') dsets_info_filename -- the path to the XML file"""
self._dsets_info_file = dsets_info_... | the_stack_v2_python_sparse | get_xsec_for_file.py | xealits/processing_ntuples | train | 0 |
a295cb7cef40c671d9f5f71efe8d7701ebfedbca | [
"cur = 0\ntotal = 0\nstart = 0\nfor i in range(len(gas)):\n cur += gas[i] - cost[i]\n total += gas[i] - cost[i]\n if cur < 0:\n start = i + 1\n cur = 0\nif total < 0:\n return -1\nreturn start",
"n = len(gas)\nfor i in range(n):\n start = (i + 1) % n\n count = gas[i] - cost[i]\n ... | <|body_start_0|>
cur = 0
total = 0
start = 0
for i in range(len(gas)):
cur += gas[i] - cost[i]
total += gas[i] - cost[i]
if cur < 0:
start = i + 1
cur = 0
if total < 0:
return -1
return start
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canCompleteCircuit(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
<|body_0|>
def canCompleteCircuit0(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int 暴力解法"""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_36k_train_013887 | 1,268 | no_license | [
{
"docstring": ":type gas: List[int] :type cost: List[int] :rtype: int",
"name": "canCompleteCircuit",
"signature": "def canCompleteCircuit(self, gas, cost)"
},
{
"docstring": ":type gas: List[int] :type cost: List[int] :rtype: int 暴力解法",
"name": "canCompleteCircuit0",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_001207 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canCompleteCircuit(self, gas, cost): :type gas: List[int] :type cost: List[int] :rtype: int
- def canCompleteCircuit0(self, gas, cost): :type gas: List[int] :type cost: List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canCompleteCircuit(self, gas, cost): :type gas: List[int] :type cost: List[int] :rtype: int
- def canCompleteCircuit0(self, gas, cost): :type gas: List[int] :type cost: List[... | 6e18c5d257840489cc3fb1079ae3804c743982a4 | <|skeleton|>
class Solution:
def canCompleteCircuit(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
<|body_0|>
def canCompleteCircuit0(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int 暴力解法"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canCompleteCircuit(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int"""
cur = 0
total = 0
start = 0
for i in range(len(gas)):
cur += gas[i] - cost[i]
total += gas[i] - cost[i]
if cur < 0:
... | the_stack_v2_python_sparse | 134.加油站.py | yangyuxiang1996/leetcode | train | 0 | |
048235c43b4b7868061d9dd44e8a692336440c3f | [
"\"\"\"Maybe add change troop structure?\"\"\"\nSTEP_SIZE = 10\ntroop = self.state[random.randint(0, len(self.state) - 1)]\nx, y = troop.get_pos()\nwhile True:\n dx, dy = (random.randint(-STEP_SIZE, STEP_SIZE), random.randint(-STEP_SIZE, STEP_SIZE))\n if util.in_margins((x + dx, y + dy)):\n troop.set_p... | <|body_start_0|>
"""Maybe add change troop structure?"""
STEP_SIZE = 10
troop = self.state[random.randint(0, len(self.state) - 1)]
x, y = troop.get_pos()
while True:
dx, dy = (random.randint(-STEP_SIZE, STEP_SIZE), random.randint(-STEP_SIZE, STEP_SIZE))
if... | Test annealer with a travelling salesman problem. | OptimalArmy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptimalArmy:
"""Test annealer with a travelling salesman problem."""
def move(self):
"""Moves a single troop to one of the possible directions"""
<|body_0|>
def energy(self):
"""Calculates the percent damage"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_36k_train_013888 | 2,167 | no_license | [
{
"docstring": "Moves a single troop to one of the possible directions",
"name": "move",
"signature": "def move(self)"
},
{
"docstring": "Calculates the percent damage",
"name": "energy",
"signature": "def energy(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017245 | Implement the Python class `OptimalArmy` described below.
Class description:
Test annealer with a travelling salesman problem.
Method signatures and docstrings:
- def move(self): Moves a single troop to one of the possible directions
- def energy(self): Calculates the percent damage | Implement the Python class `OptimalArmy` described below.
Class description:
Test annealer with a travelling salesman problem.
Method signatures and docstrings:
- def move(self): Moves a single troop to one of the possible directions
- def energy(self): Calculates the percent damage
<|skeleton|>
class OptimalArmy:
... | 091f0f7efafdf648eba62bc05a92f01b224638ba | <|skeleton|>
class OptimalArmy:
"""Test annealer with a travelling salesman problem."""
def move(self):
"""Moves a single troop to one of the possible directions"""
<|body_0|>
def energy(self):
"""Calculates the percent damage"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OptimalArmy:
"""Test annealer with a travelling salesman problem."""
def move(self):
"""Moves a single troop to one of the possible directions"""
"""Maybe add change troop structure?"""
STEP_SIZE = 10
troop = self.state[random.randint(0, len(self.state) - 1)]
x, y ... | the_stack_v2_python_sparse | simulated_annealing.py | MisterReally/Clash-of-Clans-AI | train | 1 |
524c53cdf7274980df7c783ea6f4ae2584b1a533 | [
"input_data = {}\ninput_data['title'] = kwargs.get('title', None)\ninput_data['description'] = kwargs.get('description', None)\ninput_data['tags'] = kwargs.get('tags', [])\ninput_data['categories'] = kwargs.get('categories', [])\ninput_data['video'] = kwargs.get('video', None)\nreturn input_data",
"input_data = {... | <|body_start_0|>
input_data = {}
input_data['title'] = kwargs.get('title', None)
input_data['description'] = kwargs.get('description', None)
input_data['tags'] = kwargs.get('tags', [])
input_data['categories'] = kwargs.get('categories', [])
input_data['video'] = kwargs.ge... | Validations for theclient information | VideoValidations | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VideoValidations:
"""Validations for theclient information"""
def validate_video_data(self, kwargs):
"""Runs all the individual client registration data validations in one function Args: kwargs (dict): request data Returns: input_data (dict): validated data"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_013889 | 1,862 | permissive | [
{
"docstring": "Runs all the individual client registration data validations in one function Args: kwargs (dict): request data Returns: input_data (dict): validated data",
"name": "validate_video_data",
"signature": "def validate_video_data(self, kwargs)"
},
{
"docstring": "Runs all the corporat... | 2 | stack_v2_sparse_classes_30k_val_000299 | Implement the Python class `VideoValidations` described below.
Class description:
Validations for theclient information
Method signatures and docstrings:
- def validate_video_data(self, kwargs): Runs all the individual client registration data validations in one function Args: kwargs (dict): request data Returns: inp... | Implement the Python class `VideoValidations` described below.
Class description:
Validations for theclient information
Method signatures and docstrings:
- def validate_video_data(self, kwargs): Runs all the individual client registration data validations in one function Args: kwargs (dict): request data Returns: inp... | 04ff9ebb5da482e5b2642a89654a5b5f0128eaaa | <|skeleton|>
class VideoValidations:
"""Validations for theclient information"""
def validate_video_data(self, kwargs):
"""Runs all the individual client registration data validations in one function Args: kwargs (dict): request data Returns: input_data (dict): validated data"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VideoValidations:
"""Validations for theclient information"""
def validate_video_data(self, kwargs):
"""Runs all the individual client registration data validations in one function Args: kwargs (dict): request data Returns: input_data (dict): validated data"""
input_data = {}
inpu... | the_stack_v2_python_sparse | app/api/videos/validators/validate_input.py | lunyamwis/laylinks-bend | train | 0 |
a2b22a60dab12bf7e7554da6c77aeab2692b3b5f | [
"n = len(triangle)\ndp = [[0] * n for _ in range(n)]\nfor i in range(n - 1, -1, -1):\n for j in range(len(triangle[i]) - 1, -1, -1):\n if i == n - 1:\n dp[i][j] = triangle[i][j]\n else:\n dp[i][j] = min(dp[i + 1][j + 1], dp[i + 1][j]) + triangle[i][j]\nreturn dp[0][0]",
"if ... | <|body_start_0|>
n = len(triangle)
dp = [[0] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(len(triangle[i]) - 1, -1, -1):
if i == n - 1:
dp[i][j] = triangle[i][j]
else:
dp[i][j] = min(dp[i ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minimumTotal(self, triangle):
""":type triangle: List[List[int]] :rtype: int"""
<|body_0|>
def minimumTotal2(self, triangle):
""":type triangle: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(triang... | stack_v2_sparse_classes_36k_train_013890 | 3,302 | no_license | [
{
"docstring": ":type triangle: List[List[int]] :rtype: int",
"name": "minimumTotal",
"signature": "def minimumTotal(self, triangle)"
},
{
"docstring": ":type triangle: List[List[int]] :rtype: int",
"name": "minimumTotal2",
"signature": "def minimumTotal2(self, triangle)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019841 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumTotal(self, triangle): :type triangle: List[List[int]] :rtype: int
- def minimumTotal2(self, triangle): :type triangle: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumTotal(self, triangle): :type triangle: List[List[int]] :rtype: int
- def minimumTotal2(self, triangle): :type triangle: List[List[int]] :rtype: int
<|skeleton|>
class... | 690b685048c8e89d26047b6bc48b5f9af7d59cbb | <|skeleton|>
class Solution:
def minimumTotal(self, triangle):
""":type triangle: List[List[int]] :rtype: int"""
<|body_0|>
def minimumTotal2(self, triangle):
""":type triangle: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minimumTotal(self, triangle):
""":type triangle: List[List[int]] :rtype: int"""
n = len(triangle)
dp = [[0] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(len(triangle[i]) - 1, -1, -1):
if i == n - 1:
... | the_stack_v2_python_sparse | 数组/120. 三角形最小路径和.py | SimmonsChen/LeetCode | train | 0 | |
eef1dec8dce7332730845825281d3197282ebc01 | [
"super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=timedelta(seconds=UPDATE_INTERVAL))\nsession = async_get_clientsession(hass)\nself.airq = AirQ(entry.data[CONF_IP_ADDRESS], entry.data[CONF_PASSWORD], session)\nself.device_id = entry.unique_id\nassert self.device_id is not None\nself.device_info = Devic... | <|body_start_0|>
super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=timedelta(seconds=UPDATE_INTERVAL))
session = async_get_clientsession(hass)
self.airq = AirQ(entry.data[CONF_IP_ADDRESS], entry.data[CONF_PASSWORD], session)
self.device_id = entry.unique_id
assert self... | Coordinator is responsible for querying the device at a specified route. | AirQCoordinator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AirQCoordinator:
"""Coordinator is responsible for querying the device at a specified route."""
def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Initialise a custom coordinator."""
<|body_0|>
async def _async_update_data(self) -> dict:
"""F... | stack_v2_sparse_classes_36k_train_013891 | 2,031 | permissive | [
{
"docstring": "Initialise a custom coordinator.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None"
},
{
"docstring": "Fetch the data from the device.",
"name": "_async_update_data",
"signature": "async def _async_update_data(self) ->... | 2 | stack_v2_sparse_classes_30k_train_016397 | Implement the Python class `AirQCoordinator` described below.
Class description:
Coordinator is responsible for querying the device at a specified route.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: Initialise a custom coordinator.
- async def _async_update_... | Implement the Python class `AirQCoordinator` described below.
Class description:
Coordinator is responsible for querying the device at a specified route.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: Initialise a custom coordinator.
- async def _async_update_... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class AirQCoordinator:
"""Coordinator is responsible for querying the device at a specified route."""
def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Initialise a custom coordinator."""
<|body_0|>
async def _async_update_data(self) -> dict:
"""F... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AirQCoordinator:
"""Coordinator is responsible for querying the device at a specified route."""
def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Initialise a custom coordinator."""
super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=timedelta(seconds=UPDATE... | the_stack_v2_python_sparse | homeassistant/components/airq/coordinator.py | home-assistant/core | train | 35,501 |
e84cbe88cb65b7ae6709666f376c9453d867f726 | [
"super().__init__(reduction=reduction, name='fenchel_young')\nself._batched = batched\nself._maximize = maximize\nself.func = func\nself.perturbed = perturbations.perturbed(func=func, num_samples=num_samples, sigma=sigma, noise=noise, batched=batched)",
"@tf.custom_gradient\ndef forward(theta):\n diff = self.p... | <|body_start_0|>
super().__init__(reduction=reduction, name='fenchel_young')
self._batched = batched
self._maximize = maximize
self.func = func
self.perturbed = perturbations.perturbed(func=func, num_samples=num_samples, sigma=sigma, noise=noise, batched=batched)
<|end_body_0|>
... | Implementation of a Fenchel Young loss. | FenchelYoungLoss | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FenchelYoungLoss:
"""Implementation of a Fenchel Young loss."""
def __init__(self, func=None, num_samples=1000, sigma=0.01, noise=perturbations._NORMAL, batched=True, maximize=True, reduction=tf.keras.losses.Reduction.SUM):
"""Initializes the Fenchel-Young loss. Args: func: the funct... | stack_v2_sparse_classes_36k_train_013892 | 3,623 | permissive | [
{
"docstring": "Initializes the Fenchel-Young loss. Args: func: the function whose argmax is to be differentiated by perturbation. num_samples: (int) the number of perturbed inputs. sigma: (float) the amount of noise to be considered noise: (str) the noise distribution to be used to sample perturbations. batche... | 2 | stack_v2_sparse_classes_30k_train_015121 | Implement the Python class `FenchelYoungLoss` described below.
Class description:
Implementation of a Fenchel Young loss.
Method signatures and docstrings:
- def __init__(self, func=None, num_samples=1000, sigma=0.01, noise=perturbations._NORMAL, batched=True, maximize=True, reduction=tf.keras.losses.Reduction.SUM): ... | Implement the Python class `FenchelYoungLoss` described below.
Class description:
Implementation of a Fenchel Young loss.
Method signatures and docstrings:
- def __init__(self, func=None, num_samples=1000, sigma=0.01, noise=perturbations._NORMAL, batched=True, maximize=True, reduction=tf.keras.losses.Reduction.SUM): ... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class FenchelYoungLoss:
"""Implementation of a Fenchel Young loss."""
def __init__(self, func=None, num_samples=1000, sigma=0.01, noise=perturbations._NORMAL, batched=True, maximize=True, reduction=tf.keras.losses.Reduction.SUM):
"""Initializes the Fenchel-Young loss. Args: func: the funct... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FenchelYoungLoss:
"""Implementation of a Fenchel Young loss."""
def __init__(self, func=None, num_samples=1000, sigma=0.01, noise=perturbations._NORMAL, batched=True, maximize=True, reduction=tf.keras.losses.Reduction.SUM):
"""Initializes the Fenchel-Young loss. Args: func: the function whose arg... | the_stack_v2_python_sparse | perturbations/fenchel_young.py | Jimmy-INL/google-research | train | 1 |
1bc906fc8646aa6e30f84b5f6c56e5cbc1e51e12 | [
"message = str.encode(str(record.geneid) + record.diseaseid)\nhexdigest = hashlib.sha256(message).hexdigest()\nreturn str(hexdigest)",
"try:\n parsed_df = pd.read_csv(StringIO(data))\n parsed_df = parsed_df.drop(columns=['DirectEvidence', 'InferenceChemicalName', 'InferenceScore', 'OmimIDs'])\n parsed_df... | <|body_start_0|>
message = str.encode(str(record.geneid) + record.diseaseid)
hexdigest = hashlib.sha256(message).hexdigest()
return str(hexdigest)
<|end_body_0|>
<|body_start_1|>
try:
parsed_df = pd.read_csv(StringIO(data))
parsed_df = parsed_df.drop(columns=['Di... | Implementation of CTD Database Parser. Comparative Toxicogenomics Gene-Disease Associations Database Parser. http://ctdbase.org/ | CtdParser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CtdParser:
"""Implementation of CTD Database Parser. Comparative Toxicogenomics Gene-Disease Associations Database Parser. http://ctdbase.org/"""
def hash_record(record: pd.Series) -> str:
"""Hash the ctd record to generate digest column. Arguments: record {pd.Series} -- The ctd reco... | stack_v2_sparse_classes_36k_train_013893 | 12,683 | permissive | [
{
"docstring": "Hash the ctd record to generate digest column. Arguments: record {pd.Series} -- The ctd record in form of pandas Series Returns: str -- the hex string of the computed digest",
"name": "hash_record",
"signature": "def hash_record(record: pd.Series) -> str"
},
{
"docstring": "Parse... | 2 | stack_v2_sparse_classes_30k_train_016259 | Implement the Python class `CtdParser` described below.
Class description:
Implementation of CTD Database Parser. Comparative Toxicogenomics Gene-Disease Associations Database Parser. http://ctdbase.org/
Method signatures and docstrings:
- def hash_record(record: pd.Series) -> str: Hash the ctd record to generate dig... | Implement the Python class `CtdParser` described below.
Class description:
Implementation of CTD Database Parser. Comparative Toxicogenomics Gene-Disease Associations Database Parser. http://ctdbase.org/
Method signatures and docstrings:
- def hash_record(record: pd.Series) -> str: Hash the ctd record to generate dig... | 83e36e24077169d141f25c357cb1009b79b78661 | <|skeleton|>
class CtdParser:
"""Implementation of CTD Database Parser. Comparative Toxicogenomics Gene-Disease Associations Database Parser. http://ctdbase.org/"""
def hash_record(record: pd.Series) -> str:
"""Hash the ctd record to generate digest column. Arguments: record {pd.Series} -- The ctd reco... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CtdParser:
"""Implementation of CTD Database Parser. Comparative Toxicogenomics Gene-Disease Associations Database Parser. http://ctdbase.org/"""
def hash_record(record: pd.Series) -> str:
"""Hash the ctd record to generate digest column. Arguments: record {pd.Series} -- The ctd record in form of... | the_stack_v2_python_sparse | geniepy/src/geniepy/datamgmt/parsers.py | cjflanagan/genie-1 | train | 0 |
a5ba3ba14e744d0c9ca6a5cce20d6a92d49e316c | [
"args = image_all.parse_args()\nper_page = args['per_page']\npage = args['page'] - 1\nfields = args.get('fields', '')\nimages = current_user.images.filter(deleted=False)\ntotal = images.count()\npages = int(total / per_page) + 1\nimages = images.skip(page * per_page).limit(per_page)\nif fields:\n images = images... | <|body_start_0|>
args = image_all.parse_args()
per_page = args['per_page']
page = args['page'] - 1
fields = args.get('fields', '')
images = current_user.images.filter(deleted=False)
total = images.count()
pages = int(total / per_page) + 1
images = images.s... | Images | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Images:
def get(self):
"""Returns all images"""
<|body_0|>
def post(self):
"""Creates an image"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
args = image_all.parse_args()
per_page = args['per_page']
page = args['page'] - 1
... | stack_v2_sparse_classes_36k_train_013894 | 6,500 | permissive | [
{
"docstring": "Returns all images",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Creates an image",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021180 | Implement the Python class `Images` described below.
Class description:
Implement the Images class.
Method signatures and docstrings:
- def get(self): Returns all images
- def post(self): Creates an image | Implement the Python class `Images` described below.
Class description:
Implement the Images class.
Method signatures and docstrings:
- def get(self): Returns all images
- def post(self): Creates an image
<|skeleton|>
class Images:
def get(self):
"""Returns all images"""
<|body_0|>
def post... | 9cce5d2f64944e2aa7ca829ca4032624e3305138 | <|skeleton|>
class Images:
def get(self):
"""Returns all images"""
<|body_0|>
def post(self):
"""Creates an image"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Images:
def get(self):
"""Returns all images"""
args = image_all.parse_args()
per_page = args['per_page']
page = args['page'] - 1
fields = args.get('fields', '')
images = current_user.images.filter(deleted=False)
total = images.count()
pages = in... | the_stack_v2_python_sparse | backend/webserver/api/images.py | jsbroks/coco-annotator | train | 1,987 | |
e5dcb2e437ddd215f33deb6ebe39726545c49fe5 | [
"super().__init__('LSTM', hidden_size, embedding_size, num_layers, device)\nself.embeddings = nn.Embedding(vocab_size, embedding_size)\nself.vocab_size = vocab_size\nself.dropout_layer = nn.Dropout(dropout)\nself.gates = {}\nself.decoder = nn.Linear(hidden_size, vocab_size)\nfor l in range(num_layers):\n input_s... | <|body_start_0|>
super().__init__('LSTM', hidden_size, embedding_size, num_layers, device)
self.embeddings = nn.Embedding(vocab_size, embedding_size)
self.vocab_size = vocab_size
self.dropout_layer = nn.Dropout(dropout)
self.gates = {}
self.decoder = nn.Linear(hidden_size... | Implementation of a LSTM language model that can process inputs token-wise or in sequences. | LSTMLanguageModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LSTMLanguageModel:
"""Implementation of a LSTM language model that can process inputs token-wise or in sequences."""
def __init__(self, vocab_size: int, hidden_size: int, embedding_size: int, num_layers: int, dropout: float, device: Device='cpu'):
"""Parameters ---------- vocab_size:... | stack_v2_sparse_classes_36k_train_013895 | 6,774 | no_license | [
{
"docstring": "Parameters ---------- vocab_size: int Size of input vocabulary. hidden_size: int Dimensionality of hidden activations. embedding_size: int Dimensionality of word embeddings. num_layers: int Number of RNN layers. dropout: float Probability of dropout layer that is being applied before decoding. d... | 5 | stack_v2_sparse_classes_30k_train_018607 | Implement the Python class `LSTMLanguageModel` described below.
Class description:
Implementation of a LSTM language model that can process inputs token-wise or in sequences.
Method signatures and docstrings:
- def __init__(self, vocab_size: int, hidden_size: int, embedding_size: int, num_layers: int, dropout: float,... | Implement the Python class `LSTMLanguageModel` described below.
Class description:
Implementation of a LSTM language model that can process inputs token-wise or in sequences.
Method signatures and docstrings:
- def __init__(self, vocab_size: int, hidden_size: int, embedding_size: int, num_layers: int, dropout: float,... | 6443bea8d325fa948e117b32a063e5383db2de14 | <|skeleton|>
class LSTMLanguageModel:
"""Implementation of a LSTM language model that can process inputs token-wise or in sequences."""
def __init__(self, vocab_size: int, hidden_size: int, embedding_size: int, num_layers: int, dropout: float, device: Device='cpu'):
"""Parameters ---------- vocab_size:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LSTMLanguageModel:
"""Implementation of a LSTM language model that can process inputs token-wise or in sequences."""
def __init__(self, vocab_size: int, hidden_size: int, embedding_size: int, num_layers: int, dropout: float, device: Device='cpu'):
"""Parameters ---------- vocab_size: int Size of ... | the_stack_v2_python_sparse | src/models/language_model.py | Kaleidophon/tenacious-toucan | train | 0 |
e9cb2ab51be36ac7a165ce58b1c64a669ac7adff | [
"event_type_alias = None\npayload: Dict[str, Any] = {}\nheaders = {'X-API-KEY': '{}'.format(params.get('token', ''))}\nurl = urljoin(self._base_url, etypeurl)\nresponse = requests.request(method, url, headers=headers, data=payload)\ntry:\n resp = response.json()\n if resp.get('success') or False:\n eve... | <|body_start_0|>
event_type_alias = None
payload: Dict[str, Any] = {}
headers = {'X-API-KEY': '{}'.format(params.get('token', ''))}
url = urljoin(self._base_url, etypeurl)
response = requests.request(method, url, headers=headers, data=payload)
try:
resp = resp... | Client will implement the service API, and should not contain any Demisto logic. Should only do requests and return data. | Client | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Client:
"""Client will implement the service API, and should not contain any Demisto logic. Should only do requests and return data."""
def get_event_types(self, method, etypeurl, params):
"""Fetch event types and alias using given parameters :param method: requests method to perform... | stack_v2_sparse_classes_36k_train_013896 | 20,365 | permissive | [
{
"docstring": "Fetch event types and alias using given parameters :param method: requests method to perform the desired action to be performed :param etypeurl: event type URL path :param params: parameters to be used as part of request :return: event types along with alias as a JSON",
"name": "get_event_ty... | 4 | null | Implement the Python class `Client` described below.
Class description:
Client will implement the service API, and should not contain any Demisto logic. Should only do requests and return data.
Method signatures and docstrings:
- def get_event_types(self, method, etypeurl, params): Fetch event types and alias using g... | Implement the Python class `Client` described below.
Class description:
Client will implement the service API, and should not contain any Demisto logic. Should only do requests and return data.
Method signatures and docstrings:
- def get_event_types(self, method, etypeurl, params): Fetch event types and alias using g... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class Client:
"""Client will implement the service API, and should not contain any Demisto logic. Should only do requests and return data."""
def get_event_types(self, method, etypeurl, params):
"""Fetch event types and alias using given parameters :param method: requests method to perform... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Client:
"""Client will implement the service API, and should not contain any Demisto logic. Should only do requests and return data."""
def get_event_types(self, method, etypeurl, params):
"""Fetch event types and alias using given parameters :param method: requests method to perform the desired ... | the_stack_v2_python_sparse | Packs/CybleEvents/Integrations/CybleEvents/CybleEvents.py | demisto/content | train | 1,023 |
f4a18906597ab9c90d04ebc0a0a290b303af67a4 | [
"if not s and (not t):\n return True\nsize_s, size_t = (len(s), len(t))\ni, j = (0, 0)\nwhile i < size_s and j < size_t:\n if s[i] == t[j]:\n i, j = (i + 1, j + 1)\n else:\n j += 1\nreturn i == size_s",
"if not s and (not t):\n return True\nsize_s, size_t = (len(s), len(t))\ndp = [[False... | <|body_start_0|>
if not s and (not t):
return True
size_s, size_t = (len(s), len(t))
i, j = (0, 0)
while i < size_s and j < size_t:
if s[i] == t[j]:
i, j = (i + 1, j + 1)
else:
j += 1
return i == size_s
<|end_bod... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
"""双指针法"""
<|body_0|>
def isSubsequence_1(self, s: str, t: str) -> bool:
"""动态规划"""
<|body_1|>
def isSubsequence_2(self, s: str, t: str) -> bool:
"""自底向上的动态规划"""
<|body_2|>
d... | stack_v2_sparse_classes_36k_train_013897 | 2,388 | no_license | [
{
"docstring": "双指针法",
"name": "isSubsequence",
"signature": "def isSubsequence(self, s: str, t: str) -> bool"
},
{
"docstring": "动态规划",
"name": "isSubsequence_1",
"signature": "def isSubsequence_1(self, s: str, t: str) -> bool"
},
{
"docstring": "自底向上的动态规划",
"name": "isSubse... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSubsequence(self, s: str, t: str) -> bool: 双指针法
- def isSubsequence_1(self, s: str, t: str) -> bool: 动态规划
- def isSubsequence_2(self, s: str, t: str) -> bool: 自底向上的动态规划
- d... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSubsequence(self, s: str, t: str) -> bool: 双指针法
- def isSubsequence_1(self, s: str, t: str) -> bool: 动态规划
- def isSubsequence_2(self, s: str, t: str) -> bool: 自底向上的动态规划
- d... | 3508e1ce089131b19603c3206aab4cf43023bb19 | <|skeleton|>
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
"""双指针法"""
<|body_0|>
def isSubsequence_1(self, s: str, t: str) -> bool:
"""动态规划"""
<|body_1|>
def isSubsequence_2(self, s: str, t: str) -> bool:
"""自底向上的动态规划"""
<|body_2|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
"""双指针法"""
if not s and (not t):
return True
size_s, size_t = (len(s), len(t))
i, j = (0, 0)
while i < size_s and j < size_t:
if s[i] == t[j]:
i, j = (i + 1, j + 1)
... | the_stack_v2_python_sparse | algorithm/leetcode/dp/17-判断子序列.py | lxconfig/UbuntuCode_bak | train | 0 | |
4a9c3d47c77c3afe195a78d36f406d1ead16b517 | [
"key_name = 'myapp/mydoc/key/'\nself.assertEqual(Blob.get_by_key_name(key_name), None)\nself.sign_in(self.peter)\nurl = '/docs/mydoc/key'\nresponse = self.app_client.put(url, 'data', content_type='text/plain')\nself.assertContains(response, '\"statusText\": \"Saved\"')\nself.assertEqual(Blob.get_by_key_name(key_nam... | <|body_start_0|>
key_name = 'myapp/mydoc/key/'
self.assertEqual(Blob.get_by_key_name(key_name), None)
self.sign_in(self.peter)
url = '/docs/mydoc/key'
response = self.app_client.put(url, 'data', content_type='text/plain')
self.assertContains(response, '"statusText": "Save... | RestApiTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestApiTest:
def test_crud(self):
"""Tests create, read, update, delete with REST API."""
<|body_0|>
def test_anonymous(self):
"""Anonymous user can create blobs in a public writable document."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
key_name... | stack_v2_sparse_classes_36k_train_013898 | 28,221 | no_license | [
{
"docstring": "Tests create, read, update, delete with REST API.",
"name": "test_crud",
"signature": "def test_crud(self)"
},
{
"docstring": "Anonymous user can create blobs in a public writable document.",
"name": "test_anonymous",
"signature": "def test_anonymous(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014466 | Implement the Python class `RestApiTest` described below.
Class description:
Implement the RestApiTest class.
Method signatures and docstrings:
- def test_crud(self): Tests create, read, update, delete with REST API.
- def test_anonymous(self): Anonymous user can create blobs in a public writable document. | Implement the Python class `RestApiTest` described below.
Class description:
Implement the RestApiTest class.
Method signatures and docstrings:
- def test_crud(self): Tests create, read, update, delete with REST API.
- def test_anonymous(self): Anonymous user can create blobs in a public writable document.
<|skeleto... | fb15f64b16d5cda6370ee185d047072de82f8d09 | <|skeleton|>
class RestApiTest:
def test_crud(self):
"""Tests create, read, update, delete with REST API."""
<|body_0|>
def test_anonymous(self):
"""Anonymous user can create blobs in a public writable document."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RestApiTest:
def test_crud(self):
"""Tests create, read, update, delete with REST API."""
key_name = 'myapp/mydoc/key/'
self.assertEqual(Blob.get_by_key_name(key_name), None)
self.sign_in(self.peter)
url = '/docs/mydoc/key'
response = self.app_client.put(url, 'd... | the_stack_v2_python_sparse | appengine/blobs/tests.py | mckoss/pageforest | train | 0 | |
33f54f850971a6e9051b931026ab1d7da71d4623 | [
"assert isinstance(model, torch.nn.Module)\nassert str(optimizer_type) in ['Adam', 'Adadelta', 'Adagrad', 'AdamW', 'SparseAdam', 'RMSprop', 'Rprop', 'LBFGS', 'ASGD', 'Adamax']\nself.model_type = model_type\nself.model = model\nself.optimizer_type = optimizer_type\nself.classify = classify\nself.optimizers = {}\nsel... | <|body_start_0|>
assert isinstance(model, torch.nn.Module)
assert str(optimizer_type) in ['Adam', 'Adadelta', 'Adagrad', 'AdamW', 'SparseAdam', 'RMSprop', 'Rprop', 'LBFGS', 'ASGD', 'Adamax']
self.model_type = model_type
self.model = model
self.optimizer_type = optimizer_type
... | Optimizer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Optimizer:
def __init__(self, model_type, model, optimizer_type, classify=False):
"""Wrapper for setting the model optimizer and learning rate schedulers using ReduceLROnPlateau; If the model type is 'ae' or 'vae' - var optimizers is a dict with separate optimizers for encoder, decoder, ... | stack_v2_sparse_classes_36k_train_013899 | 5,226 | permissive | [
{
"docstring": "Wrapper for setting the model optimizer and learning rate schedulers using ReduceLROnPlateau; If the model type is 'ae' or 'vae' - var optimizers is a dict with separate optimizers for encoder, decoder, latent and classifier. In case of 'lstm', var optimizers is an optimizer for lstm and TimeDis... | 3 | stack_v2_sparse_classes_30k_train_007977 | Implement the Python class `Optimizer` described below.
Class description:
Implement the Optimizer class.
Method signatures and docstrings:
- def __init__(self, model_type, model, optimizer_type, classify=False): Wrapper for setting the model optimizer and learning rate schedulers using ReduceLROnPlateau; If the mode... | Implement the Python class `Optimizer` described below.
Class description:
Implement the Optimizer class.
Method signatures and docstrings:
- def __init__(self, model_type, model, optimizer_type, classify=False): Wrapper for setting the model optimizer and learning rate schedulers using ReduceLROnPlateau; If the mode... | d4c5ff32ebdb9ee99a564e61a65dfd2443974a04 | <|skeleton|>
class Optimizer:
def __init__(self, model_type, model, optimizer_type, classify=False):
"""Wrapper for setting the model optimizer and learning rate schedulers using ReduceLROnPlateau; If the model type is 'ae' or 'vae' - var optimizers is a dict with separate optimizers for encoder, decoder, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Optimizer:
def __init__(self, model_type, model, optimizer_type, classify=False):
"""Wrapper for setting the model optimizer and learning rate schedulers using ReduceLROnPlateau; If the model type is 'ae' or 'vae' - var optimizers is a dict with separate optimizers for encoder, decoder, latent and cla... | the_stack_v2_python_sparse | traja/models/optimizers.py | traja-team/traja | train | 73 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.