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
eef931d2963599de3cceb805614f7fc79c9b8a86
[ "i = 0\nfor j in range(1, len(nums)):\n if nums[j] != nums[j - 1]:\n nums[i + 1] = nums[j]\n i += 1\n j += 1\nreturn i + 1", "i = 0\nfor num in nums[1:]:\n if nums[i] != num:\n i += 1\n nums[i] = num\nreturn i + 1" ]
<|body_start_0|> i = 0 for j in range(1, len(nums)): if nums[j] != nums[j - 1]: nums[i + 1] = nums[j] i += 1 j += 1 return i + 1 <|end_body_0|> <|body_start_1|> i = 0 for num in nums[1:]: if nums[i] != num: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def removeDuplicatesV1(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def removeDuplicates(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> i = 0 for j in range(1, l...
stack_v2_sparse_classes_75kplus_train_066200
587
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "removeDuplicatesV1", "signature": "def removeDuplicatesV1(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "removeDuplicates", "signature": "def removeDuplicates(self, nums)" } ]
2
stack_v2_sparse_classes_30k_train_001731
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def removeDuplicatesV1(self, nums): :type nums: List[int] :rtype: int - def removeDuplicates(self, nums): :type nums: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def removeDuplicatesV1(self, nums): :type nums: List[int] :rtype: int - def removeDuplicates(self, nums): :type nums: List[int] :rtype: int <|skeleton|> class Solution: def...
057ed5c6fe19268f36a1d5051d27b07aae0b63e0
<|skeleton|> class Solution: def removeDuplicatesV1(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def removeDuplicates(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def removeDuplicatesV1(self, nums): """:type nums: List[int] :rtype: int""" i = 0 for j in range(1, len(nums)): if nums[j] != nums[j - 1]: nums[i + 1] = nums[j] i += 1 j += 1 return i + 1 def removeDuplicate...
the_stack_v2_python_sparse
2020/2020-01/23/eugene.py
wavetogether/wave_algorithm_challenge
train
3
687f63423d7be487d2047d7ce4d0d016350369ce
[ "self._logger = logging.getLogger(__name__)\nself.temp_file = str(uuid.uuid4()) + '.tar.gz'\nself.source_gzip = os.path.join(temp_folder, self.temp_file)", "if not (os.path.exists(source_dir_path) and os.access(source_dir_path, os.R_OK)):\n raise MLOpsException('Path: {} does not exist or not readable'.format(...
<|body_start_0|> self._logger = logging.getLogger(__name__) self.temp_file = str(uuid.uuid4()) + '.tar.gz' self.source_gzip = os.path.join(temp_folder, self.temp_file) <|end_body_0|> <|body_start_1|> if not (os.path.exists(source_dir_path) and os.access(source_dir_path, os.R_OK)): ...
Provides API to pack a folder as tar gz archive. This is an internal class which should not be exposed to users of MLOps.
DirectoryPack
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DirectoryPack: """Provides API to pack a folder as tar gz archive. This is an internal class which should not be exposed to users of MLOps.""" def __init__(self, temp_folder='/tmp'): """Perform initialization of the DirectoryPack. :param temp_folder: folder to save a tar gz file :ret...
stack_v2_sparse_classes_75kplus_train_066201
2,096
permissive
[ { "docstring": "Perform initialization of the DirectoryPack. :param temp_folder: folder to save a tar gz file :return:", "name": "__init__", "signature": "def __init__(self, temp_folder='/tmp')" }, { "docstring": "Packs a folder :param source_dir_path: folder to pack :return: path to created tar...
3
stack_v2_sparse_classes_30k_test_000386
Implement the Python class `DirectoryPack` described below. Class description: Provides API to pack a folder as tar gz archive. This is an internal class which should not be exposed to users of MLOps. Method signatures and docstrings: - def __init__(self, temp_folder='/tmp'): Perform initialization of the DirectoryPa...
Implement the Python class `DirectoryPack` described below. Class description: Provides API to pack a folder as tar gz archive. This is an internal class which should not be exposed to users of MLOps. Method signatures and docstrings: - def __init__(self, temp_folder='/tmp'): Perform initialization of the DirectoryPa...
738356ce6d5e691a5d813acafa3f0ff730e76136
<|skeleton|> class DirectoryPack: """Provides API to pack a folder as tar gz archive. This is an internal class which should not be exposed to users of MLOps.""" def __init__(self, temp_folder='/tmp'): """Perform initialization of the DirectoryPack. :param temp_folder: folder to save a tar gz file :ret...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DirectoryPack: """Provides API to pack a folder as tar gz archive. This is an internal class which should not be exposed to users of MLOps.""" def __init__(self, temp_folder='/tmp'): """Perform initialization of the DirectoryPack. :param temp_folder: folder to save a tar gz file :return:""" ...
the_stack_v2_python_sparse
mlops/parallelm/mlops/packer.py
theromis/mlpiper
train
0
a161139a64886902e8f007b34a46617d2614aaa5
[ "self.file_name = file_name\nself.header = None\nself.data = None\nself.model = None\nself._read_file()", "with open(self.file_name, 'rb') as f:\n new_test = struct.unpack('<l', f.read(8)[4:])[0]\nf.close()\nwith open(self.file_name, 'rb') as f:\n old_test = struct.unpack('<h', f.read(6)[4:])[0]\nf.close()\...
<|body_start_0|> self.file_name = file_name self.header = None self.data = None self.model = None self._read_file() <|end_body_0|> <|body_start_1|> with open(self.file_name, 'rb') as f: new_test = struct.unpack('<l', f.read(8)[4:])[0] f.close() ...
A class that holds the information from one file output by a D&P Instruments Model 103F MicroFT or Model 202 TurboFT. Attributes: file_name - The data file name. header - A DpHeader instance holding the header information. data - A DpData instance holding the radiometric information.
DpFile
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DpFile: """A class that holds the information from one file output by a D&P Instruments Model 103F MicroFT or Model 202 TurboFT. Attributes: file_name - The data file name. header - A DpHeader instance holding the header information. data - A DpData instance holding the radiometric information.""...
stack_v2_sparse_classes_75kplus_train_066202
5,404
no_license
[ { "docstring": "DpFile instance constructor. Arguments: file_name - The filename for the data file.", "name": "__init__", "signature": "def __init__(self, file_name)" }, { "docstring": "Read the data file.", "name": "_read_file", "signature": "def _read_file(self)" }, { "docstrin...
4
stack_v2_sparse_classes_30k_train_044215
Implement the Python class `DpFile` described below. Class description: A class that holds the information from one file output by a D&P Instruments Model 103F MicroFT or Model 202 TurboFT. Attributes: file_name - The data file name. header - A DpHeader instance holding the header information. data - A DpData instance...
Implement the Python class `DpFile` described below. Class description: A class that holds the information from one file output by a D&P Instruments Model 103F MicroFT or Model 202 TurboFT. Attributes: file_name - The data file name. header - A DpHeader instance holding the header information. data - A DpData instance...
743167940f700374755ea273b90da66befae1ba4
<|skeleton|> class DpFile: """A class that holds the information from one file output by a D&P Instruments Model 103F MicroFT or Model 202 TurboFT. Attributes: file_name - The data file name. header - A DpHeader instance holding the header information. data - A DpData instance holding the radiometric information.""...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DpFile: """A class that holds the information from one file output by a D&P Instruments Model 103F MicroFT or Model 202 TurboFT. Attributes: file_name - The data file name. header - A DpHeader instance holding the header information. data - A DpData instance holding the radiometric information.""" def __...
the_stack_v2_python_sparse
tes/models/dp_models/dp_file.py
max19951001/TES
train
0
91bc08739a94ee07872811b6f25477d7b6f76648
[ "if value < 5:\n raise serializers.ValidationError('amount must be at least 5$')\nreturn value", "amount = data['amount']\nresponse = stripe.Charge.create(amount=amount, currency='usd', source=data['stripeToken'], description='Donation')\ndatabase_amount = amount * 10\nif response.paid:\n return Donation.ob...
<|body_start_0|> if value < 5: raise serializers.ValidationError('amount must be at least 5$') return value <|end_body_0|> <|body_start_1|> amount = data['amount'] response = stripe.Charge.create(amount=amount, currency='usd', source=data['stripeToken'], description='Donatio...
Donation create serializer.
DonationCreateSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DonationCreateSerializer: """Donation create serializer.""" def validate_amount(self, value): """Ammount validator.""" <|body_0|> def create(self, data): """Handle creation.""" <|body_1|> <|end_skeleton|> <|body_start_0|> if value < 5: ...
stack_v2_sparse_classes_75kplus_train_066203
1,445
no_license
[ { "docstring": "Ammount validator.", "name": "validate_amount", "signature": "def validate_amount(self, value)" }, { "docstring": "Handle creation.", "name": "create", "signature": "def create(self, data)" } ]
2
stack_v2_sparse_classes_30k_train_053939
Implement the Python class `DonationCreateSerializer` described below. Class description: Donation create serializer. Method signatures and docstrings: - def validate_amount(self, value): Ammount validator. - def create(self, data): Handle creation.
Implement the Python class `DonationCreateSerializer` described below. Class description: Donation create serializer. Method signatures and docstrings: - def validate_amount(self, value): Ammount validator. - def create(self, data): Handle creation. <|skeleton|> class DonationCreateSerializer: """Donation create...
e2f4557e2a85405838c6c9f65f1cb8a5f60a35ba
<|skeleton|> class DonationCreateSerializer: """Donation create serializer.""" def validate_amount(self, value): """Ammount validator.""" <|body_0|> def create(self, data): """Handle creation.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DonationCreateSerializer: """Donation create serializer.""" def validate_amount(self, value): """Ammount validator.""" if value < 5: raise serializers.ValidationError('amount must be at least 5$') return value def create(self, data): """Handle creation."""...
the_stack_v2_python_sparse
apps/donations/serializers/donations.py
HebertFerrer/WebMaster-back-end
train
0
2b8151df1079058e084a00ba1af3fbba603dcd48
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn UsedInsight()", "from .entity import Entity\nfrom .resource_reference import ResourceReference\nfrom .resource_visualization import ResourceVisualization\nfrom .usage_details import UsageDetails\nfrom .entity import Entity\nfrom .resou...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return UsedInsight() <|end_body_0|> <|body_start_1|> from .entity import Entity from .resource_reference import ResourceReference from .resource_visualization import ResourceVisualizati...
UsedInsight
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UsedInsight: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UsedInsight: """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: Us...
stack_v2_sparse_classes_75kplus_train_066204
3,435
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: UsedInsight", "name": "create_from_discriminator_value", "signature": "def create_from_discriminator_value(p...
3
null
Implement the Python class `UsedInsight` described below. Class description: Implement the UsedInsight class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UsedInsight: Creates a new instance of the appropriate class based on discriminator value Args:...
Implement the Python class `UsedInsight` described below. Class description: Implement the UsedInsight class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UsedInsight: Creates a new instance of the appropriate class based on discriminator value Args:...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class UsedInsight: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UsedInsight: """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: Us...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UsedInsight: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UsedInsight: """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: UsedInsight""" ...
the_stack_v2_python_sparse
msgraph/generated/models/used_insight.py
microsoftgraph/msgraph-sdk-python
train
135
914c8c5a7fd4554c904087a1b77542ed94136e9e
[ "if not correo:\n raise ValueError(_('The Email must be set'))\ncorreo = self.normalize_email(correo)\nuser = self.model(correo=correo, **extra_fields)\nuser.set_password(password)\nuser.save()\nreturn user", "extra_fields.setdefault('is_staff', True)\nextra_fields.setdefault('is_superuser', True)\nextra_field...
<|body_start_0|> if not correo: raise ValueError(_('The Email must be set')) correo = self.normalize_email(correo) user = self.model(correo=correo, **extra_fields) user.set_password(password) user.save() return user <|end_body_0|> <|body_start_1|> ext...
Custom user model manager where email is the unique identifiers for authentication instead of usernames.
CustomUserManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CustomUserManager: """Custom user model manager where email is the unique identifiers for authentication instead of usernames.""" def create_user(self, correo, password, **extra_fields): """Create and save a User with the given email and password.""" <|body_0|> def creat...
stack_v2_sparse_classes_75kplus_train_066205
4,069
no_license
[ { "docstring": "Create and save a User with the given email and password.", "name": "create_user", "signature": "def create_user(self, correo, password, **extra_fields)" }, { "docstring": "Create and save a SuperUser with the given email and password.", "name": "create_superuser", "signa...
2
stack_v2_sparse_classes_30k_train_039257
Implement the Python class `CustomUserManager` described below. Class description: Custom user model manager where email is the unique identifiers for authentication instead of usernames. Method signatures and docstrings: - def create_user(self, correo, password, **extra_fields): Create and save a User with the given...
Implement the Python class `CustomUserManager` described below. Class description: Custom user model manager where email is the unique identifiers for authentication instead of usernames. Method signatures and docstrings: - def create_user(self, correo, password, **extra_fields): Create and save a User with the given...
8dda723b08355ca5e83a0bdc9b4d920cbde28b5a
<|skeleton|> class CustomUserManager: """Custom user model manager where email is the unique identifiers for authentication instead of usernames.""" def create_user(self, correo, password, **extra_fields): """Create and save a User with the given email and password.""" <|body_0|> def creat...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CustomUserManager: """Custom user model manager where email is the unique identifiers for authentication instead of usernames.""" def create_user(self, correo, password, **extra_fields): """Create and save a User with the given email and password.""" if not correo: raise Value...
the_stack_v2_python_sparse
mysite/users/models.py
iPoe/Mascotas-App
train
0
e125e655a8febcb816ca069eaaa3bbd2076ae4e7
[ "super(Conv1dGenerated, self).__init__()\nself.in_channels = in_channels\nself.out_channels = out_channels\nself.kernel_size = kernel_size\nself.groups = groups\nself.stride = stride\nself.padding = padding\nself.dilation = dilation\nself.bottleneck = nn.Linear(E_1, E_2) if E_1 is not None else nn.Parameter(torch.r...
<|body_start_0|> super(Conv1dGenerated, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = kernel_size self.groups = groups self.stride = stride self.padding = padding self.dilation = dilation self.b...
1D convolution with a kernel generated by a linear transformation of the instrument embedding
Conv1dGenerated
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Conv1dGenerated: """1D convolution with a kernel generated by a linear transformation of the instrument embedding""" def __init__(self, E_1, E_2, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=False): """Arguments: E_1 {int} -- Dimension of th...
stack_v2_sparse_classes_75kplus_train_066206
37,269
no_license
[ { "docstring": "Arguments: E_1 {int} -- Dimension of the instrument embedding E_2 {int} -- Dimension of the instrument embedding bottleneck in_channels {int} -- Number of channels of the input out_channels {int} -- Number of channels of the output kernel_size {int} -- Kernel size of the convolution Keyword Argu...
2
stack_v2_sparse_classes_30k_train_018364
Implement the Python class `Conv1dGenerated` described below. Class description: 1D convolution with a kernel generated by a linear transformation of the instrument embedding Method signatures and docstrings: - def __init__(self, E_1, E_2, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, group...
Implement the Python class `Conv1dGenerated` described below. Class description: 1D convolution with a kernel generated by a linear transformation of the instrument embedding Method signatures and docstrings: - def __init__(self, E_1, E_2, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, group...
7e55a422588c1d1e00f35a3d3a3ff896cce59e18
<|skeleton|> class Conv1dGenerated: """1D convolution with a kernel generated by a linear transformation of the instrument embedding""" def __init__(self, E_1, E_2, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=False): """Arguments: E_1 {int} -- Dimension of th...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Conv1dGenerated: """1D convolution with a kernel generated by a linear transformation of the instrument embedding""" def __init__(self, E_1, E_2, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=False): """Arguments: E_1 {int} -- Dimension of the instrument ...
the_stack_v2_python_sparse
generated/test_pfnet_research_meta_tasnet.py
jansel/pytorch-jit-paritybench
train
35
5bf2f1e93d75a95c089a90df65252a0d1d048a6d
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn EnrollmentTroubleshootingEvent()", "from .device_enrollment_failure_reason import DeviceEnrollmentFailureReason\nfrom .device_enrollment_type import DeviceEnrollmentType\nfrom .device_management_troubleshooting_event import DeviceManag...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return EnrollmentTroubleshootingEvent() <|end_body_0|> <|body_start_1|> from .device_enrollment_failure_reason import DeviceEnrollmentFailureReason from .device_enrollment_type import DeviceEnr...
Event representing an enrollment failure.
EnrollmentTroubleshootingEvent
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EnrollmentTroubleshootingEvent: """Event representing an enrollment failure.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EnrollmentTroubleshootingEvent: """Creates a new instance of the appropriate class based on discriminator value Args: parse_nod...
stack_v2_sparse_classes_75kplus_train_066207
4,636
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: EnrollmentTroubleshootingEvent", "name": "create_from_discriminator_value", "signature": "def create_from_di...
3
null
Implement the Python class `EnrollmentTroubleshootingEvent` described below. Class description: Event representing an enrollment failure. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EnrollmentTroubleshootingEvent: Creates a new instance of the appro...
Implement the Python class `EnrollmentTroubleshootingEvent` described below. Class description: Event representing an enrollment failure. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EnrollmentTroubleshootingEvent: Creates a new instance of the appro...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class EnrollmentTroubleshootingEvent: """Event representing an enrollment failure.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EnrollmentTroubleshootingEvent: """Creates a new instance of the appropriate class based on discriminator value Args: parse_nod...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EnrollmentTroubleshootingEvent: """Event representing an enrollment failure.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EnrollmentTroubleshootingEvent: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse ...
the_stack_v2_python_sparse
msgraph/generated/models/enrollment_troubleshooting_event.py
microsoftgraph/msgraph-sdk-python
train
135
e2d2d36417b139398b4e78c3e833476598b2ba19
[ "self.send_response(200)\nself.send_header('Content-type', 'text/html')\nself.end_headers()\nself.wfile.write(bytes('<html><head><title>Android Runner HTTP Server</title></head>', 'utf-8'))\nself.wfile.write(bytes('<body>', 'utf-8'))\nself.wfile.write(bytes('<p>The Android Runner web server is running successfully!...
<|body_start_0|> self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(bytes('<html><head><title>Android Runner HTTP Server</title></head>', 'utf-8')) self.wfile.write(bytes('<body>', 'utf-8')) self.wfile.write(bytes('<p...
StopRunWebserver
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StopRunWebserver: def do_GET(self): """Handles incoming HTTP GET requests by: - Showing a simple webpage telling that the server is running and ready for accepting requests.""" <|body_0|> def do_POST(self): """Handles incoming HTTP POST requests by: 1. writing the HT...
stack_v2_sparse_classes_75kplus_train_066208
2,507
no_license
[ { "docstring": "Handles incoming HTTP GET requests by: - Showing a simple webpage telling that the server is running and ready for accepting requests.", "name": "do_GET", "signature": "def do_GET(self)" }, { "docstring": "Handles incoming HTTP POST requests by: 1. writing the HTTP POST request p...
2
stack_v2_sparse_classes_30k_train_023910
Implement the Python class `StopRunWebserver` described below. Class description: Implement the StopRunWebserver class. Method signatures and docstrings: - def do_GET(self): Handles incoming HTTP GET requests by: - Showing a simple webpage telling that the server is running and ready for accepting requests. - def do_...
Implement the Python class `StopRunWebserver` described below. Class description: Implement the StopRunWebserver class. Method signatures and docstrings: - def do_GET(self): Handles incoming HTTP GET requests by: - Showing a simple webpage telling that the server is running and ready for accepting requests. - def do_...
f0fe5f815064416ed14aadcad90f89b2674947db
<|skeleton|> class StopRunWebserver: def do_GET(self): """Handles incoming HTTP GET requests by: - Showing a simple webpage telling that the server is running and ready for accepting requests.""" <|body_0|> def do_POST(self): """Handles incoming HTTP POST requests by: 1. writing the HT...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class StopRunWebserver: def do_GET(self): """Handles incoming HTTP GET requests by: - Showing a simple webpage telling that the server is running and ready for accepting requests.""" self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self...
the_stack_v2_python_sparse
AndroidRunner/StopRunWebserver.py
S2-group/android-runner
train
29
037c756c1c6721da6b1b95bcd77e54c144604b72
[ "self.anchor = anchor\nself.sentence = sentence\nself.event_domain = event_domain\nself.event_type = event_type\nself.score = 0\nself._allocate_arrays(max_sentence_length, neighbor_distance)", "int_type = 'int32'\nnum_labels = len(self.event_domain.event_types)\nself.label = np.zeros(num_labels, dtype=int_type)\n...
<|body_start_0|> self.anchor = anchor self.sentence = sentence self.event_domain = event_domain self.event_type = event_type self.score = 0 self._allocate_arrays(max_sentence_length, neighbor_distance) <|end_body_0|> <|body_start_1|> int_type = 'int32' nu...
EventTriggerExample
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EventTriggerExample: def __init__(self, anchor, sentence, event_domain, max_sentence_length, neighbor_distance, event_type=None): """We are given a token, sentence as context, and event_type (present during training) :type anchor: nlplingo.text.text_span.Anchor :type sentence: nlplingo.t...
stack_v2_sparse_classes_75kplus_train_066209
36,438
permissive
[ { "docstring": "We are given a token, sentence as context, and event_type (present during training) :type anchor: nlplingo.text.text_span.Anchor :type sentence: nlplingo.text.text_span.Sentence :type event_domain: nlplingo.event.event_domain.EventDomain :type params: dict :type event_type: str", "name": "__...
2
stack_v2_sparse_classes_30k_train_019623
Implement the Python class `EventTriggerExample` described below. Class description: Implement the EventTriggerExample class. Method signatures and docstrings: - def __init__(self, anchor, sentence, event_domain, max_sentence_length, neighbor_distance, event_type=None): We are given a token, sentence as context, and ...
Implement the Python class `EventTriggerExample` described below. Class description: Implement the EventTriggerExample class. Method signatures and docstrings: - def __init__(self, anchor, sentence, event_domain, max_sentence_length, neighbor_distance, event_type=None): We are given a token, sentence as context, and ...
32ff17b1320937faa3d3ebe727032f4b3e7a353d
<|skeleton|> class EventTriggerExample: def __init__(self, anchor, sentence, event_domain, max_sentence_length, neighbor_distance, event_type=None): """We are given a token, sentence as context, and event_type (present during training) :type anchor: nlplingo.text.text_span.Anchor :type sentence: nlplingo.t...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EventTriggerExample: def __init__(self, anchor, sentence, event_domain, max_sentence_length, neighbor_distance, event_type=None): """We are given a token, sentence as context, and event_type (present during training) :type anchor: nlplingo.text.text_span.Anchor :type sentence: nlplingo.text.text_span....
the_stack_v2_python_sparse
nlplingo/sandbox/misc/event_trigger.py
BBN-E/nlplingo
train
3
b3218b1f63512719bf13a8f67966abd43290d8ef
[ "if model._meta.app_label in UltraTech_APP:\n return self.using\nreturn None", "if model._meta.app_label in UltraTech_APP:\n return self.using\nreturn None", "if obj1._meta.app_label in UltraTech_APP or obj2._meta.app_label in UltraTech_APP:\n return True\nreturn None", "if app_label in UltraTech_APP...
<|body_start_0|> if model._meta.app_label in UltraTech_APP: return self.using return None <|end_body_0|> <|body_start_1|> if model._meta.app_label in UltraTech_APP: return self.using return None <|end_body_1|> <|body_start_2|> if obj1._meta.app_label in ...
A router to control all database operations on models in the auth application.
UltraTechRouter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UltraTechRouter: """A router to control all database operations on models in the auth application.""" def db_for_read(self, model, **hints): """Attempts to read auth models go to auth_db.""" <|body_0|> def db_for_write(self, model, **hints): """Attempts to write ...
stack_v2_sparse_classes_75kplus_train_066210
3,768
no_license
[ { "docstring": "Attempts to read auth models go to auth_db.", "name": "db_for_read", "signature": "def db_for_read(self, model, **hints)" }, { "docstring": "Attempts to write auth models go to auth_db.", "name": "db_for_write", "signature": "def db_for_write(self, model, **hints)" }, ...
4
stack_v2_sparse_classes_30k_train_054590
Implement the Python class `UltraTechRouter` described below. Class description: A router to control all database operations on models in the auth application. Method signatures and docstrings: - def db_for_read(self, model, **hints): Attempts to read auth models go to auth_db. - def db_for_write(self, model, **hints...
Implement the Python class `UltraTechRouter` described below. Class description: A router to control all database operations on models in the auth application. Method signatures and docstrings: - def db_for_read(self, model, **hints): Attempts to read auth models go to auth_db. - def db_for_write(self, model, **hints...
23d31fbeddcd303a7dc90ac9cfbe2c762d61c61e
<|skeleton|> class UltraTechRouter: """A router to control all database operations on models in the auth application.""" def db_for_read(self, model, **hints): """Attempts to read auth models go to auth_db.""" <|body_0|> def db_for_write(self, model, **hints): """Attempts to write ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UltraTechRouter: """A router to control all database operations on models in the auth application.""" def db_for_read(self, model, **hints): """Attempts to read auth models go to auth_db.""" if model._meta.app_label in UltraTech_APP: return self.using return None ...
the_stack_v2_python_sparse
ultratech_fare/settings/routers.py
KONASANI-0143/Dev
train
0
6347ab4ef1ac777104444b8ba2eb96f9ef280896
[ "token = request.cookies.get('token')\nif token:\n try:\n uuid = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256'])['user_id']\n user = User.query.filter_by(uuid=uuid).first()\n except:\n return make_response(render_template('login.html'), 419)\n flash('You already autho...
<|body_start_0|> token = request.cookies.get('token') if token: try: uuid = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256'])['user_id'] user = User.query.filter_by(uuid=uuid).first() except: return make_response(ren...
Login resource Сontains login form Authentication is not required and shouldn't be done
Login
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Login: """Login resource Сontains login form Authentication is not required and shouldn't be done""" def get(self): """Get method Return "login.html" In case of exception can return main page""" <|body_0|> def post(self): """Post method Return redirect to "main.h...
stack_v2_sparse_classes_75kplus_train_066211
2,820
no_license
[ { "docstring": "Get method Return \"login.html\" In case of exception can return main page", "name": "get", "signature": "def get(self)" }, { "docstring": "Post method Return redirect to \"main.html\" if session joining was successful In case of exception can return login page", "name": "pos...
2
stack_v2_sparse_classes_30k_train_001635
Implement the Python class `Login` described below. Class description: Login resource Сontains login form Authentication is not required and shouldn't be done Method signatures and docstrings: - def get(self): Get method Return "login.html" In case of exception can return main page - def post(self): Post method Retur...
Implement the Python class `Login` described below. Class description: Login resource Сontains login form Authentication is not required and shouldn't be done Method signatures and docstrings: - def get(self): Get method Return "login.html" In case of exception can return main page - def post(self): Post method Retur...
a09780621357957e5575aba36391bef161b5137d
<|skeleton|> class Login: """Login resource Сontains login form Authentication is not required and shouldn't be done""" def get(self): """Get method Return "login.html" In case of exception can return main page""" <|body_0|> def post(self): """Post method Return redirect to "main.h...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Login: """Login resource Сontains login form Authentication is not required and shouldn't be done""" def get(self): """Get method Return "login.html" In case of exception can return main page""" token = request.cookies.get('token') if token: try: uuid =...
the_stack_v2_python_sparse
src/resources/login.py
meg4ik/epam_final_project
train
0
8123c2990e6fbfbfc81c9ece296c412ace1c595e
[ "mensajes = getMensajes()\nserialize = self.serializer_class(mensajes, many=True)\nreturn Response(serialize.data, status=status.HTTP_200_OK)", "serializer = self.serializer_class(data=request.data)\nif serializer.is_valid():\n try:\n createMensaje(request.data)\n return Response(serializer.data,...
<|body_start_0|> mensajes = getMensajes() serialize = self.serializer_class(mensajes, many=True) return Response(serialize.data, status=status.HTTP_200_OK) <|end_body_0|> <|body_start_1|> serializer = self.serializer_class(data=request.data) if serializer.is_valid(): ...
Clase que cocntiene el metodo GET y POST de mensaje Args: APIView Herencia
mensageListView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class mensageListView: """Clase que cocntiene el metodo GET y POST de mensaje Args: APIView Herencia""" def get(self, request, format=None): """Metodo GET que retorna la lista de mensajes Args: request ([type]): [description] format ([type], optional): [description]. Defaults to None. Retu...
stack_v2_sparse_classes_75kplus_train_066212
8,545
no_license
[ { "docstring": "Metodo GET que retorna la lista de mensajes Args: request ([type]): [description] format ([type], optional): [description]. Defaults to None. Returns: HTTP200", "name": "get", "signature": "def get(self, request, format=None)" }, { "docstring": "Metodo POST que crear un mensaje A...
2
null
Implement the Python class `mensageListView` described below. Class description: Clase que cocntiene el metodo GET y POST de mensaje Args: APIView Herencia Method signatures and docstrings: - def get(self, request, format=None): Metodo GET que retorna la lista de mensajes Args: request ([type]): [description] format ...
Implement the Python class `mensageListView` described below. Class description: Clase que cocntiene el metodo GET y POST de mensaje Args: APIView Herencia Method signatures and docstrings: - def get(self, request, format=None): Metodo GET que retorna la lista de mensajes Args: request ([type]): [description] format ...
5edfc0fb9316c899dbd5cd5607989300c75ab4e8
<|skeleton|> class mensageListView: """Clase que cocntiene el metodo GET y POST de mensaje Args: APIView Herencia""" def get(self, request, format=None): """Metodo GET que retorna la lista de mensajes Args: request ([type]): [description] format ([type], optional): [description]. Defaults to None. Retu...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class mensageListView: """Clase que cocntiene el metodo GET y POST de mensaje Args: APIView Herencia""" def get(self, request, format=None): """Metodo GET que retorna la lista de mensajes Args: request ([type]): [description] format ([type], optional): [description]. Defaults to None. Returns: HTTP200"...
the_stack_v2_python_sparse
chat_API/views.py
MartinGalvanCastro/ApoyaFem-API
train
0
a09b03ac37f60e776f3b081d59400252b8f20fc4
[ "novo_no = No(dado, None, None)\nif self.cabeca is None:\n self.cabeca = novo_no\n self.rabo = novo_no\nelse:\n novo_no.anterior = self.rabo\n novo_no.proximo = None\n self.rabo.proximo = novo_no\n self.rabo = novo_no", "no_atual = self.cabeca\nwhile no_atual is not None:\n if no_atual.dado =...
<|body_start_0|> novo_no = No(dado, None, None) if self.cabeca is None: self.cabeca = novo_no self.rabo = novo_no else: novo_no.anterior = self.rabo novo_no.proximo = None self.rabo.proximo = novo_no self.rabo = novo_no <|en...
ListaDuplamenteEncadeada
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ListaDuplamenteEncadeada: def acrescentar(self, dado): """Acrescenta um novo no a lista.""" <|body_0|> def remover(self, dado): """Remove um no da lista.""" <|body_1|> def mostrar(self): """Mostra todos os dados da lista.""" <|body_2|> <...
stack_v2_sparse_classes_75kplus_train_066213
3,743
permissive
[ { "docstring": "Acrescenta um novo no a lista.", "name": "acrescentar", "signature": "def acrescentar(self, dado)" }, { "docstring": "Remove um no da lista.", "name": "remover", "signature": "def remover(self, dado)" }, { "docstring": "Mostra todos os dados da lista.", "name"...
3
stack_v2_sparse_classes_30k_train_032118
Implement the Python class `ListaDuplamenteEncadeada` described below. Class description: Implement the ListaDuplamenteEncadeada class. Method signatures and docstrings: - def acrescentar(self, dado): Acrescenta um novo no a lista. - def remover(self, dado): Remove um no da lista. - def mostrar(self): Mostra todos os...
Implement the Python class `ListaDuplamenteEncadeada` described below. Class description: Implement the ListaDuplamenteEncadeada class. Method signatures and docstrings: - def acrescentar(self, dado): Acrescenta um novo no a lista. - def remover(self, dado): Remove um no da lista. - def mostrar(self): Mostra todos os...
8e656f846f2de4783aa59dbed8ff57b9b4b48c09
<|skeleton|> class ListaDuplamenteEncadeada: def acrescentar(self, dado): """Acrescenta um novo no a lista.""" <|body_0|> def remover(self, dado): """Remove um no da lista.""" <|body_1|> def mostrar(self): """Mostra todos os dados da lista.""" <|body_2|> <...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ListaDuplamenteEncadeada: def acrescentar(self, dado): """Acrescenta um novo no a lista.""" novo_no = No(dado, None, None) if self.cabeca is None: self.cabeca = novo_no self.rabo = novo_no else: novo_no.anterior = self.rabo novo_n...
the_stack_v2_python_sparse
UNP/ref/Python/TADs e Classes/TAD_Listas_Duplamente_Encadeadas.py
ed1rac/AulasEstruturasDados
train
8
b87f95828974a114651d6da3830cd65aca75cf03
[ "iris_prefix_found = re.search('^iris', self.metric_name, re.IGNORECASE)\nself.metric_name = self.metric_name if iris_prefix_found else 'iris_{}'.format(self.metric_name)\nself.help_str = '# HELP {} {}'.format(self.metric_name, self.help_str)\nself.type_str = '# TYPE {} {}'.format(self.metric_name, self.type_str)",...
<|body_start_0|> iris_prefix_found = re.search('^iris', self.metric_name, re.IGNORECASE) self.metric_name = self.metric_name if iris_prefix_found else 'iris_{}'.format(self.metric_name) self.help_str = '# HELP {} {}'.format(self.metric_name, self.help_str) self.type_str = '# TYPE {} {}'....
The PromStrBuilder is a class that helps transform a MetricResult into a string in .prom file format :param metric_name: the name of the Metric we want to build a prom string from :param metric_result: the MetricResult of the executed metric we want to build a prom string from :param help_str: the help string that desc...
PromStrBuilder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PromStrBuilder: """The PromStrBuilder is a class that helps transform a MetricResult into a string in .prom file format :param metric_name: the name of the Metric we want to build a prom string from :param metric_result: the MetricResult of the executed metric we want to build a prom string from ...
stack_v2_sparse_classes_75kplus_train_066214
5,963
no_license
[ { "docstring": "Add the iris_ prefix to the metric if it is not in the metric name. Create the help_str and type_str :return: None", "name": "__post_init__", "signature": "def __post_init__(self) -> None" }, { "docstring": "Create the prom string from the metric we executed :return: the metric r...
3
stack_v2_sparse_classes_30k_train_010353
Implement the Python class `PromStrBuilder` described below. Class description: The PromStrBuilder is a class that helps transform a MetricResult into a string in .prom file format :param metric_name: the name of the Metric we want to build a prom string from :param metric_result: the MetricResult of the executed metr...
Implement the Python class `PromStrBuilder` described below. Class description: The PromStrBuilder is a class that helps transform a MetricResult into a string in .prom file format :param metric_name: the name of the Metric we want to build a prom string from :param metric_result: the MetricResult of the executed metr...
e66651af2c4e106d8c05999ac1137a4b9a58f29f
<|skeleton|> class PromStrBuilder: """The PromStrBuilder is a class that helps transform a MetricResult into a string in .prom file format :param metric_name: the name of the Metric we want to build a prom string from :param metric_result: the MetricResult of the executed metric we want to build a prom string from ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PromStrBuilder: """The PromStrBuilder is a class that helps transform a MetricResult into a string in .prom file format :param metric_name: the name of the Metric we want to build a prom string from :param metric_result: the MetricResult of the executed metric we want to build a prom string from :param help_s...
the_stack_v2_python_sparse
iris/utils/prom_helpers.py
dzhang30/Iris
train
0
f795b2c6e314b2c133ad56870cb312102f7fd1ae
[ "MCMC_Sampler.__init__(self, x, lp_f, thin)\nself.max_width = max_width\nself.width = None", "logger.debug('Generating %s MCMC samples', n_samples)\nassert n_samples >= 0, 'number of samples cant be negative'\norder = list(range(self.n_dims))\nL_trace = []\nsamples = np.empty([n_samples, self.n_dims])\nif self.wi...
<|body_start_0|> MCMC_Sampler.__init__(self, x, lp_f, thin) self.max_width = max_width self.width = None <|end_body_0|> <|body_start_1|> logger.debug('Generating %s MCMC samples', n_samples) assert n_samples >= 0, 'number of samples cant be negative' order = list(range(s...
Slice sampling for multivariate continuous probability distributions. It cycles sampling from each conditional using univariate slice sampling.
SliceSampler
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SliceSampler: """Slice sampling for multivariate continuous probability distributions. It cycles sampling from each conditional using univariate slice sampling.""" def __init__(self, x, lp_f, max_width=float('inf'), thin=None): """:param x: initial state :param lp_f: function that re...
stack_v2_sparse_classes_75kplus_train_066215
7,887
permissive
[ { "docstring": ":param x: initial state :param lp_f: function that returns the log prob :param max_width: maximum bracket width :param thin: amount of thinning; if None, no thinning", "name": "__init__", "signature": "def __init__(self, x, lp_f, max_width=float('inf'), thin=None)" }, { "docstrin...
4
stack_v2_sparse_classes_30k_train_018517
Implement the Python class `SliceSampler` described below. Class description: Slice sampling for multivariate continuous probability distributions. It cycles sampling from each conditional using univariate slice sampling. Method signatures and docstrings: - def __init__(self, x, lp_f, max_width=float('inf'), thin=Non...
Implement the Python class `SliceSampler` described below. Class description: Slice sampling for multivariate continuous probability distributions. It cycles sampling from each conditional using univariate slice sampling. Method signatures and docstrings: - def __init__(self, x, lp_f, max_width=float('inf'), thin=Non...
b201b3837b7ce92588e89292c86ca9e988e31c10
<|skeleton|> class SliceSampler: """Slice sampling for multivariate continuous probability distributions. It cycles sampling from each conditional using univariate slice sampling.""" def __init__(self, x, lp_f, max_width=float('inf'), thin=None): """:param x: initial state :param lp_f: function that re...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SliceSampler: """Slice sampling for multivariate continuous probability distributions. It cycles sampling from each conditional using univariate slice sampling.""" def __init__(self, x, lp_f, max_width=float('inf'), thin=None): """:param x: initial state :param lp_f: function that returns the log...
the_stack_v2_python_sparse
experiments/evaluation/mcmc.py
johannbrehmer/manifold-flow
train
233
446f93db141f6f425732417fb84e211bbd69465d
[ "super().__init__()\nself.mha1 = MultiHeadAttention(dm, h)\nself.mha2 = MultiHeadAttention(dm, h)\nself.ffn = point_wise_feed_forward_network(dm, hidden)\nself.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\nself.layernorm2 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\nself.layernorm3 = tf.ke...
<|body_start_0|> super().__init__() self.mha1 = MultiHeadAttention(dm, h) self.mha2 = MultiHeadAttention(dm, h) self.ffn = point_wise_feed_forward_network(dm, hidden) self.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06) self.layernorm2 = tf.keras.layers.Lay...
class DecoderBlock
DecoderBlock
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DecoderBlock: """class DecoderBlock""" def __init__(self, dm, h, hidden, drop_rate=0.1): """* dm - the dimensionality of the model * h - the number of heads * hidden - the number of hidden units in the fully connected layer * drop_rate - the dropout rate Sets the following public ins...
stack_v2_sparse_classes_75kplus_train_066216
18,002
no_license
[ { "docstring": "* dm - the dimensionality of the model * h - the number of heads * hidden - the number of hidden units in the fully connected layer * drop_rate - the dropout rate Sets the following public instance attributes: * mha1 - the first MultiHeadAttention layer * mha2 - the second MultiHeadAttention lay...
2
stack_v2_sparse_classes_30k_train_047873
Implement the Python class `DecoderBlock` described below. Class description: class DecoderBlock Method signatures and docstrings: - def __init__(self, dm, h, hidden, drop_rate=0.1): * dm - the dimensionality of the model * h - the number of heads * hidden - the number of hidden units in the fully connected layer * d...
Implement the Python class `DecoderBlock` described below. Class description: class DecoderBlock Method signatures and docstrings: - def __init__(self, dm, h, hidden, drop_rate=0.1): * dm - the dimensionality of the model * h - the number of heads * hidden - the number of hidden units in the fully connected layer * d...
8ad4c2594ff78b345dbd92e9d54d2a143ac4071a
<|skeleton|> class DecoderBlock: """class DecoderBlock""" def __init__(self, dm, h, hidden, drop_rate=0.1): """* dm - the dimensionality of the model * h - the number of heads * hidden - the number of hidden units in the fully connected layer * drop_rate - the dropout rate Sets the following public ins...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DecoderBlock: """class DecoderBlock""" def __init__(self, dm, h, hidden, drop_rate=0.1): """* dm - the dimensionality of the model * h - the number of heads * hidden - the number of hidden units in the fully connected layer * drop_rate - the dropout rate Sets the following public instance attribu...
the_stack_v2_python_sparse
supervised_learning/0x12-transformer_apps/5-transformer.py
jorgezafra94/holbertonschool-machine_learning
train
1
2d9fe3a28440caaa4483df7b8fa14d4b2cc5699f
[ "vals = []\n\ndef ser(node):\n if node is None:\n vals.append('#')\n return\n vals.append(str(node.val))\n ser(node.left)\n ser(node.right)\nser(root)\nreturn ' '.join(vals)", "vals = data.split().__iter__()\n\ndef de(iterv):\n v = next(iterv)\n if v == '#':\n return None\n ...
<|body_start_0|> vals = [] def ser(node): if node is None: vals.append('#') return vals.append(str(node.val)) ser(node.left) ser(node.right) ser(root) return ' '.join(vals) <|end_body_0|> <|body_start_1|> ...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_75kplus_train_066217
1,076
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_019252
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
80e44f4e9d3a5b592fdebe0bf16d1df54e99991e
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" vals = [] def ser(node): if node is None: vals.append('#') return vals.append(str(node.val)) ser(node.left) ...
the_stack_v2_python_sparse
Python/297 - Serialize and Deserialize Binary Tree/297_serialize-and-deserialize-binary-tree.py
aptend/leetcode-rua
train
2
468baf1e64e993c75261dca4da26a130cda50195
[ "a = nums[0]\nwhile a != nums[a]:\n temp = nums[a]\n nums[a] = a\n a = temp\nreturn a", "ans = 1\nl, r = (1, len(nums) - 1)\nwhile l <= r:\n m = (l + r) // 2\n n_smaller = sum((1 for n in nums if n < m))\n if n_smaller >= m:\n r = m - 1\n else:\n ans = m\n l = m + 1\nretu...
<|body_start_0|> a = nums[0] while a != nums[a]: temp = nums[a] nums[a] = a a = temp return a <|end_body_0|> <|body_start_1|> ans = 1 l, r = (1, len(nums) - 1) while l <= r: m = (l + r) // 2 n_smaller = sum((1 f...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findDuplicate(self, nums: List[int]) -> int: """In-place O(N) / O(1)""" <|body_0|> def findDuplicate(self, nums: List[int]) -> int: """특정 숫자 m보다 작은 원소의 갯수가 m개 이상이면 그보다 작은 숫자에 겹치는 숫자가 있다는 뜻. (m-1개 이하이면 그와 같거나 큰 숫자에 정답이 있다) Binary Search로 해결. 미친 솔루션. 이렇게 ...
stack_v2_sparse_classes_75kplus_train_066218
1,969
no_license
[ { "docstring": "In-place O(N) / O(1)", "name": "findDuplicate", "signature": "def findDuplicate(self, nums: List[int]) -> int" }, { "docstring": "특정 숫자 m보다 작은 원소의 갯수가 m개 이상이면 그보다 작은 숫자에 겹치는 숫자가 있다는 뜻. (m-1개 이하이면 그와 같거나 큰 숫자에 정답이 있다) Binary Search로 해결. 미친 솔루션. 이렇게 정답 자체를 가정하고, 범위를 줄여가면서 푸는 테크닉을 알...
3
stack_v2_sparse_classes_30k_train_003956
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findDuplicate(self, nums: List[int]) -> int: In-place O(N) / O(1) - def findDuplicate(self, nums: List[int]) -> int: 특정 숫자 m보다 작은 원소의 갯수가 m개 이상이면 그보다 작은 숫자에 겹치는 숫자가 있다는 뜻. (m...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findDuplicate(self, nums: List[int]) -> int: In-place O(N) / O(1) - def findDuplicate(self, nums: List[int]) -> int: 특정 숫자 m보다 작은 원소의 갯수가 m개 이상이면 그보다 작은 숫자에 겹치는 숫자가 있다는 뜻. (m...
c26aef2a59e5cc2d9b0658b9c7386a43267ff8a1
<|skeleton|> class Solution: def findDuplicate(self, nums: List[int]) -> int: """In-place O(N) / O(1)""" <|body_0|> def findDuplicate(self, nums: List[int]) -> int: """특정 숫자 m보다 작은 원소의 갯수가 m개 이상이면 그보다 작은 숫자에 겹치는 숫자가 있다는 뜻. (m-1개 이하이면 그와 같거나 큰 숫자에 정답이 있다) Binary Search로 해결. 미친 솔루션. 이렇게 ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def findDuplicate(self, nums: List[int]) -> int: """In-place O(N) / O(1)""" a = nums[0] while a != nums[a]: temp = nums[a] nums[a] = a a = temp return a def findDuplicate(self, nums: List[int]) -> int: """특정 숫자 m보다 작은 원...
the_stack_v2_python_sparse
Leetcode/287.py
hanwgyu/algorithm_problem_solving
train
5
c3f0fe9a653b0155515eb8cee94077a084f3347d
[ "if id is not None:\n self.id = id\nelse:\n Base.__nb_objects = Base.__nb_objects + 1\n self.id = Base.__nb_objects", "if list_dictionaries is None:\n return '[]'\nelse:\n return json.dumps(list_dictionaries)", "new_list = []\nfilename = '{}.json'.format(cls.__name__)\nif list_objs is None:\n ...
<|body_start_0|> if id is not None: self.id = id else: Base.__nb_objects = Base.__nb_objects + 1 self.id = Base.__nb_objects <|end_body_0|> <|body_start_1|> if list_dictionaries is None: return '[]' else: return json.dumps(list...
Class: Base
Base
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Base: """Class: Base""" def __init__(self, id=None): """Initialization method""" <|body_0|> def to_json_string(list_dictionaries): """returns JSON string repr. of object""" <|body_1|> def save_to_file(cls, list_objs): """writes JSON string re...
stack_v2_sparse_classes_75kplus_train_066219
2,236
no_license
[ { "docstring": "Initialization method", "name": "__init__", "signature": "def __init__(self, id=None)" }, { "docstring": "returns JSON string repr. of object", "name": "to_json_string", "signature": "def to_json_string(list_dictionaries)" }, { "docstring": "writes JSON string rep...
6
null
Implement the Python class `Base` described below. Class description: Class: Base Method signatures and docstrings: - def __init__(self, id=None): Initialization method - def to_json_string(list_dictionaries): returns JSON string repr. of object - def save_to_file(cls, list_objs): writes JSON string repr. of object -...
Implement the Python class `Base` described below. Class description: Class: Base Method signatures and docstrings: - def __init__(self, id=None): Initialization method - def to_json_string(list_dictionaries): returns JSON string repr. of object - def save_to_file(cls, list_objs): writes JSON string repr. of object -...
db6d8994e5cd8ec6a0a62af72d28b23ef755d5b0
<|skeleton|> class Base: """Class: Base""" def __init__(self, id=None): """Initialization method""" <|body_0|> def to_json_string(list_dictionaries): """returns JSON string repr. of object""" <|body_1|> def save_to_file(cls, list_objs): """writes JSON string re...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Base: """Class: Base""" def __init__(self, id=None): """Initialization method""" if id is not None: self.id = id else: Base.__nb_objects = Base.__nb_objects + 1 self.id = Base.__nb_objects def to_json_string(list_dictionaries): """r...
the_stack_v2_python_sparse
0x0C-python-almost_a_circle/models/base.py
jerelhenderson/holbertonschool-higher_level_programming
train
0
f82913e2b5b06dd4434667300fc86b4e96daa857
[ "duplicated_nums = []\nfor i in range(len(nums)):\n num = nums[abs(nums[i]) - 1]\n if num < 0:\n duplicated_nums.append(abs(nums[i]))\n else:\n nums[abs(nums[i]) - 1] = -num\nreturn duplicated_nums", "num_dict = {}\nfor num in nums:\n num_dict[num] = num_dict.get(num, 0) + 1\nreturn [num...
<|body_start_0|> duplicated_nums = [] for i in range(len(nums)): num = nums[abs(nums[i]) - 1] if num < 0: duplicated_nums.append(abs(nums[i])) else: nums[abs(nums[i]) - 1] = -num return duplicated_nums <|end_body_0|> <|body_sta...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findDuplicates(self, nums): """:type nums: List[int] :rtype: List[int]""" <|body_0|> def hashTable(self, nums): """Hash table method, easy. time O(n) but space O(n)""" <|body_1|> def SortandSearch(self, nums): """This use bubble sor...
stack_v2_sparse_classes_75kplus_train_066220
2,318
no_license
[ { "docstring": ":type nums: List[int] :rtype: List[int]", "name": "findDuplicates", "signature": "def findDuplicates(self, nums)" }, { "docstring": "Hash table method, easy. time O(n) but space O(n)", "name": "hashTable", "signature": "def hashTable(self, nums)" }, { "docstring":...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findDuplicates(self, nums): :type nums: List[int] :rtype: List[int] - def hashTable(self, nums): Hash table method, easy. time O(n) but space O(n) - def SortandSearch(self, n...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findDuplicates(self, nums): :type nums: List[int] :rtype: List[int] - def hashTable(self, nums): Hash table method, easy. time O(n) but space O(n) - def SortandSearch(self, n...
54d777e11b91c5debe49c1aef723234c66a5d2cc
<|skeleton|> class Solution: def findDuplicates(self, nums): """:type nums: List[int] :rtype: List[int]""" <|body_0|> def hashTable(self, nums): """Hash table method, easy. time O(n) but space O(n)""" <|body_1|> def SortandSearch(self, nums): """This use bubble sor...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def findDuplicates(self, nums): """:type nums: List[int] :rtype: List[int]""" duplicated_nums = [] for i in range(len(nums)): num = nums[abs(nums[i]) - 1] if num < 0: duplicated_nums.append(abs(nums[i])) else: ...
the_stack_v2_python_sparse
leetcode_solution/array/#442.Find_All_Duplicates_in_an_Array.py
HsiangHung/Code-Challenges
train
0
892cbc07a1524f47caaf9eddeb1e1485bb79c915
[ "data = form.cleaned_data\nself.success_url = reverse('tokens', kwargs={'level': int(data['level']), 'semester': int(data['semester']), 'course': int(data['course'].id)})\nreturn super().form_valid(form)", "context = super().get_context_data(**kwargs)\ncontext['title_text'] = 'Choose Course To View The Tokens'\nc...
<|body_start_0|> data = form.cleaned_data self.success_url = reverse('tokens', kwargs={'level': int(data['level']), 'semester': int(data['semester']), 'course': int(data['course'].id)}) return super().form_valid(form) <|end_body_0|> <|body_start_1|> context = super().get_context_data(**...
View for choosing course tokens that will be displayed. Check that the user's account is still active. Redirects to tokens view on form valid.
ShowTokensView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ShowTokensView: """View for choosing course tokens that will be displayed. Check that the user's account is still active. Redirects to tokens view on form valid.""" def form_valid(self, form): """Compute the success URL and call super.form_valid()""" <|body_0|> def get_c...
stack_v2_sparse_classes_75kplus_train_066221
29,759
no_license
[ { "docstring": "Compute the success URL and call super.form_valid()", "name": "form_valid", "signature": "def form_valid(self, form)" }, { "docstring": "Return the data used in the templates rendering.", "name": "get_context_data", "signature": "def get_context_data(self, **kwargs)" } ...
2
stack_v2_sparse_classes_30k_train_009669
Implement the Python class `ShowTokensView` described below. Class description: View for choosing course tokens that will be displayed. Check that the user's account is still active. Redirects to tokens view on form valid. Method signatures and docstrings: - def form_valid(self, form): Compute the success URL and cal...
Implement the Python class `ShowTokensView` described below. Class description: View for choosing course tokens that will be displayed. Check that the user's account is still active. Redirects to tokens view on form valid. Method signatures and docstrings: - def form_valid(self, form): Compute the success URL and cal...
06bc577d01d3dbf6c425e03dcb903977a38e377c
<|skeleton|> class ShowTokensView: """View for choosing course tokens that will be displayed. Check that the user's account is still active. Redirects to tokens view on form valid.""" def form_valid(self, form): """Compute the success URL and call super.form_valid()""" <|body_0|> def get_c...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ShowTokensView: """View for choosing course tokens that will be displayed. Check that the user's account is still active. Redirects to tokens view on form valid.""" def form_valid(self, form): """Compute the success URL and call super.form_valid()""" data = form.cleaned_data self....
the_stack_v2_python_sparse
cbt/views.py
Festusali/CBTest
train
6
a68b9565a97edec62497eafc94f3d89a1e5616cc
[ "Part = self.old_state.apps.get_model('part', 'part')\nCompany = self.old_state.apps.get_model('company', 'company')\nSupplierPart = self.old_state.apps.get_model('company', 'supplierpart')\npart = Part.objects.create(name='CAP CER 0.1UF 10V X5R 0402', description='CAP CER 0.1UF 10V X5R 0402', purchaseable=True, le...
<|body_start_0|> Part = self.old_state.apps.get_model('part', 'part') Company = self.old_state.apps.get_model('company', 'company') SupplierPart = self.old_state.apps.get_model('company', 'supplierpart') part = Part.objects.create(name='CAP CER 0.1UF 10V X5R 0402', description='CAP CER 0...
Tests for migration 0034-0037 which added and transitioned to the ManufacturerPart model.
TestManufacturerPart
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestManufacturerPart: """Tests for migration 0034-0037 which added and transitioned to the ManufacturerPart model.""" def prepare(self): """Prepare the database by adding some test data 'before' the change: - Part object - Company object (supplier) - SupplierPart object""" <|...
stack_v2_sparse_classes_75kplus_train_066222
12,626
permissive
[ { "docstring": "Prepare the database by adding some test data 'before' the change: - Part object - Company object (supplier) - SupplierPart object", "name": "prepare", "signature": "def prepare(self)" }, { "docstring": "Test that the new companies have been created successfully.", "name": "t...
2
stack_v2_sparse_classes_30k_train_013894
Implement the Python class `TestManufacturerPart` described below. Class description: Tests for migration 0034-0037 which added and transitioned to the ManufacturerPart model. Method signatures and docstrings: - def prepare(self): Prepare the database by adding some test data 'before' the change: - Part object - Comp...
Implement the Python class `TestManufacturerPart` described below. Class description: Tests for migration 0034-0037 which added and transitioned to the ManufacturerPart model. Method signatures and docstrings: - def prepare(self): Prepare the database by adding some test data 'before' the change: - Part object - Comp...
e88a8e99a5f0b201c67a95cba097c729f090d5e2
<|skeleton|> class TestManufacturerPart: """Tests for migration 0034-0037 which added and transitioned to the ManufacturerPart model.""" def prepare(self): """Prepare the database by adding some test data 'before' the change: - Part object - Company object (supplier) - SupplierPart object""" <|...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestManufacturerPart: """Tests for migration 0034-0037 which added and transitioned to the ManufacturerPart model.""" def prepare(self): """Prepare the database by adding some test data 'before' the change: - Part object - Company object (supplier) - SupplierPart object""" Part = self.old...
the_stack_v2_python_sparse
InvenTree/company/test_migrations.py
inventree/InvenTree
train
3,077
e2dde53487c8c9f78fa93b254ddf5aa6204719b5
[ "AliasingCompensation.__init__(self, input_signal=input_signal, maximum_harmonics=maximum_harmonics)\nif resampling_algorithm is None:\n self._resampling_algorithm = sumpf.modules.ResampleSignal.SPECTRUM\nelse:\n self._resampling_algorithm = resampling_algorithm", "if input_signal is None:\n input_signal...
<|body_start_0|> AliasingCompensation.__init__(self, input_signal=input_signal, maximum_harmonics=maximum_harmonics) if resampling_algorithm is None: self._resampling_algorithm = sumpf.modules.ResampleSignal.SPECTRUM else: self._resampling_algorithm = resampling_algorithm...
A class to compensate the aliasing introduced in a nonlinear model using an upsampler. The upsampling factor of the upsampler is chosen such that aliasing is prevented in the whole spectrum of the nonlinearly processed signals.
FullUpsamplingAliasingCompensation
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FullUpsamplingAliasingCompensation: """A class to compensate the aliasing introduced in a nonlinear model using an upsampler. The upsampling factor of the upsampler is chosen such that aliasing is prevented in the whole spectrum of the nonlinearly processed signals.""" def __init__(self, inp...
stack_v2_sparse_classes_75kplus_train_066223
15,804
no_license
[ { "docstring": ":param input_signal: the input signal :type input_signal: sumpf.Signal() :param maximum_harmonics: the maximum harmonics :type maximum_harmonics: int :param resampling_algorithm: the resampling algorithm :type resampling_algorithm: Eg, sumpf.modules.ResampleSignal.SPECTRUM()", "name": "__ini...
5
stack_v2_sparse_classes_30k_train_007088
Implement the Python class `FullUpsamplingAliasingCompensation` described below. Class description: A class to compensate the aliasing introduced in a nonlinear model using an upsampler. The upsampling factor of the upsampler is chosen such that aliasing is prevented in the whole spectrum of the nonlinearly processed ...
Implement the Python class `FullUpsamplingAliasingCompensation` described below. Class description: A class to compensate the aliasing introduced in a nonlinear model using an upsampler. The upsampling factor of the upsampler is chosen such that aliasing is prevented in the whole spectrum of the nonlinearly processed ...
41ba79cddeb8f76ffed1d3435d629e014f7d04c5
<|skeleton|> class FullUpsamplingAliasingCompensation: """A class to compensate the aliasing introduced in a nonlinear model using an upsampler. The upsampling factor of the upsampler is chosen such that aliasing is prevented in the whole spectrum of the nonlinearly processed signals.""" def __init__(self, inp...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FullUpsamplingAliasingCompensation: """A class to compensate the aliasing introduced in a nonlinear model using an upsampler. The upsampling factor of the upsampler is chosen such that aliasing is prevented in the whole spectrum of the nonlinearly processed signals.""" def __init__(self, input_signal=Non...
the_stack_v2_python_sparse
aliasing_compensation/aliasing_compensation_techniques.py
zuowanbushiwo/systemidentifier
train
0
1a6cbdeb85df4e8b27d5761cf29aefcb6a64df72
[ "super(AttentionDecoderRNN, self).__init__()\nself.embed_dim = embed_dim\nself.hidden_dim = self.rnn_dim = rnn_dim\nself.vocab_size = vocab_size\nself.padding_idx = padding_idx\nself.dropout = nn.Dropout(dropout)\nself.num_layers = num_layers\nself.input_feed = input_feed\nself.rnn_type = rnn_type\nself.embedding =...
<|body_start_0|> super(AttentionDecoderRNN, self).__init__() self.embed_dim = embed_dim self.hidden_dim = self.rnn_dim = rnn_dim self.vocab_size = vocab_size self.padding_idx = padding_idx self.dropout = nn.Dropout(dropout) self.num_layers = num_layers sel...
AttentionDecoderRNN
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AttentionDecoderRNN: def __init__(self, embed_dim, rnn_dim, vocab_size, padding_idx, dropout=0.3, num_layers=2, input_feed=True, rnn_type='LSTM'): """Parameters ---------- embed_dim: int The dimensionality of the embedding layer. rnn_dim: int The dimensionality of the decoder RNN hidden ...
stack_v2_sparse_classes_75kplus_train_066224
5,458
no_license
[ { "docstring": "Parameters ---------- embed_dim: int The dimensionality of the embedding layer. rnn_dim: int The dimensionality of the decoder RNN hidden layer / output. Note that this should be the same rnn_dim used in the encoder. vocab_size: int The size of the vocabulary. padding_idx: int The index in the d...
2
null
Implement the Python class `AttentionDecoderRNN` described below. Class description: Implement the AttentionDecoderRNN class. Method signatures and docstrings: - def __init__(self, embed_dim, rnn_dim, vocab_size, padding_idx, dropout=0.3, num_layers=2, input_feed=True, rnn_type='LSTM'): Parameters ---------- embed_di...
Implement the Python class `AttentionDecoderRNN` described below. Class description: Implement the AttentionDecoderRNN class. Method signatures and docstrings: - def __init__(self, embed_dim, rnn_dim, vocab_size, padding_idx, dropout=0.3, num_layers=2, input_feed=True, rnn_type='LSTM'): Parameters ---------- embed_di...
710d7ef3b72c16369e99833fe0aa359e1fb7b2f0
<|skeleton|> class AttentionDecoderRNN: def __init__(self, embed_dim, rnn_dim, vocab_size, padding_idx, dropout=0.3, num_layers=2, input_feed=True, rnn_type='LSTM'): """Parameters ---------- embed_dim: int The dimensionality of the embedding layer. rnn_dim: int The dimensionality of the decoder RNN hidden ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AttentionDecoderRNN: def __init__(self, embed_dim, rnn_dim, vocab_size, padding_idx, dropout=0.3, num_layers=2, input_feed=True, rnn_type='LSTM'): """Parameters ---------- embed_dim: int The dimensionality of the embedding layer. rnn_dim: int The dimensionality of the decoder RNN hidden layer / output...
the_stack_v2_python_sparse
oov/models/seq2seq/modules/attention_decoder_rnn.py
nelson-liu/oov-translation
train
1
2392cf9eb64b0a5add52caed6c8027dd1fbd3b18
[ "n = len(nums)\nif n < 2:\n return False\nif sum(nums) & 1:\n return False\ntarget = sum(nums) // 2\ndp = [0] * (target + 1)\nfor i in range(1, n + 1):\n for j in range(target, nums[i - 1] - 1, -1):\n dp[j] = max(dp[j], dp[j - nums[i - 1]] + nums[i - 1])\n if dp[j] == target:\n ret...
<|body_start_0|> n = len(nums) if n < 2: return False if sum(nums) & 1: return False target = sum(nums) // 2 dp = [0] * (target + 1) for i in range(1, n + 1): for j in range(target, nums[i - 1] - 1, -1): dp[j] = max(dp[j...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def canPartition1(self, nums: List[int]) -> bool: """思路:01背包问题""" <|body_0|> def canPartition2(self, nums: List[int]) -> bool: """思路:01背包问题""" <|body_1|> <|end_skeleton|> <|body_start_0|> n = len(nums) if n < 2: return ...
stack_v2_sparse_classes_75kplus_train_066225
1,998
no_license
[ { "docstring": "思路:01背包问题", "name": "canPartition1", "signature": "def canPartition1(self, nums: List[int]) -> bool" }, { "docstring": "思路:01背包问题", "name": "canPartition2", "signature": "def canPartition2(self, nums: List[int]) -> bool" } ]
2
stack_v2_sparse_classes_30k_val_000903
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canPartition1(self, nums: List[int]) -> bool: 思路:01背包问题 - def canPartition2(self, nums: List[int]) -> bool: 思路:01背包问题
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canPartition1(self, nums: List[int]) -> bool: 思路:01背包问题 - def canPartition2(self, nums: List[int]) -> bool: 思路:01背包问题 <|skeleton|> class Solution: def canPartition1(sel...
e43ee86c5a8cdb808da09b4b6138e10275abadb5
<|skeleton|> class Solution: def canPartition1(self, nums: List[int]) -> bool: """思路:01背包问题""" <|body_0|> def canPartition2(self, nums: List[int]) -> bool: """思路:01背包问题""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def canPartition1(self, nums: List[int]) -> bool: """思路:01背包问题""" n = len(nums) if n < 2: return False if sum(nums) & 1: return False target = sum(nums) // 2 dp = [0] * (target + 1) for i in range(1, n + 1): ...
the_stack_v2_python_sparse
LeetCode/动态规划法(dp)/背包问题/416. 分割等和子集.py
yiming1012/MyLeetCode
train
2
1cb0a3e2cab7ef95893fdb45f6a3f49c16dff589
[ "ys = np.linspace(extent[2], extent[3], shape_native[1] + 1)\nxs = np.linspace(extent[0], extent[1], shape_native[0] + 1)\nfor x in xs:\n plt.plot([x, x], [ys[0], ys[-1]], **self.config_dict)\nfor y in ys:\n plt.plot([xs[0], xs[-1]], [y, y], **self.config_dict)", "try:\n plt.plot(grid[:, 1], grid[:, 0], ...
<|body_start_0|> ys = np.linspace(extent[2], extent[3], shape_native[1] + 1) xs = np.linspace(extent[0], extent[1], shape_native[0] + 1) for x in xs: plt.plot([x, x], [ys[0], ys[-1]], **self.config_dict) for y in ys: plt.plot([xs[0], xs[-1]], [y, y], **self.config...
Plots `Grid2D` data structure that are better visualized as solid lines, for example rectangular lines that are plotted over an image and grids of (y,x) coordinates as lines (as opposed to a scatter of points using the `GridScatter` object). This object wraps the following Matplotlib methods: - plt.plot: https://matplo...
GridPlot
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GridPlot: """Plots `Grid2D` data structure that are better visualized as solid lines, for example rectangular lines that are plotted over an image and grids of (y,x) coordinates as lines (as opposed to a scatter of points using the `GridScatter` object). This object wraps the following Matplotlib...
stack_v2_sparse_classes_75kplus_train_066226
21,101
permissive
[ { "docstring": "Plots a rectangular grid of lines on a plot, using the coordinate system of the figure. The size and shape of the grid is specified by the `extent` and `shape_native` properties of a data structure which will provide the rectangaular grid lines on a suitable coordinate system for the plot. Param...
3
stack_v2_sparse_classes_30k_train_003453
Implement the Python class `GridPlot` described below. Class description: Plots `Grid2D` data structure that are better visualized as solid lines, for example rectangular lines that are plotted over an image and grids of (y,x) coordinates as lines (as opposed to a scatter of points using the `GridScatter` object). Thi...
Implement the Python class `GridPlot` described below. Class description: Plots `Grid2D` data structure that are better visualized as solid lines, for example rectangular lines that are plotted over an image and grids of (y,x) coordinates as lines (as opposed to a scatter of points using the `GridScatter` object). Thi...
c21e8859bdb20737352147b9904797ac99985b73
<|skeleton|> class GridPlot: """Plots `Grid2D` data structure that are better visualized as solid lines, for example rectangular lines that are plotted over an image and grids of (y,x) coordinates as lines (as opposed to a scatter of points using the `GridScatter` object). This object wraps the following Matplotlib...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GridPlot: """Plots `Grid2D` data structure that are better visualized as solid lines, for example rectangular lines that are plotted over an image and grids of (y,x) coordinates as lines (as opposed to a scatter of points using the `GridScatter` object). This object wraps the following Matplotlib methods: - p...
the_stack_v2_python_sparse
autoarray/plot/mat_wrap/wrap/wrap_2d.py
jonathanfrawley/PyAutoArray_copy
train
0
499c539212c14e60b0adecc683c940442d641b4f
[ "try:\n return json.dumps(value)\nexcept TypeError:\n if isinstance(value, _literal_bindparam):\n return value.value\n raise", "if value is None:\n return\nreturn json.loads(value)" ]
<|body_start_0|> try: return json.dumps(value) except TypeError: if isinstance(value, _literal_bindparam): return value.value raise <|end_body_0|> <|body_start_1|> if value is None: return return json.loads(value) <|end_bod...
A json object stored as a string. json encoding/decoding is handled by SQLAlchemy, so this type is database agnostic and is not affected by differences in underlying JSON types implementations.
JSONString
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JSONString: """A json object stored as a string. json encoding/decoding is handled by SQLAlchemy, so this type is database agnostic and is not affected by differences in underlying JSON types implementations.""" def process_bind_param(self, value, dialect): """Encode object to a stri...
stack_v2_sparse_classes_75kplus_train_066227
11,229
permissive
[ { "docstring": "Encode object to a string before inserting into database.", "name": "process_bind_param", "signature": "def process_bind_param(self, value, dialect)" }, { "docstring": "Decode string to an object after selecting from database.", "name": "process_result_value", "signature"...
2
stack_v2_sparse_classes_30k_train_049474
Implement the Python class `JSONString` described below. Class description: A json object stored as a string. json encoding/decoding is handled by SQLAlchemy, so this type is database agnostic and is not affected by differences in underlying JSON types implementations. Method signatures and docstrings: - def process_...
Implement the Python class `JSONString` described below. Class description: A json object stored as a string. json encoding/decoding is handled by SQLAlchemy, so this type is database agnostic and is not affected by differences in underlying JSON types implementations. Method signatures and docstrings: - def process_...
c0de6442e1d7653fad824d75e571802a74eee605
<|skeleton|> class JSONString: """A json object stored as a string. json encoding/decoding is handled by SQLAlchemy, so this type is database agnostic and is not affected by differences in underlying JSON types implementations.""" def process_bind_param(self, value, dialect): """Encode object to a stri...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class JSONString: """A json object stored as a string. json encoding/decoding is handled by SQLAlchemy, so this type is database agnostic and is not affected by differences in underlying JSON types implementations.""" def process_bind_param(self, value, dialect): """Encode object to a string before ins...
the_stack_v2_python_sparse
rest-service/manager_rest/storage/models_base.py
cloudify-cosmo/cloudify-manager
train
146
863ec30c381cea0e13045bab89b662271773de83
[ "self._text_maze = text_maze\nself._wall_char = wall_char\nself._make_odd_sized_walls = make_odd_sized_walls\nself._covered = np.full(text_maze.shape, False, dtype=np.bool)\nself._maze_size = GridCoordinates(*text_maze.shape)\nself._next_start = GridCoordinates(0, 0)\nself._calculated = False\nself._walls = ()", ...
<|body_start_0|> self._text_maze = text_maze self._wall_char = wall_char self._make_odd_sized_walls = make_odd_sized_walls self._covered = np.full(text_maze.shape, False, dtype=np.bool) self._maze_size = GridCoordinates(*text_maze.shape) self._next_start = GridCoordinates...
Calculates a covering of text mazes with overlapping rectangular walls. This class uses a greedy algorithm to try and minimize the number of geoms generated to create a given maze. The solution is not guaranteed to be optimal, but in most cases should result in a significantly smaller number of geoms than if each cell ...
_MazeWallCoveringContext
[ "Apache-2.0", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _MazeWallCoveringContext: """Calculates a covering of text mazes with overlapping rectangular walls. This class uses a greedy algorithm to try and minimize the number of geoms generated to create a given maze. The solution is not guaranteed to be optimal, but in most cases should result in a sign...
stack_v2_sparse_classes_75kplus_train_066228
5,466
permissive
[ { "docstring": "Initializes this _MazeWallCoveringContext. Args: text_maze: A `labmaze.TextGrid` instance. wall_char: (optional) The character that signifies a wall. make_odd_sized_walls: (optional) A boolean, if `True` all wall sections generated span odd numbers of grid cells. This option exists primarily to ...
5
stack_v2_sparse_classes_30k_train_018753
Implement the Python class `_MazeWallCoveringContext` described below. Class description: Calculates a covering of text mazes with overlapping rectangular walls. This class uses a greedy algorithm to try and minimize the number of geoms generated to create a given maze. The solution is not guaranteed to be optimal, bu...
Implement the Python class `_MazeWallCoveringContext` described below. Class description: Calculates a covering of text mazes with overlapping rectangular walls. This class uses a greedy algorithm to try and minimize the number of geoms generated to create a given maze. The solution is not guaranteed to be optimal, bu...
33d3ea2682409ee82bf9c5129ceaf06ab01cd48e
<|skeleton|> class _MazeWallCoveringContext: """Calculates a covering of text mazes with overlapping rectangular walls. This class uses a greedy algorithm to try and minimize the number of geoms generated to create a given maze. The solution is not guaranteed to be optimal, but in most cases should result in a sign...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class _MazeWallCoveringContext: """Calculates a covering of text mazes with overlapping rectangular walls. This class uses a greedy algorithm to try and minimize the number of geoms generated to create a given maze. The solution is not guaranteed to be optimal, but in most cases should result in a significantly sma...
the_stack_v2_python_sparse
src/env/dm_control/dm_control/locomotion/arenas/covering.py
nicklashansen/svea-vit
train
16
a9fa36ae5eab3868b96042f88178ed764c70450a
[ "body_1 = {'reqId': '32位UUID', 'areaCode': 'atYA-A', 'startTime': '20181010' + '06000000', 'endTime': '20181023' + '06000000'}\na = api_v1_analysis_pre_security_passrate(body_1)\ndict_data = json.loads(a)\nself.assertNotEqual(dict_data['results'][0]['num'], 0)", "body_1 = {'reqId': '32位UUID', 'areaCode': 'atYA-A'...
<|body_start_0|> body_1 = {'reqId': '32位UUID', 'areaCode': 'atYA-A', 'startTime': '20181010' + '06000000', 'endTime': '20181023' + '06000000'} a = api_v1_analysis_pre_security_passrate(body_1) dict_data = json.loads(a) self.assertNotEqual(dict_data['results'][0]['num'], 0) <|end_body_0|>...
预安检通过率接口测试回归
TestApiAnalysisPreSecurityPassRate
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestApiAnalysisPreSecurityPassRate: """预安检通过率接口测试回归""" def test_01(self): """查询通过率""" <|body_0|> def test_02(self): """不在当前时间不能查出来""" <|body_1|> def test_03(self): """区域通道不存在时不能查询相关信息""" <|body_2|> def test_04(self): """验...
stack_v2_sparse_classes_75kplus_train_066229
2,178
no_license
[ { "docstring": "查询通过率", "name": "test_01", "signature": "def test_01(self)" }, { "docstring": "不在当前时间不能查出来", "name": "test_02", "signature": "def test_02(self)" }, { "docstring": "区域通道不存在时不能查询相关信息", "name": "test_03", "signature": "def test_03(self)" }, { "docstri...
4
stack_v2_sparse_classes_30k_train_015366
Implement the Python class `TestApiAnalysisPreSecurityPassRate` described below. Class description: 预安检通过率接口测试回归 Method signatures and docstrings: - def test_01(self): 查询通过率 - def test_02(self): 不在当前时间不能查出来 - def test_03(self): 区域通道不存在时不能查询相关信息 - def test_04(self): 验证服务器响应时间小于1S
Implement the Python class `TestApiAnalysisPreSecurityPassRate` described below. Class description: 预安检通过率接口测试回归 Method signatures and docstrings: - def test_01(self): 查询通过率 - def test_02(self): 不在当前时间不能查出来 - def test_03(self): 区域通道不存在时不能查询相关信息 - def test_04(self): 验证服务器响应时间小于1S <|skeleton|> class TestApiAnalysisPre...
aa0749f4a237ee76a61579dc5984635a7127a631
<|skeleton|> class TestApiAnalysisPreSecurityPassRate: """预安检通过率接口测试回归""" def test_01(self): """查询通过率""" <|body_0|> def test_02(self): """不在当前时间不能查出来""" <|body_1|> def test_03(self): """区域通道不存在时不能查询相关信息""" <|body_2|> def test_04(self): """验...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestApiAnalysisPreSecurityPassRate: """预安检通过率接口测试回归""" def test_01(self): """查询通过率""" body_1 = {'reqId': '32位UUID', 'areaCode': 'atYA-A', 'startTime': '20181010' + '06000000', 'endTime': '20181023' + '06000000'} a = api_v1_analysis_pre_security_passrate(body_1) dict_data =...
the_stack_v2_python_sparse
Airport/Auto_return/TestCase/test_data_platform_082.py
jingshiyue/zhongkeyuan_workspace
train
0
f92cd9775dfb2d18325bd58c1947049014b29fc4
[ "if poisonCnt < 1:\n return 0\nbottleCnt = int(math.ceil(math.log2(poisonCnt)))\nreturn bottleCnt", "\"\"\"Suppose: node 5 is poison \"\"\"\nantCnt = int(math.ceil(math.log2(poisonCnt)))\np1 = [1]\np2 = []\nfor i in range(1, antCnt):\n p1.append(1 << i | p1[i - 1])\nfor i in range(0, (len(p1) + 1) // 2):\n ...
<|body_start_0|> if poisonCnt < 1: return 0 bottleCnt = int(math.ceil(math.log2(poisonCnt))) return bottleCnt <|end_body_0|> <|body_start_1|> """Suppose: node 5 is poison """ antCnt = int(math.ceil(math.log2(poisonCnt))) p1 = [1] p2 = [] for i...
Author: xuwei x17133 At 2018/08/02 dsc: 1.use binary mask solve 'mice drink poison' problem. 2.show one posibility on detail. 3.use self.lensi to control output length. 4.use shift move(replacement) left/right to replace multiplication/division. 5.use a special func to convering bianry to string for outputing.
BitMask
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BitMask: """Author: xuwei x17133 At 2018/08/02 dsc: 1.use binary mask solve 'mice drink poison' problem. 2.show one posibility on detail. 3.use self.lensi to control output length. 4.use shift move(replacement) left/right to replace multiplication/division. 5.use a special func to convering bianr...
stack_v2_sparse_classes_75kplus_train_066230
2,313
no_license
[ { "docstring": "find minum count for poison test; if u need detailed process, try to use the 'showCalcuProcess' to show all", "name": "calcuAnimalCnt", "signature": "def calcuAnimalCnt(self, poisonCnt)" }, { "docstring": "Caution: this function is used to show one possibility, no which one is im...
3
stack_v2_sparse_classes_30k_train_018061
Implement the Python class `BitMask` described below. Class description: Author: xuwei x17133 At 2018/08/02 dsc: 1.use binary mask solve 'mice drink poison' problem. 2.show one posibility on detail. 3.use self.lensi to control output length. 4.use shift move(replacement) left/right to replace multiplication/division. ...
Implement the Python class `BitMask` described below. Class description: Author: xuwei x17133 At 2018/08/02 dsc: 1.use binary mask solve 'mice drink poison' problem. 2.show one posibility on detail. 3.use self.lensi to control output length. 4.use shift move(replacement) left/right to replace multiplication/division. ...
886b1bd53d610d33ac861dcded0f0f89dea7aafd
<|skeleton|> class BitMask: """Author: xuwei x17133 At 2018/08/02 dsc: 1.use binary mask solve 'mice drink poison' problem. 2.show one posibility on detail. 3.use self.lensi to control output length. 4.use shift move(replacement) left/right to replace multiplication/division. 5.use a special func to convering bianr...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BitMask: """Author: xuwei x17133 At 2018/08/02 dsc: 1.use binary mask solve 'mice drink poison' problem. 2.show one posibility on detail. 3.use self.lensi to control output length. 4.use shift move(replacement) left/right to replace multiplication/division. 5.use a special func to convering bianry to string f...
the_stack_v2_python_sparse
BitMask/BitMask.py
jeanbond/lintcode
train
1
3dc24a201856c950dcf6e30091767db83e2ffeb2
[ "if not email:\n raise ValueError('Users must have an email')\nuser = self.model(email=email, full_name=full_name, phone=phone)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user", "user = self.create_user(email=email, password=password, full_name=None)\nuser.full_name = 'Administrator'\nuser...
<|body_start_0|> if not email: raise ValueError('Users must have an email') user = self.model(email=email, full_name=full_name, phone=phone) user.set_password(password) user.save(using=self._db) return user <|end_body_0|> <|body_start_1|> user = self.create_u...
Main user manager
CustomUserManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CustomUserManager: """Main user manager""" def create_user(self, full_name, email, phone=None, password=None): """Creates and saves a user with the given phone.""" <|body_0|> def create_superuser(self, email, password): """Creates and saves a superuser with the g...
stack_v2_sparse_classes_75kplus_train_066231
2,505
no_license
[ { "docstring": "Creates and saves a user with the given phone.", "name": "create_user", "signature": "def create_user(self, full_name, email, phone=None, password=None)" }, { "docstring": "Creates and saves a superuser with the given email and password", "name": "create_superuser", "sign...
2
stack_v2_sparse_classes_30k_train_007322
Implement the Python class `CustomUserManager` described below. Class description: Main user manager Method signatures and docstrings: - def create_user(self, full_name, email, phone=None, password=None): Creates and saves a user with the given phone. - def create_superuser(self, email, password): Creates and saves a...
Implement the Python class `CustomUserManager` described below. Class description: Main user manager Method signatures and docstrings: - def create_user(self, full_name, email, phone=None, password=None): Creates and saves a user with the given phone. - def create_superuser(self, email, password): Creates and saves a...
c171ac925c1dce01d2c496847fd30e804764254a
<|skeleton|> class CustomUserManager: """Main user manager""" def create_user(self, full_name, email, phone=None, password=None): """Creates and saves a user with the given phone.""" <|body_0|> def create_superuser(self, email, password): """Creates and saves a superuser with the g...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CustomUserManager: """Main user manager""" def create_user(self, full_name, email, phone=None, password=None): """Creates and saves a user with the given phone.""" if not email: raise ValueError('Users must have an email') user = self.model(email=email, full_name=full_...
the_stack_v2_python_sparse
src/core/users/models.py
zhumakhan/sample-django-project-with-caching
train
1
672cdab38bcbc5817b8d16904c9db78e1612bb42
[ "diagonal = {}\nfor i, lst in enumerate(nums):\n for j, num in enumerate(lst):\n if i + j not in diagonal:\n diagonal[i + j] = []\n diagonal[i + j].append(num)\nrst = []\nfor i in range(len(diagonal)):\n rst.extend(list(reversed(diagonal[i])))\nreturn rst", "rst = []\nfor i, lst in ...
<|body_start_0|> diagonal = {} for i, lst in enumerate(nums): for j, num in enumerate(lst): if i + j not in diagonal: diagonal[i + j] = [] diagonal[i + j].append(num) rst = [] for i in range(len(diagonal)): rst.e...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]: """使用dict存储""" <|body_0|> def findDiagonalOrder_2(self, nums: List[List[int]]) -> List[int]: """使用list存储""" <|body_1|> <|end_skeleton|> <|body_start_0|> diagonal = {} ...
stack_v2_sparse_classes_75kplus_train_066232
1,309
no_license
[ { "docstring": "使用dict存储", "name": "findDiagonalOrder", "signature": "def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]" }, { "docstring": "使用list存储", "name": "findDiagonalOrder_2", "signature": "def findDiagonalOrder_2(self, nums: List[List[int]]) -> List[int]" } ]
2
stack_v2_sparse_classes_30k_train_029437
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]: 使用dict存储 - def findDiagonalOrder_2(self, nums: List[List[int]]) -> List[int]: 使用list存储
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]: 使用dict存储 - def findDiagonalOrder_2(self, nums: List[List[int]]) -> List[int]: 使用list存储 <|skeleton|> class Soluti...
e420eb456086db32d1d6b9576c8dcd73e041cbef
<|skeleton|> class Solution: def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]: """使用dict存储""" <|body_0|> def findDiagonalOrder_2(self, nums: List[List[int]]) -> List[int]: """使用list存储""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]: """使用dict存储""" diagonal = {} for i, lst in enumerate(nums): for j, num in enumerate(lst): if i + j not in diagonal: diagonal[i + j] = [] diagonal[i...
the_stack_v2_python_sparse
TrainFor1024/others/1424.py
yangwei-nlp/LeetCode-Python
train
0
3d3d8bab58ae8312b8f256cdb1fc23b1b535385f
[ "self.capacity = capacity\nself.cache = {}\nself.count_to_node = collections.defaultdict(collections.OrderedDict)\nself.min_count = 0", "if key not in self.cache:\n return -1\nnode = self.cache[key]\ndel self.count_to_node[node.count][key]\nnode.count += 1\nself.count_to_node[node.count][key] = node\nif not se...
<|body_start_0|> self.capacity = capacity self.cache = {} self.count_to_node = collections.defaultdict(collections.OrderedDict) self.min_count = 0 <|end_body_0|> <|body_start_1|> if key not in self.cache: return -1 node = self.cache[key] del self.coun...
LFUCache
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LFUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: None""" <|body_2|> <|end_s...
stack_v2_sparse_classes_75kplus_train_066233
3,450
no_license
[ { "docstring": ":type capacity: int", "name": "__init__", "signature": "def __init__(self, capacity)" }, { "docstring": ":type key: int :rtype: int", "name": "get", "signature": "def get(self, key)" }, { "docstring": ":type key: int :type value: int :rtype: None", "name": "pu...
3
stack_v2_sparse_classes_30k_train_027621
Implement the Python class `LFUCache` described below. Class description: Implement the LFUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: None
Implement the Python class `LFUCache` described below. Class description: Implement the LFUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: None <|sk...
54ff328131bf2ef387292f31a0e2a2c2cf612cdd
<|skeleton|> class LFUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: None""" <|body_2|> <|end_s...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LFUCache: def __init__(self, capacity): """:type capacity: int""" self.capacity = capacity self.cache = {} self.count_to_node = collections.defaultdict(collections.OrderedDict) self.min_count = 0 def get(self, key): """:type key: int :rtype: int""" ...
the_stack_v2_python_sparse
hashtable/460.lfu-cache.py
hjlarry/leetcode
train
0
8c30eb20d96c5c93de83d3c88332c0453ccfb25d
[ "keys = ['times', 'timens', 'encoder', 'counter', 'di']\nself.data = pd.read_csv(fpath, delimiter=' ', header=None)\nself.data.columns = keys\nself.data['timestamp'] = self.data['times'] + 1e-09 * self.data['timens']\nself.data['encoder'] = self.data['encoder'].apply(lambda x: int(x) if int(x) <= 0 else -(int(x) ^ ...
<|body_start_0|> keys = ['times', 'timens', 'encoder', 'counter', 'di'] self.data = pd.read_csv(fpath, delimiter=' ', header=None) self.data.columns = keys self.data['timestamp'] = self.data['times'] + 1e-09 * self.data['timens'] self.data['encoder'] = self.data['encoder'].apply(...
PizzaBoxEncHandlerTxt
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PizzaBoxEncHandlerTxt: def __init__(self, fpath, chunk_size=0): """adds the chunks of data to a list This combines the chunks together and ignores the chunk size to speed things up.""" <|body_0|> def __call__(self, chunk_num): """returns specified chunk number/index ...
stack_v2_sparse_classes_75kplus_train_066234
6,501
permissive
[ { "docstring": "adds the chunks of data to a list This combines the chunks together and ignores the chunk size to speed things up.", "name": "__init__", "signature": "def __init__(self, fpath, chunk_size=0)" }, { "docstring": "returns specified chunk number/index from list of all chunks created"...
2
stack_v2_sparse_classes_30k_train_031784
Implement the Python class `PizzaBoxEncHandlerTxt` described below. Class description: Implement the PizzaBoxEncHandlerTxt class. Method signatures and docstrings: - def __init__(self, fpath, chunk_size=0): adds the chunks of data to a list This combines the chunks together and ignores the chunk size to speed things ...
Implement the Python class `PizzaBoxEncHandlerTxt` described below. Class description: Implement the PizzaBoxEncHandlerTxt class. Method signatures and docstrings: - def __init__(self, fpath, chunk_size=0): adds the chunks of data to a list This combines the chunks together and ignores the chunk size to speed things ...
14638d04636c9784e4dfa3de28b7251120ee27e7
<|skeleton|> class PizzaBoxEncHandlerTxt: def __init__(self, fpath, chunk_size=0): """adds the chunks of data to a list This combines the chunks together and ignores the chunk size to speed things up.""" <|body_0|> def __call__(self, chunk_num): """returns specified chunk number/index ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PizzaBoxEncHandlerTxt: def __init__(self, fpath, chunk_size=0): """adds the chunks of data to a list This combines the chunks together and ignores the chunk size to speed things up.""" keys = ['times', 'timens', 'encoder', 'counter', 'di'] self.data = pd.read_csv(fpath, delimiter=' ', ...
the_stack_v2_python_sparse
startup/11-handlers.py
NSLS-II-QAS/profile_collection
train
0
c23ce6598da18687bd7ae46d14cb5d4914c503b6
[ "self._basis_name = 'Kazhdan-Lusztig'\nCombinatorialFreeModule.__init__(self, M.base_ring(), tuple(M._lattice), prefix=prefix, category=MoebiusAlgebraBases(M))\nE = M.E()\nphi = self.module_morphism(self._to_natural_basis, codomain=E, category=self.category(), triangular='lower', unitriangular=True, key=M._lattice....
<|body_start_0|> self._basis_name = 'Kazhdan-Lusztig' CombinatorialFreeModule.__init__(self, M.base_ring(), tuple(M._lattice), prefix=prefix, category=MoebiusAlgebraBases(M)) E = M.E() phi = self.module_morphism(self._to_natural_basis, codomain=E, category=self.category(), triangular='lo...
The Kazhdan-Lusztig basis of a quantum Möbius algebra. The Kazhdan-Lusztig basis `\\{ B_x \\mid x \\in L \\}` of `M_L` for some lattice `L` is defined by .. MATH:: B_x = \\sum_{y \\geq x} P_{x,y}(q) E_a, where `P_{x,y}(q)` is the Kazhdan-Lusztig polynomial of `L`, following the definition given in [EPW14]_. EXAMPLES: W...
KL
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KL: """The Kazhdan-Lusztig basis of a quantum Möbius algebra. The Kazhdan-Lusztig basis `\\{ B_x \\mid x \\in L \\}` of `M_L` for some lattice `L` is defined by .. MATH:: B_x = \\sum_{y \\geq x} P_{x,y}(q) E_a, where `P_{x,y}(q)` is the Kazhdan-Lusztig polynomial of `L`, following the definition ...
stack_v2_sparse_classes_75kplus_train_066235
26,467
no_license
[ { "docstring": "Initialize ``self``. TESTS:: sage: L = posets.BooleanLattice(4) sage: M = L.quantum_moebius_algebra() sage: TestSuite(M.KL()).run() # long time", "name": "__init__", "signature": "def __init__(self, M, prefix='KL')" }, { "docstring": "Convert the element indexed by ``x`` to the n...
2
stack_v2_sparse_classes_30k_val_000427
Implement the Python class `KL` described below. Class description: The Kazhdan-Lusztig basis of a quantum Möbius algebra. The Kazhdan-Lusztig basis `\\{ B_x \\mid x \\in L \\}` of `M_L` for some lattice `L` is defined by .. MATH:: B_x = \\sum_{y \\geq x} P_{x,y}(q) E_a, where `P_{x,y}(q)` is the Kazhdan-Lusztig polyn...
Implement the Python class `KL` described below. Class description: The Kazhdan-Lusztig basis of a quantum Möbius algebra. The Kazhdan-Lusztig basis `\\{ B_x \\mid x \\in L \\}` of `M_L` for some lattice `L` is defined by .. MATH:: B_x = \\sum_{y \\geq x} P_{x,y}(q) E_a, where `P_{x,y}(q)` is the Kazhdan-Lusztig polyn...
0d9eacbf74e2acffefde93e39f8bcbec745cdaba
<|skeleton|> class KL: """The Kazhdan-Lusztig basis of a quantum Möbius algebra. The Kazhdan-Lusztig basis `\\{ B_x \\mid x \\in L \\}` of `M_L` for some lattice `L` is defined by .. MATH:: B_x = \\sum_{y \\geq x} P_{x,y}(q) E_a, where `P_{x,y}(q)` is the Kazhdan-Lusztig polynomial of `L`, following the definition ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class KL: """The Kazhdan-Lusztig basis of a quantum Möbius algebra. The Kazhdan-Lusztig basis `\\{ B_x \\mid x \\in L \\}` of `M_L` for some lattice `L` is defined by .. MATH:: B_x = \\sum_{y \\geq x} P_{x,y}(q) E_a, where `P_{x,y}(q)` is the Kazhdan-Lusztig polynomial of `L`, following the definition given in [EPW...
the_stack_v2_python_sparse
sage/src/sage/combinat/posets/moebius_algebra.py
bopopescu/geosci
train
0
a16ca73de77154b147c3e70ca080cfec7e490710
[ "self._rng = make_np_rng(rng, which_method=['random_integers', 'shuffle'])\nassert num_batches is None or num_batches >= 0\nself._dataset_size = dataset_size\nif batch_size is None:\n if num_batches is not None:\n batch_size = int(numpy.ceil(self._dataset_size / num_batches))\n else:\n raise Val...
<|body_start_0|> self._rng = make_np_rng(rng, which_method=['random_integers', 'shuffle']) assert num_batches is None or num_batches >= 0 self._dataset_size = dataset_size if batch_size is None: if num_batches is not None: batch_size = int(numpy.ceil(self._dat...
Returns minibatches randomly, but sequential inside each minibatch
BatchwiseShuffledSequentialIterator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BatchwiseShuffledSequentialIterator: """Returns minibatches randomly, but sequential inside each minibatch""" def __init__(self, dataset_size, batch_size, num_batches=None, rng=None): """.. todo:: WRITEME""" <|body_0|> def next(self): """.. todo:: WRITEME""" ...
stack_v2_sparse_classes_75kplus_train_066236
17,332
no_license
[ { "docstring": ".. todo:: WRITEME", "name": "__init__", "signature": "def __init__(self, dataset_size, batch_size, num_batches=None, rng=None)" }, { "docstring": ".. todo:: WRITEME", "name": "next", "signature": "def next(self)" } ]
2
stack_v2_sparse_classes_30k_train_018892
Implement the Python class `BatchwiseShuffledSequentialIterator` described below. Class description: Returns minibatches randomly, but sequential inside each minibatch Method signatures and docstrings: - def __init__(self, dataset_size, batch_size, num_batches=None, rng=None): .. todo:: WRITEME - def next(self): .. t...
Implement the Python class `BatchwiseShuffledSequentialIterator` described below. Class description: Returns minibatches randomly, but sequential inside each minibatch Method signatures and docstrings: - def __init__(self, dataset_size, batch_size, num_batches=None, rng=None): .. todo:: WRITEME - def next(self): .. t...
73b99cdbdb609fecff3cf85e500c1f1bfd589930
<|skeleton|> class BatchwiseShuffledSequentialIterator: """Returns minibatches randomly, but sequential inside each minibatch""" def __init__(self, dataset_size, batch_size, num_batches=None, rng=None): """.. todo:: WRITEME""" <|body_0|> def next(self): """.. todo:: WRITEME""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BatchwiseShuffledSequentialIterator: """Returns minibatches randomly, but sequential inside each minibatch""" def __init__(self, dataset_size, batch_size, num_batches=None, rng=None): """.. todo:: WRITEME""" self._rng = make_np_rng(rng, which_method=['random_integers', 'shuffle']) ...
the_stack_v2_python_sparse
pylearn2/utils/iteration.py
lpigou/chalearn2014
train
2
78c4a417387845f68beff6f4c0d64d25900a554a
[ "from keras.preprocessing.image import ImageDataGenerator\nsuper(Cifar10PreprocessedAugmentDataGenerator, self).__init__(next_batch_size=next_batch_size, path_prefix=path_prefix, filenames=['data_batch_%d' % x for x in range(1, 6)])\nself.datagen = ImageDataGenerator(featurewise_center=True, samplewise_center=False...
<|body_start_0|> from keras.preprocessing.image import ImageDataGenerator super(Cifar10PreprocessedAugmentDataGenerator, self).__init__(next_batch_size=next_batch_size, path_prefix=path_prefix, filenames=['data_batch_%d' % x for x in range(1, 6)]) self.datagen = ImageDataGenerator(featurewise_ce...
Cifar10PreprocessedAugmentDataGenerator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Cifar10PreprocessedAugmentDataGenerator: def __init__(self, next_batch_size, path_prefix='./cifar10_data'): """使用 Keras 处理的数据, 用于训练集 :param next_batch_size: 下一批的数据大小 :param path_prefix: 数据前导路径""" <|body_0|> def generate_augment_batch(self): """产生一批次的数据(可迭代对象, 有限形式) :...
stack_v2_sparse_classes_75kplus_train_066237
7,748
no_license
[ { "docstring": "使用 Keras 处理的数据, 用于训练集 :param next_batch_size: 下一批的数据大小 :param path_prefix: 数据前导路径", "name": "__init__", "signature": "def __init__(self, next_batch_size, path_prefix='./cifar10_data')" }, { "docstring": "产生一批次的数据(可迭代对象, 有限形式) :return: 图像 [BATCH SIZE, HEIGHT, WIDTH, CHANNEL], 标签(O...
2
stack_v2_sparse_classes_30k_test_002538
Implement the Python class `Cifar10PreprocessedAugmentDataGenerator` described below. Class description: Implement the Cifar10PreprocessedAugmentDataGenerator class. Method signatures and docstrings: - def __init__(self, next_batch_size, path_prefix='./cifar10_data'): 使用 Keras 处理的数据, 用于训练集 :param next_batch_size: 下一批...
Implement the Python class `Cifar10PreprocessedAugmentDataGenerator` described below. Class description: Implement the Cifar10PreprocessedAugmentDataGenerator class. Method signatures and docstrings: - def __init__(self, next_batch_size, path_prefix='./cifar10_data'): 使用 Keras 处理的数据, 用于训练集 :param next_batch_size: 下一批...
7fca2e00624b2ea22887f9ae45b56435dbf73418
<|skeleton|> class Cifar10PreprocessedAugmentDataGenerator: def __init__(self, next_batch_size, path_prefix='./cifar10_data'): """使用 Keras 处理的数据, 用于训练集 :param next_batch_size: 下一批的数据大小 :param path_prefix: 数据前导路径""" <|body_0|> def generate_augment_batch(self): """产生一批次的数据(可迭代对象, 有限形式) :...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Cifar10PreprocessedAugmentDataGenerator: def __init__(self, next_batch_size, path_prefix='./cifar10_data'): """使用 Keras 处理的数据, 用于训练集 :param next_batch_size: 下一批的数据大小 :param path_prefix: 数据前导路径""" from keras.preprocessing.image import ImageDataGenerator super(Cifar10PreprocessedAugmentD...
the_stack_v2_python_sparse
homework/cnn_cifar/cifar10_loadFile.py
ddayzzz/machine_learning
train
0
362c935bb20e114323fb3f0cc3734d961070b3c2
[ "self.logo = logo\nself.alternate_logo = alternate_logo\nself.icon = icon\nself.primary_color = primary_color\nself.title = title\nself.additional_properties = additional_properties", "if dictionary is None:\n return None\nlogo = dictionary.get('logo')\nalternate_logo = dictionary.get('alternateLogo')\nicon = ...
<|body_start_0|> self.logo = logo self.alternate_logo = alternate_logo self.icon = icon self.primary_color = primary_color self.title = title self.additional_properties = additional_properties <|end_body_0|> <|body_start_1|> if dictionary is None: ret...
Implementation of the 'Branding' model. All assets are SVGs so can be slightly resized without any issues. Attributes: logo (string): File path of the institution's logo. For white backgrounds designed at 375 x 72, has built in spacing around it to normalize brand sizing. alternate_logo (string): File path of the insti...
Branding
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Branding: """Implementation of the 'Branding' model. All assets are SVGs so can be slightly resized without any issues. Attributes: logo (string): File path of the institution's logo. For white backgrounds designed at 375 x 72, has built in spacing around it to normalize brand sizing. alternate_l...
stack_v2_sparse_classes_75kplus_train_066238
3,029
permissive
[ { "docstring": "Constructor for the Branding class", "name": "__init__", "signature": "def __init__(self, logo=None, alternate_logo=None, icon=None, primary_color=None, title=None, additional_properties={})" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary ...
2
stack_v2_sparse_classes_30k_train_038626
Implement the Python class `Branding` described below. Class description: Implementation of the 'Branding' model. All assets are SVGs so can be slightly resized without any issues. Attributes: logo (string): File path of the institution's logo. For white backgrounds designed at 375 x 72, has built in spacing around it...
Implement the Python class `Branding` described below. Class description: Implementation of the 'Branding' model. All assets are SVGs so can be slightly resized without any issues. Attributes: logo (string): File path of the institution's logo. For white backgrounds designed at 375 x 72, has built in spacing around it...
b2ab1ded435db75c78d42261f5e4acd2a3061487
<|skeleton|> class Branding: """Implementation of the 'Branding' model. All assets are SVGs so can be slightly resized without any issues. Attributes: logo (string): File path of the institution's logo. For white backgrounds designed at 375 x 72, has built in spacing around it to normalize brand sizing. alternate_l...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Branding: """Implementation of the 'Branding' model. All assets are SVGs so can be slightly resized without any issues. Attributes: logo (string): File path of the institution's logo. For white backgrounds designed at 375 x 72, has built in spacing around it to normalize brand sizing. alternate_logo (string):...
the_stack_v2_python_sparse
finicityapi/models/branding.py
monarchmoney/finicity-python
train
0
4459ed2430b5a854ade13b9bd65f81668cf2c59e
[ "serializer = self.get_serializer(data=request.data)\nserializer.is_valid(raise_exception=True)\nserializer.save()\nresponse = Response(serializer.data, status=status.HTTP_201_CREATED)\nuser = self.user\nmerge_cookie_cart_to_redis(request, user, response)\nreturn response", "code = request.query_params.get('code'...
<|body_start_0|> serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() response = Response(serializer.data, status=status.HTTP_201_CREATED) user = self.user merge_cookie_cart_to_redis(request, user, response) ...
QQAuthUserView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QQAuthUserView: def post(self, request): """保存qq登录用户绑定数据 1.获取参数并进行校验(参数完整性,手机号格式,短信验证码是否正确,access_token是否有效) 2.保存绑定用户的数据并签发jwt token 3.返回应答,绑定成功""" <|body_0|> def get(self, request): """获取QQ登录用户的openid并处理 1.获取code并校验 2.获取QQ登录用户的openid 2.1根据code请求QQ服务器获取access_token 2...
stack_v2_sparse_classes_75kplus_train_066239
8,213
permissive
[ { "docstring": "保存qq登录用户绑定数据 1.获取参数并进行校验(参数完整性,手机号格式,短信验证码是否正确,access_token是否有效) 2.保存绑定用户的数据并签发jwt token 3.返回应答,绑定成功", "name": "post", "signature": "def post(self, request)" }, { "docstring": "获取QQ登录用户的openid并处理 1.获取code并校验 2.获取QQ登录用户的openid 2.1根据code请求QQ服务器获取access_token 2.2根据access_token请求QQ服务...
2
stack_v2_sparse_classes_30k_train_018264
Implement the Python class `QQAuthUserView` described below. Class description: Implement the QQAuthUserView class. Method signatures and docstrings: - def post(self, request): 保存qq登录用户绑定数据 1.获取参数并进行校验(参数完整性,手机号格式,短信验证码是否正确,access_token是否有效) 2.保存绑定用户的数据并签发jwt token 3.返回应答,绑定成功 - def get(self, request): 获取QQ登录用户的openi...
Implement the Python class `QQAuthUserView` described below. Class description: Implement the QQAuthUserView class. Method signatures and docstrings: - def post(self, request): 保存qq登录用户绑定数据 1.获取参数并进行校验(参数完整性,手机号格式,短信验证码是否正确,access_token是否有效) 2.保存绑定用户的数据并签发jwt token 3.返回应答,绑定成功 - def get(self, request): 获取QQ登录用户的openi...
faa4443c11d1534642c8dc9f8262f818f489c554
<|skeleton|> class QQAuthUserView: def post(self, request): """保存qq登录用户绑定数据 1.获取参数并进行校验(参数完整性,手机号格式,短信验证码是否正确,access_token是否有效) 2.保存绑定用户的数据并签发jwt token 3.返回应答,绑定成功""" <|body_0|> def get(self, request): """获取QQ登录用户的openid并处理 1.获取code并校验 2.获取QQ登录用户的openid 2.1根据code请求QQ服务器获取access_token 2...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class QQAuthUserView: def post(self, request): """保存qq登录用户绑定数据 1.获取参数并进行校验(参数完整性,手机号格式,短信验证码是否正确,access_token是否有效) 2.保存绑定用户的数据并签发jwt token 3.返回应答,绑定成功""" serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() response =...
the_stack_v2_python_sparse
Ethanyan_mall/Ethanyan_mall/apps/oauth/views.py
wenmingshuo/E-commerce-sites
train
0
2ea516eb208dbcaba9b8e26345298187a8e21f67
[ "self.n = n\nself.m = m\nself.lamb = lamb\nself.R = R\nself.A = A\nself.b = b", "x = cvx.Variable(self.m)\nprob = cvx.Minimize(0)\nfor i in range(self.n):\n for j in range(len(self.A[i])):\n prob += cvx.Minimize(cvx.logistic(self.A[i][j] * x) - self.b[i][j] * (self.A[i][j] * x))\n prob += cvx.Minimiz...
<|body_start_0|> self.n = n self.m = m self.lamb = lamb self.R = R self.A = A self.b = b <|end_body_0|> <|body_start_1|> x = cvx.Variable(self.m) prob = cvx.Minimize(0) for i in range(self.n): for j in range(len(self.A[i])): ...
Optimal
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Optimal: def __init__(self, n, m, A, b, lamb, R): """:param n: int :param m: int :param lamb: float :return: float,float,float""" <|body_0|> def optimal(self): """:return: float, float""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.n = n ...
stack_v2_sparse_classes_75kplus_train_066240
1,330
no_license
[ { "docstring": ":param n: int :param m: int :param lamb: float :return: float,float,float", "name": "__init__", "signature": "def __init__(self, n, m, A, b, lamb, R)" }, { "docstring": ":return: float, float", "name": "optimal", "signature": "def optimal(self)" } ]
2
stack_v2_sparse_classes_30k_train_047298
Implement the Python class `Optimal` described below. Class description: Implement the Optimal class. Method signatures and docstrings: - def __init__(self, n, m, A, b, lamb, R): :param n: int :param m: int :param lamb: float :return: float,float,float - def optimal(self): :return: float, float
Implement the Python class `Optimal` described below. Class description: Implement the Optimal class. Method signatures and docstrings: - def __init__(self, n, m, A, b, lamb, R): :param n: int :param m: int :param lamb: float :return: float,float,float - def optimal(self): :return: float, float <|skeleton|> class Op...
d64010f2299591f337391c642438a483f670cf61
<|skeleton|> class Optimal: def __init__(self, n, m, A, b, lamb, R): """:param n: int :param m: int :param lamb: float :return: float,float,float""" <|body_0|> def optimal(self): """:return: float, float""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Optimal: def __init__(self, n, m, A, b, lamb, R): """:param n: int :param m: int :param lamb: float :return: float,float,float""" self.n = n self.m = m self.lamb = lamb self.R = R self.A = A self.b = b def optimal(self): """:return: float, f...
the_stack_v2_python_sparse
event_trigger_subgrad/optimal.py
kajiyama1126/Doctor_simulation
train
0
6e7fe974bfdb2964c75073d35c1401f4750fea78
[ "super(BasicBlock, self).__init__()\nself.conv1 = conv3x3(in_planes, planes, stride)\nself.bn1 = nn.BatchNorm2d(planes)\nself.conv2 = conv3x3(planes, planes)\nself.bn2 = nn.BatchNorm2d(planes)\nself.shortcut = nn.Sequential()\nif stride != 1 or in_planes != self.expansion * planes:\n self.shortcut = nn.Sequentia...
<|body_start_0|> super(BasicBlock, self).__init__() self.conv1 = conv3x3(in_planes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = conv3x3(planes, planes) self.bn2 = nn.BatchNorm2d(planes) self.shortcut = nn.Sequential() if stride != 1 or in_planes...
The basic block of ResNet.
BasicBlock
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BasicBlock: """The basic block of ResNet.""" def __init__(self, in_planes: int, planes: int, stride: int=1) -> None: """Instantiates the basic block of the network. :param in_planes: the number of input channels :param planes: the number of channels (to be possibly expanded)""" ...
stack_v2_sparse_classes_75kplus_train_066241
7,594
permissive
[ { "docstring": "Instantiates the basic block of the network. :param in_planes: the number of input channels :param planes: the number of channels (to be possibly expanded)", "name": "__init__", "signature": "def __init__(self, in_planes: int, planes: int, stride: int=1) -> None" }, { "docstring"...
2
stack_v2_sparse_classes_30k_train_045789
Implement the Python class `BasicBlock` described below. Class description: The basic block of ResNet. Method signatures and docstrings: - def __init__(self, in_planes: int, planes: int, stride: int=1) -> None: Instantiates the basic block of the network. :param in_planes: the number of input channels :param planes: ...
Implement the Python class `BasicBlock` described below. Class description: The basic block of ResNet. Method signatures and docstrings: - def __init__(self, in_planes: int, planes: int, stride: int=1) -> None: Instantiates the basic block of the network. :param in_planes: the number of input channels :param planes: ...
0e39b1f4791f0444ed3ee4e8c6fc55bfcc2d001c
<|skeleton|> class BasicBlock: """The basic block of ResNet.""" def __init__(self, in_planes: int, planes: int, stride: int=1) -> None: """Instantiates the basic block of the network. :param in_planes: the number of input channels :param planes: the number of channels (to be possibly expanded)""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BasicBlock: """The basic block of ResNet.""" def __init__(self, in_planes: int, planes: int, stride: int=1) -> None: """Instantiates the basic block of the network. :param in_planes: the number of input channels :param planes: the number of channels (to be possibly expanded)""" super(Basi...
the_stack_v2_python_sparse
backbone/ResNet18.py
wutong8023/Continual-MM
train
1
3b21d808c8e8129510e98e92c54df31b72418480
[ "super(MultiHeadedAttention, self).__init__()\nassert d_model % h == 0\nself.d_k = d_model // h\nself.h = h\nself.linears = clones(nn.Linear(d_model, d_model), 4)\nself.attn = None\nself.dropout = nn.Dropout(p=dropout)", "if mask is not None:\n mask = mask.unsqueeze(1)\nnbatches = query.size(0)\nquery, key, va...
<|body_start_0|> super(MultiHeadedAttention, self).__init__() assert d_model % h == 0 self.d_k = d_model // h self.h = h self.linears = clones(nn.Linear(d_model, d_model), 4) self.attn = None self.dropout = nn.Dropout(p=dropout) <|end_body_0|> <|body_start_1|> ...
MultiHeadedAttention
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiHeadedAttention: def __init__(self, h, d_model, dropout=0.1): """Take in model size and number of heads.""" <|body_0|> def forward(self, query, key, value, mask=None, num_outputs=1, attn=None, attn_dropout=True, dependent_posterior=0, temperature=None): """Imple...
stack_v2_sparse_classes_75kplus_train_066242
45,569
no_license
[ { "docstring": "Take in model size and number of heads.", "name": "__init__", "signature": "def __init__(self, h, d_model, dropout=0.1)" }, { "docstring": "Implements Figure 2", "name": "forward", "signature": "def forward(self, query, key, value, mask=None, num_outputs=1, attn=None, att...
2
stack_v2_sparse_classes_30k_train_007808
Implement the Python class `MultiHeadedAttention` described below. Class description: Implement the MultiHeadedAttention class. Method signatures and docstrings: - def __init__(self, h, d_model, dropout=0.1): Take in model size and number of heads. - def forward(self, query, key, value, mask=None, num_outputs=1, attn...
Implement the Python class `MultiHeadedAttention` described below. Class description: Implement the MultiHeadedAttention class. Method signatures and docstrings: - def __init__(self, h, d_model, dropout=0.1): Take in model size and number of heads. - def forward(self, query, key, value, mask=None, num_outputs=1, attn...
63b69e31239b5676616722b25062b74ad9c399f3
<|skeleton|> class MultiHeadedAttention: def __init__(self, h, d_model, dropout=0.1): """Take in model size and number of heads.""" <|body_0|> def forward(self, query, key, value, mask=None, num_outputs=1, attn=None, attn_dropout=True, dependent_posterior=0, temperature=None): """Imple...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MultiHeadedAttention: def __init__(self, h, d_model, dropout=0.1): """Take in model size and number of heads.""" super(MultiHeadedAttention, self).__init__() assert d_model % h == 0 self.d_k = d_model // h self.h = h self.linears = clones(nn.Linear(d_model, d_mo...
the_stack_v2_python_sparse
model.py
da03/energy-network
train
1
7444b5029f2d1205696058eceaf2a7ba9aafa096
[ "ret = self.libssock.SCIONListen(self.fd)\nself.port = self.libssock.SCIONGetPort(self.fd)\nreturn ret", "newfd = self.libssock.SCIONAccept(self.fd)\nlogging.debug('Accepted socket %d' % newfd)\nreturn (ScionBaseSocket(self.proto, self.sciond_addr, newfd), None)" ]
<|body_start_0|> ret = self.libssock.SCIONListen(self.fd) self.port = self.libssock.SCIONGetPort(self.fd) return ret <|end_body_0|> <|body_start_1|> newfd = self.libssock.SCIONAccept(self.fd) logging.debug('Accepted socket %d' % newfd) return (ScionBaseSocket(self.proto,...
Server side wrapper of the SCION Multi-Path Socket.
ScionServerSocket
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ScionServerSocket: """Server side wrapper of the SCION Multi-Path Socket.""" def listen(self): """Setup the socket to receive incoming connection requests. :returns: 0 on success, -1 on failure :rtype: int""" <|body_0|> def accept(self): """Accepts a connection. ...
stack_v2_sparse_classes_75kplus_train_066243
19,489
permissive
[ { "docstring": "Setup the socket to receive incoming connection requests. :returns: 0 on success, -1 on failure :rtype: int", "name": "listen", "signature": "def listen(self)" }, { "docstring": "Accepts a connection. The return value is a pair (conn, address) where conn is a new ScionBaseSocket ...
2
stack_v2_sparse_classes_30k_train_014438
Implement the Python class `ScionServerSocket` described below. Class description: Server side wrapper of the SCION Multi-Path Socket. Method signatures and docstrings: - def listen(self): Setup the socket to receive incoming connection requests. :returns: 0 on success, -1 on failure :rtype: int - def accept(self): A...
Implement the Python class `ScionServerSocket` described below. Class description: Server side wrapper of the SCION Multi-Path Socket. Method signatures and docstrings: - def listen(self): Setup the socket to receive incoming connection requests. :returns: 0 on success, -1 on failure :rtype: int - def accept(self): A...
06f3f0b82dc8a535ce8b0a128282af00a8425a06
<|skeleton|> class ScionServerSocket: """Server side wrapper of the SCION Multi-Path Socket.""" def listen(self): """Setup the socket to receive incoming connection requests. :returns: 0 on success, -1 on failure :rtype: int""" <|body_0|> def accept(self): """Accepts a connection. ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ScionServerSocket: """Server side wrapper of the SCION Multi-Path Socket.""" def listen(self): """Setup the socket to receive incoming connection requests. :returns: 0 on success, -1 on failure :rtype: int""" ret = self.libssock.SCIONListen(self.fd) self.port = self.libssock.SCION...
the_stack_v2_python_sparse
endhost/scion_socket.py
marcoeilers/scion
train
1
6d15a8bef7d7ebcb241c8f923b0370473904210c
[ "self.x_values = x_values\nself.y_values = y_values\nself.poly = np.poly1d(np.polyfit(x_values, y_values, 3))\nself.error = sum(np.square(self.poly(self.x_values) - self.y_values))\nself.min_x = min(x_values)\nself.max_x = max(x_values)", "if self._deriv is None:\n self._deriv = self.poly.deriv()\nreturn self....
<|body_start_0|> self.x_values = x_values self.y_values = y_values self.poly = np.poly1d(np.polyfit(x_values, y_values, 3)) self.error = sum(np.square(self.poly(self.x_values) - self.y_values)) self.min_x = min(x_values) self.max_x = max(x_values) <|end_body_0|> <|body_s...
Polynomial of 3rd degree fitted on the given values.
FittedPolynomial
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FittedPolynomial: """Polynomial of 3rd degree fitted on the given values.""" def __init__(self, x_values, y_values): """Initialize fitted polynomial.""" <|body_0|> def deriv(self): """Return first derivative of the polynomial.""" <|body_1|> def deriv...
stack_v2_sparse_classes_75kplus_train_066244
3,200
permissive
[ { "docstring": "Initialize fitted polynomial.", "name": "__init__", "signature": "def __init__(self, x_values, y_values)" }, { "docstring": "Return first derivative of the polynomial.", "name": "deriv", "signature": "def deriv(self)" }, { "docstring": "Return real roots of the fi...
5
stack_v2_sparse_classes_30k_train_017510
Implement the Python class `FittedPolynomial` described below. Class description: Polynomial of 3rd degree fitted on the given values. Method signatures and docstrings: - def __init__(self, x_values, y_values): Initialize fitted polynomial. - def deriv(self): Return first derivative of the polynomial. - def deriv_roo...
Implement the Python class `FittedPolynomial` described below. Class description: Polynomial of 3rd degree fitted on the given values. Method signatures and docstrings: - def __init__(self, x_values, y_values): Initialize fitted polynomial. - def deriv(self): Return first derivative of the polynomial. - def deriv_roo...
bae6105812c2f2414d0c10ddd465bf589503f61a
<|skeleton|> class FittedPolynomial: """Polynomial of 3rd degree fitted on the given values.""" def __init__(self, x_values, y_values): """Initialize fitted polynomial.""" <|body_0|> def deriv(self): """Return first derivative of the polynomial.""" <|body_1|> def deriv...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FittedPolynomial: """Polynomial of 3rd degree fitted on the given values.""" def __init__(self, x_values, y_values): """Initialize fitted polynomial.""" self.x_values = x_values self.y_values = y_values self.poly = np.poly1d(np.polyfit(x_values, y_values, 3)) self....
the_stack_v2_python_sparse
src/lactolyse/analyses/utils.py
dblenkus/lactolyse
train
2
da817dd980b415840fd0993a05d82e623f44d1e2
[ "if x < 2:\n return x\nleft, right = (0, x // 2)\nwhile left < right:\n pivot = left + (right - left) // 2\n num = pivot * pivot\n if num < x:\n left = pivot + 1\n elif num > x:\n right = pivot - 1\n else:\n return pivot\nreturn right", "from math import e, log\nif x < 2:\n ...
<|body_start_0|> if x < 2: return x left, right = (0, x // 2) while left < right: pivot = left + (right - left) // 2 num = pivot * pivot if num < x: left = pivot + 1 elif num > x: right = pivot - 1 ...
SquareRoot
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SquareRoot: def answer(self, x: int) -> int: """Approach: Binary Search Condition: 0 < 1 < x / 2 Time Complexity: O(log N) Space Complexity: O(1) :param x: :return:""" <|body_0|> def answer_(self, x: int) -> int: """Approach: Pocket Calculator Time Complexity: O(1) S...
stack_v2_sparse_classes_75kplus_train_066245
1,291
no_license
[ { "docstring": "Approach: Binary Search Condition: 0 < 1 < x / 2 Time Complexity: O(log N) Space Complexity: O(1) :param x: :return:", "name": "answer", "signature": "def answer(self, x: int) -> int" }, { "docstring": "Approach: Pocket Calculator Time Complexity: O(1) Space Complexity: O(1) :par...
2
null
Implement the Python class `SquareRoot` described below. Class description: Implement the SquareRoot class. Method signatures and docstrings: - def answer(self, x: int) -> int: Approach: Binary Search Condition: 0 < 1 < x / 2 Time Complexity: O(log N) Space Complexity: O(1) :param x: :return: - def answer_(self, x: i...
Implement the Python class `SquareRoot` described below. Class description: Implement the SquareRoot class. Method signatures and docstrings: - def answer(self, x: int) -> int: Approach: Binary Search Condition: 0 < 1 < x / 2 Time Complexity: O(log N) Space Complexity: O(1) :param x: :return: - def answer_(self, x: i...
65cc78b5afa0db064f9fe8f06597e3e120f7363d
<|skeleton|> class SquareRoot: def answer(self, x: int) -> int: """Approach: Binary Search Condition: 0 < 1 < x / 2 Time Complexity: O(log N) Space Complexity: O(1) :param x: :return:""" <|body_0|> def answer_(self, x: int) -> int: """Approach: Pocket Calculator Time Complexity: O(1) S...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SquareRoot: def answer(self, x: int) -> int: """Approach: Binary Search Condition: 0 < 1 < x / 2 Time Complexity: O(log N) Space Complexity: O(1) :param x: :return:""" if x < 2: return x left, right = (0, x // 2) while left < right: pivot = left + (right...
the_stack_v2_python_sparse
revisited_2021/math_and_string/square_root.py
Shiv2157k/leet_code
train
1
6639a52fe035376e27d36b6c69b3fa15f564f458
[ "self.sum_hit_at_one = 0.0\nself.sum_perr = 0.0\nself.sum_loss = 0.0\nself.map_calculator = map_calculator.MeanAveragePrecisionCalculator(num_class)\nself.global_ap_calculator = ap_calculator.AveragePrecisionCalculator()\nself.pr_calculator = PRCalculator()\nself.pr_calculator_per_tag = PRCalculatorPerTag(num_class...
<|body_start_0|> self.sum_hit_at_one = 0.0 self.sum_perr = 0.0 self.sum_loss = 0.0 self.map_calculator = map_calculator.MeanAveragePrecisionCalculator(num_class) self.global_ap_calculator = ap_calculator.AveragePrecisionCalculator() self.pr_calculator = PRCalculator() ...
A class to store the evaluation metrics.
EvaluationMetrics
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EvaluationMetrics: """A class to store the evaluation metrics.""" def __init__(self, num_class, top_k, accumulate_per_tag=False): """Construct an EvaluationMetrics object to store the evaluation metrics. Args: num_class: A positive integer specifying the number of classes. top_k: A p...
stack_v2_sparse_classes_75kplus_train_066246
24,184
no_license
[ { "docstring": "Construct an EvaluationMetrics object to store the evaluation metrics. Args: num_class: A positive integer specifying the number of classes. top_k: A positive integer specifying how many predictions are considered per video. Raises: ValueError: An error occurred when MeanAveragePrecisionCalculat...
4
stack_v2_sparse_classes_30k_train_047500
Implement the Python class `EvaluationMetrics` described below. Class description: A class to store the evaluation metrics. Method signatures and docstrings: - def __init__(self, num_class, top_k, accumulate_per_tag=False): Construct an EvaluationMetrics object to store the evaluation metrics. Args: num_class: A posi...
Implement the Python class `EvaluationMetrics` described below. Class description: A class to store the evaluation metrics. Method signatures and docstrings: - def __init__(self, num_class, top_k, accumulate_per_tag=False): Construct an EvaluationMetrics object to store the evaluation metrics. Args: num_class: A posi...
aa5083f15e68b637403cd96bd43633b93dc59844
<|skeleton|> class EvaluationMetrics: """A class to store the evaluation metrics.""" def __init__(self, num_class, top_k, accumulate_per_tag=False): """Construct an EvaluationMetrics object to store the evaluation metrics. Args: num_class: A positive integer specifying the number of classes. top_k: A p...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EvaluationMetrics: """A class to store the evaluation metrics.""" def __init__(self, num_class, top_k, accumulate_per_tag=False): """Construct an EvaluationMetrics object to store the evaluation metrics. Args: num_class: A positive integer specifying the number of classes. top_k: A positive integ...
the_stack_v2_python_sparse
utils/train_util.py
hezhiqian01/MultiModal-Tagging
train
4
d5cacbf48d08affed6a6fb7e4d4c55059bd4b274
[ "self.num = num\nfor i, x in enumerate(events):\n if 'addC' in x.Event:\n for y in range(i + 1, i + PLAYER_COUNT):\n events[y].Event = dict()\nbidRows = filter(lambda x: 'bid' in x.Event, events)\nplayRows = filter(lambda x: 'playC' in x.Event, events)\nscoreRow = filter(lambda x: 'sco' in x.Ev...
<|body_start_0|> self.num = num for i, x in enumerate(events): if 'addC' in x.Event: for y in range(i + 1, i + PLAYER_COUNT): events[y].Event = dict() bidRows = filter(lambda x: 'bid' in x.Event, events) playRows = filter(lambda x: 'playC' ...
Helper class for parsing game logs. Attributes: num (int): The hand number within the game. trump (int): The trump for the hand. bids (dict): With the keys: - values (list): Bid amounts in pNum order (list index == pNum). - dealer (int): pNum of dealer. - winner (int): pNum of bid winner. tricks (list): Each element is...
Hand
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Hand: """Helper class for parsing game logs. Attributes: num (int): The hand number within the game. trump (int): The trump for the hand. bids (dict): With the keys: - values (list): Bid amounts in pNum order (list index == pNum). - dealer (int): pNum of dealer. - winner (int): pNum of bid winner...
stack_v2_sparse_classes_75kplus_train_066247
5,091
permissive
[ { "docstring": "Process events and store hand data. Args: num (int): Hand number events (list): List of events for this hand.", "name": "__init__", "signature": "def __init__(self, num, events)" }, { "docstring": "Set the bids attribute for the Hand. The 'actvP' in the final bid is the bid winne...
4
stack_v2_sparse_classes_30k_train_002248
Implement the Python class `Hand` described below. Class description: Helper class for parsing game logs. Attributes: num (int): The hand number within the game. trump (int): The trump for the hand. bids (dict): With the keys: - values (list): Bid amounts in pNum order (list index == pNum). - dealer (int): pNum of dea...
Implement the Python class `Hand` described below. Class description: Helper class for parsing game logs. Attributes: num (int): The hand number within the game. trump (int): The trump for the hand. bids (dict): With the keys: - values (list): Bid amounts in pNum order (list index == pNum). - dealer (int): pNum of dea...
f8b9e8c073f555ff827fa7887153e82b263a8aab
<|skeleton|> class Hand: """Helper class for parsing game logs. Attributes: num (int): The hand number within the game. trump (int): The trump for the hand. bids (dict): With the keys: - values (list): Bid amounts in pNum order (list index == pNum). - dealer (int): pNum of dealer. - winner (int): pNum of bid winner...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Hand: """Helper class for parsing game logs. Attributes: num (int): The hand number within the game. trump (int): The trump for the hand. bids (dict): With the keys: - values (list): Bid amounts in pNum order (list index == pNum). - dealer (int): pNum of dealer. - winner (int): pNum of bid winner. tricks (lis...
the_stack_v2_python_sparse
db/parseLog.py
JackieChiles/Cinch
train
2
331e2ff3c5f8d31e5f2a7d34eded954dca5e6759
[ "bert = BertModel.shared(config=config, name='bert')\nsequence_output, pooled_output = bert(input_ids, input_mask, type_ids, deterministic=deterministic)\nif masked_lm_positions is None:\n return (sequence_output, pooled_output)\nmasked_lm_input = GatherIndexes(sequence_output, masked_lm_positions)\nmasked_lm_in...
<|body_start_0|> bert = BertModel.shared(config=config, name='bert') sequence_output, pooled_output = bert(input_ids, input_mask, type_ids, deterministic=deterministic) if masked_lm_positions is None: return (sequence_output, pooled_output) masked_lm_input = GatherIndexes(seq...
Bert model for pre-training.
BertForPreTraining
[ "CC-BY-4.0", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BertForPreTraining: """Bert model for pre-training.""" def apply(self, input_ids, input_mask, type_ids, masked_lm_positions=None, masked_lm_labels=None, masked_lm_weights=None, next_sentence_labels=None, *, config, deterministic=False): """Applies BERT for pre-training.""" <|...
stack_v2_sparse_classes_75kplus_train_066248
8,883
permissive
[ { "docstring": "Applies BERT for pre-training.", "name": "apply", "signature": "def apply(self, input_ids, input_mask, type_ids, masked_lm_positions=None, masked_lm_labels=None, masked_lm_weights=None, next_sentence_labels=None, *, config, deterministic=False)" }, { "docstring": "Computes the pr...
2
stack_v2_sparse_classes_30k_train_026644
Implement the Python class `BertForPreTraining` described below. Class description: Bert model for pre-training. Method signatures and docstrings: - def apply(self, input_ids, input_mask, type_ids, masked_lm_positions=None, masked_lm_labels=None, masked_lm_weights=None, next_sentence_labels=None, *, config, determini...
Implement the Python class `BertForPreTraining` described below. Class description: Bert model for pre-training. Method signatures and docstrings: - def apply(self, input_ids, input_mask, type_ids, masked_lm_positions=None, masked_lm_labels=None, masked_lm_weights=None, next_sentence_labels=None, *, config, determini...
0714e9a5a3934d922c0b9dd017943a8e511eb5bc
<|skeleton|> class BertForPreTraining: """Bert model for pre-training.""" def apply(self, input_ids, input_mask, type_ids, masked_lm_positions=None, masked_lm_labels=None, masked_lm_weights=None, next_sentence_labels=None, *, config, deterministic=False): """Applies BERT for pre-training.""" <|...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BertForPreTraining: """Bert model for pre-training.""" def apply(self, input_ids, input_mask, type_ids, masked_lm_positions=None, masked_lm_labels=None, masked_lm_weights=None, next_sentence_labels=None, *, config, deterministic=False): """Applies BERT for pre-training.""" bert = BertMode...
the_stack_v2_python_sparse
flax_models/bert/models.py
pdybczak/google-research
train
1
122a88d597095b1ec328c2f67925de2182365551
[ "self.env.revert_snapshot('deploy_ha_influxdb_grafana')\nmanipulated_node = {'slave-03': ['controller']}\nself.helpers.remove_nodes_from_cluster(manipulated_node)\nself.check_plugin_online()\nself.helpers.run_ostf(should_fail=1)\nself.helpers.add_nodes_to_cluster(manipulated_node)\nself.check_plugin_online()\nself....
<|body_start_0|> self.env.revert_snapshot('deploy_ha_influxdb_grafana') manipulated_node = {'slave-03': ['controller']} self.helpers.remove_nodes_from_cluster(manipulated_node) self.check_plugin_online() self.helpers.run_ostf(should_fail=1) self.helpers.add_nodes_to_clust...
Class for system tests for InfluxDB-Grafana plugin.
TestNodesInfluxdbPlugin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestNodesInfluxdbPlugin: """Class for system tests for InfluxDB-Grafana plugin.""" def add_remove_controller_influxdb_grafana(self): """Verify that the number of controllers can scale up and down Scenario: 1. Revert snapshot with 9 deployed nodes in HA configuration 2. Remove one con...
stack_v2_sparse_classes_75kplus_train_066249
7,472
no_license
[ { "docstring": "Verify that the number of controllers can scale up and down Scenario: 1. Revert snapshot with 9 deployed nodes in HA configuration 2. Remove one controller node and update the cluster 3. Check that plugin is working 4. Run OSTF 5. Add one controller node (return previous state) and update the cl...
5
stack_v2_sparse_classes_30k_train_000375
Implement the Python class `TestNodesInfluxdbPlugin` described below. Class description: Class for system tests for InfluxDB-Grafana plugin. Method signatures and docstrings: - def add_remove_controller_influxdb_grafana(self): Verify that the number of controllers can scale up and down Scenario: 1. Revert snapshot wi...
Implement the Python class `TestNodesInfluxdbPlugin` described below. Class description: Class for system tests for InfluxDB-Grafana plugin. Method signatures and docstrings: - def add_remove_controller_influxdb_grafana(self): Verify that the number of controllers can scale up and down Scenario: 1. Revert snapshot wi...
179249df2d206eeabb3955c9dc8cb78cac3c36c6
<|skeleton|> class TestNodesInfluxdbPlugin: """Class for system tests for InfluxDB-Grafana plugin.""" def add_remove_controller_influxdb_grafana(self): """Verify that the number of controllers can scale up and down Scenario: 1. Revert snapshot with 9 deployed nodes in HA configuration 2. Remove one con...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestNodesInfluxdbPlugin: """Class for system tests for InfluxDB-Grafana plugin.""" def add_remove_controller_influxdb_grafana(self): """Verify that the number of controllers can scale up and down Scenario: 1. Revert snapshot with 9 deployed nodes in HA configuration 2. Remove one controller node ...
the_stack_v2_python_sparse
stacklight_tests/influxdb_grafana/test_system.py
rkhozinov/stacklight-integration-tests
train
1
e1f2c067e1b18b0688adaa425b177c218225e8e7
[ "super(ResNet, self).__init__()\nself.blocks = blocks\nself.in_channels = in_channels\nself.num_classes = num_classes\nself.global_pool = global_pool\nself.output_stride = output_stride\nself.include_root_block = include_root_block\nself.conv2d_same = Conv2dSame(self.in_channels, 64, 7, 2)\nself.max_pool2d = nn.Max...
<|body_start_0|> super(ResNet, self).__init__() self.blocks = blocks self.in_channels = in_channels self.num_classes = num_classes self.global_pool = global_pool self.output_stride = output_stride self.include_root_block = include_root_block self.conv2d_sa...
Resnet
ResNet
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ResNet: """Resnet""" def __init__(self, blocks, in_channels, num_classes=None, global_pool=True, output_stride=None, include_root_block=True): """Args: blocks: blocks config. should be generated by _make_block in_channels: in channels num_classes: the number of classes global_pool: I...
stack_v2_sparse_classes_75kplus_train_066250
11,719
permissive
[ { "docstring": "Args: blocks: blocks config. should be generated by _make_block in_channels: in channels num_classes: the number of classes global_pool: If True, we perform global average pooling before computing the logits. Set to True for image classification, False for dense prediction. output_stride: If Non...
2
stack_v2_sparse_classes_30k_train_047409
Implement the Python class `ResNet` described below. Class description: Resnet Method signatures and docstrings: - def __init__(self, blocks, in_channels, num_classes=None, global_pool=True, output_stride=None, include_root_block=True): Args: blocks: blocks config. should be generated by _make_block in_channels: in c...
Implement the Python class `ResNet` described below. Class description: Resnet Method signatures and docstrings: - def __init__(self, blocks, in_channels, num_classes=None, global_pool=True, output_stride=None, include_root_block=True): Args: blocks: blocks config. should be generated by _make_block in_channels: in c...
eab643f51336dbf7d711f02d27e6516e5affee59
<|skeleton|> class ResNet: """Resnet""" def __init__(self, blocks, in_channels, num_classes=None, global_pool=True, output_stride=None, include_root_block=True): """Args: blocks: blocks config. should be generated by _make_block in_channels: in channels num_classes: the number of classes global_pool: I...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ResNet: """Resnet""" def __init__(self, blocks, in_channels, num_classes=None, global_pool=True, output_stride=None, include_root_block=True): """Args: blocks: blocks config. should be generated by _make_block in_channels: in channels num_classes: the number of classes global_pool: If True, we pe...
the_stack_v2_python_sparse
research/cv/ArtTrack/src/model/resnet/resnet.py
mindspore-ai/models
train
301
4829de30ea0dc00650aac0d42f868ebdf300f416
[ "self._parameters = parameters\nself._mapper = OCPGCPProviderMap(provider=self.provider, report_type=parameters.report_type)\nif parameters.get_filter('enabled') is None:\n parameters.set_filter(**{'enabled': True})\nsuper().__init__(parameters)", "filter_map = deepcopy(TagQueryHandler.FILTER_MAP)\nif self._pa...
<|body_start_0|> self._parameters = parameters self._mapper = OCPGCPProviderMap(provider=self.provider, report_type=parameters.report_type) if parameters.get_filter('enabled') is None: parameters.set_filter(**{'enabled': True}) super().__init__(parameters) <|end_body_0|> <|b...
Handles tag queries and responses for OCP-on-GCP.
OCPGCPTagQueryHandler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OCPGCPTagQueryHandler: """Handles tag queries and responses for OCP-on-GCP.""" def __init__(self, parameters): """Establish GCP report query handler. Args: parameters (QueryParameters): parameter object for query""" <|body_0|> def filter_map(self): """Establish w...
stack_v2_sparse_classes_75kplus_train_066251
3,966
permissive
[ { "docstring": "Establish GCP report query handler. Args: parameters (QueryParameters): parameter object for query", "name": "__init__", "signature": "def __init__(self, parameters)" }, { "docstring": "Establish which filter map to use based on tag API.", "name": "filter_map", "signature...
2
stack_v2_sparse_classes_30k_train_030827
Implement the Python class `OCPGCPTagQueryHandler` described below. Class description: Handles tag queries and responses for OCP-on-GCP. Method signatures and docstrings: - def __init__(self, parameters): Establish GCP report query handler. Args: parameters (QueryParameters): parameter object for query - def filter_m...
Implement the Python class `OCPGCPTagQueryHandler` described below. Class description: Handles tag queries and responses for OCP-on-GCP. Method signatures and docstrings: - def __init__(self, parameters): Establish GCP report query handler. Args: parameters (QueryParameters): parameter object for query - def filter_m...
0416e5216eb1ec4b41c8dd4999adde218b1ab2e1
<|skeleton|> class OCPGCPTagQueryHandler: """Handles tag queries and responses for OCP-on-GCP.""" def __init__(self, parameters): """Establish GCP report query handler. Args: parameters (QueryParameters): parameter object for query""" <|body_0|> def filter_map(self): """Establish w...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class OCPGCPTagQueryHandler: """Handles tag queries and responses for OCP-on-GCP.""" def __init__(self, parameters): """Establish GCP report query handler. Args: parameters (QueryParameters): parameter object for query""" self._parameters = parameters self._mapper = OCPGCPProviderMap(pr...
the_stack_v2_python_sparse
koku/api/tags/gcp/openshift/queries.py
project-koku/koku
train
225
c66654e5ce8afdd80b6d98ce11865674951ace1c
[ "self.Wh = np.random.randn(i + h, h)\nself.Wy = np.random.randn(h, o)\nself.bh = np.zeros((1, h))\nself.by = np.zeros((1, o))", "Exp = np.exp(h)\nExp = Exp / np.sum(Exp, 1, keepdims=True)\nreturn Exp", "h_next = np.tanh(np.hstack((h_prev, x_t)) @ self.Wh + self.bh)\ny = self.softmax(h_next @ self.Wy + self.by)\...
<|body_start_0|> self.Wh = np.random.randn(i + h, h) self.Wy = np.random.randn(h, o) self.bh = np.zeros((1, h)) self.by = np.zeros((1, o)) <|end_body_0|> <|body_start_1|> Exp = np.exp(h) Exp = Exp / np.sum(Exp, 1, keepdims=True) return Exp <|end_body_1|> <|body_...
represents a cell of a simple RNN
RNNCell
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RNNCell: """represents a cell of a simple RNN""" def __init__(self, i, h, o): """Class constructor""" <|body_0|> def softmax(h): """softmax activation function""" <|body_1|> def forward(self, h_prev, x_t): """represent the weights and biases ...
stack_v2_sparse_classes_75kplus_train_066252
855
no_license
[ { "docstring": "Class constructor", "name": "__init__", "signature": "def __init__(self, i, h, o)" }, { "docstring": "softmax activation function", "name": "softmax", "signature": "def softmax(h)" }, { "docstring": "represent the weights and biases of the cell", "name": "forw...
3
stack_v2_sparse_classes_30k_train_011436
Implement the Python class `RNNCell` described below. Class description: represents a cell of a simple RNN Method signatures and docstrings: - def __init__(self, i, h, o): Class constructor - def softmax(h): softmax activation function - def forward(self, h_prev, x_t): represent the weights and biases of the cell
Implement the Python class `RNNCell` described below. Class description: represents a cell of a simple RNN Method signatures and docstrings: - def __init__(self, i, h, o): Class constructor - def softmax(h): softmax activation function - def forward(self, h_prev, x_t): represent the weights and biases of the cell <|...
c23deee331a71a089197547fcae4c1eefb8d24ef
<|skeleton|> class RNNCell: """represents a cell of a simple RNN""" def __init__(self, i, h, o): """Class constructor""" <|body_0|> def softmax(h): """softmax activation function""" <|body_1|> def forward(self, h_prev, x_t): """represent the weights and biases ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RNNCell: """represents a cell of a simple RNN""" def __init__(self, i, h, o): """Class constructor""" self.Wh = np.random.randn(i + h, h) self.Wy = np.random.randn(h, o) self.bh = np.zeros((1, h)) self.by = np.zeros((1, o)) def softmax(h): """softmax a...
the_stack_v2_python_sparse
supervised_learning/0x0D-RNNs/0-rnn_cell.py
YosriGFX/holbertonschool-machine_learning
train
0
ffbcf06dfb4ca6f267808f4235baf87d86dcaf11
[ "E0 = a0 * m_e * c ** 2 * k0 / e\nself.k0 = k0\nself.waist = waist\nself.inv_tau = 1.0 / tau\nself.t_peak = t_peak\nself.E0 = E0\nself.v_antenna = source_v\nself.boost = boost\nself.temporal_order = temporal_order\nself.theta_zx = theta_zx\nself.x_center = x_center\nself.geom_coeff = get_geometric_coeff(dim)", "t...
<|body_start_0|> E0 = a0 * m_e * c ** 2 * k0 / e self.k0 = k0 self.waist = waist self.inv_tau = 1.0 / tau self.t_peak = t_peak self.E0 = E0 self.v_antenna = source_v self.boost = boost self.temporal_order = temporal_order self.theta_zx = th...
Class that calculates a laser pulse with transverse Jinc profile, longitudinal Gaussian profile and propagating at an arbitrary angle with respect to z.
JincGaussianAngleProfile
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JincGaussianAngleProfile: """Class that calculates a laser pulse with transverse Jinc profile, longitudinal Gaussian profile and propagating at an arbitrary angle with respect to z.""" def __init__(self, k0, waist, tau, t_peak, a0, dim, temporal_order=2, boost=None, source_v=0, theta_zx=0.0,...
stack_v2_sparse_classes_75kplus_train_066253
34,589
permissive
[ { "docstring": "Define a laser profile with is a Jinc function transversely and a supergaussian function longitudinally. The antenna is orthogonal to z, but this profile supports a non-zero angle in the (z, x) plane, and is compatible with the boosted frame and a moving window. Note 1: The focal plane is the pl...
2
stack_v2_sparse_classes_30k_train_028748
Implement the Python class `JincGaussianAngleProfile` described below. Class description: Class that calculates a laser pulse with transverse Jinc profile, longitudinal Gaussian profile and propagating at an arbitrary angle with respect to z. Method signatures and docstrings: - def __init__(self, k0, waist, tau, t_pe...
Implement the Python class `JincGaussianAngleProfile` described below. Class description: Class that calculates a laser pulse with transverse Jinc profile, longitudinal Gaussian profile and propagating at an arbitrary angle with respect to z. Method signatures and docstrings: - def __init__(self, k0, waist, tau, t_pe...
091c982f82788209017315e13eb7d0e743687d46
<|skeleton|> class JincGaussianAngleProfile: """Class that calculates a laser pulse with transverse Jinc profile, longitudinal Gaussian profile and propagating at an arbitrary angle with respect to z.""" def __init__(self, k0, waist, tau, t_peak, a0, dim, temporal_order=2, boost=None, source_v=0, theta_zx=0.0,...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class JincGaussianAngleProfile: """Class that calculates a laser pulse with transverse Jinc profile, longitudinal Gaussian profile and propagating at an arbitrary angle with respect to z.""" def __init__(self, k0, waist, tau, t_peak, a0, dim, temporal_order=2, boost=None, source_v=0, theta_zx=0.0, x_center=0.0...
the_stack_v2_python_sparse
scripts/field_solvers/laser/laser_profiles.py
giadarol/warp
train
0
eaed4300547a49bf6e86ad1ce1b1c709c9a25b92
[ "self.access_zone_id = access_zone_id\nself.description = description\nself.share_name = share_name", "if dictionary is None:\n return None\naccess_zone_id = dictionary.get('accessZoneId')\ndescription = dictionary.get('description')\nshare_name = dictionary.get('shareName')\nreturn cls(access_zone_id, descrip...
<|body_start_0|> self.access_zone_id = access_zone_id self.description = description self.share_name = share_name <|end_body_0|> <|body_start_1|> if dictionary is None: return None access_zone_id = dictionary.get('accessZoneId') description = dictionary.get('...
Implementation of the 'IsilonSmbMountPoint' model. Specifies information specific to SMB shares exposed by Isilon file system. Attributes: access_zone_id (long|int): Specifies the Access Zone Id. description (string): Specifies the description of the NFS mount point. share_name (string): Specifies the name of the SMB/C...
IsilonSmbMountPoint
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IsilonSmbMountPoint: """Implementation of the 'IsilonSmbMountPoint' model. Specifies information specific to SMB shares exposed by Isilon file system. Attributes: access_zone_id (long|int): Specifies the Access Zone Id. description (string): Specifies the description of the NFS mount point. share...
stack_v2_sparse_classes_75kplus_train_066254
1,925
permissive
[ { "docstring": "Constructor for the IsilonSmbMountPoint class", "name": "__init__", "signature": "def __init__(self, access_zone_id=None, description=None, share_name=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary represe...
2
stack_v2_sparse_classes_30k_val_000527
Implement the Python class `IsilonSmbMountPoint` described below. Class description: Implementation of the 'IsilonSmbMountPoint' model. Specifies information specific to SMB shares exposed by Isilon file system. Attributes: access_zone_id (long|int): Specifies the Access Zone Id. description (string): Specifies the de...
Implement the Python class `IsilonSmbMountPoint` described below. Class description: Implementation of the 'IsilonSmbMountPoint' model. Specifies information specific to SMB shares exposed by Isilon file system. Attributes: access_zone_id (long|int): Specifies the Access Zone Id. description (string): Specifies the de...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class IsilonSmbMountPoint: """Implementation of the 'IsilonSmbMountPoint' model. Specifies information specific to SMB shares exposed by Isilon file system. Attributes: access_zone_id (long|int): Specifies the Access Zone Id. description (string): Specifies the description of the NFS mount point. share...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class IsilonSmbMountPoint: """Implementation of the 'IsilonSmbMountPoint' model. Specifies information specific to SMB shares exposed by Isilon file system. Attributes: access_zone_id (long|int): Specifies the Access Zone Id. description (string): Specifies the description of the NFS mount point. share_name (string...
the_stack_v2_python_sparse
cohesity_management_sdk/models/isilon_smb_mount_point.py
cohesity/management-sdk-python
train
24
79c7025eef0c00e5531062fc253b8ce6ef85cb1f
[ "super().__init__(data, seed=seed, shuffle=shuffle)\nif fields_to_merge is not None:\n if merged_field is not None:\n log.info('Merging fields <<{}>> to new field <<{}>>'.format(fields_to_merge, merged_field))\n self._merge_data(fields_to_merge=fields_to_merge, merged_field=merged_field)\n else:...
<|body_start_0|> super().__init__(data, seed=seed, shuffle=shuffle) if fields_to_merge is not None: if merged_field is not None: log.info('Merging fields <<{}>> to new field <<{}>>'.format(fields_to_merge, merged_field)) self._merge_data(fields_to_merge=fields...
Class gets data dictionary from DatasetReader instance, merge fields if necessary, split a field if necessary Args: data: dictionary of data with fields "train", "valid" and "test" (or some of them) fields_to_merge: list of fields (out of ``"train", "valid", "test"``) to merge merged_field: name of field (out of ``"tra...
BasicClassificationDatasetIterator
[ "Python-2.0", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BasicClassificationDatasetIterator: """Class gets data dictionary from DatasetReader instance, merge fields if necessary, split a field if necessary Args: data: dictionary of data with fields "train", "valid" and "test" (or some of them) fields_to_merge: list of fields (out of ``"train", "valid",...
stack_v2_sparse_classes_75kplus_train_066255
5,935
permissive
[ { "docstring": "Initialize dataset using data from DatasetReader, merges and splits fields according to the given parameters.", "name": "__init__", "signature": "def __init__(self, data: dict, fields_to_merge: List[str]=None, merged_field: str=None, field_to_split: str=None, split_fields: List[str]=None...
3
stack_v2_sparse_classes_30k_train_010959
Implement the Python class `BasicClassificationDatasetIterator` described below. Class description: Class gets data dictionary from DatasetReader instance, merge fields if necessary, split a field if necessary Args: data: dictionary of data with fields "train", "valid" and "test" (or some of them) fields_to_merge: lis...
Implement the Python class `BasicClassificationDatasetIterator` described below. Class description: Class gets data dictionary from DatasetReader instance, merge fields if necessary, split a field if necessary Args: data: dictionary of data with fields "train", "valid" and "test" (or some of them) fields_to_merge: lis...
65f69dfb898f5444cc2c98ae03ec7b3f44266df2
<|skeleton|> class BasicClassificationDatasetIterator: """Class gets data dictionary from DatasetReader instance, merge fields if necessary, split a field if necessary Args: data: dictionary of data with fields "train", "valid" and "test" (or some of them) fields_to_merge: list of fields (out of ``"train", "valid",...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BasicClassificationDatasetIterator: """Class gets data dictionary from DatasetReader instance, merge fields if necessary, split a field if necessary Args: data: dictionary of data with fields "train", "valid" and "test" (or some of them) fields_to_merge: list of fields (out of ``"train", "valid", "test"``) to...
the_stack_v2_python_sparse
deeppavlov/dataset_iterators/basic_classification_iterator.py
vintagexav/DeepPavlov
train
2
716a49e260e69a61f581213e629fd5c4cc6b6470
[ "delay = 0\nrow = []\nfor val in prev:\n row.append(val + delay)\n delay = val\nrow.append(delay)\nreturn row", "self.tri = []\nif numRows >= 1:\n self.tri.append([1])\nif numRows >= 2:\n self.tri.append([1, 1])\ni = 3\nwhile i <= numRows:\n self.tri.append(self.nextRow(self.tri[-1]))\n i = i + ...
<|body_start_0|> delay = 0 row = [] for val in prev: row.append(val + delay) delay = val row.append(delay) return row <|end_body_0|> <|body_start_1|> self.tri = [] if numRows >= 1: self.tri.append([1]) if numRows >= 2: ...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def nextRow(self, prev): """:type prev: List[int] :rtype: List[int] difference equation: y(n) = x(n) + x(n-1)""" <|body_0|> def generate(self, numRows): """:type numRows: int :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_75kplus_train_066256
1,004
permissive
[ { "docstring": ":type prev: List[int] :rtype: List[int] difference equation: y(n) = x(n) + x(n-1)", "name": "nextRow", "signature": "def nextRow(self, prev)" }, { "docstring": ":type numRows: int :rtype: List[List[int]]", "name": "generate", "signature": "def generate(self, numRows)" }...
2
stack_v2_sparse_classes_30k_train_050413
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def nextRow(self, prev): :type prev: List[int] :rtype: List[int] difference equation: y(n) = x(n) + x(n-1) - def generate(self, numRows): :type numRows: int :rtype: List[List[int...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def nextRow(self, prev): :type prev: List[int] :rtype: List[int] difference equation: y(n) = x(n) + x(n-1) - def generate(self, numRows): :type numRows: int :rtype: List[List[int...
0521e27097a01a0a2ba2af30f3185d8bb5e3e227
<|skeleton|> class Solution: def nextRow(self, prev): """:type prev: List[int] :rtype: List[int] difference equation: y(n) = x(n) + x(n-1)""" <|body_0|> def generate(self, numRows): """:type numRows: int :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def nextRow(self, prev): """:type prev: List[int] :rtype: List[int] difference equation: y(n) = x(n) + x(n-1)""" delay = 0 row = [] for val in prev: row.append(val + delay) delay = val row.append(delay) return row def gener...
the_stack_v2_python_sparse
P118-PascalsTriangle/main.py
rlan/LeetCode
train
0
9ba89c3cee2ffc636c9107167a553c07f1fc1597
[ "self.assertTrue(reverse('abc') == 'cba')\nself.assertTrue(reverse('abd') == 'cba')\nself.assertTrue(reverse('abc') == 'abc')", "self.assertTrue(list(rev_enumerate('Python')) == [(5, 'n'), (4, 'o'), (3, 'h'), (2, 't'), (1, 'y'), (0, 'P')])\nself.assertTrue(list(rev_enumerate('hell')) == [(4, 'o'), (3, 'l'), (2, '...
<|body_start_0|> self.assertTrue(reverse('abc') == 'cba') self.assertTrue(reverse('abd') == 'cba') self.assertTrue(reverse('abc') == 'abc') <|end_body_0|> <|body_start_1|> self.assertTrue(list(rev_enumerate('Python')) == [(5, 'n'), (4, 'o'), (3, 'h'), (2, 't'), (1, 'y'), (0, 'P')]) ...
TestString
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestString: def test_reverse(self): """to verify that reverse works properly""" <|body_0|> def test_rev_enumerate(self): """to verify that rev_enumerate works""" <|body_1|> def test_find_second(self): """to verify that find_second works""" ...
stack_v2_sparse_classes_75kplus_train_066257
1,556
no_license
[ { "docstring": "to verify that reverse works properly", "name": "test_reverse", "signature": "def test_reverse(self)" }, { "docstring": "to verify that rev_enumerate works", "name": "test_rev_enumerate", "signature": "def test_rev_enumerate(self)" }, { "docstring": "to verify tha...
4
null
Implement the Python class `TestString` described below. Class description: Implement the TestString class. Method signatures and docstrings: - def test_reverse(self): to verify that reverse works properly - def test_rev_enumerate(self): to verify that rev_enumerate works - def test_find_second(self): to verify that ...
Implement the Python class `TestString` described below. Class description: Implement the TestString class. Method signatures and docstrings: - def test_reverse(self): to verify that reverse works properly - def test_rev_enumerate(self): to verify that rev_enumerate works - def test_find_second(self): to verify that ...
228897e2a76c45b5c7c7e40711cfd81adf1037cb
<|skeleton|> class TestString: def test_reverse(self): """to verify that reverse works properly""" <|body_0|> def test_rev_enumerate(self): """to verify that rev_enumerate works""" <|body_1|> def test_find_second(self): """to verify that find_second works""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestString: def test_reverse(self): """to verify that reverse works properly""" self.assertTrue(reverse('abc') == 'cba') self.assertTrue(reverse('abd') == 'cba') self.assertTrue(reverse('abc') == 'abc') def test_rev_enumerate(self): """to verify that rev_enumerate ...
the_stack_v2_python_sparse
Homework05/HW05_Test_Dinesh_Nadar.py
DineshNadar95/CS-810
train
0
742e0f8ce81152eac381de7e4b2e09b117ccee26
[ "super(Test200SmartSanityForce001, self).prepare()\nself.logger.info('Preconditions:')\nself.logger.info('1. Open Micro/WIN; ')\nself.logger.info('2. Set up connection with PLC;')\nself.MicroWIN.test_prepare('force_qb0.smart', False)", "super(Test200SmartSanityForce001, self).process()\nself.logger.info('Step ac...
<|body_start_0|> super(Test200SmartSanityForce001, self).prepare() self.logger.info('Preconditions:') self.logger.info('1. Open Micro/WIN; ') self.logger.info('2. Set up connection with PLC;') self.MicroWIN.test_prepare('force_qb0.smart', False) <|end_body_0|> <|body_start_1|> ...
Force and unforce new value No.: test_200smart_sanity_force_001 Preconditions: 1. Open Micro/WIN; 2. Set up connection with PLC; Step actions: 1. Make the PLC in run Mode, open status chart, Force a new value to QB0; 2. Unforce the forced new value; Expected results: 1. Force successful, the value of QB0 is same with t...
Test200SmartSanityForce001
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Test200SmartSanityForce001: """Force and unforce new value No.: test_200smart_sanity_force_001 Preconditions: 1. Open Micro/WIN; 2. Set up connection with PLC; Step actions: 1. Make the PLC in run Mode, open status chart, Force a new value to QB0; 2. Unforce the forced new value; Expected results...
stack_v2_sparse_classes_75kplus_train_066258
3,173
no_license
[ { "docstring": "the preparation before executing the test steps Args: Example: Return: Author: Cai, Yong IsInterface: False ChangeInfo: Cai, Yong 2019-09-20 create", "name": "prepare", "signature": "def prepare(self)" }, { "docstring": "execute the test steps Args: Example: Return: Author: Cai, ...
3
null
Implement the Python class `Test200SmartSanityForce001` described below. Class description: Force and unforce new value No.: test_200smart_sanity_force_001 Preconditions: 1. Open Micro/WIN; 2. Set up connection with PLC; Step actions: 1. Make the PLC in run Mode, open status chart, Force a new value to QB0; 2. Unforce...
Implement the Python class `Test200SmartSanityForce001` described below. Class description: Force and unforce new value No.: test_200smart_sanity_force_001 Preconditions: 1. Open Micro/WIN; 2. Set up connection with PLC; Step actions: 1. Make the PLC in run Mode, open status chart, Force a new value to QB0; 2. Unforce...
2d3490393737b3e5f086cb6623369b988ffce67f
<|skeleton|> class Test200SmartSanityForce001: """Force and unforce new value No.: test_200smart_sanity_force_001 Preconditions: 1. Open Micro/WIN; 2. Set up connection with PLC; Step actions: 1. Make the PLC in run Mode, open status chart, Force a new value to QB0; 2. Unforce the forced new value; Expected results...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Test200SmartSanityForce001: """Force and unforce new value No.: test_200smart_sanity_force_001 Preconditions: 1. Open Micro/WIN; 2. Set up connection with PLC; Step actions: 1. Make the PLC in run Mode, open status chart, Force a new value to QB0; 2. Unforce the forced new value; Expected results: 1. Force su...
the_stack_v2_python_sparse
test_case/task/test_200smart_sanity_force_001.py
Lewescaiyong/auto_test_framework
train
1
806b47c1df93405d490948e7ff1e15270c702b6a
[ "yield ('Unit', '()')\nyield ('Pair', '(,)')\nyield ('Cons', ':')\nyield ('Nil', '[]')\nyield ('True_', 'True')\nyield ('False_', 'False')", "yield '[]'\nyield 'IO'\nfor typename, _ in self.TYPES:\n if inspect.isa_tuple_name(typename):\n yield typename\nyield '(->)'\nyield '_biGenerator'\nfor funcname, ...
<|body_start_0|> yield ('Unit', '()') yield ('Pair', '(,)') yield ('Cons', ':') yield ('Nil', '[]') yield ('True_', 'True') yield ('False_', 'False') <|end_body_0|> <|body_start_1|> yield '[]' yield 'IO' for typename, _ in self.TYPES: ...
PreludeSpecification
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PreludeSpecification: def aliases(self): """Returns prelude aliases. Simply for convenience.""" <|body_0|> def exports(self): """Returns the name of each symbol that must be copied to the Prelude. This is allowed to clobber symbols defined in Prelude.curry.""" ...
stack_v2_sparse_classes_75kplus_train_066259
7,396
no_license
[ { "docstring": "Returns prelude aliases. Simply for convenience.", "name": "aliases", "signature": "def aliases(self)" }, { "docstring": "Returns the name of each symbol that must be copied to the Prelude. This is allowed to clobber symbols defined in Prelude.curry.", "name": "exports", ...
2
null
Implement the Python class `PreludeSpecification` described below. Class description: Implement the PreludeSpecification class. Method signatures and docstrings: - def aliases(self): Returns prelude aliases. Simply for convenience. - def exports(self): Returns the name of each symbol that must be copied to the Prelud...
Implement the Python class `PreludeSpecification` described below. Class description: Implement the PreludeSpecification class. Method signatures and docstrings: - def aliases(self): Returns prelude aliases. Simply for convenience. - def exports(self): Returns the name of each symbol that must be copied to the Prelud...
c28c09ca100ac102fcaa8559ad2e12eb0d12d7d5
<|skeleton|> class PreludeSpecification: def aliases(self): """Returns prelude aliases. Simply for convenience.""" <|body_0|> def exports(self): """Returns the name of each symbol that must be copied to the Prelude. This is allowed to clobber symbols defined in Prelude.curry.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PreludeSpecification: def aliases(self): """Returns prelude aliases. Simply for convenience.""" yield ('Unit', '()') yield ('Pair', '(,)') yield ('Cons', ':') yield ('Nil', '[]') yield ('True_', 'True') yield ('False_', 'False') def exports(self): ...
the_stack_v2_python_sparse
src/python/backends/generic/currylib/prelude.py
andyjost/Sprite
train
5
4ab294eed45070e1819e6bbb58fa92f6a0ee9be7
[ "assert capacity >= 1, 'capacity should be a positive integer in (0, inf)'\nself.capacity = capacity\nself._buffer = {'params': [None] * capacity, 'sim_data': [None] * capacity}\nself._idx = 0\nself.size_in_batches = 0\nself._is_full = False", "if self._is_full:\n self._overwrite(params, sim_data)\nelse:\n ...
<|body_start_0|> assert capacity >= 1, 'capacity should be a positive integer in (0, inf)' self.capacity = capacity self._buffer = {'params': [None] * capacity, 'sim_data': [None] * capacity} self._idx = 0 self.size_in_batches = 0 self._is_full = False <|end_body_0|> <|b...
Implements a memory replay buffer for simulation-based inference. Attributes ---------- capacity: int Maximum number of batches to store in the buffer size_in_batches: int Number of currently stored batches _buffer : dict Buffer data as a dictionary with keys `'params', 'sim_data'`
MemoryReplayBuffer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MemoryReplayBuffer: """Implements a memory replay buffer for simulation-based inference. Attributes ---------- capacity: int Maximum number of batches to store in the buffer size_in_batches: int Number of currently stored batches _buffer : dict Buffer data as a dictionary with keys `'params', 'si...
stack_v2_sparse_classes_75kplus_train_066260
3,103
no_license
[ { "docstring": "Creates a memory replay buffer for simulation-based inference. Parameters ---------- capacity : int Maximum number of batches to store in buffer", "name": "__init__", "signature": "def __init__(self, capacity)" }, { "docstring": "Stores params and simulated data. If buffer is not...
4
null
Implement the Python class `MemoryReplayBuffer` described below. Class description: Implements a memory replay buffer for simulation-based inference. Attributes ---------- capacity: int Maximum number of batches to store in the buffer size_in_batches: int Number of currently stored batches _buffer : dict Buffer data a...
Implement the Python class `MemoryReplayBuffer` described below. Class description: Implements a memory replay buffer for simulation-based inference. Attributes ---------- capacity: int Maximum number of batches to store in the buffer size_in_batches: int Number of currently stored batches _buffer : dict Buffer data a...
37c25b35175382a286657e2bde9d7896e853b881
<|skeleton|> class MemoryReplayBuffer: """Implements a memory replay buffer for simulation-based inference. Attributes ---------- capacity: int Maximum number of batches to store in the buffer size_in_batches: int Number of currently stored batches _buffer : dict Buffer data as a dictionary with keys `'params', 'si...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MemoryReplayBuffer: """Implements a memory replay buffer for simulation-based inference. Attributes ---------- capacity: int Maximum number of batches to store in the buffer size_in_batches: int Number of currently stored batches _buffer : dict Buffer data as a dictionary with keys `'params', 'sim_data'`""" ...
the_stack_v2_python_sparse
Conversion/Conversion (data interpolation, n_obs=3)/bayesflow/buffer.py
zijianwang2000/BA_MissingData
train
0
074d22760e2360dfd0e11f9acf434031bb601245
[ "if not id:\n raise JsonError('ID不能为空')\nobj = Friendlink.Q.filter(Friendlink.id == id).first()\nreturn obj", "query = Friendlink.Q\nif 'status' in where.keys():\n query = query.filter(Friendlink.status == where['status'])\nelse:\n query = query.filter(Friendlink.status != -1)\nquery = query.order_by(Fri...
<|body_start_0|> if not id: raise JsonError('ID不能为空') obj = Friendlink.Q.filter(Friendlink.id == id).first() return obj <|end_body_0|> <|body_start_1|> query = Friendlink.Q if 'status' in where.keys(): query = query.filter(Friendlink.status == where['stat...
FriendlinkService
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FriendlinkService: def get(id): """获取单条记录 [description] Arguments: id int -- 主键 return: Friendlink Model 实例 | None""" <|body_0|> def get_list(where, limit=12): """列表记录 Arguments: where dict -- 查询条件 page int -- 当前页 per_page int -- 每页记录数 return: Paginate 对象 | None""" ...
stack_v2_sparse_classes_75kplus_train_066261
1,257
permissive
[ { "docstring": "获取单条记录 [description] Arguments: id int -- 主键 return: Friendlink Model 实例 | None", "name": "get", "signature": "def get(id)" }, { "docstring": "列表记录 Arguments: where dict -- 查询条件 page int -- 当前页 per_page int -- 每页记录数 return: Paginate 对象 | None", "name": "get_list", "signat...
2
stack_v2_sparse_classes_30k_train_050224
Implement the Python class `FriendlinkService` described below. Class description: Implement the FriendlinkService class. Method signatures and docstrings: - def get(id): 获取单条记录 [description] Arguments: id int -- 主键 return: Friendlink Model 实例 | None - def get_list(where, limit=12): 列表记录 Arguments: where dict -- 查询条件...
Implement the Python class `FriendlinkService` described below. Class description: Implement the FriendlinkService class. Method signatures and docstrings: - def get(id): 获取单条记录 [description] Arguments: id int -- 主键 return: Friendlink Model 实例 | None - def get_list(where, limit=12): 列表记录 Arguments: where dict -- 查询条件...
3300561c5686b674197ffc097cf781a931fd4787
<|skeleton|> class FriendlinkService: def get(id): """获取单条记录 [description] Arguments: id int -- 主键 return: Friendlink Model 实例 | None""" <|body_0|> def get_list(where, limit=12): """列表记录 Arguments: where dict -- 查询条件 page int -- 当前页 per_page int -- 每页记录数 return: Paginate 对象 | None""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FriendlinkService: def get(id): """获取单条记录 [description] Arguments: id int -- 主键 return: Friendlink Model 实例 | None""" if not id: raise JsonError('ID不能为空') obj = Friendlink.Q.filter(Friendlink.id == id).first() return obj def get_list(where, limit=12): "...
the_stack_v2_python_sparse
applications/huifeng/services/friendlink.py
leeyisoft/py_admin
train
17
b3ac2504aa8a11a80ff4d33d2fb3bd8f509571d9
[ "test_args = list(kwargs.get('test_args') or [])\ntest_args.append('--enable-run-ios-unittests-with-xctest')\nkwargs['test_args'] = test_args\nsuper(DeviceXCTestUnitTestsApp, self).__init__(tests_app, **kwargs)", "plugins_dir = os.path.join(self.test_app_path, 'PlugIns')\nif not os.path.exists(plugins_dir):\n ...
<|body_start_0|> test_args = list(kwargs.get('test_args') or []) test_args.append('--enable-run-ios-unittests-with-xctest') kwargs['test_args'] = test_args super(DeviceXCTestUnitTestsApp, self).__init__(tests_app, **kwargs) <|end_body_0|> <|body_start_1|> plugins_dir = os.path.j...
XCTest hosted unit tests to run on devices. This is for the XCTest framework hosted unit tests running on devices. Stores data about tests: tests_app: full path to tests app. project_path: root project folder. module_name: egtests module name. included_tests: List of tests to run. excluded_tests: List of tests not to r...
DeviceXCTestUnitTestsApp
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DeviceXCTestUnitTestsApp: """XCTest hosted unit tests to run on devices. This is for the XCTest framework hosted unit tests running on devices. Stores data about tests: tests_app: full path to tests app. project_path: root project folder. module_name: egtests module name. included_tests: List of ...
stack_v2_sparse_classes_75kplus_train_066262
24,623
permissive
[ { "docstring": "Initialize the class. Args: tests_app: (str) full path to tests app. (Following are potential args in **kwargs) included_tests: (list) Specific tests to run E.g. [ 'TestCaseClass1/testMethod1', 'TestCaseClass2/testMethod2'] excluded_tests: (list) Specific tests not to run E.g. [ 'TestCaseClass1'...
3
stack_v2_sparse_classes_30k_train_032231
Implement the Python class `DeviceXCTestUnitTestsApp` described below. Class description: XCTest hosted unit tests to run on devices. This is for the XCTest framework hosted unit tests running on devices. Stores data about tests: tests_app: full path to tests app. project_path: root project folder. module_name: egtest...
Implement the Python class `DeviceXCTestUnitTestsApp` described below. Class description: XCTest hosted unit tests to run on devices. This is for the XCTest framework hosted unit tests running on devices. Stores data about tests: tests_app: full path to tests app. project_path: root project folder. module_name: egtest...
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
<|skeleton|> class DeviceXCTestUnitTestsApp: """XCTest hosted unit tests to run on devices. This is for the XCTest framework hosted unit tests running on devices. Stores data about tests: tests_app: full path to tests app. project_path: root project folder. module_name: egtests module name. included_tests: List of ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DeviceXCTestUnitTestsApp: """XCTest hosted unit tests to run on devices. This is for the XCTest framework hosted unit tests running on devices. Stores data about tests: tests_app: full path to tests app. project_path: root project folder. module_name: egtests module name. included_tests: List of tests to run....
the_stack_v2_python_sparse
ios/build/bots/scripts/test_apps.py
chromium/chromium
train
17,408
3f781aac821dda05baa8d8a105a05895aa9de4b0
[ "EPF.download(directory)\nclass_group = EPFInfo.get_group(group)\npath = f'{directory}/epf/datasets'\nfile = f'{path}/{group}.csv'\ndf = pd.read_csv(file)\ndf.columns = ['ds', 'y'] + [f'Exogenous{i}' for i in range(1, len(df.columns) - 1)]\ndf['unique_id'] = group\ndf['ds'] = pd.to_datetime(df['ds'])\ndf['week_day'...
<|body_start_0|> EPF.download(directory) class_group = EPFInfo.get_group(group) path = f'{directory}/epf/datasets' file = f'{path}/{group}.csv' df = pd.read_csv(file) df.columns = ['ds', 'y'] + [f'Exogenous{i}' for i in range(1, len(df.columns) - 1)] df['unique_id...
EPF
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EPF: def load(directory: str, group: str) -> Tuple[pd.DataFrame, Optional[pd.DataFrame], Optional[pd.DataFrame]]: """Downloads and loads EPF data. Parameters ---------- directory: str Directory where data will be downloaded. group: str Group name. Allowed groups: 'NP', 'PJM', 'BE', 'FR',...
stack_v2_sparse_classes_75kplus_train_066263
5,353
permissive
[ { "docstring": "Downloads and loads EPF data. Parameters ---------- directory: str Directory where data will be downloaded. group: str Group name. Allowed groups: 'NP', 'PJM', 'BE', 'FR', 'DE'.", "name": "load", "signature": "def load(directory: str, group: str) -> Tuple[pd.DataFrame, Optional[pd.DataFr...
3
stack_v2_sparse_classes_30k_train_018116
Implement the Python class `EPF` described below. Class description: Implement the EPF class. Method signatures and docstrings: - def load(directory: str, group: str) -> Tuple[pd.DataFrame, Optional[pd.DataFrame], Optional[pd.DataFrame]]: Downloads and loads EPF data. Parameters ---------- directory: str Directory wh...
Implement the Python class `EPF` described below. Class description: Implement the EPF class. Method signatures and docstrings: - def load(directory: str, group: str) -> Tuple[pd.DataFrame, Optional[pd.DataFrame], Optional[pd.DataFrame]]: Downloads and loads EPF data. Parameters ---------- directory: str Directory wh...
cc4726198bd1f8ecddeb4faeab939f87d8df57e6
<|skeleton|> class EPF: def load(directory: str, group: str) -> Tuple[pd.DataFrame, Optional[pd.DataFrame], Optional[pd.DataFrame]]: """Downloads and loads EPF data. Parameters ---------- directory: str Directory where data will be downloaded. group: str Group name. Allowed groups: 'NP', 'PJM', 'BE', 'FR',...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EPF: def load(directory: str, group: str) -> Tuple[pd.DataFrame, Optional[pd.DataFrame], Optional[pd.DataFrame]]: """Downloads and loads EPF data. Parameters ---------- directory: str Directory where data will be downloaded. group: str Group name. Allowed groups: 'NP', 'PJM', 'BE', 'FR', 'DE'.""" ...
the_stack_v2_python_sparse
nixtlats/data/datasets/epf.py
dhutexas/nixtlats
train
0
f49d02863cdca5431859a3da1ebb79a26bc14c9c
[ "z = z.copy()\nz[z < 0] = 0\nz[z > 6] = 6\nreturn z", "z = z.copy()\nz[np.where(np.logical_and(z >= 0, z <= 6))] = 1\nz[z < 0] = 0\nz[z > 6] = 0\nreturn z" ]
<|body_start_0|> z = z.copy() z[z < 0] = 0 z[z > 6] = 6 return z <|end_body_0|> <|body_start_1|> z = z.copy() z[np.where(np.logical_and(z >= 0, z <= 6))] = 1 z[z < 0] = 0 z[z > 6] = 0 return z <|end_body_1|>
ReLU6
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReLU6: def f(self, z): """f: Real -> [0,inf)""" <|body_0|> def f_prime(self, z): """f: Real -> [0,inf)""" <|body_1|> <|end_skeleton|> <|body_start_0|> z = z.copy() z[z < 0] = 0 z[z > 6] = 6 return z <|end_body_0|> <|body_sta...
stack_v2_sparse_classes_75kplus_train_066264
2,027
no_license
[ { "docstring": "f: Real -> [0,inf)", "name": "f", "signature": "def f(self, z)" }, { "docstring": "f: Real -> [0,inf)", "name": "f_prime", "signature": "def f_prime(self, z)" } ]
2
stack_v2_sparse_classes_30k_train_043707
Implement the Python class `ReLU6` described below. Class description: Implement the ReLU6 class. Method signatures and docstrings: - def f(self, z): f: Real -> [0,inf) - def f_prime(self, z): f: Real -> [0,inf)
Implement the Python class `ReLU6` described below. Class description: Implement the ReLU6 class. Method signatures and docstrings: - def f(self, z): f: Real -> [0,inf) - def f_prime(self, z): f: Real -> [0,inf) <|skeleton|> class ReLU6: def f(self, z): """f: Real -> [0,inf)""" <|body_0|> d...
84e4ad5d1792fcce214d6be81c2175939a3a9a09
<|skeleton|> class ReLU6: def f(self, z): """f: Real -> [0,inf)""" <|body_0|> def f_prime(self, z): """f: Real -> [0,inf)""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ReLU6: def f(self, z): """f: Real -> [0,inf)""" z = z.copy() z[z < 0] = 0 z[z > 6] = 6 return z def f_prime(self, z): """f: Real -> [0,inf)""" z = z.copy() z[np.where(np.logical_and(z >= 0, z <= 6))] = 1 z[z < 0] = 0 z[z > 6]...
the_stack_v2_python_sparse
deep-q-learning/lib/activation_function.py
felixjchen/learning
train
0
1f0541256fd276183bf28bcfd9f444b62353313b
[ "files = self.files.all()\nresult = '<ul class=\"order-files-list\">'\nfor file_obj in files:\n result += '<li><a href=\"%s%s\" target=\"_blank\">%s</a></li>' % (settings.SITE_URL, file_obj.data.url, file_obj.filename)\nresult += '</ul>'\nreturn result", "try:\n upload = Upload.objects.get(data=attachment, ...
<|body_start_0|> files = self.files.all() result = '<ul class="order-files-list">' for file_obj in files: result += '<li><a href="%s%s" target="_blank">%s</a></li>' % (settings.SITE_URL, file_obj.data.url, file_obj.filename) result += '</ul>' return result <|end_body_...
Миксин для моделей с возможностью загрузки файлов
UploadMixin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UploadMixin: """Миксин для моделей с возможностью загрузки файлов""" def files_list(self): """Выводит список файлов объекта""" <|body_0|> def attach_file(self, attachment): """Добавляет файл к текущему объекту attachment - путь к файлу относительно MEDIA_URL""" ...
stack_v2_sparse_classes_75kplus_train_066265
3,750
no_license
[ { "docstring": "Выводит список файлов объекта", "name": "files_list", "signature": "def files_list(self)" }, { "docstring": "Добавляет файл к текущему объекту attachment - путь к файлу относительно MEDIA_URL", "name": "attach_file", "signature": "def attach_file(self, attachment)" } ]
2
stack_v2_sparse_classes_30k_train_054256
Implement the Python class `UploadMixin` described below. Class description: Миксин для моделей с возможностью загрузки файлов Method signatures and docstrings: - def files_list(self): Выводит список файлов объекта - def attach_file(self, attachment): Добавляет файл к текущему объекту attachment - путь к файлу относи...
Implement the Python class `UploadMixin` described below. Class description: Миксин для моделей с возможностью загрузки файлов Method signatures and docstrings: - def files_list(self): Выводит список файлов объекта - def attach_file(self, attachment): Добавляет файл к текущему объекту attachment - путь к файлу относи...
20cee1aee02da192c9c79a51bd0898c1dba0c98f
<|skeleton|> class UploadMixin: """Миксин для моделей с возможностью загрузки файлов""" def files_list(self): """Выводит список файлов объекта""" <|body_0|> def attach_file(self, attachment): """Добавляет файл к текущему объекту attachment - путь к файлу относительно MEDIA_URL""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UploadMixin: """Миксин для моделей с возможностью загрузки файлов""" def files_list(self): """Выводит список файлов объекта""" files = self.files.all() result = '<ul class="order-files-list">' for file_obj in files: result += '<li><a href="%s%s" target="_blank"...
the_stack_v2_python_sparse
apps/uploadifive/models.py
Emilnurg/anas.ru
train
0
c5b69d72cf595b9a998ed6cc341f8fe436254f26
[ "self.oldstdout = sys.stdout\nself.oldstderr = sys.stderr\nos.chdir(self.config['rundir'])", "service.IService(self.application).privilegedStartService()\napp.startApplication(self.application, not self.config['no_save'])\napp.startApplication(internet.TimerService(0.1, lambda: None), 0)\nself.startReactor(None, ...
<|body_start_0|> self.oldstdout = sys.stdout self.oldstderr = sys.stderr os.chdir(self.config['rundir']) <|end_body_0|> <|body_start_1|> service.IService(self.application).privilegedStartService() app.startApplication(self.application, not self.config['no_save']) app.sta...
An ApplicationRunner which avoids unix-specific things. No forking, no PID files, no privileges.
WindowsApplicationRunner
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WindowsApplicationRunner: """An ApplicationRunner which avoids unix-specific things. No forking, no PID files, no privileges.""" def preApplication(self): """Do pre-application-creation setup.""" <|body_0|> def postApplication(self): """Start the application and ...
stack_v2_sparse_classes_75kplus_train_066266
1,540
permissive
[ { "docstring": "Do pre-application-creation setup.", "name": "preApplication", "signature": "def preApplication(self)" }, { "docstring": "Start the application and run the reactor.", "name": "postApplication", "signature": "def postApplication(self)" } ]
2
null
Implement the Python class `WindowsApplicationRunner` described below. Class description: An ApplicationRunner which avoids unix-specific things. No forking, no PID files, no privileges. Method signatures and docstrings: - def preApplication(self): Do pre-application-creation setup. - def postApplication(self): Start...
Implement the Python class `WindowsApplicationRunner` described below. Class description: An ApplicationRunner which avoids unix-specific things. No forking, no PID files, no privileges. Method signatures and docstrings: - def preApplication(self): Do pre-application-creation setup. - def postApplication(self): Start...
5cee0a8c4180a3108538b4e4ce945a18726595a6
<|skeleton|> class WindowsApplicationRunner: """An ApplicationRunner which avoids unix-specific things. No forking, no PID files, no privileges.""" def preApplication(self): """Do pre-application-creation setup.""" <|body_0|> def postApplication(self): """Start the application and ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class WindowsApplicationRunner: """An ApplicationRunner which avoids unix-specific things. No forking, no PID files, no privileges.""" def preApplication(self): """Do pre-application-creation setup.""" self.oldstdout = sys.stdout self.oldstderr = sys.stderr os.chdir(self.config[...
the_stack_v2_python_sparse
venv/Lib/site-packages/twisted/scripts/_twistw.py
zoelesv/Smathchat
train
9
cf565a0347de89bb47111b777c9e870d0d3f41c0
[ "self.A = copy.deepcopy(A)\nself.b = b\nself.n = A.colRank\nif x0 == 0:\n self.x0 = FullMatrix(self.n, 1)\nelse:\n self.x0 = x0\nself.tol = tol\nself.max_iter = max_iter\nself.D_inv = SparseMatrix(self.n, self.n)\nself.R = copy.deepcopy(A)\nfor i in range(self.n):\n aii = A.retrieveElement(i, i)\n self....
<|body_start_0|> self.A = copy.deepcopy(A) self.b = b self.n = A.colRank if x0 == 0: self.x0 = FullMatrix(self.n, 1) else: self.x0 = x0 self.tol = tol self.max_iter = max_iter self.D_inv = SparseMatrix(self.n, self.n) self.R...
An instance is a representation of the linear system to be solved using the Jacobi iterative method.
Jacobi_Solver
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Jacobi_Solver: """An instance is a representation of the linear system to be solved using the Jacobi iterative method.""" def __init__(self, A, b, x0=0, tol=10 ** (-9), max_iter=10 ** 100): """Initializes the matrix A, column matrix b, initial guess x0, tolerance, and maximum number ...
stack_v2_sparse_classes_75kplus_train_066267
2,750
no_license
[ { "docstring": "Initializes the matrix A, column matrix b, initial guess x0, tolerance, and maximum number of iterations max_iter. D_inv is the inverse of the diagonal matrix D obtained from the diagonal elements of A. R is the matrix obtained from (A - D) which is equivalent to (L+U) Db is the product obtained...
5
null
Implement the Python class `Jacobi_Solver` described below. Class description: An instance is a representation of the linear system to be solved using the Jacobi iterative method. Method signatures and docstrings: - def __init__(self, A, b, x0=0, tol=10 ** (-9), max_iter=10 ** 100): Initializes the matrix A, column m...
Implement the Python class `Jacobi_Solver` described below. Class description: An instance is a representation of the linear system to be solved using the Jacobi iterative method. Method signatures and docstrings: - def __init__(self, A, b, x0=0, tol=10 ** (-9), max_iter=10 ** 100): Initializes the matrix A, column m...
7439f25c7809f4198e452f70ae4269447873f7db
<|skeleton|> class Jacobi_Solver: """An instance is a representation of the linear system to be solved using the Jacobi iterative method.""" def __init__(self, A, b, x0=0, tol=10 ** (-9), max_iter=10 ** 100): """Initializes the matrix A, column matrix b, initial guess x0, tolerance, and maximum number ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Jacobi_Solver: """An instance is a representation of the linear system to be solved using the Jacobi iterative method.""" def __init__(self, A, b, x0=0, tol=10 ** (-9), max_iter=10 ** 100): """Initializes the matrix A, column matrix b, initial guess x0, tolerance, and maximum number of iterations...
the_stack_v2_python_sparse
PA2/jacobi.py
ta275/Scientific-Computing-in-Python
train
0
c983380edef5d95b87b808fb08bcc876c32012c0
[ "if not root:\n return ''\nstack = [root]\nres = ''\nwhile stack:\n for i in range(len(stack)):\n node = stack.pop(0)\n if not node:\n res += 'None,'\n else:\n res += str(node.val) + ','\n stack.append(node.left)\n stack.append(node.right)\nretu...
<|body_start_0|> if not root: return '' stack = [root] res = '' while stack: for i in range(len(stack)): node = stack.pop(0) if not node: res += 'None,' else: res += str(node.v...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_75kplus_train_066268
2,750
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
null
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
78285a8e1829999cde3fd72bd8564fe8ff383cff
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" if not root: return '' stack = [root] res = '' while stack: for i in range(len(stack)): node = stack.pop(0) ...
the_stack_v2_python_sparse
First Session(By Tag)/Tree/297.Serialize and Deserialize Binary Tree.py
SixuLi/Leetcode-Practice
train
0
8d664168fe10c45fdb84b7d3f9b78412096ef56c
[ "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...
Msg defines the staking Msg service.
MsgServicer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MsgServicer: """Msg defines the staking Msg service.""" def CreateValidator(self, request, context): """CreateValidator defines a method for creating a new validator.""" <|body_0|> def EditValidator(self, request, context): """EditValidator defines a method for e...
stack_v2_sparse_classes_75kplus_train_066269
10,044
permissive
[ { "docstring": "CreateValidator defines a method for creating a new validator.", "name": "CreateValidator", "signature": "def CreateValidator(self, request, context)" }, { "docstring": "EditValidator defines a method for editing an existing validator.", "name": "EditValidator", "signatur...
5
null
Implement the Python class `MsgServicer` described below. Class description: Msg defines the staking Msg service. Method signatures and docstrings: - def CreateValidator(self, request, context): CreateValidator defines a method for creating a new validator. - def EditValidator(self, request, context): EditValidator d...
Implement the Python class `MsgServicer` described below. Class description: Msg defines the staking Msg service. Method signatures and docstrings: - def CreateValidator(self, request, context): CreateValidator defines a method for creating a new validator. - def EditValidator(self, request, context): EditValidator d...
c38a07458a36305457680196e8c47372008db5ab
<|skeleton|> class MsgServicer: """Msg defines the staking Msg service.""" def CreateValidator(self, request, context): """CreateValidator defines a method for creating a new validator.""" <|body_0|> def EditValidator(self, request, context): """EditValidator defines a method for e...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MsgServicer: """Msg defines the staking Msg service.""" def CreateValidator(self, request, context): """CreateValidator defines a method for creating a new validator.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise No...
the_stack_v2_python_sparse
bluzelle/codec/cosmos/staking/v1beta1/tx_pb2_grpc.py
hhio618/bluzelle-py
train
3
f17ee66118f23f08c23b01eb4527b6dd94baf973
[ "result = []\nappend = result.append\nget = PROPERTIES.get\nfor residue in sequence:\n append('O' if get(residue, 0) & HYDROPHOBIC else 'I')\nreturn ''.join(result)", "hhProperties = self.convertAAToHydrophobicHydrophilic(read.sequence)\nfor match in ALPHA_HELIX_PI.finditer(hhProperties):\n start = match.st...
<|body_start_0|> result = [] append = result.append get = PROPERTIES.get for residue in sequence: append('O' if get(residue, 0) & HYDROPHOBIC else 'I') return ''.join(result) <|end_body_0|> <|body_start_1|> hhProperties = self.convertAAToHydrophobicHydrophili...
A class for computing statistics based on Pi alpha helices. Based around the assumption that a pi alpha helix is composed of at least two repeats of one hydrophobic and then 4 hydrophilic amino acids.
AlphaHelix_pi
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AlphaHelix_pi: """A class for computing statistics based on Pi alpha helices. Based around the assumption that a pi alpha helix is composed of at least two repeats of one hydrophobic and then 4 hydrophilic amino acids.""" def convertAAToHydrophobicHydrophilic(self, sequence): """Take...
stack_v2_sparse_classes_75kplus_train_066270
1,555
no_license
[ { "docstring": "Takes an amino acid sequence, converts it to a sequence of hydrophobic / hydrophilic. @param sequence: an amino acid sequence.", "name": "convertAAToHydrophobicHydrophilic", "signature": "def convertAAToHydrophobicHydrophilic(self, sequence)" }, { "docstring": "A function that ch...
2
stack_v2_sparse_classes_30k_train_046217
Implement the Python class `AlphaHelix_pi` described below. Class description: A class for computing statistics based on Pi alpha helices. Based around the assumption that a pi alpha helix is composed of at least two repeats of one hydrophobic and then 4 hydrophilic amino acids. Method signatures and docstrings: - de...
Implement the Python class `AlphaHelix_pi` described below. Class description: A class for computing statistics based on Pi alpha helices. Based around the assumption that a pi alpha helix is composed of at least two repeats of one hydrophobic and then 4 hydrophilic amino acids. Method signatures and docstrings: - de...
3e848dfa66f5fd07f1fb709abc935baff9f43d87
<|skeleton|> class AlphaHelix_pi: """A class for computing statistics based on Pi alpha helices. Based around the assumption that a pi alpha helix is composed of at least two repeats of one hydrophobic and then 4 hydrophilic amino acids.""" def convertAAToHydrophobicHydrophilic(self, sequence): """Take...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AlphaHelix_pi: """A class for computing statistics based on Pi alpha helices. Based around the assumption that a pi alpha helix is composed of at least two repeats of one hydrophobic and then 4 hydrophilic amino acids.""" def convertAAToHydrophobicHydrophilic(self, sequence): """Takes an amino ac...
the_stack_v2_python_sparse
light/landmarks/alpha_helix_pi.py
acorg/light-matter
train
0
0d95949e900a2914e7da4d36065d6def2de59020
[ "cache_len = 100000\nself.random_prob_cache = np.random.random(size=(cache_len,))\nself.random_prob_ptr = cache_len - 1", "value = self.random_prob_cache[self.random_prob_ptr]\nself.random_prob_ptr -= 1\nif self.random_prob_ptr == -1:\n self.reset_random_prob()\nreturn value", "token = self.token_list[self.t...
<|body_start_0|> cache_len = 100000 self.random_prob_cache = np.random.random(size=(cache_len,)) self.random_prob_ptr = cache_len - 1 <|end_body_0|> <|body_start_1|> value = self.random_prob_cache[self.random_prob_ptr] self.random_prob_ptr -= 1 if self.random_prob_ptr ==...
A base class that generate multiple random numbers at the same time.
EfficientRandomGen
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EfficientRandomGen: """A base class that generate multiple random numbers at the same time.""" def reset_random_prob(self): """Generate many random numbers at the same time and cache them.""" <|body_0|> def get_random_prob(self): """Get a random number.""" ...
stack_v2_sparse_classes_75kplus_train_066271
14,026
no_license
[ { "docstring": "Generate many random numbers at the same time and cache them.", "name": "reset_random_prob", "signature": "def reset_random_prob(self)" }, { "docstring": "Get a random number.", "name": "get_random_prob", "signature": "def get_random_prob(self)" }, { "docstring": ...
3
stack_v2_sparse_classes_30k_train_050465
Implement the Python class `EfficientRandomGen` described below. Class description: A base class that generate multiple random numbers at the same time. Method signatures and docstrings: - def reset_random_prob(self): Generate many random numbers at the same time and cache them. - def get_random_prob(self): Get a ran...
Implement the Python class `EfficientRandomGen` described below. Class description: A base class that generate multiple random numbers at the same time. Method signatures and docstrings: - def reset_random_prob(self): Generate many random numbers at the same time and cache them. - def get_random_prob(self): Get a ran...
778156466bc06ab1e4ecd1661d8ad8b98023afca
<|skeleton|> class EfficientRandomGen: """A base class that generate multiple random numbers at the same time.""" def reset_random_prob(self): """Generate many random numbers at the same time and cache them.""" <|body_0|> def get_random_prob(self): """Get a random number.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EfficientRandomGen: """A base class that generate multiple random numbers at the same time.""" def reset_random_prob(self): """Generate many random numbers at the same time and cache them.""" cache_len = 100000 self.random_prob_cache = np.random.random(size=(cache_len,)) s...
the_stack_v2_python_sparse
data/gen_uda_dataset.py
mainliufeng/models
train
0
85003e042f2ee32a40d167c11ced6d3f6cc94ac6
[ "if not triangle:\n return 0\nn = len(triangle)\ndp = [[0] * n for _ in range(n)]\ndp[0][0] = triangle[0][0]\nfor i in range(1, n):\n dp[i][0] = dp[i - 1][0] + triangle[i][0]\n for j in range(1, i):\n dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j]) + triangle[i][j]\n dp[i][i] = dp[i - 1][i - 1] + ...
<|body_start_0|> if not triangle: return 0 n = len(triangle) dp = [[0] * n for _ in range(n)] dp[0][0] = triangle[0][0] for i in range(1, n): dp[i][0] = dp[i - 1][0] + triangle[i][0] for j in range(1, i): dp[i][j] = min(dp[i - 1...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def minimumTotal(self, triangle: list) -> int: """自顶向下的动态规划""" <|body_0|> def minimumTotal_1(self, triangle: list) -> int: """自底向上的动态规划""" <|body_1|> def minimumTotal_2(self, triangle: list) -> int: """自底向上的动态规划 空间优化 发现dp[i][j]只和下一层dp[i...
stack_v2_sparse_classes_75kplus_train_066272
1,739
no_license
[ { "docstring": "自顶向下的动态规划", "name": "minimumTotal", "signature": "def minimumTotal(self, triangle: list) -> int" }, { "docstring": "自底向上的动态规划", "name": "minimumTotal_1", "signature": "def minimumTotal_1(self, triangle: list) -> int" }, { "docstring": "自底向上的动态规划 空间优化 发现dp[i][j]只和下...
3
stack_v2_sparse_classes_30k_train_023838
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minimumTotal(self, triangle: list) -> int: 自顶向下的动态规划 - def minimumTotal_1(self, triangle: list) -> int: 自底向上的动态规划 - def minimumTotal_2(self, triangle: list) -> int: 自底向上的动态规划...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minimumTotal(self, triangle: list) -> int: 自顶向下的动态规划 - def minimumTotal_1(self, triangle: list) -> int: 自底向上的动态规划 - def minimumTotal_2(self, triangle: list) -> int: 自底向上的动态规划...
3508e1ce089131b19603c3206aab4cf43023bb19
<|skeleton|> class Solution: def minimumTotal(self, triangle: list) -> int: """自顶向下的动态规划""" <|body_0|> def minimumTotal_1(self, triangle: list) -> int: """自底向上的动态规划""" <|body_1|> def minimumTotal_2(self, triangle: list) -> int: """自底向上的动态规划 空间优化 发现dp[i][j]只和下一层dp[i...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def minimumTotal(self, triangle: list) -> int: """自顶向下的动态规划""" if not triangle: return 0 n = len(triangle) dp = [[0] * n for _ in range(n)] dp[0][0] = triangle[0][0] for i in range(1, n): dp[i][0] = dp[i - 1][0] + triangle[i][0]...
the_stack_v2_python_sparse
algorithm/leetcode/dp/14-三角形最小路径和.py
lxconfig/UbuntuCode_bak
train
0
c6534f2b02083cc2c84f178595179d566236d323
[ "logger.info('Processing BioBamBam Filtering')\nif configuration is None:\n configuration = {}\nself.configuration.update(configuration)", "output_files_generated = {}\noutput_metadata = {}\nb3f = biobambam(self.configuration)\nlogger.progress('BioBamBam Filter', status='RUNNING')\nb3f_files, b3f_meta = b3f.ru...
<|body_start_0|> logger.info('Processing BioBamBam Filtering') if configuration is None: configuration = {} self.configuration.update(configuration) <|end_body_0|> <|body_start_1|> output_files_generated = {} output_metadata = {} b3f = biobambam(self.configur...
Functions for filtering FastQ alignments with BioBamBam.
process_biobambam
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class process_biobambam: """Functions for filtering FastQ alignments with BioBamBam.""" def __init__(self, configuration=None): """Initialise the class Parameters ---------- configuration : dict a dictionary containing parameters that define how the operation should be carried out, which a...
stack_v2_sparse_classes_75kplus_train_066273
5,528
permissive
[ { "docstring": "Initialise the class Parameters ---------- configuration : dict a dictionary containing parameters that define how the operation should be carried out, which are specific to each Tool.", "name": "__init__", "signature": "def __init__(self, configuration=None)" }, { "docstring": "...
2
null
Implement the Python class `process_biobambam` described below. Class description: Functions for filtering FastQ alignments with BioBamBam. Method signatures and docstrings: - def __init__(self, configuration=None): Initialise the class Parameters ---------- configuration : dict a dictionary containing parameters tha...
Implement the Python class `process_biobambam` described below. Class description: Functions for filtering FastQ alignments with BioBamBam. Method signatures and docstrings: - def __init__(self, configuration=None): Initialise the class Parameters ---------- configuration : dict a dictionary containing parameters tha...
50c7115c0c1a6af48dc34f275e469d1b9eb02999
<|skeleton|> class process_biobambam: """Functions for filtering FastQ alignments with BioBamBam.""" def __init__(self, configuration=None): """Initialise the class Parameters ---------- configuration : dict a dictionary containing parameters that define how the operation should be carried out, which a...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class process_biobambam: """Functions for filtering FastQ alignments with BioBamBam.""" def __init__(self, configuration=None): """Initialise the class Parameters ---------- configuration : dict a dictionary containing parameters that define how the operation should be carried out, which are specific t...
the_stack_v2_python_sparse
process_biobambam.py
Multiscale-Genomics/mg-process-fastq
train
2
8e20764c59d17b909ac79ac9d57729e827c591db
[ "z = [0 for _ in range(len(s))]\nL, R = (0, 1)\nfor i in range(1, len(s)):\n if R <= i or z[i - L] >= R - i:\n z[i] = (z[i - L] if i + z[i - L] < R else R - i) if R > i else 0\n while i + z[i] < len(s) and s[i + z[i]] == s[z[i]]:\n z[i] += 1\n if i + z[i] > R:\n L, R = ...
<|body_start_0|> z = [0 for _ in range(len(s))] L, R = (0, 1) for i in range(1, len(s)): if R <= i or z[i - L] >= R - i: z[i] = (z[i - L] if i + z[i - L] < R else R - i) if R > i else 0 while i + z[i] < len(s) and s[i + z[i]] == s[z[i]]: ...
ZAlgorithm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ZAlgorithm: def longestSubstring(self, s): """:type s: str :rtype: str""" <|body_0|> def longestPalindrome(self, s): """:type s: str :rtype: str""" <|body_1|> <|end_skeleton|> <|body_start_0|> z = [0 for _ in range(len(s))] L, R = (0, 1) ...
stack_v2_sparse_classes_75kplus_train_066274
1,578
no_license
[ { "docstring": ":type s: str :rtype: str", "name": "longestSubstring", "signature": "def longestSubstring(self, s)" }, { "docstring": ":type s: str :rtype: str", "name": "longestPalindrome", "signature": "def longestPalindrome(self, s)" } ]
2
stack_v2_sparse_classes_30k_train_042343
Implement the Python class `ZAlgorithm` described below. Class description: Implement the ZAlgorithm class. Method signatures and docstrings: - def longestSubstring(self, s): :type s: str :rtype: str - def longestPalindrome(self, s): :type s: str :rtype: str
Implement the Python class `ZAlgorithm` described below. Class description: Implement the ZAlgorithm class. Method signatures and docstrings: - def longestSubstring(self, s): :type s: str :rtype: str - def longestPalindrome(self, s): :type s: str :rtype: str <|skeleton|> class ZAlgorithm: def longestSubstring(s...
0e93358ecd06e6c44637bc6f67f52c964bc2c1e2
<|skeleton|> class ZAlgorithm: def longestSubstring(self, s): """:type s: str :rtype: str""" <|body_0|> def longestPalindrome(self, s): """:type s: str :rtype: str""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ZAlgorithm: def longestSubstring(self, s): """:type s: str :rtype: str""" z = [0 for _ in range(len(s))] L, R = (0, 1) for i in range(1, len(s)): if R <= i or z[i - L] >= R - i: z[i] = (z[i - L] if i + z[i - L] < R else R - i) if R > i else 0 ...
the_stack_v2_python_sparse
z.py
easydaniel/leetcode
train
0
2697b628a60034f76dfd09e9f3cddeecb1e5d11e
[ "super(PreModParser, self).__init__(node)\nif not issubclass(node.process_class, CalculationFactory('premod')):\n raise exceptions.ParsingError('Can only parse PreModCalculation')", "try:\n output_folder = self.retrieved\nexcept exceptions.NotExistent:\n return self.exit_codes.ERROR_NO_RETRIEVED_FOLDE\nf...
<|body_start_0|> super(PreModParser, self).__init__(node) if not issubclass(node.process_class, CalculationFactory('premod')): raise exceptions.ParsingError('Can only parse PreModCalculation') <|end_body_0|> <|body_start_1|> try: output_folder = self.retrieved ex...
Parser class for parsing output of calculation.
PreModParser
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PreModParser: """Parser class for parsing output of calculation.""" def __init__(self, node): """Initialize Parser instance Checks that the ProcessNode being passed was produced by a PreModCalculation. :param node: ProcessNode of calculation :param type node: :class:`aiida.orm.Proces...
stack_v2_sparse_classes_75kplus_train_066275
2,374
permissive
[ { "docstring": "Initialize Parser instance Checks that the ProcessNode being passed was produced by a PreModCalculation. :param node: ProcessNode of calculation :param type node: :class:`aiida.orm.ProcessNode`", "name": "__init__", "signature": "def __init__(self, node)" }, { "docstring": "Parse...
2
stack_v2_sparse_classes_30k_train_011855
Implement the Python class `PreModParser` described below. Class description: Parser class for parsing output of calculation. Method signatures and docstrings: - def __init__(self, node): Initialize Parser instance Checks that the ProcessNode being passed was produced by a PreModCalculation. :param node: ProcessNode ...
Implement the Python class `PreModParser` described below. Class description: Parser class for parsing output of calculation. Method signatures and docstrings: - def __init__(self, node): Initialize Parser instance Checks that the ProcessNode being passed was produced by a PreModCalculation. :param node: ProcessNode ...
6c202841786edc8897a3b8a872792dadb78b13fd
<|skeleton|> class PreModParser: """Parser class for parsing output of calculation.""" def __init__(self, node): """Initialize Parser instance Checks that the ProcessNode being passed was produced by a PreModCalculation. :param node: ProcessNode of calculation :param type node: :class:`aiida.orm.Proces...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PreModParser: """Parser class for parsing output of calculation.""" def __init__(self, node): """Initialize Parser instance Checks that the ProcessNode being passed was produced by a PreModCalculation. :param node: ProcessNode of calculation :param type node: :class:`aiida.orm.ProcessNode`""" ...
the_stack_v2_python_sparse
aiida_premod/parsers/premod.py
SINTEF/aiida-premod
train
0
fcc183c46f90d3cf6067728dd8ce56a5a08d735c
[ "self.directory: str = directory\nself.files_summary: Dict[str, Dict[str, int]] = dict()\nself.analyze_files()", "py_files: List = [f for f in os.listdir(self.directory) if f.endswith('.py')]\nfor pyf in py_files:\n try:\n file: IO = open(os.path.join(self.directory, pyf), 'r')\n classes: int = 0...
<|body_start_0|> self.directory: str = directory self.files_summary: Dict[str, Dict[str, int]] = dict() self.analyze_files() <|end_body_0|> <|body_start_1|> py_files: List = [f for f in os.listdir(self.directory) if f.endswith('.py')] for pyf in py_files: try: ...
Class which checks for python files and analyzes the content.
FileAnalyzer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FileAnalyzer: """Class which checks for python files and analyzes the content.""" def __init__(self, directory: str) -> None: """Constructor to initialize data structure and call class methods analyze_files and pretty_print.""" <|body_0|> def analyze_files(self) -> None:...
stack_v2_sparse_classes_75kplus_train_066276
3,592
no_license
[ { "docstring": "Constructor to initialize data structure and call class methods analyze_files and pretty_print.", "name": "__init__", "signature": "def __init__(self, directory: str) -> None" }, { "docstring": "Your docstring should go here for the description of the method.", "name": "analy...
3
stack_v2_sparse_classes_30k_train_018961
Implement the Python class `FileAnalyzer` described below. Class description: Class which checks for python files and analyzes the content. Method signatures and docstrings: - def __init__(self, directory: str) -> None: Constructor to initialize data structure and call class methods analyze_files and pretty_print. - ...
Implement the Python class `FileAnalyzer` described below. Class description: Class which checks for python files and analyzes the content. Method signatures and docstrings: - def __init__(self, directory: str) -> None: Constructor to initialize data structure and call class methods analyze_files and pretty_print. - ...
f36e34adab9f2723890aa87e1e02fb20ffb440c5
<|skeleton|> class FileAnalyzer: """Class which checks for python files and analyzes the content.""" def __init__(self, directory: str) -> None: """Constructor to initialize data structure and call class methods analyze_files and pretty_print.""" <|body_0|> def analyze_files(self) -> None:...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FileAnalyzer: """Class which checks for python files and analyzes the content.""" def __init__(self, directory: str) -> None: """Constructor to initialize data structure and call class methods analyze_files and pretty_print.""" self.directory: str = directory self.files_summary: D...
the_stack_v2_python_sparse
Assignments/HW08_Aditya_Kulkarni.py
BeardedAmbivert/SSW-810-Python
train
0
af13a6efae40d4a59114f91cec56a62d07a72054
[ "node_set = sorted(reduce(lambda x, y: x + y, communities))\nassert (np.arange(len(node_set)) == np.array(node_set)).all(), 'communities is not a partition of {0, 1, ..., n-1}'\nself.no_vertices = len(node_set)\nself.communities = [np.array(c) for c in communities]\nself.no_communities = len(self.communities)\nmemb...
<|body_start_0|> node_set = sorted(reduce(lambda x, y: x + y, communities)) assert (np.arange(len(node_set)) == np.array(node_set)).all(), 'communities is not a partition of {0, 1, ..., n-1}' self.no_vertices = len(node_set) self.communities = [np.array(c) for c in communities] s...
Wilson, James D., Nathaniel T. Stevens, and William H. Woodall. ``Modeling and estimating change in temporal networks via a dynamic degree corrected stochastic block model.'' arXiv preprint arXiv:1605.04049 (2016).
DegreeCorrectedStochasticBlockModel
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DegreeCorrectedStochasticBlockModel: """Wilson, James D., Nathaniel T. Stevens, and William H. Woodall. ``Modeling and estimating change in temporal networks via a dynamic degree corrected stochastic block model.'' arXiv preprint arXiv:1605.04049 (2016).""" def __init__(self, communities, pr...
stack_v2_sparse_classes_75kplus_train_066277
6,435
permissive
[ { "docstring": ":param communities: (list of lists) partition of set {0, ..., n-1} :param prob_matrix: (np.ndarray(no_communities, no_communities)) inter- and intra-community link propensity :param theta: (np.ndarray(no_nodes,)) degree correction :param delta: (np.ndarray(no_communities,)) parameters to generat...
3
null
Implement the Python class `DegreeCorrectedStochasticBlockModel` described below. Class description: Wilson, James D., Nathaniel T. Stevens, and William H. Woodall. ``Modeling and estimating change in temporal networks via a dynamic degree corrected stochastic block model.'' arXiv preprint arXiv:1605.04049 (2016). Me...
Implement the Python class `DegreeCorrectedStochasticBlockModel` described below. Class description: Wilson, James D., Nathaniel T. Stevens, and William H. Woodall. ``Modeling and estimating change in temporal networks via a dynamic degree corrected stochastic block model.'' arXiv preprint arXiv:1605.04049 (2016). Me...
b76f8e4bae01fba3c48e13b1e1c5d9568a20b77c
<|skeleton|> class DegreeCorrectedStochasticBlockModel: """Wilson, James D., Nathaniel T. Stevens, and William H. Woodall. ``Modeling and estimating change in temporal networks via a dynamic degree corrected stochastic block model.'' arXiv preprint arXiv:1605.04049 (2016).""" def __init__(self, communities, pr...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DegreeCorrectedStochasticBlockModel: """Wilson, James D., Nathaniel T. Stevens, and William H. Woodall. ``Modeling and estimating change in temporal networks via a dynamic degree corrected stochastic block model.'' arXiv preprint arXiv:1605.04049 (2016).""" def __init__(self, communities, prob_matrix, th...
the_stack_v2_python_sparse
cdg/graph/sbm.py
gluon31/cdg
train
0
78db134fffac10f1e3c757a6506cbf1135214a5f
[ "rawline = self.file.readline()\nwhile rawline:\n rematch = self.line_re.match(rawline)\n if not rematch:\n rawline = self.file.readline()\n continue\n while rematch:\n rep = Replica()\n self.reps.append(rep)\n rep.index = [0 for i in range(self.numexchg)]\n rep.po...
<|body_start_0|> rawline = self.file.readline() while rawline: rematch = self.line_re.match(rawline) if not rematch: rawline = self.file.readline() continue while rematch: rep = Replica() self.reps.append...
Replica exchange log file
TempRemLog
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TempRemLog: """Replica exchange log file""" def _get_replicas(self): """Gets all of the replica information from the first block of repinfo""" <|body_0|> def _parse(self): """Parses the rem.log file and loads the data arrays""" <|body_1|> <|end_skeleton|...
stack_v2_sparse_classes_75kplus_train_066278
12,296
no_license
[ { "docstring": "Gets all of the replica information from the first block of repinfo", "name": "_get_replicas", "signature": "def _get_replicas(self)" }, { "docstring": "Parses the rem.log file and loads the data arrays", "name": "_parse", "signature": "def _parse(self)" } ]
2
stack_v2_sparse_classes_30k_val_001263
Implement the Python class `TempRemLog` described below. Class description: Replica exchange log file Method signatures and docstrings: - def _get_replicas(self): Gets all of the replica information from the first block of repinfo - def _parse(self): Parses the rem.log file and loads the data arrays
Implement the Python class `TempRemLog` described below. Class description: Replica exchange log file Method signatures and docstrings: - def _get_replicas(self): Gets all of the replica information from the first block of repinfo - def _parse(self): Parses the rem.log file and loads the data arrays <|skeleton|> cla...
5cec8112637be7a19c4aac893f612aa8c354b733
<|skeleton|> class TempRemLog: """Replica exchange log file""" def _get_replicas(self): """Gets all of the replica information from the first block of repinfo""" <|body_0|> def _parse(self): """Parses the rem.log file and loads the data arrays""" <|body_1|> <|end_skeleton|...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TempRemLog: """Replica exchange log file""" def _get_replicas(self): """Gets all of the replica information from the first block of repinfo""" rawline = self.file.readline() while rawline: rematch = self.line_re.match(rawline) if not rematch: ...
the_stack_v2_python_sparse
remd.py
jeff-wang/JmsScripts
train
0
cef4c317f83761400ab85fbddfa3f418936b94e8
[ "session = Session()\ntry:\n user = session.query(SystemUser).get(user_id)\n if user is None:\n raise falcon.HTTPNotFound()\n errors = validate_put(req.media, user_id, role_id, session)\n if errors:\n raise HTTPUnprocessableEntity(errors)\n user_role = find_user_role(user_id, role_id, s...
<|body_start_0|> session = Session() try: user = session.query(SystemUser).get(user_id) if user is None: raise falcon.HTTPNotFound() errors = validate_put(req.media, user_id, role_id, session) if errors: raise HTTPUnprocessa...
PUT and DELETE a system role to/from a user.
Item
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Item: """PUT and DELETE a system role to/from a user.""" def on_put(self, req, resp, user_id, role_id): """Adds a role to a system user. :param req: See Falcon Request documentation. :param resp: See Falcon Response documentation. :param user_id: The id of user. :param role_id: The i...
stack_v2_sparse_classes_75kplus_train_066279
2,870
no_license
[ { "docstring": "Adds a role to a system user. :param req: See Falcon Request documentation. :param resp: See Falcon Response documentation. :param user_id: The id of user. :param role_id: The id of role to be added.", "name": "on_put", "signature": "def on_put(self, req, resp, user_id, role_id)" }, ...
2
null
Implement the Python class `Item` described below. Class description: PUT and DELETE a system role to/from a user. Method signatures and docstrings: - def on_put(self, req, resp, user_id, role_id): Adds a role to a system user. :param req: See Falcon Request documentation. :param resp: See Falcon Response documentati...
Implement the Python class `Item` described below. Class description: PUT and DELETE a system role to/from a user. Method signatures and docstrings: - def on_put(self, req, resp, user_id, role_id): Adds a role to a system user. :param req: See Falcon Request documentation. :param resp: See Falcon Response documentati...
62723133595829230e5b589431a32cda3b092460
<|skeleton|> class Item: """PUT and DELETE a system role to/from a user.""" def on_put(self, req, resp, user_id, role_id): """Adds a role to a system user. :param req: See Falcon Request documentation. :param resp: See Falcon Response documentation. :param user_id: The id of user. :param role_id: The i...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Item: """PUT and DELETE a system role to/from a user.""" def on_put(self, req, resp, user_id, role_id): """Adds a role to a system user. :param req: See Falcon Request documentation. :param resp: See Falcon Response documentation. :param user_id: The id of user. :param role_id: The id of role to ...
the_stack_v2_python_sparse
knoweak/api/resources/system_user_role.py
psvaiter/knoweak-api
train
0
fdc2fbb7b22f2d2bb237b4c8d4129692f207ec7e
[ "self.stream = stream\nself.queue = Queue()\nself.thread = Thread(target=self.wait_output)\nself.thread.daemon = True\nself.thread.start()\nself.decoder = OutputDecoder()", "for line in iter(self.stream.readline, b''):\n self.queue.put(line)\nself.stream.close()", "result = []\ntry:\n for i in range(0, 10...
<|body_start_0|> self.stream = stream self.queue = Queue() self.thread = Thread(target=self.wait_output) self.thread.daemon = True self.thread.start() self.decoder = OutputDecoder() <|end_body_0|> <|body_start_1|> for line in iter(self.stream.readline, b''): ...
Non-blocking stream reader. Uses in WebConsole.
OutputReader
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OutputReader: """Non-blocking stream reader. Uses in WebConsole.""" def __init__(self, stream): """Creates thread which wait data from stream and put they in inter-thread queue :param stream: stream to read""" <|body_0|> def wait_output(self): """Reading thread e...
stack_v2_sparse_classes_75kplus_train_066280
1,670
permissive
[ { "docstring": "Creates thread which wait data from stream and put they in inter-thread queue :param stream: stream to read", "name": "__init__", "signature": "def __init__(self, stream)" }, { "docstring": "Reading thread entry point", "name": "wait_output", "signature": "def wait_output...
3
stack_v2_sparse_classes_30k_train_008822
Implement the Python class `OutputReader` described below. Class description: Non-blocking stream reader. Uses in WebConsole. Method signatures and docstrings: - def __init__(self, stream): Creates thread which wait data from stream and put they in inter-thread queue :param stream: stream to read - def wait_output(se...
Implement the Python class `OutputReader` described below. Class description: Non-blocking stream reader. Uses in WebConsole. Method signatures and docstrings: - def __init__(self, stream): Creates thread which wait data from stream and put they in inter-thread queue :param stream: stream to read - def wait_output(se...
a33ba547f553bcce415f7a54bd89c444f82e48ee
<|skeleton|> class OutputReader: """Non-blocking stream reader. Uses in WebConsole.""" def __init__(self, stream): """Creates thread which wait data from stream and put they in inter-thread queue :param stream: stream to read""" <|body_0|> def wait_output(self): """Reading thread e...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class OutputReader: """Non-blocking stream reader. Uses in WebConsole.""" def __init__(self, stream): """Creates thread which wait data from stream and put they in inter-thread queue :param stream: stream to read""" self.stream = stream self.queue = Queue() self.thread = Thread(...
the_stack_v2_python_sparse
Zoocmd/core/api/util/streams.py
worriy/zoo
train
0
7e2ec42e8a0146bff17f738a6c94158b7e8367d0
[ "if not matrix:\n return False\nfor x in xrange(len(matrix)):\n if target in matrix[x]:\n return True\nreturn False", "if not matrix:\n return False\nrow = len(matrix)\ncol = len(matrix[0])\nleft = 0\nright = row * col\nwhile left < right:\n mid = left + (right - left) / 2\n if matrix[mid / ...
<|body_start_0|> if not matrix: return False for x in xrange(len(matrix)): if target in matrix[x]: return True return False <|end_body_0|> <|body_start_1|> if not matrix: return False row = len(matrix) col = len(matrix[...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def searchMatrix(self, matrix, target): """:type matrix: List[List[int]] :type target: int :rtype: bool""" <|body_0|> def BinsearchMatrix(self, matrix, target): """:type matrix: List[List[int]] :type target: int :rtype: bool""" <|body_1|> def B...
stack_v2_sparse_classes_75kplus_train_066281
2,285
no_license
[ { "docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool", "name": "searchMatrix", "signature": "def searchMatrix(self, matrix, target)" }, { "docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool", "name": "BinsearchMatrix", "signature": "def Bins...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool - def BinsearchMatrix(self, matrix, target): :type matrix: List[List[int]] :t...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool - def BinsearchMatrix(self, matrix, target): :type matrix: List[List[int]] :t...
2d5fa4cd696d5035ea8859befeadc5cc436959c9
<|skeleton|> class Solution: def searchMatrix(self, matrix, target): """:type matrix: List[List[int]] :type target: int :rtype: bool""" <|body_0|> def BinsearchMatrix(self, matrix, target): """:type matrix: List[List[int]] :type target: int :rtype: bool""" <|body_1|> def B...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def searchMatrix(self, matrix, target): """:type matrix: List[List[int]] :type target: int :rtype: bool""" if not matrix: return False for x in xrange(len(matrix)): if target in matrix[x]: return True return False def Binse...
the_stack_v2_python_sparse
SourceCode/Python/Problem/00074.Search a 2D Matrix.py
roger6blog/LeetCode
train
0
88dba35202f1a18de87bb1f842951da36c7c6c24
[ "user = self.request.user\nusername = user.username\ntry:\n article = Article.objects.get(id=article_id)\nexcept:\n return Response({'error': 'No article with that id found.'}, status=status.HTTP_404_NOT_FOUND)\nbookmark = Bookmark.objects.filter(article_id=article_id)\nif bookmark.exists() and (not bookmark[...
<|body_start_0|> user = self.request.user username = user.username try: article = Article.objects.get(id=article_id) except: return Response({'error': 'No article with that id found.'}, status=status.HTTP_404_NOT_FOUND) bookmark = Bookmark.objects.filter(a...
Contains views that allow a user to create a single bookmark and fetch an article.
CreateBookmark
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CreateBookmark: """Contains views that allow a user to create a single bookmark and fetch an article.""" def post(self, request, article_id): """Accepts an article id argument as an int from the URL. Creates a bookmark object for an existing article. It then creates a relationship be...
stack_v2_sparse_classes_75kplus_train_066282
3,342
permissive
[ { "docstring": "Accepts an article id argument as an int from the URL. Creates a bookmark object for an existing article. It then creates a relationship between the current user object and the article bookmark.", "name": "post", "signature": "def post(self, request, article_id)" }, { "docstring"...
2
stack_v2_sparse_classes_30k_test_000743
Implement the Python class `CreateBookmark` described below. Class description: Contains views that allow a user to create a single bookmark and fetch an article. Method signatures and docstrings: - def post(self, request, article_id): Accepts an article id argument as an int from the URL. Creates a bookmark object f...
Implement the Python class `CreateBookmark` described below. Class description: Contains views that allow a user to create a single bookmark and fetch an article. Method signatures and docstrings: - def post(self, request, article_id): Accepts an article id argument as an int from the URL. Creates a bookmark object f...
4b14cce62be06c0bd652fcc9be3264d8c62f8718
<|skeleton|> class CreateBookmark: """Contains views that allow a user to create a single bookmark and fetch an article.""" def post(self, request, article_id): """Accepts an article id argument as an int from the URL. Creates a bookmark object for an existing article. It then creates a relationship be...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CreateBookmark: """Contains views that allow a user to create a single bookmark and fetch an article.""" def post(self, request, article_id): """Accepts an article id argument as an int from the URL. Creates a bookmark object for an existing article. It then creates a relationship between the cur...
the_stack_v2_python_sparse
authors/apps/bookmark/views.py
andela/ah-the-answer-backend
train
0
f26b3bed25a3f985b8e2299e4a2efbe94b7f9775
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn OnenotePage()", "from .notebook import Notebook\nfrom .onenote_entity_schema_object_model import OnenoteEntitySchemaObjectModel\nfrom .onenote_section import OnenoteSection\nfrom .page_links import PageLinks\nfrom .notebook import Note...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return OnenotePage() <|end_body_0|> <|body_start_1|> from .notebook import Notebook from .onenote_entity_schema_object_model import OnenoteEntitySchemaObjectModel from .onenote_section ...
OnenotePage
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OnenotePage: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> OnenotePage: """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: On...
stack_v2_sparse_classes_75kplus_train_066283
5,456
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: OnenotePage", "name": "create_from_discriminator_value", "signature": "def create_from_discriminator_value(p...
3
stack_v2_sparse_classes_30k_train_051196
Implement the Python class `OnenotePage` described below. Class description: Implement the OnenotePage class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> OnenotePage: Creates a new instance of the appropriate class based on discriminator value Args:...
Implement the Python class `OnenotePage` described below. Class description: Implement the OnenotePage class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> OnenotePage: Creates a new instance of the appropriate class based on discriminator value Args:...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class OnenotePage: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> OnenotePage: """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: On...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class OnenotePage: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> OnenotePage: """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: OnenotePage""" ...
the_stack_v2_python_sparse
msgraph/generated/models/onenote_page.py
microsoftgraph/msgraph-sdk-python
train
135
d284feb9047341fa3ce83d4216398ebe61aa9dd0
[ "if not (userName or tabelNumber):\n raise ValueError('Users must have an username and tabel number')\nuser = self.model(userName=userName, tabelNumber=tabelNumber)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user", "user = self.create_user(userName, tabelNumber, password=password)\nuser.is...
<|body_start_0|> if not (userName or tabelNumber): raise ValueError('Users must have an username and tabel number') user = self.model(userName=userName, tabelNumber=tabelNumber) user.set_password(password) user.save(using=self._db) return user <|end_body_0|> <|body_s...
UserKBManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserKBManager: def create_user(self, userName, tabelNumber, password=None): """Creates and saves a User with the given username, date of birth and password.""" <|body_0|> def create_superuser(self, userName, tabelNumber, password): """Creates and saves a superuser wi...
stack_v2_sparse_classes_75kplus_train_066284
4,079
no_license
[ { "docstring": "Creates and saves a User with the given username, date of birth and password.", "name": "create_user", "signature": "def create_user(self, userName, tabelNumber, password=None)" }, { "docstring": "Creates and saves a superuser with the given username, date of birth and password."...
2
null
Implement the Python class `UserKBManager` described below. Class description: Implement the UserKBManager class. Method signatures and docstrings: - def create_user(self, userName, tabelNumber, password=None): Creates and saves a User with the given username, date of birth and password. - def create_superuser(self, ...
Implement the Python class `UserKBManager` described below. Class description: Implement the UserKBManager class. Method signatures and docstrings: - def create_user(self, userName, tabelNumber, password=None): Creates and saves a User with the given username, date of birth and password. - def create_superuser(self, ...
a70f2b9c930a07b9db85b08e3bc725cef11d56f6
<|skeleton|> class UserKBManager: def create_user(self, userName, tabelNumber, password=None): """Creates and saves a User with the given username, date of birth and password.""" <|body_0|> def create_superuser(self, userName, tabelNumber, password): """Creates and saves a superuser wi...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UserKBManager: def create_user(self, userName, tabelNumber, password=None): """Creates and saves a User with the given username, date of birth and password.""" if not (userName or tabelNumber): raise ValueError('Users must have an username and tabel number') user = self.mod...
the_stack_v2_python_sparse
KB_Users/models.py
party13/ticketProject
train
0
901129522cc3a85bd4e23a8cd08ff7e9184bc8f0
[ "self._dist = dist\nself._p = dist.pmf\nself._domain = np.stack(domain)\nself._domain_inv = np.linalg.pinv(self._domain)", "q = np.dot(x, self._domain)\nq /= q.sum()\nreturn q", "q = self._q(x)\ndkl = relative_entropy(self._p, q)\nreturn dkl", "x0 = np.dot(self._p, self._domain_inv)\nbounds = [(0, 1)] * x0.si...
<|body_start_0|> self._dist = dist self._p = dist.pmf self._domain = np.stack(domain) self._domain_inv = np.linalg.pinv(self._domain) <|end_body_0|> <|body_start_1|> q = np.dot(x, self._domain) q /= q.sum() return q <|end_body_1|> <|body_start_2|> q = se...
An optimizer to find the minimum D_KL(p||q) given p and a restriction on the domain of q.
MinDKLOptimizer
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MinDKLOptimizer: """An optimizer to find the minimum D_KL(p||q) given p and a restriction on the domain of q.""" def __init__(self, dist, domain): """Initialize the optimizer. Parameters ---------- dist : Distribution The distribution `p`. domain : list of lists The pmfs defining the...
stack_v2_sparse_classes_75kplus_train_066285
5,557
permissive
[ { "docstring": "Initialize the optimizer. Parameters ---------- dist : Distribution The distribution `p`. domain : list of lists The pmfs defining the domain over which `q` is optimized.", "name": "__init__", "signature": "def __init__(self, dist, domain)" }, { "docstring": "Transform `x` into a...
5
stack_v2_sparse_classes_30k_train_041976
Implement the Python class `MinDKLOptimizer` described below. Class description: An optimizer to find the minimum D_KL(p||q) given p and a restriction on the domain of q. Method signatures and docstrings: - def __init__(self, dist, domain): Initialize the optimizer. Parameters ---------- dist : Distribution The distr...
Implement the Python class `MinDKLOptimizer` described below. Class description: An optimizer to find the minimum D_KL(p||q) given p and a restriction on the domain of q. Method signatures and docstrings: - def __init__(self, dist, domain): Initialize the optimizer. Parameters ---------- dist : Distribution The distr...
b13c5020a2b8524527a4a0db5a81d8549142228c
<|skeleton|> class MinDKLOptimizer: """An optimizer to find the minimum D_KL(p||q) given p and a restriction on the domain of q.""" def __init__(self, dist, domain): """Initialize the optimizer. Parameters ---------- dist : Distribution The distribution `p`. domain : list of lists The pmfs defining the...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MinDKLOptimizer: """An optimizer to find the minimum D_KL(p||q) given p and a restriction on the domain of q.""" def __init__(self, dist, domain): """Initialize the optimizer. Parameters ---------- dist : Distribution The distribution `p`. domain : list of lists The pmfs defining the domain over ...
the_stack_v2_python_sparse
dit/pid/measures/iproj.py
dit/dit
train
468
9ff5c1cc53d609e2729b3e61fd0dd7faddc563c9
[ "char_count = {}\nfor c in s:\n char_count[c] = char_count.get(c, 0) + 1\nmax_odd = 1\nmax_pal_len = 0\nhas_max_odd = False\nfor word in char_count:\n if char_count[word] % 2 == 0:\n max_pal_len += char_count[word]\n elif char_count[word] >= max_odd:\n has_max_odd = True\n max_pal_len ...
<|body_start_0|> char_count = {} for c in s: char_count[c] = char_count.get(c, 0) + 1 max_odd = 1 max_pal_len = 0 has_max_odd = False for word in char_count: if char_count[word] % 2 == 0: max_pal_len += char_count[word] ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def longestPalindrome1(self, s): """:type s: str :rtype: int""" <|body_0|> def longestPalindrome(self, s): """:type s: str :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> char_count = {} for c in s: char_cou...
stack_v2_sparse_classes_75kplus_train_066286
1,678
no_license
[ { "docstring": ":type s: str :rtype: int", "name": "longestPalindrome1", "signature": "def longestPalindrome1(self, s)" }, { "docstring": ":type s: str :rtype: int", "name": "longestPalindrome", "signature": "def longestPalindrome(self, s)" } ]
2
stack_v2_sparse_classes_30k_train_019213
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestPalindrome1(self, s): :type s: str :rtype: int - def longestPalindrome(self, s): :type s: str :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestPalindrome1(self, s): :type s: str :rtype: int - def longestPalindrome(self, s): :type s: str :rtype: int <|skeleton|> class Solution: def longestPalindrome1(sel...
852fad258f5070c7b93c35252f7404e85e709ea6
<|skeleton|> class Solution: def longestPalindrome1(self, s): """:type s: str :rtype: int""" <|body_0|> def longestPalindrome(self, s): """:type s: str :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def longestPalindrome1(self, s): """:type s: str :rtype: int""" char_count = {} for c in s: char_count[c] = char_count.get(c, 0) + 1 max_odd = 1 max_pal_len = 0 has_max_odd = False for word in char_count: if char_count[w...
the_stack_v2_python_sparse
401-500/409. Longest Palindrome.py
SunnyMarkLiu/LeetCode
train
1
59b0a26114af22dbfaee93ff23ee86ca39e2fdf5
[ "probabilities = []\nlist_theoretical_amplitude = []\nbest_algorithms = []\nconfigurations = []\nlist_number_calls_made = []\nimprovements = []\nfor eta_group in self._eta_groups:\n self._global_eta_group = eta_group\n result = self._compute_theoretical_best_configuration()\n best_algorithms.append(result[...
<|body_start_0|> probabilities = [] list_theoretical_amplitude = [] best_algorithms = [] configurations = [] list_number_calls_made = [] improvements = [] for eta_group in self._eta_groups: self._global_eta_group = eta_group result = self._...
Representation of the theoretical One Shot Optimization
TheoreticalOneShotEntangledOptimization
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TheoreticalOneShotEntangledOptimization: """Representation of the theoretical One Shot Optimization""" def compute_theoretical_optimal_results(self) -> TheoreticalOneShotEntangledOptimalConfigurations: """Finds out the theoretical optimal entangled configuration for each pair of atte...
stack_v2_sparse_classes_75kplus_train_066287
3,912
permissive
[ { "docstring": "Finds out the theoretical optimal entangled configuration for each pair of attenuation levels", "name": "compute_theoretical_optimal_results", "signature": "def compute_theoretical_optimal_results(self) -> TheoreticalOneShotEntangledOptimalConfigurations" }, { "docstring": "Find ...
2
stack_v2_sparse_classes_30k_train_019482
Implement the Python class `TheoreticalOneShotEntangledOptimization` described below. Class description: Representation of the theoretical One Shot Optimization Method signatures and docstrings: - def compute_theoretical_optimal_results(self) -> TheoreticalOneShotEntangledOptimalConfigurations: Finds out the theoreti...
Implement the Python class `TheoreticalOneShotEntangledOptimization` described below. Class description: Representation of the theoretical One Shot Optimization Method signatures and docstrings: - def compute_theoretical_optimal_results(self) -> TheoreticalOneShotEntangledOptimalConfigurations: Finds out the theoreti...
ea37fca21fc4c8cf7ac6a39b3a6666e8a4fe5a19
<|skeleton|> class TheoreticalOneShotEntangledOptimization: """Representation of the theoretical One Shot Optimization""" def compute_theoretical_optimal_results(self) -> TheoreticalOneShotEntangledOptimalConfigurations: """Finds out the theoretical optimal entangled configuration for each pair of atte...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TheoreticalOneShotEntangledOptimization: """Representation of the theoretical One Shot Optimization""" def compute_theoretical_optimal_results(self) -> TheoreticalOneShotEntangledOptimalConfigurations: """Finds out the theoretical optimal entangled configuration for each pair of attenuation level...
the_stack_v2_python_sparse
qcd/optimizations/theoreticaloneshotentangledoptimization.py
iamtxena/quantum-channel-discrimination
train
0
b6dc7579deb3358c6d85852a8fba19a696e533e2
[ "assert self.f.findString('3rd') == self.lines[2]\nassert self.f.currentLine() == self.lines[2]\nself.f.toEOF()\nassert self.f.findString('1st', backward=True) == self.lines[0]\nassert self.f.currentLine() == self.lines[0]", "assert self.f.findString('line', 2) == self.lines[1]\nassert self.f.currentLine() == sel...
<|body_start_0|> assert self.f.findString('3rd') == self.lines[2] assert self.f.currentLine() == self.lines[2] self.f.toEOF() assert self.f.findString('1st', backward=True) == self.lines[0] assert self.f.currentLine() == self.lines[0] <|end_body_0|> <|body_start_1|> asse...
Test findString
FileReaderFindStringTest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FileReaderFindStringTest: """Test findString""" def testFindStringBasic(self): """Findstring functionality/basic search""" <|body_0|> def testFindStringCounted(self): """Findstring functionality/counted search""" <|body_1|> def testFindStringNotFound...
stack_v2_sparse_classes_75kplus_train_066288
10,074
no_license
[ { "docstring": "Findstring functionality/basic search", "name": "testFindStringBasic", "signature": "def testFindStringBasic(self)" }, { "docstring": "Findstring functionality/counted search", "name": "testFindStringCounted", "signature": "def testFindStringCounted(self)" }, { "d...
4
stack_v2_sparse_classes_30k_train_000285
Implement the Python class `FileReaderFindStringTest` described below. Class description: Test findString Method signatures and docstrings: - def testFindStringBasic(self): Findstring functionality/basic search - def testFindStringCounted(self): Findstring functionality/counted search - def testFindStringNotFound(sel...
Implement the Python class `FileReaderFindStringTest` described below. Class description: Test findString Method signatures and docstrings: - def testFindStringBasic(self): Findstring functionality/basic search - def testFindStringCounted(self): Findstring functionality/counted search - def testFindStringNotFound(sel...
5f92b013018e65bea5354be95e2538b5434d1fe7
<|skeleton|> class FileReaderFindStringTest: """Test findString""" def testFindStringBasic(self): """Findstring functionality/basic search""" <|body_0|> def testFindStringCounted(self): """Findstring functionality/counted search""" <|body_1|> def testFindStringNotFound...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FileReaderFindStringTest: """Test findString""" def testFindStringBasic(self): """Findstring functionality/basic search""" assert self.f.findString('3rd') == self.lines[2] assert self.f.currentLine() == self.lines[2] self.f.toEOF() assert self.f.findString('1st', b...
the_stack_v2_python_sparse
code/libraries/testFileReader20.py
stefanoborini/quantum-chemistry
train
0
4b0587f4d4fa067a590dc79ee2796214fa1a7d37
[ "if isinstance(test, TestModule):\n log.debug('isolating sys.modules changes in %s', test)\n self._mods = sys.modules.copy()", "if isinstance(test, TestModule):\n to_del = [m for m in sys.modules.keys() if m not in self._mods]\n if to_del:\n log.debug('removing sys modules entries: %s', to_del)...
<|body_start_0|> if isinstance(test, TestModule): log.debug('isolating sys.modules changes in %s', test) self._mods = sys.modules.copy() <|end_body_0|> <|body_start_1|> if isinstance(test, TestModule): to_del = [m for m in sys.modules.keys() if m not in self._mods] ...
Activate the isolation plugin to isolate changes to external modules to a single test module or package. The isolation plugin resets the contents of sys.modules after each test module or package runs to its state before the test. PLEASE NOTE that this plugin may not be used with the coverage plugin.
IsolationPlugin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IsolationPlugin: """Activate the isolation plugin to isolate changes to external modules to a single test module or package. The isolation plugin resets the contents of sys.modules after each test module or package runs to its state before the test. PLEASE NOTE that this plugin may not be used wi...
stack_v2_sparse_classes_75kplus_train_066289
2,101
no_license
[ { "docstring": "Save the state of sys.modules if we're starting a test module", "name": "startTest", "signature": "def startTest(self, test)" }, { "docstring": "Restore the saved state of sys.modules if we're ending a test module", "name": "stopTest", "signature": "def stopTest(self, tes...
2
stack_v2_sparse_classes_30k_train_010009
Implement the Python class `IsolationPlugin` described below. Class description: Activate the isolation plugin to isolate changes to external modules to a single test module or package. The isolation plugin resets the contents of sys.modules after each test module or package runs to its state before the test. PLEASE N...
Implement the Python class `IsolationPlugin` described below. Class description: Activate the isolation plugin to isolate changes to external modules to a single test module or package. The isolation plugin resets the contents of sys.modules after each test module or package runs to its state before the test. PLEASE N...
ca228848364edb204b15a7411fd6192379781c78
<|skeleton|> class IsolationPlugin: """Activate the isolation plugin to isolate changes to external modules to a single test module or package. The isolation plugin resets the contents of sys.modules after each test module or package runs to its state before the test. PLEASE NOTE that this plugin may not be used wi...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class IsolationPlugin: """Activate the isolation plugin to isolate changes to external modules to a single test module or package. The isolation plugin resets the contents of sys.modules after each test module or package runs to its state before the test. PLEASE NOTE that this plugin may not be used with the covera...
the_stack_v2_python_sparse
working-env/lib/python2.5/nose-0.9.3-py2.5.egg/nose/plugins/isolate.py
thraxil/gtreed
train
1
2f63d7bbb540347bc8af6a2cb9cabf9c4c17954d
[ "orderList = Shop_User(id=current_user.id).orderList\nif orderList:\n orderList = marshal(orderList, output_order)\n return Response(data=orderList)\nelse:\n return Response(code=HttpStatus.HTTP_404_NOT_FOUND, message='无符合条件的订单')", "args = reqparse.RequestParser().add_argument('order_id', type=str, locat...
<|body_start_0|> orderList = Shop_User(id=current_user.id).orderList if orderList: orderList = marshal(orderList, output_order) return Response(data=orderList) else: return Response(code=HttpStatus.HTTP_404_NOT_FOUND, message='无符合条件的订单') <|end_body_0|> <|body...
Order
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Order: def get(self): """获取个人订单 :return:""" <|body_0|> def post(self): """评价个人订单 :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> orderList = Shop_User(id=current_user.id).orderList if orderList: orderList = marshal(order...
stack_v2_sparse_classes_75kplus_train_066290
2,760
no_license
[ { "docstring": "获取个人订单 :return:", "name": "get", "signature": "def get(self)" }, { "docstring": "评价个人订单 :return:", "name": "post", "signature": "def post(self)" } ]
2
stack_v2_sparse_classes_30k_train_034786
Implement the Python class `Order` described below. Class description: Implement the Order class. Method signatures and docstrings: - def get(self): 获取个人订单 :return: - def post(self): 评价个人订单 :return:
Implement the Python class `Order` described below. Class description: Implement the Order class. Method signatures and docstrings: - def get(self): 获取个人订单 :return: - def post(self): 评价个人订单 :return: <|skeleton|> class Order: def get(self): """获取个人订单 :return:""" <|body_0|> def post(self): ...
34a2bf4a51cc40a22dd43cb5eb88af7c2f2c5120
<|skeleton|> class Order: def get(self): """获取个人订单 :return:""" <|body_0|> def post(self): """评价个人订单 :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Order: def get(self): """获取个人订单 :return:""" orderList = Shop_User(id=current_user.id).orderList if orderList: orderList = marshal(orderList, output_order) return Response(data=orderList) else: return Response(code=HttpStatus.HTTP_404_NOT_FOUN...
the_stack_v2_python_sparse
App/Shop/Controller/UserResource.py
Vulcanhy/api.grooo-master
train
0
afea820f7a66db0ac8e118890b779efacb2f0b5c
[ "if not preorder or not inorder:\n return None\nval = preorder[0]\nindex = inorder.index(val)\nleft_inorder = inorder[:index]\nright_inorder = inorder[index + 1:]\nleft_preorder = preorder[1:len(left_inorder) + 1]\nright_preorder = preorder[1 + len(left_inorder):]\nnode = TreeNode(val)\nnode.left = self.buildTre...
<|body_start_0|> if not preorder or not inorder: return None val = preorder[0] index = inorder.index(val) left_inorder = inorder[:index] right_inorder = inorder[index + 1:] left_preorder = preorder[1:len(left_inorder) + 1] right_preorder = preorder[1 +...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def buildTree(self, preorder, inorder): """根据先序遍历和中序遍历,构造二叉树 :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode""" <|body_0|> def buildTree2(self, preorder, inorder): """根据先序遍历和中序遍历,构造二叉树 :type preorder: List[int] :type inorder: List[int] :...
stack_v2_sparse_classes_75kplus_train_066291
2,512
no_license
[ { "docstring": "根据先序遍历和中序遍历,构造二叉树 :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode", "name": "buildTree", "signature": "def buildTree(self, preorder, inorder)" }, { "docstring": "根据先序遍历和中序遍历,构造二叉树 :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode", "name"...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def buildTree(self, preorder, inorder): 根据先序遍历和中序遍历,构造二叉树 :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode - def buildTree2(self, preorder, inorder): 根据先序遍历和中序...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def buildTree(self, preorder, inorder): 根据先序遍历和中序遍历,构造二叉树 :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode - def buildTree2(self, preorder, inorder): 根据先序遍历和中序...
04d87d76b762f6ea7cfb3a453382b2d7d4e154dc
<|skeleton|> class Solution: def buildTree(self, preorder, inorder): """根据先序遍历和中序遍历,构造二叉树 :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode""" <|body_0|> def buildTree2(self, preorder, inorder): """根据先序遍历和中序遍历,构造二叉树 :type preorder: List[int] :type inorder: List[int] :...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def buildTree(self, preorder, inorder): """根据先序遍历和中序遍历,构造二叉树 :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode""" if not preorder or not inorder: return None val = preorder[0] index = inorder.index(val) left_inorder = inorder[:ind...
the_stack_v2_python_sparse
leetcode/105 Construct Binary Tree from Preorder and Inorder Traversal.py
mofei952/algorithm_exercise
train
1
e31dfa3dce0318fdec3fef4e324bebae028a5e30
[ "stack = []\nfinalArr = []\nfor i in range(k):\n stack.append(nums.pop())\nfor i in range(len(stack)):\n finalArr.append(stack.pop())\nfor cur in nums:\n finalArr.append(cur)\nreturn finalArr", "k %= len(nums)\nj = 0\nfor i in range(len(nums) // 2):\n temp = nums[i]\n nums[i] = nums[len(nums) - 1 -...
<|body_start_0|> stack = [] finalArr = [] for i in range(k): stack.append(nums.pop()) for i in range(len(stack)): finalArr.append(stack.pop()) for cur in nums: finalArr.append(cur) return finalArr <|end_body_0|> <|body_start_1|> ...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def rotate(self, nums, k): """:type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.""" <|body_0|> def rotate_inplace(self, nums, k): """:type nums: List[int] :type k: int :rtype: void Do not return anything, m...
stack_v2_sparse_classes_75kplus_train_066292
2,053
permissive
[ { "docstring": ":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.", "name": "rotate", "signature": "def rotate(self, nums, k)" }, { "docstring": ":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place inste...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rotate(self, nums, k): :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. - def rotate_inplace(self, nums, k): :type nums: ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rotate(self, nums, k): :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. - def rotate_inplace(self, nums, k): :type nums: ...
889bde40bfcd4a4f25f889355f9c5a83b9ead7d7
<|skeleton|> class Solution: def rotate(self, nums, k): """:type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.""" <|body_0|> def rotate_inplace(self, nums, k): """:type nums: List[int] :type k: int :rtype: void Do not return anything, m...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def rotate(self, nums, k): """:type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.""" stack = [] finalArr = [] for i in range(k): stack.append(nums.pop()) for i in range(len(stack)): fina...
the_stack_v2_python_sparse
leetcode/easy/Arrays and Strings/RotateArray.py
rohan8594/DS-Algos
train
3
1cf037201d6afa486ec53a69b53cf18537942668
[ "if Resource.base_path == None:\n Resource.base_path = os.path.normpath(path)\nfull_path = os.path.join(os.path.dirname(rpicard.__file__), 'static', second, path)\nif full_path != os.path.abspath(full_path):\n raise RpiCarDExp(errorcode.PARAM_ERROR, \"path '%s' is invalid\" % path)\nreturn '.'.join((full_path...
<|body_start_0|> if Resource.base_path == None: Resource.base_path = os.path.normpath(path) full_path = os.path.join(os.path.dirname(rpicard.__file__), 'static', second, path) if full_path != os.path.abspath(full_path): raise RpiCarDExp(errorcode.PARAM_ERROR, "path '%s' i...
Resource
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Resource: def _get_full_path(self, second, path): """Get full path of resource. :second: second part of the path :path: relative file path without suffix :returns: full path""" <|body_0|> def _get_html(self, path): """Get the html resource. :path: relative file path ...
stack_v2_sparse_classes_75kplus_train_066293
3,121
permissive
[ { "docstring": "Get full path of resource. :second: second part of the path :path: relative file path without suffix :returns: full path", "name": "_get_full_path", "signature": "def _get_full_path(self, second, path)" }, { "docstring": "Get the html resource. :path: relative file path without s...
6
null
Implement the Python class `Resource` described below. Class description: Implement the Resource class. Method signatures and docstrings: - def _get_full_path(self, second, path): Get full path of resource. :second: second part of the path :path: relative file path without suffix :returns: full path - def _get_html(s...
Implement the Python class `Resource` described below. Class description: Implement the Resource class. Method signatures and docstrings: - def _get_full_path(self, second, path): Get full path of resource. :second: second part of the path :path: relative file path without suffix :returns: full path - def _get_html(s...
40a704247594ef2a9bde02e543b169d99804a011
<|skeleton|> class Resource: def _get_full_path(self, second, path): """Get full path of resource. :second: second part of the path :path: relative file path without suffix :returns: full path""" <|body_0|> def _get_html(self, path): """Get the html resource. :path: relative file path ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Resource: def _get_full_path(self, second, path): """Get full path of resource. :second: second part of the path :path: relative file path without suffix :returns: full path""" if Resource.base_path == None: Resource.base_path = os.path.normpath(path) full_path = os.path.jo...
the_stack_v2_python_sparse
rpicard/webserver/resource.py
fortime/rpicard
train
1
2ee640c9b20521d327afb3fcb75af63c9205460d
[ "user = get_object_or_404(User, id=pk)\nqueryset = Friendship.objects.filter(me=user)\nreturn Response({'friends': [{'id': f.counterpart.get_user_id(), 'username': f.counterpart.get_username(), 'profile_img': Profile.objects.get(user=f.counterpart).get_profile_img(), 'status_msg': Profile.objects.get(user=f.counter...
<|body_start_0|> user = get_object_or_404(User, id=pk) queryset = Friendship.objects.filter(me=user) return Response({'friends': [{'id': f.counterpart.get_user_id(), 'username': f.counterpart.get_username(), 'profile_img': Profile.objects.get(user=f.counterpart).get_profile_img(), 'status_msg': ...
FriendViewSet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FriendViewSet: def retrieve(self, request, pk=None): """## 친구 목록 조회하기 ### API url에 pk를 받아서 조회""" <|body_0|> def create(self, request): """## 친구 추가 ### API url에 pk를 받지만 실제론 토큰을 통해서 사용자를 구분한다.""" <|body_1|> def destroy(self, request, pk=None): """#...
stack_v2_sparse_classes_75kplus_train_066294
10,169
no_license
[ { "docstring": "## 친구 목록 조회하기 ### API url에 pk를 받아서 조회", "name": "retrieve", "signature": "def retrieve(self, request, pk=None)" }, { "docstring": "## 친구 추가 ### API url에 pk를 받지만 실제론 토큰을 통해서 사용자를 구분한다.", "name": "create", "signature": "def create(self, request)" }, { "docstring": "...
3
null
Implement the Python class `FriendViewSet` described below. Class description: Implement the FriendViewSet class. Method signatures and docstrings: - def retrieve(self, request, pk=None): ## 친구 목록 조회하기 ### API url에 pk를 받아서 조회 - def create(self, request): ## 친구 추가 ### API url에 pk를 받지만 실제론 토큰을 통해서 사용자를 구분한다. - def dest...
Implement the Python class `FriendViewSet` described below. Class description: Implement the FriendViewSet class. Method signatures and docstrings: - def retrieve(self, request, pk=None): ## 친구 목록 조회하기 ### API url에 pk를 받아서 조회 - def create(self, request): ## 친구 추가 ### API url에 pk를 받지만 실제론 토큰을 통해서 사용자를 구분한다. - def dest...
41a1bb3a23fed99b8816519ebf529fa029362180
<|skeleton|> class FriendViewSet: def retrieve(self, request, pk=None): """## 친구 목록 조회하기 ### API url에 pk를 받아서 조회""" <|body_0|> def create(self, request): """## 친구 추가 ### API url에 pk를 받지만 실제론 토큰을 통해서 사용자를 구분한다.""" <|body_1|> def destroy(self, request, pk=None): """#...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FriendViewSet: def retrieve(self, request, pk=None): """## 친구 목록 조회하기 ### API url에 pk를 받아서 조회""" user = get_object_or_404(User, id=pk) queryset = Friendship.objects.filter(me=user) return Response({'friends': [{'id': f.counterpart.get_user_id(), 'username': f.counterpart.get_us...
the_stack_v2_python_sparse
backend/accounts/views.py
applevalley/YOGOMOGO
train
0
4eb5ed949f32b4c3950f62125948fc484466660c
[ "username = self.cleaned_data.get('username')\nif not checkutils.username_correct(username):\n raise forms.ValidationError(_(u'Username may only contain alphanumeric characters or dashes and cannot begin with a dash'))\ntry:\n User.objects.get(username=username)\nexcept ObjectDoesNotExist:\n return usernam...
<|body_start_0|> username = self.cleaned_data.get('username') if not checkutils.username_correct(username): raise forms.ValidationError(_(u'Username may only contain alphanumeric characters or dashes and cannot begin with a dash')) try: User.objects.get(username=username)...
SignupForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SignupForm: def clean_username(self): """Checks if the user exists and that the username is only -a-zA-Z""" <|body_0|> def clean_password2(self): """Checks if the length is correct and both passwords are the same""" <|body_1|> def clean_email(self): ...
stack_v2_sparse_classes_75kplus_train_066295
3,700
no_license
[ { "docstring": "Checks if the user exists and that the username is only -a-zA-Z", "name": "clean_username", "signature": "def clean_username(self)" }, { "docstring": "Checks if the length is correct and both passwords are the same", "name": "clean_password2", "signature": "def clean_pass...
3
stack_v2_sparse_classes_30k_train_045663
Implement the Python class `SignupForm` described below. Class description: Implement the SignupForm class. Method signatures and docstrings: - def clean_username(self): Checks if the user exists and that the username is only -a-zA-Z - def clean_password2(self): Checks if the length is correct and both passwords are ...
Implement the Python class `SignupForm` described below. Class description: Implement the SignupForm class. Method signatures and docstrings: - def clean_username(self): Checks if the user exists and that the username is only -a-zA-Z - def clean_password2(self): Checks if the length is correct and both passwords are ...
bee916136a67f2203a7ca6078220553ae1ce9c3c
<|skeleton|> class SignupForm: def clean_username(self): """Checks if the user exists and that the username is only -a-zA-Z""" <|body_0|> def clean_password2(self): """Checks if the length is correct and both passwords are the same""" <|body_1|> def clean_email(self): ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SignupForm: def clean_username(self): """Checks if the user exists and that the username is only -a-zA-Z""" username = self.cleaned_data.get('username') if not checkutils.username_correct(username): raise forms.ValidationError(_(u'Username may only contain alphanumeric char...
the_stack_v2_python_sparse
dwarf/userprofile/forms.py
slok/dwarf
train
1
f2f1082816e85cd13bca5b0a6a2da3d5295a881b
[ "from statsmodels.tsa.api import VAR\nself.dim = timeseries.shape[1]\nself.order = r\nmodel = VAR(timeseries)\nresults = model.fit(r)\nself.summary = results.summary()\nself.covariance = results.sigma_u_mle\nself.mu = results.params[0, :]\nself.mu_std = results.stderr[0, :]\nself.phi = results.coefs\nself.phi_std =...
<|body_start_0|> from statsmodels.tsa.api import VAR self.dim = timeseries.shape[1] self.order = r model = VAR(timeseries) results = model.fit(r) self.summary = results.summary() self.covariance = results.sigma_u_mle self.mu = results.params[0, :] ...
VectorAutoRegression
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VectorAutoRegression: def __init__(self, timeseries, r): """Fit a vector autogressive (VAR) process to data using statsmodels.tsa.vector_ar. The output object is just reduction and renaming of attributes produced after running the fit() method of the VAR class For more detailed docs, see...
stack_v2_sparse_classes_75kplus_train_066296
26,530
permissive
[ { "docstring": "Fit a vector autogressive (VAR) process to data using statsmodels.tsa.vector_ar. The output object is just reduction and renaming of attributes produced after running the fit() method of the VAR class For more detailed docs, see: https://www.statsmodels.org/dev/vector_ar.html#module-statsmodels....
2
stack_v2_sparse_classes_30k_train_037618
Implement the Python class `VectorAutoRegression` described below. Class description: Implement the VectorAutoRegression class. Method signatures and docstrings: - def __init__(self, timeseries, r): Fit a vector autogressive (VAR) process to data using statsmodels.tsa.vector_ar. The output object is just reduction an...
Implement the Python class `VectorAutoRegression` described below. Class description: Implement the VectorAutoRegression class. Method signatures and docstrings: - def __init__(self, timeseries, r): Fit a vector autogressive (VAR) process to data using statsmodels.tsa.vector_ar. The output object is just reduction an...
e94694f298909352d7e9d912625314a1e46aa5b6
<|skeleton|> class VectorAutoRegression: def __init__(self, timeseries, r): """Fit a vector autogressive (VAR) process to data using statsmodels.tsa.vector_ar. The output object is just reduction and renaming of attributes produced after running the fit() method of the VAR class For more detailed docs, see...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class VectorAutoRegression: def __init__(self, timeseries, r): """Fit a vector autogressive (VAR) process to data using statsmodels.tsa.vector_ar. The output object is just reduction and renaming of attributes produced after running the fit() method of the VAR class For more detailed docs, see: https://www....
the_stack_v2_python_sparse
LLC_Membranes/llclib/timeseries.py
NKM-ML/LLC_Membranes
train
0
8718b8c740aebbfcd8dab32c1ed96e6262ae3970
[ "if not request.path.endswith('/manage/'):\n return None\ntry:\n telnet = pexpect.spawn('telnet', [settings.TELNET_HOST, str(settings.TELNET_PORT)], timeout=settings.TELNET_TIMEOUT)\n telnet.expect(':')\n telnet.sendline(settings.TELNET_USERNAME)\n telnet.expect(':')\n telnet.sendline(settings.TEL...
<|body_start_0|> if not request.path.endswith('/manage/'): return None try: telnet = pexpect.spawn('telnet', [settings.TELNET_HOST, str(settings.TELNET_PORT)], timeout=settings.TELNET_TIMEOUT) telnet.expect(':') telnet.sendline(settings.TELNET_USERNAME) ...
TelnetConnectionMiddleware
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TelnetConnectionMiddleware: def process_request(self, request): """Add a telnet connection to all request paths that start with /api/ assuming we only need to connect for these means we avoid unecessary overhead on any other functionality we add, and keeps URL path clear for it.""" ...
stack_v2_sparse_classes_75kplus_train_066297
4,315
no_license
[ { "docstring": "Add a telnet connection to all request paths that start with /api/ assuming we only need to connect for these means we avoid unecessary overhead on any other functionality we add, and keeps URL path clear for it.", "name": "process_request", "signature": "def process_request(self, reques...
2
null
Implement the Python class `TelnetConnectionMiddleware` described below. Class description: Implement the TelnetConnectionMiddleware class. Method signatures and docstrings: - def process_request(self, request): Add a telnet connection to all request paths that start with /api/ assuming we only need to connect for th...
Implement the Python class `TelnetConnectionMiddleware` described below. Class description: Implement the TelnetConnectionMiddleware class. Method signatures and docstrings: - def process_request(self, request): Add a telnet connection to all request paths that start with /api/ assuming we only need to connect for th...
d7dfe74a63663571178843d5e664b2121d4d5943
<|skeleton|> class TelnetConnectionMiddleware: def process_request(self, request): """Add a telnet connection to all request paths that start with /api/ assuming we only need to connect for these means we avoid unecessary overhead on any other functionality we add, and keeps URL path clear for it.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TelnetConnectionMiddleware: def process_request(self, request): """Add a telnet connection to all request paths that start with /api/ assuming we only need to connect for these means we avoid unecessary overhead on any other functionality we add, and keeps URL path clear for it.""" if not requ...
the_stack_v2_python_sparse
main/core/middleware.py
101t/jasmin-web-panel
train
66
5279be123f7f6bc9cea2641601a62070ae56e064
[ "self.net = net\nself.data = data\nself.optimizer = optimizer\nself.loss = loss\nself.step = step\nself.seed = 33", "paddle.enable_static()\npaddle.disable_static()\npaddle.seed(self.seed)\nnp.random.seed(self.seed)", "reset(self.seed)\nnet = self.net.get_layer()\nnet.train()\nopt = self.optimizer.get_opt(net=n...
<|body_start_0|> self.net = net self.data = data self.optimizer = optimizer self.loss = loss self.step = step self.seed = 33 <|end_body_0|> <|body_start_1|> paddle.enable_static() paddle.disable_static() paddle.seed(self.seed) np.random.se...
构建Layer训练的通用类
LayerTrain
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LayerTrain: """构建Layer训练的通用类""" def __init__(self, net, data, optimizer, loss, step): """初始化""" <|body_0|> def reset(self): """重置模型图 :return:""" <|body_1|> def dy_train(self): """dygraph train""" <|body_2|> def dy_train_dl(self):...
stack_v2_sparse_classes_75kplus_train_066298
4,955
no_license
[ { "docstring": "初始化", "name": "__init__", "signature": "def __init__(self, net, data, optimizer, loss, step)" }, { "docstring": "重置模型图 :return:", "name": "reset", "signature": "def reset(self)" }, { "docstring": "dygraph train", "name": "dy_train", "signature": "def dy_tr...
6
stack_v2_sparse_classes_30k_train_019689
Implement the Python class `LayerTrain` described below. Class description: 构建Layer训练的通用类 Method signatures and docstrings: - def __init__(self, net, data, optimizer, loss, step): 初始化 - def reset(self): 重置模型图 :return: - def dy_train(self): dygraph train - def dy_train_dl(self): dygraph train with dataloader - def dy2...
Implement the Python class `LayerTrain` described below. Class description: 构建Layer训练的通用类 Method signatures and docstrings: - def __init__(self, net, data, optimizer, loss, step): 初始化 - def reset(self): 重置模型图 :return: - def dy_train(self): dygraph train - def dy_train_dl(self): dygraph train with dataloader - def dy2...
bd3790ce72a2a26611b5eda3901651b5a809348f
<|skeleton|> class LayerTrain: """构建Layer训练的通用类""" def __init__(self, net, data, optimizer, loss, step): """初始化""" <|body_0|> def reset(self): """重置模型图 :return:""" <|body_1|> def dy_train(self): """dygraph train""" <|body_2|> def dy_train_dl(self):...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LayerTrain: """构建Layer训练的通用类""" def __init__(self, net, data, optimizer, loss, step): """初始化""" self.net = net self.data = data self.optimizer = optimizer self.loss = loss self.step = step self.seed = 33 def reset(self): """重置模型图 :retur...
the_stack_v2_python_sparse
framework/e2e/paddleLT/donotuse/train_origin.py
PaddlePaddle/PaddleTest
train
42
df95e6c92f8ee4009bc7db56a5188cd1c392f7f1
[ "self.name = name\nself.id = id\nself.date_time = date_time\nself.type = type\nself.payload = payload", "repr_string = '{}('.format(self.__class__.__name__)\nrepr_string += 'date_time={}, '.format(self.date_time)\nrepr_string += 'name={}, '.format(self.name)\nrepr_string += 'id={}, '.format(self.id)\nrepr_string ...
<|body_start_0|> self.name = name self.id = id self.date_time = date_time self.type = type self.payload = payload <|end_body_0|> <|body_start_1|> repr_string = '{}('.format(self.__class__.__name__) repr_string += 'date_time={}, '.format(self.date_time) re...
The Message class is used as the vessel for objects sent between process and threads over sockets, pipes and queues.
Message
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Message: """The Message class is used as the vessel for objects sent between process and threads over sockets, pipes and queues.""" def __init__(self, name, date_time, type, payload=None, id=0): """Initializes a Message with: Args: name: A string name of the sender. id: An integer in...
stack_v2_sparse_classes_75kplus_train_066299
1,521
no_license
[ { "docstring": "Initializes a Message with: Args: name: A string name of the sender. id: An integer index for objects that have multiple instances. date_time: None or a datetime object indicating the time sent. type: A string indicating the type of message sent. NOTE: An enum would be less error prone, but woul...
2
stack_v2_sparse_classes_30k_val_000973
Implement the Python class `Message` described below. Class description: The Message class is used as the vessel for objects sent between process and threads over sockets, pipes and queues. Method signatures and docstrings: - def __init__(self, name, date_time, type, payload=None, id=0): Initializes a Message with: A...
Implement the Python class `Message` described below. Class description: The Message class is used as the vessel for objects sent between process and threads over sockets, pipes and queues. Method signatures and docstrings: - def __init__(self, name, date_time, type, payload=None, id=0): Initializes a Message with: A...
e2b7136c7feda4deb667bd1e6cba3c1ef7eeff9d
<|skeleton|> class Message: """The Message class is used as the vessel for objects sent between process and threads over sockets, pipes and queues.""" def __init__(self, name, date_time, type, payload=None, id=0): """Initializes a Message with: Args: name: A string name of the sender. id: An integer in...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Message: """The Message class is used as the vessel for objects sent between process and threads over sockets, pipes and queues.""" def __init__(self, name, date_time, type, payload=None, id=0): """Initializes a Message with: Args: name: A string name of the sender. id: An integer index for objec...
the_stack_v2_python_sparse
shared/message.py
NickBayard/sf
train
0