blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1565e838be733eb91a1cb3ae88165fad76beb591 | [
"ionization_energy_from_nr = self.energy_nr_to_detectable_energy_function()\nionization_resolution = self._energy_parameters[self.detector_key]['sigma_ion']\nreturn _get_nr_resolution(energies_in_kev, ionization_energy_from_nr, ionization_resolution)",
"bg_rate_nr = 0.0033\nconv_units = 1000.0\nreturn self._flat_... | <|body_start_0|>
ionization_energy_from_nr = self.energy_nr_to_detectable_energy_function()
ionization_resolution = self._energy_parameters[self.detector_key]['sigma_ion']
return _get_nr_resolution(energies_in_kev, ionization_energy_from_nr, ionization_resolution)
<|end_body_0|>
<|body_start_1|... | SuperCdmsIzipGeNr | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SuperCdmsIzipGeNr:
def resolution(self, energies_in_kev):
"""Flat resolution"""
<|body_0|>
def background_function(self, energies_in_kev):
"""Flat bg rate"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ionization_energy_from_nr = self.energy_nr_to_... | stack_v2_sparse_classes_75kplus_train_003600 | 12,973 | permissive | [
{
"docstring": "Flat resolution",
"name": "resolution",
"signature": "def resolution(self, energies_in_kev)"
},
{
"docstring": "Flat bg rate",
"name": "background_function",
"signature": "def background_function(self, energies_in_kev)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020600 | Implement the Python class `SuperCdmsIzipGeNr` described below.
Class description:
Implement the SuperCdmsIzipGeNr class.
Method signatures and docstrings:
- def resolution(self, energies_in_kev): Flat resolution
- def background_function(self, energies_in_kev): Flat bg rate | Implement the Python class `SuperCdmsIzipGeNr` described below.
Class description:
Implement the SuperCdmsIzipGeNr class.
Method signatures and docstrings:
- def resolution(self, energies_in_kev): Flat resolution
- def background_function(self, energies_in_kev): Flat bg rate
<|skeleton|>
class SuperCdmsIzipGeNr:
... | f305b70229473de19178298b5ef4afa898f79fa0 | <|skeleton|>
class SuperCdmsIzipGeNr:
def resolution(self, energies_in_kev):
"""Flat resolution"""
<|body_0|>
def background_function(self, energies_in_kev):
"""Flat bg rate"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SuperCdmsIzipGeNr:
def resolution(self, energies_in_kev):
"""Flat resolution"""
ionization_energy_from_nr = self.energy_nr_to_detectable_energy_function()
ionization_resolution = self._energy_parameters[self.detector_key]['sigma_ion']
return _get_nr_resolution(energies_in_kev, ... | the_stack_v2_python_sparse | dddm/detectors/super_cdms.py | JoranAngevaare/dddm | train | 0 | |
f2fd975bcf31650bc785d5a241aae312d13ee7d4 | [
"try:\n self.ID = hash(ID)\nexcept:\n raise TypeError('Item IDs must be hashable')\nself.data, self.keyCache = ({}, {})\nself.writeTracker = DeferredTracker()\nif url:\n self.i = items.Items(self.ID, url[0], **kw)\nelse:\n self.i = items.Items(self.ID)\nself.isPreloadMode = False",
"d = self.loadAll()... | <|body_start_0|>
try:
self.ID = hash(ID)
except:
raise TypeError('Item IDs must be hashable')
self.data, self.keyCache = ({}, {})
self.writeTracker = DeferredTracker()
if url:
self.i = items.Items(self.ID, url[0], **kw)
else:
... | I am a base class for a database-persistent dictionary-like object uniquely identified by the hashable constructor argument I{ID}. Before you use any instance of me, you must specify the parameters for creating an SQLAlchemy database engine. A single argument is used, which specifies a connection to a database via an R... | PersistentDictBase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PersistentDictBase:
"""I am a base class for a database-persistent dictionary-like object uniquely identified by the hashable constructor argument I{ID}. Before you use any instance of me, you must specify the parameters for creating an SQLAlchemy database engine. A single argument is used, which... | stack_v2_sparse_classes_75kplus_train_003601 | 15,255 | no_license | [
{
"docstring": "Instantiates me with an item store keyed to the supplied hashable I{ID}. Ensures that I have access to a class-wide instance of a L{Search} object so that I can update the database's full-text index when writing values containing text content. In addition to any engine-specifying keywords suppli... | 5 | stack_v2_sparse_classes_30k_train_039925 | Implement the Python class `PersistentDictBase` described below.
Class description:
I am a base class for a database-persistent dictionary-like object uniquely identified by the hashable constructor argument I{ID}. Before you use any instance of me, you must specify the parameters for creating an SQLAlchemy database e... | Implement the Python class `PersistentDictBase` described below.
Class description:
I am a base class for a database-persistent dictionary-like object uniquely identified by the hashable constructor argument I{ID}. Before you use any instance of me, you must specify the parameters for creating an SQLAlchemy database e... | f8e1fd067a1d001006163e8c3316029f37af139c | <|skeleton|>
class PersistentDictBase:
"""I am a base class for a database-persistent dictionary-like object uniquely identified by the hashable constructor argument I{ID}. Before you use any instance of me, you must specify the parameters for creating an SQLAlchemy database engine. A single argument is used, which... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PersistentDictBase:
"""I am a base class for a database-persistent dictionary-like object uniquely identified by the hashable constructor argument I{ID}. Before you use any instance of me, you must specify the parameters for creating an SQLAlchemy database engine. A single argument is used, which specifies a ... | the_stack_v2_python_sparse | src/dsem/lib/sasync/pdict.py | D3f0/txscada | train | 9 |
90c9903ad7407436a873643fb1dfc9c9e5803a87 | [
"super(Keypoint2DLoss, self).__init__()\nif loss_type == 'l1':\n self.loss_fn = nn.L1Loss(reduction='none')\nelif loss_type == 'l2':\n self.loss_fn = nn.MSELoss(reduction='none')\nelse:\n raise NotImplementedError('Unsupported loss function')",
"conf = gt_keypoints_2d[:, :, :, -1].unsqueeze(-1).clone()\n... | <|body_start_0|>
super(Keypoint2DLoss, self).__init__()
if loss_type == 'l1':
self.loss_fn = nn.L1Loss(reduction='none')
elif loss_type == 'l2':
self.loss_fn = nn.MSELoss(reduction='none')
else:
raise NotImplementedError('Unsupported loss function')
<|... | Keypoint2DLoss | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Keypoint2DLoss:
def __init__(self, loss_type: str='l1'):
"""2D keypoint loss module. Args: loss_type (str): Choose between l1 and l2 losses."""
<|body_0|>
def forward(self, pred_keypoints_2d: torch.Tensor, gt_keypoints_2d: torch.Tensor) -> torch.Tensor:
"""Compute 2D... | stack_v2_sparse_classes_75kplus_train_003602 | 4,009 | permissive | [
{
"docstring": "2D keypoint loss module. Args: loss_type (str): Choose between l1 and l2 losses.",
"name": "__init__",
"signature": "def __init__(self, loss_type: str='l1')"
},
{
"docstring": "Compute 2D reprojection loss on the keypoints. Args: pred_keypoints_2d (torch.Tensor): Tensor of shape ... | 2 | stack_v2_sparse_classes_30k_train_046498 | Implement the Python class `Keypoint2DLoss` described below.
Class description:
Implement the Keypoint2DLoss class.
Method signatures and docstrings:
- def __init__(self, loss_type: str='l1'): 2D keypoint loss module. Args: loss_type (str): Choose between l1 and l2 losses.
- def forward(self, pred_keypoints_2d: torch... | Implement the Python class `Keypoint2DLoss` described below.
Class description:
Implement the Keypoint2DLoss class.
Method signatures and docstrings:
- def __init__(self, loss_type: str='l1'): 2D keypoint loss module. Args: loss_type (str): Choose between l1 and l2 losses.
- def forward(self, pred_keypoints_2d: torch... | dac2409c0b451b6dd5d91f03cbe7132aa495792f | <|skeleton|>
class Keypoint2DLoss:
def __init__(self, loss_type: str='l1'):
"""2D keypoint loss module. Args: loss_type (str): Choose between l1 and l2 losses."""
<|body_0|>
def forward(self, pred_keypoints_2d: torch.Tensor, gt_keypoints_2d: torch.Tensor) -> torch.Tensor:
"""Compute 2D... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Keypoint2DLoss:
def __init__(self, loss_type: str='l1'):
"""2D keypoint loss module. Args: loss_type (str): Choose between l1 and l2 losses."""
super(Keypoint2DLoss, self).__init__()
if loss_type == 'l1':
self.loss_fn = nn.L1Loss(reduction='none')
elif loss_type == ... | the_stack_v2_python_sparse | prohmr/models/losses.py | goyallon/ProHMR | train | 0 | |
5a757ea70e686dccd0091cad07e97c316343b434 | [
"if name == 'MNIST':\n ds = MNIST()\n return ds[name]\nelif name == 'MNIST-C':\n ds = MNIST()\n return ds[name]\nelif name == 'FashionMnist':\n ds = FashionMnist()\n return ds['Fashion']\nelif name == 'svhn_cropped':\n ds = SVHN()\n return ds['svhn_cropped']\nelif name == 'cifar10':\n ds ... | <|body_start_0|>
if name == 'MNIST':
ds = MNIST()
return ds[name]
elif name == 'MNIST-C':
ds = MNIST()
return ds[name]
elif name == 'FashionMnist':
ds = FashionMnist()
return ds['Fashion']
elif name == 'svhn_cropped'... | GetData | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetData:
def get_ds(name):
"""Get Dataset from DS folder :param name: Name dataset :return: x_data, y_data"""
<|body_0|>
def get_filter(x_data, y_data, list_values):
"""Filter data :param x_data: original x_data :param y_data: original y_data :param list_values: list... | stack_v2_sparse_classes_75kplus_train_003603 | 2,395 | permissive | [
{
"docstring": "Get Dataset from DS folder :param name: Name dataset :return: x_data, y_data",
"name": "get_ds",
"signature": "def get_ds(name)"
},
{
"docstring": "Filter data :param x_data: original x_data :param y_data: original y_data :param list_values: list values to take :return: new x_dat... | 3 | null | Implement the Python class `GetData` described below.
Class description:
Implement the GetData class.
Method signatures and docstrings:
- def get_ds(name): Get Dataset from DS folder :param name: Name dataset :return: x_data, y_data
- def get_filter(x_data, y_data, list_values): Filter data :param x_data: original x_... | Implement the Python class `GetData` described below.
Class description:
Implement the GetData class.
Method signatures and docstrings:
- def get_ds(name): Get Dataset from DS folder :param name: Name dataset :return: x_data, y_data
- def get_filter(x_data, y_data, list_values): Filter data :param x_data: original x_... | 91dbb0eebba64f1fa2c18562e2c9f35f532ef7c0 | <|skeleton|>
class GetData:
def get_ds(name):
"""Get Dataset from DS folder :param name: Name dataset :return: x_data, y_data"""
<|body_0|>
def get_filter(x_data, y_data, list_values):
"""Filter data :param x_data: original x_data :param y_data: original y_data :param list_values: list... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GetData:
def get_ds(name):
"""Get Dataset from DS folder :param name: Name dataset :return: x_data, y_data"""
if name == 'MNIST':
ds = MNIST()
return ds[name]
elif name == 'MNIST-C':
ds = MNIST()
return ds[name]
elif name == 'Fash... | the_stack_v2_python_sparse | src/python_code/DataSets/getData.py | ipmach/Thesis2021 | train | 0 | |
b571df4713bca6425bbacd1cec81705812de801b | [
"if self.current_user is None:\n return\nfilter_dict = {}\nfilters = [('name', str)]\nfor filt in filters:\n if filt[0] in self.request.arguments:\n if filt[1] == str:\n filter_dict[filt[0]] = self.request.arguments[filt[0]][0].decode('utf-8')\n else:\n filter_dict[filt[0]]... | <|body_start_0|>
if self.current_user is None:
return
filter_dict = {}
filters = [('name', str)]
for filt in filters:
if filt[0] in self.request.arguments:
if filt[1] == str:
filter_dict[filt[0]] = self.request.arguments[filt[0]... | The RoleCollection API. Ops that interact with the Role collection. | RoleCollectionAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoleCollectionAPI:
"""The RoleCollection API. Ops that interact with the Role collection."""
def get(self):
"""HTTP GET method"""
<|body_0|>
def post(self):
"""HTTP POST method."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if self.current_use... | stack_v2_sparse_classes_75kplus_train_003604 | 4,210 | permissive | [
{
"docstring": "HTTP GET method",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "HTTP POST method.",
"name": "post",
"signature": "def post(self)"
}
] | 2 | null | Implement the Python class `RoleCollectionAPI` described below.
Class description:
The RoleCollection API. Ops that interact with the Role collection.
Method signatures and docstrings:
- def get(self): HTTP GET method
- def post(self): HTTP POST method. | Implement the Python class `RoleCollectionAPI` described below.
Class description:
The RoleCollection API. Ops that interact with the Role collection.
Method signatures and docstrings:
- def get(self): HTTP GET method
- def post(self): HTTP POST method.
<|skeleton|>
class RoleCollectionAPI:
"""The RoleCollection... | c8e0c908af1954a8b41d0f6de23d08589564f0ab | <|skeleton|>
class RoleCollectionAPI:
"""The RoleCollection API. Ops that interact with the Role collection."""
def get(self):
"""HTTP GET method"""
<|body_0|>
def post(self):
"""HTTP POST method."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RoleCollectionAPI:
"""The RoleCollection API. Ops that interact with the Role collection."""
def get(self):
"""HTTP GET method"""
if self.current_user is None:
return
filter_dict = {}
filters = [('name', str)]
for filt in filters:
if filt[0]... | the_stack_v2_python_sparse | zoe_api/rest_api/role.py | DistributedSystemsGroup/zoe | train | 60 |
a66a565e4a7b254f554f0f3ad1569bac98445be2 | [
"self.partial = []\na = 0\nfor i in nums:\n a += i\n self.partial.append(a)\nprint('partial sum', self.partial)",
"if i == 0:\n return self.partial[j]\nelse:\n return self.partial[j] - self.partial[i - 1]"
] | <|body_start_0|>
self.partial = []
a = 0
for i in nums:
a += i
self.partial.append(a)
print('partial sum', self.partial)
<|end_body_0|>
<|body_start_1|>
if i == 0:
return self.partial[j]
else:
return self.partial[j] - self.... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.partial = []
a = 0
for i in nums:
... | stack_v2_sparse_classes_75kplus_train_003605 | 1,418 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, i, j)"
}
] | 2 | null | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int
<|skeleton|>
class NumArray:
def __init__(self, nums):
... | 483f0c93faca8ccaf038b77ebe2fa712f6b0c6bc | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
self.partial = []
a = 0
for i in nums:
a += i
self.partial.append(a)
print('partial sum', self.partial)
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: in... | the_stack_v2_python_sparse | Algorithms and Data Structures Practice/LeetCode Questions/Easy/303. Range Sum Query - Immutable.py | harman666666/Algorithms-Data-Structures-and-Design | train | 3 | |
5e9791417050a60409cd4a1b3d7cc4863b9a7134 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ManagedDeviceOverview()",
"from .device_exchange_access_state_summary import DeviceExchangeAccessStateSummary\nfrom .device_operating_system_summary import DeviceOperatingSystemSummary\nfrom .entity import Entity\nfrom .device_exchange... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ManagedDeviceOverview()
<|end_body_0|>
<|body_start_1|>
from .device_exchange_access_state_summary import DeviceExchangeAccessStateSummary
from .device_operating_system_summary import De... | Summary data for managed devices | ManagedDeviceOverview | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ManagedDeviceOverview:
"""Summary data for managed devices"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ManagedDeviceOverview:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to... | stack_v2_sparse_classes_75kplus_train_003606 | 4,046 | 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: ManagedDeviceOverview",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminat... | 3 | stack_v2_sparse_classes_30k_train_035923 | Implement the Python class `ManagedDeviceOverview` described below.
Class description:
Summary data for managed devices
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ManagedDeviceOverview: Creates a new instance of the appropriate class based on discr... | Implement the Python class `ManagedDeviceOverview` described below.
Class description:
Summary data for managed devices
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ManagedDeviceOverview: Creates a new instance of the appropriate class based on discr... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ManagedDeviceOverview:
"""Summary data for managed devices"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ManagedDeviceOverview:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ManagedDeviceOverview:
"""Summary data for managed devices"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ManagedDeviceOverview:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the dis... | the_stack_v2_python_sparse | msgraph/generated/models/managed_device_overview.py | microsoftgraph/msgraph-sdk-python | train | 135 |
18927d88eab6aaf565372ecb99ee9e18706c1b6c | [
"mask = APPROXIMATIONS['sign'](x.gt(0.0))\nctx['mask'] = mask\nreturn x * mask",
"mask = ctx['mask']\nres_grad = grad * mask\nreturn res_grad"
] | <|body_start_0|>
mask = APPROXIMATIONS['sign'](x.gt(0.0))
ctx['mask'] = mask
return x * mask
<|end_body_0|>
<|body_start_1|>
mask = ctx['mask']
res_grad = grad * mask
return res_grad
<|end_body_1|>
| The sigmoid gradient function. | GradReLU | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GradReLU:
"""The sigmoid gradient function."""
def forward(ctx: Dict[str, Any], x: MPCTensor) -> MPCTensor:
"""Perform the feedforward and compute the result for the ReLU operation. Args: ctx (Dict[str, Any]): Context used to save information needed in the backward pass x (MPCTensor)... | stack_v2_sparse_classes_75kplus_train_003607 | 27,230 | permissive | [
{
"docstring": "Perform the feedforward and compute the result for the ReLU operation. Args: ctx (Dict[str, Any]): Context used to save information needed in the backward pass x (MPCTensor): The operand on which to apply the sigmoid function Returns: relu(x) (MPCTensor): The sigmoid approximation applied on the... | 2 | null | Implement the Python class `GradReLU` described below.
Class description:
The sigmoid gradient function.
Method signatures and docstrings:
- def forward(ctx: Dict[str, Any], x: MPCTensor) -> MPCTensor: Perform the feedforward and compute the result for the ReLU operation. Args: ctx (Dict[str, Any]): Context used to s... | Implement the Python class `GradReLU` described below.
Class description:
The sigmoid gradient function.
Method signatures and docstrings:
- def forward(ctx: Dict[str, Any], x: MPCTensor) -> MPCTensor: Perform the feedforward and compute the result for the ReLU operation. Args: ctx (Dict[str, Any]): Context used to s... | ee6ac74050acd03c3088104855d0b8e4ab3e03fa | <|skeleton|>
class GradReLU:
"""The sigmoid gradient function."""
def forward(ctx: Dict[str, Any], x: MPCTensor) -> MPCTensor:
"""Perform the feedforward and compute the result for the ReLU operation. Args: ctx (Dict[str, Any]): Context used to save information needed in the backward pass x (MPCTensor)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GradReLU:
"""The sigmoid gradient function."""
def forward(ctx: Dict[str, Any], x: MPCTensor) -> MPCTensor:
"""Perform the feedforward and compute the result for the ReLU operation. Args: ctx (Dict[str, Any]): Context used to save information needed in the backward pass x (MPCTensor): The operand... | the_stack_v2_python_sparse | src/sympc/grads/grad_functions.py | shubhank-saxena/SyMPC | train | 1 |
512b145a65da12587d310400d972040efbcf7822 | [
"self.gate_idx = np.random.randint(0, self.n_expert, size=(200,)).astype(self.dtype)\nexpert_count = count(self.gate_idx, self.n_expert * self.n_worker)\ncapacity = np.random.randint(10, 200, size=(self.n_expert,))\nself.expert_count = limit_by_capacity(expert_count, capacity, self.n_worker).astype(self.dtype)\nsel... | <|body_start_0|>
self.gate_idx = np.random.randint(0, self.n_expert, size=(200,)).astype(self.dtype)
expert_count = count(self.gate_idx, self.n_expert * self.n_worker)
capacity = np.random.randint(10, 200, size=(self.n_expert,))
self.expert_count = limit_by_capacity(expert_count, capacit... | TestPruneGateByCapacityAPI | TestPruneGateByCapacityAPI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestPruneGateByCapacityAPI:
"""TestPruneGateByCapacityAPI"""
def init_test_case(self):
"""init_test_case"""
<|body_0|>
def setUp(self):
"""setUp"""
<|body_1|>
def test_MoE_prune_gate_by_capacity_static(self):
"""test_MoE_prune_gate_by_capacit... | stack_v2_sparse_classes_75kplus_train_003608 | 4,813 | no_license | [
{
"docstring": "init_test_case",
"name": "init_test_case",
"signature": "def init_test_case(self)"
},
{
"docstring": "setUp",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "test_MoE_prune_gate_by_capacity_static",
"name": "test_MoE_prune_gate_by_capacity_s... | 4 | stack_v2_sparse_classes_30k_train_022483 | Implement the Python class `TestPruneGateByCapacityAPI` described below.
Class description:
TestPruneGateByCapacityAPI
Method signatures and docstrings:
- def init_test_case(self): init_test_case
- def setUp(self): setUp
- def test_MoE_prune_gate_by_capacity_static(self): test_MoE_prune_gate_by_capacity_static
- def ... | Implement the Python class `TestPruneGateByCapacityAPI` described below.
Class description:
TestPruneGateByCapacityAPI
Method signatures and docstrings:
- def init_test_case(self): init_test_case
- def setUp(self): setUp
- def test_MoE_prune_gate_by_capacity_static(self): test_MoE_prune_gate_by_capacity_static
- def ... | bd3790ce72a2a26611b5eda3901651b5a809348f | <|skeleton|>
class TestPruneGateByCapacityAPI:
"""TestPruneGateByCapacityAPI"""
def init_test_case(self):
"""init_test_case"""
<|body_0|>
def setUp(self):
"""setUp"""
<|body_1|>
def test_MoE_prune_gate_by_capacity_static(self):
"""test_MoE_prune_gate_by_capacit... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestPruneGateByCapacityAPI:
"""TestPruneGateByCapacityAPI"""
def init_test_case(self):
"""init_test_case"""
self.gate_idx = np.random.randint(0, self.n_expert, size=(200,)).astype(self.dtype)
expert_count = count(self.gate_idx, self.n_expert * self.n_worker)
capacity = np.... | the_stack_v2_python_sparse | distributed/CE_API/case/dist_MoE_prune_gate_by_capacity.py | PaddlePaddle/PaddleTest | train | 42 |
e41c2460f7feed261955fe031e00d484d5c107f1 | [
"self.model = ThreeDEPN()\nself.model.load_state_dict(torch.load(ckpt, map_location='cpu'))\nself.model.eval()\nself.truncation_distance = 3",
"input_sdf = np.clip(input_sdf, a_min=-self.truncation_distance, a_max=self.truncation_distance)\ntarget_df = np.clip(target_df, a_min=0, a_max=self.truncation_distance)\n... | <|body_start_0|>
self.model = ThreeDEPN()
self.model.load_state_dict(torch.load(ckpt, map_location='cpu'))
self.model.eval()
self.truncation_distance = 3
<|end_body_0|>
<|body_start_1|>
input_sdf = np.clip(input_sdf, a_min=-self.truncation_distance, a_max=self.truncation_distanc... | InferenceHandler3DEPN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InferenceHandler3DEPN:
def __init__(self, ckpt):
""":param ckpt: checkpoint path to weights of the trained network"""
<|body_0|>
def infer_single(self, input_sdf, target_df):
"""Reconstruct a full shape given a partial observation :param input_sdf: Input grid with pa... | stack_v2_sparse_classes_75kplus_train_003609 | 1,860 | no_license | [
{
"docstring": ":param ckpt: checkpoint path to weights of the trained network",
"name": "__init__",
"signature": "def __init__(self, ckpt)"
},
{
"docstring": "Reconstruct a full shape given a partial observation :param input_sdf: Input grid with partial SDF of shape 32x32x32 :param target_df: T... | 2 | stack_v2_sparse_classes_30k_train_025770 | Implement the Python class `InferenceHandler3DEPN` described below.
Class description:
Implement the InferenceHandler3DEPN class.
Method signatures and docstrings:
- def __init__(self, ckpt): :param ckpt: checkpoint path to weights of the trained network
- def infer_single(self, input_sdf, target_df): Reconstruct a f... | Implement the Python class `InferenceHandler3DEPN` described below.
Class description:
Implement the InferenceHandler3DEPN class.
Method signatures and docstrings:
- def __init__(self, ckpt): :param ckpt: checkpoint path to weights of the trained network
- def infer_single(self, input_sdf, target_df): Reconstruct a f... | a98d61403017317eb2b5da9760f78a19c76622e4 | <|skeleton|>
class InferenceHandler3DEPN:
def __init__(self, ckpt):
""":param ckpt: checkpoint path to weights of the trained network"""
<|body_0|>
def infer_single(self, input_sdf, target_df):
"""Reconstruct a full shape given a partial observation :param input_sdf: Input grid with pa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InferenceHandler3DEPN:
def __init__(self, ckpt):
""":param ckpt: checkpoint path to weights of the trained network"""
self.model = ThreeDEPN()
self.model.load_state_dict(torch.load(ckpt, map_location='cpu'))
self.model.eval()
self.truncation_distance = 3
def infer_... | the_stack_v2_python_sparse | E3/exercise_3/inference/infer_3depn.py | nazmicancalik/ml3d | train | 7 | |
7a75d894b23309893900d07e8fdbe5a5a3e080a5 | [
"assert 0.0 <= mixing_beta <= 1.0\nsuper().__init__(model)\nself._observation_keys = [f'RMSE/{properties[0]}', f'RMSE/{properties[1]}', 'total']\nself._mixing_beta = mixing_beta\nif mixing_beta == 0.0:\n warnings.warn('If mixing_beta=0.0, you should use loss function type `zeroth` instead of `first`.')",
"inpu... | <|body_start_0|>
assert 0.0 <= mixing_beta <= 1.0
super().__init__(model)
self._observation_keys = [f'RMSE/{properties[0]}', f'RMSE/{properties[1]}', 'total']
self._mixing_beta = mixing_beta
if mixing_beta == 0.0:
warnings.warn('If mixing_beta=0.0, you should use loss... | Loss function to optimize 0th and 1st-order property. | First | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class First:
"""Loss function to optimize 0th and 1st-order property."""
def __init__(self, model, properties, mixing_beta, **_):
"""Args: model (HighDimensionalNNP): HDNNP object to optimize parameters. properties (list [str]): Names of properties to optimize. mixing_beta (float): Mixing ... | stack_v2_sparse_classes_75kplus_train_003610 | 2,922 | permissive | [
{
"docstring": "Args: model (HighDimensionalNNP): HDNNP object to optimize parameters. properties (list [str]): Names of properties to optimize. mixing_beta (float): Mixing parameter of errors of 0th and 1st order. It accepts 0.0 to 1.0. If 0.0 it optimizes HDNNP by only 0th order property and it is equal to lo... | 2 | stack_v2_sparse_classes_30k_train_019522 | Implement the Python class `First` described below.
Class description:
Loss function to optimize 0th and 1st-order property.
Method signatures and docstrings:
- def __init__(self, model, properties, mixing_beta, **_): Args: model (HighDimensionalNNP): HDNNP object to optimize parameters. properties (list [str]): Name... | Implement the Python class `First` described below.
Class description:
Loss function to optimize 0th and 1st-order property.
Method signatures and docstrings:
- def __init__(self, model, properties, mixing_beta, **_): Args: model (HighDimensionalNNP): HDNNP object to optimize parameters. properties (list [str]): Name... | 394544bf8e89534fa535ebfbc7fc8ecab870f17e | <|skeleton|>
class First:
"""Loss function to optimize 0th and 1st-order property."""
def __init__(self, model, properties, mixing_beta, **_):
"""Args: model (HighDimensionalNNP): HDNNP object to optimize parameters. properties (list [str]): Names of properties to optimize. mixing_beta (float): Mixing ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class First:
"""Loss function to optimize 0th and 1st-order property."""
def __init__(self, model, properties, mixing_beta, **_):
"""Args: model (HighDimensionalNNP): HDNNP object to optimize parameters. properties (list [str]): Names of properties to optimize. mixing_beta (float): Mixing parameter of ... | the_stack_v2_python_sparse | hdnnpy/training/loss_function/first.py | eminamitani/hdnnpy-update | train | 1 |
fd31f0e46335ac30cc4a155376e618adb2d493c0 | [
"if not root:\n return []\nfrom collections import deque\nres, queue = ([], deque())\nqueue.append(root)\nwhile queue:\n node = queue.popleft()\n if node:\n res.append(str(node.val))\n queue.append(node.left)\n queue.append(node.right)\n else:\n res.append('X')\ns = ','.join(... | <|body_start_0|>
if not root:
return []
from collections import deque
res, queue = ([], deque())
queue.append(root)
while queue:
node = queue.popleft()
if node:
res.append(str(node.val))
queue.append(node.left)
... | Codec2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec2:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_75kplus_train_003611 | 2,730 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_024338 | Implement the Python class `Codec2` described below.
Class description:
Implement the Codec2 class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtyp... | Implement the Python class `Codec2` described below.
Class description:
Implement the Codec2 class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtyp... | 8808db52630b34cc43daaa4a7dbfb1998acc7ee4 | <|skeleton|>
class Codec2:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec2:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return []
from collections import deque
res, queue = ([], deque())
queue.append(root)
while queue:
node = queue.popl... | the_stack_v2_python_sparse | Week_03/297.二叉树的序列化与反序列化.py | lvjiujin/algorithm016 | train | 1 | |
023bfd34c453b2458a6fc054d60fe99290dab58f | [
"super().__init__()\nself.depth = depth\nself.embedding_dim = embedding_dim\nself.num_heads = num_heads\nself.mlp_dim = mlp_dim\nself.layers = nn.LayerList()\nfor i in range(depth):\n self.layers.append(TwoWayAttentionBlock(embedding_dim=embedding_dim, num_heads=num_heads, mlp_dim=mlp_dim, activation=activation,... | <|body_start_0|>
super().__init__()
self.depth = depth
self.embedding_dim = embedding_dim
self.num_heads = num_heads
self.mlp_dim = mlp_dim
self.layers = nn.LayerList()
for i in range(depth):
self.layers.append(TwoWayAttentionBlock(embedding_dim=embedd... | TwoWayTransformer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwoWayTransformer:
def __init__(self, depth: int, embedding_dim: int, num_heads: int, mlp_dim: int, activation: Type[nn.Layer]=nn.ReLU, attention_downsample_rate: int=2) -> None:
"""A transformer decoder that attends to an input image using queries whose positional embedding is supplied.... | stack_v2_sparse_classes_75kplus_train_003612 | 8,182 | permissive | [
{
"docstring": "A transformer decoder that attends to an input image using queries whose positional embedding is supplied. Args: depth (int): number of layers in the transformer embedding_dim (int): the channel dimension for the input embeddings num_heads (int): the number of heads for multihead attention. Must... | 2 | stack_v2_sparse_classes_30k_train_052085 | Implement the Python class `TwoWayTransformer` described below.
Class description:
Implement the TwoWayTransformer class.
Method signatures and docstrings:
- def __init__(self, depth: int, embedding_dim: int, num_heads: int, mlp_dim: int, activation: Type[nn.Layer]=nn.ReLU, attention_downsample_rate: int=2) -> None: ... | Implement the Python class `TwoWayTransformer` described below.
Class description:
Implement the TwoWayTransformer class.
Method signatures and docstrings:
- def __init__(self, depth: int, embedding_dim: int, num_heads: int, mlp_dim: int, activation: Type[nn.Layer]=nn.ReLU, attention_downsample_rate: int=2) -> None: ... | 2c8c35a8949fef74599f5ec557d340a14415f20d | <|skeleton|>
class TwoWayTransformer:
def __init__(self, depth: int, embedding_dim: int, num_heads: int, mlp_dim: int, activation: Type[nn.Layer]=nn.ReLU, attention_downsample_rate: int=2) -> None:
"""A transformer decoder that attends to an input image using queries whose positional embedding is supplied.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TwoWayTransformer:
def __init__(self, depth: int, embedding_dim: int, num_heads: int, mlp_dim: int, activation: Type[nn.Layer]=nn.ReLU, attention_downsample_rate: int=2) -> None:
"""A transformer decoder that attends to an input image using queries whose positional embedding is supplied. Args: depth (... | the_stack_v2_python_sparse | contrib/SegmentAnything/segment_anything/modeling/transformer.py | PaddlePaddle/PaddleSeg | train | 8,531 | |
55b1e02e9c4f37b52174cf1633a0778afd7d1f5e | [
"self.sums = [0 for i in range(len(nums))]\nif len(nums) > 0:\n self.sums[0] = nums[0]\nfor i in range(1, len(nums)):\n self.sums[i] = self.sums[i - 1] + nums[i]",
"if i == 0:\n return self.sums[j]\nelse:\n return self.sums[j] - self.sums[i - 1]"
] | <|body_start_0|>
self.sums = [0 for i in range(len(nums))]
if len(nums) > 0:
self.sums[0] = nums[0]
for i in range(1, len(nums)):
self.sums[i] = self.sums[i - 1] + nums[i]
<|end_body_0|>
<|body_start_1|>
if i == 0:
return self.sums[j]
else:
... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.sums = [0 for i in range(len(nums))]
if len(nu... | stack_v2_sparse_classes_75kplus_train_003613 | 689 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, i, j)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000530 | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int
<|skeleton|>
class NumArray:
def __init__(self, nums):
... | bf54a0c12f9bc2986e1fd6e62255830802fbcf43 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
self.sums = [0 for i in range(len(nums))]
if len(nums) > 0:
self.sums[0] = nums[0]
for i in range(1, len(nums)):
self.sums[i] = self.sums[i - 1] + nums[i]
def sumRange(self, i, j):
... | the_stack_v2_python_sparse | ALG/303sumRange-2.py | scientiacoder/ALG | train | 0 | |
4631d101572c10b714fb8942248f1adfc729600a | [
"from .index import ArtifactReference\ndel_index_ids = [obj.index_id() for obj in objects_deleted]\ndeleted_aref_ids = [aref._id for aref in ArtifactReference.query.find(dict(_id={'$in': del_index_ids}))]\ncls = self.__class__\ncls.to_add -= set(deleted_aref_ids)\ncls.to_delete |= set(del_index_ids)\ncls.to_add |= ... | <|body_start_0|>
from .index import ArtifactReference
del_index_ids = [obj.index_id() for obj in objects_deleted]
deleted_aref_ids = [aref._id for aref in ArtifactReference.query.find(dict(_id={'$in': del_index_ids}))]
cls = self.__class__
cls.to_add -= set(deleted_aref_ids)
... | Tracks needed search index operations over the life of a :class:`ming.odm.session.ThreadLocalODMSession` session, and performs them in a batch when :meth:`flush` is called. | BatchIndexer | [
"OFL-1.1",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchIndexer:
"""Tracks needed search index operations over the life of a :class:`ming.odm.session.ThreadLocalODMSession` session, and performs them in a batch when :meth:`flush` is called."""
def update_index(self, objects_deleted, arefs_added):
"""Caches adds and deletes for handli... | stack_v2_sparse_classes_75kplus_train_003614 | 10,838 | permissive | [
{
"docstring": "Caches adds and deletes for handling later. Called after each flush of the parent session. :param objects_deleted: :class:`allura.model.artifact.Artifact` instances that were deleted in the flush. :param arefs_added: :class:`allura.model.artifact.ArtifactReference` instances for all ``Artifact``... | 3 | stack_v2_sparse_classes_30k_train_018402 | Implement the Python class `BatchIndexer` described below.
Class description:
Tracks needed search index operations over the life of a :class:`ming.odm.session.ThreadLocalODMSession` session, and performs them in a batch when :meth:`flush` is called.
Method signatures and docstrings:
- def update_index(self, objects_... | Implement the Python class `BatchIndexer` described below.
Class description:
Tracks needed search index operations over the life of a :class:`ming.odm.session.ThreadLocalODMSession` session, and performs them in a batch when :meth:`flush` is called.
Method signatures and docstrings:
- def update_index(self, objects_... | 7e602764a67883d49736a72271987060dab47ecc | <|skeleton|>
class BatchIndexer:
"""Tracks needed search index operations over the life of a :class:`ming.odm.session.ThreadLocalODMSession` session, and performs them in a batch when :meth:`flush` is called."""
def update_index(self, objects_deleted, arefs_added):
"""Caches adds and deletes for handli... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BatchIndexer:
"""Tracks needed search index operations over the life of a :class:`ming.odm.session.ThreadLocalODMSession` session, and performs them in a batch when :meth:`flush` is called."""
def update_index(self, objects_deleted, arefs_added):
"""Caches adds and deletes for handling later. Cal... | the_stack_v2_python_sparse | Allura/allura/model/session.py | apache/allura | train | 130 |
0a92a75286e46fce8ae7dfcdbe79f8559700f0b1 | [
"pictures = os.listdir(self.__class__.picture_paths)\nfor picture in pictures:\n picture_path = os.path.join(self.picture_paths, picture)\n self.get_picture_exif(picture_path)",
"img_file = open(picture_name, 'rb')\npicture_info = exifread.process_file(img_file)\nif picture_info:\n for tag, value in pict... | <|body_start_0|>
pictures = os.listdir(self.__class__.picture_paths)
for picture in pictures:
picture_path = os.path.join(self.picture_paths, picture)
self.get_picture_exif(picture_path)
<|end_body_0|>
<|body_start_1|>
img_file = open(picture_name, 'rb')
picture_... | MetaPicture | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetaPicture:
def read_picture(self):
"""读取图片,并调用自身提取元数据方法"""
<|body_0|>
def get_picture_exif(self, picture_name):
"""提取图片元数据"""
<|body_1|>
def deal_data_format(self, data):
"""处理数据,清洗格式生成对应内容"""
<|body_2|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_75kplus_train_003615 | 2,617 | no_license | [
{
"docstring": "读取图片,并调用自身提取元数据方法",
"name": "read_picture",
"signature": "def read_picture(self)"
},
{
"docstring": "提取图片元数据",
"name": "get_picture_exif",
"signature": "def get_picture_exif(self, picture_name)"
},
{
"docstring": "处理数据,清洗格式生成对应内容",
"name": "deal_data_format",
... | 3 | stack_v2_sparse_classes_30k_train_045319 | Implement the Python class `MetaPicture` described below.
Class description:
Implement the MetaPicture class.
Method signatures and docstrings:
- def read_picture(self): 读取图片,并调用自身提取元数据方法
- def get_picture_exif(self, picture_name): 提取图片元数据
- def deal_data_format(self, data): 处理数据,清洗格式生成对应内容 | Implement the Python class `MetaPicture` described below.
Class description:
Implement the MetaPicture class.
Method signatures and docstrings:
- def read_picture(self): 读取图片,并调用自身提取元数据方法
- def get_picture_exif(self, picture_name): 提取图片元数据
- def deal_data_format(self, data): 处理数据,清洗格式生成对应内容
<|skeleton|>
class MetaPi... | a24869d88cb41e53fb0abe482ba87dd1e54b2167 | <|skeleton|>
class MetaPicture:
def read_picture(self):
"""读取图片,并调用自身提取元数据方法"""
<|body_0|>
def get_picture_exif(self, picture_name):
"""提取图片元数据"""
<|body_1|>
def deal_data_format(self, data):
"""处理数据,清洗格式生成对应内容"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MetaPicture:
def read_picture(self):
"""读取图片,并调用自身提取元数据方法"""
pictures = os.listdir(self.__class__.picture_paths)
for picture in pictures:
picture_path = os.path.join(self.picture_paths, picture)
self.get_picture_exif(picture_path)
def get_picture_exif(self,... | the_stack_v2_python_sparse | findLocation.py | Arithmeticjia/leetcode-python | train | 1 | |
1fa3fea4ca582f2e3ff020c5cc64cf68b245aa05 | [
"def is_mysql_stopped():\n cmd = 'ps -ef | grep [m]ysql'\n return not remote.execute(cmd).is_ok\n\ndef is_mysql_started():\n self.env.run_tests('fuel_health.tests.ha.test_mysql_replication.TestMysqlReplication.test_mysql_replication')\n return self.env.is_last_test_result_ok()\ncontroller = self.env.pri... | <|body_start_0|>
def is_mysql_stopped():
cmd = 'ps -ef | grep [m]ysql'
return not remote.execute(cmd).is_ok
def is_mysql_started():
self.env.run_tests('fuel_health.tests.ha.test_mysql_replication.TestMysqlReplication.test_mysql_replication')
return self.e... | TestFailoverRestarts | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestFailoverRestarts:
def test_restart_galera_services_with_replication(self):
"""Restart all Galera services with data replication Scenario: 1. 'pcs resource disable clone_p_mysqld' to stop Galera service. 2. 'ps -ef | grep mysql' and check that all mysql processes were killed. 3. 'pcs ... | stack_v2_sparse_classes_75kplus_train_003616 | 7,909 | no_license | [
{
"docstring": "Restart all Galera services with data replication Scenario: 1. 'pcs resource disable clone_p_mysqld' to stop Galera service. 2. 'ps -ef | grep mysql' and check that all mysql processes were killed. 3. 'pcs resource enable clone_p_mysqld' to start Galera service. 4. 'ps -ef | grep mysql' and chec... | 3 | null | Implement the Python class `TestFailoverRestarts` described below.
Class description:
Implement the TestFailoverRestarts class.
Method signatures and docstrings:
- def test_restart_galera_services_with_replication(self): Restart all Galera services with data replication Scenario: 1. 'pcs resource disable clone_p_mysq... | Implement the Python class `TestFailoverRestarts` described below.
Class description:
Implement the TestFailoverRestarts class.
Method signatures and docstrings:
- def test_restart_galera_services_with_replication(self): Restart all Galera services with data replication Scenario: 1. 'pcs resource disable clone_p_mysq... | 8aced2855b78b5f123195d188c80e27b43888a2e | <|skeleton|>
class TestFailoverRestarts:
def test_restart_galera_services_with_replication(self):
"""Restart all Galera services with data replication Scenario: 1. 'pcs resource disable clone_p_mysqld' to stop Galera service. 2. 'ps -ef | grep mysql' and check that all mysql processes were killed. 3. 'pcs ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestFailoverRestarts:
def test_restart_galera_services_with_replication(self):
"""Restart all Galera services with data replication Scenario: 1. 'pcs resource disable clone_p_mysqld' to stop Galera service. 2. 'ps -ef | grep mysql' and check that all mysql processes were killed. 3. 'pcs resource enabl... | the_stack_v2_python_sparse | mos_tests/failover/test_failover_restarts.py | Mirantis/mos-integration-tests | train | 16 | |
9ece43640bb3d5218cf9542d446dacfb74d28266 | [
"super(CNN, self).__init__()\nif 'vocab_length' in params.keys():\n vocab_length = params['vocab_length']\n self.embedding = nn.Embedding(vocab_length + 1, embedding_size, padding_idx=0)\nelif 'emb_matrix' in params.keys():\n wordvectors = params['emb_matrix'].vectors\n zeros = np.zeros((1, len(wordvect... | <|body_start_0|>
super(CNN, self).__init__()
if 'vocab_length' in params.keys():
vocab_length = params['vocab_length']
self.embedding = nn.Embedding(vocab_length + 1, embedding_size, padding_idx=0)
elif 'emb_matrix' in params.keys():
wordvectors = params['emb_... | CNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CNN:
def __init__(self, params, embedding_size, output_size, kernels, dropout):
"""CNN network class. See master thesis for architecture details. Args: params (dict{vocab_length/emb_matrix}): Parameters from embedder, which holds necessary information. embedding_size (int): Dimensionalit... | stack_v2_sparse_classes_75kplus_train_003617 | 13,585 | no_license | [
{
"docstring": "CNN network class. See master thesis for architecture details. Args: params (dict{vocab_length/emb_matrix}): Parameters from embedder, which holds necessary information. embedding_size (int): Dimensionality of word embeddings in EmbLayer/Word2vec. output_size (int): Number of filters per filter ... | 2 | stack_v2_sparse_classes_30k_train_018519 | Implement the Python class `CNN` described below.
Class description:
Implement the CNN class.
Method signatures and docstrings:
- def __init__(self, params, embedding_size, output_size, kernels, dropout): CNN network class. See master thesis for architecture details. Args: params (dict{vocab_length/emb_matrix}): Para... | Implement the Python class `CNN` described below.
Class description:
Implement the CNN class.
Method signatures and docstrings:
- def __init__(self, params, embedding_size, output_size, kernels, dropout): CNN network class. See master thesis for architecture details. Args: params (dict{vocab_length/emb_matrix}): Para... | 5b3fa974002eb68244081df6442688f2cc411008 | <|skeleton|>
class CNN:
def __init__(self, params, embedding_size, output_size, kernels, dropout):
"""CNN network class. See master thesis for architecture details. Args: params (dict{vocab_length/emb_matrix}): Parameters from embedder, which holds necessary information. embedding_size (int): Dimensionalit... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CNN:
def __init__(self, params, embedding_size, output_size, kernels, dropout):
"""CNN network class. See master thesis for architecture details. Args: params (dict{vocab_length/emb_matrix}): Parameters from embedder, which holds necessary information. embedding_size (int): Dimensionality of word embe... | the_stack_v2_python_sparse | networks.py | joakiol/RealEstateSummaryQuality | train | 0 | |
670931cf7f4f784c56c13a837e247cdd8e9f8565 | [
"self.certificate = certificate\nself.name = name\nself.date_of_birth = APIHelper.RFC3339DateTime(date_of_birth) if date_of_birth else None\nself.pid = pid\nself.ssn = ssn\nself.signed_timestamp = APIHelper.RFC3339DateTime(signed_timestamp) if signed_timestamp else None\nself.valid = valid\nself.ocsp = ocsp\nself.e... | <|body_start_0|>
self.certificate = certificate
self.name = name
self.date_of_birth = APIHelper.RFC3339DateTime(date_of_birth) if date_of_birth else None
self.pid = pid
self.ssn = ssn
self.signed_timestamp = APIHelper.RFC3339DateTime(signed_timestamp) if signed_timestamp ... | Implementation of the 'SDOSigners' model. TODO: type model description here. Attributes: certificate (Certificate): TODO: type description here. name (string): TODO: type description here. date_of_birth (datetime): TODO: type description here. pid (string): TODO: type description here. ssn (string): TODO: type descript... | SDOSigners | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SDOSigners:
"""Implementation of the 'SDOSigners' model. TODO: type model description here. Attributes: certificate (Certificate): TODO: type description here. name (string): TODO: type description here. date_of_birth (datetime): TODO: type description here. pid (string): TODO: type description h... | stack_v2_sparse_classes_75kplus_train_003618 | 4,143 | permissive | [
{
"docstring": "Constructor for the SDOSigners class",
"name": "__init__",
"signature": "def __init__(self, certificate=None, name=None, date_of_birth=None, pid=None, ssn=None, signed_timestamp=None, valid=None, ocsp=None, environment=None, additional_properties={})"
},
{
"docstring": "Creates a... | 2 | stack_v2_sparse_classes_30k_train_028270 | Implement the Python class `SDOSigners` described below.
Class description:
Implementation of the 'SDOSigners' model. TODO: type model description here. Attributes: certificate (Certificate): TODO: type description here. name (string): TODO: type description here. date_of_birth (datetime): TODO: type description here.... | Implement the Python class `SDOSigners` described below.
Class description:
Implementation of the 'SDOSigners' model. TODO: type model description here. Attributes: certificate (Certificate): TODO: type description here. name (string): TODO: type description here. date_of_birth (datetime): TODO: type description here.... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class SDOSigners:
"""Implementation of the 'SDOSigners' model. TODO: type model description here. Attributes: certificate (Certificate): TODO: type description here. name (string): TODO: type description here. date_of_birth (datetime): TODO: type description here. pid (string): TODO: type description h... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SDOSigners:
"""Implementation of the 'SDOSigners' model. TODO: type model description here. Attributes: certificate (Certificate): TODO: type description here. name (string): TODO: type description here. date_of_birth (datetime): TODO: type description here. pid (string): TODO: type description here. ssn (str... | the_stack_v2_python_sparse | idfy_rest_client/models/sdo_signers.py | dealflowteam/Idfy | train | 0 |
30fc70590cbe446265c98b20da4c707a9b32f658 | [
"self.api_key = api_key\nself.api_secret = api_secret\nself.access_token = access_token\nself.access_token_secret = access_token_secret\nself.listener = listener\nself.auth = None\nself.source_addr = source_addr\nself.stream = None\nself.track_list = []\nself.doAuth()",
"log.debug('doAuth')\nself.auth = tweepy.OA... | <|body_start_0|>
self.api_key = api_key
self.api_secret = api_secret
self.access_token = access_token
self.access_token_secret = access_token_secret
self.listener = listener
self.auth = None
self.source_addr = source_addr
self.stream = None
self.tr... | Streamer class. | Streamer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Streamer:
"""Streamer class."""
def __init__(self, listener, api_key, api_secret, access_token, access_token_secret, source_addr=None):
"""initialize the streamer object."""
<|body_0|>
def doAuth(self):
"""perform authorization."""
<|body_1|>
def sta... | stack_v2_sparse_classes_75kplus_train_003619 | 3,950 | no_license | [
{
"docstring": "initialize the streamer object.",
"name": "__init__",
"signature": "def __init__(self, listener, api_key, api_secret, access_token, access_token_secret, source_addr=None)"
},
{
"docstring": "perform authorization.",
"name": "doAuth",
"signature": "def doAuth(self)"
},
... | 5 | stack_v2_sparse_classes_30k_train_043729 | Implement the Python class `Streamer` described below.
Class description:
Streamer class.
Method signatures and docstrings:
- def __init__(self, listener, api_key, api_secret, access_token, access_token_secret, source_addr=None): initialize the streamer object.
- def doAuth(self): perform authorization.
- def start(s... | Implement the Python class `Streamer` described below.
Class description:
Streamer class.
Method signatures and docstrings:
- def __init__(self, listener, api_key, api_secret, access_token, access_token_secret, source_addr=None): initialize the streamer object.
- def doAuth(self): perform authorization.
- def start(s... | 96b24dae671e4dd1948decdb0d84ff3c5ce6981c | <|skeleton|>
class Streamer:
"""Streamer class."""
def __init__(self, listener, api_key, api_secret, access_token, access_token_secret, source_addr=None):
"""initialize the streamer object."""
<|body_0|>
def doAuth(self):
"""perform authorization."""
<|body_1|>
def sta... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Streamer:
"""Streamer class."""
def __init__(self, listener, api_key, api_secret, access_token, access_token_secret, source_addr=None):
"""initialize the streamer object."""
self.api_key = api_key
self.api_secret = api_secret
self.access_token = access_token
self.a... | the_stack_v2_python_sparse | streamer.py | geosoco/twitter_capture_client | train | 1 |
566905583fa9fa160ede52179600e7e6f23ae63c | [
"name = arg\nif name == None or name.strip() == '':\n return Result(error='输入参数不可为空')\ntry:\n users = User.query.filter(User.name.like('%%%s%%' % name)).all()\n if len(users) == 0:\n return Result(error='没有查询到用户')\n para = []\n for row in users:\n user = {'id': row.id, 'name': row.name,... | <|body_start_0|>
name = arg
if name == None or name.strip() == '':
return Result(error='输入参数不可为空')
try:
users = User.query.filter(User.name.like('%%%s%%' % name)).all()
if len(users) == 0:
return Result(error='没有查询到用户')
para = []
... | Restful_Model | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Restful_Model:
def get(self, arg):
"""根据name模糊查询用户"""
<|body_0|>
def post(self):
"""添加用户"""
<|body_1|>
def delete(self, arg):
"""根据id删除用户"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
name = arg
if name == None or name... | stack_v2_sparse_classes_75kplus_train_003620 | 2,444 | no_license | [
{
"docstring": "根据name模糊查询用户",
"name": "get",
"signature": "def get(self, arg)"
},
{
"docstring": "添加用户",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "根据id删除用户",
"name": "delete",
"signature": "def delete(self, arg)"
}
] | 3 | null | Implement the Python class `Restful_Model` described below.
Class description:
Implement the Restful_Model class.
Method signatures and docstrings:
- def get(self, arg): 根据name模糊查询用户
- def post(self): 添加用户
- def delete(self, arg): 根据id删除用户 | Implement the Python class `Restful_Model` described below.
Class description:
Implement the Restful_Model class.
Method signatures and docstrings:
- def get(self, arg): 根据name模糊查询用户
- def post(self): 添加用户
- def delete(self, arg): 根据id删除用户
<|skeleton|>
class Restful_Model:
def get(self, arg):
"""根据name模... | 43109bb6092f70f5ed8a6c5957dc95341d65515f | <|skeleton|>
class Restful_Model:
def get(self, arg):
"""根据name模糊查询用户"""
<|body_0|>
def post(self):
"""添加用户"""
<|body_1|>
def delete(self, arg):
"""根据id删除用户"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Restful_Model:
def get(self, arg):
"""根据name模糊查询用户"""
name = arg
if name == None or name.strip() == '':
return Result(error='输入参数不可为空')
try:
users = User.query.filter(User.name.like('%%%s%%' % name)).all()
if len(users) == 0:
... | the_stack_v2_python_sparse | sql_restful/orm_restful.py | hugoMQ/mypython | train | 0 | |
2145d50acf6e7994297b58a08e4b4d160f465644 | [
"cluster_infos = []\nclusters = datastore_entities.ClusterInfo.query().fetch()\nfor cluster in clusters:\n host_msgs = []\n if request.include_hosts:\n host_msgs = self._GetHostsForCluster(cluster.cluster)\n cluster_infos.append(self._BuildClusterInfo(cluster, host_msgs))\nreturn ClusterInfoCollecti... | <|body_start_0|>
cluster_infos = []
clusters = datastore_entities.ClusterInfo.query().fetch()
for cluster in clusters:
host_msgs = []
if request.include_hosts:
host_msgs = self._GetHostsForCluster(cluster.cluster)
cluster_infos.append(self._Bui... | A class for cluster API service. | ClusterApi | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusterApi:
"""A class for cluster API service."""
def ListClusters(self, request):
"""Fetches a list of clusters that are available. Args: request: an API request. Returns: a ClusterInfoCollection object."""
<|body_0|>
def GetCluster(self, request):
"""Fetches t... | stack_v2_sparse_classes_75kplus_train_003621 | 7,145 | permissive | [
{
"docstring": "Fetches a list of clusters that are available. Args: request: an API request. Returns: a ClusterInfoCollection object.",
"name": "ListClusters",
"signature": "def ListClusters(self, request)"
},
{
"docstring": "Fetches the information/status for a given cluster id. Args: request:... | 5 | stack_v2_sparse_classes_30k_train_013187 | Implement the Python class `ClusterApi` described below.
Class description:
A class for cluster API service.
Method signatures and docstrings:
- def ListClusters(self, request): Fetches a list of clusters that are available. Args: request: an API request. Returns: a ClusterInfoCollection object.
- def GetCluster(self... | Implement the Python class `ClusterApi` described below.
Class description:
A class for cluster API service.
Method signatures and docstrings:
- def ListClusters(self, request): Fetches a list of clusters that are available. Args: request: an API request. Returns: a ClusterInfoCollection object.
- def GetCluster(self... | 0568fc1d9b9dca79aed2de493955ce1adebb1d6b | <|skeleton|>
class ClusterApi:
"""A class for cluster API service."""
def ListClusters(self, request):
"""Fetches a list of clusters that are available. Args: request: an API request. Returns: a ClusterInfoCollection object."""
<|body_0|>
def GetCluster(self, request):
"""Fetches t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ClusterApi:
"""A class for cluster API service."""
def ListClusters(self, request):
"""Fetches a list of clusters that are available. Args: request: an API request. Returns: a ClusterInfoCollection object."""
cluster_infos = []
clusters = datastore_entities.ClusterInfo.query().fet... | the_stack_v2_python_sparse | tradefed_cluster/cluster_api.py | maksonlee/tradefed_cluster | train | 0 |
d41b6fbe6e4d03ebbe4cd8e0dfa75c4a0cd47219 | [
"manifest_file = files.Get(manifest_path, disabled_services=[SERVICE_NAME])\nnew_data = {}\nif manifest_file:\n new_data.update(json.loads(manifest_file.content))\nnew_data[variant_path] = data\nnew_data = json.dumps(new_data)\nfiles.Write(manifest_path, new_data, disabled_services=[SERVICE_NAME])",
"if not va... | <|body_start_0|>
manifest_file = files.Get(manifest_path, disabled_services=[SERVICE_NAME])
new_data = {}
if manifest_file:
new_data.update(json.loads(manifest_file.content))
new_data[variant_path] = data
new_data = json.dumps(new_data)
files.Write(manifest_pa... | Hook for files.Write(). | HookForWrite | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HookForWrite:
"""Hook for files.Write()."""
def __UpdateOrCreateManifest(variant_path, manifest_path, data):
"""Update or create the manifest file. Args: variant_path: The path to the variant, ex: /de/foo.html manifest_path: The path to the manfiest, ex: /foo.html.manifest data: The ... | stack_v2_sparse_classes_75kplus_train_003622 | 3,794 | no_license | [
{
"docstring": "Update or create the manifest file. Args: variant_path: The path to the variant, ex: /de/foo.html manifest_path: The path to the manfiest, ex: /foo.html.manifest data: The dictionary of variant-specific data.",
"name": "__UpdateOrCreateManifest",
"signature": "def __UpdateOrCreateManifes... | 2 | stack_v2_sparse_classes_30k_train_004500 | Implement the Python class `HookForWrite` described below.
Class description:
Hook for files.Write().
Method signatures and docstrings:
- def __UpdateOrCreateManifest(variant_path, manifest_path, data): Update or create the manifest file. Args: variant_path: The path to the variant, ex: /de/foo.html manifest_path: Th... | Implement the Python class `HookForWrite` described below.
Class description:
Hook for files.Write().
Method signatures and docstrings:
- def __UpdateOrCreateManifest(variant_path, manifest_path, data): Update or create the manifest file. Args: variant_path: The path to the variant, ex: /de/foo.html manifest_path: Th... | 9ee133499a692584ebbaf299aff8c1873d1aee22 | <|skeleton|>
class HookForWrite:
"""Hook for files.Write()."""
def __UpdateOrCreateManifest(variant_path, manifest_path, data):
"""Update or create the manifest file. Args: variant_path: The path to the variant, ex: /de/foo.html manifest_path: The path to the manfiest, ex: /foo.html.manifest data: The ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HookForWrite:
"""Hook for files.Write()."""
def __UpdateOrCreateManifest(variant_path, manifest_path, data):
"""Update or create the manifest file. Args: variant_path: The path to the variant, ex: /de/foo.html manifest_path: The path to the manfiest, ex: /foo.html.manifest data: The dictionary of... | the_stack_v2_python_sparse | titan/services/manifest.py | poindexterc/plumGit | train | 0 |
220d9922ce7854b19ab7d07d532f37bb7d621402 | [
"if n == 0:\n return ['']\noutput = []\nfor c in range(n):\n for left in self.generates(c):\n for right in self.generates(n - 1 - c):\n output.append('({}){}'.format(left, right))\nreturn output",
"def back_track(s='', left=0, right=0):\n if len(s) == n * 2:\n output.append(s)\n ... | <|body_start_0|>
if n == 0:
return ['']
output = []
for c in range(n):
for left in self.generates(c):
for right in self.generates(n - 1 - c):
output.append('({}){}'.format(left, right))
return output
<|end_body_0|>
<|body_start... | Parentheses | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Parentheses:
def generates(self, n: int) -> List[str]:
"""Approach: Closure Time Complexity: O(4^n/root(n)) Space Complexity: O(4^n/root(n)) :param n: :return:"""
<|body_0|>
def generate(self, n: int) -> List[str]:
"""Approach: Back tracking Time Complexity: O(4^n/ro... | stack_v2_sparse_classes_75kplus_train_003623 | 1,294 | no_license | [
{
"docstring": "Approach: Closure Time Complexity: O(4^n/root(n)) Space Complexity: O(4^n/root(n)) :param n: :return:",
"name": "generates",
"signature": "def generates(self, n: int) -> List[str]"
},
{
"docstring": "Approach: Back tracking Time Complexity: O(4^n/root(n)) Space Complexity: O(4^n/... | 2 | stack_v2_sparse_classes_30k_train_014766 | Implement the Python class `Parentheses` described below.
Class description:
Implement the Parentheses class.
Method signatures and docstrings:
- def generates(self, n: int) -> List[str]: Approach: Closure Time Complexity: O(4^n/root(n)) Space Complexity: O(4^n/root(n)) :param n: :return:
- def generate(self, n: int)... | Implement the Python class `Parentheses` described below.
Class description:
Implement the Parentheses class.
Method signatures and docstrings:
- def generates(self, n: int) -> List[str]: Approach: Closure Time Complexity: O(4^n/root(n)) Space Complexity: O(4^n/root(n)) :param n: :return:
- def generate(self, n: int)... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Parentheses:
def generates(self, n: int) -> List[str]:
"""Approach: Closure Time Complexity: O(4^n/root(n)) Space Complexity: O(4^n/root(n)) :param n: :return:"""
<|body_0|>
def generate(self, n: int) -> List[str]:
"""Approach: Back tracking Time Complexity: O(4^n/ro... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Parentheses:
def generates(self, n: int) -> List[str]:
"""Approach: Closure Time Complexity: O(4^n/root(n)) Space Complexity: O(4^n/root(n)) :param n: :return:"""
if n == 0:
return ['']
output = []
for c in range(n):
for left in self.generates(c):
... | the_stack_v2_python_sparse | revisited/back_tracking/generate_parentheses.py | Shiv2157k/leet_code | train | 1 | |
0e103175b0aa04e41769df1903e096d4ac2d6596 | [
"print()\nprint('-+- ' * 40)\nlog.debug('ROUTE class : %s', self.__class__.__name__)\nlog.debug('payload : \\n{}'.format(pformat(ns.payload)))\nclaims = get_jwt_claims()\nlog.debug('claims : \\n %s', pformat(claims))\nupdated_doc, response_code = Query_db_update(ns, models, document_type, doc_id, claims, roles_for_... | <|body_start_0|>
print()
print('-+- ' * 40)
log.debug('ROUTE class : %s', self.__class__.__name__)
log.debug('payload : \n{}'.format(pformat(ns.payload)))
claims = get_jwt_claims()
log.debug('claims : \n %s', pformat(claims))
updated_doc, response_code = Query_db_... | rec edition : PUT - Updates document's infos DELETE - Let you delete document | Rec_edit | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rec_edit:
"""rec edition : PUT - Updates document's infos DELETE - Let you delete document"""
def put(self, doc_id):
"""Update a dmf in db > --- needs : a valid access_token in the header, field_to_update, field_value >>> returns : msg, doc data"""
<|body_0|>
def delete(... | stack_v2_sparse_classes_75kplus_train_003624 | 3,280 | permissive | [
{
"docstring": "Update a dmf in db > --- needs : a valid access_token in the header, field_to_update, field_value >>> returns : msg, doc data",
"name": "put",
"signature": "def put(self, doc_id)"
},
{
"docstring": "delete a rec in db > --- needs : a valid access_token (as admin or current user) ... | 2 | stack_v2_sparse_classes_30k_val_001042 | Implement the Python class `Rec_edit` described below.
Class description:
rec edition : PUT - Updates document's infos DELETE - Let you delete document
Method signatures and docstrings:
- def put(self, doc_id): Update a dmf in db > --- needs : a valid access_token in the header, field_to_update, field_value >>> retur... | Implement the Python class `Rec_edit` described below.
Class description:
rec edition : PUT - Updates document's infos DELETE - Let you delete document
Method signatures and docstrings:
- def put(self, doc_id): Update a dmf in db > --- needs : a valid access_token in the header, field_to_update, field_value >>> retur... | 08ba9151069f2f633461f5166b1954fdeac7854a | <|skeleton|>
class Rec_edit:
"""rec edition : PUT - Updates document's infos DELETE - Let you delete document"""
def put(self, doc_id):
"""Update a dmf in db > --- needs : a valid access_token in the header, field_to_update, field_value >>> returns : msg, doc data"""
<|body_0|>
def delete(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Rec_edit:
"""rec edition : PUT - Updates document's infos DELETE - Let you delete document"""
def put(self, doc_id):
"""Update a dmf in db > --- needs : a valid access_token in the header, field_to_update, field_value >>> returns : msg, doc data"""
print()
print('-+- ' * 40)
... | the_stack_v2_python_sparse | solidata_api/api/api_recipes/endpoint_rec_edit.py | entrepreneur-interet-general/solidata_backend | train | 9 |
75da30ac44e3af5b3c94b184ef2a07e1600a96f4 | [
"dct = {}\nfor i in A:\n if i not in dct.keys():\n dct[i] = 1\n else:\n dct[i] += 1\nfor k, v in dct.items():\n if v == 1:\n return k",
"for i in A:\n if A.count(i) == 1:\n return i",
"lst1 = []\nlst2 = []\nfor i in A:\n if i not in lst1:\n if i not in lst2:\n ... | <|body_start_0|>
dct = {}
for i in A:
if i not in dct.keys():
dct[i] = 1
else:
dct[i] += 1
for k, v in dct.items():
if v == 1:
return k
<|end_body_0|>
<|body_start_1|>
for i in A:
if A.count(... | @param: A: An integer array @return: An integer | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""@param: A: An integer array @return: An integer"""
def singleNumberII_1(self, A):
"""字典,lintcode居然超时了, 这台垃圾电脑秒出结果"""
<|body_0|>
def singleNumberII_2(self, A):
"""逗比答案, 还是超时"""
<|body_1|>
def singleNumberII_3(self, A):
"""不用怀疑还是超时... | stack_v2_sparse_classes_75kplus_train_003625 | 2,222 | no_license | [
{
"docstring": "字典,lintcode居然超时了, 这台垃圾电脑秒出结果",
"name": "singleNumberII_1",
"signature": "def singleNumberII_1(self, A)"
},
{
"docstring": "逗比答案, 还是超时",
"name": "singleNumberII_2",
"signature": "def singleNumberII_2(self, A)"
},
{
"docstring": "不用怀疑还是超时...",
"name": "singleNum... | 4 | stack_v2_sparse_classes_30k_train_021968 | Implement the Python class `Solution` described below.
Class description:
@param: A: An integer array @return: An integer
Method signatures and docstrings:
- def singleNumberII_1(self, A): 字典,lintcode居然超时了, 这台垃圾电脑秒出结果
- def singleNumberII_2(self, A): 逗比答案, 还是超时
- def singleNumberII_3(self, A): 不用怀疑还是超时...
- def singl... | Implement the Python class `Solution` described below.
Class description:
@param: A: An integer array @return: An integer
Method signatures and docstrings:
- def singleNumberII_1(self, A): 字典,lintcode居然超时了, 这台垃圾电脑秒出结果
- def singleNumberII_2(self, A): 逗比答案, 还是超时
- def singleNumberII_3(self, A): 不用怀疑还是超时...
- def singl... | 87592a39d67d8e734e693327d6b063be334b37e2 | <|skeleton|>
class Solution:
"""@param: A: An integer array @return: An integer"""
def singleNumberII_1(self, A):
"""字典,lintcode居然超时了, 这台垃圾电脑秒出结果"""
<|body_0|>
def singleNumberII_2(self, A):
"""逗比答案, 还是超时"""
<|body_1|>
def singleNumberII_3(self, A):
"""不用怀疑还是超时... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""@param: A: An integer array @return: An integer"""
def singleNumberII_1(self, A):
"""字典,lintcode居然超时了, 这台垃圾电脑秒出结果"""
dct = {}
for i in A:
if i not in dct.keys():
dct[i] = 1
else:
dct[i] += 1
for k, v in d... | the_stack_v2_python_sparse | LintCode/LintCode-83:落单的数 II.py | hoshizorahikari/PythonExercise | train | 0 |
20e7991f4068a4b7c31b61b3a22a35b4a3a510be | [
"super().__init__()\nif residuals is not None:\n residuals = residuals.lower()\nself.residuals = residuals\nself.body = nn.Sequential(nn.Linear(features_in, features_out, bias=False), norm_factory(features_out), activation_factory())",
"if self.residuals is None:\n return self.body(x)\nif self.residuals == ... | <|body_start_0|>
super().__init__()
if residuals is not None:
residuals = residuals.lower()
self.residuals = residuals
self.body = nn.Sequential(nn.Linear(features_in, features_out, bias=False), norm_factory(features_out), activation_factory())
<|end_body_0|>
<|body_start_1|... | A building block for a fully-connected (MLP) network. This block expects the features to be located along the last dimension of the tensor. | MLPBlock | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MLPBlock:
"""A building block for a fully-connected (MLP) network. This block expects the features to be located along the last dimension of the tensor."""
def __init__(self, features_in, features_out, activation_factory, norm_factory, residuals=None):
"""Args: features_in: The numbe... | stack_v2_sparse_classes_75kplus_train_003626 | 9,125 | permissive | [
{
"docstring": "Args: features_in: The number of features of the block input. features_out: The number of features of the block output. activation_factory: A factory functional to create the activation layers in the block. norm_factory: A factory functional to create the normalization layers used in the block. ... | 2 | stack_v2_sparse_classes_30k_train_045855 | Implement the Python class `MLPBlock` described below.
Class description:
A building block for a fully-connected (MLP) network. This block expects the features to be located along the last dimension of the tensor.
Method signatures and docstrings:
- def __init__(self, features_in, features_out, activation_factory, no... | Implement the Python class `MLPBlock` described below.
Class description:
A building block for a fully-connected (MLP) network. This block expects the features to be located along the last dimension of the tensor.
Method signatures and docstrings:
- def __init__(self, features_in, features_out, activation_factory, no... | a27e329cd30337995c359160a0d878bf331c13fb | <|skeleton|>
class MLPBlock:
"""A building block for a fully-connected (MLP) network. This block expects the features to be located along the last dimension of the tensor."""
def __init__(self, features_in, features_out, activation_factory, norm_factory, residuals=None):
"""Args: features_in: The numbe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MLPBlock:
"""A building block for a fully-connected (MLP) network. This block expects the features to be located along the last dimension of the tensor."""
def __init__(self, features_in, features_out, activation_factory, norm_factory, residuals=None):
"""Args: features_in: The number of features... | the_stack_v2_python_sparse | quantnn/models/pytorch/fully_connected.py | simonpf/quantnn | train | 7 |
9d48427d0423ad9a0b9e6a137892555944a8fc2a | [
"self.app_name = app_name\nself.template_name = template_name\nself.ext = ext\nself.mode = mode\ninstalled_apps = dict(get_apps())\nself.app = installed_apps.get(app_name)\nif self.app is None:\n raise Exception('App {} is not available'.format(app_name))",
"if self.ext == 'py':\n to_path = os.path.join(sel... | <|body_start_0|>
self.app_name = app_name
self.template_name = template_name
self.ext = ext
self.mode = mode
installed_apps = dict(get_apps())
self.app = installed_apps.get(app_name)
if self.app is None:
raise Exception('App {} is not available'.format... | Template Render | Template | [
"Apache-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Template:
"""Template Render"""
def __init__(self, app_name, template_name, ext='py', mode=None):
"""Construye la app :param app_name:"""
<|body_0|>
def render(self):
"""Renderiza el template dado en el archivo solicitado :return:"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus_train_003627 | 6,459 | permissive | [
{
"docstring": "Construye la app :param app_name:",
"name": "__init__",
"signature": "def __init__(self, app_name, template_name, ext='py', mode=None)"
},
{
"docstring": "Renderiza el template dado en el archivo solicitado :return:",
"name": "render",
"signature": "def render(self)"
}
... | 2 | stack_v2_sparse_classes_30k_test_001124 | Implement the Python class `Template` described below.
Class description:
Template Render
Method signatures and docstrings:
- def __init__(self, app_name, template_name, ext='py', mode=None): Construye la app :param app_name:
- def render(self): Renderiza el template dado en el archivo solicitado :return: | Implement the Python class `Template` described below.
Class description:
Template Render
Method signatures and docstrings:
- def __init__(self, app_name, template_name, ext='py', mode=None): Construye la app :param app_name:
- def render(self): Renderiza el template dado en el archivo solicitado :return:
<|skeleton... | 201237266a64e49b5c37f3d373ff6913dfbd099e | <|skeleton|>
class Template:
"""Template Render"""
def __init__(self, app_name, template_name, ext='py', mode=None):
"""Construye la app :param app_name:"""
<|body_0|>
def render(self):
"""Renderiza el template dado en el archivo solicitado :return:"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Template:
"""Template Render"""
def __init__(self, app_name, template_name, ext='py', mode=None):
"""Construye la app :param app_name:"""
self.app_name = app_name
self.template_name = template_name
self.ext = ext
self.mode = mode
installed_apps = dict(get_a... | the_stack_v2_python_sparse | brainutils/gen_engine.py | jimbuho/django-brain | train | 0 |
c104a6e8f5e388b9ed5fb5bab3e2908f18ba1804 | [
"data = {'name': 'Green Bell Peppers'}\nform = IngredientForm(data=data)\nself.assertTrue(form.is_valid())",
"data = {'name': ''}\nform = IngredientForm(data=data)\nself.assertFalse(form.is_valid())",
"data = {'name': 'green bell peppers'}\nform = IngredientForm(data=data)\nform.full_clean()\nself.assertEqual('... | <|body_start_0|>
data = {'name': 'Green Bell Peppers'}
form = IngredientForm(data=data)
self.assertTrue(form.is_valid())
<|end_body_0|>
<|body_start_1|>
data = {'name': ''}
form = IngredientForm(data=data)
self.assertFalse(form.is_valid())
<|end_body_1|>
<|body_start_2|... | Ensures that all of the forms work properly | WorkShopFormTests | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkShopFormTests:
"""Ensures that all of the forms work properly"""
def test_ingredientform_valid(self):
"""Ensures that IngredientForm is valid"""
<|body_0|>
def test_ingredientform_empty(self):
"""Ensures that an empty form cannot be valid"""
<|body_1|... | stack_v2_sparse_classes_75kplus_train_003628 | 11,372 | permissive | [
{
"docstring": "Ensures that IngredientForm is valid",
"name": "test_ingredientform_valid",
"signature": "def test_ingredientform_valid(self)"
},
{
"docstring": "Ensures that an empty form cannot be valid",
"name": "test_ingredientform_empty",
"signature": "def test_ingredientform_empty(... | 5 | stack_v2_sparse_classes_30k_train_043679 | Implement the Python class `WorkShopFormTests` described below.
Class description:
Ensures that all of the forms work properly
Method signatures and docstrings:
- def test_ingredientform_valid(self): Ensures that IngredientForm is valid
- def test_ingredientform_empty(self): Ensures that an empty form cannot be valid... | Implement the Python class `WorkShopFormTests` described below.
Class description:
Ensures that all of the forms work properly
Method signatures and docstrings:
- def test_ingredientform_valid(self): Ensures that IngredientForm is valid
- def test_ingredientform_empty(self): Ensures that an empty form cannot be valid... | 5948b10e9e99e7f2e8ffdbe6c0efbb87000808a9 | <|skeleton|>
class WorkShopFormTests:
"""Ensures that all of the forms work properly"""
def test_ingredientform_valid(self):
"""Ensures that IngredientForm is valid"""
<|body_0|>
def test_ingredientform_empty(self):
"""Ensures that an empty form cannot be valid"""
<|body_1|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WorkShopFormTests:
"""Ensures that all of the forms work properly"""
def test_ingredientform_valid(self):
"""Ensures that IngredientForm is valid"""
data = {'name': 'Green Bell Peppers'}
form = IngredientForm(data=data)
self.assertTrue(form.is_valid())
def test_ingred... | the_stack_v2_python_sparse | pizzeria/workshop/tests.py | Zachary-Jackson/Django-Pizzeria | train | 1 |
0a763de92b0b0258170c07b8b039d823b632ce69 | [
"self.logger.debug('Start unzipping the file: %s.' % zip_file)\ndir_name = os.path.basename(zip_file).rsplit('.', 1)[0]\nif not unzip_path:\n if add_dir:\n unzip_path = zip_file.rsplit('.', 1)[0]\n else:\n unzip_path = os.path.dirname(zip_file)\nwith zipfile.ZipFile(zip_file, 'r') as f:\n for... | <|body_start_0|>
self.logger.debug('Start unzipping the file: %s.' % zip_file)
dir_name = os.path.basename(zip_file).rsplit('.', 1)[0]
if not unzip_path:
if add_dir:
unzip_path = zip_file.rsplit('.', 1)[0]
else:
unzip_path = os.path.dirname... | cleanup class. Args: Example: Return: Author: cai, yong IsInterface: False ChangeInfo: cai, yong 2019-09-17 | MyZip | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyZip:
"""cleanup class. Args: Example: Return: Author: cai, yong IsInterface: False ChangeInfo: cai, yong 2019-09-17"""
def unzip_file(self, zip_file, unzip_path='', add_dir=False):
"""unzip the file. Args: zip_file type(str) the abspath of the file to be unzipped. unzip_path type(s... | stack_v2_sparse_classes_75kplus_train_003629 | 2,756 | no_license | [
{
"docstring": "unzip the file. Args: zip_file type(str) the abspath of the file to be unzipped. unzip_path type(str) unzipped path add_dir type(bool) whether to add a layer of directory when unzip the file Example: Return: Author: cai, yong IsInterface: False ChangeInfo: cai, yong 2019-09-23",
"name": "unz... | 2 | stack_v2_sparse_classes_30k_test_002317 | Implement the Python class `MyZip` described below.
Class description:
cleanup class. Args: Example: Return: Author: cai, yong IsInterface: False ChangeInfo: cai, yong 2019-09-17
Method signatures and docstrings:
- def unzip_file(self, zip_file, unzip_path='', add_dir=False): unzip the file. Args: zip_file type(str) ... | Implement the Python class `MyZip` described below.
Class description:
cleanup class. Args: Example: Return: Author: cai, yong IsInterface: False ChangeInfo: cai, yong 2019-09-17
Method signatures and docstrings:
- def unzip_file(self, zip_file, unzip_path='', add_dir=False): unzip the file. Args: zip_file type(str) ... | 2d3490393737b3e5f086cb6623369b988ffce67f | <|skeleton|>
class MyZip:
"""cleanup class. Args: Example: Return: Author: cai, yong IsInterface: False ChangeInfo: cai, yong 2019-09-17"""
def unzip_file(self, zip_file, unzip_path='', add_dir=False):
"""unzip the file. Args: zip_file type(str) the abspath of the file to be unzipped. unzip_path type(s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyZip:
"""cleanup class. Args: Example: Return: Author: cai, yong IsInterface: False ChangeInfo: cai, yong 2019-09-17"""
def unzip_file(self, zip_file, unzip_path='', add_dir=False):
"""unzip the file. Args: zip_file type(str) the abspath of the file to be unzipped. unzip_path type(str) unzipped ... | the_stack_v2_python_sparse | lib/tools/public/my_zip.py | Lewescaiyong/auto_test_framework | train | 1 |
e98ece502c8d3a7c028760254aa435727ca16cd3 | [
"boxes_scores.sort(key=lambda x: self._size_box(x[0], dataclass), reverse=True)\nidx_to_del = []\nfor idx1, (box1, score1) in enumerate(boxes_scores):\n contains = []\n for idx2, (box2, score2) in enumerate(boxes_scores):\n if box1 == box2:\n continue\n if box_in_box_dataclass(box2, b... | <|body_start_0|>
boxes_scores.sort(key=lambda x: self._size_box(x[0], dataclass), reverse=True)
idx_to_del = []
for idx1, (box1, score1) in enumerate(boxes_scores):
contains = []
for idx2, (box2, score2) in enumerate(boxes_scores):
if box1 == box2:
... | ResolveNested | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResolveNested:
def resolve_nested(self, boxes_scores, dataclass):
"""Sort boxes_scores from biggest to smallest box. If a given box contain other boxes and among them there is at least one that has higher confidence than the given box delete the given box, otherwise delete all nested box... | stack_v2_sparse_classes_75kplus_train_003630 | 20,599 | no_license | [
{
"docstring": "Sort boxes_scores from biggest to smallest box. If a given box contain other boxes and among them there is at least one that has higher confidence than the given box delete the given box, otherwise delete all nested boxes Args: boxes_scores: a list of (box, score) dataclass: row/column/cell Retu... | 2 | stack_v2_sparse_classes_30k_test_001947 | Implement the Python class `ResolveNested` described below.
Class description:
Implement the ResolveNested class.
Method signatures and docstrings:
- def resolve_nested(self, boxes_scores, dataclass): Sort boxes_scores from biggest to smallest box. If a given box contain other boxes and among them there is at least o... | Implement the Python class `ResolveNested` described below.
Class description:
Implement the ResolveNested class.
Method signatures and docstrings:
- def resolve_nested(self, boxes_scores, dataclass): Sort boxes_scores from biggest to smallest box. If a given box contain other boxes and among them there is at least o... | 4c9970151294006fdafaba3c2ca84b7c04da97e7 | <|skeleton|>
class ResolveNested:
def resolve_nested(self, boxes_scores, dataclass):
"""Sort boxes_scores from biggest to smallest box. If a given box contain other boxes and among them there is at least one that has higher confidence than the given box delete the given box, otherwise delete all nested box... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResolveNested:
def resolve_nested(self, boxes_scores, dataclass):
"""Sort boxes_scores from biggest to smallest box. If a given box contain other boxes and among them there is at least one that has higher confidence than the given box delete the given box, otherwise delete all nested boxes Args: boxes... | the_stack_v2_python_sparse | detectron2_tables/postproc_maskrcnn.py | akmaral-yes/table_structure_recognition_using_detectron2 | train | 4 | |
c4283acfd717a08df6924e388d70454ad65d1d31 | [
"pre = ''\nmin_length = 0\nif len(strs) != 0:\n min_length = min((len(ele) for ele in strs))\nfor x in range(min_length):\n for y in range(len(strs) - 1):\n if strs[y][0:x + 1] != strs[y + 1][0:x + 1]:\n return pre\n pre = strs[0][0:x + 1]\nreturn pre",
"res = ''\nif len(strs) == 0:\n ... | <|body_start_0|>
pre = ''
min_length = 0
if len(strs) != 0:
min_length = min((len(ele) for ele in strs))
for x in range(min_length):
for y in range(len(strs) - 1):
if strs[y][0:x + 1] != strs[y + 1][0:x + 1]:
return pre
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestCommonPrefix(self, strs):
""":type strs: List[str] :rtype: str"""
<|body_0|>
def longestCommonPrefix(self, strs):
""":type strs: List[str] :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pre = ''
min_length =... | stack_v2_sparse_classes_75kplus_train_003631 | 977 | no_license | [
{
"docstring": ":type strs: List[str] :rtype: str",
"name": "longestCommonPrefix",
"signature": "def longestCommonPrefix(self, strs)"
},
{
"docstring": ":type strs: List[str] :rtype: str",
"name": "longestCommonPrefix",
"signature": "def longestCommonPrefix(self, strs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001856 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonPrefix(self, strs): :type strs: List[str] :rtype: str
- def longestCommonPrefix(self, strs): :type strs: List[str] :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonPrefix(self, strs): :type strs: List[str] :rtype: str
- def longestCommonPrefix(self, strs): :type strs: List[str] :rtype: str
<|skeleton|>
class Solution:
... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def longestCommonPrefix(self, strs):
""":type strs: List[str] :rtype: str"""
<|body_0|>
def longestCommonPrefix(self, strs):
""":type strs: List[str] :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def longestCommonPrefix(self, strs):
""":type strs: List[str] :rtype: str"""
pre = ''
min_length = 0
if len(strs) != 0:
min_length = min((len(ele) for ele in strs))
for x in range(min_length):
for y in range(len(strs) - 1):
... | the_stack_v2_python_sparse | 0014_Longest_Common_Prefix.py | bingli8802/leetcode | train | 0 | |
5719de02c8b56e9c1a4c5b8efa338146b0461852 | [
"super(Downsample, self).__init__()\nself.apply_batchnorm = apply_batchnorm\ninitializer = tf.random_normal_initializer(0, 0.02)\nself.conv1 = tf.keras.layers.Conv2D(filters=filters, kernel_size=(size, size), strides=(2, 2), padding='same', kernel_initializer=initializer, use_bias=False)\nif self.apply_batchnorm:\n... | <|body_start_0|>
super(Downsample, self).__init__()
self.apply_batchnorm = apply_batchnorm
initializer = tf.random_normal_initializer(0, 0.02)
self.conv1 = tf.keras.layers.Conv2D(filters=filters, kernel_size=(size, size), strides=(2, 2), padding='same', kernel_initializer=initializer, us... | Use convolution layer to downsample | Downsample | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Downsample:
"""Use convolution layer to downsample"""
def __init__(self, filters, size, apply_batchnorm=True):
"""The construct function. Args: filters: The convolution filters number. size: The convolution filter size. apply_batchnorm If use batch normalization:"""
<|body_0|... | stack_v2_sparse_classes_75kplus_train_003632 | 20,044 | no_license | [
{
"docstring": "The construct function. Args: filters: The convolution filters number. size: The convolution filter size. apply_batchnorm If use batch normalization:",
"name": "__init__",
"signature": "def __init__(self, filters, size, apply_batchnorm=True)"
},
{
"docstring": "Calls the model on... | 2 | stack_v2_sparse_classes_30k_train_030604 | Implement the Python class `Downsample` described below.
Class description:
Use convolution layer to downsample
Method signatures and docstrings:
- def __init__(self, filters, size, apply_batchnorm=True): The construct function. Args: filters: The convolution filters number. size: The convolution filter size. apply_b... | Implement the Python class `Downsample` described below.
Class description:
Use convolution layer to downsample
Method signatures and docstrings:
- def __init__(self, filters, size, apply_batchnorm=True): The construct function. Args: filters: The convolution filters number. size: The convolution filter size. apply_b... | d1b70b2a954f4665b628ba252b03c1a74b95559f | <|skeleton|>
class Downsample:
"""Use convolution layer to downsample"""
def __init__(self, filters, size, apply_batchnorm=True):
"""The construct function. Args: filters: The convolution filters number. size: The convolution filter size. apply_batchnorm If use batch normalization:"""
<|body_0|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Downsample:
"""Use convolution layer to downsample"""
def __init__(self, filters, size, apply_batchnorm=True):
"""The construct function. Args: filters: The convolution filters number. size: The convolution filter size. apply_batchnorm If use batch normalization:"""
super(Downsample, self... | the_stack_v2_python_sparse | NeuralNetworks-tensorflow/generation_network_model/GAN/pix2pix.py | zhaocc1106/machine_learn | train | 15 |
c0095cab6af56ed40673b22f7eb7b9a91964ebb8 | [
"if len(nums) == 0:\n return False\nif len(nums) <= k:\n return len(nums) != len(set(nums))\nreturn any([len(nums[i:i + k + 1]) != len(set(nums[i:i + k + 1])) for i in range(len(nums) - k)])",
"if len(nums) <= 1 or k == 0:\n return False\nif len(nums) <= k:\n x = sorted(nums)\n return any(map(lambd... | <|body_start_0|>
if len(nums) == 0:
return False
if len(nums) <= k:
return len(nums) != len(set(nums))
return any([len(nums[i:i + k + 1]) != len(set(nums[i:i + k + 1])) for i in range(len(nums) - k)])
<|end_body_0|>
<|body_start_1|>
if len(nums) <= 1 or k == 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_0|>
def containsNearbyAlmostDuplicate(self, nums, k, t):
""":type nums: List[int] :type k: int :type t: int :rtype: bool"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus_train_003633 | 1,013 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: bool",
"name": "containsNearbyDuplicate",
"signature": "def containsNearbyDuplicate(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :type t: int :rtype: bool",
"name": "containsNearbyAlmostDuplicate",
"signa... | 2 | stack_v2_sparse_classes_30k_train_011224 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rtype: bool
- def containsNearbyAlmostDuplicate(self, nums, k, t): :type nums: List[int] :type k: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rtype: bool
- def containsNearbyAlmostDuplicate(self, nums, k, t): :type nums: List[int] :type k: ... | 113d052de41d85f366c9497fb132df91e619f13a | <|skeleton|>
class Solution:
def containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_0|>
def containsNearbyAlmostDuplicate(self, nums, k, t):
""":type nums: List[int] :type k: int :type t: int :rtype: bool"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
if len(nums) == 0:
return False
if len(nums) <= k:
return len(nums) != len(set(nums))
return any([len(nums[i:i + k + 1]) != len(set(nums[i:i + k +... | the_stack_v2_python_sparse | contains-duplicate.py | ding4it/leetcode | train | 1 | |
cb13c00cfb6032383b7dac6070d6bdb64fe02563 | [
"import netCDF4\nfrom netcdftime import utime\nself.nc = netCDF4.Dataset(filename)\nself.ncv = self.nc.variables\nself.lon = self.ncv['SCHISM_hgrid_node_x'][:]\nself.lat = self.ncv['SCHISM_hgrid_node_y'][:]\nself.nodeids = np.arange(len(self.lon))\nself.nv = self.ncv['SCHISM_hgrid_face_nodes'][:, :3] - 1\nself.time... | <|body_start_0|>
import netCDF4
from netcdftime import utime
self.nc = netCDF4.Dataset(filename)
self.ncv = self.nc.variables
self.lon = self.ncv['SCHISM_hgrid_node_x'][:]
self.lat = self.ncv['SCHISM_hgrid_node_y'][:]
self.nodeids = np.arange(len(self.lon))
... | schism_output | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class schism_output:
def __init__(self, filename):
"""read output filename and initialize grid"""
<|body_0|>
def init_node_tree(self, latlon=True):
"""build a node tree using cKDTree for a quick search for node coordinates"""
<|body_1|>
def find_nearest_node(s... | stack_v2_sparse_classes_75kplus_train_003634 | 19,398 | no_license | [
{
"docstring": "read output filename and initialize grid",
"name": "__init__",
"signature": "def __init__(self, filename)"
},
{
"docstring": "build a node tree using cKDTree for a quick search for node coordinates",
"name": "init_node_tree",
"signature": "def init_node_tree(self, latlon=... | 3 | stack_v2_sparse_classes_30k_train_004220 | Implement the Python class `schism_output` described below.
Class description:
Implement the schism_output class.
Method signatures and docstrings:
- def __init__(self, filename): read output filename and initialize grid
- def init_node_tree(self, latlon=True): build a node tree using cKDTree for a quick search for n... | Implement the Python class `schism_output` described below.
Class description:
Implement the schism_output class.
Method signatures and docstrings:
- def __init__(self, filename): read output filename and initialize grid
- def init_node_tree(self, latlon=True): build a node tree using cKDTree for a quick search for n... | 1828b3be0531d38171e5d16f77c1c422033adb2e | <|skeleton|>
class schism_output:
def __init__(self, filename):
"""read output filename and initialize grid"""
<|body_0|>
def init_node_tree(self, latlon=True):
"""build a node tree using cKDTree for a quick search for node coordinates"""
<|body_1|>
def find_nearest_node(s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class schism_output:
def __init__(self, filename):
"""read output filename and initialize grid"""
import netCDF4
from netcdftime import utime
self.nc = netCDF4.Dataset(filename)
self.ncv = self.nc.variables
self.lon = self.ncv['SCHISM_hgrid_node_x'][:]
self.la... | the_stack_v2_python_sparse | scripts/schism.py | hofmeist/schism-setups | train | 0 | |
de3a560441b9fb48f1ed577d00011576ba92e174 | [
"params = Parser.AuditListGetRequest.parse_args()\naudit_query = AuditTable.select(AuditTable)\nif len(params['q']) > 0:\n audit_query = audit_query.where(AuditTable.name ** '%{}%'.format(params['q']) | AuditTable.description ** '%{}%'.format(params['q']))\ntotal = audit_query.count()\naudit_query = audit_query.... | <|body_start_0|>
params = Parser.AuditListGetRequest.parse_args()
audit_query = AuditTable.select(AuditTable)
if len(params['q']) > 0:
audit_query = audit_query.where(AuditTable.name ** '%{}%'.format(params['q']) | AuditTable.description ** '%{}%'.format(params['q']))
total =... | AuditList | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuditList:
def get(self):
"""Retrieve list of audits"""
<|body_0|>
def post(self):
"""Create new audit"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
params = Parser.AuditListGetRequest.parse_args()
audit_query = AuditTable.select(AuditTabl... | stack_v2_sparse_classes_75kplus_train_003635 | 9,187 | permissive | [
{
"docstring": "Retrieve list of audits",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Create new audit",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004175 | Implement the Python class `AuditList` described below.
Class description:
Implement the AuditList class.
Method signatures and docstrings:
- def get(self): Retrieve list of audits
- def post(self): Create new audit | Implement the Python class `AuditList` described below.
Class description:
Implement the AuditList class.
Method signatures and docstrings:
- def get(self): Retrieve list of audits
- def post(self): Create new audit
<|skeleton|>
class AuditList:
def get(self):
"""Retrieve list of audits"""
<|bod... | e034d9db4c3fae697bfa15d4ba3d1475f5dd7e8a | <|skeleton|>
class AuditList:
def get(self):
"""Retrieve list of audits"""
<|body_0|>
def post(self):
"""Create new audit"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AuditList:
def get(self):
"""Retrieve list of audits"""
params = Parser.AuditListGetRequest.parse_args()
audit_query = AuditTable.select(AuditTable)
if len(params['q']) > 0:
audit_query = audit_query.where(AuditTable.name ** '%{}%'.format(params['q']) | AuditTable.d... | the_stack_v2_python_sparse | core/apis/audit.py | nishimunea/NT-D | train | 2 | |
387c35b6fa27d62ac46c157315515c84edfa1c8e | [
"name, extension = os.path.splitext(path)\nif extension and extension[1:] in self.CANDIDATE_EXTENSIONS:\n return True\nreturn False",
"filelead, filetail = os.path.split(filepath)\nname, extension = os.path.splitext(filetail)\nif extension:\n extension = extension[1:]\nfilenames = [name]\nif not name.starts... | <|body_start_0|>
name, extension = os.path.splitext(path)
if extension and extension[1:] in self.CANDIDATE_EXTENSIONS:
return True
return False
<|end_body_0|>
<|body_start_1|>
filelead, filetail = os.path.split(filepath)
name, extension = os.path.splitext(filetail)
... | Import paths resolver. Resolve given paths from SCSS source to absolute paths. It's a mixin, meaning without own ``__init__`` method so it's should be safe enough to inherit it from another class. Attributes: CANDIDATE_EXTENSIONS (list): List of extensions available to build candidate paths. Beware, order does matter, ... | ImportPathsResolver | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImportPathsResolver:
"""Import paths resolver. Resolve given paths from SCSS source to absolute paths. It's a mixin, meaning without own ``__init__`` method so it's should be safe enough to inherit it from another class. Attributes: CANDIDATE_EXTENSIONS (list): List of extensions available to bui... | stack_v2_sparse_classes_75kplus_train_003636 | 7,507 | permissive | [
{
"docstring": "Check given path is an allowed source file. A source file must have the right file extension to be allowed. Args: path (string): A file path, either relative or absolute. Returns: bool: True if allowed, else False.",
"name": "is_allowed_source",
"signature": "def is_allowed_source(self, ... | 4 | stack_v2_sparse_classes_30k_train_051315 | Implement the Python class `ImportPathsResolver` described below.
Class description:
Import paths resolver. Resolve given paths from SCSS source to absolute paths. It's a mixin, meaning without own ``__init__`` method so it's should be safe enough to inherit it from another class. Attributes: CANDIDATE_EXTENSIONS (lis... | Implement the Python class `ImportPathsResolver` described below.
Class description:
Import paths resolver. Resolve given paths from SCSS source to absolute paths. It's a mixin, meaning without own ``__init__`` method so it's should be safe enough to inherit it from another class. Attributes: CANDIDATE_EXTENSIONS (lis... | 491c0db5d6a3d6c18f858a8b94673d697b79b0a8 | <|skeleton|>
class ImportPathsResolver:
"""Import paths resolver. Resolve given paths from SCSS source to absolute paths. It's a mixin, meaning without own ``__init__`` method so it's should be safe enough to inherit it from another class. Attributes: CANDIDATE_EXTENSIONS (list): List of extensions available to bui... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImportPathsResolver:
"""Import paths resolver. Resolve given paths from SCSS source to absolute paths. It's a mixin, meaning without own ``__init__`` method so it's should be safe enough to inherit it from another class. Attributes: CANDIDATE_EXTENSIONS (list): List of extensions available to build candidate ... | the_stack_v2_python_sparse | boussole/resolver.py | sveetch/boussole | train | 14 |
7f64e5c2bf8f0bfbc208835fcbb940b888205e7e | [
"Simulator.__init__(self, *args, **kwargs)\nself.add_command('cv', self.change_value)\nself.add_command('set_pi', self.set_pi)\nslave = self.server.add_slave(1)\nslave.add_block('foo', HOLDING_REGISTERS, 0, 100)",
"address = int(args[1])\nvalues = []\nfor val in args[2:]:\n values.append(int(val))\nif address ... | <|body_start_0|>
Simulator.__init__(self, *args, **kwargs)
self.add_command('cv', self.change_value)
self.add_command('set_pi', self.set_pi)
slave = self.server.add_slave(1)
slave.add_block('foo', HOLDING_REGISTERS, 0, 100)
<|end_body_0|>
<|body_start_1|>
address = int(a... | A custom simulator | MySimulator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MySimulator:
"""A custom simulator"""
def __init__(self, *args, **kwargs):
"""Constructor"""
<|body_0|>
def change_value(self, args):
"""change the value of some registers"""
<|body_1|>
def set_pi(self, args):
"""change the value of some regi... | stack_v2_sparse_classes_75kplus_train_003637 | 3,089 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "change the value of some registers",
"name": "change_value",
"signature": "def change_value(self, args)"
},
{
"docstring": "change the value of some registers",... | 3 | stack_v2_sparse_classes_30k_train_022705 | Implement the Python class `MySimulator` described below.
Class description:
A custom simulator
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Constructor
- def change_value(self, args): change the value of some registers
- def set_pi(self, args): change the value of some registers | Implement the Python class `MySimulator` described below.
Class description:
A custom simulator
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Constructor
- def change_value(self, args): change the value of some registers
- def set_pi(self, args): change the value of some registers
<|skelet... | 6854d0fd4e0edb4fc9ecf33be0c613b8f7054366 | <|skeleton|>
class MySimulator:
"""A custom simulator"""
def __init__(self, *args, **kwargs):
"""Constructor"""
<|body_0|>
def change_value(self, args):
"""change the value of some registers"""
<|body_1|>
def set_pi(self, args):
"""change the value of some regi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MySimulator:
"""A custom simulator"""
def __init__(self, *args, **kwargs):
"""Constructor"""
Simulator.__init__(self, *args, **kwargs)
self.add_command('cv', self.change_value)
self.add_command('set_pi', self.set_pi)
slave = self.server.add_slave(1)
slave.a... | the_stack_v2_python_sparse | modbus-tk/mysimu.py | igomine/Pi3_Portable_Controller | train | 2 |
a8b4e306e78420d46847ed2d7da36432fe0d9b24 | [
"b1 = all((isinstance(d, float) for d in [P, I, D]))\nb2 = all((isinstance(d, np.ndarray) for d in [P, I, D]))\nif not b1 and (not b2):\n pid_coef_types = [type(d) for d in [P, I, D]]\n err_msg = 'PidController: Data type of P,I,D coefficients are wrong: ' + str(pid_coef_types)\n raise RuntimeError(err_msg... | <|body_start_0|>
b1 = all((isinstance(d, float) for d in [P, I, D]))
b2 = all((isinstance(d, np.ndarray) for d in [P, I, D]))
if not b1 and (not b2):
pid_coef_types = [type(d) for d in [P, I, D]]
err_msg = 'PidController: Data type of P,I,D coefficients are wrong: ' + str... | PID controller | PidController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PidController:
"""PID controller"""
def __init__(self, T, P=0.0, I=0.0, D=0.0):
"""Arguments T {float}: Control period. Unit: second. This is the inverse of control frequency. P {float or np.array}: Proportional control coefficient. I {float or np.array}: Integral control coefficient... | stack_v2_sparse_classes_75kplus_train_003638 | 1,648 | no_license | [
{
"docstring": "Arguments T {float}: Control period. Unit: second. This is the inverse of control frequency. P {float or np.array}: Proportional control coefficient. I {float or np.array}: Integral control coefficient. D {float or np.array}: Differential control coefficient.",
"name": "__init__",
"signa... | 2 | stack_v2_sparse_classes_30k_train_027503 | Implement the Python class `PidController` described below.
Class description:
PID controller
Method signatures and docstrings:
- def __init__(self, T, P=0.0, I=0.0, D=0.0): Arguments T {float}: Control period. Unit: second. This is the inverse of control frequency. P {float or np.array}: Proportional control coeffic... | Implement the Python class `PidController` described below.
Class description:
PID controller
Method signatures and docstrings:
- def __init__(self, T, P=0.0, I=0.0, D=0.0): Arguments T {float}: Control period. Unit: second. This is the inverse of control frequency. P {float or np.array}: Proportional control coeffic... | a68f32d77bf44664d29c5a4ece80e213d7cd2f6e | <|skeleton|>
class PidController:
"""PID controller"""
def __init__(self, T, P=0.0, I=0.0, D=0.0):
"""Arguments T {float}: Control period. Unit: second. This is the inverse of control frequency. P {float or np.array}: Proportional control coefficient. I {float or np.array}: Integral control coefficient... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PidController:
"""PID controller"""
def __init__(self, T, P=0.0, I=0.0, D=0.0):
"""Arguments T {float}: Control period. Unit: second. This is the inverse of control frequency. P {float or np.array}: Proportional control coefficient. I {float or np.array}: Integral control coefficient. D {float or... | the_stack_v2_python_sparse | utils/pid_controller.py | dfaizaditya/rodrigo | train | 0 |
6b11653ed2b9e55cd25155202d749ee37ebedc77 | [
"adjList = [[False] * n for _ in range(n)]\ndeg = [0] * n\nfor u, v in edges:\n adjList[u - 1][v - 1] = adjList[v - 1][u - 1] = True\n deg[u - 1] += 1\n deg[v - 1] += 1\nres = INF\nfor i in range(n):\n for j in range(i + 1, n):\n if adjList[i][j]:\n for k in range(j + 1, n):\n ... | <|body_start_0|>
adjList = [[False] * n for _ in range(n)]
deg = [0] * n
for u, v in edges:
adjList[u - 1][v - 1] = adjList[v - 1][u - 1] = True
deg[u - 1] += 1
deg[v - 1] += 1
res = INF
for i in range(n):
for j in range(i + 1, n):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minTrioDegree1(self, n: int, edges: List[List[int]]) -> int:
"""时间复杂度O(n^3)"""
<|body_0|>
def minTrioDegree(self, n: int, edges: List[List[int]]) -> int:
"""三元环计数 n<=400 稠密图 边定向 度数为第一关键字,点的标号为第二关键字 此时任意点的出度不会超过 (sqrt(2E)) 时间复杂度O(E^(3/2))"""
<|bo... | stack_v2_sparse_classes_75kplus_train_003639 | 2,578 | no_license | [
{
"docstring": "时间复杂度O(n^3)",
"name": "minTrioDegree1",
"signature": "def minTrioDegree1(self, n: int, edges: List[List[int]]) -> int"
},
{
"docstring": "三元环计数 n<=400 稠密图 边定向 度数为第一关键字,点的标号为第二关键字 此时任意点的出度不会超过 (sqrt(2E)) 时间复杂度O(E^(3/2))",
"name": "minTrioDegree",
"signature": "def minTrioD... | 2 | stack_v2_sparse_classes_30k_train_037053 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minTrioDegree1(self, n: int, edges: List[List[int]]) -> int: 时间复杂度O(n^3)
- def minTrioDegree(self, n: int, edges: List[List[int]]) -> int: 三元环计数 n<=400 稠密图 边定向 度数为第一关键字,点的标号为... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minTrioDegree1(self, n: int, edges: List[List[int]]) -> int: 时间复杂度O(n^3)
- def minTrioDegree(self, n: int, edges: List[List[int]]) -> int: 三元环计数 n<=400 稠密图 边定向 度数为第一关键字,点的标号为... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def minTrioDegree1(self, n: int, edges: List[List[int]]) -> int:
"""时间复杂度O(n^3)"""
<|body_0|>
def minTrioDegree(self, n: int, edges: List[List[int]]) -> int:
"""三元环计数 n<=400 稠密图 边定向 度数为第一关键字,点的标号为第二关键字 此时任意点的出度不会超过 (sqrt(2E)) 时间复杂度O(E^(3/2))"""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minTrioDegree1(self, n: int, edges: List[List[int]]) -> int:
"""时间复杂度O(n^3)"""
adjList = [[False] * n for _ in range(n)]
deg = [0] * n
for u, v in edges:
adjList[u - 1][v - 1] = adjList[v - 1][u - 1] = True
deg[u - 1] += 1
deg[v... | the_stack_v2_python_sparse | 7_graph/经典题/枚举边或顶点/1761. 一个图中连通三元组的最小度数-无向图定向.py | 981377660LMT/algorithm-study | train | 225 | |
9144e5d189ed704f69eb27ad0845f1b4f7edcee1 | [
"PygameScreen.__init__(self)\nself.attacksMenu = attacksMenu\nself.lastScreen = lastScreen",
"previousScreenSurface = self.lastScreen.draw()\nself.drawOnSurface(previousScreenSurface, left=0, top=0)\nmenuSurface = self.attacksMenu.draw()\nself.drawOnSurface(menuSurface, left=0.05, top=0.7)"
] | <|body_start_0|>
PygameScreen.__init__(self)
self.attacksMenu = attacksMenu
self.lastScreen = lastScreen
<|end_body_0|>
<|body_start_1|>
previousScreenSurface = self.lastScreen.draw()
self.drawOnSurface(previousScreenSurface, left=0, top=0)
menuSurface = self.attacksMenu... | Represents the screen for a Picking an Attack | AttackPickerScreen | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttackPickerScreen:
"""Represents the screen for a Picking an Attack"""
def __init__(self, attacksMenu, lastScreen):
"""Initialize the screen"""
<|body_0|>
def drawSurface(self):
"""Draws the screen"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_003640 | 675 | no_license | [
{
"docstring": "Initialize the screen",
"name": "__init__",
"signature": "def __init__(self, attacksMenu, lastScreen)"
},
{
"docstring": "Draws the screen",
"name": "drawSurface",
"signature": "def drawSurface(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_038274 | Implement the Python class `AttackPickerScreen` described below.
Class description:
Represents the screen for a Picking an Attack
Method signatures and docstrings:
- def __init__(self, attacksMenu, lastScreen): Initialize the screen
- def drawSurface(self): Draws the screen | Implement the Python class `AttackPickerScreen` described below.
Class description:
Represents the screen for a Picking an Attack
Method signatures and docstrings:
- def __init__(self, attacksMenu, lastScreen): Initialize the screen
- def drawSurface(self): Draws the screen
<|skeleton|>
class AttackPickerScreen:
... | 3931eee5fd04e18bb1738a0b27a4c6979dc4db01 | <|skeleton|>
class AttackPickerScreen:
"""Represents the screen for a Picking an Attack"""
def __init__(self, attacksMenu, lastScreen):
"""Initialize the screen"""
<|body_0|>
def drawSurface(self):
"""Draws the screen"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AttackPickerScreen:
"""Represents the screen for a Picking an Attack"""
def __init__(self, attacksMenu, lastScreen):
"""Initialize the screen"""
PygameScreen.__init__(self)
self.attacksMenu = attacksMenu
self.lastScreen = lastScreen
def drawSurface(self):
"""D... | the_stack_v2_python_sparse | src/Screen/Pygame/Event/LearnAttack/attack_picker_screen.py | sgtnourry/Pokemon-Project | train | 0 |
282b1a31ed7e1e8696e4fe393773ef61736182fe | [
"args = parse_base.parse_args()\nspace_id = args.get('space_id')\nurl = args.get('url')\ninfo = args.get('info')\nimg = args.get('img')\nname = args.get('name')\nsort = args.get('sort')\nmodel_data = Ad()\nmodel_data.space_id = space_id\nmodel_data.img = img\nmodel_data.url = url\nmodel_data.info = info\nmodel_data... | <|body_start_0|>
args = parse_base.parse_args()
space_id = args.get('space_id')
url = args.get('url')
info = args.get('info')
img = args.get('img')
name = args.get('name')
sort = args.get('sort')
model_data = Ad()
model_data.space_id = space_id
... | AdResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdResource:
def post(self):
"""添加"""
<|body_0|>
def put(self):
"""修改"""
<|body_1|>
def get(self):
"""获取列表"""
<|body_2|>
def delete(self):
"""删除"""
<|body_3|>
<|end_skeleton|>
<|body_start_0|>
args = parse_ba... | stack_v2_sparse_classes_75kplus_train_003641 | 5,824 | permissive | [
{
"docstring": "添加",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "修改",
"name": "put",
"signature": "def put(self)"
},
{
"docstring": "获取列表",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "删除",
"name": "delete",
"signatur... | 4 | null | Implement the Python class `AdResource` described below.
Class description:
Implement the AdResource class.
Method signatures and docstrings:
- def post(self): 添加
- def put(self): 修改
- def get(self): 获取列表
- def delete(self): 删除 | Implement the Python class `AdResource` described below.
Class description:
Implement the AdResource class.
Method signatures and docstrings:
- def post(self): 添加
- def put(self): 修改
- def get(self): 获取列表
- def delete(self): 删除
<|skeleton|>
class AdResource:
def post(self):
"""添加"""
<|body_0|>
... | 35ddd2946bf4c97806bb38057a7dc9d6fa97c118 | <|skeleton|>
class AdResource:
def post(self):
"""添加"""
<|body_0|>
def put(self):
"""修改"""
<|body_1|>
def get(self):
"""获取列表"""
<|body_2|>
def delete(self):
"""删除"""
<|body_3|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AdResource:
def post(self):
"""添加"""
args = parse_base.parse_args()
space_id = args.get('space_id')
url = args.get('url')
info = args.get('info')
img = args.get('img')
name = args.get('name')
sort = args.get('sort')
model_data = Ad()
... | the_stack_v2_python_sparse | service/app/apis/resource/ad.py | xuannanxan/maitul-manage | train | 0 | |
2d3a94dbdbc69e3eff3d48c6b51c8e2a3c56d0ac | [
"self.length = len(nums)\nself.st = [0] * self.length\nself.st.extend(nums)\nfor i in range(self.length - 1, 0, -1):\n self.st[i] = self.st[2 * i] + self.st[2 * i + 1]",
"if -1 < i < self.length:\n p = i + self.length\n self.st[p] = val\n while p > 1:\n self.st[p // 2] = self.st[p] + self.st[p ... | <|body_start_0|>
self.length = len(nums)
self.st = [0] * self.length
self.st.extend(nums)
for i in range(self.length - 1, 0, -1):
self.st[i] = self.st[2 * i] + self.st[2 * i + 1]
<|end_body_0|>
<|body_start_1|>
if -1 < i < self.length:
p = i + self.length... | NumArray_SegmentTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray_SegmentTree:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: void"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
... | stack_v2_sparse_classes_75kplus_train_003642 | 4,069 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type val: int :rtype: void",
"name": "update",
"signature": "def update(self, i, val)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
... | 3 | stack_v2_sparse_classes_30k_test_002243 | Implement the Python class `NumArray_SegmentTree` described below.
Class description:
Implement the NumArray_SegmentTree class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: void
- def sumRange(self, i, j): :type i: ... | Implement the Python class `NumArray_SegmentTree` described below.
Class description:
Implement the NumArray_SegmentTree class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: void
- def sumRange(self, i, j): :type i: ... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class NumArray_SegmentTree:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: void"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumArray_SegmentTree:
def __init__(self, nums):
""":type nums: List[int]"""
self.length = len(nums)
self.st = [0] * self.length
self.st.extend(nums)
for i in range(self.length - 1, 0, -1):
self.st[i] = self.st[2 * i] + self.st[2 * i + 1]
def update(self... | the_stack_v2_python_sparse | code307RangeSumQueryMutable.py | cybelewang/leetcode-python | train | 0 | |
7b92ecdcc4d45ca866457fad1f28e9f45f90e422 | [
"p0 = p1 = 0\nfor i in range(len(nums)):\n if nums[i] == 0:\n nums[p0], nums[i] = (nums[i], nums[p0])\n p0 += 1\n if p1 < p0:\n p1 = p0\n else:\n nums[p1], nums[i] = (nums[i], nums[p1])\n p1 += 1\n if nums[i] == 1:\n nums[p1], nums[i] = (nums... | <|body_start_0|>
p0 = p1 = 0
for i in range(len(nums)):
if nums[i] == 0:
nums[p0], nums[i] = (nums[i], nums[p0])
p0 += 1
if p1 < p0:
p1 = p0
else:
nums[p1], nums[i] = (nums[i], nums[p1])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def sortColors2(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_75kplus_train_003643 | 1,185 | no_license | [
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "sortColors",
"signature": "def sortColors(self, nums: List[int]) -> None"
},
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "sortColors2",
"signature": "def sortColors2(self,... | 2 | stack_v2_sparse_classes_30k_train_051828 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead.
- def sortColors2(self, nums: List[int]) -> None: Do not return anything, mod... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead.
- def sortColors2(self, nums: List[int]) -> None: Do not return anything, mod... | 68a09a1ea2fb5083d62d8188c7ef213b2cc315cd | <|skeleton|>
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def sortColors2(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def sortColors(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
p0 = p1 = 0
for i in range(len(nums)):
if nums[i] == 0:
nums[p0], nums[i] = (nums[i], nums[p0])
p0 += 1
if p1... | the_stack_v2_python_sparse | leetcode061-080/leetcode75-sort-colors.py | linshuang/code4fun | train | 0 | |
a5f7875b1b36f21e9b5a8f409ef0c76e3012ceca | [
"self.open(base_url + '/logout')\nself.open(base_url + '/login')\nself.type('#email', test_user.email)\nself.type('#password', test_user.password)\nself.click('input[type=\"submit\"]')\nself.assert_element('#sell_form')\nself.assert_element(\"#sell_form form div label[for='name']\")\nself.type('#sell_form form div ... | <|body_start_0|>
self.open(base_url + '/logout')
self.open(base_url + '/login')
self.type('#email', test_user.email)
self.type('#password', test_user.password)
self.click('input[type="submit"]')
self.assert_element('#sell_form')
self.assert_element("#sell_form for... | FrontendSellR4 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FrontendSellR4:
def test_sellDateNumeric(self, *_):
"""This function tests that upon an invalid date the sell post is not sent and an error message is displayed"""
<|body_0|>
def test_sellDate8Chars(self, *_):
"""This function tests that the date must contain exactly... | stack_v2_sparse_classes_75kplus_train_003644 | 4,790 | permissive | [
{
"docstring": "This function tests that upon an invalid date the sell post is not sent and an error message is displayed",
"name": "test_sellDateNumeric",
"signature": "def test_sellDateNumeric(self, *_)"
},
{
"docstring": "This function tests that the date must contain exactly eight characters... | 2 | stack_v2_sparse_classes_30k_train_020876 | Implement the Python class `FrontendSellR4` described below.
Class description:
Implement the FrontendSellR4 class.
Method signatures and docstrings:
- def test_sellDateNumeric(self, *_): This function tests that upon an invalid date the sell post is not sent and an error message is displayed
- def test_sellDate8Char... | Implement the Python class `FrontendSellR4` described below.
Class description:
Implement the FrontendSellR4 class.
Method signatures and docstrings:
- def test_sellDateNumeric(self, *_): This function tests that upon an invalid date the sell post is not sent and an error message is displayed
- def test_sellDate8Char... | 582e00a4c16016e545fedcbb14a745d125db94e0 | <|skeleton|>
class FrontendSellR4:
def test_sellDateNumeric(self, *_):
"""This function tests that upon an invalid date the sell post is not sent and an error message is displayed"""
<|body_0|>
def test_sellDate8Chars(self, *_):
"""This function tests that the date must contain exactly... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FrontendSellR4:
def test_sellDateNumeric(self, *_):
"""This function tests that upon an invalid date the sell post is not sent and an error message is displayed"""
self.open(base_url + '/logout')
self.open(base_url + '/login')
self.type('#email', test_user.email)
self.t... | the_stack_v2_python_sparse | qa327_test/frontend/sell/test_R4_5.py | GraemeBadley/QA-Project | train | 0 | |
09555195b025a37cd8a10ab0fe9d0e4427648e79 | [
"self.is_email_otp_setup_done = is_email_otp_setup_done\nself.is_totp_setup_done = is_totp_setup_done\nself.is_user_exempt_from_mfa = is_user_exempt_from_mfa",
"if dictionary is None:\n return None\nis_email_otp_setup_done = dictionary.get('isEmailOtpSetupDone')\nis_totp_setup_done = dictionary.get('isTotpSetu... | <|body_start_0|>
self.is_email_otp_setup_done = is_email_otp_setup_done
self.is_totp_setup_done = is_totp_setup_done
self.is_user_exempt_from_mfa = is_user_exempt_from_mfa
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
is_email_otp_setup_done = di... | Implementation of the 'MfaInfo' model. Specifies information about MFA. Attributes: is_email_otp_setup_done (bool): Specifies if email OTP setup is done on the user. is_totp_setup_done (bool): Specifies if TOTP setup is done on the user. is_user_exempt_from_mfa (bool): Specifies if MFA is disabled on the user. | MfaInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MfaInfo:
"""Implementation of the 'MfaInfo' model. Specifies information about MFA. Attributes: is_email_otp_setup_done (bool): Specifies if email OTP setup is done on the user. is_totp_setup_done (bool): Specifies if TOTP setup is done on the user. is_user_exempt_from_mfa (bool): Specifies if MF... | stack_v2_sparse_classes_75kplus_train_003645 | 2,122 | permissive | [
{
"docstring": "Constructor for the MfaInfo class",
"name": "__init__",
"signature": "def __init__(self, is_email_otp_setup_done=None, is_totp_setup_done=None, is_user_exempt_from_mfa=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A d... | 2 | stack_v2_sparse_classes_30k_train_042891 | Implement the Python class `MfaInfo` described below.
Class description:
Implementation of the 'MfaInfo' model. Specifies information about MFA. Attributes: is_email_otp_setup_done (bool): Specifies if email OTP setup is done on the user. is_totp_setup_done (bool): Specifies if TOTP setup is done on the user. is_user_... | Implement the Python class `MfaInfo` described below.
Class description:
Implementation of the 'MfaInfo' model. Specifies information about MFA. Attributes: is_email_otp_setup_done (bool): Specifies if email OTP setup is done on the user. is_totp_setup_done (bool): Specifies if TOTP setup is done on the user. is_user_... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class MfaInfo:
"""Implementation of the 'MfaInfo' model. Specifies information about MFA. Attributes: is_email_otp_setup_done (bool): Specifies if email OTP setup is done on the user. is_totp_setup_done (bool): Specifies if TOTP setup is done on the user. is_user_exempt_from_mfa (bool): Specifies if MF... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MfaInfo:
"""Implementation of the 'MfaInfo' model. Specifies information about MFA. Attributes: is_email_otp_setup_done (bool): Specifies if email OTP setup is done on the user. is_totp_setup_done (bool): Specifies if TOTP setup is done on the user. is_user_exempt_from_mfa (bool): Specifies if MFA is disabled... | the_stack_v2_python_sparse | cohesity_management_sdk/models/mfa_info.py | cohesity/management-sdk-python | train | 24 |
5df396206a05756d8a3349cdc1529a610f7b748b | [
"if values:\n queryset = LessonPlan.objects.order_by('book')\nreturn queryset",
"if values:\n books = values.split(',')\n queryset = LessonPlan.objects.filter(book__in=books)\nreturn queryset"
] | <|body_start_0|>
if values:
queryset = LessonPlan.objects.order_by('book')
return queryset
<|end_body_0|>
<|body_start_1|>
if values:
books = values.split(',')
queryset = LessonPlan.objects.filter(book__in=books)
return queryset
<|end_body_1|>
| LessonPlanFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LessonPlanFilter:
def filter_get_all(self, queryset, name, values):
"""Filtering all locations. :param queryset: :param name: - :param values: example - True, False :return:"""
<|body_0|>
def filter_book(self, queryset, name, values):
"""Filtering all locations. :par... | stack_v2_sparse_classes_75kplus_train_003646 | 25,200 | no_license | [
{
"docstring": "Filtering all locations. :param queryset: :param name: - :param values: example - True, False :return:",
"name": "filter_get_all",
"signature": "def filter_get_all(self, queryset, name, values)"
},
{
"docstring": "Filtering all locations. :param queryset: :param name: - :param va... | 2 | stack_v2_sparse_classes_30k_train_027506 | Implement the Python class `LessonPlanFilter` described below.
Class description:
Implement the LessonPlanFilter class.
Method signatures and docstrings:
- def filter_get_all(self, queryset, name, values): Filtering all locations. :param queryset: :param name: - :param values: example - True, False :return:
- def fil... | Implement the Python class `LessonPlanFilter` described below.
Class description:
Implement the LessonPlanFilter class.
Method signatures and docstrings:
- def filter_get_all(self, queryset, name, values): Filtering all locations. :param queryset: :param name: - :param values: example - True, False :return:
- def fil... | 3dab33b61f50c254d7c6d53add2b776a7e211cbb | <|skeleton|>
class LessonPlanFilter:
def filter_get_all(self, queryset, name, values):
"""Filtering all locations. :param queryset: :param name: - :param values: example - True, False :return:"""
<|body_0|>
def filter_book(self, queryset, name, values):
"""Filtering all locations. :par... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LessonPlanFilter:
def filter_get_all(self, queryset, name, values):
"""Filtering all locations. :param queryset: :param name: - :param values: example - True, False :return:"""
if values:
queryset = LessonPlan.objects.order_by('book')
return queryset
def filter_book(se... | the_stack_v2_python_sparse | classapp/filters.py | promaster171019/Beacon | train | 0 | |
22084869c8fa8f8b8d28bad2ad5ba9076062dfba | [
"if not a:\n return 0\nn = len(a)\ns = [0]\nfor i in range(n):\n s.append(s[-1] + a[i])\np = float('inf')\nm = len(s)\nfor i in range(m):\n t = s[i] + x\n if t <= s[-1]:\n j = self.find_target_sum(i, t, s)\n p = min(p, j - i)\nif p == float('inf'):\n return 0\nelse:\n return p",
"i... | <|body_start_0|>
if not a:
return 0
n = len(a)
s = [0]
for i in range(n):
s.append(s[-1] + a[i])
p = float('inf')
m = len(s)
for i in range(m):
t = s[i] + x
if t <= s[-1]:
j = self.find_target_sum(i, ... | Iterative binary search over array of incremental cumulative sums. Time complexity: O(n * log(n)) - Amortized iterate over array with binary search for cumulative sum Space complexity: O(n) - Amortized store array of incremental cumulative sums | Solution3 | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution3:
"""Iterative binary search over array of incremental cumulative sums. Time complexity: O(n * log(n)) - Amortized iterate over array with binary search for cumulative sum Space complexity: O(n) - Amortized store array of incremental cumulative sums"""
def find_min_sub_len(self, x, ... | stack_v2_sparse_classes_75kplus_train_003647 | 9,763 | permissive | [
{
"docstring": "Determines minimum subarray length to meet or exceed target sum. :param int x: target integer sum :param list[int] a: array of input positive integers :return: minimum number of elements required for target sum :rtype: int",
"name": "find_min_sub_len",
"signature": "def find_min_sub_len(... | 2 | stack_v2_sparse_classes_30k_train_054574 | Implement the Python class `Solution3` described below.
Class description:
Iterative binary search over array of incremental cumulative sums. Time complexity: O(n * log(n)) - Amortized iterate over array with binary search for cumulative sum Space complexity: O(n) - Amortized store array of incremental cumulative sums... | Implement the Python class `Solution3` described below.
Class description:
Iterative binary search over array of incremental cumulative sums. Time complexity: O(n * log(n)) - Amortized iterate over array with binary search for cumulative sum Space complexity: O(n) - Amortized store array of incremental cumulative sums... | 69f90877c5466927e8b081c4268cbcda074813ec | <|skeleton|>
class Solution3:
"""Iterative binary search over array of incremental cumulative sums. Time complexity: O(n * log(n)) - Amortized iterate over array with binary search for cumulative sum Space complexity: O(n) - Amortized store array of incremental cumulative sums"""
def find_min_sub_len(self, x, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution3:
"""Iterative binary search over array of incremental cumulative sums. Time complexity: O(n * log(n)) - Amortized iterate over array with binary search for cumulative sum Space complexity: O(n) - Amortized store array of incremental cumulative sums"""
def find_min_sub_len(self, x, a):
"... | the_stack_v2_python_sparse | 0209_minimum_size_subarray_sum/python_source.py | arthurdysart/LeetCode | train | 0 |
dddef8f53525eec616ffdfcd73c9cb028e7fd261 | [
"super(Uptime, self).__init__(connection=connection, prompt=prompt, newline_chars=newline_chars, runner=runner)\nself.options = options\nself._converter_helper = ConverterHelper.get_converter_helper()",
"cmd = 'uptime'\nif self.options:\n cmd = '{} {}'.format(cmd, self.options)\nreturn cmd",
"if is_full_line... | <|body_start_0|>
super(Uptime, self).__init__(connection=connection, prompt=prompt, newline_chars=newline_chars, runner=runner)
self.options = options
self._converter_helper = ConverterHelper.get_converter_helper()
<|end_body_0|>
<|body_start_1|>
cmd = 'uptime'
if self.options:
... | Uptime | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Uptime:
def __init__(self, connection, options=None, prompt=None, newline_chars=None, runner=None):
""":param connection: Moler connection to device, terminal when command is executed. :param options: uptime unix command options :param prompt: prompt (on system where command runs). :para... | stack_v2_sparse_classes_75kplus_train_003648 | 7,261 | permissive | [
{
"docstring": ":param connection: Moler connection to device, terminal when command is executed. :param options: uptime unix command options :param prompt: prompt (on system where command runs). :param newline_chars: Characters to split lines - list. :param runner: Runner to run command.",
"name": "__init_... | 6 | null | Implement the Python class `Uptime` described below.
Class description:
Implement the Uptime class.
Method signatures and docstrings:
- def __init__(self, connection, options=None, prompt=None, newline_chars=None, runner=None): :param connection: Moler connection to device, terminal when command is executed. :param o... | Implement the Python class `Uptime` described below.
Class description:
Implement the Uptime class.
Method signatures and docstrings:
- def __init__(self, connection, options=None, prompt=None, newline_chars=None, runner=None): :param connection: Moler connection to device, terminal when command is executed. :param o... | 5a7bb06807b6e0124c77040367d0c20f42849a4c | <|skeleton|>
class Uptime:
def __init__(self, connection, options=None, prompt=None, newline_chars=None, runner=None):
""":param connection: Moler connection to device, terminal when command is executed. :param options: uptime unix command options :param prompt: prompt (on system where command runs). :para... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Uptime:
def __init__(self, connection, options=None, prompt=None, newline_chars=None, runner=None):
""":param connection: Moler connection to device, terminal when command is executed. :param options: uptime unix command options :param prompt: prompt (on system where command runs). :param newline_char... | the_stack_v2_python_sparse | moler/cmd/unix/uptime.py | nokia/moler | train | 60 | |
83453fed0c0ce8f86fc7bef9d46dca2095f24657 | [
"application_id = self.application.id\nassert _assert__application_id(application_id)\ndatas = await self.http.application_role_connection_metadata_get_all(application_id)\nreturn [ApplicationRoleConnectionMetadata.from_data(data) for data in datas]",
"application_id = self.application.id\nassert _assert__applica... | <|body_start_0|>
application_id = self.application.id
assert _assert__application_id(application_id)
datas = await self.http.application_role_connection_metadata_get_all(application_id)
return [ApplicationRoleConnectionMetadata.from_data(data) for data in datas]
<|end_body_0|>
<|body_st... | ClientCompoundApplicationRoleConnectionEndpoints | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClientCompoundApplicationRoleConnectionEndpoints:
async def application_role_connection_metadata_get_all(self):
"""Requests all the role connection metadatas of the client's application. Returns ------- application_role_connection_metadatas : `list` of `ApplicationRoleConnectionMetadata`... | stack_v2_sparse_classes_75kplus_train_003649 | 2,417 | permissive | [
{
"docstring": "Requests all the role connection metadatas of the client's application. Returns ------- application_role_connection_metadatas : `list` of `ApplicationRoleConnectionMetadata` Raises ------ ConnectionError No internet connection. DiscordException If any exception was received from the Discord API.... | 2 | stack_v2_sparse_classes_30k_val_000470 | Implement the Python class `ClientCompoundApplicationRoleConnectionEndpoints` described below.
Class description:
Implement the ClientCompoundApplicationRoleConnectionEndpoints class.
Method signatures and docstrings:
- async def application_role_connection_metadata_get_all(self): Requests all the role connection met... | Implement the Python class `ClientCompoundApplicationRoleConnectionEndpoints` described below.
Class description:
Implement the ClientCompoundApplicationRoleConnectionEndpoints class.
Method signatures and docstrings:
- async def application_role_connection_metadata_get_all(self): Requests all the role connection met... | 53f24fdb38459dc5a4fd04f11bdbfee8295b76a4 | <|skeleton|>
class ClientCompoundApplicationRoleConnectionEndpoints:
async def application_role_connection_metadata_get_all(self):
"""Requests all the role connection metadatas of the client's application. Returns ------- application_role_connection_metadatas : `list` of `ApplicationRoleConnectionMetadata`... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ClientCompoundApplicationRoleConnectionEndpoints:
async def application_role_connection_metadata_get_all(self):
"""Requests all the role connection metadatas of the client's application. Returns ------- application_role_connection_metadatas : `list` of `ApplicationRoleConnectionMetadata` Raises ------... | the_stack_v2_python_sparse | hata/discord/client/compounds/application_role_connection.py | HuyaneMatsu/hata | train | 3 | |
800308521b57239404b208770ba356e4fb428d07 | [
"self.first_failed_run_time_usecs = first_failed_run_time_usecs\nself.first_successful_run_time_usecs = first_successful_run_time_usecs\nself.last_failed_run_time_usecs = last_failed_run_time_usecs\nself.last_run_end_time_usecs = last_run_end_time_usecs\nself.last_run_error_msg = last_run_error_msg\nself.last_run_s... | <|body_start_0|>
self.first_failed_run_time_usecs = first_failed_run_time_usecs
self.first_successful_run_time_usecs = first_successful_run_time_usecs
self.last_failed_run_time_usecs = last_failed_run_time_usecs
self.last_run_end_time_usecs = last_run_end_time_usecs
self.last_run... | Implementation of the 'ProtectionSourcesSummaryStats' model. Specifies Job Run (Snapshot) summary statistics about the specified leaf Protection Source Object (such as a VM). Attributes: first_failed_run_time_usecs (long|int): Specifies the start time of the first failed Job Run protecting this Protection Source Object... | ProtectionSourcesSummaryStats | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProtectionSourcesSummaryStats:
"""Implementation of the 'ProtectionSourcesSummaryStats' model. Specifies Job Run (Snapshot) summary statistics about the specified leaf Protection Source Object (such as a VM). Attributes: first_failed_run_time_usecs (long|int): Specifies the start time of the firs... | stack_v2_sparse_classes_75kplus_train_003650 | 10,502 | permissive | [
{
"docstring": "Constructor for the ProtectionSourcesSummaryStats class",
"name": "__init__",
"signature": "def __init__(self, first_failed_run_time_usecs=None, first_successful_run_time_usecs=None, last_failed_run_time_usecs=None, last_run_end_time_usecs=None, last_run_error_msg=None, last_run_start_ti... | 2 | stack_v2_sparse_classes_30k_train_050808 | Implement the Python class `ProtectionSourcesSummaryStats` described below.
Class description:
Implementation of the 'ProtectionSourcesSummaryStats' model. Specifies Job Run (Snapshot) summary statistics about the specified leaf Protection Source Object (such as a VM). Attributes: first_failed_run_time_usecs (long|int... | Implement the Python class `ProtectionSourcesSummaryStats` described below.
Class description:
Implementation of the 'ProtectionSourcesSummaryStats' model. Specifies Job Run (Snapshot) summary statistics about the specified leaf Protection Source Object (such as a VM). Attributes: first_failed_run_time_usecs (long|int... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ProtectionSourcesSummaryStats:
"""Implementation of the 'ProtectionSourcesSummaryStats' model. Specifies Job Run (Snapshot) summary statistics about the specified leaf Protection Source Object (such as a VM). Attributes: first_failed_run_time_usecs (long|int): Specifies the start time of the firs... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProtectionSourcesSummaryStats:
"""Implementation of the 'ProtectionSourcesSummaryStats' model. Specifies Job Run (Snapshot) summary statistics about the specified leaf Protection Source Object (such as a VM). Attributes: first_failed_run_time_usecs (long|int): Specifies the start time of the first failed Job ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/protection_sources_summary_stats.py | cohesity/management-sdk-python | train | 24 |
b800923ace451f5793be39ee42413de6eb030af4 | [
"self.data = data\nself.best_F1 = best_F1\nself.file_weights = file_weights\nself.early_stopping = early_stopping\nself.epochs_since_improvement = 0\nself.epoch_best = 0\nself.considered_improvement = considered_improvement\nself.label_list = label_list",
"results = evaluate_metrics(self.model, self.data, ['taggi... | <|body_start_0|>
self.data = data
self.best_F1 = best_F1
self.file_weights = file_weights
self.early_stopping = early_stopping
self.epochs_since_improvement = 0
self.epoch_best = 0
self.considered_improvement = considered_improvement
self.label_list = labe... | Keras callback to calculate acc after each epoch and save file with the weights if the evaluation improves | TaggingCallback | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaggingCallback:
"""Keras callback to calculate acc after each epoch and save file with the weights if the evaluation improves"""
def __init__(self, data, file_weights=None, best_F1=0, early_stopping=0, considered_improvement=0.01, label_list=[]):
"""Initialize the keras callback Par... | stack_v2_sparse_classes_75kplus_train_003651 | 8,596 | permissive | [
{
"docstring": "Initialize the keras callback Parameters ---------- data : tuple or KerasDataGenerator Validation data for model evaluation (X_val, Y_val) or KerasDataGenerator file_weights : string Path to the file with the weights best_acc : float Last accuracy value, only if continue early_stopping : int Num... | 2 | stack_v2_sparse_classes_30k_train_000831 | Implement the Python class `TaggingCallback` described below.
Class description:
Keras callback to calculate acc after each epoch and save file with the weights if the evaluation improves
Method signatures and docstrings:
- def __init__(self, data, file_weights=None, best_F1=0, early_stopping=0, considered_improvemen... | Implement the Python class `TaggingCallback` described below.
Class description:
Keras callback to calculate acc after each epoch and save file with the weights if the evaluation improves
Method signatures and docstrings:
- def __init__(self, data, file_weights=None, best_F1=0, early_stopping=0, considered_improvemen... | 61103493c55233a80f92f0f52639788b50ef2edd | <|skeleton|>
class TaggingCallback:
"""Keras callback to calculate acc after each epoch and save file with the weights if the evaluation improves"""
def __init__(self, data, file_weights=None, best_F1=0, early_stopping=0, considered_improvement=0.01, label_list=[]):
"""Initialize the keras callback Par... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TaggingCallback:
"""Keras callback to calculate acc after each epoch and save file with the weights if the evaluation improves"""
def __init__(self, data, file_weights=None, best_F1=0, early_stopping=0, considered_improvement=0.01, label_list=[]):
"""Initialize the keras callback Parameters -----... | the_stack_v2_python_sparse | dcase_models/util/callbacks.py | BilalAltundag/DCASE-models | train | 0 |
11d17334b68d15d1355a9c0d9b41b59801b88cf8 | [
"super(CityNavAgent, self).__init__(num_actions, observation_names, goal_type, heading_stop_gradient, heading_num_hiddens, heading_num_bins, xy_stop_gradient, xy_num_hiddens, xy_num_bins_lat, xy_num_bins_lng, target_xy_stop_gradient, dropout, lstm_num_hiddens=locale_lstm_num_hiddens, feed_action_and_reward=feed_act... | <|body_start_0|>
super(CityNavAgent, self).__init__(num_actions, observation_names, goal_type, heading_stop_gradient, heading_num_hiddens, heading_num_bins, xy_stop_gradient, xy_num_hiddens, xy_num_bins_lat, xy_num_bins_lng, target_xy_stop_gradient, dropout, lstm_num_hiddens=locale_lstm_num_hiddens, feed_action... | Core with A2C/A3C-compatible outputs for simple visual observations. | CityNavAgent | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CityNavAgent:
"""Core with A2C/A3C-compatible outputs for simple visual observations."""
def __init__(self, num_actions, observation_names, goal_type='target_latlng', heading_stop_gradient=False, heading_num_hiddens=256, heading_num_bins=16, xy_stop_gradient=True, xy_num_hiddens=256, xy_num_... | stack_v2_sparse_classes_75kplus_train_003652 | 7,297 | permissive | [
{
"docstring": "Initializes an agent core designed to be used with A3C/IMPALA. Supports a single visual observation tensor and goal instruction tensor and outputs a single, scalar discrete action with policy logits and a baseline value, as well as the agent heading, XY position and target XY predictions. Args: ... | 3 | null | Implement the Python class `CityNavAgent` described below.
Class description:
Core with A2C/A3C-compatible outputs for simple visual observations.
Method signatures and docstrings:
- def __init__(self, num_actions, observation_names, goal_type='target_latlng', heading_stop_gradient=False, heading_num_hiddens=256, hea... | Implement the Python class `CityNavAgent` described below.
Class description:
Core with A2C/A3C-compatible outputs for simple visual observations.
Method signatures and docstrings:
- def __init__(self, num_actions, observation_names, goal_type='target_latlng', heading_stop_gradient=False, heading_num_hiddens=256, hea... | dd348cb811064582a77abe855b9ac15799e4a1ef | <|skeleton|>
class CityNavAgent:
"""Core with A2C/A3C-compatible outputs for simple visual observations."""
def __init__(self, num_actions, observation_names, goal_type='target_latlng', heading_stop_gradient=False, heading_num_hiddens=256, heading_num_bins=16, xy_stop_gradient=True, xy_num_hiddens=256, xy_num_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CityNavAgent:
"""Core with A2C/A3C-compatible outputs for simple visual observations."""
def __init__(self, num_actions, observation_names, goal_type='target_latlng', heading_stop_gradient=False, heading_num_hiddens=256, heading_num_bins=16, xy_stop_gradient=True, xy_num_hiddens=256, xy_num_bins_lat=32, ... | the_stack_v2_python_sparse | streetlearn/python/agents/city_nav_agent.py | turningpoint1988/streetlearn | train | 0 |
1c963fdbf942b0fa301b36cd9f617e125eecf6d7 | [
"special_words = ['<PAD>', '<UNK>', '<GO>', '<EOS>']\nword_set = set([character for line in data.split('\\n') for character in line])\nint_to_vocab = {word_i: word for word_i, word in enumerate(special_words + list(word_set))}\nvocab_to_int = {word: word_i for word_i, word in int_to_vocab.items()}\nreturn (int_to_v... | <|body_start_0|>
special_words = ['<PAD>', '<UNK>', '<GO>', '<EOS>']
word_set = set([character for line in data.split('\n') for character in line])
int_to_vocab = {word_i: word for word_i, word in enumerate(special_words + list(word_set))}
vocab_to_int = {word: word_i for word_i, word in... | DataPreprocessor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataPreprocessor:
def extract_character_vocab(self, data):
"""Extract vocabulary from the data and create lookup dictionaries."""
<|body_0|>
def convert_characters_to_ids(self, sentences, letter_to_int, addEOS):
"""Convert characters in sentences to integers."""
... | stack_v2_sparse_classes_75kplus_train_003653 | 32,837 | no_license | [
{
"docstring": "Extract vocabulary from the data and create lookup dictionaries.",
"name": "extract_character_vocab",
"signature": "def extract_character_vocab(self, data)"
},
{
"docstring": "Convert characters in sentences to integers.",
"name": "convert_characters_to_ids",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_016403 | Implement the Python class `DataPreprocessor` described below.
Class description:
Implement the DataPreprocessor class.
Method signatures and docstrings:
- def extract_character_vocab(self, data): Extract vocabulary from the data and create lookup dictionaries.
- def convert_characters_to_ids(self, sentences, letter_... | Implement the Python class `DataPreprocessor` described below.
Class description:
Implement the DataPreprocessor class.
Method signatures and docstrings:
- def extract_character_vocab(self, data): Extract vocabulary from the data and create lookup dictionaries.
- def convert_characters_to_ids(self, sentences, letter_... | 10dc2ae19f259a4683a729deb3a18e86c9177d90 | <|skeleton|>
class DataPreprocessor:
def extract_character_vocab(self, data):
"""Extract vocabulary from the data and create lookup dictionaries."""
<|body_0|>
def convert_characters_to_ids(self, sentences, letter_to_int, addEOS):
"""Convert characters in sentences to integers."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataPreprocessor:
def extract_character_vocab(self, data):
"""Extract vocabulary from the data and create lookup dictionaries."""
special_words = ['<PAD>', '<UNK>', '<GO>', '<EOS>']
word_set = set([character for line in data.split('\n') for character in line])
int_to_vocab = {w... | the_stack_v2_python_sparse | programs/part-04-recurrent-neural-networks/lesson-10-sequence-to-sequence/seq2seq-rnn-refactored.py | aifoss/udacity-deep-learning-nanodegree | train | 0 | |
4e25a1ee4bf90e43e20c1dc9f47cbbc79efa16a7 | [
"forms = [row.doc for row in self.db.view('form', 'enabled', include_docs=True)]\nfor form in forms:\n if form.get('ordinal') is None:\n form['ordinal'] = 0\nforms.sort(key=lambda i: i['ordinal'])\nif not self.current_user:\n self.render('home/anonymous.html', forms=forms)\nelif self.current_user['role... | <|body_start_0|>
forms = [row.doc for row in self.db.view('form', 'enabled', include_docs=True)]
for form in forms:
if form.get('ordinal') is None:
form['ordinal'] = 0
forms.sort(key=lambda i: i['ordinal'])
if not self.current_user:
self.render('ho... | Home page; dashboard. Contents according to role of logged-in account. | Home | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Home:
"""Home page; dashboard. Contents according to role of logged-in account."""
def get(self):
"""Home page; contents depends on the role of the logged-in account, if any."""
<|body_0|>
def home_admin(self, **kwargs):
"""Home page for a current user having rol... | stack_v2_sparse_classes_75kplus_train_003654 | 7,366 | permissive | [
{
"docstring": "Home page; contents depends on the role of the logged-in account, if any.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Home page for a current user having role 'admin'.",
"name": "home_admin",
"signature": "def home_admin(self, **kwargs)"
},
{
... | 4 | stack_v2_sparse_classes_30k_test_003024 | Implement the Python class `Home` described below.
Class description:
Home page; dashboard. Contents according to role of logged-in account.
Method signatures and docstrings:
- def get(self): Home page; contents depends on the role of the logged-in account, if any.
- def home_admin(self, **kwargs): Home page for a cu... | Implement the Python class `Home` described below.
Class description:
Home page; dashboard. Contents according to role of logged-in account.
Method signatures and docstrings:
- def get(self): Home page; contents depends on the role of the logged-in account, if any.
- def home_admin(self, **kwargs): Home page for a cu... | ac02295cd33f4be562152c7b0ae3ab7cb11735d9 | <|skeleton|>
class Home:
"""Home page; dashboard. Contents according to role of logged-in account."""
def get(self):
"""Home page; contents depends on the role of the logged-in account, if any."""
<|body_0|>
def home_admin(self, **kwargs):
"""Home page for a current user having rol... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Home:
"""Home page; dashboard. Contents according to role of logged-in account."""
def get(self):
"""Home page; contents depends on the role of the logged-in account, if any."""
forms = [row.doc for row in self.db.view('form', 'enabled', include_docs=True)]
for form in forms:
... | the_stack_v2_python_sparse | orderportal/home.py | pekrau/OrderPortal | train | 7 |
ecc92716dfd0d6e6a7f65199741a6378aa6c24a9 | [
"losses = []\nfor obs in batch_handler.val_data:\n gen = self._tf_generate(obs.low_res)\n loss, _ = self.calc_loss(obs.high_res, gen, weight_gen_advers=weight_gen_advers, train_gen=True, train_disc=True)\n losses.append(float(loss))\nreturn losses",
"losses = []\nfor obs in batch_handler.val_data:\n g... | <|body_start_0|>
losses = []
for obs in batch_handler.val_data:
gen = self._tf_generate(obs.low_res)
loss, _ = self.calc_loss(obs.high_res, gen, weight_gen_advers=weight_gen_advers, train_gen=True, train_disc=True)
losses.append(float(loss))
return losses
<|en... | Data-centric model using loss across time bins to select training observations | Sup3rGanDC | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sup3rGanDC:
"""Data-centric model using loss across time bins to select training observations"""
def calc_val_loss_gen(self, batch_handler, weight_gen_advers):
"""Calculate the validation total loss across the validation samples. e.g. If the sample domain has 100 steps and the valida... | stack_v2_sparse_classes_75kplus_train_003655 | 11,269 | permissive | [
{
"docstring": "Calculate the validation total loss across the validation samples. e.g. If the sample domain has 100 steps and the validation set has 10 bins then this will get a list of losses across step 0 to 10, 10 to 20, etc. Use this to determine performance within bins and to update how observations are s... | 4 | stack_v2_sparse_classes_30k_train_026694 | Implement the Python class `Sup3rGanDC` described below.
Class description:
Data-centric model using loss across time bins to select training observations
Method signatures and docstrings:
- def calc_val_loss_gen(self, batch_handler, weight_gen_advers): Calculate the validation total loss across the validation sample... | Implement the Python class `Sup3rGanDC` described below.
Class description:
Data-centric model using loss across time bins to select training observations
Method signatures and docstrings:
- def calc_val_loss_gen(self, batch_handler, weight_gen_advers): Calculate the validation total loss across the validation sample... | f3803a823c7bb0afd7ab6064625908dca0be3476 | <|skeleton|>
class Sup3rGanDC:
"""Data-centric model using loss across time bins to select training observations"""
def calc_val_loss_gen(self, batch_handler, weight_gen_advers):
"""Calculate the validation total loss across the validation samples. e.g. If the sample domain has 100 steps and the valida... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Sup3rGanDC:
"""Data-centric model using loss across time bins to select training observations"""
def calc_val_loss_gen(self, batch_handler, weight_gen_advers):
"""Calculate the validation total loss across the validation samples. e.g. If the sample domain has 100 steps and the validation set has ... | the_stack_v2_python_sparse | sup3r/models/data_centric.py | NREL/sup3r | train | 20 |
a9282d408fca6b429600c738032dd00dd498ceed | [
"if root is None:\n return None\nroot.left = self.pruneTree(root.left)\nroot.right = self.pruneTree(root.right)\nif root.left is None and root.right is None and (root.val == 0):\n return None\nreturn root",
"if not root:\n return None\nroot.left = self.pruneTree(root.left)\nroot.right = self.pruneTree(ro... | <|body_start_0|>
if root is None:
return None
root.left = self.pruneTree(root.left)
root.right = self.pruneTree(root.right)
if root.left is None and root.right is None and (root.val == 0):
return None
return root
<|end_body_0|>
<|body_start_1|>
if... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def pruneTree(self, root: TreeNode) -> TreeNode:
"""09/19/2020 17:58"""
<|body_0|>
def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
"""08/20/2021 04:36"""
<|body_1|>
def pruneTree(self, root: Optional[TreeNode]) -> Optional[... | stack_v2_sparse_classes_75kplus_train_003656 | 2,592 | no_license | [
{
"docstring": "09/19/2020 17:58",
"name": "pruneTree",
"signature": "def pruneTree(self, root: TreeNode) -> TreeNode"
},
{
"docstring": "08/20/2021 04:36",
"name": "pruneTree",
"signature": "def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]"
},
{
"docstring": "... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pruneTree(self, root: TreeNode) -> TreeNode: 09/19/2020 17:58
- def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: 08/20/2021 04:36
- def pruneTree(self, ro... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pruneTree(self, root: TreeNode) -> TreeNode: 09/19/2020 17:58
- def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: 08/20/2021 04:36
- def pruneTree(self, ro... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def pruneTree(self, root: TreeNode) -> TreeNode:
"""09/19/2020 17:58"""
<|body_0|>
def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
"""08/20/2021 04:36"""
<|body_1|>
def pruneTree(self, root: Optional[TreeNode]) -> Optional[... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def pruneTree(self, root: TreeNode) -> TreeNode:
"""09/19/2020 17:58"""
if root is None:
return None
root.left = self.pruneTree(root.left)
root.right = self.pruneTree(root.right)
if root.left is None and root.right is None and (root.val == 0):
... | the_stack_v2_python_sparse | leetcode/solved/832_Binary_Tree_Pruning/solution.py | sungminoh/algorithms | train | 0 | |
fec9cb5ca579b887938c1288af05664db07ba9bd | [
"self.s = compressedString\nself.p = 0\nself.num = 0\nself.ch = ''",
"if not self.hasNext():\n return ' '\nif self.num == 0:\n self.ch = self.s[self.p]\n self.p += 1\n while self.p < len(self.s) and (not self.s[self.p].isalpha()):\n self.num = self.num * 10 + int(self.s[self.p])\n self.p... | <|body_start_0|>
self.s = compressedString
self.p = 0
self.num = 0
self.ch = ''
<|end_body_0|>
<|body_start_1|>
if not self.hasNext():
return ' '
if self.num == 0:
self.ch = self.s[self.p]
self.p += 1
while self.p < len(sel... | StringIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StringIterator:
def __init__(self, compressedString):
""":type compressedString: str"""
<|body_0|>
def next(self):
""":rtype: str"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
s... | stack_v2_sparse_classes_75kplus_train_003657 | 1,101 | no_license | [
{
"docstring": ":type compressedString: str",
"name": "__init__",
"signature": "def __init__(self, compressedString)"
},
{
"docstring": ":rtype: str",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"name": "hasNext",
"signature": "def hasN... | 3 | stack_v2_sparse_classes_30k_train_017442 | Implement the Python class `StringIterator` described below.
Class description:
Implement the StringIterator class.
Method signatures and docstrings:
- def __init__(self, compressedString): :type compressedString: str
- def next(self): :rtype: str
- def hasNext(self): :rtype: bool | Implement the Python class `StringIterator` described below.
Class description:
Implement the StringIterator class.
Method signatures and docstrings:
- def __init__(self, compressedString): :type compressedString: str
- def next(self): :rtype: str
- def hasNext(self): :rtype: bool
<|skeleton|>
class StringIterator:
... | 36cb33af758b1d01da35982481a8bbfbee5c2810 | <|skeleton|>
class StringIterator:
def __init__(self, compressedString):
""":type compressedString: str"""
<|body_0|>
def next(self):
""":rtype: str"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StringIterator:
def __init__(self, compressedString):
""":type compressedString: str"""
self.s = compressedString
self.p = 0
self.num = 0
self.ch = ''
def next(self):
""":rtype: str"""
if not self.hasNext():
return ' '
if self.nu... | the_stack_v2_python_sparse | LeetCode/designCompressedStringIterator.py | dicao425/algorithmExercise | train | 0 | |
07f59c07f2a89b86c3966e17075e0c212abc8e76 | [
"self._model = TOAHModel(number_of_stools)\nself._stools = number_of_stools\nself._cheese = number_of_cheeses\nself._model.fill_first_stool(number_of_cheeses)",
"print(\"This is a Tower of Anne Hoy Game\\n The rules are the same as the Tower of Hanoi, you have to move the cheeses to the last stool.\\n Remember th... | <|body_start_0|>
self._model = TOAHModel(number_of_stools)
self._stools = number_of_stools
self._cheese = number_of_cheeses
self._model.fill_first_stool(number_of_cheeses)
<|end_body_0|>
<|body_start_1|>
print("This is a Tower of Anne Hoy Game\n The rules are the same as the Tow... | Controller for text console. | ConsoleController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConsoleController:
"""Controller for text console."""
def __init__(self, number_of_cheeses, number_of_stools):
"""Initialize a new ConsoleController self. @param ConsoleController self: this ConsoleController object @param int number_of_cheeses: the number of cheese to start with @pa... | stack_v2_sparse_classes_75kplus_train_003658 | 4,812 | no_license | [
{
"docstring": "Initialize a new ConsoleController self. @param ConsoleController self: this ConsoleController object @param int number_of_cheeses: the number of cheese to start with @param int number_of_stools: the number of stools to play with @rtype: None",
"name": "__init__",
"signature": "def __ini... | 2 | null | Implement the Python class `ConsoleController` described below.
Class description:
Controller for text console.
Method signatures and docstrings:
- def __init__(self, number_of_cheeses, number_of_stools): Initialize a new ConsoleController self. @param ConsoleController self: this ConsoleController object @param int ... | Implement the Python class `ConsoleController` described below.
Class description:
Controller for text console.
Method signatures and docstrings:
- def __init__(self, number_of_cheeses, number_of_stools): Initialize a new ConsoleController self. @param ConsoleController self: this ConsoleController object @param int ... | 107ee44025f76e51ed510747aa4fed57e908df2d | <|skeleton|>
class ConsoleController:
"""Controller for text console."""
def __init__(self, number_of_cheeses, number_of_stools):
"""Initialize a new ConsoleController self. @param ConsoleController self: this ConsoleController object @param int number_of_cheeses: the number of cheese to start with @pa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConsoleController:
"""Controller for text console."""
def __init__(self, number_of_cheeses, number_of_stools):
"""Initialize a new ConsoleController self. @param ConsoleController self: this ConsoleController object @param int number_of_cheeses: the number of cheese to start with @param int numbe... | the_stack_v2_python_sparse | CSC148/a1/console_controller.py | Anorth1997/School-Projects | train | 1 |
7cd54903fb97780668dcefaaabb949973d56f6bd | [
"if not kwargs.get('obj_id'):\n rights_write = request.GET.get('rights_write')\n environment = request.GET.get('environment')\n ipv4 = request.GET.get('ipv4')\n ipv6 = request.GET.get('ipv6')\n is_router = request.GET.get('is_router')\n environment_sdn_controller = request.GET.get('environment_sdn... | <|body_start_0|>
if not kwargs.get('obj_id'):
rights_write = request.GET.get('rights_write')
environment = request.GET.get('environment')
ipv4 = request.GET.get('ipv4')
ipv6 = request.GET.get('ipv6')
is_router = request.GET.get('is_router')
... | EquipmentView | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EquipmentView:
def get(self, request, *args, **kwargs):
"""Return list of equipments :param rights_write(optional): Right of Write - Filter by rights of write :param environment(optional): Id of environment - Filter by environment :param ipv4(optional): Id of ipv4 - Filter by id ipv4 :pa... | stack_v2_sparse_classes_75kplus_train_003659 | 5,669 | permissive | [
{
"docstring": "Return list of equipments :param rights_write(optional): Right of Write - Filter by rights of write :param environment(optional): Id of environment - Filter by environment :param ipv4(optional): Id of ipv4 - Filter by id ipv4 :param ipv6(optional): Id of ipv6 - Filter by id ipv6 :param is_router... | 4 | stack_v2_sparse_classes_30k_train_042509 | Implement the Python class `EquipmentView` described below.
Class description:
Implement the EquipmentView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Return list of equipments :param rights_write(optional): Right of Write - Filter by rights of write :param environment(optional... | Implement the Python class `EquipmentView` described below.
Class description:
Implement the EquipmentView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Return list of equipments :param rights_write(optional): Right of Write - Filter by rights of write :param environment(optional... | eb27e1d977a1c4bb1fee8fb51b8d8050c64696d9 | <|skeleton|>
class EquipmentView:
def get(self, request, *args, **kwargs):
"""Return list of equipments :param rights_write(optional): Right of Write - Filter by rights of write :param environment(optional): Id of environment - Filter by environment :param ipv4(optional): Id of ipv4 - Filter by id ipv4 :pa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EquipmentView:
def get(self, request, *args, **kwargs):
"""Return list of equipments :param rights_write(optional): Right of Write - Filter by rights of write :param environment(optional): Id of environment - Filter by environment :param ipv4(optional): Id of ipv4 - Filter by id ipv4 :param ipv6(optio... | the_stack_v2_python_sparse | networkapi/api_equipment/views/v3.py | globocom/GloboNetworkAPI | train | 86 | |
7dca867313791dc6442cf03ebabfed3d2a7b9091 | [
"try:\n payload = {'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=int(60)), 'iat': datetime.datetime.utcnow(), 'sub': user_id}\n return jwt.encode(payload, os.getenv('JWT_SECRET_KEY'), 'HS256').decode('utf-8')\nexcept Exception as e:\n return Response(mimetype='application/json', response=j... | <|body_start_0|>
try:
payload = {'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=int(60)), 'iat': datetime.datetime.utcnow(), 'sub': user_id}
return jwt.encode(payload, os.getenv('JWT_SECRET_KEY'), 'HS256').decode('utf-8')
except Exception as e:
return ... | Auth Class | Auth | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Auth:
"""Auth Class"""
def generate_token(user_id):
"""Generate Token Method"""
<|body_0|>
def decode_token(token):
"""Decode token method método estático para decodificar o token do usuário fornecido usando o mesmo JWT_SECRET_KEY que usamos ao assinar o token ve... | stack_v2_sparse_classes_75kplus_train_003660 | 3,413 | permissive | [
{
"docstring": "Generate Token Method",
"name": "generate_token",
"signature": "def generate_token(user_id)"
},
{
"docstring": "Decode token method método estático para decodificar o token do usuário fornecido usando o mesmo JWT_SECRET_KEY que usamos ao assinar o token verifica e valida o token"... | 3 | null | Implement the Python class `Auth` described below.
Class description:
Auth Class
Method signatures and docstrings:
- def generate_token(user_id): Generate Token Method
- def decode_token(token): Decode token method método estático para decodificar o token do usuário fornecido usando o mesmo JWT_SECRET_KEY que usamos ... | Implement the Python class `Auth` described below.
Class description:
Auth Class
Method signatures and docstrings:
- def generate_token(user_id): Generate Token Method
- def decode_token(token): Decode token method método estático para decodificar o token do usuário fornecido usando o mesmo JWT_SECRET_KEY que usamos ... | 46f902fcd9a8d75c79115b874f8e04f82d901fc3 | <|skeleton|>
class Auth:
"""Auth Class"""
def generate_token(user_id):
"""Generate Token Method"""
<|body_0|>
def decode_token(token):
"""Decode token method método estático para decodificar o token do usuário fornecido usando o mesmo JWT_SECRET_KEY que usamos ao assinar o token ve... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Auth:
"""Auth Class"""
def generate_token(user_id):
"""Generate Token Method"""
try:
payload = {'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=int(60)), 'iat': datetime.datetime.utcnow(), 'sub': user_id}
return jwt.encode(payload, os.getenv('JWT_SEC... | the_stack_v2_python_sparse | src/shared/Authentication.py | RodrigoSantosRodrigues/Api-Autocomplete | train | 0 |
7a463cb3e435fae4040d8942676e6ee5a05afba8 | [
"super(KFoldSplitter, self).__init__(**kwargs)\nself.index_splitter = IndexSplitter(**kwargs)\nself.loo_pool = not no_loo_pool\nself.num_folds = num_folds",
"data_indices = np.arange(len(data))\nnp.random.shuffle(data_indices)\nnum_folds = min(self.num_folds, len(data_indices))\nfolds = np.array_split(data_indice... | <|body_start_0|>
super(KFoldSplitter, self).__init__(**kwargs)
self.index_splitter = IndexSplitter(**kwargs)
self.loo_pool = not no_loo_pool
self.num_folds = num_folds
<|end_body_0|>
<|body_start_1|>
data_indices = np.arange(len(data))
np.random.shuffle(data_indices)
... | Return k fold splits | KFoldSplitter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KFoldSplitter:
"""Return k fold splits"""
def __init__(self, no_loo_pool: bool=False, num_folds: int=3, **kwargs):
"""__init__. Args: no_loo_pool (bool): If true, pool all items together. Treat them as separate metrics. num_folds (int): Number of k folds to use kwargs:"""
<|b... | stack_v2_sparse_classes_75kplus_train_003661 | 23,923 | no_license | [
{
"docstring": "__init__. Args: no_loo_pool (bool): If true, pool all items together. Treat them as separate metrics. num_folds (int): Number of k folds to use kwargs:",
"name": "__init__",
"signature": "def __init__(self, no_loo_pool: bool=False, num_folds: int=3, **kwargs)"
},
{
"docstring": "... | 2 | stack_v2_sparse_classes_30k_train_039839 | Implement the Python class `KFoldSplitter` described below.
Class description:
Return k fold splits
Method signatures and docstrings:
- def __init__(self, no_loo_pool: bool=False, num_folds: int=3, **kwargs): __init__. Args: no_loo_pool (bool): If true, pool all items together. Treat them as separate metrics. num_fol... | Implement the Python class `KFoldSplitter` described below.
Class description:
Return k fold splits
Method signatures and docstrings:
- def __init__(self, no_loo_pool: bool=False, num_folds: int=3, **kwargs): __init__. Args: no_loo_pool (bool): If true, pool all items together. Treat them as separate metrics. num_fol... | 84c9026c78bec9a2267960a87080b71beba5c305 | <|skeleton|>
class KFoldSplitter:
"""Return k fold splits"""
def __init__(self, no_loo_pool: bool=False, num_folds: int=3, **kwargs):
"""__init__. Args: no_loo_pool (bool): If true, pool all items together. Treat them as separate metrics. num_folds (int): Number of k folds to use kwargs:"""
<|b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KFoldSplitter:
"""Return k fold splits"""
def __init__(self, no_loo_pool: bool=False, num_folds: int=3, **kwargs):
"""__init__. Args: no_loo_pool (bool): If true, pool all items together. Treat them as separate metrics. num_folds (int): Number of k folds to use kwargs:"""
super(KFoldSplit... | the_stack_v2_python_sparse | enzpred/dataset/splitter.py | liudongliangHI/enz-pred | train | 0 |
997d7f586ede3e0354754218eab15385a35ea74d | [
"super().__init__()\nself._model = model\nself._dev_x = x\nself._dev_y = y\nself._valid_steps = once_every\nself._batch_size = batch_size\nself._model_save_path = model_save_path\nself._verbose = verbose",
"if (epoch + 1) % self._valid_steps == 0:\n val_logs = self._model.evaluate(self._dev_x, self._dev_y, sel... | <|body_start_0|>
super().__init__()
self._model = model
self._dev_x = x
self._dev_y = y
self._valid_steps = once_every
self._batch_size = batch_size
self._model_save_path = model_save_path
self._verbose = verbose
<|end_body_0|>
<|body_start_1|>
if... | Callback to evaluate all metrics. MatchZoo metrics can not be evaluated batch-wise since they require dataset-level information. As a result, MatchZoo metrics are not evaluated automatically when a Model `fit`. When this callback is used, all metrics, including MatchZoo metrics and Keras metrics, are evluated once ever... | EvaluateAllMetrics | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EvaluateAllMetrics:
"""Callback to evaluate all metrics. MatchZoo metrics can not be evaluated batch-wise since they require dataset-level information. As a result, MatchZoo metrics are not evaluated automatically when a Model `fit`. When this callback is used, all metrics, including MatchZoo met... | stack_v2_sparse_classes_75kplus_train_003662 | 2,513 | permissive | [
{
"docstring": "Initializer.",
"name": "__init__",
"signature": "def __init__(self, model: 'BaseModel', x: typing.Union[np.ndarray, typing.List[np.ndarray]], y: np.ndarray, once_every: int=1, batch_size: int=128, model_save_path: str=None, verbose=1)"
},
{
"docstring": "Called at the end of en e... | 2 | stack_v2_sparse_classes_30k_train_000359 | Implement the Python class `EvaluateAllMetrics` described below.
Class description:
Callback to evaluate all metrics. MatchZoo metrics can not be evaluated batch-wise since they require dataset-level information. As a result, MatchZoo metrics are not evaluated automatically when a Model `fit`. When this callback is us... | Implement the Python class `EvaluateAllMetrics` described below.
Class description:
Callback to evaluate all metrics. MatchZoo metrics can not be evaluated batch-wise since they require dataset-level information. As a result, MatchZoo metrics are not evaluated automatically when a Model `fit`. When this callback is us... | db101beed691a0e399f9b0b19fb59c7dc8b16760 | <|skeleton|>
class EvaluateAllMetrics:
"""Callback to evaluate all metrics. MatchZoo metrics can not be evaluated batch-wise since they require dataset-level information. As a result, MatchZoo metrics are not evaluated automatically when a Model `fit`. When this callback is used, all metrics, including MatchZoo met... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EvaluateAllMetrics:
"""Callback to evaluate all metrics. MatchZoo metrics can not be evaluated batch-wise since they require dataset-level information. As a result, MatchZoo metrics are not evaluated automatically when a Model `fit`. When this callback is used, all metrics, including MatchZoo metrics and Kera... | the_stack_v2_python_sparse | matchzoo/engine/callbacks.py | nguyenvo09/LearningFromFactCheckers | train | 11 |
fe0ad291402decb172a5c19141c559eb37f284e2 | [
"self.validate_parameters(customer_id=customer_id, asset_id=asset_id)\n_url_path = '//aggregation/v1/customers/{customerId}/assets/{assetId}'\n_url_path = APIHelper.append_url_with_template_parameters(_url_path, {'customerId': customer_id, 'assetId': asset_id})\n_query_builder = Configuration.get_base_uri()\n_query... | <|body_start_0|>
self.validate_parameters(customer_id=customer_id, asset_id=asset_id)
_url_path = '//aggregation/v1/customers/{customerId}/assets/{assetId}'
_url_path = APIHelper.append_url_with_template_parameters(_url_path, {'customerId': customer_id, 'assetId': asset_id})
_query_build... | A Controller to access Endpoints in the finicityapi API. | APIController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class APIController:
"""A Controller to access Endpoints in the finicityapi API."""
def get_asset_by_customer_id(self, customer_id, asset_id):
"""Does a GET request to //aggregation/v1/customers/{customerId}/assets/{assetId}. Retrieve a binary file with the given assetId. The returned cont... | stack_v2_sparse_classes_75kplus_train_003663 | 6,379 | permissive | [
{
"docstring": "Does a GET request to //aggregation/v1/customers/{customerId}/assets/{assetId}. Retrieve a binary file with the given assetId. The returned content type is always application/octet-stream. If the service successfully retrieves the asset, HTTP 200 (OK) will be returned. If the asset doesn’t exist... | 2 | null | Implement the Python class `APIController` described below.
Class description:
A Controller to access Endpoints in the finicityapi API.
Method signatures and docstrings:
- def get_asset_by_customer_id(self, customer_id, asset_id): Does a GET request to //aggregation/v1/customers/{customerId}/assets/{assetId}. Retriev... | Implement the Python class `APIController` described below.
Class description:
A Controller to access Endpoints in the finicityapi API.
Method signatures and docstrings:
- def get_asset_by_customer_id(self, customer_id, asset_id): Does a GET request to //aggregation/v1/customers/{customerId}/assets/{assetId}. Retriev... | b2ab1ded435db75c78d42261f5e4acd2a3061487 | <|skeleton|>
class APIController:
"""A Controller to access Endpoints in the finicityapi API."""
def get_asset_by_customer_id(self, customer_id, asset_id):
"""Does a GET request to //aggregation/v1/customers/{customerId}/assets/{assetId}. Retrieve a binary file with the given assetId. The returned cont... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class APIController:
"""A Controller to access Endpoints in the finicityapi API."""
def get_asset_by_customer_id(self, customer_id, asset_id):
"""Does a GET request to //aggregation/v1/customers/{customerId}/assets/{assetId}. Retrieve a binary file with the given assetId. The returned content type is a... | the_stack_v2_python_sparse | finicityapi/controllers/api_controller.py | monarchmoney/finicity-python | train | 0 |
7b3943700dd932d3aeb67973c6b8cc31641f5ffb | [
"struct = mojom.Struct('test')\nindex = 1\nfor kind in kinds:\n struct.AddField('%d' % index, kind)\n index += 1\nps = pack.PackedStruct(struct)\nnum_fields = len(ps.packed_fields)\nself.assertEquals(len(kinds), num_fields)\nfor i in xrange(num_fields):\n self.assertEquals('%d' % fields[i], ps.packed_field... | <|body_start_0|>
struct = mojom.Struct('test')
index = 1
for kind in kinds:
struct.AddField('%d' % index, kind)
index += 1
ps = pack.PackedStruct(struct)
num_fields = len(ps.packed_fields)
self.assertEquals(len(kinds), num_fields)
for i in ... | PackTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PackTest:
def _CheckPackSequence(self, kinds, fields, offsets):
"""Checks the pack order and offsets of a sequence of mojom.Kinds. Args: kinds: A sequence of mojom.Kinds that specify the fields that are to be created. fields: The expected order of the resulting fields, with the integer "... | stack_v2_sparse_classes_75kplus_train_003664 | 4,828 | permissive | [
{
"docstring": "Checks the pack order and offsets of a sequence of mojom.Kinds. Args: kinds: A sequence of mojom.Kinds that specify the fields that are to be created. fields: The expected order of the resulting fields, with the integer \"1\" first. offsets: The expected order of offsets, with the integer \"0\" ... | 6 | stack_v2_sparse_classes_30k_train_025851 | Implement the Python class `PackTest` described below.
Class description:
Implement the PackTest class.
Method signatures and docstrings:
- def _CheckPackSequence(self, kinds, fields, offsets): Checks the pack order and offsets of a sequence of mojom.Kinds. Args: kinds: A sequence of mojom.Kinds that specify the fiel... | Implement the Python class `PackTest` described below.
Class description:
Implement the PackTest class.
Method signatures and docstrings:
- def _CheckPackSequence(self, kinds, fields, offsets): Checks the pack order and offsets of a sequence of mojom.Kinds. Args: kinds: A sequence of mojom.Kinds that specify the fiel... | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | <|skeleton|>
class PackTest:
def _CheckPackSequence(self, kinds, fields, offsets):
"""Checks the pack order and offsets of a sequence of mojom.Kinds. Args: kinds: A sequence of mojom.Kinds that specify the fields that are to be created. fields: The expected order of the resulting fields, with the integer "... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PackTest:
def _CheckPackSequence(self, kinds, fields, offsets):
"""Checks the pack order and offsets of a sequence of mojom.Kinds. Args: kinds: A sequence of mojom.Kinds that specify the fields that are to be created. fields: The expected order of the resulting fields, with the integer "1" first. offs... | the_stack_v2_python_sparse | mojo/public/tools/bindings/pylib/mojom_tests/generate/pack_unittest.py | Samsung/Castanets | train | 58 | |
7a25202ae1238fb270e3c5eb016c4b32baa5e66a | [
"self.event = event\nself.user_id = None\nself.img_name = None\nself.img_desc = None\nself.img_b64_str = None\nself.img_bytes = None\ninvocation_id = event.get('invocation_id')\nsuper(Validation, self).__init__(prefix='VL', phase_name='Validation', invocation_id=invocation_id)",
"if not self.__extract_info_from_b... | <|body_start_0|>
self.event = event
self.user_id = None
self.img_name = None
self.img_desc = None
self.img_b64_str = None
self.img_bytes = None
invocation_id = event.get('invocation_id')
super(Validation, self).__init__(prefix='VL', phase_name='Validation'... | Validation object class, responsible for validating, decoding and exposing data retrieved from the client's sent request object (event dictionary). | Validation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Validation:
"""Validation object class, responsible for validating, decoding and exposing data retrieved from the client's sent request object (event dictionary)."""
def __init__(self, event: dict):
"""Constructor of the Validation object, stores client provided and decoded data. :pa... | stack_v2_sparse_classes_75kplus_train_003665 | 3,812 | no_license | [
{
"docstring": "Constructor of the Validation object, stores client provided and decoded data. :param event: AWS event dictionary.",
"name": "__init__",
"signature": "def __init__(self, event: dict)"
},
{
"docstring": "Object's main procedure: extract and decode information from event object. :r... | 4 | stack_v2_sparse_classes_30k_train_038976 | Implement the Python class `Validation` described below.
Class description:
Validation object class, responsible for validating, decoding and exposing data retrieved from the client's sent request object (event dictionary).
Method signatures and docstrings:
- def __init__(self, event: dict): Constructor of the Valida... | Implement the Python class `Validation` described below.
Class description:
Validation object class, responsible for validating, decoding and exposing data retrieved from the client's sent request object (event dictionary).
Method signatures and docstrings:
- def __init__(self, event: dict): Constructor of the Valida... | 8f1b94518303c4e0a38df1ff6caa0e7326451d67 | <|skeleton|>
class Validation:
"""Validation object class, responsible for validating, decoding and exposing data retrieved from the client's sent request object (event dictionary)."""
def __init__(self, event: dict):
"""Constructor of the Validation object, stores client provided and decoded data. :pa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Validation:
"""Validation object class, responsible for validating, decoding and exposing data retrieved from the client's sent request object (event dictionary)."""
def __init__(self, event: dict):
"""Constructor of the Validation object, stores client provided and decoded data. :param event: AW... | the_stack_v2_python_sparse | Serverless/handlers/http_add_picture/validation.py | RogerVFbr/MyCelebs | train | 0 |
6ab4908d6555ff73bd7e026ed845a758f482b8bd | [
"self._start_time = start_time\nself._end_time = end_time\nself._runtimes = pd.date_range(start=self._start_time, end=self._end_time, freq='D', tz='UTC')\nself._steps = 0\nif test_data is not None:\n self._test_data = test_data\nelse:\n logging.error('No test data provided.')",
"load = self._test_data['load... | <|body_start_0|>
self._start_time = start_time
self._end_time = end_time
self._runtimes = pd.date_range(start=self._start_time, end=self._end_time, freq='D', tz='UTC')
self._steps = 0
if test_data is not None:
self._test_data = test_data
else:
logg... | TestDataGenerator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDataGenerator:
def __init__(self, start_time='2018-08-20 08:00:00', end_time='2019-02-10 08:00:00', test_data=None):
"""Initializer :param start_time: Earliest time to generate test data :param end_time: Latest time to generate test daya :param test_data: A dictionary with keys ['loa... | stack_v2_sparse_classes_75kplus_train_003666 | 2,347 | no_license | [
{
"docstring": "Initializer :param start_time: Earliest time to generate test data :param end_time: Latest time to generate test daya :param test_data: A dictionary with keys ['load', 'gfs', 'nam'] and corresponding datatsets as dataframes",
"name": "__init__",
"signature": "def __init__(self, start_tim... | 3 | stack_v2_sparse_classes_30k_val_001561 | Implement the Python class `TestDataGenerator` described below.
Class description:
Implement the TestDataGenerator class.
Method signatures and docstrings:
- def __init__(self, start_time='2018-08-20 08:00:00', end_time='2019-02-10 08:00:00', test_data=None): Initializer :param start_time: Earliest time to generate t... | Implement the Python class `TestDataGenerator` described below.
Class description:
Implement the TestDataGenerator class.
Method signatures and docstrings:
- def __init__(self, start_time='2018-08-20 08:00:00', end_time='2019-02-10 08:00:00', test_data=None): Initializer :param start_time: Earliest time to generate t... | 7ddb2b6191251baaa0847b0c69425771bcded416 | <|skeleton|>
class TestDataGenerator:
def __init__(self, start_time='2018-08-20 08:00:00', end_time='2019-02-10 08:00:00', test_data=None):
"""Initializer :param start_time: Earliest time to generate test data :param end_time: Latest time to generate test daya :param test_data: A dictionary with keys ['loa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestDataGenerator:
def __init__(self, start_time='2018-08-20 08:00:00', end_time='2019-02-10 08:00:00', test_data=None):
"""Initializer :param start_time: Earliest time to generate test data :param end_time: Latest time to generate test daya :param test_data: A dictionary with keys ['load', 'gfs', 'na... | the_stack_v2_python_sparse | sample/build/lib/test_harness/test_data_generator.py | GabrielKS/CMU_Load_Forecasting | train | 0 | |
200a0984bfc9a30ae07e21bea146e50118a1eb78 | [
"context = super(LoggerList, self).get_context_data(project_id, *args, **kwargs)\nlogs = LoggerHistory.objects.filter(project__contains={'id': str(project_id)})\ncontext['logs'] = self.paginate_logs(logs[::-1], self.request.GET.get('page'))\nreturn context",
"paginator = Paginator(logs, 20)\ntry:\n logs = pagi... | <|body_start_0|>
context = super(LoggerList, self).get_context_data(project_id, *args, **kwargs)
logs = LoggerHistory.objects.filter(project__contains={'id': str(project_id)})
context['logs'] = self.paginate_logs(logs[::-1], self.request.GET.get('page'))
return context
<|end_body_0|>
<|... | A list of all history logs. | LoggerList | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoggerList:
"""A list of all history logs."""
def get_context_data(self, project_id, *args, **kwargs):
"""Return the context to render the view. Parameters ---------- project_id : int Identifies the project in the database. Returns ------- dict Context."""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus_train_003667 | 2,669 | permissive | [
{
"docstring": "Return the context to render the view. Parameters ---------- project_id : int Identifies the project in the database. Returns ------- dict Context.",
"name": "get_context_data",
"signature": "def get_context_data(self, project_id, *args, **kwargs)"
},
{
"docstring": "Paginate all... | 2 | null | Implement the Python class `LoggerList` described below.
Class description:
A list of all history logs.
Method signatures and docstrings:
- def get_context_data(self, project_id, *args, **kwargs): Return the context to render the view. Parameters ---------- project_id : int Identifies the project in the database. Ret... | Implement the Python class `LoggerList` described below.
Class description:
A list of all history logs.
Method signatures and docstrings:
- def get_context_data(self, project_id, *args, **kwargs): Return the context to render the view. Parameters ---------- project_id : int Identifies the project in the database. Ret... | 16d31b5207de9f699fc01054baad1fe65ad1c3ca | <|skeleton|>
class LoggerList:
"""A list of all history logs."""
def get_context_data(self, project_id, *args, **kwargs):
"""Return the context to render the view. Parameters ---------- project_id : int Identifies the project in the database. Returns ------- dict Context."""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LoggerList:
"""A list of all history logs."""
def get_context_data(self, project_id, *args, **kwargs):
"""Return the context to render the view. Parameters ---------- project_id : int Identifies the project in the database. Returns ------- dict Context."""
context = super(LoggerList, self... | the_stack_v2_python_sparse | geokey/core/views.py | NeolithEra/geokey | train | 0 |
9b8820eec4dbf8634650d9bed86640a09eddf1cc | [
"if word not in before.wv.vocab or word not in after.wv.vocab:\n return 0\nvec1 = before.wv[word] / np.linalg.norm(before.wv[word])\nvec2 = after.wv[word] / np.linalg.norm(after.wv[word])\nsim = vec1.dot(vec2)\nreturn 1 - sim",
"if word not in before.wv.vocab or word not in after.wv.vocab:\n return 0\nnn1 =... | <|body_start_0|>
if word not in before.wv.vocab or word not in after.wv.vocab:
return 0
vec1 = before.wv[word] / np.linalg.norm(before.wv[word])
vec2 = after.wv[word] / np.linalg.norm(after.wv[word])
sim = vec1.dot(vec2)
return 1 - sim
<|end_body_0|>
<|body_start_1|>... | HamiltonMeasures | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HamiltonMeasures:
def linguistic_drift(before, after, word):
"""Hamilton et al. (2016) proposed a measure for linguistic drift, which is simply the cosine distance between the embeddings of a word before and after Parameters ---------- :before: gensim.models.Word2Vec embeddings model :af... | stack_v2_sparse_classes_75kplus_train_003668 | 2,166 | permissive | [
{
"docstring": "Hamilton et al. (2016) proposed a measure for linguistic drift, which is simply the cosine distance between the embeddings of a word before and after Parameters ---------- :before: gensim.models.Word2Vec embeddings model :after: gensim.models.Word2Vec embeddings model :word: str word for which t... | 2 | stack_v2_sparse_classes_30k_val_002586 | Implement the Python class `HamiltonMeasures` described below.
Class description:
Implement the HamiltonMeasures class.
Method signatures and docstrings:
- def linguistic_drift(before, after, word): Hamilton et al. (2016) proposed a measure for linguistic drift, which is simply the cosine distance between the embeddi... | Implement the Python class `HamiltonMeasures` described below.
Class description:
Implement the HamiltonMeasures class.
Method signatures and docstrings:
- def linguistic_drift(before, after, word): Hamilton et al. (2016) proposed a measure for linguistic drift, which is simply the cosine distance between the embeddi... | 824079b388d0eebc92b2197805b27ed320353f8f | <|skeleton|>
class HamiltonMeasures:
def linguistic_drift(before, after, word):
"""Hamilton et al. (2016) proposed a measure for linguistic drift, which is simply the cosine distance between the embeddings of a word before and after Parameters ---------- :before: gensim.models.Word2Vec embeddings model :af... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HamiltonMeasures:
def linguistic_drift(before, after, word):
"""Hamilton et al. (2016) proposed a measure for linguistic drift, which is simply the cosine distance between the embeddings of a word before and after Parameters ---------- :before: gensim.models.Word2Vec embeddings model :after: gensim.mo... | the_stack_v2_python_sparse | modules/semshift/measures.py | petershan1119/semantic-progressiveness | train | 0 | |
acf6c1f62626e3eaa611e20e967382221c3e7025 | [
"output = []\nfor c in input:\n if encoding:\n try:\n output.append(c.encode(encoding))\n continue\n except:\n pass\n if ord(c) in latex_equivalents:\n output.append(latex_equivalents[ord(c)])\n else:\n output += ['{\\\\char', str(ord(c)), '}']\n... | <|body_start_0|>
output = []
for c in input:
if encoding:
try:
output.append(c.encode(encoding))
continue
except:
pass
if ord(c) in latex_equivalents:
output.append(latex_e... | Codec | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, input, errors='strict'):
"""Convert unicode string to latex."""
<|body_0|>
def decode(self, input, errors='strict'):
"""Convert latex source string to unicode."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
output = []
... | stack_v2_sparse_classes_75kplus_train_003669 | 28,955 | permissive | [
{
"docstring": "Convert unicode string to latex.",
"name": "encode",
"signature": "def encode(self, input, errors='strict')"
},
{
"docstring": "Convert latex source string to unicode.",
"name": "decode",
"signature": "def decode(self, input, errors='strict')"
}
] | 2 | stack_v2_sparse_classes_30k_train_033067 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, input, errors='strict'): Convert unicode string to latex.
- def decode(self, input, errors='strict'): Convert latex source string to unicode. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, input, errors='strict'): Convert unicode string to latex.
- def decode(self, input, errors='strict'): Convert latex source string to unicode.
<|skeleton|>
class Codec... | 0090c406677a35cfdf790894480a2aee8e319419 | <|skeleton|>
class Codec:
def encode(self, input, errors='strict'):
"""Convert unicode string to latex."""
<|body_0|>
def decode(self, input, errors='strict'):
"""Convert latex source string to unicode."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def encode(self, input, errors='strict'):
"""Convert unicode string to latex."""
output = []
for c in input:
if encoding:
try:
output.append(c.encode(encoding))
continue
except:
... | the_stack_v2_python_sparse | bibstuff/data/latex_codec.py | dschwilk/bibstuff | train | 11 | |
d3e318f2e9cde2fb7d94faad20e1976a1af42de5 | [
"result = m.copy()\nfor x, row in enumerate(m):\n col = [i[x] for i in m]\n result[x] = col[::-1]\nreturn result",
"l = len(m) - 1\npprint(m)\nresult = m.copy()\nfor x, row in enumerate(m):\n col = [i[x] for i in m]\n result[l - x] = col\nreturn result"
] | <|body_start_0|>
result = m.copy()
for x, row in enumerate(m):
col = [i[x] for i in m]
result[x] = col[::-1]
return result
<|end_body_0|>
<|body_start_1|>
l = len(m) - 1
pprint(m)
result = m.copy()
for x, row in enumerate(m):
c... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate_matrix(self, m):
"""Given a matrix of NxN dimension, rotate it 90 degrees clockwise."""
<|body_0|>
def rotate_matrix_ccw(self, m):
"""Given a matrix of NxN dimension, rotate it 90 degrees counter-clockwise."""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_75kplus_train_003670 | 1,261 | no_license | [
{
"docstring": "Given a matrix of NxN dimension, rotate it 90 degrees clockwise.",
"name": "rotate_matrix",
"signature": "def rotate_matrix(self, m)"
},
{
"docstring": "Given a matrix of NxN dimension, rotate it 90 degrees counter-clockwise.",
"name": "rotate_matrix_ccw",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_052014 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate_matrix(self, m): Given a matrix of NxN dimension, rotate it 90 degrees clockwise.
- def rotate_matrix_ccw(self, m): Given a matrix of NxN dimension, rotate it 90 degre... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate_matrix(self, m): Given a matrix of NxN dimension, rotate it 90 degrees clockwise.
- def rotate_matrix_ccw(self, m): Given a matrix of NxN dimension, rotate it 90 degre... | acad7283f4af301539c621b4b50268208509d38f | <|skeleton|>
class Solution:
def rotate_matrix(self, m):
"""Given a matrix of NxN dimension, rotate it 90 degrees clockwise."""
<|body_0|>
def rotate_matrix_ccw(self, m):
"""Given a matrix of NxN dimension, rotate it 90 degrees counter-clockwise."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def rotate_matrix(self, m):
"""Given a matrix of NxN dimension, rotate it 90 degrees clockwise."""
result = m.copy()
for x, row in enumerate(m):
col = [i[x] for i in m]
result[x] = col[::-1]
return result
def rotate_matrix_ccw(self, m):
... | the_stack_v2_python_sparse | algos/rotate_matrix.py | arijort/prep | train | 2 | |
88d7c4ce1a6fe3cb9d6490788a0ed17eef1ecec9 | [
"res = [0] * len(T)\ncurrentPeak = []\nfor i in range(len(T) - 1, -1, -1):\n while currentPeak and T[i] >= T[currentPeak[-1]]:\n currentPeak.pop()\n if currentPeak:\n res[i] = currentPeak[-1] - i\n currentPeak.append(i)\nreturn res",
"res = []\nfor i in range(len(T)):\n count = 0\n fo... | <|body_start_0|>
res = [0] * len(T)
currentPeak = []
for i in range(len(T) - 1, -1, -1):
while currentPeak and T[i] >= T[currentPeak[-1]]:
currentPeak.pop()
if currentPeak:
res[i] = currentPeak[-1] - i
currentPeak.append(i)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def dailyTemperatures(self, T):
""":type T: List[int] :rtype: List[int]"""
<|body_0|>
def dailyTemperatures2(self, T):
""":type T: List[int] :rtype: List[int] #quadratic solution. exceeds time limit"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_003671 | 1,206 | no_license | [
{
"docstring": ":type T: List[int] :rtype: List[int]",
"name": "dailyTemperatures",
"signature": "def dailyTemperatures(self, T)"
},
{
"docstring": ":type T: List[int] :rtype: List[int] #quadratic solution. exceeds time limit",
"name": "dailyTemperatures2",
"signature": "def dailyTempera... | 2 | stack_v2_sparse_classes_30k_train_022842 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dailyTemperatures(self, T): :type T: List[int] :rtype: List[int]
- def dailyTemperatures2(self, T): :type T: List[int] :rtype: List[int] #quadratic solution. exceeds time lim... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dailyTemperatures(self, T): :type T: List[int] :rtype: List[int]
- def dailyTemperatures2(self, T): :type T: List[int] :rtype: List[int] #quadratic solution. exceeds time lim... | 813235789ce422a3bab198317aafc46fbc61625e | <|skeleton|>
class Solution:
def dailyTemperatures(self, T):
""":type T: List[int] :rtype: List[int]"""
<|body_0|>
def dailyTemperatures2(self, T):
""":type T: List[int] :rtype: List[int] #quadratic solution. exceeds time limit"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def dailyTemperatures(self, T):
""":type T: List[int] :rtype: List[int]"""
res = [0] * len(T)
currentPeak = []
for i in range(len(T) - 1, -1, -1):
while currentPeak and T[i] >= T[currentPeak[-1]]:
currentPeak.pop()
if currentPea... | the_stack_v2_python_sparse | 12.STACK/739_daily_temperature/solution.py | kimmyoo/python_leetcode | train | 1 | |
423a8416990f51a64d13195a6b920419bf5903c2 | [
"if not digits:\n return []\ndigit2chars = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}\nres = [i for i in digit2chars[digits[0]]]\nfor i in digits[1:]:\n res = [m + n for m in res for n in digit2chars[i]]\n print(res)\nreturn res",
"if not digits:\n ... | <|body_start_0|>
if not digits:
return []
digit2chars = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
res = [i for i in digit2chars[digits[0]]]
for i in digits[1:]:
res = [m + n for m in res for n in digit2chars... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def letterCombinations(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_0|>
def letterCombinations2(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not digits:
... | stack_v2_sparse_classes_75kplus_train_003672 | 1,709 | no_license | [
{
"docstring": ":type digits: str :rtype: List[str]",
"name": "letterCombinations",
"signature": "def letterCombinations(self, digits)"
},
{
"docstring": ":type digits: str :rtype: List[str]",
"name": "letterCombinations2",
"signature": "def letterCombinations2(self, digits)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCombinations(self, digits): :type digits: str :rtype: List[str]
- def letterCombinations2(self, digits): :type digits: str :rtype: List[str] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCombinations(self, digits): :type digits: str :rtype: List[str]
- def letterCombinations2(self, digits): :type digits: str :rtype: List[str]
<|skeleton|>
class Solutio... | 2866df7587ee867a958a2b4fc02345bc3ef56999 | <|skeleton|>
class Solution:
def letterCombinations(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_0|>
def letterCombinations2(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def letterCombinations(self, digits):
""":type digits: str :rtype: List[str]"""
if not digits:
return []
digit2chars = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
res = [i for i in digit2chars[digits[0... | the_stack_v2_python_sparse | 中级算法/letterCombinations.py | OrangeJessie/Fighting_Leetcode | train | 1 | |
9adc96bd7b6fdb25b973a79394ce1289b5c0300d | [
"super(TenorNetworkModule, self).__init__()\nself.args = args\nself.setup_weights()\nself.init_parameters()",
"self.weight_matrix = torch.nn.Parameter(torch.Tensor(self.args.filters_3, self.args.filters_3, self.args.tensor_neurons))\nself.weight_matrix_block = torch.nn.Parameter(torch.Tensor(self.args.tensor_neur... | <|body_start_0|>
super(TenorNetworkModule, self).__init__()
self.args = args
self.setup_weights()
self.init_parameters()
<|end_body_0|>
<|body_start_1|>
self.weight_matrix = torch.nn.Parameter(torch.Tensor(self.args.filters_3, self.args.filters_3, self.args.tensor_neurons))
... | SimGNN Tensor Network module to calculate similarity vector. | TenorNetworkModule | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TenorNetworkModule:
"""SimGNN Tensor Network module to calculate similarity vector."""
def __init__(self, args):
""":param args: Arguments object."""
<|body_0|>
def setup_weights(self):
"""Defining weights."""
<|body_1|>
def init_parameters(self):
... | stack_v2_sparse_classes_75kplus_train_003673 | 8,576 | no_license | [
{
"docstring": ":param args: Arguments object.",
"name": "__init__",
"signature": "def __init__(self, args)"
},
{
"docstring": "Defining weights.",
"name": "setup_weights",
"signature": "def setup_weights(self)"
},
{
"docstring": "Initializing weights.",
"name": "init_paramet... | 4 | stack_v2_sparse_classes_30k_train_012824 | Implement the Python class `TenorNetworkModule` described below.
Class description:
SimGNN Tensor Network module to calculate similarity vector.
Method signatures and docstrings:
- def __init__(self, args): :param args: Arguments object.
- def setup_weights(self): Defining weights.
- def init_parameters(self): Initia... | Implement the Python class `TenorNetworkModule` described below.
Class description:
SimGNN Tensor Network module to calculate similarity vector.
Method signatures and docstrings:
- def __init__(self, args): :param args: Arguments object.
- def setup_weights(self): Defining weights.
- def init_parameters(self): Initia... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class TenorNetworkModule:
"""SimGNN Tensor Network module to calculate similarity vector."""
def __init__(self, args):
""":param args: Arguments object."""
<|body_0|>
def setup_weights(self):
"""Defining weights."""
<|body_1|>
def init_parameters(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TenorNetworkModule:
"""SimGNN Tensor Network module to calculate similarity vector."""
def __init__(self, args):
""":param args: Arguments object."""
super(TenorNetworkModule, self).__init__()
self.args = args
self.setup_weights()
self.init_parameters()
def se... | the_stack_v2_python_sparse | generated/test_benedekrozemberczki_SimGNN.py | jansel/pytorch-jit-paritybench | train | 35 |
77fb6134344395737c317b0100cbcb34a171757a | [
"self.hass = hass\nself._devices = config.get(CONF_DEVICES, None)\nself._access_token_payload = {'username': config.get(CONF_USERNAME), 'password': config.get(CONF_PASSWORD), 'client_id': config.get(CONF_CLIENT_ID), 'client_secret': config.get(CONF_SECRET), 'grant_type': 'password', 'scope': SCOPE}\nself._headers =... | <|body_start_0|>
self.hass = hass
self._devices = config.get(CONF_DEVICES, None)
self._access_token_payload = {'username': config.get(CONF_USERNAME), 'password': config.get(CONF_PASSWORD), 'client_id': config.get(CONF_CLIENT_ID), 'client_secret': config.get(CONF_SECRET), 'grant_type': 'password'... | A class representing an Automatic device. | AutomaticDeviceScanner | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutomaticDeviceScanner:
"""A class representing an Automatic device."""
def __init__(self, hass, config: dict, see) -> None:
"""Initialize the automatic device scanner."""
<|body_0|>
def _update_headers(self):
"""Get the access token from automatic."""
<|... | stack_v2_sparse_classes_75kplus_train_003674 | 5,190 | permissive | [
{
"docstring": "Initialize the automatic device scanner.",
"name": "__init__",
"signature": "def __init__(self, hass, config: dict, see) -> None"
},
{
"docstring": "Get the access token from automatic.",
"name": "_update_headers",
"signature": "def _update_headers(self)"
},
{
"do... | 3 | stack_v2_sparse_classes_30k_train_036979 | Implement the Python class `AutomaticDeviceScanner` described below.
Class description:
A class representing an Automatic device.
Method signatures and docstrings:
- def __init__(self, hass, config: dict, see) -> None: Initialize the automatic device scanner.
- def _update_headers(self): Get the access token from aut... | Implement the Python class `AutomaticDeviceScanner` described below.
Class description:
A class representing an Automatic device.
Method signatures and docstrings:
- def __init__(self, hass, config: dict, see) -> None: Initialize the automatic device scanner.
- def _update_headers(self): Get the access token from aut... | ca0e92aba83de2fd6cb1cc4d14f3b4471f17cf3d | <|skeleton|>
class AutomaticDeviceScanner:
"""A class representing an Automatic device."""
def __init__(self, hass, config: dict, see) -> None:
"""Initialize the automatic device scanner."""
<|body_0|>
def _update_headers(self):
"""Get the access token from automatic."""
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AutomaticDeviceScanner:
"""A class representing an Automatic device."""
def __init__(self, hass, config: dict, see) -> None:
"""Initialize the automatic device scanner."""
self.hass = hass
self._devices = config.get(CONF_DEVICES, None)
self._access_token_payload = {'userna... | the_stack_v2_python_sparse | homeassistant/components/device_tracker/automatic.py | Smart-Torvy/torvy-home-assistant | train | 2 |
a996cdd391d29059a86ace30db7c268515c156ba | [
"self.reader = reader\nself.server_add = f'http://{host}:{port}'\nself.server_config = None\nself.update_config()",
"result = requests.get(f'{self.server_add}/fields')\nif result.status_code != 200:\n return 1\nself.server_config = json.loads(result.json())\nreturn 0",
"ep = f'{self.server_add}/{user_id}/sna... | <|body_start_0|>
self.reader = reader
self.server_add = f'http://{host}:{port}'
self.server_config = None
self.update_config()
<|end_body_0|>
<|body_start_1|>
result = requests.get(f'{self.server_add}/fields')
if result.status_code != 200:
return 1
se... | Client | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Client:
def __init__(self, host='127.0.0.1', port='5000', reader=None, parser=None):
"""Server Class Sends the data of the sample file to the server :param host: defaults to '127.0.0.1' :param port: defaults to '5000' :param reader: read the data from sample file :param parser: parse the... | stack_v2_sparse_classes_75kplus_train_003675 | 2,020 | no_license | [
{
"docstring": "Server Class Sends the data of the sample file to the server :param host: defaults to '127.0.0.1' :param port: defaults to '5000' :param reader: read the data from sample file :param parser: parse the snapshot and leave only the relevant fields",
"name": "__init__",
"signature": "def __i... | 5 | null | Implement the Python class `Client` described below.
Class description:
Implement the Client class.
Method signatures and docstrings:
- def __init__(self, host='127.0.0.1', port='5000', reader=None, parser=None): Server Class Sends the data of the sample file to the server :param host: defaults to '127.0.0.1' :param ... | Implement the Python class `Client` described below.
Class description:
Implement the Client class.
Method signatures and docstrings:
- def __init__(self, host='127.0.0.1', port='5000', reader=None, parser=None): Server Class Sends the data of the sample file to the server :param host: defaults to '127.0.0.1' :param ... | d9715360e5e9481ac9523ee6434cd0c653d81322 | <|skeleton|>
class Client:
def __init__(self, host='127.0.0.1', port='5000', reader=None, parser=None):
"""Server Class Sends the data of the sample file to the server :param host: defaults to '127.0.0.1' :param port: defaults to '5000' :param reader: read the data from sample file :param parser: parse the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Client:
def __init__(self, host='127.0.0.1', port='5000', reader=None, parser=None):
"""Server Class Sends the data of the sample file to the server :param host: defaults to '127.0.0.1' :param port: defaults to '5000' :param reader: read the data from sample file :param parser: parse the snapshot and ... | the_stack_v2_python_sparse | asd/client/client_module.py | idoosams/ASDFP | train | 0 | |
45edebe5eb48d75e24b2329fd16c5ef9c32a447c | [
"n = len(A)\nans = left = 0\nwhile left + 2 < n:\n right = left + 1\n if A[left] < A[left + 1]:\n while right + 1 < n and A[right] < A[right + 1]:\n right += 1\n if right < n - 1 and A[right] > A[right + 1]:\n while right + 1 < n and A[right] > A[right + 1]:\n ... | <|body_start_0|>
n = len(A)
ans = left = 0
while left + 2 < n:
right = left + 1
if A[left] < A[left + 1]:
while right + 1 < n and A[right] < A[right + 1]:
right += 1
if right < n - 1 and A[right] > A[right + 1]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longest_mountain(A: List[int]) -> int:
"""双指针"""
<|body_0|>
def longest_mountain_v2(A: List[int]) -> int:
"""dp"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(A)
ans = left = 0
while left + 2 < n:
r... | stack_v2_sparse_classes_75kplus_train_003676 | 2,511 | no_license | [
{
"docstring": "双指针",
"name": "longest_mountain",
"signature": "def longest_mountain(A: List[int]) -> int"
},
{
"docstring": "dp",
"name": "longest_mountain_v2",
"signature": "def longest_mountain_v2(A: List[int]) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longest_mountain(A: List[int]) -> int: 双指针
- def longest_mountain_v2(A: List[int]) -> int: dp | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longest_mountain(A: List[int]) -> int: 双指针
- def longest_mountain_v2(A: List[int]) -> int: dp
<|skeleton|>
class Solution:
def longest_mountain(A: List[int]) -> int:
... | 1d1876620a55ff88af7bc390cf1a4fd4350d8d16 | <|skeleton|>
class Solution:
def longest_mountain(A: List[int]) -> int:
"""双指针"""
<|body_0|>
def longest_mountain_v2(A: List[int]) -> int:
"""dp"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def longest_mountain(A: List[int]) -> int:
"""双指针"""
n = len(A)
ans = left = 0
while left + 2 < n:
right = left + 1
if A[left] < A[left + 1]:
while right + 1 < n and A[right] < A[right + 1]:
right += 1
... | the_stack_v2_python_sparse | 02-算法思想/双指针/845.数组中的最长山脉(M).py | jh-lau/leetcode_in_python | train | 0 | |
0280bfcf96f430e9cc1a594dbbc8b8ba29ccb190 | [
"super(MultiHeadAttention, self).__init__()\nassert size % num_heads == 0\nself.head_size = head_size = size // num_heads\nself.model_size = size\nself.num_heads = num_heads\nself.k_layer = nn.Linear(size, num_heads * head_size)\nself.v_layer = nn.Linear(size, num_heads * head_size)\nself.q_layer = nn.Linear(size, ... | <|body_start_0|>
super(MultiHeadAttention, self).__init__()
assert size % num_heads == 0
self.head_size = head_size = size // num_heads
self.model_size = size
self.num_heads = num_heads
self.k_layer = nn.Linear(size, num_heads * head_size)
self.v_layer = nn.Linear... | Multi-Head Attention module from "Attention is All You Need" Implementation modified from OpenNMT-py. https://github.com/OpenNMT/OpenNMT-py | MultiHeadAttention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadAttention:
"""Multi-Head Attention module from "Attention is All You Need" Implementation modified from OpenNMT-py. https://github.com/OpenNMT/OpenNMT-py"""
def __init__(self, num_heads: int, size: int, dropout: float=0.1) -> None:
"""Create a multi-headed attention layer. :... | stack_v2_sparse_classes_75kplus_train_003677 | 2,916 | permissive | [
{
"docstring": "Create a multi-headed attention layer. :param num_heads: the number of heads :param size: model size (must be divisible by num_heads) :param dropout: probability of dropping a unit",
"name": "__init__",
"signature": "def __init__(self, num_heads: int, size: int, dropout: float=0.1) -> No... | 2 | null | Implement the Python class `MultiHeadAttention` described below.
Class description:
Multi-Head Attention module from "Attention is All You Need" Implementation modified from OpenNMT-py. https://github.com/OpenNMT/OpenNMT-py
Method signatures and docstrings:
- def __init__(self, num_heads: int, size: int, dropout: flo... | Implement the Python class `MultiHeadAttention` described below.
Class description:
Multi-Head Attention module from "Attention is All You Need" Implementation modified from OpenNMT-py. https://github.com/OpenNMT/OpenNMT-py
Method signatures and docstrings:
- def __init__(self, num_heads: int, size: int, dropout: flo... | e10df55ad145df78467b664889c8d84fa53a8e21 | <|skeleton|>
class MultiHeadAttention:
"""Multi-Head Attention module from "Attention is All You Need" Implementation modified from OpenNMT-py. https://github.com/OpenNMT/OpenNMT-py"""
def __init__(self, num_heads: int, size: int, dropout: float=0.1) -> None:
"""Create a multi-headed attention layer. :... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiHeadAttention:
"""Multi-Head Attention module from "Attention is All You Need" Implementation modified from OpenNMT-py. https://github.com/OpenNMT/OpenNMT-py"""
def __init__(self, num_heads: int, size: int, dropout: float=0.1) -> None:
"""Create a multi-headed attention layer. :param num_hea... | the_stack_v2_python_sparse | src/module/attention/multi_head_attention.py | jiangqn/TextVAE | train | 0 |
86cdbb1c860d8cd193ca1854cdb34b69dd38b4c1 | [
"DiscreteDomain.__init__(self, dim, coord, local_volume, id, referential)\nif topology is not None:\n if topology.shape != (self.size, self.size):\n raise ValueError('Incompatible shape for topological model')\nself.topology = topology",
"td = DiscreteDomain.mask(self, bmask)\nstopo = reduce_coo_matrix(... | <|body_start_0|>
DiscreteDomain.__init__(self, dim, coord, local_volume, id, referential)
if topology is not None:
if topology.shape != (self.size, self.size):
raise ValueError('Incompatible shape for topological model')
self.topology = topology
<|end_body_0|>
<|body... | Besides DiscreteDomain attributed, StructuredDomain has a topology, which allows many operations (morphology etc.) | StructuredDomain | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StructuredDomain:
"""Besides DiscreteDomain attributed, StructuredDomain has a topology, which allows many operations (morphology etc.)"""
def __init__(self, dim, coord, local_volume, topology, did='', referential=''):
"""Initialize structured domain instance Parameters ---------- di... | stack_v2_sparse_classes_75kplus_train_003678 | 23,653 | permissive | [
{
"docstring": "Initialize structured domain instance Parameters ---------- dim: int, the (physical) dimension of the domain coord: array of shape(size, em_dim), explicit coordinates of the domain sites local_volume: array of shape(size), yields the volume associated with each site topology: sparse binary coo_m... | 2 | stack_v2_sparse_classes_30k_train_002138 | Implement the Python class `StructuredDomain` described below.
Class description:
Besides DiscreteDomain attributed, StructuredDomain has a topology, which allows many operations (morphology etc.)
Method signatures and docstrings:
- def __init__(self, dim, coord, local_volume, topology, did='', referential=''): Initi... | Implement the Python class `StructuredDomain` described below.
Class description:
Besides DiscreteDomain attributed, StructuredDomain has a topology, which allows many operations (morphology etc.)
Method signatures and docstrings:
- def __init__(self, dim, coord, local_volume, topology, did='', referential=''): Initi... | 7eede02471567487e454016c1e7cf637d3afac9e | <|skeleton|>
class StructuredDomain:
"""Besides DiscreteDomain attributed, StructuredDomain has a topology, which allows many operations (morphology etc.)"""
def __init__(self, dim, coord, local_volume, topology, did='', referential=''):
"""Initialize structured domain instance Parameters ---------- di... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StructuredDomain:
"""Besides DiscreteDomain attributed, StructuredDomain has a topology, which allows many operations (morphology etc.)"""
def __init__(self, dim, coord, local_volume, topology, did='', referential=''):
"""Initialize structured domain instance Parameters ---------- dim: int, the (... | the_stack_v2_python_sparse | nipy/labs/spatial_models/discrete_domain.py | nipy/nipy | train | 275 |
c3ab1961ed82d868b371bde8961f16db18868f03 | [
"essential_keys = ['nvars', 'dw', 'eps', 'newton_maxiter', 'newton_tol', 'interval', 'radius']\nfor key in essential_keys:\n if key not in problem_params:\n msg = 'need %s to instantiate problem, only got %s' % (key, str(problem_params.keys()))\n raise ParameterError(msg)\nif problem_params['nvars'... | <|body_start_0|>
essential_keys = ['nvars', 'dw', 'eps', 'newton_maxiter', 'newton_tol', 'interval', 'radius']
for key in essential_keys:
if key not in problem_params:
msg = 'need %s to instantiate problem, only got %s' % (key, str(problem_params.keys()))
rais... | Example implementing the Allen-Cahn equation in 1D with finite differences and periodic BC, with driving force, 0-1 formulation (Bayreuth example) | allencahn_periodic_semiimplicit | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class allencahn_periodic_semiimplicit:
"""Example implementing the Allen-Cahn equation in 1D with finite differences and periodic BC, with driving force, 0-1 formulation (Bayreuth example)"""
def __init__(self, problem_params, dtype_u=mesh, dtype_f=imex_mesh):
"""Initialization routine Arg... | stack_v2_sparse_classes_75kplus_train_003679 | 27,394 | permissive | [
{
"docstring": "Initialization routine Args: problem_params (dict): custom parameters for the example dtype_u: mesh data type (will be passed parent class) dtype_f: mesh data type (will be passed parent class)",
"name": "__init__",
"signature": "def __init__(self, problem_params, dtype_u=mesh, dtype_f=i... | 3 | stack_v2_sparse_classes_30k_train_016747 | Implement the Python class `allencahn_periodic_semiimplicit` described below.
Class description:
Example implementing the Allen-Cahn equation in 1D with finite differences and periodic BC, with driving force, 0-1 formulation (Bayreuth example)
Method signatures and docstrings:
- def __init__(self, problem_params, dty... | Implement the Python class `allencahn_periodic_semiimplicit` described below.
Class description:
Example implementing the Allen-Cahn equation in 1D with finite differences and periodic BC, with driving force, 0-1 formulation (Bayreuth example)
Method signatures and docstrings:
- def __init__(self, problem_params, dty... | de2cd523411276083355389d7e7993106cedf93d | <|skeleton|>
class allencahn_periodic_semiimplicit:
"""Example implementing the Allen-Cahn equation in 1D with finite differences and periodic BC, with driving force, 0-1 formulation (Bayreuth example)"""
def __init__(self, problem_params, dtype_u=mesh, dtype_f=imex_mesh):
"""Initialization routine Arg... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class allencahn_periodic_semiimplicit:
"""Example implementing the Allen-Cahn equation in 1D with finite differences and periodic BC, with driving force, 0-1 formulation (Bayreuth example)"""
def __init__(self, problem_params, dtype_u=mesh, dtype_f=imex_mesh):
"""Initialization routine Args: problem_pa... | the_stack_v2_python_sparse | pySDC/implementations/problem_classes/AllenCahn_1D_FD.py | ruthschoebel/pySDC | train | 0 |
51ce6a2db64880c212cb789a87835b5cf56f16d0 | [
"\"\"\"\n Make end-of-life == end-of-episode, but only reset on true game over.\n Done by DeepMind for the DQN and co. since it helps value estimation.\n \"\"\"\ngym.Wrapper.__init__(self, env)\nself.lives = 0\nself.was_real_done = True",
"obs, reward, done, info = self.env.step(action)\nself... | <|body_start_0|>
"""
Make end-of-life == end-of-episode, but only reset on true game over.
Done by DeepMind for the DQN and co. since it helps value estimation.
"""
gym.Wrapper.__init__(self, env)
self.lives = 0
self.was_real_done = True
<|... | EpisodicLifeEnv | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EpisodicLifeEnv:
def __init__(self, env):
""":param env:"""
<|body_0|>
def step(self, action):
""":param action: :return:"""
<|body_1|>
def reset(self, **kwargs):
""":param kwargs: :return:"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_75kplus_train_003680 | 6,164 | no_license | [
{
"docstring": ":param env:",
"name": "__init__",
"signature": "def __init__(self, env)"
},
{
"docstring": ":param action: :return:",
"name": "step",
"signature": "def step(self, action)"
},
{
"docstring": ":param kwargs: :return:",
"name": "reset",
"signature": "def rese... | 3 | stack_v2_sparse_classes_30k_test_001178 | Implement the Python class `EpisodicLifeEnv` described below.
Class description:
Implement the EpisodicLifeEnv class.
Method signatures and docstrings:
- def __init__(self, env): :param env:
- def step(self, action): :param action: :return:
- def reset(self, **kwargs): :param kwargs: :return: | Implement the Python class `EpisodicLifeEnv` described below.
Class description:
Implement the EpisodicLifeEnv class.
Method signatures and docstrings:
- def __init__(self, env): :param env:
- def step(self, action): :param action: :return:
- def reset(self, **kwargs): :param kwargs: :return:
<|skeleton|>
class Epis... | 375633b9dc34302fa1d806a7ee69c86f97f1054d | <|skeleton|>
class EpisodicLifeEnv:
def __init__(self, env):
""":param env:"""
<|body_0|>
def step(self, action):
""":param action: :return:"""
<|body_1|>
def reset(self, **kwargs):
""":param kwargs: :return:"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EpisodicLifeEnv:
def __init__(self, env):
""":param env:"""
"""
Make end-of-life == end-of-episode, but only reset on true game over.
Done by DeepMind for the DQN and co. since it helps value estimation.
"""
gym.Wrapper.__init__(self, env... | the_stack_v2_python_sparse | utils/wrappers.py | kessi1990/masterthesis | train | 1 | |
3e53ebba10be2b2c70c9d2efc190f5cef9dd8aca | [
"mycursor = self.db.connection.cursor()\nmycursor.execute('\\n INSERT INTO Substitute (id_product_to_substitute, id_product_substitute)\\n VALUES (%(id_product_to_substitute)s, %(id_product_substitute)s)\\n ', {'id_product_to_substitute': selected_product[0].id, 'id_product_substitute': better_... | <|body_start_0|>
mycursor = self.db.connection.cursor()
mycursor.execute('\n INSERT INTO Substitute (id_product_to_substitute, id_product_substitute)\n VALUES (%(id_product_to_substitute)s, %(id_product_substitute)s)\n ', {'id_product_to_substitute': selected_product[0].id, 'id_prod... | Manage the substitutes in the SQL database | SubstituteManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubstituteManager:
"""Manage the substitutes in the SQL database"""
def insert_substitute(self, selected_product, better_product):
"""Inserts substitutes into the SQL table when the user choose this option"""
<|body_0|>
def fetch_substitute_list(self):
"""Fetch a... | stack_v2_sparse_classes_75kplus_train_003681 | 7,181 | no_license | [
{
"docstring": "Inserts substitutes into the SQL table when the user choose this option",
"name": "insert_substitute",
"signature": "def insert_substitute(self, selected_product, better_product)"
},
{
"docstring": "Fetch all the substitutes from the SQL Substitute table so that the controllers c... | 2 | stack_v2_sparse_classes_30k_train_017905 | Implement the Python class `SubstituteManager` described below.
Class description:
Manage the substitutes in the SQL database
Method signatures and docstrings:
- def insert_substitute(self, selected_product, better_product): Inserts substitutes into the SQL table when the user choose this option
- def fetch_substitut... | Implement the Python class `SubstituteManager` described below.
Class description:
Manage the substitutes in the SQL database
Method signatures and docstrings:
- def insert_substitute(self, selected_product, better_product): Inserts substitutes into the SQL table when the user choose this option
- def fetch_substitut... | 8b1ae1ed03d2274e85b8a38c39ebfcf354857e42 | <|skeleton|>
class SubstituteManager:
"""Manage the substitutes in the SQL database"""
def insert_substitute(self, selected_product, better_product):
"""Inserts substitutes into the SQL table when the user choose this option"""
<|body_0|>
def fetch_substitute_list(self):
"""Fetch a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SubstituteManager:
"""Manage the substitutes in the SQL database"""
def insert_substitute(self, selected_product, better_product):
"""Inserts substitutes into the SQL table when the user choose this option"""
mycursor = self.db.connection.cursor()
mycursor.execute('\n INSER... | the_stack_v2_python_sparse | core/managers.py | bientavu/openfoodfacts | train | 0 |
6f4cb55a74da7b43fc3207dbc5a2f8ed41a29270 | [
"super(LinearKernelSteinTest, self).__init__(p, alpha)\nself.k = k\nself.seed = seed",
"with util.ContextTimer() as t:\n alpha = self.alpha\n X = dat.data()\n n = X.shape[0]\n _, H = self.compute_stat(dat, return_pointwise_stats=True)\n test_stat = np.sqrt(old_div(n, 2)) * np.mean(H)\n stat_var ... | <|body_start_0|>
super(LinearKernelSteinTest, self).__init__(p, alpha)
self.k = k
self.seed = seed
<|end_body_0|>
<|body_start_1|>
with util.ContextTimer() as t:
alpha = self.alpha
X = dat.data()
n = X.shape[0]
_, H = self.compute_stat(dat... | Goodness-of-fit test using the linear-version of kernelized Stein discrepancy test of Liu et al., 2016 in ICML 2016. Described in Liu et al., 2016. - This test runs in O(n d^2) time. - test stat = sqrt(n_half)*linear-time Stein discrepancy - Asymptotically normal under both H0 and H1. H0: the sample follows p H1: the s... | LinearKernelSteinTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearKernelSteinTest:
"""Goodness-of-fit test using the linear-version of kernelized Stein discrepancy test of Liu et al., 2016 in ICML 2016. Described in Liu et al., 2016. - This test runs in O(n d^2) time. - test stat = sqrt(n_half)*linear-time Stein discrepancy - Asymptotically normal under b... | stack_v2_sparse_classes_75kplus_train_003682 | 41,550 | permissive | [
{
"docstring": "p: an instance of UnnormalizedDensity k: a LinearKSTKernel object alpha: significance level n_simulate: The number of times to simulate from the null distribution by bootstrapping. Must be a positive integer.",
"name": "__init__",
"signature": "def __init__(self, p, k, alpha=0.01, seed=1... | 3 | stack_v2_sparse_classes_30k_train_012445 | Implement the Python class `LinearKernelSteinTest` described below.
Class description:
Goodness-of-fit test using the linear-version of kernelized Stein discrepancy test of Liu et al., 2016 in ICML 2016. Described in Liu et al., 2016. - This test runs in O(n d^2) time. - test stat = sqrt(n_half)*linear-time Stein disc... | Implement the Python class `LinearKernelSteinTest` described below.
Class description:
Goodness-of-fit test using the linear-version of kernelized Stein discrepancy test of Liu et al., 2016 in ICML 2016. Described in Liu et al., 2016. - This test runs in O(n d^2) time. - test stat = sqrt(n_half)*linear-time Stein disc... | 039a95ed9d8062e283da6bd051b7161a190b4876 | <|skeleton|>
class LinearKernelSteinTest:
"""Goodness-of-fit test using the linear-version of kernelized Stein discrepancy test of Liu et al., 2016 in ICML 2016. Described in Liu et al., 2016. - This test runs in O(n d^2) time. - test stat = sqrt(n_half)*linear-time Stein discrepancy - Asymptotically normal under b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LinearKernelSteinTest:
"""Goodness-of-fit test using the linear-version of kernelized Stein discrepancy test of Liu et al., 2016 in ICML 2016. Described in Liu et al., 2016. - This test runs in O(n d^2) time. - test stat = sqrt(n_half)*linear-time Stein discrepancy - Asymptotically normal under both H0 and H1... | the_stack_v2_python_sparse | kgof/goftest.py | wittawatj/kernel-gof | train | 69 |
a544e5074b140bb8bb212d4a9da2643f184e2d78 | [
"service = self.sys_services.get(request.match_info.get('service'))\nif not service:\n raise APIError('Service does not exist')\nreturn service",
"services = []\nfor service in self.sys_services.list_services:\n services.append({ATTR_SLUG: service.slug, ATTR_AVAILABLE: service.enabled, ATTR_PROVIDERS: servi... | <|body_start_0|>
service = self.sys_services.get(request.match_info.get('service'))
if not service:
raise APIError('Service does not exist')
return service
<|end_body_0|>
<|body_start_1|>
services = []
for service in self.sys_services.list_services:
servi... | Handle RESTful API for services functions. | APIServices | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class APIServices:
"""Handle RESTful API for services functions."""
def _extract_service(self, request):
"""Return service, throw an exception if it doesn't exist."""
<|body_0|>
async def list(self, request):
"""Show register services."""
<|body_1|>
async ... | stack_v2_sparse_classes_75kplus_train_003683 | 2,506 | permissive | [
{
"docstring": "Return service, throw an exception if it doesn't exist.",
"name": "_extract_service",
"signature": "def _extract_service(self, request)"
},
{
"docstring": "Show register services.",
"name": "list",
"signature": "async def list(self, request)"
},
{
"docstring": "Wr... | 5 | null | Implement the Python class `APIServices` described below.
Class description:
Handle RESTful API for services functions.
Method signatures and docstrings:
- def _extract_service(self, request): Return service, throw an exception if it doesn't exist.
- async def list(self, request): Show register services.
- async def ... | Implement the Python class `APIServices` described below.
Class description:
Handle RESTful API for services functions.
Method signatures and docstrings:
- def _extract_service(self, request): Return service, throw an exception if it doesn't exist.
- async def list(self, request): Show register services.
- async def ... | 4838b280adafed0997f32e021274b531178386cd | <|skeleton|>
class APIServices:
"""Handle RESTful API for services functions."""
def _extract_service(self, request):
"""Return service, throw an exception if it doesn't exist."""
<|body_0|>
async def list(self, request):
"""Show register services."""
<|body_1|>
async ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class APIServices:
"""Handle RESTful API for services functions."""
def _extract_service(self, request):
"""Return service, throw an exception if it doesn't exist."""
service = self.sys_services.get(request.match_info.get('service'))
if not service:
raise APIError('Service d... | the_stack_v2_python_sparse | supervisor/api/services.py | home-assistant/supervisor | train | 928 |
62de178bbbe4f50fe1369ed7d499ccdbac9c32db | [
"parent = request.GET.get('id', '')\nplanCase = request.GET.get('planCase', '')\nif not parent:\n return Response([])\nelif planCase:\n obj = SceneCase.objects.filter(parent=parent)\n data = PlanModuleSceneCaseSer(obj, many=True).data\nelse:\n obj = SceneCase.objects.filter(parent=parent)\n data = Sc... | <|body_start_0|>
parent = request.GET.get('id', '')
planCase = request.GET.get('planCase', '')
if not parent:
return Response([])
elif planCase:
obj = SceneCase.objects.filter(parent=parent)
data = PlanModuleSceneCaseSer(obj, many=True).data
el... | SceneCaseTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SceneCaseTree:
def get(self, request, *args, **kwargs):
"""1.项目不存在返回[] 2.项目存在返回项目下所有的节点"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""创建场景用例"""
<|body_1|>
def put(self, request, *args, **kwargs):
"""编辑场景接口"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus_train_003684 | 23,358 | no_license | [
{
"docstring": "1.项目不存在返回[] 2.项目存在返回项目下所有的节点",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "创建场景用例",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
},
{
"docstring": "编辑场景接口",
"name": "put",
"signature":... | 4 | stack_v2_sparse_classes_30k_train_020469 | Implement the Python class `SceneCaseTree` described below.
Class description:
Implement the SceneCaseTree class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): 1.项目不存在返回[] 2.项目存在返回项目下所有的节点
- def post(self, request, *args, **kwargs): 创建场景用例
- def put(self, request, *args, **kwargs): 编辑场景... | Implement the Python class `SceneCaseTree` described below.
Class description:
Implement the SceneCaseTree class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): 1.项目不存在返回[] 2.项目存在返回项目下所有的节点
- def post(self, request, *args, **kwargs): 创建场景用例
- def put(self, request, *args, **kwargs): 编辑场景... | f2523d6e51cde1b53ac6f453f8066b4b90c523b9 | <|skeleton|>
class SceneCaseTree:
def get(self, request, *args, **kwargs):
"""1.项目不存在返回[] 2.项目存在返回项目下所有的节点"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""创建场景用例"""
<|body_1|>
def put(self, request, *args, **kwargs):
"""编辑场景接口"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SceneCaseTree:
def get(self, request, *args, **kwargs):
"""1.项目不存在返回[] 2.项目存在返回项目下所有的节点"""
parent = request.GET.get('id', '')
planCase = request.GET.get('planCase', '')
if not parent:
return Response([])
elif planCase:
obj = SceneCase.objects.fil... | the_stack_v2_python_sparse | api/interface/rest/sceneInterface.py | zhuzhanhao1/backend | train | 0 | |
f0bfc0292e1ad37cdba8d08fabe7da8e51785966 | [
"self.expectations = expectations\nself.old_json_output_file_path = None\nself.new_json_output_dir = None\nself.new_json_output_filename = None",
"parser = argparse.ArgumentParser(description=__doc__)\nparser.add_argument('--old-json-output-file-path', help='The JSON output file to be updated, generated by WPT.')... | <|body_start_0|>
self.expectations = expectations
self.old_json_output_file_path = None
self.new_json_output_dir = None
self.new_json_output_filename = None
<|end_body_0|>
<|body_start_1|>
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--old-j... | WPTOutputUpdater | [
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WPTOutputUpdater:
def __init__(self, expectations):
"""Args: expectations: a blinkpy.web_tests.models.test_expectations.TestExpectations object"""
<|body_0|>
def run(self, args=None):
"""Main entry point to parse flags and execute the script."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_003685 | 7,476 | permissive | [
{
"docstring": "Args: expectations: a blinkpy.web_tests.models.test_expectations.TestExpectations object",
"name": "__init__",
"signature": "def __init__(self, expectations)"
},
{
"docstring": "Main entry point to parse flags and execute the script.",
"name": "run",
"signature": "def run... | 6 | stack_v2_sparse_classes_30k_train_047970 | Implement the Python class `WPTOutputUpdater` described below.
Class description:
Implement the WPTOutputUpdater class.
Method signatures and docstrings:
- def __init__(self, expectations): Args: expectations: a blinkpy.web_tests.models.test_expectations.TestExpectations object
- def run(self, args=None): Main entry ... | Implement the Python class `WPTOutputUpdater` described below.
Class description:
Implement the WPTOutputUpdater class.
Method signatures and docstrings:
- def __init__(self, expectations): Args: expectations: a blinkpy.web_tests.models.test_expectations.TestExpectations object
- def run(self, args=None): Main entry ... | ac814e85cb870a6b569e184c7a60a70ff3cb19f9 | <|skeleton|>
class WPTOutputUpdater:
def __init__(self, expectations):
"""Args: expectations: a blinkpy.web_tests.models.test_expectations.TestExpectations object"""
<|body_0|>
def run(self, args=None):
"""Main entry point to parse flags and execute the script."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WPTOutputUpdater:
def __init__(self, expectations):
"""Args: expectations: a blinkpy.web_tests.models.test_expectations.TestExpectations object"""
self.expectations = expectations
self.old_json_output_file_path = None
self.new_json_output_dir = None
self.new_json_output... | the_stack_v2_python_sparse | third_party/blink/tools/blinkpy/w3c/wpt_output_updater.py | ECS-251-W2020/chromium | train | 7 | |
145be6da4b6d7b6bf0b387132f5592209b8cc185 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('aquan_erj826', 'aquan_erj826')\nurl = 'https://data.boston.gov/export/245/954/2459542e-7026-48e2-9128-ca29dd3bebf8.json'\nresponse = urllib.request.urlopen(url).read().decode('utf-8')\nr = json.loads(res... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('aquan_erj826', 'aquan_erj826')
url = 'https://data.boston.gov/export/245/954/2459542e-7026-48e2-9128-ca29dd3bebf8.json'
response = urllib.request.... | get911Dispatch | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class get911Dispatch:
def execute(trial=False):
"""Retrieve 911 DAILY DISPATCH COUNT BY AGENCY data set from analyze Boston."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything h... | stack_v2_sparse_classes_75kplus_train_003686 | 4,037 | no_license | [
{
"docstring": "Retrieve 911 DAILY DISPATCH COUNT BY AGENCY data set from analyze Boston.",
"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 docu... | 2 | stack_v2_sparse_classes_30k_train_026559 | Implement the Python class `get911Dispatch` described below.
Class description:
Implement the get911Dispatch class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve 911 DAILY DISPATCH COUNT BY AGENCY data set from analyze Boston.
- def provenance(doc=prov.model.ProvDocument(), startTime=None, en... | Implement the Python class `get911Dispatch` described below.
Class description:
Implement the get911Dispatch class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve 911 DAILY DISPATCH COUNT BY AGENCY data set from analyze Boston.
- def provenance(doc=prov.model.ProvDocument(), startTime=None, en... | 97e72731ffadbeae57d7a332decd58706e7c08de | <|skeleton|>
class get911Dispatch:
def execute(trial=False):
"""Retrieve 911 DAILY DISPATCH COUNT BY AGENCY data set from analyze Boston."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything h... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class get911Dispatch:
def execute(trial=False):
"""Retrieve 911 DAILY DISPATCH COUNT BY AGENCY data set from analyze Boston."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('aquan_erj826', 'aquan_erj826')
... | the_stack_v2_python_sparse | aquan_erj826/get911Dispatch.py | ROODAY/course-2017-fal-proj | train | 3 | |
32bda878a583d63a656ac0de55bf366e69b8e487 | [
"self.__charWindowSize = charWindowSize\nself.__charWindow = Window(lexicon, charWindowSize, startPadding, endPadding)\nself.__wordWindow = Window(lexicon, wrdWindowSize, startPaddingWrd, endPaddingWrd)\nself.__lexicon = lexicon\nself.__numMaxChar = numMaxChar\nself.__wrdWindowSize = wrdWindowSize\nself.__filters =... | <|body_start_0|>
self.__charWindowSize = charWindowSize
self.__charWindow = Window(lexicon, charWindowSize, startPadding, endPadding)
self.__wordWindow = Window(lexicon, wrdWindowSize, startPaddingWrd, endPaddingWrd)
self.__lexicon = lexicon
self.__numMaxChar = numMaxChar
... | Generate sequences of character windows for a given sequence of words. For each word in the given sequence, a sequence of character windows will be generated. This class considers that words has the same number of character (numMaxChar). If a word has less than numMaxChar characters, then it will be filled with an arti... | CharacterWindowGenerator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CharacterWindowGenerator:
"""Generate sequences of character windows for a given sequence of words. For each word in the given sequence, a sequence of character windows will be generated. This class considers that words has the same number of character (numMaxChar). If a word has less than numMax... | stack_v2_sparse_classes_75kplus_train_003687 | 3,762 | no_license | [
{
"docstring": "Create a character window feature generator. TODO: Irving, comentar cada parâmetro. :param lexicon: :param numMaxChar: :param charWindowSize: :param wrdWindowSize: :param artificialChar: :param startPadding: :param endPadding: :param startPaddingWrd: :param endPaddingWrd: :param filters:",
"... | 2 | stack_v2_sparse_classes_30k_train_008025 | Implement the Python class `CharacterWindowGenerator` described below.
Class description:
Generate sequences of character windows for a given sequence of words. For each word in the given sequence, a sequence of character windows will be generated. This class considers that words has the same number of character (numM... | Implement the Python class `CharacterWindowGenerator` described below.
Class description:
Generate sequences of character windows for a given sequence of words. For each word in the given sequence, a sequence of character windows will be generated. This class considers that words has the same number of character (numM... | c2b6d502790fb1b15eee41b32636bd0a55ab3de2 | <|skeleton|>
class CharacterWindowGenerator:
"""Generate sequences of character windows for a given sequence of words. For each word in the given sequence, a sequence of character windows will be generated. This class considers that words has the same number of character (numMaxChar). If a word has less than numMax... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CharacterWindowGenerator:
"""Generate sequences of character windows for a given sequence of words. For each word in the given sequence, a sequence of character windows will be generated. This class considers that words has the same number of character (numMaxChar). If a word has less than numMaxChar characte... | the_stack_v2_python_sparse | data/CharacterWindowGenerator.py | eraldoluis/lia-pln-deeplearning | train | 5 |
c96b71a9590a709724d8c414ad03183c980f6f42 | [
"l_dow = p_schedule_obj.DOW\nl_now_day = p_now.weekday()\nl_day = 2 ** l_now_day\nl_is_in_dow = l_dow & l_day != 0\nif l_is_in_dow:\n return 0\nl_days = 1\nfor _l_ix in range(0, 7):\n l_now_day = (l_now_day + 1) % 7\n l_day = 2 ** l_now_day\n l_is_in_dow = l_dow & l_day != 0\n if l_is_in_dow:\n ... | <|body_start_0|>
l_dow = p_schedule_obj.DOW
l_now_day = p_now.weekday()
l_day = 2 ** l_now_day
l_is_in_dow = l_dow & l_day != 0
if l_is_in_dow:
return 0
l_days = 1
for _l_ix in range(0, 7):
l_now_day = (l_now_day + 1) % 7
l_day ... | Get the when scheduled time. It may be from about a minute to about 1 week. If the schedule is not active return a None This class deals with extracting information from the time and DOW fields of a schedule. DOW mon=1, tue=2, wed=4, thu=8, fri=16, sat=32, sun=64 weekday mon=0, tue=1, wed=2, thu=3, fri=4, sat=5, sun=6 ... | SchedTime | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchedTime:
"""Get the when scheduled time. It may be from about a minute to about 1 week. If the schedule is not active return a None This class deals with extracting information from the time and DOW fields of a schedule. DOW mon=1, tue=2, wed=4, thu=8, fri=16, sat=32, sun=64 weekday mon=0, tue=... | stack_v2_sparse_classes_75kplus_train_003688 | 12,791 | permissive | [
{
"docstring": "Get the number of days until the next DOW in the schedule. DOW mon=1, tue=2, wed=4, thu=8, fri=16, sat=32, sun=64 weekday() mon=0, tue=1, wed=2, thu=3, fri=4, sat=5, sun=6 @param p_schedule_obj: is the schedule object we are working on @param p_now: is a datetime.datetime.now() @return: the numb... | 3 | stack_v2_sparse_classes_30k_train_040430 | Implement the Python class `SchedTime` described below.
Class description:
Get the when scheduled time. It may be from about a minute to about 1 week. If the schedule is not active return a None This class deals with extracting information from the time and DOW fields of a schedule. DOW mon=1, tue=2, wed=4, thu=8, fri... | Implement the Python class `SchedTime` described below.
Class description:
Get the when scheduled time. It may be from about a minute to about 1 week. If the schedule is not active return a None This class deals with extracting information from the time and DOW fields of a schedule. DOW mon=1, tue=2, wed=4, thu=8, fri... | 6444ed0b4c38ab59b9e419e4d54d65d598e6a54e | <|skeleton|>
class SchedTime:
"""Get the when scheduled time. It may be from about a minute to about 1 week. If the schedule is not active return a None This class deals with extracting information from the time and DOW fields of a schedule. DOW mon=1, tue=2, wed=4, thu=8, fri=16, sat=32, sun=64 weekday mon=0, tue=... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SchedTime:
"""Get the when scheduled time. It may be from about a minute to about 1 week. If the schedule is not active return a None This class deals with extracting information from the time and DOW fields of a schedule. DOW mon=1, tue=2, wed=4, thu=8, fri=16, sat=32, sun=64 weekday mon=0, tue=1, wed=2, thu... | the_stack_v2_python_sparse | src/Modules/Scheduling/schedule.py | bopopescu/PyHouse_1 | train | 0 |
7604342b678825c5d9abd8bb90c988a912beb159 | [
"form = UserSignUpForm({'username': 'test', 'password1': 'tH1$isA7357', 'password2': 'tH1$isA7357'})\nself.assertFalse(form.is_valid())\nform = UserSignUpForm({'username': 'test', 'email': 'test@test.com', 'password1': 'tH1$isA7357', 'password2': 'tH1$isA7357'})\nself.assertTrue(form.is_valid())",
"test_user = Us... | <|body_start_0|>
form = UserSignUpForm({'username': 'test', 'password1': 'tH1$isA7357', 'password2': 'tH1$isA7357'})
self.assertFalse(form.is_valid())
form = UserSignUpForm({'username': 'test', 'email': 'test@test.com', 'password1': 'tH1$isA7357', 'password2': 'tH1$isA7357'})
self.assert... | Class to test user sign up form. | UserSignUpFormTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserSignUpFormTestCase:
"""Class to test user sign up form."""
def test_requires_email(self):
"""The email field is required, and submitted forms should only be valid if it is completed"""
<|body_0|>
def test_email_must_be_unique(self):
"""The email cannot alread... | stack_v2_sparse_classes_75kplus_train_003689 | 1,282 | no_license | [
{
"docstring": "The email field is required, and submitted forms should only be valid if it is completed",
"name": "test_requires_email",
"signature": "def test_requires_email(self)"
},
{
"docstring": "The email cannot already have a user assoctaed with it.",
"name": "test_email_must_be_uniq... | 2 | stack_v2_sparse_classes_30k_train_026293 | Implement the Python class `UserSignUpFormTestCase` described below.
Class description:
Class to test user sign up form.
Method signatures and docstrings:
- def test_requires_email(self): The email field is required, and submitted forms should only be valid if it is completed
- def test_email_must_be_unique(self): Th... | Implement the Python class `UserSignUpFormTestCase` described below.
Class description:
Class to test user sign up form.
Method signatures and docstrings:
- def test_requires_email(self): The email field is required, and submitted forms should only be valid if it is completed
- def test_email_must_be_unique(self): Th... | 089126403f135631b72f5a66adb1a219ff7a9fc7 | <|skeleton|>
class UserSignUpFormTestCase:
"""Class to test user sign up form."""
def test_requires_email(self):
"""The email field is required, and submitted forms should only be valid if it is completed"""
<|body_0|>
def test_email_must_be_unique(self):
"""The email cannot alread... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserSignUpFormTestCase:
"""Class to test user sign up form."""
def test_requires_email(self):
"""The email field is required, and submitted forms should only be valid if it is completed"""
form = UserSignUpForm({'username': 'test', 'password1': 'tH1$isA7357', 'password2': 'tH1$isA7357'})
... | the_stack_v2_python_sparse | account/test_forms.py | ASquirrelsTail/issue-tracker | train | 0 |
82bfe30eb8447fab158e2d011bcfe6875f0d55bb | [
"if attrs['password'] != attrs['password2']:\n raise serializers.ValidationError({'password': \"Password fields didn't match.\"})\nreturn attrs",
"user = User.objects.create(username=validated_data['username'], email=validated_data['email'])\nuser.set_password(validated_data['password'])\nuser.save()\nreturn u... | <|body_start_0|>
if attrs['password'] != attrs['password2']:
raise serializers.ValidationError({'password': "Password fields didn't match."})
return attrs
<|end_body_0|>
<|body_start_1|>
user = User.objects.create(username=validated_data['username'], email=validated_data['email'])
... | Serializer for User model | UserSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserSerializer:
"""Serializer for User model"""
def validate(self, attrs):
"""Check that password fields match"""
<|body_0|>
def create(self, validated_data):
"""Method for creating user instance"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
i... | stack_v2_sparse_classes_75kplus_train_003690 | 4,891 | no_license | [
{
"docstring": "Check that password fields match",
"name": "validate",
"signature": "def validate(self, attrs)"
},
{
"docstring": "Method for creating user instance",
"name": "create",
"signature": "def create(self, validated_data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_042043 | Implement the Python class `UserSerializer` described below.
Class description:
Serializer for User model
Method signatures and docstrings:
- def validate(self, attrs): Check that password fields match
- def create(self, validated_data): Method for creating user instance | Implement the Python class `UserSerializer` described below.
Class description:
Serializer for User model
Method signatures and docstrings:
- def validate(self, attrs): Check that password fields match
- def create(self, validated_data): Method for creating user instance
<|skeleton|>
class UserSerializer:
"""Ser... | 407413fa558d24e8f5762e8bdb4778b1ed5fc59f | <|skeleton|>
class UserSerializer:
"""Serializer for User model"""
def validate(self, attrs):
"""Check that password fields match"""
<|body_0|>
def create(self, validated_data):
"""Method for creating user instance"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserSerializer:
"""Serializer for User model"""
def validate(self, attrs):
"""Check that password fields match"""
if attrs['password'] != attrs['password2']:
raise serializers.ValidationError({'password': "Password fields didn't match."})
return attrs
def create(s... | the_stack_v2_python_sparse | tradeplatform/apps/registration/serializers.py | webclinic017/Tradeplatform-1 | train | 0 |
866c5f07f843369d8f12c6aa476e70b828fc45e7 | [
"self.include_labels = True\nif del_existing:\n if os.path.exists(output_path):\n os.remove(output_path)\nelif os.path.exists(output_path):\n raise ValueError('Output path already exists', output_path)\nself.db = h5py.File(output_path, 'w', libver='latest')\nself.feat_dataset = self.db.create_dataset(f... | <|body_start_0|>
self.include_labels = True
if del_existing:
if os.path.exists(output_path):
os.remove(output_path)
elif os.path.exists(output_path):
raise ValueError('Output path already exists', output_path)
self.db = h5py.File(output_path, 'w', ... | HDF5Writer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HDF5Writer:
def __init__(self, dimensions, output_path, feat_key='X', label_key='Y', buf_size=BUF_SIZE, del_existing=False, dtype_feat=np.float32, dtype_label=np.uint8):
"""Create the new HDF5 file for simple 2D matrices :param dimensions: e.g. (# of records, # of features) or (# of imag... | stack_v2_sparse_classes_75kplus_train_003691 | 3,622 | no_license | [
{
"docstring": "Create the new HDF5 file for simple 2D matrices :param dimensions: e.g. (# of records, # of features) or (# of images, height, width, # of channels) :param output_path: full path to the HDF5 file :param feat_key: name of the features data set :param label_key: name of the labels data set :param ... | 5 | stack_v2_sparse_classes_30k_train_044618 | Implement the Python class `HDF5Writer` described below.
Class description:
Implement the HDF5Writer class.
Method signatures and docstrings:
- def __init__(self, dimensions, output_path, feat_key='X', label_key='Y', buf_size=BUF_SIZE, del_existing=False, dtype_feat=np.float32, dtype_label=np.uint8): Create the new H... | Implement the Python class `HDF5Writer` described below.
Class description:
Implement the HDF5Writer class.
Method signatures and docstrings:
- def __init__(self, dimensions, output_path, feat_key='X', label_key='Y', buf_size=BUF_SIZE, del_existing=False, dtype_feat=np.float32, dtype_label=np.uint8): Create the new H... | e9f2010715fa06f50095d05684617c86e18ca661 | <|skeleton|>
class HDF5Writer:
def __init__(self, dimensions, output_path, feat_key='X', label_key='Y', buf_size=BUF_SIZE, del_existing=False, dtype_feat=np.float32, dtype_label=np.uint8):
"""Create the new HDF5 file for simple 2D matrices :param dimensions: e.g. (# of records, # of features) or (# of imag... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HDF5Writer:
def __init__(self, dimensions, output_path, feat_key='X', label_key='Y', buf_size=BUF_SIZE, del_existing=False, dtype_feat=np.float32, dtype_label=np.uint8):
"""Create the new HDF5 file for simple 2D matrices :param dimensions: e.g. (# of records, # of features) or (# of images, height, wi... | the_stack_v2_python_sparse | dltoolkit/iomisc/hdf5writer.py | GeoffBreemer/DLToolkit | train | 2 | |
948adab58674da7eaf6742e4eaaec94567615fb3 | [
"ret = ''\ni = 0\nwhile i < len(s):\n if s[i].isalpha():\n ret += s[i]\n i += 1\n elif s[i].isdigit():\n nums = 0\n while s[i].isdigit():\n nums = nums * 10 + int(s[i])\n i += 1\n elif s[i] == '[':\n count = 1\n j = 1\n while count > 0:... | <|body_start_0|>
ret = ''
i = 0
while i < len(s):
if s[i].isalpha():
ret += s[i]
i += 1
elif s[i].isdigit():
nums = 0
while s[i].isdigit():
nums = nums * 10 + int(s[i])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def decodeString(self, s: str) -> str:
"""递归思想,找出数字和对应括号内的字符串,并对字符串进行递归求解 :param s: :return:"""
<|body_0|>
def decodeString_stack(self, s: str) -> str:
"""栈, 一共四类,字母、数字、[、],注意每种情况的入栈、出栈和条件变更即可 :param s: :return:"""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_75kplus_train_003692 | 2,032 | no_license | [
{
"docstring": "递归思想,找出数字和对应括号内的字符串,并对字符串进行递归求解 :param s: :return:",
"name": "decodeString",
"signature": "def decodeString(self, s: str) -> str"
},
{
"docstring": "栈, 一共四类,字母、数字、[、],注意每种情况的入栈、出栈和条件变更即可 :param s: :return:",
"name": "decodeString_stack",
"signature": "def decodeString_sta... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def decodeString(self, s: str) -> str: 递归思想,找出数字和对应括号内的字符串,并对字符串进行递归求解 :param s: :return:
- def decodeString_stack(self, s: str) -> str: 栈, 一共四类,字母、数字、[、],注意每种情况的入栈、出栈和条件变更即可 :pa... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def decodeString(self, s: str) -> str: 递归思想,找出数字和对应括号内的字符串,并对字符串进行递归求解 :param s: :return:
- def decodeString_stack(self, s: str) -> str: 栈, 一共四类,字母、数字、[、],注意每种情况的入栈、出栈和条件变更即可 :pa... | f2c162654a83c51495ebd161f42a1d0b69caf72d | <|skeleton|>
class Solution:
def decodeString(self, s: str) -> str:
"""递归思想,找出数字和对应括号内的字符串,并对字符串进行递归求解 :param s: :return:"""
<|body_0|>
def decodeString_stack(self, s: str) -> str:
"""栈, 一共四类,字母、数字、[、],注意每种情况的入栈、出栈和条件变更即可 :param s: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def decodeString(self, s: str) -> str:
"""递归思想,找出数字和对应括号内的字符串,并对字符串进行递归求解 :param s: :return:"""
ret = ''
i = 0
while i < len(s):
if s[i].isalpha():
ret += s[i]
i += 1
elif s[i].isdigit():
nums = 0... | the_stack_v2_python_sparse | 394 decodeString.py | ABenxj/leetcode | train | 1 | |
594c58568a7496f5ce748f7a9c32b29a5fa40d20 | [
"if is_single_source:\n return exp\nmerged = defaultdict(list) if is_single_agent else defaultdict(lambda: defaultdict(list))\nfor ex in exp.values():\n if is_single_agent:\n for k, v in ex.items():\n merged[k].extend[v]\n else:\n for agent_id, e in ex.items():\n for k, ... | <|body_start_0|>
if is_single_source:
return exp
merged = defaultdict(list) if is_single_agent else defaultdict(lambda: defaultdict(list))
for ex in exp.values():
if is_single_agent:
for k, v in ex.items():
merged[k].extend[v]
... | ExperienceCollectionUtils | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExperienceCollectionUtils:
def concat(exp, is_single_source: bool=False, is_single_agent: bool=False) -> dict:
"""Concatenate experiences from multiple sources, by agent ID. The experience from each source is expected to be already grouped by agent ID. The result is a single dictionary o... | stack_v2_sparse_classes_75kplus_train_003693 | 2,343 | permissive | [
{
"docstring": "Concatenate experiences from multiple sources, by agent ID. The experience from each source is expected to be already grouped by agent ID. The result is a single dictionary of experiences with keys being agent IDs and values being the concatenation of experiences from all sources for each agent ... | 2 | null | Implement the Python class `ExperienceCollectionUtils` described below.
Class description:
Implement the ExperienceCollectionUtils class.
Method signatures and docstrings:
- def concat(exp, is_single_source: bool=False, is_single_agent: bool=False) -> dict: Concatenate experiences from multiple sources, by agent ID. ... | Implement the Python class `ExperienceCollectionUtils` described below.
Class description:
Implement the ExperienceCollectionUtils class.
Method signatures and docstrings:
- def concat(exp, is_single_source: bool=False, is_single_agent: bool=False) -> dict: Concatenate experiences from multiple sources, by agent ID. ... | c989fc38e4fc281ac808fa50cec4353cc0de8e57 | <|skeleton|>
class ExperienceCollectionUtils:
def concat(exp, is_single_source: bool=False, is_single_agent: bool=False) -> dict:
"""Concatenate experiences from multiple sources, by agent ID. The experience from each source is expected to be already grouped by agent ID. The result is a single dictionary o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExperienceCollectionUtils:
def concat(exp, is_single_source: bool=False, is_single_agent: bool=False) -> dict:
"""Concatenate experiences from multiple sources, by agent ID. The experience from each source is expected to be already grouped by agent ID. The result is a single dictionary of experiences ... | the_stack_v2_python_sparse | maro/rl/utils/experience_collection.py | Jinyu-W/maro | train | 2 | |
afe8b6067b34f46f92dbecbb84f35289887b0026 | [
"super(TrainValueHook, self).__init__()\nself.verb_step = verb_step\nself.loss = loss\nself.write_summary = write_summary\nif self.write_summary:\n assert ckpt_dir is not None\n self.train_mse_summary = HookValueSummary(value_name)\nself.verb = verb",
"self.step += 1\nif self.step % self.verb_step == 0:\n ... | <|body_start_0|>
super(TrainValueHook, self).__init__()
self.verb_step = verb_step
self.loss = loss
self.write_summary = write_summary
if self.write_summary:
assert ckpt_dir is not None
self.train_mse_summary = HookValueSummary(value_name)
self.ver... | This hook monitors performance on the training set | TrainValueHook | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrainValueHook:
"""This hook monitors performance on the training set"""
def __init__(self, verb_step, loss, ckpt_dir=None, value_name='mean_squared_error', write_summary=False, verb=True):
"""Initialize the hook :param verb_step: # steps between every print message :param loss: valu... | stack_v2_sparse_classes_75kplus_train_003694 | 9,701 | permissive | [
{
"docstring": "Initialize the hook :param verb_step: # steps between every print message :param loss: value to log at every verbose step :param ckpt_dir: checkpoint directory, only use it if write_summary is True :param value_name: name of this summary in tensorboard :param write_summary: log summary or not :p... | 2 | null | Implement the Python class `TrainValueHook` described below.
Class description:
This hook monitors performance on the training set
Method signatures and docstrings:
- def __init__(self, verb_step, loss, ckpt_dir=None, value_name='mean_squared_error', write_summary=False, verb=True): Initialize the hook :param verb_st... | Implement the Python class `TrainValueHook` described below.
Class description:
This hook monitors performance on the training set
Method signatures and docstrings:
- def __init__(self, verb_step, loss, ckpt_dir=None, value_name='mean_squared_error', write_summary=False, verb=True): Initialize the hook :param verb_st... | 5fbe62c7309331c0b326cca3c4a5e4aaea55cb7d | <|skeleton|>
class TrainValueHook:
"""This hook monitors performance on the training set"""
def __init__(self, verb_step, loss, ckpt_dir=None, value_name='mean_squared_error', write_summary=False, verb=True):
"""Initialize the hook :param verb_step: # steps between every print message :param loss: valu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TrainValueHook:
"""This hook monitors performance on the training set"""
def __init__(self, verb_step, loss, ckpt_dir=None, value_name='mean_squared_error', write_summary=False, verb=True):
"""Initialize the hook :param verb_step: # steps between every print message :param loss: value to log at e... | the_stack_v2_python_sparse | network_helper.py | chnadell/dlmCN | train | 1 |
bf4de1539026567b345f2737ee45b0e86987bc63 | [
"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... | The price service definition. | PriceServicer | [
"BSD-2-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PriceServicer:
"""The price service definition."""
def GetPrice(self, request, context):
"""A simple RPC. Sends a price for a utility, tariff, type, duration (start, end), and window An empty PricePoint is returned if there are no prices for the given request"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_003695 | 4,782 | permissive | [
{
"docstring": "A simple RPC. Sends a price for a utility, tariff, type, duration (start, end), and window An empty PricePoint is returned if there are no prices for the given request",
"name": "GetPrice",
"signature": "def GetPrice(self, request, context)"
},
{
"docstring": "Sends all available... | 5 | stack_v2_sparse_classes_30k_train_013810 | Implement the Python class `PriceServicer` described below.
Class description:
The price service definition.
Method signatures and docstrings:
- def GetPrice(self, request, context): A simple RPC. Sends a price for a utility, tariff, type, duration (start, end), and window An empty PricePoint is returned if there are... | Implement the Python class `PriceServicer` described below.
Class description:
The price service definition.
Method signatures and docstrings:
- def GetPrice(self, request, context): A simple RPC. Sends a price for a utility, tariff, type, duration (start, end), and window An empty PricePoint is returned if there are... | 1604ae035a3bd81e87a4037326b7935d1f268452 | <|skeleton|>
class PriceServicer:
"""The price service definition."""
def GetPrice(self, request, context):
"""A simple RPC. Sends a price for a utility, tariff, type, duration (start, end), and window An empty PricePoint is returned if there are no prices for the given request"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PriceServicer:
"""The price service definition."""
def GetPrice(self, request, context):
"""A simple RPC. Sends a price for a utility, tariff, type, duration (start, end), and window An empty PricePoint is returned if there are no prices for the given request"""
context.set_code(grpc.Stat... | the_stack_v2_python_sparse | services/price/price_pb2_grpc.py | vishalbelsare/XBOS | train | 1 |
b38563cbe08214f12be818c94df0c37ceb934b55 | [
"super(Devmem, self).__init__(connection, prompt=prompt, newline_chars=newline_chars, runner=runner)\nself.address = address\nself.value = value\nself.size = size\nself.options = options",
"cmd = 'devmem'\nif self.options:\n cmd = '{} {}'.format(cmd, self.options)\ncmd = '{} {}'.format(cmd, self.address)\nif s... | <|body_start_0|>
super(Devmem, self).__init__(connection, prompt=prompt, newline_chars=newline_chars, runner=runner)
self.address = address
self.value = value
self.size = size
self.options = options
<|end_body_0|>
<|body_start_1|>
cmd = 'devmem'
if self.options:
... | Devmem command class. | Devmem | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Devmem:
"""Devmem command class."""
def __init__(self, connection, address, size=None, value=None, options=None, prompt=None, newline_chars=None, runner=None):
"""Devmem command. :param connection: moler connection to device, terminal when command is executed. :param address: memory ... | stack_v2_sparse_classes_75kplus_train_003696 | 3,678 | permissive | [
{
"docstring": "Devmem command. :param connection: moler connection to device, terminal when command is executed. :param address: memory address :param size: size of variable (bites) :param value: value that will be set in memory :param options: parameter with which the command will be executed :param prompt: e... | 4 | stack_v2_sparse_classes_30k_train_011718 | Implement the Python class `Devmem` described below.
Class description:
Devmem command class.
Method signatures and docstrings:
- def __init__(self, connection, address, size=None, value=None, options=None, prompt=None, newline_chars=None, runner=None): Devmem command. :param connection: moler connection to device, t... | Implement the Python class `Devmem` described below.
Class description:
Devmem command class.
Method signatures and docstrings:
- def __init__(self, connection, address, size=None, value=None, options=None, prompt=None, newline_chars=None, runner=None): Devmem command. :param connection: moler connection to device, t... | 5a7bb06807b6e0124c77040367d0c20f42849a4c | <|skeleton|>
class Devmem:
"""Devmem command class."""
def __init__(self, connection, address, size=None, value=None, options=None, prompt=None, newline_chars=None, runner=None):
"""Devmem command. :param connection: moler connection to device, terminal when command is executed. :param address: memory ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Devmem:
"""Devmem command class."""
def __init__(self, connection, address, size=None, value=None, options=None, prompt=None, newline_chars=None, runner=None):
"""Devmem command. :param connection: moler connection to device, terminal when command is executed. :param address: memory address :para... | the_stack_v2_python_sparse | moler/cmd/unix/devmem.py | nokia/moler | train | 60 |
04d7cf372cf79f27dd58a6ffbe47796e7182434c | [
"self.data = data\nself.params = params\nself.allowed_params = ['contributor', 'maintainer']\nself.contributor_valid_schema = Schema(schema={'contributor_id': And(str, lambda contrib: len(contrib.strip()) == 8)})\nself.maintainer_valid_schema = Schema(schema={'maintainer_id': And(str, lambda maintainer_id: len(main... | <|body_start_0|>
self.data = data
self.params = params
self.allowed_params = ['contributor', 'maintainer']
self.contributor_valid_schema = Schema(schema={'contributor_id': And(str, lambda contrib: len(contrib.strip()) == 8)})
self.maintainer_valid_schema = Schema(schema={'maintai... | RejectionSchema | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RejectionSchema:
def __init__(self, data: Dict[str, Any], params: str) -> None:
"""Class for deletion schema Args: data (Dict[str, Any]): incoming request data params (str): query params"""
<|body_0|>
def valid(self) -> Dict[str, str]:
"""Get valid remove schema Retu... | stack_v2_sparse_classes_75kplus_train_003697 | 4,931 | permissive | [
{
"docstring": "Class for deletion schema Args: data (Dict[str, Any]): incoming request data params (str): query params",
"name": "__init__",
"signature": "def __init__(self, data: Dict[str, Any], params: str) -> None"
},
{
"docstring": "Get valid remove schema Returns: Dict[str, str]: schema va... | 2 | null | Implement the Python class `RejectionSchema` described below.
Class description:
Implement the RejectionSchema class.
Method signatures and docstrings:
- def __init__(self, data: Dict[str, Any], params: str) -> None: Class for deletion schema Args: data (Dict[str, Any]): incoming request data params (str): query para... | Implement the Python class `RejectionSchema` described below.
Class description:
Implement the RejectionSchema class.
Method signatures and docstrings:
- def __init__(self, data: Dict[str, Any], params: str) -> None: Class for deletion schema Args: data (Dict[str, Any]): incoming request data params (str): query para... | 49813fda4c270f995afdbc854efaa181b3a867e0 | <|skeleton|>
class RejectionSchema:
def __init__(self, data: Dict[str, Any], params: str) -> None:
"""Class for deletion schema Args: data (Dict[str, Any]): incoming request data params (str): query params"""
<|body_0|>
def valid(self) -> Dict[str, str]:
"""Get valid remove schema Retu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RejectionSchema:
def __init__(self, data: Dict[str, Any], params: str) -> None:
"""Class for deletion schema Args: data (Dict[str, Any]): incoming request data params (str): query params"""
self.data = data
self.params = params
self.allowed_params = ['contributor', 'maintainer'... | the_stack_v2_python_sparse | server/githubsrm/administrator/definitions.py | gitaalekhyapaul/githubsrm | train | 0 | |
37028f5e4fcc1f4527e19d00b4b7a1f9012fcf66 | [
"self.columnNumber = columnNumber\nself.sourceColumnNumber = sourceColumnNumber\nself.hxlTag = hxlTag\nself.languageCode = languageCode\nself.headerText = headerText",
"if self.hxlTag:\n if self.languageCode:\n return self.hxlTag + '/' + self.languageCode\n else:\n return self.hxlTag\nelse:\n ... | <|body_start_0|>
self.columnNumber = columnNumber
self.sourceColumnNumber = sourceColumnNumber
self.hxlTag = hxlTag
self.languageCode = languageCode
self.headerText = headerText
<|end_body_0|>
<|body_start_1|>
if self.hxlTag:
if self.languageCode:
... | The definition of a logical column in the HXL data. | HXLColumn | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HXLColumn:
"""The definition of a logical column in the HXL data."""
def __init__(self, columnNumber=None, sourceColumnNumber=None, hxlTag=None, languageCode=None, headerText=None):
"""Initialise a column definition. @param columnNumber the logical column number (default: None) @para... | stack_v2_sparse_classes_75kplus_train_003698 | 7,903 | permissive | [
{
"docstring": "Initialise a column definition. @param columnNumber the logical column number (default: None) @param sourceColumnNumber the raw column number in the source dataset (default: None) @param hxlTag the HXL hashtag for the column (default: None) @param languageCode the ISO 639- language code for the ... | 3 | stack_v2_sparse_classes_30k_train_020161 | Implement the Python class `HXLColumn` described below.
Class description:
The definition of a logical column in the HXL data.
Method signatures and docstrings:
- def __init__(self, columnNumber=None, sourceColumnNumber=None, hxlTag=None, languageCode=None, headerText=None): Initialise a column definition. @param col... | Implement the Python class `HXLColumn` described below.
Class description:
The definition of a logical column in the HXL data.
Method signatures and docstrings:
- def __init__(self, columnNumber=None, sourceColumnNumber=None, hxlTag=None, languageCode=None, headerText=None): Initialise a column definition. @param col... | b0209e75789501d99a2fb2df8a30cf55a383065a | <|skeleton|>
class HXLColumn:
"""The definition of a logical column in the HXL data."""
def __init__(self, columnNumber=None, sourceColumnNumber=None, hxlTag=None, languageCode=None, headerText=None):
"""Initialise a column definition. @param columnNumber the logical column number (default: None) @para... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HXLColumn:
"""The definition of a logical column in the HXL data."""
def __init__(self, columnNumber=None, sourceColumnNumber=None, hxlTag=None, languageCode=None, headerText=None):
"""Initialise a column definition. @param columnNumber the logical column number (default: None) @param sourceColum... | the_stack_v2_python_sparse | hxl/model.py | jayvdb/libhxl-python | train | 0 |
a73385757582857689d968ab4ae864af8ef10c2c | [
"visual = ball_game.load_sprite('ball.png')\nboard = ball_game.Board()\nself.assertEqual('<rect(0, 0, 61, 18)>', str(board.get_rect()))\nself.assertEqual('<Sprite sprite(in 0 groups)>', str(board.get_visual()))\nboard.set_limits(5, 10)\nself.assertEqual(5, board.left_limit)\nself.assertEqual(10, board.right_limit)"... | <|body_start_0|>
visual = ball_game.load_sprite('ball.png')
board = ball_game.Board()
self.assertEqual('<rect(0, 0, 61, 18)>', str(board.get_rect()))
self.assertEqual('<Sprite sprite(in 0 groups)>', str(board.get_visual()))
board.set_limits(5, 10)
self.assertEqual(5, boar... | PrimesTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrimesTest:
def test_class_board(self):
"""Method testing the class Board which is controlled by player."""
<|body_0|>
def test_class_ball(self):
"""Method testing the class Ball which is controlled by game logic."""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_75kplus_train_003699 | 1,070 | no_license | [
{
"docstring": "Method testing the class Board which is controlled by player.",
"name": "test_class_board",
"signature": "def test_class_board(self)"
},
{
"docstring": "Method testing the class Ball which is controlled by game logic.",
"name": "test_class_ball",
"signature": "def test_cl... | 2 | stack_v2_sparse_classes_30k_train_005799 | Implement the Python class `PrimesTest` described below.
Class description:
Implement the PrimesTest class.
Method signatures and docstrings:
- def test_class_board(self): Method testing the class Board which is controlled by player.
- def test_class_ball(self): Method testing the class Ball which is controlled by ga... | Implement the Python class `PrimesTest` described below.
Class description:
Implement the PrimesTest class.
Method signatures and docstrings:
- def test_class_board(self): Method testing the class Board which is controlled by player.
- def test_class_ball(self): Method testing the class Ball which is controlled by ga... | d1930cd345c656e774e960696037bdba11a4e9c1 | <|skeleton|>
class PrimesTest:
def test_class_board(self):
"""Method testing the class Board which is controlled by player."""
<|body_0|>
def test_class_ball(self):
"""Method testing the class Ball which is controlled by game logic."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PrimesTest:
def test_class_board(self):
"""Method testing the class Board which is controlled by player."""
visual = ball_game.load_sprite('ball.png')
board = ball_game.Board()
self.assertEqual('<rect(0, 0, 61, 18)>', str(board.get_rect()))
self.assertEqual('<Sprite spr... | the_stack_v2_python_sparse | classes_test.py | PROPERAT/pyCue | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.