blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c883e2a4c9d6a4881787f4f7cdae953c6e82070f | [
"self._tbirth = tbirth\nself._mass = mass\nself._metal = metal\nself._radiation = radiation\nself._wind = wind\nself._star = stars.Star(mass, metal, rotating=rotating)",
"integrator = weltgeist.integrator.Integrator()\nt = integrator.time\ndt = integrator.dt\nage = t - self._tbirth\nTeff = 0.0\nstar = self._star\... | <|body_start_0|>
self._tbirth = tbirth
self._mass = mass
self._metal = metal
self._radiation = radiation
self._wind = wind
self._star = stars.Star(mass, metal, rotating=rotating)
<|end_body_0|>
<|body_start_1|>
integrator = weltgeist.integrator.Integrator()
... | Source of energy & photons based on a lookup table | StellarSource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StellarSource:
"""Source of energy & photons based on a lookup table"""
def __init__(self, mass, metal, tbirth=0.0, radiation=True, wind=True, rotating=True):
"""Constructor Parameters ---------- mass : float Mass of star in solar masses tbirth : float Birth time of the star in secon... | stack_v2_sparse_classes_36k_train_023400 | 3,252 | no_license | [
{
"docstring": "Constructor Parameters ---------- mass : float Mass of star in solar masses tbirth : float Birth time of the star in seconds radiation : bool Turn radiation on? wind : bool Turn winds on? rotating : bool Use the Geneva rotating tracks?",
"name": "__init__",
"signature": "def __init__(sel... | 2 | stack_v2_sparse_classes_30k_train_003991 | Implement the Python class `StellarSource` described below.
Class description:
Source of energy & photons based on a lookup table
Method signatures and docstrings:
- def __init__(self, mass, metal, tbirth=0.0, radiation=True, wind=True, rotating=True): Constructor Parameters ---------- mass : float Mass of star in so... | Implement the Python class `StellarSource` described below.
Class description:
Source of energy & photons based on a lookup table
Method signatures and docstrings:
- def __init__(self, mass, metal, tbirth=0.0, radiation=True, wind=True, rotating=True): Constructor Parameters ---------- mass : float Mass of star in so... | d1ecb297daabc559e2a0ef045e5c032d4e492fb0 | <|skeleton|>
class StellarSource:
"""Source of energy & photons based on a lookup table"""
def __init__(self, mass, metal, tbirth=0.0, radiation=True, wind=True, rotating=True):
"""Constructor Parameters ---------- mass : float Mass of star in solar masses tbirth : float Birth time of the star in secon... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StellarSource:
"""Source of energy & photons based on a lookup table"""
def __init__(self, mass, metal, tbirth=0.0, radiation=True, wind=True, rotating=True):
"""Constructor Parameters ---------- mass : float Mass of star in solar masses tbirth : float Birth time of the star in seconds radiation ... | the_stack_v2_python_sparse | Shells/scripts/stellarsource.py | samgeen/mcrtscripts | train | 0 |
d70113f927a7cf062be3fa9350b0e2d074ff5909 | [
"self.pump = Pump('127.0.0.1', 8000)\nself.pump.set_state = MagicMock(return_value=True)\nself.new_sensor = Sensor('127.0.0.1', 8000)\nself.new_decider = Decider(100, 0.1)\nself.new_controller = Controller(self.new_sensor, self.pump, self.new_decider)\nself.actions = {'PUMP_IN': self.pump.PUMP_IN, 'PUMP_OUT': self.... | <|body_start_0|>
self.pump = Pump('127.0.0.1', 8000)
self.pump.set_state = MagicMock(return_value=True)
self.new_sensor = Sensor('127.0.0.1', 8000)
self.new_decider = Decider(100, 0.1)
self.new_controller = Controller(self.new_sensor, self.pump, self.new_decider)
self.act... | Unit tests for the Controller class | ControllerTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ControllerTests:
"""Unit tests for the Controller class"""
def setUp(self):
"""Sets the necessary varialbles to test the Controller class"""
<|body_0|>
def test_controller_tick(self):
"""Tests each of the behaviors defined in the Controller class"""
<|bod... | stack_v2_sparse_classes_36k_train_023401 | 5,129 | no_license | [
{
"docstring": "Sets the necessary varialbles to test the Controller class",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Tests each of the behaviors defined in the Controller class",
"name": "test_controller_tick",
"signature": "def test_controller_tick(self)"
}
... | 2 | stack_v2_sparse_classes_30k_train_001823 | Implement the Python class `ControllerTests` described below.
Class description:
Unit tests for the Controller class
Method signatures and docstrings:
- def setUp(self): Sets the necessary varialbles to test the Controller class
- def test_controller_tick(self): Tests each of the behaviors defined in the Controller c... | Implement the Python class `ControllerTests` described below.
Class description:
Unit tests for the Controller class
Method signatures and docstrings:
- def setUp(self): Sets the necessary varialbles to test the Controller class
- def test_controller_tick(self): Tests each of the behaviors defined in the Controller c... | b1fea0309b3495b3e1dc167d7029bc9e4b6f00f1 | <|skeleton|>
class ControllerTests:
"""Unit tests for the Controller class"""
def setUp(self):
"""Sets the necessary varialbles to test the Controller class"""
<|body_0|>
def test_controller_tick(self):
"""Tests each of the behaviors defined in the Controller class"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ControllerTests:
"""Unit tests for the Controller class"""
def setUp(self):
"""Sets the necessary varialbles to test the Controller class"""
self.pump = Pump('127.0.0.1', 8000)
self.pump.set_state = MagicMock(return_value=True)
self.new_sensor = Sensor('127.0.0.1', 8000)
... | the_stack_v2_python_sparse | students/rob_sanchez/lesson_06/Water_Regulation/waterregulation/test.py | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | train | 4 |
adeadef0a9995f28fbac2dc8a8e3efa9a3075c97 | [
"state = self.device.states.get(self.entity_description.key)\nif not state or not state.value:\n return None\nif self.entity_description.native_value:\n return self.entity_description.native_value(state.value)\nif isinstance(state.value, (dict, list)):\n return None\nreturn state.value",
"if not (default... | <|body_start_0|>
state = self.device.states.get(self.entity_description.key)
if not state or not state.value:
return None
if self.entity_description.native_value:
return self.entity_description.native_value(state.value)
if isinstance(state.value, (dict, list)):
... | Representation of an Overkiz Sensor. | OverkizStateSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OverkizStateSensor:
"""Representation of an Overkiz Sensor."""
def native_value(self) -> StateType:
"""Return the value of the sensor."""
<|body_0|>
def native_unit_of_measurement(self) -> str | None:
"""Return the unit of measurement."""
<|body_1|>
<|en... | stack_v2_sparse_classes_36k_train_023402 | 20,039 | permissive | [
{
"docstring": "Return the value of the sensor.",
"name": "native_value",
"signature": "def native_value(self) -> StateType"
},
{
"docstring": "Return the unit of measurement.",
"name": "native_unit_of_measurement",
"signature": "def native_unit_of_measurement(self) -> str | None"
}
] | 2 | stack_v2_sparse_classes_30k_train_012802 | Implement the Python class `OverkizStateSensor` described below.
Class description:
Representation of an Overkiz Sensor.
Method signatures and docstrings:
- def native_value(self) -> StateType: Return the value of the sensor.
- def native_unit_of_measurement(self) -> str | None: Return the unit of measurement. | Implement the Python class `OverkizStateSensor` described below.
Class description:
Representation of an Overkiz Sensor.
Method signatures and docstrings:
- def native_value(self) -> StateType: Return the value of the sensor.
- def native_unit_of_measurement(self) -> str | None: Return the unit of measurement.
<|ske... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class OverkizStateSensor:
"""Representation of an Overkiz Sensor."""
def native_value(self) -> StateType:
"""Return the value of the sensor."""
<|body_0|>
def native_unit_of_measurement(self) -> str | None:
"""Return the unit of measurement."""
<|body_1|>
<|en... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OverkizStateSensor:
"""Representation of an Overkiz Sensor."""
def native_value(self) -> StateType:
"""Return the value of the sensor."""
state = self.device.states.get(self.entity_description.key)
if not state or not state.value:
return None
if self.entity_des... | the_stack_v2_python_sparse | homeassistant/components/overkiz/sensor.py | home-assistant/core | train | 35,501 |
8e44d12efc2eb8f81bb8235c50df34da1b3839d1 | [
"cur_frame = None\ntry:\n 1 / 0\nexcept ZeroDivisionError:\n cur_frame = sys.exc_info()[2].tb_frame\nfor i in range(skip + 2):\n cur_frame = cur_frame.f_back\nstack_trace = []\nwhile cur_frame is not None:\n stack_trace.append((cur_frame, cur_frame.f_lineno))\n cur_frame = cur_frame.f_back\nreturn st... | <|body_start_0|>
cur_frame = None
try:
1 / 0
except ZeroDivisionError:
cur_frame = sys.exc_info()[2].tb_frame
for i in range(skip + 2):
cur_frame = cur_frame.f_back
stack_trace = []
while cur_frame is not None:
stack_trace.a... | Utilities for accessing the full stack trace of your application. | CommonStacktraceUtil | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommonStacktraceUtil:
"""Utilities for accessing the full stack trace of your application."""
def current_stack(skip: int=0) -> Any:
"""Retrieve the current stack :param skip: The number of lines to skip :return: A collection of the current stack."""
<|body_0|>
def _exte... | stack_v2_sparse_classes_36k_train_023403 | 2,612 | permissive | [
{
"docstring": "Retrieve the current stack :param skip: The number of lines to skip :return: A collection of the current stack.",
"name": "current_stack",
"signature": "def current_stack(skip: int=0) -> Any"
},
{
"docstring": "Extend traceback with stack info.",
"name": "_extend_traceback",
... | 4 | stack_v2_sparse_classes_30k_train_014542 | Implement the Python class `CommonStacktraceUtil` described below.
Class description:
Utilities for accessing the full stack trace of your application.
Method signatures and docstrings:
- def current_stack(skip: int=0) -> Any: Retrieve the current stack :param skip: The number of lines to skip :return: A collection o... | Implement the Python class `CommonStacktraceUtil` described below.
Class description:
Utilities for accessing the full stack trace of your application.
Method signatures and docstrings:
- def current_stack(skip: int=0) -> Any: Retrieve the current stack :param skip: The number of lines to skip :return: A collection o... | b59ea7e5f4bd01d3b3bd7603843d525a9c179867 | <|skeleton|>
class CommonStacktraceUtil:
"""Utilities for accessing the full stack trace of your application."""
def current_stack(skip: int=0) -> Any:
"""Retrieve the current stack :param skip: The number of lines to skip :return: A collection of the current stack."""
<|body_0|>
def _exte... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommonStacktraceUtil:
"""Utilities for accessing the full stack trace of your application."""
def current_stack(skip: int=0) -> Any:
"""Retrieve the current stack :param skip: The number of lines to skip :return: A collection of the current stack."""
cur_frame = None
try:
... | the_stack_v2_python_sparse | src/sims4communitylib/exceptions/common_stacktrace_utils.py | velocist/TS4CheatsInfo | train | 1 |
a4a17d12b3aa4a8266b98c4e28f4cbf48e0014d5 | [
"self.format = format\nself.trigmode = tmod\nself.atwa = [None] * 4\nself.atwb = [None] * 4\nself.atwd = [None] * 8\nself.fadc = []\nif format & 1:\n self.atwa[0] = self.atwd[0] = struct.unpack('128h', zbuf.read(256))\nif format & 2:\n self.atwa[1] = self.atwd[1] = struct.unpack('128h', zbuf.read(256))\nif fo... | <|body_start_0|>
self.format = format
self.trigmode = tmod
self.atwa = [None] * 4
self.atwb = [None] * 4
self.atwd = [None] * 8
self.fadc = []
if format & 1:
self.atwa[0] = self.atwd[0] = struct.unpack('128h', zbuf.read(256))
if format & 2:
... | Waveform hit class. This class contains data members that hold information about a 'hit' or waveform capture in the ATWD and/or FADC. There are also slots for the DOM clock information. - hit.atwa[i][j] : holds j-th sample of ATWD-A channel i - hit.atwb[i][j] : ibid. but for ATWD-B - hit.fadc[j] : only one FADC - hit.c... | hit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class hit:
"""Waveform hit class. This class contains data members that hold information about a 'hit' or waveform capture in the ATWD and/or FADC. There are also slots for the DOM clock information. - hit.atwa[i][j] : holds j-th sample of ATWD-A channel i - hit.atwb[i][j] : ibid. but for ATWD-B - hit.... | stack_v2_sparse_classes_36k_train_023404 | 21,290 | no_license | [
{
"docstring": "Unpack from acqX memory dump",
"name": "__init__",
"signature": "def __init__(self, zbuf, format, tmod)"
},
{
"docstring": "Write self out as engineering event",
"name": "toeng",
"signature": "def toeng(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016574 | Implement the Python class `hit` described below.
Class description:
Waveform hit class. This class contains data members that hold information about a 'hit' or waveform capture in the ATWD and/or FADC. There are also slots for the DOM clock information. - hit.atwa[i][j] : holds j-th sample of ATWD-A channel i - hit.a... | Implement the Python class `hit` described below.
Class description:
Waveform hit class. This class contains data members that hold information about a 'hit' or waveform capture in the ATWD and/or FADC. There are also slots for the DOM clock information. - hit.atwa[i][j] : holds j-th sample of ATWD-A channel i - hit.a... | 13cb63ba2390bbd49facb2d9093da528ae52cd91 | <|skeleton|>
class hit:
"""Waveform hit class. This class contains data members that hold information about a 'hit' or waveform capture in the ATWD and/or FADC. There are also slots for the DOM clock information. - hit.atwa[i][j] : holds j-th sample of ATWD-A channel i - hit.atwb[i][j] : ibid. but for ATWD-B - hit.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class hit:
"""Waveform hit class. This class contains data members that hold information about a 'hit' or waveform capture in the ATWD and/or FADC. There are also slots for the DOM clock information. - hit.atwa[i][j] : holds j-th sample of ATWD-A channel i - hit.atwb[i][j] : ibid. but for ATWD-B - hit.fadc[j] : onl... | the_stack_v2_python_sparse | icecube/domtest/ibidaq.py | dglo/PyDOM | train | 0 |
9a03b5e0bd5352662411677421c78850561bcf0e | [
"super().__init__(name, unique_id, sensor_type, sensor_configuration, weather_coordinator)\nself._weather_coordinator = weather_coordinator\nself._forecast_mode = forecast_mode\nself._attr_entity_registry_enabled_default = self._forecast_mode == FORECAST_MODE_DAILY",
"forecast = None\nforecasts = self._weather_co... | <|body_start_0|>
super().__init__(name, unique_id, sensor_type, sensor_configuration, weather_coordinator)
self._weather_coordinator = weather_coordinator
self._forecast_mode = forecast_mode
self._attr_entity_registry_enabled_default = self._forecast_mode == FORECAST_MODE_DAILY
<|end_bod... | Implementation of an AEMET OpenData forecast sensor. | AemetForecastSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AemetForecastSensor:
"""Implementation of an AEMET OpenData forecast sensor."""
def __init__(self, name, unique_id, sensor_type, sensor_configuration, weather_coordinator: WeatherUpdateCoordinator, forecast_mode):
"""Initialize the sensor."""
<|body_0|>
def state(self):
... | stack_v2_sparse_classes_36k_train_023405 | 4,513 | permissive | [
{
"docstring": "Initialize the sensor.",
"name": "__init__",
"signature": "def __init__(self, name, unique_id, sensor_type, sensor_configuration, weather_coordinator: WeatherUpdateCoordinator, forecast_mode)"
},
{
"docstring": "Return the state of the device.",
"name": "state",
"signatur... | 2 | stack_v2_sparse_classes_30k_train_000807 | Implement the Python class `AemetForecastSensor` described below.
Class description:
Implementation of an AEMET OpenData forecast sensor.
Method signatures and docstrings:
- def __init__(self, name, unique_id, sensor_type, sensor_configuration, weather_coordinator: WeatherUpdateCoordinator, forecast_mode): Initialize... | Implement the Python class `AemetForecastSensor` described below.
Class description:
Implementation of an AEMET OpenData forecast sensor.
Method signatures and docstrings:
- def __init__(self, name, unique_id, sensor_type, sensor_configuration, weather_coordinator: WeatherUpdateCoordinator, forecast_mode): Initialize... | 2fee32fce03bc49e86cf2e7b741a15621a97cce5 | <|skeleton|>
class AemetForecastSensor:
"""Implementation of an AEMET OpenData forecast sensor."""
def __init__(self, name, unique_id, sensor_type, sensor_configuration, weather_coordinator: WeatherUpdateCoordinator, forecast_mode):
"""Initialize the sensor."""
<|body_0|>
def state(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AemetForecastSensor:
"""Implementation of an AEMET OpenData forecast sensor."""
def __init__(self, name, unique_id, sensor_type, sensor_configuration, weather_coordinator: WeatherUpdateCoordinator, forecast_mode):
"""Initialize the sensor."""
super().__init__(name, unique_id, sensor_type,... | the_stack_v2_python_sparse | homeassistant/components/aemet/sensor.py | BenWoodford/home-assistant | train | 11 |
f275d0b0f76f511e5993cc7e2a7ff80d0b678fc6 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AttributeMappingSource()",
"from .attribute_mapping_source_type import AttributeMappingSourceType\nfrom .string_key_attribute_mapping_source_value_pair import StringKeyAttributeMappingSourceValuePair\nfrom .attribute_mapping_source_typ... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AttributeMappingSource()
<|end_body_0|>
<|body_start_1|>
from .attribute_mapping_source_type import AttributeMappingSourceType
from .string_key_attribute_mapping_source_value_pair import... | AttributeMappingSource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttributeMappingSource:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AttributeMappingSource:
"""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 ... | stack_v2_sparse_classes_36k_train_023406 | 4,212 | 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: AttributeMappingSource",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrimina... | 3 | stack_v2_sparse_classes_30k_train_015523 | Implement the Python class `AttributeMappingSource` described below.
Class description:
Implement the AttributeMappingSource class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AttributeMappingSource: Creates a new instance of the appropriate class b... | Implement the Python class `AttributeMappingSource` described below.
Class description:
Implement the AttributeMappingSource class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AttributeMappingSource: Creates a new instance of the appropriate class b... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AttributeMappingSource:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AttributeMappingSource:
"""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 ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AttributeMappingSource:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AttributeMappingSource:
"""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 Ret... | the_stack_v2_python_sparse | msgraph/generated/models/attribute_mapping_source.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
088ac256a3cf15785085c494bc69912280c63774 | [
"client = mock_client(mocker)\nargs = {'user-profile': {'email': 'testdemisto2@paloaltonetworks.com', 'givenname': 'mock_first_name'}}\nmocker.patch.object(client, 'get_user', return_value=None)\nmocker.patch.object(IAMUserProfile, 'map_object', return_value={})\nmocker.patch.object(client, 'create_user', return_va... | <|body_start_0|>
client = mock_client(mocker)
args = {'user-profile': {'email': 'testdemisto2@paloaltonetworks.com', 'givenname': 'mock_first_name'}}
mocker.patch.object(client, 'get_user', return_value=None)
mocker.patch.object(IAMUserProfile, 'map_object', return_value={})
mock... | Class to group the update user commands test | TestUpdateUserCommand | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestUpdateUserCommand:
"""Class to group the update user commands test"""
def test_update_user_command__non_existing_user(self, mocker):
"""Given: - An app client object - A user-profile argument that contains user data When: - The user does not exist in the application - create-if-n... | stack_v2_sparse_classes_36k_train_023407 | 13,964 | permissive | [
{
"docstring": "Given: - An app client object - A user-profile argument that contains user data When: - The user does not exist in the application - create-if-not-exists parameter is checked - Create User command is enabled - Calling function update_user_command Then: - Ensure the create action is executed - En... | 3 | stack_v2_sparse_classes_30k_train_003394 | Implement the Python class `TestUpdateUserCommand` described below.
Class description:
Class to group the update user commands test
Method signatures and docstrings:
- def test_update_user_command__non_existing_user(self, mocker): Given: - An app client object - A user-profile argument that contains user data When: -... | Implement the Python class `TestUpdateUserCommand` described below.
Class description:
Class to group the update user commands test
Method signatures and docstrings:
- def test_update_user_command__non_existing_user(self, mocker): Given: - An app client object - A user-profile argument that contains user data When: -... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class TestUpdateUserCommand:
"""Class to group the update user commands test"""
def test_update_user_command__non_existing_user(self, mocker):
"""Given: - An app client object - A user-profile argument that contains user data When: - The user does not exist in the application - create-if-n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestUpdateUserCommand:
"""Class to group the update user commands test"""
def test_update_user_command__non_existing_user(self, mocker):
"""Given: - An app client object - A user-profile argument that contains user data When: - The user does not exist in the application - create-if-not-exists par... | the_stack_v2_python_sparse | Packs/PrismaCloud/Integrations/PrismaCloudIAM/PrismaCloudIAM_test.py | demisto/content | train | 1,023 |
4fceb6d00774e69b63564ee7ba3e93eb2319ca15 | [
"if jwthandler.authorize_action(self, 2) == False:\n return None\nbody_categories = {'username': 1}\nuser_dict = errorutil.check_fields(self.request.arguments, body_categories, self)\nif user_dict == False:\n return None\nself.write({'user_id': userutil.get_uid(user_dict['username'])})",
"if jwthandler.auth... | <|body_start_0|>
if jwthandler.authorize_action(self, 2) == False:
return None
body_categories = {'username': 1}
user_dict = errorutil.check_fields(self.request.arguments, body_categories, self)
if user_dict == False:
return None
self.write({'user_id': use... | Class to handle password API requests Functions: get, put | User | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class User:
"""Class to handle password API requests Functions: get, put"""
def get(self):
"""Function to get user data Inputs: Tornado web request Output: User ID Caveats: Authentication needs to be passed"""
<|body_0|>
def put(self):
"""Function to change user data I... | stack_v2_sparse_classes_36k_train_023408 | 6,183 | no_license | [
{
"docstring": "Function to get user data Inputs: Tornado web request Output: User ID Caveats: Authentication needs to be passed",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Function to change user data Inputs: Tornado web request Output: Success message Caveats: Authenticati... | 2 | stack_v2_sparse_classes_30k_train_006694 | Implement the Python class `User` described below.
Class description:
Class to handle password API requests Functions: get, put
Method signatures and docstrings:
- def get(self): Function to get user data Inputs: Tornado web request Output: User ID Caveats: Authentication needs to be passed
- def put(self): Function ... | Implement the Python class `User` described below.
Class description:
Class to handle password API requests Functions: get, put
Method signatures and docstrings:
- def get(self): Function to get user data Inputs: Tornado web request Output: User ID Caveats: Authentication needs to be passed
- def put(self): Function ... | ee812db479ccd65bb319c1d5e268cd119952e2f0 | <|skeleton|>
class User:
"""Class to handle password API requests Functions: get, put"""
def get(self):
"""Function to get user data Inputs: Tornado web request Output: User ID Caveats: Authentication needs to be passed"""
<|body_0|>
def put(self):
"""Function to change user data I... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class User:
"""Class to handle password API requests Functions: get, put"""
def get(self):
"""Function to get user data Inputs: Tornado web request Output: User ID Caveats: Authentication needs to be passed"""
if jwthandler.authorize_action(self, 2) == False:
return None
bod... | the_stack_v2_python_sparse | src/handlers/api/user.py | FedoraTipper/AMS-Project | train | 0 |
6d6511175c5ad8137cae878375c3c96fcaa3ec9a | [
"if not root:\n return ''\nfrom collections import deque\nque, res = (deque(), [])\nque.append(root)\nwhile any(que):\n node = que.popleft()\n if not node:\n res.append('#')\n else:\n res.append(str(node.val))\n que.extend([node.left, node.right])\nreturn ' '.join(res)",
"nodes = ... | <|body_start_0|>
if not root:
return ''
from collections import deque
que, res = (deque(), [])
que.append(root)
while any(que):
node = que.popleft()
if not node:
res.append('#')
else:
res.append(str(n... | Codec | [
"MIT"
] | 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_36k_train_023409 | 1,754 | permissive | [
{
"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_008100 | 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:... | a61fd583e33a769b44ab758990625d3381793768 | <|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_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
from collections import deque
que, res = (deque(), [])
que.append(root)
while any(que):
node = que.popleft(... | the_stack_v2_python_sparse | LeetCodeSolutions/LeetCode_0297.py | lih627/python-algorithm-templates | train | 29 | |
98c5fc7247ee2cd1a88fcc51a0f750eb17392b81 | [
"self.stack = MinMaxStack()\nself.stack.push(5)\nself.stack.push(2)\nself.stack.push(7)\nself.stack.push(8)\nself.stack.pop()\nreturn self.stack",
"stack = self.SetUp()\nmin_val = stack.getMin()\nself.assertEqual(min_val, 2)",
"stack = self.SetUp()\nmax_val = stack.getMax()\nself.assertEqual(max_val, 7)",
"st... | <|body_start_0|>
self.stack = MinMaxStack()
self.stack.push(5)
self.stack.push(2)
self.stack.push(7)
self.stack.push(8)
self.stack.pop()
return self.stack
<|end_body_0|>
<|body_start_1|>
stack = self.SetUp()
min_val = stack.getMin()
self.a... | Class with unittests for MinMaxStackConstruction.py | test_MinMaxStackConstruction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_MinMaxStackConstruction:
"""Class with unittests for MinMaxStackConstruction.py"""
def SetUp(self):
"""Set Up input stack."""
<|body_0|>
def test_Min_method(self):
"""Checks if getMin() is correct."""
<|body_1|>
def test_Max_method(self):
... | stack_v2_sparse_classes_36k_train_023410 | 1,441 | no_license | [
{
"docstring": "Set Up input stack.",
"name": "SetUp",
"signature": "def SetUp(self)"
},
{
"docstring": "Checks if getMin() is correct.",
"name": "test_Min_method",
"signature": "def test_Min_method(self)"
},
{
"docstring": "Checks if getMax() is correct.",
"name": "test_Max_... | 4 | null | Implement the Python class `test_MinMaxStackConstruction` described below.
Class description:
Class with unittests for MinMaxStackConstruction.py
Method signatures and docstrings:
- def SetUp(self): Set Up input stack.
- def test_Min_method(self): Checks if getMin() is correct.
- def test_Max_method(self): Checks if ... | Implement the Python class `test_MinMaxStackConstruction` described below.
Class description:
Class with unittests for MinMaxStackConstruction.py
Method signatures and docstrings:
- def SetUp(self): Set Up input stack.
- def test_Min_method(self): Checks if getMin() is correct.
- def test_Max_method(self): Checks if ... | 3aa62ad36c3b06b2a3b05f1f8e2a9e21d68b371f | <|skeleton|>
class test_MinMaxStackConstruction:
"""Class with unittests for MinMaxStackConstruction.py"""
def SetUp(self):
"""Set Up input stack."""
<|body_0|>
def test_Min_method(self):
"""Checks if getMin() is correct."""
<|body_1|>
def test_Max_method(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class test_MinMaxStackConstruction:
"""Class with unittests for MinMaxStackConstruction.py"""
def SetUp(self):
"""Set Up input stack."""
self.stack = MinMaxStack()
self.stack.push(5)
self.stack.push(2)
self.stack.push(7)
self.stack.push(8)
self.stack.pop(... | the_stack_v2_python_sparse | AlgoExpert_algorithms/Medium/MinMaxStackConstruction/test_MinMaxStackConstruction.py | JakubKazimierski/PythonPortfolio | train | 9 |
3f1ed110fd2690216ccc93944995037fa7c4e902 | [
"for idx, c in enumerate(s):\n if c not in s[idx + 1:] and c not in s[:idx]:\n return idx\nreturn -1",
"m = {}\nfor c in s:\n m[c] = m.get(c, 0) + 1\nfor c in s:\n if m[c] == 1:\n return s.index(c)\nreturn -1",
"a = [0] * 26\nfor c in s:\n a[ord(c) - ord('a')] += 1\nfor c in s:\n if... | <|body_start_0|>
for idx, c in enumerate(s):
if c not in s[idx + 1:] and c not in s[:idx]:
return idx
return -1
<|end_body_0|>
<|body_start_1|>
m = {}
for c in s:
m[c] = m.get(c, 0) + 1
for c in s:
if m[c] == 1:
... | 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 案例: s = "leetcode" 返回 0. s = "loveleetcode", 返回 2. 注意事项:您可以假定该字符串只包含小写字母。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 案例: s = "leetcode" 返回 0. s = "loveleetcode", 返回 2. 注意事项:您可以假定该字符串只包含小写字母。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。"""
def firstUniqChar(self, s: str) -> i... | stack_v2_sparse_classes_36k_train_023411 | 2,094 | permissive | [
{
"docstring": "遍历字符串中的字符,如果满足以下两个条件,则返回idx 1. 该字符不存在于 s[:idx] 2. 该字符不存在于 s[idx + 1:] :param s: :return:",
"name": "firstUniqChar",
"signature": "def firstUniqChar(self, s: str) -> int"
},
{
"docstring": "1. 将所有字符存入dict,value表示出现的次数 2. 从头遍历一次字符串,第一次出现 value = 1 的字符就是要找字符 :param s: :return:",
... | 3 | stack_v2_sparse_classes_30k_train_017033 | Implement the Python class `Solution` described below.
Class description:
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 案例: s = "leetcode" 返回 0. s = "loveleetcode", 返回 2. 注意事项:您可以假定该字符串只包含小写字母。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Meth... | Implement the Python class `Solution` described below.
Class description:
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 案例: s = "leetcode" 返回 0. s = "loveleetcode", 返回 2. 注意事项:您可以假定该字符串只包含小写字母。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Meth... | d599e223bed1b957a1283face7606cb651b28ec4 | <|skeleton|>
class Solution:
"""给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 案例: s = "leetcode" 返回 0. s = "loveleetcode", 返回 2. 注意事项:您可以假定该字符串只包含小写字母。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。"""
def firstUniqChar(self, s: str) -> i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 案例: s = "leetcode" 返回 0. s = "loveleetcode", 返回 2. 注意事项:您可以假定该字符串只包含小写字母。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。"""
def firstUniqChar(self, s: str) -> int:
"... | the_stack_v2_python_sparse | problems/0387-first-unique-character-in-a-string.py | tzxyz/leetcode | train | 0 |
c053bf43c5e6d659a1a42a45b2352e74fd4e1fb7 | [
"args = parser.parse_args()\nif request.query_string:\n abort(400)\npost_data = request.get_json()\nif post_data.has_key('creator_id') and post_data.has_key('target1_id') and post_data.has_key('target2_id'):\n creator_id = post_data.get('creator_id')\n target1_id = post_data.get('target1_id')\n target2_... | <|body_start_0|>
args = parser.parse_args()
if request.query_string:
abort(400)
post_data = request.get_json()
if post_data.has_key('creator_id') and post_data.has_key('target1_id') and post_data.has_key('target2_id'):
creator_id = post_data.get('creator_id')
... | Matches | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Matches:
def post(self):
"""Creates match between the users with the given target_ids Request: POST /Matches { 'status': 'success', 'data': { 'creator_id' = creator_id 'target1_id' = target1_id 'target2_id' = target2_id } } Response: HTTP 200 OK { 'status': 'success', 'data': { 'match_id... | stack_v2_sparse_classes_36k_train_023412 | 6,658 | no_license | [
{
"docstring": "Creates match between the users with the given target_ids Request: POST /Matches { 'status': 'success', 'data': { 'creator_id' = creator_id 'target1_id' = target1_id 'target2_id' = target2_id } } Response: HTTP 200 OK { 'status': 'success', 'data': { 'match_id': match_id } }",
"name": "post"... | 2 | stack_v2_sparse_classes_30k_train_003966 | Implement the Python class `Matches` described below.
Class description:
Implement the Matches class.
Method signatures and docstrings:
- def post(self): Creates match between the users with the given target_ids Request: POST /Matches { 'status': 'success', 'data': { 'creator_id' = creator_id 'target1_id' = target1_i... | Implement the Python class `Matches` described below.
Class description:
Implement the Matches class.
Method signatures and docstrings:
- def post(self): Creates match between the users with the given target_ids Request: POST /Matches { 'status': 'success', 'data': { 'creator_id' = creator_id 'target1_id' = target1_i... | 6998dd53493e463c487f4dfb2a637dbcfe25593d | <|skeleton|>
class Matches:
def post(self):
"""Creates match between the users with the given target_ids Request: POST /Matches { 'status': 'success', 'data': { 'creator_id' = creator_id 'target1_id' = target1_id 'target2_id' = target2_id } } Response: HTTP 200 OK { 'status': 'success', 'data': { 'match_id... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Matches:
def post(self):
"""Creates match between the users with the given target_ids Request: POST /Matches { 'status': 'success', 'data': { 'creator_id' = creator_id 'target1_id' = target1_id 'target2_id' = target2_id } } Response: HTTP 200 OK { 'status': 'success', 'data': { 'match_id': match_id } ... | the_stack_v2_python_sparse | app/mod_api/resources/matches.py | I-C-Karakozis/HackPrinceton2017_Matchr | train | 1 | |
26537d9382d6f8363261e12c6a0c4e880ac9a552 | [
"self.force_delete = force_delete\nself.id = id\nself.include_marked_for_removal = include_marked_for_removal\nself.retry = retry",
"if dictionary is None:\n return None\nforce_delete = dictionary.get('forceDelete')\nid = dictionary.get('id')\ninclude_marked_for_removal = dictionary.get('includeMarkedForRemova... | <|body_start_0|>
self.force_delete = force_delete
self.id = id
self.include_marked_for_removal = include_marked_for_removal
self.retry = retry
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
force_delete = dictionary.get('forceDelete')
... | Implementation of the 'VaultDeleteParams' model. VaultDeleteParams represents the parameters needed to delete a specific vault. Attributes: force_delete (bool): Specifies whether to force delete the vault. If the flag is set to true, the RemovalState of the vault is changed to 'kMarkedForRemoval' and Eventually vault i... | VaultDeleteParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VaultDeleteParams:
"""Implementation of the 'VaultDeleteParams' model. VaultDeleteParams represents the parameters needed to delete a specific vault. Attributes: force_delete (bool): Specifies whether to force delete the vault. If the flag is set to true, the RemovalState of the vault is changed ... | stack_v2_sparse_classes_36k_train_023413 | 2,521 | permissive | [
{
"docstring": "Constructor for the VaultDeleteParams class",
"name": "__init__",
"signature": "def __init__(self, force_delete=None, id=None, include_marked_for_removal=None, retry=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dic... | 2 | stack_v2_sparse_classes_30k_train_019785 | Implement the Python class `VaultDeleteParams` described below.
Class description:
Implementation of the 'VaultDeleteParams' model. VaultDeleteParams represents the parameters needed to delete a specific vault. Attributes: force_delete (bool): Specifies whether to force delete the vault. If the flag is set to true, th... | Implement the Python class `VaultDeleteParams` described below.
Class description:
Implementation of the 'VaultDeleteParams' model. VaultDeleteParams represents the parameters needed to delete a specific vault. Attributes: force_delete (bool): Specifies whether to force delete the vault. If the flag is set to true, th... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class VaultDeleteParams:
"""Implementation of the 'VaultDeleteParams' model. VaultDeleteParams represents the parameters needed to delete a specific vault. Attributes: force_delete (bool): Specifies whether to force delete the vault. If the flag is set to true, the RemovalState of the vault is changed ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VaultDeleteParams:
"""Implementation of the 'VaultDeleteParams' model. VaultDeleteParams represents the parameters needed to delete a specific vault. Attributes: force_delete (bool): Specifies whether to force delete the vault. If the flag is set to true, the RemovalState of the vault is changed to 'kMarkedFo... | the_stack_v2_python_sparse | cohesity_management_sdk/models/vault_delete_params.py | cohesity/management-sdk-python | train | 24 |
d2e255737b5c37972a519266509de2d4291e2ac5 | [
"i = 0\nwhile i < len(arr):\n if len(arr[i:]) < m * k:\n return False\n j = 1\n while j < k:\n if arr[i:i + m] != arr[i + m * j:i + m * (j + 1)]:\n i += 1\n break\n elif arr[i:i + m] == arr[i + m * j:i + m * (j + 1)]:\n j += 1\n if j == k:\n r... | <|body_start_0|>
i = 0
while i < len(arr):
if len(arr[i:]) < m * k:
return False
j = 1
while j < k:
if arr[i:i + m] != arr[i + m * j:i + m * (j + 1)]:
i += 1
break
elif arr[i:i + m... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def containsPattern(self, arr, m, k):
""":type arr: List[int] :type m: int :type k: int :rtype: bool"""
<|body_0|>
def containsPattern(self, arr, m, k):
""":type arr: List[int] :type m: int :type k: int :rtype: bool"""
<|body_1|>
def containsPa... | stack_v2_sparse_classes_36k_train_023414 | 1,339 | no_license | [
{
"docstring": ":type arr: List[int] :type m: int :type k: int :rtype: bool",
"name": "containsPattern",
"signature": "def containsPattern(self, arr, m, k)"
},
{
"docstring": ":type arr: List[int] :type m: int :type k: int :rtype: bool",
"name": "containsPattern",
"signature": "def conta... | 3 | stack_v2_sparse_classes_30k_train_005014 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsPattern(self, arr, m, k): :type arr: List[int] :type m: int :type k: int :rtype: bool
- def containsPattern(self, arr, m, k): :type arr: List[int] :type m: int :type ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsPattern(self, arr, m, k): :type arr: List[int] :type m: int :type k: int :rtype: bool
- def containsPattern(self, arr, m, k): :type arr: List[int] :type m: int :type ... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def containsPattern(self, arr, m, k):
""":type arr: List[int] :type m: int :type k: int :rtype: bool"""
<|body_0|>
def containsPattern(self, arr, m, k):
""":type arr: List[int] :type m: int :type k: int :rtype: bool"""
<|body_1|>
def containsPa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def containsPattern(self, arr, m, k):
""":type arr: List[int] :type m: int :type k: int :rtype: bool"""
i = 0
while i < len(arr):
if len(arr[i:]) < m * k:
return False
j = 1
while j < k:
if arr[i:i + m] != ar... | the_stack_v2_python_sparse | 1566_Detect_Pattern_of_Length_M_Repeated_K_or_More.py | bingli8802/leetcode | train | 0 | |
e429e29171b0c1c1ecf7fabe03fc088b05a323d2 | [
"self.lstick = wpilib.Joystick(0)\nself.rstick = wpilib.Joystick(1)\nself.l_motor = wpilib.Jaguar(1)\nself.r_motor = wpilib.Jaguar(2)\nself.gyro = wpilib.AnalogGyro(1)\nself.robot_drive = wpilib.RobotDrive(self.l_motor, self.r_motor)\nself.motor = wpilib.Jaguar(4)\nself.light_sensor_left = wpilib.DigitalInput(1)\ns... | <|body_start_0|>
self.lstick = wpilib.Joystick(0)
self.rstick = wpilib.Joystick(1)
self.l_motor = wpilib.Jaguar(1)
self.r_motor = wpilib.Jaguar(2)
self.gyro = wpilib.AnalogGyro(1)
self.robot_drive = wpilib.RobotDrive(self.l_motor, self.r_motor)
self.motor = wpilib... | Main robot class | MyRobot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyRobot:
"""Main robot class"""
def robotInit(self):
"""Robot-wide initialization code should go here"""
<|body_0|>
def disabled(self):
"""Called when the robot is disabled"""
<|body_1|>
def autonomous(self):
"""Called when autonomous mode is... | stack_v2_sparse_classes_36k_train_023415 | 2,215 | no_license | [
{
"docstring": "Robot-wide initialization code should go here",
"name": "robotInit",
"signature": "def robotInit(self)"
},
{
"docstring": "Called when the robot is disabled",
"name": "disabled",
"signature": "def disabled(self)"
},
{
"docstring": "Called when autonomous mode is e... | 4 | stack_v2_sparse_classes_30k_train_000001 | Implement the Python class `MyRobot` described below.
Class description:
Main robot class
Method signatures and docstrings:
- def robotInit(self): Robot-wide initialization code should go here
- def disabled(self): Called when the robot is disabled
- def autonomous(self): Called when autonomous mode is enabled
- def ... | Implement the Python class `MyRobot` described below.
Class description:
Main robot class
Method signatures and docstrings:
- def robotInit(self): Robot-wide initialization code should go here
- def disabled(self): Called when the robot is disabled
- def autonomous(self): Called when autonomous mode is enabled
- def ... | ea9a960acddfbd045301feed846d49d669d13599 | <|skeleton|>
class MyRobot:
"""Main robot class"""
def robotInit(self):
"""Robot-wide initialization code should go here"""
<|body_0|>
def disabled(self):
"""Called when the robot is disabled"""
<|body_1|>
def autonomous(self):
"""Called when autonomous mode is... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyRobot:
"""Main robot class"""
def robotInit(self):
"""Robot-wide initialization code should go here"""
self.lstick = wpilib.Joystick(0)
self.rstick = wpilib.Joystick(1)
self.l_motor = wpilib.Jaguar(1)
self.r_motor = wpilib.Jaguar(2)
self.gyro = wpilib.Ana... | the_stack_v2_python_sparse | linefollowing/src/robot.py | McDowellRobotics63/FRC.63.2020 | train | 2 |
481e04e30e4ad1c375a1d9e98e6a9b55bc2cbc93 | [
"if not isinstance(hour, (list, tuple)):\n hour = [hour]\nif not isinstance(min, (list, tuple)):\n min = [min]\nif not isinstance(sec, (list, tuple)):\n sec = [sec]\nself._timings = (hour, min, sec)\nself._last_time = datetime.datetime.now()\nself._schedule_next()",
"hour, min, sec = self._timings\nnow =... | <|body_start_0|>
if not isinstance(hour, (list, tuple)):
hour = [hour]
if not isinstance(min, (list, tuple)):
min = [min]
if not isinstance(sec, (list, tuple)):
sec = [sec]
self._timings = (hour, min, sec)
self._last_time = datetime.datetime.no... | A timer that is triggered at a specific time of day. Once the timer fires it is stopped. | OneShotAtTimer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OneShotAtTimer:
"""A timer that is triggered at a specific time of day. Once the timer fires it is stopped."""
def start(self, hour=range(24), min=range(60), sec=0):
"""Starts the timer, causing it to be fired at the specified time. By default, the timer will fire every minute at 0 s... | stack_v2_sparse_classes_36k_train_023416 | 11,203 | no_license | [
{
"docstring": "Starts the timer, causing it to be fired at the specified time. By default, the timer will fire every minute at 0 seconds. The timer has second precision. :param hour: the hour number (0-23) or list of hours :type hour: int or list of ints :param min: the minute number (0-59) or list of minutes ... | 2 | null | Implement the Python class `OneShotAtTimer` described below.
Class description:
A timer that is triggered at a specific time of day. Once the timer fires it is stopped.
Method signatures and docstrings:
- def start(self, hour=range(24), min=range(60), sec=0): Starts the timer, causing it to be fired at the specified ... | Implement the Python class `OneShotAtTimer` described below.
Class description:
A timer that is triggered at a specific time of day. Once the timer fires it is stopped.
Method signatures and docstrings:
- def start(self, hour=range(24), min=range(60), sec=0): Starts the timer, causing it to be fired at the specified ... | 1a75e48dae55876f04718cfd594cfc6e43e5c966 | <|skeleton|>
class OneShotAtTimer:
"""A timer that is triggered at a specific time of day. Once the timer fires it is stopped."""
def start(self, hour=range(24), min=range(60), sec=0):
"""Starts the timer, causing it to be fired at the specified time. By default, the timer will fire every minute at 0 s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OneShotAtTimer:
"""A timer that is triggered at a specific time of day. Once the timer fires it is stopped."""
def start(self, hour=range(24), min=range(60), sec=0):
"""Starts the timer, causing it to be fired at the specified time. By default, the timer will fire every minute at 0 seconds. The t... | the_stack_v2_python_sparse | env/lib/python2.7/site-packages/kaa/timer.py | jpmunz/smartplayer | train | 0 |
ff0efe3353bad53bac784257e5133b7d1ce1022b | [
"if isinstance(object_or_objects, StatefulObject):\n obj = object_or_objects\nelse:\n obj = StatefulObjectGroup(object_or_objects)\nself._obj = obj\nself._pickle_protocol = pickle_protocol",
"if not file_path.endswith('.npz'):\n raise ValueError('`file_path` must end with \".npz\"')\nnpz_state = {}\nfor ... | <|body_start_0|>
if isinstance(object_or_objects, StatefulObject):
obj = object_or_objects
else:
obj = StatefulObjectGroup(object_or_objects)
self._obj = obj
self._pickle_protocol = pickle_protocol
<|end_body_0|>
<|body_start_1|>
if not file_path.endswith... | Class to save/load :class:`StatefulObject` to/from disk file. This class internally uses :func:`np.savez` to save the state dict. If a value of the state dict is a NumPy array, it will be directly saved; otherwise it will be serialized via :mod:`pickle` before saving. Usage:: # save the state a = SimpleStatefulObject()... | StateSaver | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StateSaver:
"""Class to save/load :class:`StatefulObject` to/from disk file. This class internally uses :func:`np.savez` to save the state dict. If a value of the state dict is a NumPy array, it will be directly saved; otherwise it will be serialized via :mod:`pickle` before saving. Usage:: # sav... | stack_v2_sparse_classes_36k_train_023417 | 8,335 | permissive | [
{
"docstring": "Construct a new :class:`StateSaver`. Args: object_or_objects: A :class:`StatefulObject`, or a dict of stateful objects (which can be grouped by :class:`StatefulObjectGroup`). pickle_protocol: The protocol for :mod:`pickle` to use. Default the highest possible protocol.",
"name": "__init__",
... | 3 | stack_v2_sparse_classes_30k_train_003758 | Implement the Python class `StateSaver` described below.
Class description:
Class to save/load :class:`StatefulObject` to/from disk file. This class internally uses :func:`np.savez` to save the state dict. If a value of the state dict is a NumPy array, it will be directly saved; otherwise it will be serialized via :mo... | Implement the Python class `StateSaver` described below.
Class description:
Class to save/load :class:`StatefulObject` to/from disk file. This class internally uses :func:`np.savez` to save the state dict. If a value of the state dict is a NumPy array, it will be directly saved; otherwise it will be serialized via :mo... | fcdfbc34b8d539f058b4289b2d3f141a0b28cefd | <|skeleton|>
class StateSaver:
"""Class to save/load :class:`StatefulObject` to/from disk file. This class internally uses :func:`np.savez` to save the state dict. If a value of the state dict is a NumPy array, it will be directly saved; otherwise it will be serialized via :mod:`pickle` before saving. Usage:: # sav... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StateSaver:
"""Class to save/load :class:`StatefulObject` to/from disk file. This class internally uses :func:`np.savez` to save the state dict. If a value of the state dict is a NumPy array, it will be directly saved; otherwise it will be serialized via :mod:`pickle` before saving. Usage:: # save the state a... | the_stack_v2_python_sparse | mltk/stateful.py | haowen-xu/ml-essentials | train | 4 |
f3d050b8f43941956b360966ac75f975103df7d1 | [
"x, x_shape = self._prepare_x(x)\ny = self._evaluate_derivatives(x, der)\ny = y.reshape((y.shape[0],) + x_shape + self._y_extra_shape)\nif self._y_axis != 0 and x_shape != ():\n nx = len(x_shape)\n ny = len(self._y_extra_shape)\n s = [0] + list(range(nx + 1, nx + self._y_axis + 1)) + list(range(1, nx + 1))... | <|body_start_0|>
x, x_shape = self._prepare_x(x)
y = self._evaluate_derivatives(x, der)
y = y.reshape((y.shape[0],) + x_shape + self._y_extra_shape)
if self._y_axis != 0 and x_shape != ():
nx = len(x_shape)
ny = len(self._y_extra_shape)
s = [0] + list(... | _Interpolator1DWithDerivatives | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Interpolator1DWithDerivatives:
def derivatives(self, x, der=None):
"""Evaluate many derivatives of the polynomial at the point x. The function produce an array of all derivative values at the point x. Parameters ---------- x : cupy.ndarray Point or points at which to evaluate the deriva... | stack_v2_sparse_classes_36k_train_023418 | 17,500 | permissive | [
{
"docstring": "Evaluate many derivatives of the polynomial at the point x. The function produce an array of all derivative values at the point x. Parameters ---------- x : cupy.ndarray Point or points at which to evaluate the derivatives der : int or None, optional How many derivatives to extract; None for all... | 2 | null | Implement the Python class `_Interpolator1DWithDerivatives` described below.
Class description:
Implement the _Interpolator1DWithDerivatives class.
Method signatures and docstrings:
- def derivatives(self, x, der=None): Evaluate many derivatives of the polynomial at the point x. The function produce an array of all d... | Implement the Python class `_Interpolator1DWithDerivatives` described below.
Class description:
Implement the _Interpolator1DWithDerivatives class.
Method signatures and docstrings:
- def derivatives(self, x, der=None): Evaluate many derivatives of the polynomial at the point x. The function produce an array of all d... | 96105afb78aa3f8380834d2516184b8365e23fcb | <|skeleton|>
class _Interpolator1DWithDerivatives:
def derivatives(self, x, der=None):
"""Evaluate many derivatives of the polynomial at the point x. The function produce an array of all derivative values at the point x. Parameters ---------- x : cupy.ndarray Point or points at which to evaluate the deriva... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _Interpolator1DWithDerivatives:
def derivatives(self, x, der=None):
"""Evaluate many derivatives of the polynomial at the point x. The function produce an array of all derivative values at the point x. Parameters ---------- x : cupy.ndarray Point or points at which to evaluate the derivatives der : in... | the_stack_v2_python_sparse | cupyx/scipy/interpolate/_polyint.py | cupy/cupy | train | 7,505 | |
ff12d89d9f671c7574f2213ad516dafcf486fcd5 | [
"self._scale_to = scale_to\nself._allow_zero_scale = allow_zero_scale\nself._allow_unknown_scale = allow_unknown_scale",
"try:\n scale_to(self._scale_to, group, self._allow_zero_scale, self._allow_unknown_scale)\nexcept TypeError:\n raise lena.core.LenaValueError('value must be a list or other materialized ... | <|body_start_0|>
self._scale_to = scale_to
self._allow_zero_scale = allow_zero_scale
self._allow_unknown_scale = allow_unknown_scale
<|end_body_0|>
<|body_start_1|>
try:
scale_to(self._scale_to, group, self._allow_zero_scale, self._allow_unknown_scale)
except TypeErr... | Scale a group of data. | GroupScale | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupScale:
"""Scale a group of data."""
def __init__(self, scale_to, allow_zero_scale=False, allow_unknown_scale=False):
"""*scale_to* defines the method of scaling. If a number is given, group items are scaled to that. Otherwise it is converted to a :class:`.Selector`, which must r... | stack_v2_sparse_classes_36k_train_023419 | 3,277 | permissive | [
{
"docstring": "*scale_to* defines the method of scaling. If a number is given, group items are scaled to that. Otherwise it is converted to a :class:`.Selector`, which must return a unique item from the group. Group items will be scaled to the scale of that item. By default, attempts to rescale a structure wit... | 2 | stack_v2_sparse_classes_30k_val_000848 | Implement the Python class `GroupScale` described below.
Class description:
Scale a group of data.
Method signatures and docstrings:
- def __init__(self, scale_to, allow_zero_scale=False, allow_unknown_scale=False): *scale_to* defines the method of scaling. If a number is given, group items are scaled to that. Otherw... | Implement the Python class `GroupScale` described below.
Class description:
Scale a group of data.
Method signatures and docstrings:
- def __init__(self, scale_to, allow_zero_scale=False, allow_unknown_scale=False): *scale_to* defines the method of scaling. If a number is given, group items are scaled to that. Otherw... | 8b85a93e3c15a69d58521332aac3202a077aa7ba | <|skeleton|>
class GroupScale:
"""Scale a group of data."""
def __init__(self, scale_to, allow_zero_scale=False, allow_unknown_scale=False):
"""*scale_to* defines the method of scaling. If a number is given, group items are scaled to that. Otherwise it is converted to a :class:`.Selector`, which must r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GroupScale:
"""Scale a group of data."""
def __init__(self, scale_to, allow_zero_scale=False, allow_unknown_scale=False):
"""*scale_to* defines the method of scaling. If a number is given, group items are scaled to that. Otherwise it is converted to a :class:`.Selector`, which must return a uniqu... | the_stack_v2_python_sparse | lena/flow/group_scale.py | ynikitenko/lena | train | 4 |
4986d7562765fae465ddffef852a0071fca82fc4 | [
"apply_ipaddr, apply_port = System.get_apply_ip_and_port()\ntry:\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:\n send_data = json.dumps(send_data)\n send_data = send_data.encode()\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sock.setsockopt(socket... | <|body_start_0|>
apply_ipaddr, apply_port = System.get_apply_ip_and_port()
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
send_data = json.dumps(send_data)
send_data = send_data.encode()
sock.setsockopt(socket.SOL_SOCKET, ... | RequestToApply | [
"Apache-2.0",
"BSD-3-Clause",
"LGPL-3.0-only",
"MIT",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RequestToApply:
def _request(cls, send_data, request=None):
"""[概要] 適用君へリクエスト送信 [引数] send_data : リクエスト用データ [戻り値] recv_data : 受信データ"""
<|body_0|>
def operate(cls, send_data, request=None):
"""[概要] アプライ君にルール関連の操作を要求する [引数] send_data : リクエスト用データ [戻り値] result : 正常ならTrue,... | stack_v2_sparse_classes_36k_train_023420 | 9,642 | permissive | [
{
"docstring": "[概要] 適用君へリクエスト送信 [引数] send_data : リクエスト用データ [戻り値] recv_data : 受信データ",
"name": "_request",
"signature": "def _request(cls, send_data, request=None)"
},
{
"docstring": "[概要] アプライ君にルール関連の操作を要求する [引数] send_data : リクエスト用データ [戻り値] result : 正常ならTrue, 異常ならFalse msg : 受信メッセージ",
"name"... | 3 | stack_v2_sparse_classes_30k_train_020436 | Implement the Python class `RequestToApply` described below.
Class description:
Implement the RequestToApply class.
Method signatures and docstrings:
- def _request(cls, send_data, request=None): [概要] 適用君へリクエスト送信 [引数] send_data : リクエスト用データ [戻り値] recv_data : 受信データ
- def operate(cls, send_data, request=None): [概要] アプライ... | Implement the Python class `RequestToApply` described below.
Class description:
Implement the RequestToApply class.
Method signatures and docstrings:
- def _request(cls, send_data, request=None): [概要] 適用君へリクエスト送信 [引数] send_data : リクエスト用データ [戻り値] recv_data : 受信データ
- def operate(cls, send_data, request=None): [概要] アプライ... | c00ea4fe1bf4b4a18d545aabeaaf1d95c7664b94 | <|skeleton|>
class RequestToApply:
def _request(cls, send_data, request=None):
"""[概要] 適用君へリクエスト送信 [引数] send_data : リクエスト用データ [戻り値] recv_data : 受信データ"""
<|body_0|>
def operate(cls, send_data, request=None):
"""[概要] アプライ君にルール関連の操作を要求する [引数] send_data : リクエスト用データ [戻り値] result : 正常ならTrue,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RequestToApply:
def _request(cls, send_data, request=None):
"""[概要] 適用君へリクエスト送信 [引数] send_data : リクエスト用データ [戻り値] recv_data : 受信データ"""
apply_ipaddr, apply_port = System.get_apply_ip_and_port()
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
... | the_stack_v2_python_sparse | oase-root/libs/webcommonlibs/common.py | exastro-suite/oase | train | 10 | |
25bd7f3d0311b499140d3e0a5a647b45c36459b8 | [
"if cls.MMPBSA_EXE == None:\n engine_path = Config.Amber.AmberHome + '/bin/MMPBSA.py.MPI'\nelse:\n engine_path = cls.MMPBSA_EXE\nreturn engine_path",
"if out_path == '':\n if os.path.exists('./tmp'):\n pass\n else:\n os.makedirs('./tmp')\n out_path = './tmp/MMPBSA.in'\nframe_line = ' ... | <|body_start_0|>
if cls.MMPBSA_EXE == None:
engine_path = Config.Amber.AmberHome + '/bin/MMPBSA.py.MPI'
else:
engine_path = cls.MMPBSA_EXE
return engine_path
<|end_body_0|>
<|body_start_1|>
if out_path == '':
if os.path.exists('./tmp'):
... | MMPBSA | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MMPBSA:
def get_MMPBSA_engine(cls):
"""Give default value to MMPBSA engine Only support MPI version now. --- return engine_path"""
<|body_0|>
def build_MMPBSA_in(cls, out_path='', use_sander=1):
"""build MMPBSA.in in out_path"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_023421 | 22,088 | no_license | [
{
"docstring": "Give default value to MMPBSA engine Only support MPI version now. --- return engine_path",
"name": "get_MMPBSA_engine",
"signature": "def get_MMPBSA_engine(cls)"
},
{
"docstring": "build MMPBSA.in in out_path",
"name": "build_MMPBSA_in",
"signature": "def build_MMPBSA_in(... | 2 | stack_v2_sparse_classes_30k_train_015891 | Implement the Python class `MMPBSA` described below.
Class description:
Implement the MMPBSA class.
Method signatures and docstrings:
- def get_MMPBSA_engine(cls): Give default value to MMPBSA engine Only support MPI version now. --- return engine_path
- def build_MMPBSA_in(cls, out_path='', use_sander=1): build MMPB... | Implement the Python class `MMPBSA` described below.
Class description:
Implement the MMPBSA class.
Method signatures and docstrings:
- def get_MMPBSA_engine(cls): Give default value to MMPBSA engine Only support MPI version now. --- return engine_path
- def build_MMPBSA_in(cls, out_path='', use_sander=1): build MMPB... | 47f733b994fd3b96b3aff6f4d0174a9718da6617 | <|skeleton|>
class MMPBSA:
def get_MMPBSA_engine(cls):
"""Give default value to MMPBSA engine Only support MPI version now. --- return engine_path"""
<|body_0|>
def build_MMPBSA_in(cls, out_path='', use_sander=1):
"""build MMPBSA.in in out_path"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MMPBSA:
def get_MMPBSA_engine(cls):
"""Give default value to MMPBSA engine Only support MPI version now. --- return engine_path"""
if cls.MMPBSA_EXE == None:
engine_path = Config.Amber.AmberHome + '/bin/MMPBSA.py.MPI'
else:
engine_path = cls.MMPBSA_EXE
r... | the_stack_v2_python_sparse | Class_Conf.py | ChemBioHTP/EnzyHTP | train | 39 | |
4bcea79345fde93851624c0606f74a16bfb70b07 | [
"se = ''\nfor s in strs:\n se += str(len(s)) + ':' + s\nreturn se",
"res = []\ni, j, length = (0, 0, len(s))\nwhile i < length:\n if s[j] == ':':\n num = int(s[i:j])\n res.append('' + s[j + 1:j + 1 + num])\n i = j + 1 + num\n j = j + 1 + num\n else:\n j += 1\nreturn res... | <|body_start_0|>
se = ''
for s in strs:
se += str(len(s)) + ':' + s
return se
<|end_body_0|>
<|body_start_1|>
res = []
i, j, length = (0, 0, len(s))
while i < length:
if s[j] == ':':
num = int(s[i:j])
res.append('' ... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_023422 | 1,314 | no_license | [
{
"docstring": "Encodes a list of strings to a single string. :type strs: List[str] :rtype: str",
"name": "encode",
"signature": "def encode(self, strs)"
},
{
"docstring": "Decodes a single string to a list of strings. :type s: str :rtype: List[str]",
"name": "decode",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_000211 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | f2ea7165d40b392b8f8892ba7152438001900a4d | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
se = ''
for s in strs:
se += str(len(s)) + ':' + s
return se
def decode(self, s):
"""Decodes a single string to a list of strings. :type... | the_stack_v2_python_sparse | 271-Encode_and_Decode_Strings.py | weichuntsai0217/leetcode | train | 0 | |
3514dbc248659746f31001350ea2c88824ec1d86 | [
"template = self.template\npagerdutyalert = template.add_resource(sns.Topic('Topic'))\ntemplate.add_output(Output('%sARN' % pagerdutyalert.title, Description='SNS topic', Value=Ref(pagerdutyalert)))",
"self.template.add_version('2010-09-09')\nself.template.add_description('Sturdy Platform - Core - SNS Topic - {0}... | <|body_start_0|>
template = self.template
pagerdutyalert = template.add_resource(sns.Topic('Topic'))
template.add_output(Output('%sARN' % pagerdutyalert.title, Description='SNS topic', Value=Ref(pagerdutyalert)))
<|end_body_0|>
<|body_start_1|>
self.template.add_version('2010-09-09')
... | Blueprint for setting up SNS topic. | SnsTopic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnsTopic:
"""Blueprint for setting up SNS topic."""
def add_resources(self):
"""Add resources to template."""
<|body_0|>
def create_template(self):
"""Create template (main function called by Stacker)."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_023423 | 1,675 | no_license | [
{
"docstring": "Add resources to template.",
"name": "add_resources",
"signature": "def add_resources(self)"
},
{
"docstring": "Create template (main function called by Stacker).",
"name": "create_template",
"signature": "def create_template(self)"
}
] | 2 | null | Implement the Python class `SnsTopic` described below.
Class description:
Blueprint for setting up SNS topic.
Method signatures and docstrings:
- def add_resources(self): Add resources to template.
- def create_template(self): Create template (main function called by Stacker). | Implement the Python class `SnsTopic` described below.
Class description:
Blueprint for setting up SNS topic.
Method signatures and docstrings:
- def add_resources(self): Add resources to template.
- def create_template(self): Create template (main function called by Stacker).
<|skeleton|>
class SnsTopic:
"""Blu... | befa3a3a50a26d4ba7fdc9a08e35fbf1128bcb55 | <|skeleton|>
class SnsTopic:
"""Blueprint for setting up SNS topic."""
def add_resources(self):
"""Add resources to template."""
<|body_0|>
def create_template(self):
"""Create template (main function called by Stacker)."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SnsTopic:
"""Blueprint for setting up SNS topic."""
def add_resources(self):
"""Add resources to template."""
template = self.template
pagerdutyalert = template.add_resource(sns.Topic('Topic'))
template.add_output(Output('%sARN' % pagerdutyalert.title, Description='SNS top... | the_stack_v2_python_sparse | terraform/standard-lab/stacker/core/core_blueprints/sns_topic.py | threadstonesecure/cfn_templates | train | 0 |
f860a8bb1b534a711bd2a6dcb7413fe0663cebb9 | [
"if not nums:\n return 0\nn = nums.__len__()\ndp = [1 for _ in range(n)]\nfor i in range(n - 2, -1, -1):\n iter_max = 0\n for j in range(i + 1, n):\n if nums[i] < nums[j]:\n iter_max = max(dp[j], iter_max)\n dp[i] = iter_max + 1\nreturn max(dp)",
"if not nums:\n return 0\nn = nums... | <|body_start_0|>
if not nums:
return 0
n = nums.__len__()
dp = [1 for _ in range(n)]
for i in range(n - 2, -1, -1):
iter_max = 0
for j in range(i + 1, n):
if nums[i] < nums[j]:
iter_max = max(dp[j], iter_max)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def lengthOfLIS1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
return 0
n ... | stack_v2_sparse_classes_36k_train_023424 | 4,613 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "lengthOfLIS",
"signature": "def lengthOfLIS(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "lengthOfLIS1",
"signature": "def lengthOfLIS1(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020586 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int
- def lengthOfLIS1(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 lengthOfLIS(self, nums): :type nums: List[int] :rtype: int
- def lengthOfLIS1(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def lengthOfLI... | 472f780c3214aab5c713612812d834ccbe589434 | <|skeleton|>
class Solution:
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def lengthOfLIS1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
if not nums:
return 0
n = nums.__len__()
dp = [1 for _ in range(n)]
for i in range(n - 2, -1, -1):
iter_max = 0
for j in range(i + 1, n):
i... | the_stack_v2_python_sparse | 4/300-Longest_Increasing_Subsequence.py | ChangXiaodong/Leetcode-solutions | train | 4 | |
053e00724e15994fceab321e57079c60203d8e20 | [
"result = 0\nfor i in range(0, len(s)):\n l = {}\n l[s[i]] = 1\n j = i + 1\n L = 1\n while j < len(s) and s[j] not in l:\n l[s[j]] = 1\n L = L + 1\n j = j + 1\n if result < L:\n result = L\nreturn result",
"result = 0\nl = {}\nright = 0\nleft = 0\nwhile right < len(s)... | <|body_start_0|>
result = 0
for i in range(0, len(s)):
l = {}
l[s[i]] = 1
j = i + 1
L = 1
while j < len(s) and s[j] not in l:
l[s[j]] = 1
L = L + 1
j = j + 1
if result < L:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def lengthOfLongestSubstring_2(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = 0
for i in range(0, len(... | stack_v2_sparse_classes_36k_train_023425 | 987 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "lengthOfLongestSubstring",
"signature": "def lengthOfLongestSubstring(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "lengthOfLongestSubstring_2",
"signature": "def lengthOfLongestSubstring_2(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s): :type s: str :rtype: int
- def lengthOfLongestSubstring_2(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 lengthOfLongestSubstring(self, s): :type s: str :rtype: int
- def lengthOfLongestSubstring_2(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def lengthO... | 94b46e6c89d254d9dafc504f14c60136403b7ae8 | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def lengthOfLongestSubstring_2(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
result = 0
for i in range(0, len(s)):
l = {}
l[s[i]] = 1
j = i + 1
L = 1
while j < len(s) and s[j] not in l:
l[s[j]] = 1
... | the_stack_v2_python_sparse | leetcode_3.py | lp2016/New_Algorithm | train | 0 | |
d1714802427644c54a9704cb765041e16381387e | [
"out = [-1] * len(nums)\nfor i in range(len(nums)):\n newNums = nums[i:] + nums[0:i]\n for n in range(1, len(newNums)):\n if newNums[n] > nums[i]:\n out[i] = newNums[n]\n break\nreturn out",
"out = [-1] * len(nums)\nstack = []\nfor i in range(2 * len(nums) - 1, -1, -1):\n whi... | <|body_start_0|>
out = [-1] * len(nums)
for i in range(len(nums)):
newNums = nums[i:] + nums[0:i]
for n in range(1, len(newNums)):
if newNums[n] > nums[i]:
out[i] = newNums[n]
break
return out
<|end_body_0|>
<|body_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nextGreaterElements1(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def nextGreaterElements2(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
out = [-1] * le... | stack_v2_sparse_classes_36k_train_023426 | 1,339 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "nextGreaterElements1",
"signature": "def nextGreaterElements1(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "nextGreaterElements2",
"signature": "def nextGreaterElements2(self, nums)"
... | 2 | stack_v2_sparse_classes_30k_train_005071 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextGreaterElements1(self, nums): :type nums: List[int] :rtype: List[int]
- def nextGreaterElements2(self, nums): :type nums: List[int] :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextGreaterElements1(self, nums): :type nums: List[int] :rtype: List[int]
- def nextGreaterElements2(self, nums): :type nums: List[int] :rtype: List[int]
<|skeleton|>
class ... | 604efd2c53c369fb262f42f7f7f31997ea4d029b | <|skeleton|>
class Solution:
def nextGreaterElements1(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def nextGreaterElements2(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def nextGreaterElements1(self, nums):
""":type nums: List[int] :rtype: List[int]"""
out = [-1] * len(nums)
for i in range(len(nums)):
newNums = nums[i:] + nums[0:i]
for n in range(1, len(newNums)):
if newNums[n] > nums[i]:
... | the_stack_v2_python_sparse | 503_Next_Greater_Element_II.py | fxy1018/Leetcode | train | 1 | |
440fa2c0cfcf6e5b4875dc700c31c61af8210bf7 | [
"context = super(SignUpFormView, self).get_context_data(**kwargs)\ncontext['title'] = 'Sign Up'\nreturn context",
"user_name = form.cleaned_data['username']\nemail = form.cleaned_data['email']\npassword = form.cleaned_data['password']\nconfirm_password = form.cleaned_data['confirm_password']\ncontext = self.get_c... | <|body_start_0|>
context = super(SignUpFormView, self).get_context_data(**kwargs)
context['title'] = 'Sign Up'
return context
<|end_body_0|>
<|body_start_1|>
user_name = form.cleaned_data['username']
email = form.cleaned_data['email']
password = form.cleaned_data['passwo... | A class of FormView to register a new user ... Attributes ---------- template_name : str the name of the template form_class : SignUpForm Form of the view success_url : str url of the success page Methods ------- get_context_data(**kwargs): Get the context of the view form_valid(form): Register the new user | SignUpFormView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignUpFormView:
"""A class of FormView to register a new user ... Attributes ---------- template_name : str the name of the template form_class : SignUpForm Form of the view success_url : str url of the success page Methods ------- get_context_data(**kwargs): Get the context of the view form_vali... | stack_v2_sparse_classes_36k_train_023427 | 9,386 | no_license | [
{
"docstring": "Call the original method of the view and add the title on the context Parameters ---------- kwargs : str Some argument that Django are passing, need when call the original method of the view Returns ------- dict a dict of the context of the page",
"name": "get_context_data",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_020960 | Implement the Python class `SignUpFormView` described below.
Class description:
A class of FormView to register a new user ... Attributes ---------- template_name : str the name of the template form_class : SignUpForm Form of the view success_url : str url of the success page Methods ------- get_context_data(**kwargs)... | Implement the Python class `SignUpFormView` described below.
Class description:
A class of FormView to register a new user ... Attributes ---------- template_name : str the name of the template form_class : SignUpForm Form of the view success_url : str url of the success page Methods ------- get_context_data(**kwargs)... | 939245d046974fabf33fa540b4c3b6d077100ff5 | <|skeleton|>
class SignUpFormView:
"""A class of FormView to register a new user ... Attributes ---------- template_name : str the name of the template form_class : SignUpForm Form of the view success_url : str url of the success page Methods ------- get_context_data(**kwargs): Get the context of the view form_vali... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SignUpFormView:
"""A class of FormView to register a new user ... Attributes ---------- template_name : str the name of the template form_class : SignUpForm Form of the view success_url : str url of the success page Methods ------- get_context_data(**kwargs): Get the context of the view form_valid(form): Regi... | the_stack_v2_python_sparse | purebeurre/views/user.py | M0l42/P08_PureBeurre | train | 1 |
e6376c62ddc5d7b104671ab3eac471745ea24c51 | [
"ref = self.cleaned_data['reference']\ntmp_ref = re.sub('\\\\W+', '', ref)\ntmp_ref = re.sub('_', '', tmp_ref)\nif len(tmp_ref) < 6:\n raise ValidationError(_('Reference must have at least 6 alphanumeric characters.'))\nif re.search('\\\\\\\\s', ref):\n raise ValidationError(_('Reference must not contain spac... | <|body_start_0|>
ref = self.cleaned_data['reference']
tmp_ref = re.sub('\\W+', '', ref)
tmp_ref = re.sub('_', '', tmp_ref)
if len(tmp_ref) < 6:
raise ValidationError(_('Reference must have at least 6 alphanumeric characters.'))
if re.search('\\\\s', ref):
... | DirectDebitForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DirectDebitForm:
def clean_reference(self):
"""Validates the reference field. :return:"""
<|body_0|>
def clean_sort_code(self):
"""Validates the sort code :return:"""
<|body_1|>
def clean_account_number(self):
"""Validates the account number :ret... | stack_v2_sparse_classes_36k_train_023428 | 1,789 | no_license | [
{
"docstring": "Validates the reference field. :return:",
"name": "clean_reference",
"signature": "def clean_reference(self)"
},
{
"docstring": "Validates the sort code :return:",
"name": "clean_sort_code",
"signature": "def clean_sort_code(self)"
},
{
"docstring": "Validates the... | 3 | null | Implement the Python class `DirectDebitForm` described below.
Class description:
Implement the DirectDebitForm class.
Method signatures and docstrings:
- def clean_reference(self): Validates the reference field. :return:
- def clean_sort_code(self): Validates the sort code :return:
- def clean_account_number(self): V... | Implement the Python class `DirectDebitForm` described below.
Class description:
Implement the DirectDebitForm class.
Method signatures and docstrings:
- def clean_reference(self): Validates the reference field. :return:
- def clean_sort_code(self): Validates the sort code :return:
- def clean_account_number(self): V... | ee93c49d55bb5717ff1ce73b5d2df6c8daf7678f | <|skeleton|>
class DirectDebitForm:
def clean_reference(self):
"""Validates the reference field. :return:"""
<|body_0|>
def clean_sort_code(self):
"""Validates the sort code :return:"""
<|body_1|>
def clean_account_number(self):
"""Validates the account number :ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DirectDebitForm:
def clean_reference(self):
"""Validates the reference field. :return:"""
ref = self.cleaned_data['reference']
tmp_ref = re.sub('\\W+', '', ref)
tmp_ref = re.sub('_', '', tmp_ref)
if len(tmp_ref) < 6:
raise ValidationError(_('Reference must h... | the_stack_v2_python_sparse | core_direct_debits/forms.py | portman-asset-finance/_GO_PAF | train | 0 | |
d967aba0f4c962584c13e787c6767bab0e5cb0f4 | [
"nums = map(str, nums)\nnums.sort(cmp=self.cmp, reverse=True)\nnums = ''.join(nums)\nnums = nums.lstrip('0')\nif not nums:\n nums = '0'\nreturn nums",
"order = 1\nif len(a) > len(b):\n order = -1\n a, b = (b, a)\nfor i in xrange(len(a)):\n if int(a[i]) != int(b[i]):\n return order * (int(a[i]) ... | <|body_start_0|>
nums = map(str, nums)
nums.sort(cmp=self.cmp, reverse=True)
nums = ''.join(nums)
nums = nums.lstrip('0')
if not nums:
nums = '0'
return nums
<|end_body_0|>
<|body_start_1|>
order = 1
if len(a) > len(b):
order = -1
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def largestNumber(self, nums):
"""Start off by enumerate simple examples Compare digit by digit The comparator is the core. :type nums: list[int] :rtype: str"""
<|body_0|>
def cmp(self, a, b):
""":type a: str :type b: str :rtype: int"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_023429 | 2,264 | permissive | [
{
"docstring": "Start off by enumerate simple examples Compare digit by digit The comparator is the core. :type nums: list[int] :rtype: str",
"name": "largestNumber",
"signature": "def largestNumber(self, nums)"
},
{
"docstring": ":type a: str :type b: str :rtype: int",
"name": "cmp",
"s... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestNumber(self, nums): Start off by enumerate simple examples Compare digit by digit The comparator is the core. :type nums: list[int] :rtype: str
- def cmp(self, a, b): ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestNumber(self, nums): Start off by enumerate simple examples Compare digit by digit The comparator is the core. :type nums: list[int] :rtype: str
- def cmp(self, a, b): ... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class Solution:
def largestNumber(self, nums):
"""Start off by enumerate simple examples Compare digit by digit The comparator is the core. :type nums: list[int] :rtype: str"""
<|body_0|>
def cmp(self, a, b):
""":type a: str :type b: str :rtype: int"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def largestNumber(self, nums):
"""Start off by enumerate simple examples Compare digit by digit The comparator is the core. :type nums: list[int] :rtype: str"""
nums = map(str, nums)
nums.sort(cmp=self.cmp, reverse=True)
nums = ''.join(nums)
nums = nums.lstrip... | the_stack_v2_python_sparse | 179 Largest Number.py | Aminaba123/LeetCode | train | 1 | |
80450931af747cb592c68ba744d56bfdf30578d1 | [
"super(AggregateCell, self).__init__()\nself.pre_transform = pre_transform\nself.concat = concat\nif self.pre_transform:\n self.branch_1 = conv_bn_relu(size_1, agg_size, 1, 1, 0)\n self.branch_2 = conv_bn_relu(size_2, agg_size, 1, 1, 0)\nif self.concat:\n self.conv1x1 = conv_bn_relu(agg_size * 2, agg_size,... | <|body_start_0|>
super(AggregateCell, self).__init__()
self.pre_transform = pre_transform
self.concat = concat
if self.pre_transform:
self.branch_1 = conv_bn_relu(size_1, agg_size, 1, 1, 0)
self.branch_2 = conv_bn_relu(size_2, agg_size, 1, 1, 0)
if self.co... | Aggregate two cells and sum or concat them up. | AggregateCell | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AggregateCell:
"""Aggregate two cells and sum or concat them up."""
def __init__(self, size_1, size_2, agg_size, pre_transform=True, concat=False):
"""Construct AggregateCell. :param size_1: channel of first input :param size_2: channel of second input :param agg_size: channel of agg... | stack_v2_sparse_classes_36k_train_023430 | 27,877 | permissive | [
{
"docstring": "Construct AggregateCell. :param size_1: channel of first input :param size_2: channel of second input :param agg_size: channel of aggregated tensor :param pre_transform: whether to do a transform on two inputs :param concat: concat the result if set to True, otherwise add the result",
"name"... | 2 | null | Implement the Python class `AggregateCell` described below.
Class description:
Aggregate two cells and sum or concat them up.
Method signatures and docstrings:
- def __init__(self, size_1, size_2, agg_size, pre_transform=True, concat=False): Construct AggregateCell. :param size_1: channel of first input :param size_2... | Implement the Python class `AggregateCell` described below.
Class description:
Aggregate two cells and sum or concat them up.
Method signatures and docstrings:
- def __init__(self, size_1, size_2, agg_size, pre_transform=True, concat=False): Construct AggregateCell. :param size_1: channel of first input :param size_2... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class AggregateCell:
"""Aggregate two cells and sum or concat them up."""
def __init__(self, size_1, size_2, agg_size, pre_transform=True, concat=False):
"""Construct AggregateCell. :param size_1: channel of first input :param size_2: channel of second input :param agg_size: channel of agg... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AggregateCell:
"""Aggregate two cells and sum or concat them up."""
def __init__(self, size_1, size_2, agg_size, pre_transform=True, concat=False):
"""Construct AggregateCell. :param size_1: channel of first input :param size_2: channel of second input :param agg_size: channel of aggregated tenso... | the_stack_v2_python_sparse | built-in/TensorFlow/Official/cv/image_classification/ResnetVariant_for_TensorFlow/automl/vega/search_space/networks/pytorch/operator/op.py | Huawei-Ascend/modelzoo | train | 1 |
786f0d598dd75e66c4184f07bc00043bfd2af4fc | [
"super().__init__()\nself.cse_block = cSE(in_channels, r)\nself.sse_block = sSE(in_channels)",
"cse = self.cse_block(x)\nsse = self.sse_block(x)\nx = torch.add(cse, sse)\nreturn x"
] | <|body_start_0|>
super().__init__()
self.cse_block = cSE(in_channels, r)
self.sse_block = sSE(in_channels)
<|end_body_0|>
<|body_start_1|>
cse = self.cse_block(x)
sse = self.sse_block(x)
x = torch.add(cse, sse)
return x
<|end_body_1|>
| The scSE (Concurrent Spatial and Channel Squeeze and Channel Excitation) block from the `Concurrent Spatial and Channel ‘Squeeze & Excitation’ in Fully Convolutional Networks`__ paper. Adapted from https://www.kaggle.com/c/tgs-salt-identification-challenge/discussion/66178 Shape: - Input: (batch, channels, height, widt... | scSE | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class scSE:
"""The scSE (Concurrent Spatial and Channel Squeeze and Channel Excitation) block from the `Concurrent Spatial and Channel ‘Squeeze & Excitation’ in Fully Convolutional Networks`__ paper. Adapted from https://www.kaggle.com/c/tgs-salt-identification-challenge/discussion/66178 Shape: - Input... | stack_v2_sparse_classes_36k_train_023431 | 3,491 | permissive | [
{
"docstring": "Args: in_channels: The number of channels in the feature map of the input. r: The reduction ratio of the intermediate channels. Default: 16.",
"name": "__init__",
"signature": "def __init__(self, in_channels: int, r: int=16)"
},
{
"docstring": "Forward call.",
"name": "forwar... | 2 | null | Implement the Python class `scSE` described below.
Class description:
The scSE (Concurrent Spatial and Channel Squeeze and Channel Excitation) block from the `Concurrent Spatial and Channel ‘Squeeze & Excitation’ in Fully Convolutional Networks`__ paper. Adapted from https://www.kaggle.com/c/tgs-salt-identification-ch... | Implement the Python class `scSE` described below.
Class description:
The scSE (Concurrent Spatial and Channel Squeeze and Channel Excitation) block from the `Concurrent Spatial and Channel ‘Squeeze & Excitation’ in Fully Convolutional Networks`__ paper. Adapted from https://www.kaggle.com/c/tgs-salt-identification-ch... | e99f90655d0efcf22559a46e928f0f98c9807ebf | <|skeleton|>
class scSE:
"""The scSE (Concurrent Spatial and Channel Squeeze and Channel Excitation) block from the `Concurrent Spatial and Channel ‘Squeeze & Excitation’ in Fully Convolutional Networks`__ paper. Adapted from https://www.kaggle.com/c/tgs-salt-identification-challenge/discussion/66178 Shape: - Input... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class scSE:
"""The scSE (Concurrent Spatial and Channel Squeeze and Channel Excitation) block from the `Concurrent Spatial and Channel ‘Squeeze & Excitation’ in Fully Convolutional Networks`__ paper. Adapted from https://www.kaggle.com/c/tgs-salt-identification-challenge/discussion/66178 Shape: - Input: (batch, cha... | the_stack_v2_python_sparse | catalyst/contrib/layers/se.py | catalyst-team/catalyst | train | 3,038 |
52b8105bfa97d49120b5ddddf199756386753241 | [
"n = len(arr)\nk = k % n\nself.reverse(arr, 0, n - 1)\nself.reverse(arr, 0, k - 1)\nself.reverse(arr, k, n - 1)",
"while i < j:\n arr[i], arr[j] = (arr[j], arr[i])\n i += 1\n j -= 1",
"if not nums:\n return\nl = len(nums)\nk %= l\nres = nums[len(nums) - k:]\nres.extend(nums[:len(nums) - k])\nfor i i... | <|body_start_0|>
n = len(arr)
k = k % n
self.reverse(arr, 0, n - 1)
self.reverse(arr, 0, k - 1)
self.reverse(arr, k, n - 1)
<|end_body_0|>
<|body_start_1|>
while i < j:
arr[i], arr[j] = (arr[j], arr[i])
i += 1
j -= 1
<|end_body_1|>
<|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, arr, k):
""":type arr: List[int] :type k: int :rtype: void Do not return anything, modify arr in-place instead."""
<|body_0|>
def reverse(self, arr, i, j):
"""reverse a list"""
<|body_1|>
def rotate2(self, nums, k):
"""... | stack_v2_sparse_classes_36k_train_023432 | 2,438 | no_license | [
{
"docstring": ":type arr: List[int] :type k: int :rtype: void Do not return anything, modify arr in-place instead.",
"name": "rotate",
"signature": "def rotate(self, arr, k)"
},
{
"docstring": "reverse a list",
"name": "reverse",
"signature": "def reverse(self, arr, i, j)"
},
{
... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, arr, k): :type arr: List[int] :type k: int :rtype: void Do not return anything, modify arr in-place instead.
- def reverse(self, arr, i, j): reverse a list
- def... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, arr, k): :type arr: List[int] :type k: int :rtype: void Do not return anything, modify arr in-place instead.
- def reverse(self, arr, i, j): reverse a list
- def... | 813235789ce422a3bab198317aafc46fbc61625e | <|skeleton|>
class Solution:
def rotate(self, arr, k):
""":type arr: List[int] :type k: int :rtype: void Do not return anything, modify arr in-place instead."""
<|body_0|>
def reverse(self, arr, i, j):
"""reverse a list"""
<|body_1|>
def rotate2(self, nums, k):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate(self, arr, k):
""":type arr: List[int] :type k: int :rtype: void Do not return anything, modify arr in-place instead."""
n = len(arr)
k = k % n
self.reverse(arr, 0, n - 1)
self.reverse(arr, 0, k - 1)
self.reverse(arr, k, n - 1)
def reve... | the_stack_v2_python_sparse | rotate_array/solution.py | kimmyoo/python_leetcode | train | 1 | |
a02a5e7846dbc3679274699a071b435788d8d4be | [
"height = len(matrix)\nwidth = len(matrix[0])\nrotated = [[0 for x in range(width)] for y in range(height)]\nfor y in range(height):\n for x in range(width):\n rotated[x][height - 1 - y] = matrix[y][x]\nfor y in range(height):\n for x in range(width):\n matrix[y][x] = rotated[y][x]\nreturn None"... | <|body_start_0|>
height = len(matrix)
width = len(matrix[0])
rotated = [[0 for x in range(width)] for y in range(height)]
for y in range(height):
for x in range(width):
rotated[x][height - 1 - y] = matrix[y][x]
for y in range(height):
for x... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, matrix: 'List[List[int]]') -> 'None':
"""Do not return anything, modify matrix in-place instead."""
<|body_0|>
def rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.""... | stack_v2_sparse_classes_36k_train_023433 | 1,234 | no_license | [
{
"docstring": "Do not return anything, modify matrix in-place instead.",
"name": "rotate",
"signature": "def rotate(self, matrix: 'List[List[int]]') -> 'None'"
},
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.",
"name": "ro... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, matrix: 'List[List[int]]') -> 'None': Do not return anything, modify matrix in-place instead.
- def rotate(self, matrix): :type matrix: List[List[int]] :rtype: v... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, matrix: 'List[List[int]]') -> 'None': Do not return anything, modify matrix in-place instead.
- def rotate(self, matrix): :type matrix: List[List[int]] :rtype: v... | ae8bb8bf4ae4026ccaf1dce323b4098547dd35ec | <|skeleton|>
class Solution:
def rotate(self, matrix: 'List[List[int]]') -> 'None':
"""Do not return anything, modify matrix in-place instead."""
<|body_0|>
def rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate(self, matrix: 'List[List[int]]') -> 'None':
"""Do not return anything, modify matrix in-place instead."""
height = len(matrix)
width = len(matrix[0])
rotated = [[0 for x in range(width)] for y in range(height)]
for y in range(height):
fo... | the_stack_v2_python_sparse | leet_code/48_Rotate_Image.py | roiei/algo | train | 0 | |
e3b44eeec58d1ff8bca1901a4eb06dfc27450357 | [
"word_list = []\nfor k in ['东', '南', '西', '北']:\n if k in str(direction):\n word_list.append(k)\nif len(word_list) > 0 and ''.join(word_list) in cls._true_words:\n return ''.join(word_list)",
"query = {'city': city, 'region': region, 'name': name, 'house_num': house_num}\nif room_num:\n query = {'... | <|body_start_0|>
word_list = []
for k in ['东', '南', '西', '北']:
if k in str(direction):
word_list.append(k)
if len(word_list) > 0 and ''.join(word_list) in cls._true_words:
return ''.join(word_list)
<|end_body_0|>
<|body_start_1|>
query = {'city': ... | Direction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Direction:
def format_direction(cls, direction):
""":param direction: 朝向 :return: 有效朝向"""
<|body_0|>
def update_direction(cls, city, region, name, house_num, direction, direction_source, room_num=None):
""":param city: 城市 :param region: 区域 :param name: 小区名 :param hou... | stack_v2_sparse_classes_36k_train_023434 | 2,714 | no_license | [
{
"docstring": ":param direction: 朝向 :return: 有效朝向",
"name": "format_direction",
"signature": "def format_direction(cls, direction)"
},
{
"docstring": ":param city: 城市 :param region: 区域 :param name: 小区名 :param house_num: 楼栋号 :param direction: 朝向 :param direction_source: 朝向来源 :param room_num: 房号"... | 2 | stack_v2_sparse_classes_30k_train_016916 | Implement the Python class `Direction` described below.
Class description:
Implement the Direction class.
Method signatures and docstrings:
- def format_direction(cls, direction): :param direction: 朝向 :return: 有效朝向
- def update_direction(cls, city, region, name, house_num, direction, direction_source, room_num=None):... | Implement the Python class `Direction` described below.
Class description:
Implement the Direction class.
Method signatures and docstrings:
- def format_direction(cls, direction): :param direction: 朝向 :return: 有效朝向
- def update_direction(cls, city, region, name, house_num, direction, direction_source, room_num=None):... | 808cb78fc3887f35bf838d77d62308fce9e6aa5d | <|skeleton|>
class Direction:
def format_direction(cls, direction):
""":param direction: 朝向 :return: 有效朝向"""
<|body_0|>
def update_direction(cls, city, region, name, house_num, direction, direction_source, room_num=None):
""":param city: 城市 :param region: 区域 :param name: 小区名 :param hou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Direction:
def format_direction(cls, direction):
""":param direction: 朝向 :return: 有效朝向"""
word_list = []
for k in ['东', '南', '西', '北']:
if k in str(direction):
word_list.append(k)
if len(word_list) > 0 and ''.join(word_list) in cls._true_words:
... | the_stack_v2_python_sparse | hilder_pretreatment/raise_coverage/house_raise/direction_update.py | pjkui/githubproject | train | 0 | |
64bd799ee06ec000c220e1d41c1e9cd835ffe328 | [
"super(VGG, self).__init__()\nself.features = features\nself.avgpool = nn.AdaptiveAvgPool2d((7, 7))\nself.classifier = nn.Sequential(nn.Linear(512 * 7 * 7, 4096), nn.ReLU(True), nn.Dropout(), nn.Linear(4096, 4096), nn.ReLU(True), nn.Dropout(), nn.Linear(4096, out_channels))\nself.sigmoid = nn.Sigmoid()",
"x = sel... | <|body_start_0|>
super(VGG, self).__init__()
self.features = features
self.avgpool = nn.AdaptiveAvgPool2d((7, 7))
self.classifier = nn.Sequential(nn.Linear(512 * 7 * 7, 4096), nn.ReLU(True), nn.Dropout(), nn.Linear(4096, 4096), nn.ReLU(True), nn.Dropout(), nn.Linear(4096, out_channels))
... | VGG network structure with a multilabelling output. The output returns a sigmoid of size out_channels. Neural network structure : (features): Layers combinations that depends on which VGG structure selected (avgpool): (0): AdaptiveAvgPool2d(kernel=7) (classifier): (0): Linear(in_features=25088, out_features=4096, bias=... | VGG | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VGG:
"""VGG network structure with a multilabelling output. The output returns a sigmoid of size out_channels. Neural network structure : (features): Layers combinations that depends on which VGG structure selected (avgpool): (0): AdaptiveAvgPool2d(kernel=7) (classifier): (0): Linear(in_features=... | stack_v2_sparse_classes_36k_train_023435 | 5,496 | no_license | [
{
"docstring": ":param features : nn.Module, convolutionnal layers structures :param out_channels : int, number of labels to classify - default : out_channels = 2",
"name": "__init__",
"signature": "def __init__(self, features: nn.Module, out_channels: int=2) -> None"
},
{
"docstring": ":param x... | 2 | stack_v2_sparse_classes_30k_train_006719 | Implement the Python class `VGG` described below.
Class description:
VGG network structure with a multilabelling output. The output returns a sigmoid of size out_channels. Neural network structure : (features): Layers combinations that depends on which VGG structure selected (avgpool): (0): AdaptiveAvgPool2d(kernel=7)... | Implement the Python class `VGG` described below.
Class description:
VGG network structure with a multilabelling output. The output returns a sigmoid of size out_channels. Neural network structure : (features): Layers combinations that depends on which VGG structure selected (avgpool): (0): AdaptiveAvgPool2d(kernel=7)... | 9189d2eeb748b1e539a1062a09a06b38a09780de | <|skeleton|>
class VGG:
"""VGG network structure with a multilabelling output. The output returns a sigmoid of size out_channels. Neural network structure : (features): Layers combinations that depends on which VGG structure selected (avgpool): (0): AdaptiveAvgPool2d(kernel=7) (classifier): (0): Linear(in_features=... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VGG:
"""VGG network structure with a multilabelling output. The output returns a sigmoid of size out_channels. Neural network structure : (features): Layers combinations that depends on which VGG structure selected (avgpool): (0): AdaptiveAvgPool2d(kernel=7) (classifier): (0): Linear(in_features=25088, out_fe... | the_stack_v2_python_sparse | Simulations/helpers/model/vgg.py | emmahoggett/Error_class_lenstronomy | train | 1 |
4718ad8581f9410bbc91a66694ead7aabb98eedc | [
"\"\"\"\n DP算法:复杂度:O(n^2)\n \"\"\"\nif not nums:\n return 0\ndp = [1 for i in range(len(nums))]\nfor i in range(1, len(nums)):\n for j in range(i):\n if nums[i] > nums[j]:\n dp[i] = max(dp[j] + 1, dp[i])\nreturn max(dp)",
"if not nums:\n return 0\nlis = []\nfor i in range(... | <|body_start_0|>
"""
DP算法:复杂度:O(n^2)
"""
if not nums:
return 0
dp = [1 for i in range(len(nums))]
for i in range(1, len(nums)):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[j] + 1, dp[i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLIS1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def lengthOfLIS(self, nums):
"""维护一个数组,依次二分查找当前元素在维护的数组中的位置,选择更新或者不做操作,最后所维护数组长度即为最长子序列长度 :param nums: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_023436 | 1,231 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "lengthOfLIS1",
"signature": "def lengthOfLIS1(self, nums)"
},
{
"docstring": "维护一个数组,依次二分查找当前元素在维护的数组中的位置,选择更新或者不做操作,最后所维护数组长度即为最长子序列长度 :param nums: :return:",
"name": "lengthOfLIS",
"signature": "def lengthOfLIS(self, nums)"
... | 2 | stack_v2_sparse_classes_30k_test_000095 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS1(self, nums): :type nums: List[int] :rtype: int
- def lengthOfLIS(self, nums): 维护一个数组,依次二分查找当前元素在维护的数组中的位置,选择更新或者不做操作,最后所维护数组长度即为最长子序列长度 :param nums: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS1(self, nums): :type nums: List[int] :rtype: int
- def lengthOfLIS(self, nums): 维护一个数组,依次二分查找当前元素在维护的数组中的位置,选择更新或者不做操作,最后所维护数组长度即为最长子序列长度 :param nums: :return:
<|... | e8eae749e77be21716ada6019db4c39d3f00989c | <|skeleton|>
class Solution:
def lengthOfLIS1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def lengthOfLIS(self, nums):
"""维护一个数组,依次二分查找当前元素在维护的数组中的位置,选择更新或者不做操作,最后所维护数组长度即为最长子序列长度 :param nums: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lengthOfLIS1(self, nums):
""":type nums: List[int] :rtype: int"""
"""
DP算法:复杂度:O(n^2)
"""
if not nums:
return 0
dp = [1 for i in range(len(nums))]
for i in range(1, len(nums)):
for j in range(i):
... | the_stack_v2_python_sparse | binary search/300. Longest Increasing Subsequence.py | zazaliu/leetcode-python | train | 1 | |
3ef3693f01c5ac00563a657704ef48a0173988d2 | [
"phi, lambda_, h = (radians(latitude), radians(longitude), altitude)\nN = cls.a / sqrt(1 - cls.e2 * sin(phi) ** 2)\nx = (N + h) * cos(phi) * cos(lambda_)\ny = (N + h) * cos(phi) * sin(lambda_)\nz = (N * (1 - cls.e2) + h) * sin(phi)\nreturn (x, y, z)",
"p = hypot(x, y)\ntheta = atan2(z * cls.a, p * cls.b)\nphi = a... | <|body_start_0|>
phi, lambda_, h = (radians(latitude), radians(longitude), altitude)
N = cls.a / sqrt(1 - cls.e2 * sin(phi) ** 2)
x = (N + h) * cos(phi) * cos(lambda_)
y = (N + h) * cos(phi) * sin(lambda_)
z = (N * (1 - cls.e2) + h) * sin(phi)
return (x, y, z)
<|end_body_... | Geographic datum transformations. | DatumTransformation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatumTransformation:
"""Geographic datum transformations."""
def wgs_to_ecef(cls, latitude, longitude, altitude):
"""From World Geodesic System (WGS) coordinates to Earth-centered Earth-fixed (ECEF) coordinates."""
<|body_0|>
def ecef_to_wgs(cls, x, y, z):
"""Fro... | stack_v2_sparse_classes_36k_train_023437 | 10,327 | permissive | [
{
"docstring": "From World Geodesic System (WGS) coordinates to Earth-centered Earth-fixed (ECEF) coordinates.",
"name": "wgs_to_ecef",
"signature": "def wgs_to_ecef(cls, latitude, longitude, altitude)"
},
{
"docstring": "From Earth-centered Earth-fixed (ECEF) coordinates to World Geodesic Syste... | 2 | stack_v2_sparse_classes_30k_train_001737 | Implement the Python class `DatumTransformation` described below.
Class description:
Geographic datum transformations.
Method signatures and docstrings:
- def wgs_to_ecef(cls, latitude, longitude, altitude): From World Geodesic System (WGS) coordinates to Earth-centered Earth-fixed (ECEF) coordinates.
- def ecef_to_w... | Implement the Python class `DatumTransformation` described below.
Class description:
Geographic datum transformations.
Method signatures and docstrings:
- def wgs_to_ecef(cls, latitude, longitude, altitude): From World Geodesic System (WGS) coordinates to Earth-centered Earth-fixed (ECEF) coordinates.
- def ecef_to_w... | 50ab220b536ba3d3ec645471c70efddfff1855a3 | <|skeleton|>
class DatumTransformation:
"""Geographic datum transformations."""
def wgs_to_ecef(cls, latitude, longitude, altitude):
"""From World Geodesic System (WGS) coordinates to Earth-centered Earth-fixed (ECEF) coordinates."""
<|body_0|>
def ecef_to_wgs(cls, x, y, z):
"""Fro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DatumTransformation:
"""Geographic datum transformations."""
def wgs_to_ecef(cls, latitude, longitude, altitude):
"""From World Geodesic System (WGS) coordinates to Earth-centered Earth-fixed (ECEF) coordinates."""
phi, lambda_, h = (radians(latitude), radians(longitude), altitude)
... | the_stack_v2_python_sparse | demos/multilateration.py | lschoe/mpyc | train | 322 |
eb90e6cd01b97c3c8dc0d6d859b269d6be558285 | [
"super(FilteredLeaveOneGroupOut, self).__init__()\nself.keep = keep\nself.example_ids = example_ids\nself._warned = False\nself.logger = logger if logger else logging.getLogger(__name__)",
"for train_index, test_index in super(FilteredLeaveOneGroupOut, self).split(X, y, groups):\n train_len = len(train_index)\... | <|body_start_0|>
super(FilteredLeaveOneGroupOut, self).__init__()
self.keep = keep
self.example_ids = example_ids
self._warned = False
self.logger = logger if logger else logging.getLogger(__name__)
<|end_body_0|>
<|body_start_1|>
for train_index, test_index in super(Fil... | Custom version ``LeaveOneGroupOut`` cross-validation iterator. This version only outputs indices of instances with IDs in a prespecified set. Parameters ---------- keep : Iterable[IdType] A set of IDs to keep. example_ids : numpy.ndarray, of length n_samples A list of example IDs. logger : Optional[logging.Logger], def... | FilteredLeaveOneGroupOut | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilteredLeaveOneGroupOut:
"""Custom version ``LeaveOneGroupOut`` cross-validation iterator. This version only outputs indices of instances with IDs in a prespecified set. Parameters ---------- keep : Iterable[IdType] A set of IDs to keep. example_ids : numpy.ndarray, of length n_samples A list of... | stack_v2_sparse_classes_36k_train_023438 | 47,118 | permissive | [
{
"docstring": "Initialize the model.",
"name": "__init__",
"signature": "def __init__(self, keep: Iterable[IdType], example_ids: np.ndarray, logger: Optional[logging.Logger]=None)"
},
{
"docstring": "Generate indices to split data into training and test set. Parameters ---------- X : numpy.ndar... | 2 | stack_v2_sparse_classes_30k_train_016738 | Implement the Python class `FilteredLeaveOneGroupOut` described below.
Class description:
Custom version ``LeaveOneGroupOut`` cross-validation iterator. This version only outputs indices of instances with IDs in a prespecified set. Parameters ---------- keep : Iterable[IdType] A set of IDs to keep. example_ids : numpy... | Implement the Python class `FilteredLeaveOneGroupOut` described below.
Class description:
Custom version ``LeaveOneGroupOut`` cross-validation iterator. This version only outputs indices of instances with IDs in a prespecified set. Parameters ---------- keep : Iterable[IdType] A set of IDs to keep. example_ids : numpy... | b10ce3963620d8679a1ce82ccb2268f7ea5fb9c9 | <|skeleton|>
class FilteredLeaveOneGroupOut:
"""Custom version ``LeaveOneGroupOut`` cross-validation iterator. This version only outputs indices of instances with IDs in a prespecified set. Parameters ---------- keep : Iterable[IdType] A set of IDs to keep. example_ids : numpy.ndarray, of length n_samples A list of... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FilteredLeaveOneGroupOut:
"""Custom version ``LeaveOneGroupOut`` cross-validation iterator. This version only outputs indices of instances with IDs in a prespecified set. Parameters ---------- keep : Iterable[IdType] A set of IDs to keep. example_ids : numpy.ndarray, of length n_samples A list of example IDs.... | the_stack_v2_python_sparse | skll/learner/utils.py | EducationalTestingService/skll | train | 320 |
2bb911741c43493ffe36ce3a1e048036384ad70e | [
"user = get_a_user(userpermissionid)\nif not user:\n api.abort(404)\nelse:\n return user\ndata = request.json\nreturn get_a_user(data=data)",
"user = complete_users(userpermissionid)\nif not user:\n api.abort(404)\nelse:\n return user\ndata = request.json\nreturn complete_users(data=data)",
"user = ... | <|body_start_0|>
user = get_a_user(userpermissionid)
if not user:
api.abort(404)
else:
return user
data = request.json
return get_a_user(data=data)
<|end_body_0|>
<|body_start_1|>
user = complete_users(userpermissionid)
if not user:
... | UserPermissions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserPermissions:
def get(self, userpermissionid):
"""get a UserPermissions given its identifier"""
<|body_0|>
def put(self, userpermissionid):
"""UserPermissions updated"""
<|body_1|>
def delete(self, userpermissionid):
"""UserPermissions deleted... | stack_v2_sparse_classes_36k_train_023439 | 2,909 | no_license | [
{
"docstring": "get a UserPermissions given its identifier",
"name": "get",
"signature": "def get(self, userpermissionid)"
},
{
"docstring": "UserPermissions updated",
"name": "put",
"signature": "def put(self, userpermissionid)"
},
{
"docstring": "UserPermissions deleted",
"... | 3 | stack_v2_sparse_classes_30k_val_000410 | Implement the Python class `UserPermissions` described below.
Class description:
Implement the UserPermissions class.
Method signatures and docstrings:
- def get(self, userpermissionid): get a UserPermissions given its identifier
- def put(self, userpermissionid): UserPermissions updated
- def delete(self, userpermis... | Implement the Python class `UserPermissions` described below.
Class description:
Implement the UserPermissions class.
Method signatures and docstrings:
- def get(self, userpermissionid): get a UserPermissions given its identifier
- def put(self, userpermissionid): UserPermissions updated
- def delete(self, userpermis... | 4fa4042304ee01cf23ecc81f9c27977fd12c31b9 | <|skeleton|>
class UserPermissions:
def get(self, userpermissionid):
"""get a UserPermissions given its identifier"""
<|body_0|>
def put(self, userpermissionid):
"""UserPermissions updated"""
<|body_1|>
def delete(self, userpermissionid):
"""UserPermissions deleted... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserPermissions:
def get(self, userpermissionid):
"""get a UserPermissions given its identifier"""
user = get_a_user(userpermissionid)
if not user:
api.abort(404)
else:
return user
data = request.json
return get_a_user(data=data)
def... | the_stack_v2_python_sparse | main/controller/userpermissions_controller.py | Gauravkumar45/Flask-RESTPlus-API | train | 0 | |
5884eb3002f49bc3129b14e6eba27b0794c924ae | [
"ans = ''\nstack = [root]\nwhile stack:\n node = stack.pop()\n if not node:\n ans += '^$'\n else:\n ans += '^{}('.format(node.val)\n stack.append(node.right)\n stack.append(node.left)\nreturn ans",
"def parse(i):\n assert data[i] == '^'\n i += 1\n if data[i] == '$':\n... | <|body_start_0|>
ans = ''
stack = [root]
while stack:
node = stack.pop()
if not node:
ans += '^$'
else:
ans += '^{}('.format(node.val)
stack.append(node.right)
stack.append(node.left)
retu... | 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_36k_train_023440 | 1,395 | 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_019156 | 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:... | 43a5e436b6ec8950c6952554329ae0314430afea | <|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_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
ans = ''
stack = [root]
while stack:
node = stack.pop()
if not node:
ans += '^$'
else:
ans += '^{}('.f... | the_stack_v2_python_sparse | problems/serialize_and_deserialize_binary_tree/solution.py | dengl11/Leetcode | train | 0 | |
2ae191ed3841bfd5a55b334408c69a51b8f203aa | [
"try:\n if headers:\n reply = requests.get(request_content, headers=headers, timeout=MyHTTPRequest.time_out)\n else:\n reply = requests.get(request_content, timeout=MyHTTPRequest.time_out)\nexcept requests.RequestException as ex:\n print('Request exception occured {0}'.format(str(ex)))\nelse:... | <|body_start_0|>
try:
if headers:
reply = requests.get(request_content, headers=headers, timeout=MyHTTPRequest.time_out)
else:
reply = requests.get(request_content, timeout=MyHTTPRequest.time_out)
except requests.RequestException as ex:
... | This class does HTTP basic CRUD operations | MyHTTPRequest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyHTTPRequest:
"""This class does HTTP basic CRUD operations"""
def get_request(request_content, headers=None):
"""HTTP Get Request to process JSON server request"""
<|body_0|>
def post_request(request_content, post_content):
"""HTTP POST Request to send JSON con... | stack_v2_sparse_classes_36k_train_023441 | 6,173 | permissive | [
{
"docstring": "HTTP Get Request to process JSON server request",
"name": "get_request",
"signature": "def get_request(request_content, headers=None)"
},
{
"docstring": "HTTP POST Request to send JSON content to server",
"name": "post_request",
"signature": "def post_request(request_cont... | 5 | stack_v2_sparse_classes_30k_train_003979 | Implement the Python class `MyHTTPRequest` described below.
Class description:
This class does HTTP basic CRUD operations
Method signatures and docstrings:
- def get_request(request_content, headers=None): HTTP Get Request to process JSON server request
- def post_request(request_content, post_content): HTTP POST Req... | Implement the Python class `MyHTTPRequest` described below.
Class description:
This class does HTTP basic CRUD operations
Method signatures and docstrings:
- def get_request(request_content, headers=None): HTTP Get Request to process JSON server request
- def post_request(request_content, post_content): HTTP POST Req... | 7b1b95afad3f9803e55aa0fe96182cf27a2877d1 | <|skeleton|>
class MyHTTPRequest:
"""This class does HTTP basic CRUD operations"""
def get_request(request_content, headers=None):
"""HTTP Get Request to process JSON server request"""
<|body_0|>
def post_request(request_content, post_content):
"""HTTP POST Request to send JSON con... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyHTTPRequest:
"""This class does HTTP basic CRUD operations"""
def get_request(request_content, headers=None):
"""HTTP Get Request to process JSON server request"""
try:
if headers:
reply = requests.get(request_content, headers=headers, timeout=MyHTTPRequest.t... | the_stack_v2_python_sparse | Learn/http_crud_example.py | pandiarajan-src/PyWorks | train | 0 |
e3b011d583ba1bc375c176c8ff82128a252c3d0a | [
"self.class_score_th = class_score_th\nsession_option = onnxruntime.SessionOptions()\nsession_option.log_severity_level = 3\nself.onnx_session = onnxruntime.InferenceSession(model_path, sess_options=session_option, providers=providers)\nself.providers = self.onnx_session.get_providers()\nself.input_shapes = [input.... | <|body_start_0|>
self.class_score_th = class_score_th
session_option = onnxruntime.SessionOptions()
session_option.log_severity_level = 3
self.onnx_session = onnxruntime.InferenceSession(model_path, sess_options=session_option, providers=providers)
self.providers = self.onnx_sess... | YOLOv5ONNX | [
"AGPL-3.0-only",
"LicenseRef-scancode-proprietary-license",
"MIT",
"GPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class YOLOv5ONNX:
def __init__(self, model_path: Optional[str]='yolov5l6_ball_1088x1920_130050_post.onnx', class_score_th: Optional[float]=0.3, providers: Optional[List]=[('TensorrtExecutionProvider', {'trt_engine_cache_enable': True, 'trt_engine_cache_path': '.', 'trt_fp16_enable': True}), 'CUDAExecu... | stack_v2_sparse_classes_36k_train_023442 | 9,092 | permissive | [
{
"docstring": "YOLOv5ONNX Parameters ---------- model_path: Optional[str] ONNX file path for YOLOv5 class_score_th: Optional[float] class_score_th: Optional[float] Score threshold. Default: 0.30 providers: Optional[List] Name of onnx execution providers Default: [ ( 'TensorrtExecutionProvider', { 'trt_engine_c... | 4 | stack_v2_sparse_classes_30k_train_001994 | Implement the Python class `YOLOv5ONNX` described below.
Class description:
Implement the YOLOv5ONNX class.
Method signatures and docstrings:
- def __init__(self, model_path: Optional[str]='yolov5l6_ball_1088x1920_130050_post.onnx', class_score_th: Optional[float]=0.3, providers: Optional[List]=[('TensorrtExecutionPr... | Implement the Python class `YOLOv5ONNX` described below.
Class description:
Implement the YOLOv5ONNX class.
Method signatures and docstrings:
- def __init__(self, model_path: Optional[str]='yolov5l6_ball_1088x1920_130050_post.onnx', class_score_th: Optional[float]=0.3, providers: Optional[List]=[('TensorrtExecutionPr... | ff08e6e8ab095d98e96fc4a136ad5cbccc75fcf9 | <|skeleton|>
class YOLOv5ONNX:
def __init__(self, model_path: Optional[str]='yolov5l6_ball_1088x1920_130050_post.onnx', class_score_th: Optional[float]=0.3, providers: Optional[List]=[('TensorrtExecutionProvider', {'trt_engine_cache_enable': True, 'trt_engine_cache_path': '.', 'trt_fp16_enable': True}), 'CUDAExecu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class YOLOv5ONNX:
def __init__(self, model_path: Optional[str]='yolov5l6_ball_1088x1920_130050_post.onnx', class_score_th: Optional[float]=0.3, providers: Optional[List]=[('TensorrtExecutionProvider', {'trt_engine_cache_enable': True, 'trt_engine_cache_path': '.', 'trt_fp16_enable': True}), 'CUDAExecutionProvider',... | the_stack_v2_python_sparse | 331_YOLOv5L6_Ball/demo_yolov5_onnx.py | PINTO0309/PINTO_model_zoo | train | 2,849 | |
ec64b26f3e346d8705ff33bd80129c4632ba0d6e | [
"self.group_sids = group_sids\nself.is_node_in_cluster = is_node_in_cluster\nself.privileges = privileges\nself.user = user",
"if dictionary is None:\n return None\ngroup_sids = dictionary.get('groupSids')\nis_node_in_cluster = dictionary.get('isNodeInCluster')\nprivileges = dictionary.get('privileges')\nuser ... | <|body_start_0|>
self.group_sids = group_sids
self.is_node_in_cluster = is_node_in_cluster
self.privileges = privileges
self.user = user
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
group_sids = dictionary.get('groupSids')
is_nod... | Implementation of the 'SessionUser' model. TODO: type description here. Attributes: group_sids (list of string): SIDs of the groups the user is a member of. is_node_in_cluster (bool): Whether node is in cluster. privileges (list of string): Privileges is the array of privileges the current user has. user (User): User i... | SessionUser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionUser:
"""Implementation of the 'SessionUser' model. TODO: type description here. Attributes: group_sids (list of string): SIDs of the groups the user is a member of. is_node_in_cluster (bool): Whether node is in cluster. privileges (list of string): Privileges is the array of privileges th... | stack_v2_sparse_classes_36k_train_023443 | 2,251 | permissive | [
{
"docstring": "Constructor for the SessionUser class",
"name": "__init__",
"signature": "def __init__(self, group_sids=None, is_node_in_cluster=None, privileges=None, user=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary r... | 2 | null | Implement the Python class `SessionUser` described below.
Class description:
Implementation of the 'SessionUser' model. TODO: type description here. Attributes: group_sids (list of string): SIDs of the groups the user is a member of. is_node_in_cluster (bool): Whether node is in cluster. privileges (list of string): P... | Implement the Python class `SessionUser` described below.
Class description:
Implementation of the 'SessionUser' model. TODO: type description here. Attributes: group_sids (list of string): SIDs of the groups the user is a member of. is_node_in_cluster (bool): Whether node is in cluster. privileges (list of string): P... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class SessionUser:
"""Implementation of the 'SessionUser' model. TODO: type description here. Attributes: group_sids (list of string): SIDs of the groups the user is a member of. is_node_in_cluster (bool): Whether node is in cluster. privileges (list of string): Privileges is the array of privileges th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SessionUser:
"""Implementation of the 'SessionUser' model. TODO: type description here. Attributes: group_sids (list of string): SIDs of the groups the user is a member of. is_node_in_cluster (bool): Whether node is in cluster. privileges (list of string): Privileges is the array of privileges the current use... | the_stack_v2_python_sparse | cohesity_management_sdk/models/session_user.py | cohesity/management-sdk-python | train | 24 |
310e193414d0d0b2f684ef30deed19c14431e774 | [
"if kwargs is not None:\n for key, value in kwargs.items():\n if key == 'optimizer':\n value = optimizer_dict[value]\n if key == 'rnn':\n value = rnn_dict[value]\n if key == 'rnncell':\n value = rnncell_dict[value]\n setattr(self, key, value)\nself.dat... | <|body_start_0|>
if kwargs is not None:
for key, value in kwargs.items():
if key == 'optimizer':
value = optimizer_dict[value]
if key == 'rnn':
value = rnn_dict[value]
if key == 'rnncell':
val... | Config | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Config:
def __init__(self, **kwargs):
"""Configuration Class: set kwargs as class attributes with setattr"""
<|body_0|>
def __str__(self):
"""Pretty-print configurations in alphabetical order"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if kwargs... | stack_v2_sparse_classes_36k_train_023444 | 5,291 | permissive | [
{
"docstring": "Configuration Class: set kwargs as class attributes with setattr",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Pretty-print configurations in alphabetical order",
"name": "__str__",
"signature": "def __str__(self)"
}
] | 2 | null | Implement the Python class `Config` described below.
Class description:
Implement the Config class.
Method signatures and docstrings:
- def __init__(self, **kwargs): Configuration Class: set kwargs as class attributes with setattr
- def __str__(self): Pretty-print configurations in alphabetical order | Implement the Python class `Config` described below.
Class description:
Implement the Config class.
Method signatures and docstrings:
- def __init__(self, **kwargs): Configuration Class: set kwargs as class attributes with setattr
- def __str__(self): Pretty-print configurations in alphabetical order
<|skeleton|>
cl... | 8851bbde8bedd0fe07beec72d74b3b3624c9c729 | <|skeleton|>
class Config:
def __init__(self, **kwargs):
"""Configuration Class: set kwargs as class attributes with setattr"""
<|body_0|>
def __str__(self):
"""Pretty-print configurations in alphabetical order"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Config:
def __init__(self, **kwargs):
"""Configuration Class: set kwargs as class attributes with setattr"""
if kwargs is not None:
for key, value in kwargs.items():
if key == 'optimizer':
value = optimizer_dict[value]
if key == '... | the_stack_v2_python_sparse | TL-ERC/bert_model/configs.py | declare-lab/conv-emotion | train | 791 | |
abf103845299e7eb8edd6df81b7b2244f466e5d9 | [
"tf.reset_default_graph()\noptim = tf.train.GradientDescentOptimizer(0.001)\nsparse_optim = sparse_optimizers.SparseSnipOptimizer(optim, default_sparsity, mask_init_method, custom_sparsity_map=custom_sparsity_map)\ninp_values = np.arange(1, n_inp + 1)\nscale_vector_values = np.random.uniform(size=(n_out,)) - 0.5\ne... | <|body_start_0|>
tf.reset_default_graph()
optim = tf.train.GradientDescentOptimizer(0.001)
sparse_optim = sparse_optimizers.SparseSnipOptimizer(optim, default_sparsity, mask_init_method, custom_sparsity_map=custom_sparsity_map)
inp_values = np.arange(1, n_inp + 1)
scale_vector_va... | SparseSnipOptimizerTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparseSnipOptimizerTest:
def _setup_graph(self, default_sparsity, mask_init_method, custom_sparsity_map, n_inp=3, n_out=5):
"""Setups a trivial training procedure for sparse training."""
<|body_0|>
def testSnipSparsity(self, n_inp, n_out, default_sparsity):
"""Checki... | stack_v2_sparse_classes_36k_train_023445 | 25,606 | permissive | [
{
"docstring": "Setups a trivial training procedure for sparse training.",
"name": "_setup_graph",
"signature": "def _setup_graph(self, default_sparsity, mask_init_method, custom_sparsity_map, n_inp=3, n_out=5)"
},
{
"docstring": "Checking whether masked_grad is calculated after apply_gradients.... | 5 | null | Implement the Python class `SparseSnipOptimizerTest` described below.
Class description:
Implement the SparseSnipOptimizerTest class.
Method signatures and docstrings:
- def _setup_graph(self, default_sparsity, mask_init_method, custom_sparsity_map, n_inp=3, n_out=5): Setups a trivial training procedure for sparse tr... | Implement the Python class `SparseSnipOptimizerTest` described below.
Class description:
Implement the SparseSnipOptimizerTest class.
Method signatures and docstrings:
- def _setup_graph(self, default_sparsity, mask_init_method, custom_sparsity_map, n_inp=3, n_out=5): Setups a trivial training procedure for sparse tr... | d39fc7d46505cb3196cb1edeb32ed0b6dd44c0f9 | <|skeleton|>
class SparseSnipOptimizerTest:
def _setup_graph(self, default_sparsity, mask_init_method, custom_sparsity_map, n_inp=3, n_out=5):
"""Setups a trivial training procedure for sparse training."""
<|body_0|>
def testSnipSparsity(self, n_inp, n_out, default_sparsity):
"""Checki... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SparseSnipOptimizerTest:
def _setup_graph(self, default_sparsity, mask_init_method, custom_sparsity_map, n_inp=3, n_out=5):
"""Setups a trivial training procedure for sparse training."""
tf.reset_default_graph()
optim = tf.train.GradientDescentOptimizer(0.001)
sparse_optim = sp... | the_stack_v2_python_sparse | rigl/sparse_optimizers_test.py | google-research/rigl | train | 324 | |
08a38ac1dbb0396fe91c1a91498ca87a9cd58a86 | [
"if isinstance(path, (str, Path)):\n path = str(path)\nelse:\n raise TypeError(f\"'path' must be a str or a Path object, but received {type(path)}.\")\nimages = scandir(path, suffix=IMG_EXTENSIONS, recursive=True)\nimages = [osp.join(path, v) for v in images]\nassert images, f'{path} has no valid image file.'... | <|body_start_0|>
if isinstance(path, (str, Path)):
path = str(path)
else:
raise TypeError(f"'path' must be a str or a Path object, but received {type(path)}.")
images = scandir(path, suffix=IMG_EXTENSIONS, recursive=True)
images = [osp.join(path, v) for v in image... | Base class for generation datasets. | BaseGenerationDataset | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseGenerationDataset:
"""Base class for generation datasets."""
def scan_folder(path):
"""Obtain image path list (including sub-folders) from a given folder. Args: path (str | :obj:`Path`): Folder path. Returns: list[str]: Image list obtained from the given folder."""
<|body... | stack_v2_sparse_classes_36k_train_023446 | 1,948 | permissive | [
{
"docstring": "Obtain image path list (including sub-folders) from a given folder. Args: path (str | :obj:`Path`): Folder path. Returns: list[str]: Image list obtained from the given folder.",
"name": "scan_folder",
"signature": "def scan_folder(path)"
},
{
"docstring": "Evaluating with saving ... | 2 | null | Implement the Python class `BaseGenerationDataset` described below.
Class description:
Base class for generation datasets.
Method signatures and docstrings:
- def scan_folder(path): Obtain image path list (including sub-folders) from a given folder. Args: path (str | :obj:`Path`): Folder path. Returns: list[str]: Ima... | Implement the Python class `BaseGenerationDataset` described below.
Class description:
Base class for generation datasets.
Method signatures and docstrings:
- def scan_folder(path): Obtain image path list (including sub-folders) from a given folder. Args: path (str | :obj:`Path`): Folder path. Returns: list[str]: Ima... | 5678851339dff90becb09c3dec41e7214207ccbc | <|skeleton|>
class BaseGenerationDataset:
"""Base class for generation datasets."""
def scan_folder(path):
"""Obtain image path list (including sub-folders) from a given folder. Args: path (str | :obj:`Path`): Folder path. Returns: list[str]: Image list obtained from the given folder."""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseGenerationDataset:
"""Base class for generation datasets."""
def scan_folder(path):
"""Obtain image path list (including sub-folders) from a given folder. Args: path (str | :obj:`Path`): Folder path. Returns: list[str]: Image list obtained from the given folder."""
if isinstance(path,... | the_stack_v2_python_sparse | mmedit/datasets/base_generation_dataset.py | ImCharlesY/AdaInt | train | 141 |
a38ba1b7becdabbc87f1751cc17223d23717af1c | [
"super().__init__(max_retry_attempts=max_retry_attempts, backoff_time_sec=backoff_time_sec)\nself._agent_file_path = os.path.join(self._rospack.get_path(DeepRacerPackages.DEEPRACER_SIMULATION_ENVIRONMENT), 'urdf', 'deepracer_kinematics', 'racecar.xacro')\nself._control_nodes = ['/{}/controller_manager', '/{}/robot_... | <|body_start_0|>
super().__init__(max_retry_attempts=max_retry_attempts, backoff_time_sec=backoff_time_sec)
self._agent_file_path = os.path.join(self._rospack.get_path(DeepRacerPackages.DEEPRACER_SIMULATION_ENVIRONMENT), 'urdf', 'deepracer_kinematics', 'racecar.xacro')
self._control_nodes = ['/{... | agent model class to handle gazebo spawn and delete | AgentModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AgentModel:
"""agent model class to handle gazebo spawn and delete"""
def __init__(self, max_retry_attempts: int=10, backoff_time_sec: float=1.0):
"""Constructor Args: max_retry_attempts (int): max retry attempts for waiting spawn/delete to complete backoff_time_sec (float): backoff ... | stack_v2_sparse_classes_36k_train_023447 | 6,161 | permissive | [
{
"docstring": "Constructor Args: max_retry_attempts (int): max retry attempts for waiting spawn/delete to complete backoff_time_sec (float): backoff time in seconds for spawn/delete to complete",
"name": "__init__",
"signature": "def __init__(self, max_retry_attempts: int=10, backoff_time_sec: float=1.... | 5 | null | Implement the Python class `AgentModel` described below.
Class description:
agent model class to handle gazebo spawn and delete
Method signatures and docstrings:
- def __init__(self, max_retry_attempts: int=10, backoff_time_sec: float=1.0): Constructor Args: max_retry_attempts (int): max retry attempts for waiting sp... | Implement the Python class `AgentModel` described below.
Class description:
agent model class to handle gazebo spawn and delete
Method signatures and docstrings:
- def __init__(self, max_retry_attempts: int=10, backoff_time_sec: float=1.0): Constructor Args: max_retry_attempts (int): max retry attempts for waiting sp... | 2ce50508dd4100eaef7f8729436549a801505705 | <|skeleton|>
class AgentModel:
"""agent model class to handle gazebo spawn and delete"""
def __init__(self, max_retry_attempts: int=10, backoff_time_sec: float=1.0):
"""Constructor Args: max_retry_attempts (int): max retry attempts for waiting spawn/delete to complete backoff_time_sec (float): backoff ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AgentModel:
"""agent model class to handle gazebo spawn and delete"""
def __init__(self, max_retry_attempts: int=10, backoff_time_sec: float=1.0):
"""Constructor Args: max_retry_attempts (int): max retry attempts for waiting spawn/delete to complete backoff_time_sec (float): backoff time in secon... | the_stack_v2_python_sparse | bundle/markov/spawn/models/agent_model.py | aws-deepracer-community/deepracer-simapp | train | 83 |
8053d30e7d2efbc3f6a4a2b30ab812d9fbac469a | [
"self.name = name\nself.table_info = table_info\nself.mtype = mtype\nself.uuid = uuid",
"if dictionary is None:\n return None\nname = dictionary.get('name')\ntable_info = cohesity_management_sdk.models.hive_table.HiveTable.from_dictionary(dictionary.get('tableInfo')) if dictionary.get('tableInfo') else None\nm... | <|body_start_0|>
self.name = name
self.table_info = table_info
self.mtype = mtype
self.uuid = uuid
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
name = dictionary.get('name')
table_info = cohesity_management_sdk.models.hive_table.... | Implementation of the 'HiveProtectionSource' model. Specifies an Object representing Hive. Attributes: name (string): Specifies the instance name of the Hive entity. table_info (HiveTable): Information of a Hive Table, only valid for an entity of type kTable. mtype (TypeHiveProtectionSourceEnum): Specifies the type of ... | HiveProtectionSource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HiveProtectionSource:
"""Implementation of the 'HiveProtectionSource' model. Specifies an Object representing Hive. Attributes: name (string): Specifies the instance name of the Hive entity. table_info (HiveTable): Information of a Hive Table, only valid for an entity of type kTable. mtype (TypeH... | stack_v2_sparse_classes_36k_train_023448 | 2,496 | permissive | [
{
"docstring": "Constructor for the HiveProtectionSource class",
"name": "__init__",
"signature": "def __init__(self, name=None, table_info=None, mtype=None, uuid=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representat... | 2 | null | Implement the Python class `HiveProtectionSource` described below.
Class description:
Implementation of the 'HiveProtectionSource' model. Specifies an Object representing Hive. Attributes: name (string): Specifies the instance name of the Hive entity. table_info (HiveTable): Information of a Hive Table, only valid for... | Implement the Python class `HiveProtectionSource` described below.
Class description:
Implementation of the 'HiveProtectionSource' model. Specifies an Object representing Hive. Attributes: name (string): Specifies the instance name of the Hive entity. table_info (HiveTable): Information of a Hive Table, only valid for... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class HiveProtectionSource:
"""Implementation of the 'HiveProtectionSource' model. Specifies an Object representing Hive. Attributes: name (string): Specifies the instance name of the Hive entity. table_info (HiveTable): Information of a Hive Table, only valid for an entity of type kTable. mtype (TypeH... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HiveProtectionSource:
"""Implementation of the 'HiveProtectionSource' model. Specifies an Object representing Hive. Attributes: name (string): Specifies the instance name of the Hive entity. table_info (HiveTable): Information of a Hive Table, only valid for an entity of type kTable. mtype (TypeHiveProtection... | the_stack_v2_python_sparse | cohesity_management_sdk/models/hive_protection_source.py | cohesity/management-sdk-python | train | 24 |
546da4336aab8bb0e83a3be2303b77c6baa21bcd | [
"if kw.get('interleaved_gate', None) is not None:\n self.default_experiment_name = 'SingleQubitIRB'\nkw['dim_hilbert'] = 2\nsuper().__init__(task_list, sweep_points=sweep_points, nr_seeds=nr_seeds, cliffords=cliffords, **kw)",
"interleaved_gate = kw.get('interleaved_gate', None)\npulse_op_codes_list = []\ntl =... | <|body_start_0|>
if kw.get('interleaved_gate', None) is not None:
self.default_experiment_name = 'SingleQubitIRB'
kw['dim_hilbert'] = 2
super().__init__(task_list, sweep_points=sweep_points, nr_seeds=nr_seeds, cliffords=cliffords, **kw)
<|end_body_0|>
<|body_start_1|>
interl... | Class for running the single qubit randomized benchmarking experiment on several qubits in parallel. | SingleQubitRandomizedBenchmarking | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingleQubitRandomizedBenchmarking:
"""Class for running the single qubit randomized benchmarking experiment on several qubits in parallel."""
def __init__(self, task_list, sweep_points=None, nr_seeds=None, cliffords=None, **kw):
"""Init of the SingleQubitRandomizedBenchmarking class.... | stack_v2_sparse_classes_36k_train_023449 | 38,263 | permissive | [
{
"docstring": "Init of the SingleQubitRandomizedBenchmarking class. Args: nr_seeds (int): the number of times the Clifford group should be sampled for each Clifford sequence length. cliffords(list/array): integers specifying the number of cliffords to apply. Keyword args: passed to parent class interleaved_gat... | 2 | stack_v2_sparse_classes_30k_train_019475 | Implement the Python class `SingleQubitRandomizedBenchmarking` described below.
Class description:
Class for running the single qubit randomized benchmarking experiment on several qubits in parallel.
Method signatures and docstrings:
- def __init__(self, task_list, sweep_points=None, nr_seeds=None, cliffords=None, **... | Implement the Python class `SingleQubitRandomizedBenchmarking` described below.
Class description:
Class for running the single qubit randomized benchmarking experiment on several qubits in parallel.
Method signatures and docstrings:
- def __init__(self, task_list, sweep_points=None, nr_seeds=None, cliffords=None, **... | bc6733d774fe31a23f4c7e73e5eb0beed8d30e7d | <|skeleton|>
class SingleQubitRandomizedBenchmarking:
"""Class for running the single qubit randomized benchmarking experiment on several qubits in parallel."""
def __init__(self, task_list, sweep_points=None, nr_seeds=None, cliffords=None, **kw):
"""Init of the SingleQubitRandomizedBenchmarking class.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SingleQubitRandomizedBenchmarking:
"""Class for running the single qubit randomized benchmarking experiment on several qubits in parallel."""
def __init__(self, task_list, sweep_points=None, nr_seeds=None, cliffords=None, **kw):
"""Init of the SingleQubitRandomizedBenchmarking class. Args: nr_see... | the_stack_v2_python_sparse | pycqed/measurement/benchmarking/randomized_benchmarking.py | QudevETH/PycQED_py3 | train | 8 |
7730af6fc733fdf98d564d81dd57ed7cb5d0231b | [
"super(WorkLogThread, self).__init__(parent)\nself.sig = sig\nself.repository = repository\nself.parent = parent",
"message = 'Journal de travail'\nrestTructuredText = message + os.linesep\nrestTructuredText += '=' * len(message) + os.linesep * 2\nfor commit in self.repository.get_commits():\n com = commit.com... | <|body_start_0|>
super(WorkLogThread, self).__init__(parent)
self.sig = sig
self.repository = repository
self.parent = parent
<|end_body_0|>
<|body_start_1|>
message = 'Journal de travail'
restTructuredText = message + os.linesep
restTructuredText += '=' * len(me... | Thread used to write work log from repository. | WorkLogThread | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkLogThread:
"""Thread used to write work log from repository."""
def __init__(self, parent, repository=None, sig=None):
"""Init thread."""
<|body_0|>
def run(self):
"""Run thread."""
<|body_1|>
def format_message_for_rst(self, message):
""... | stack_v2_sparse_classes_36k_train_023450 | 11,571 | permissive | [
{
"docstring": "Init thread.",
"name": "__init__",
"signature": "def __init__(self, parent, repository=None, sig=None)"
},
{
"docstring": "Run thread.",
"name": "run",
"signature": "def run(self)"
},
{
"docstring": "Format message for a nice rst print.",
"name": "format_messa... | 3 | stack_v2_sparse_classes_30k_train_010927 | Implement the Python class `WorkLogThread` described below.
Class description:
Thread used to write work log from repository.
Method signatures and docstrings:
- def __init__(self, parent, repository=None, sig=None): Init thread.
- def run(self): Run thread.
- def format_message_for_rst(self, message): Format message... | Implement the Python class `WorkLogThread` described below.
Class description:
Thread used to write work log from repository.
Method signatures and docstrings:
- def __init__(self, parent, repository=None, sig=None): Init thread.
- def run(self): Run thread.
- def format_message_for_rst(self, message): Format message... | 93dd7abb03d27cf3490d8b2514365260d67ab15b | <|skeleton|>
class WorkLogThread:
"""Thread used to write work log from repository."""
def __init__(self, parent, repository=None, sig=None):
"""Init thread."""
<|body_0|>
def run(self):
"""Run thread."""
<|body_1|>
def format_message_for_rst(self, message):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorkLogThread:
"""Thread used to write work log from repository."""
def __init__(self, parent, repository=None, sig=None):
"""Init thread."""
super(WorkLogThread, self).__init__(parent)
self.sig = sig
self.repository = repository
self.parent = parent
def run(s... | the_stack_v2_python_sparse | Work_Log_Generator/work_log.py | hastagAB/Awesome-Python-Scripts | train | 1,757 |
d08724279631f36c85d461389fdd940c5e6395bf | [
"if not date:\n return 0\ndays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\ndate = list(map(int, date.split('-')))\nif date[0] % 4 == 0 and date[0] % 100 != 0 or date[0] % 400 == 0:\n days[1] = 29\nres = sum(days[:date[1] - 1]) + date[2]\nreturn res",
"if not date:\n return 0\nY, M, D = map(int, d... | <|body_start_0|>
if not date:
return 0
days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
date = list(map(int, date.split('-')))
if date[0] % 4 == 0 and date[0] % 100 != 0 or date[0] % 400 == 0:
days[1] = 29
res = sum(days[:date[1] - 1]) + date[2]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def dayOfYear(self, date):
""":type date: str :rtype: int"""
<|body_0|>
def dayOfYear_1(self, date):
""":type date: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not date:
return 0
days = [31, 28, 3... | stack_v2_sparse_classes_36k_train_023451 | 1,901 | no_license | [
{
"docstring": ":type date: str :rtype: int",
"name": "dayOfYear",
"signature": "def dayOfYear(self, date)"
},
{
"docstring": ":type date: str :rtype: int",
"name": "dayOfYear_1",
"signature": "def dayOfYear_1(self, date)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dayOfYear(self, date): :type date: str :rtype: int
- def dayOfYear_1(self, date): :type date: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dayOfYear(self, date): :type date: str :rtype: int
- def dayOfYear_1(self, date): :type date: str :rtype: int
<|skeleton|>
class Solution:
def dayOfYear(self, date):
... | 3d9e0ad2f6ed92ec969556f75d97c51ea4854719 | <|skeleton|>
class Solution:
def dayOfYear(self, date):
""":type date: str :rtype: int"""
<|body_0|>
def dayOfYear_1(self, date):
""":type date: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def dayOfYear(self, date):
""":type date: str :rtype: int"""
if not date:
return 0
days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
date = list(map(int, date.split('-')))
if date[0] % 4 == 0 and date[0] % 100 != 0 or date[0] % 400 == 0:
... | the_stack_v2_python_sparse | Solutions/1154_dayOfYear.py | YoupengLi/leetcode-sorting | train | 3 | |
7d45de391bf6e4137a72f13f10662027f73c10f2 | [
"from .services import sort_book_items\nbook = Book()\nbook.price = 1\nbook.certificate_background_width = 100\nbook.certificate_background_height = 100\nbook.certificate_name_top = 50\nbook.save()\nitem_a = Item(book=book, title='a')\nitem_a.save()\nitem_b = Item(book=book, title='b')\nitem_b.save()\nitem_c = Item... | <|body_start_0|>
from .services import sort_book_items
book = Book()
book.price = 1
book.certificate_background_width = 100
book.certificate_background_height = 100
book.certificate_name_top = 50
book.save()
item_a = Item(book=book, title='a')
item... | Service Test. | ServicesTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServicesTest:
"""Service Test."""
def test_sort_book_items(self):
"""Docstring."""
<|body_0|>
def test_sort_book_chapters(self):
"""Docstring."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
from .services import sort_book_items
book = B... | stack_v2_sparse_classes_36k_train_023452 | 6,322 | no_license | [
{
"docstring": "Docstring.",
"name": "test_sort_book_items",
"signature": "def test_sort_book_items(self)"
},
{
"docstring": "Docstring.",
"name": "test_sort_book_chapters",
"signature": "def test_sort_book_chapters(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021295 | Implement the Python class `ServicesTest` described below.
Class description:
Service Test.
Method signatures and docstrings:
- def test_sort_book_items(self): Docstring.
- def test_sort_book_chapters(self): Docstring. | Implement the Python class `ServicesTest` described below.
Class description:
Service Test.
Method signatures and docstrings:
- def test_sort_book_items(self): Docstring.
- def test_sort_book_chapters(self): Docstring.
<|skeleton|>
class ServicesTest:
"""Service Test."""
def test_sort_book_items(self):
... | ee6c8ec70e99c10b1056b28a3a219d7cda5faf06 | <|skeleton|>
class ServicesTest:
"""Service Test."""
def test_sort_book_items(self):
"""Docstring."""
<|body_0|>
def test_sort_book_chapters(self):
"""Docstring."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ServicesTest:
"""Service Test."""
def test_sort_book_items(self):
"""Docstring."""
from .services import sort_book_items
book = Book()
book.price = 1
book.certificate_background_width = 100
book.certificate_background_height = 100
book.certificate_n... | the_stack_v2_python_sparse | dwb_editor/tests.py | ksbek/discleship | train | 0 |
54125502f388c1768a01670557979b5686089a45 | [
"self.input = img\nself.siftDetector = cv2.FeatureDetector_create('SIFT')\nself.siftDetector.setInt('nOctaveLayers', nOctaveLayers)\nself.siftDetector.setDouble('contrastThreshold', contrastThreshold)\nself.siftDetector.setInt('edgeThreshold', edgeThreshold)\nself.siftDetector.setDouble('sigma', sigma)\nself.siftEx... | <|body_start_0|>
self.input = img
self.siftDetector = cv2.FeatureDetector_create('SIFT')
self.siftDetector.setInt('nOctaveLayers', nOctaveLayers)
self.siftDetector.setDouble('contrastThreshold', contrastThreshold)
self.siftDetector.setInt('edgeThreshold', edgeThreshold)
s... | SIFT_Obj | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SIFT_Obj:
def __init__(self, img, nOctaveLayers=3, contrastThreshold=0.04, edgeThreshold=10, sigma=1.6):
"""**Definition**: SIFT_Obj(img, upright = False) SIFT object class. Implementation of SIFT detector and SIFT descriptor. **Inputs**: * img: the source image for which the descriptors... | stack_v2_sparse_classes_36k_train_023453 | 6,133 | no_license | [
{
"docstring": "**Definition**: SIFT_Obj(img, upright = False) SIFT object class. Implementation of SIFT detector and SIFT descriptor. **Inputs**: * img: the source image for which the descriptors are computed * nOctaveLayers (optional): default *3*. See OpenCV documentation * contrastThreshold (optional): defa... | 2 | stack_v2_sparse_classes_30k_train_008853 | Implement the Python class `SIFT_Obj` described below.
Class description:
Implement the SIFT_Obj class.
Method signatures and docstrings:
- def __init__(self, img, nOctaveLayers=3, contrastThreshold=0.04, edgeThreshold=10, sigma=1.6): **Definition**: SIFT_Obj(img, upright = False) SIFT object class. Implementation of... | Implement the Python class `SIFT_Obj` described below.
Class description:
Implement the SIFT_Obj class.
Method signatures and docstrings:
- def __init__(self, img, nOctaveLayers=3, contrastThreshold=0.04, edgeThreshold=10, sigma=1.6): **Definition**: SIFT_Obj(img, upright = False) SIFT object class. Implementation of... | 90531055691a094dd271966b53c40b7a097df375 | <|skeleton|>
class SIFT_Obj:
def __init__(self, img, nOctaveLayers=3, contrastThreshold=0.04, edgeThreshold=10, sigma=1.6):
"""**Definition**: SIFT_Obj(img, upright = False) SIFT object class. Implementation of SIFT detector and SIFT descriptor. **Inputs**: * img: the source image for which the descriptors... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SIFT_Obj:
def __init__(self, img, nOctaveLayers=3, contrastThreshold=0.04, edgeThreshold=10, sigma=1.6):
"""**Definition**: SIFT_Obj(img, upright = False) SIFT object class. Implementation of SIFT detector and SIFT descriptor. **Inputs**: * img: the source image for which the descriptors are computed ... | the_stack_v2_python_sparse | Descriptors/SIFT/SIFT.py | kmakantasis/CV-Tools | train | 0 | |
9f7914ac00edc507c5393840a7fb2377bae6a8ed | [
"super().__init__(observation_spaces=[cost_function], **kwargs)\nself.cost_function: str = cost_function\nself.init_cost_function: str = init_cost_function\nself.previous_cost: Optional[ObservationType] = None",
"del benchmark\ndel observation_view\nself.previous_cost = None",
"del actions\ncost: RewardType = o... | <|body_start_0|>
super().__init__(observation_spaces=[cost_function], **kwargs)
self.cost_function: str = cost_function
self.init_cost_function: str = init_cost_function
self.previous_cost: Optional[ObservationType] = None
<|end_body_0|>
<|body_start_1|>
del benchmark
de... | A reward function that uses a scalar observation space as a cost function. | CostFunctionReward | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CostFunctionReward:
"""A reward function that uses a scalar observation space as a cost function."""
def __init__(self, cost_function: str, init_cost_function: str, **kwargs):
"""Constructor. :param cost_function: The ID of the observation space used to produce scalar costs. :param i... | stack_v2_sparse_classes_36k_train_023454 | 4,165 | permissive | [
{
"docstring": "Constructor. :param cost_function: The ID of the observation space used to produce scalar costs. :param init_cost_function: The ID of an observation space that produces a scalar cost equivalent to cost_function before any actions are made.",
"name": "__init__",
"signature": "def __init__... | 3 | null | Implement the Python class `CostFunctionReward` described below.
Class description:
A reward function that uses a scalar observation space as a cost function.
Method signatures and docstrings:
- def __init__(self, cost_function: str, init_cost_function: str, **kwargs): Constructor. :param cost_function: The ID of the... | Implement the Python class `CostFunctionReward` described below.
Class description:
A reward function that uses a scalar observation space as a cost function.
Method signatures and docstrings:
- def __init__(self, cost_function: str, init_cost_function: str, **kwargs): Constructor. :param cost_function: The ID of the... | 9e0c0beb12da1e1ea82ae6ce920713ee28dda4c9 | <|skeleton|>
class CostFunctionReward:
"""A reward function that uses a scalar observation space as a cost function."""
def __init__(self, cost_function: str, init_cost_function: str, **kwargs):
"""Constructor. :param cost_function: The ID of the observation space used to produce scalar costs. :param i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CostFunctionReward:
"""A reward function that uses a scalar observation space as a cost function."""
def __init__(self, cost_function: str, init_cost_function: str, **kwargs):
"""Constructor. :param cost_function: The ID of the observation space used to produce scalar costs. :param init_cost_func... | the_stack_v2_python_sparse | compiler_gym/envs/llvm/llvm_rewards.py | facebookresearch/CompilerGym | train | 787 |
0f6283b4e3e3e57f2001b80c41e274299a984ae7 | [
"if node is None:\n return None\nwhile node.right:\n node = node.right\nreturn node",
"if node is None:\n return None\nwhile node.left:\n node = node.left\nreturn node",
"if root is None:\n return True\nresult = False\nif self.isValidBST(root.left) and self.isValidBST(root.right):\n max_left =... | <|body_start_0|>
if node is None:
return None
while node.right:
node = node.right
return node
<|end_body_0|>
<|body_start_1|>
if node is None:
return None
while node.left:
node = node.left
return node
<|end_body_1|>
<|body... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def right_most(self, node):
""">>> s = Solution() >>> one, two, three = TreeNode(1), TreeNode(2), TreeNode(3) >>> two.left, one.right = one, three >>> result = s.right_most(one) >>> result.val 3 >>> result = s.right_most(two) >>> result.val 2"""
<|body_0|>
def left... | stack_v2_sparse_classes_36k_train_023455 | 2,115 | no_license | [
{
"docstring": ">>> s = Solution() >>> one, two, three = TreeNode(1), TreeNode(2), TreeNode(3) >>> two.left, one.right = one, three >>> result = s.right_most(one) >>> result.val 3 >>> result = s.right_most(two) >>> result.val 2",
"name": "right_most",
"signature": "def right_most(self, node)"
},
{
... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def right_most(self, node): >>> s = Solution() >>> one, two, three = TreeNode(1), TreeNode(2), TreeNode(3) >>> two.left, one.right = one, three >>> result = s.right_most(one) >>>... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def right_most(self, node): >>> s = Solution() >>> one, two, three = TreeNode(1), TreeNode(2), TreeNode(3) >>> two.left, one.right = one, three >>> result = s.right_most(one) >>>... | 3b13a02f9c8273f9794a57b948d2655792707f37 | <|skeleton|>
class Solution:
def right_most(self, node):
""">>> s = Solution() >>> one, two, three = TreeNode(1), TreeNode(2), TreeNode(3) >>> two.left, one.right = one, three >>> result = s.right_most(one) >>> result.val 3 >>> result = s.right_most(two) >>> result.val 2"""
<|body_0|>
def left... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def right_most(self, node):
""">>> s = Solution() >>> one, two, three = TreeNode(1), TreeNode(2), TreeNode(3) >>> two.left, one.right = one, three >>> result = s.right_most(one) >>> result.val 3 >>> result = s.right_most(two) >>> result.val 2"""
if node is None:
return No... | the_stack_v2_python_sparse | validate_bst.py | gsy/leetcode | train | 1 | |
607db387ef25c1944a8519011ac9aafe49019962 | [
"pos_number = _ObjectIdHelper.id_to_int(pos)\nstart_number = _ObjectIdHelper.id_to_int(start)\nend_number = _ObjectIdHelper.id_to_int(end)\nreturn (pos_number - start_number) / (end_number - start_number)",
"start_number = _ObjectIdHelper.id_to_int(start)\nend_number = _ObjectIdHelper.id_to_int(end)\ntotal = end_... | <|body_start_0|>
pos_number = _ObjectIdHelper.id_to_int(pos)
start_number = _ObjectIdHelper.id_to_int(start)
end_number = _ObjectIdHelper.id_to_int(end)
return (pos_number - start_number) / (end_number - start_number)
<|end_body_0|>
<|body_start_1|>
start_number = _ObjectIdHelpe... | RangeTracker for tracking mongodb _id of bson ObjectId type. | _ObjectIdRangeTracker | [
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-protobuf",
"Apache-2.0",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _ObjectIdRangeTracker:
"""RangeTracker for tracking mongodb _id of bson ObjectId type."""
def position_to_fraction(self, pos: ObjectId, start: ObjectId, end: ObjectId):
"""Returns the fraction of keys in the range [start, end) that are less than the given key."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_023456 | 28,533 | permissive | [
{
"docstring": "Returns the fraction of keys in the range [start, end) that are less than the given key.",
"name": "position_to_fraction",
"signature": "def position_to_fraction(self, pos: ObjectId, start: ObjectId, end: ObjectId)"
},
{
"docstring": "Converts a fraction between 0 and 1 to a posi... | 2 | null | Implement the Python class `_ObjectIdRangeTracker` described below.
Class description:
RangeTracker for tracking mongodb _id of bson ObjectId type.
Method signatures and docstrings:
- def position_to_fraction(self, pos: ObjectId, start: ObjectId, end: ObjectId): Returns the fraction of keys in the range [start, end) ... | Implement the Python class `_ObjectIdRangeTracker` described below.
Class description:
RangeTracker for tracking mongodb _id of bson ObjectId type.
Method signatures and docstrings:
- def position_to_fraction(self, pos: ObjectId, start: ObjectId, end: ObjectId): Returns the fraction of keys in the range [start, end) ... | 6d5048e05087ea54abc889ce402ae2a0abb9252b | <|skeleton|>
class _ObjectIdRangeTracker:
"""RangeTracker for tracking mongodb _id of bson ObjectId type."""
def position_to_fraction(self, pos: ObjectId, start: ObjectId, end: ObjectId):
"""Returns the fraction of keys in the range [start, end) that are less than the given key."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _ObjectIdRangeTracker:
"""RangeTracker for tracking mongodb _id of bson ObjectId type."""
def position_to_fraction(self, pos: ObjectId, start: ObjectId, end: ObjectId):
"""Returns the fraction of keys in the range [start, end) that are less than the given key."""
pos_number = _ObjectIdHel... | the_stack_v2_python_sparse | sdks/python/apache_beam/io/mongodbio.py | apache/beam | train | 7,061 |
0ac7a5a4b0e5fc6e7d8788ba25088571814ed0bd | [
"res = 0\nfor n in nums:\n res ^= n\nreturn res",
"nums.sort()\nfor i in range(0, len(nums) - 2, 2):\n if nums[i] != nums[i + 1]:\n return nums[i]\nreturn nums[-1]",
"dic = {}\nfor n in nums:\n if n in dic:\n dic[n] += 1\n else:\n dic[n] = 1\nfor n in dic.keys():\n if dic[n] ... | <|body_start_0|>
res = 0
for n in nums:
res ^= n
return res
<|end_body_0|>
<|body_start_1|>
nums.sort()
for i in range(0, len(nums) - 2, 2):
if nums[i] != nums[i + 1]:
return nums[i]
return nums[-1]
<|end_body_1|>
<|body_start_2|>... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def singleNumber2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def singleNumber3(self, nums):
""":type nums: List[int] :rtype: int"""
... | stack_v2_sparse_classes_36k_train_023457 | 1,028 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "singleNumber",
"signature": "def singleNumber(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "singleNumber2",
"signature": "def singleNumber2(self, nums)"
},
{
"docstring": ":type nums: List... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums): :type nums: List[int] :rtype: int
- def singleNumber2(self, nums): :type nums: List[int] :rtype: int
- def singleNumber3(self, nums): :type nums: Li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums): :type nums: List[int] :rtype: int
- def singleNumber2(self, nums): :type nums: List[int] :rtype: int
- def singleNumber3(self, nums): :type nums: Li... | 31b2b4dc1e5c3b1c53b333fe30b98ed04b0bdacc | <|skeleton|>
class Solution:
def singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def singleNumber2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def singleNumber3(self, nums):
""":type nums: List[int] :rtype: int"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
res = 0
for n in nums:
res ^= n
return res
def singleNumber2(self, nums):
""":type nums: List[int] :rtype: int"""
nums.sort()
for i in range(0, len(nums) - 2... | the_stack_v2_python_sparse | prob136_single_number.py | Hu-Wenchao/leetcode | train | 0 | |
b3b622525aca2fd41e93fa9532266bc33a2d33bb | [
"if isGPIB(interface):\n unit = 0\n addr = int(interface[4:])\n rm = visa.ResourceManager()\n rm.list_resources()\n self._set_interface(rm.open_resource('GPIB{}::{}::INSTR'.format(unit, addr)))\nelif isserial(interface):\n rm = visa.ResourceManager()\n rm.list_resources()\n self._set_interfa... | <|body_start_0|>
if isGPIB(interface):
unit = 0
addr = int(interface[4:])
rm = visa.ResourceManager()
rm.list_resources()
self._set_interface(rm.open_resource('GPIB{}::{}::INSTR'.format(unit, addr)))
elif isserial(interface):
rm = v... | Dynamically define interface methods/parameters. To be inherited by each instrument class. | Interface | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Interface:
"""Dynamically define interface methods/parameters. To be inherited by each instrument class."""
def __init__(self, interface='gpib0'):
"""Interpret interface string and return dictionary holding created interface object (with address included)."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_023458 | 2,490 | permissive | [
{
"docstring": "Interpret interface string and return dictionary holding created interface object (with address included).",
"name": "__init__",
"signature": "def __init__(self, interface='gpib0')"
},
{
"docstring": "Register essential methods.",
"name": "_set_interface",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_016974 | Implement the Python class `Interface` described below.
Class description:
Dynamically define interface methods/parameters. To be inherited by each instrument class.
Method signatures and docstrings:
- def __init__(self, interface='gpib0'): Interpret interface string and return dictionary holding created interface ob... | Implement the Python class `Interface` described below.
Class description:
Dynamically define interface methods/parameters. To be inherited by each instrument class.
Method signatures and docstrings:
- def __init__(self, interface='gpib0'): Interpret interface string and return dictionary holding created interface ob... | 088fba2568d10451adda51a068c15c8c2a73d9ce | <|skeleton|>
class Interface:
"""Dynamically define interface methods/parameters. To be inherited by each instrument class."""
def __init__(self, interface='gpib0'):
"""Interpret interface string and return dictionary holding created interface object (with address included)."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Interface:
"""Dynamically define interface methods/parameters. To be inherited by each instrument class."""
def __init__(self, interface='gpib0'):
"""Interpret interface string and return dictionary holding created interface object (with address included)."""
if isGPIB(interface):
... | the_stack_v2_python_sparse | cryomem/tnminstruments/base.py | bebaek/cryomem | train | 1 |
ba308a701b479ba42e97e868e8e2e892de64308d | [
"self.ngram = ngram\nself.successors = successors if successors else {}\nself.finishing = finishing",
"def weighted_choice(weights):\n rnd = random.random() * sum(weights)\n for i, w in enumerate(weights):\n rnd -= w\n if rnd < 0:\n return i\n\ndef random_item(weightsdict):\n \"\... | <|body_start_0|>
self.ngram = ngram
self.successors = successors if successors else {}
self.finishing = finishing
<|end_body_0|>
<|body_start_1|>
def weighted_choice(weights):
rnd = random.random() * sum(weights)
for i, w in enumerate(weights):
rn... | A ProbState is a state of a ProbWordTree. It is composed of a n-gram and a dictonary of successor => weight pairs. Furthermore, it can be finishing or not. | ProbState | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProbState:
"""A ProbState is a state of a ProbWordTree. It is composed of a n-gram and a dictonary of successor => weight pairs. Furthermore, it can be finishing or not."""
def __init__(self, ngram, successors=None, finishing=False):
"""Initialize a state. ngram -- the n-gram of this... | stack_v2_sparse_classes_36k_train_023459 | 10,121 | no_license | [
{
"docstring": "Initialize a state. ngram -- the n-gram of this state; successors -- a dictionary of successor => weight pairs; finishing -- whether or not the n-gram is a finishing n-gram.",
"name": "__init__",
"signature": "def __init__(self, ngram, successors=None, finishing=False)"
},
{
"doc... | 2 | stack_v2_sparse_classes_30k_train_015165 | Implement the Python class `ProbState` described below.
Class description:
A ProbState is a state of a ProbWordTree. It is composed of a n-gram and a dictonary of successor => weight pairs. Furthermore, it can be finishing or not.
Method signatures and docstrings:
- def __init__(self, ngram, successors=None, finishin... | Implement the Python class `ProbState` described below.
Class description:
A ProbState is a state of a ProbWordTree. It is composed of a n-gram and a dictonary of successor => weight pairs. Furthermore, it can be finishing or not.
Method signatures and docstrings:
- def __init__(self, ngram, successors=None, finishin... | ee60d5341be1304a23b6e41db3d38beb92c29662 | <|skeleton|>
class ProbState:
"""A ProbState is a state of a ProbWordTree. It is composed of a n-gram and a dictonary of successor => weight pairs. Furthermore, it can be finishing or not."""
def __init__(self, ngram, successors=None, finishing=False):
"""Initialize a state. ngram -- the n-gram of this... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProbState:
"""A ProbState is a state of a ProbWordTree. It is composed of a n-gram and a dictonary of successor => weight pairs. Furthermore, it can be finishing or not."""
def __init__(self, ngram, successors=None, finishing=False):
"""Initialize a state. ngram -- the n-gram of this state; succe... | the_stack_v2_python_sparse | src/probs/probwordtree.py | sbusard/MePGen | train | 1 |
94ae49040d657845ae0da7f07bde03941ec84765 | [
"count = ex.first_result(await ex.conn.fetchrow(f'SELECT COUNT(*) FROM currency.Levels WHERE UserID = $1 AND {command} > $2', user_id, 1))\nif not count:\n level = 1\nelse:\n level = ex.first_result(await ex.conn.fetchrow(f'SELECT {command} FROM currency.Levels WHERE UserID = $1', user_id))\nreturn int(level)... | <|body_start_0|>
count = ex.first_result(await ex.conn.fetchrow(f'SELECT COUNT(*) FROM currency.Levels WHERE UserID = $1 AND {command} > $2', user_id, 1))
if not count:
level = 1
else:
level = ex.first_result(await ex.conn.fetchrow(f'SELECT {command} FROM currency.Levels ... | Levels | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Levels:
async def get_level(user_id, command):
"""Get the level of a command (rob/beg/daily)."""
<|body_0|>
async def set_level(user_id, level, command):
"""Set the level of a user for a specific command."""
<|body_1|>
async def get_xp(level, command):
... | stack_v2_sparse_classes_36k_train_023460 | 1,827 | permissive | [
{
"docstring": "Get the level of a command (rob/beg/daily).",
"name": "get_level",
"signature": "async def get_level(user_id, command)"
},
{
"docstring": "Set the level of a user for a specific command.",
"name": "set_level",
"signature": "async def set_level(user_id, level, command)"
... | 4 | stack_v2_sparse_classes_30k_train_000195 | Implement the Python class `Levels` described below.
Class description:
Implement the Levels class.
Method signatures and docstrings:
- async def get_level(user_id, command): Get the level of a command (rob/beg/daily).
- async def set_level(user_id, level, command): Set the level of a user for a specific command.
- a... | Implement the Python class `Levels` described below.
Class description:
Implement the Levels class.
Method signatures and docstrings:
- async def get_level(user_id, command): Get the level of a command (rob/beg/daily).
- async def set_level(user_id, level, command): Set the level of a user for a specific command.
- a... | 9193fcd3b6c73f61c57fb2fad557921141b1c07a | <|skeleton|>
class Levels:
async def get_level(user_id, command):
"""Get the level of a command (rob/beg/daily)."""
<|body_0|>
async def set_level(user_id, level, command):
"""Set the level of a user for a specific command."""
<|body_1|>
async def get_xp(level, command):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Levels:
async def get_level(user_id, command):
"""Get the level of a command (rob/beg/daily)."""
count = ex.first_result(await ex.conn.fetchrow(f'SELECT COUNT(*) FROM currency.Levels WHERE UserID = $1 AND {command} > $2', user_id, 1))
if not count:
level = 1
else:
... | the_stack_v2_python_sparse | util/levels.py | Developing-Studio/ci-IreneBot | train | 0 | |
3236b0b970465c83630651fb37628868a253f3e2 | [
"node = self._getObjectNode('object')\nnode.appendChild(self._extractProperties())\nnode.appendChild(self._extractObjects())\nself._logger.info('Types tool exported.')\nreturn node",
"if self.environ.shouldPurge():\n self._purgeProperties()\n self._purgeObjects()\nself._initProperties(node)\nself._initObjec... | <|body_start_0|>
node = self._getObjectNode('object')
node.appendChild(self._extractProperties())
node.appendChild(self._extractObjects())
self._logger.info('Types tool exported.')
return node
<|end_body_0|>
<|body_start_1|>
if self.environ.shouldPurge():
sel... | XML im- and exporter for TypesTool. | TypesToolXMLAdapter | [
"ZPL-2.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TypesToolXMLAdapter:
"""XML im- and exporter for TypesTool."""
def _exportNode(self):
"""Export the object as a DOM node."""
<|body_0|>
def _importNode(self, node):
"""Import the object from the DOM node."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_023461 | 8,767 | permissive | [
{
"docstring": "Export the object as a DOM node.",
"name": "_exportNode",
"signature": "def _exportNode(self)"
},
{
"docstring": "Import the object from the DOM node.",
"name": "_importNode",
"signature": "def _importNode(self, node)"
}
] | 2 | null | Implement the Python class `TypesToolXMLAdapter` described below.
Class description:
XML im- and exporter for TypesTool.
Method signatures and docstrings:
- def _exportNode(self): Export the object as a DOM node.
- def _importNode(self, node): Import the object from the DOM node. | Implement the Python class `TypesToolXMLAdapter` described below.
Class description:
XML im- and exporter for TypesTool.
Method signatures and docstrings:
- def _exportNode(self): Export the object as a DOM node.
- def _importNode(self, node): Import the object from the DOM node.
<|skeleton|>
class TypesToolXMLAdapt... | 8c32b5ec521536c1a2c3752426f6ed209b11190c | <|skeleton|>
class TypesToolXMLAdapter:
"""XML im- and exporter for TypesTool."""
def _exportNode(self):
"""Export the object as a DOM node."""
<|body_0|>
def _importNode(self, node):
"""Import the object from the DOM node."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TypesToolXMLAdapter:
"""XML im- and exporter for TypesTool."""
def _exportNode(self):
"""Export the object as a DOM node."""
node = self._getObjectNode('object')
node.appendChild(self._extractProperties())
node.appendChild(self._extractObjects())
self._logger.info(... | the_stack_v2_python_sparse | src/Products/CMFCore/exportimport/typeinfo.py | zopefoundation/Products.CMFCore | train | 4 |
af286d59e275e1d3957c187905950923b3167e3b | [
"goods: List[Stock] = Stock.objects(id=goodid)\nif not goods:\n raise error.StockNotFound(goodid)\nreturn goods[0]",
"if individual:\n return Stock.objects(name__icontains=name, individual=True)\nreturn Stock.objects(name__icontains=name)",
"tags = [tag.strip().lower() for tag in tags]\nif individual:\n ... | <|body_start_0|>
goods: List[Stock] = Stock.objects(id=goodid)
if not goods:
raise error.StockNotFound(goodid)
return goods[0]
<|end_body_0|>
<|body_start_1|>
if individual:
return Stock.objects(name__icontains=name, individual=True)
return Stock.objects(... | 查询相关函数 | Retrieve | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Retrieve:
"""查询相关函数"""
def byid(goodid: ObjectId) -> Stock:
"""根据商品ID查询商品"""
<|body_0|>
def byname(name: str, individual: bool=False) -> List[Stock]:
"""根据名称查找商品"""
<|body_1|>
def bytags(tags: List[str], individual: bool=False) -> List[Stock]:
... | stack_v2_sparse_classes_36k_train_023462 | 1,684 | permissive | [
{
"docstring": "根据商品ID查询商品",
"name": "byid",
"signature": "def byid(goodid: ObjectId) -> Stock"
},
{
"docstring": "根据名称查找商品",
"name": "byname",
"signature": "def byname(name: str, individual: bool=False) -> List[Stock]"
},
{
"docstring": "根据标签查找商品",
"name": "bytags",
"sig... | 3 | null | Implement the Python class `Retrieve` described below.
Class description:
查询相关函数
Method signatures and docstrings:
- def byid(goodid: ObjectId) -> Stock: 根据商品ID查询商品
- def byname(name: str, individual: bool=False) -> List[Stock]: 根据名称查找商品
- def bytags(tags: List[str], individual: bool=False) -> List[Stock]: 根据标签查找商品 | Implement the Python class `Retrieve` described below.
Class description:
查询相关函数
Method signatures and docstrings:
- def byid(goodid: ObjectId) -> Stock: 根据商品ID查询商品
- def byname(name: str, individual: bool=False) -> List[Stock]: 根据名称查找商品
- def bytags(tags: List[str], individual: bool=False) -> List[Stock]: 根据标签查找商品
... | 79e34f4b8fba8c6fd208b5a3049103dca2064ab5 | <|skeleton|>
class Retrieve:
"""查询相关函数"""
def byid(goodid: ObjectId) -> Stock:
"""根据商品ID查询商品"""
<|body_0|>
def byname(name: str, individual: bool=False) -> List[Stock]:
"""根据名称查找商品"""
<|body_1|>
def bytags(tags: List[str], individual: bool=False) -> List[Stock]:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Retrieve:
"""查询相关函数"""
def byid(goodid: ObjectId) -> Stock:
"""根据商品ID查询商品"""
goods: List[Stock] = Stock.objects(id=goodid)
if not goods:
raise error.StockNotFound(goodid)
return goods[0]
def byname(name: str, individual: bool=False) -> List[Stock]:
... | the_stack_v2_python_sparse | leaf/selling/functions/stock.py | guiqiqi/leaf | train | 122 |
e76ea67c34129393b23335ae1ab31ba755bc250f | [
"if classnames_add is None:\n classnames_add = []\nif classnames_exclude is None:\n classnames_exclude = []\nclassnames = self.edit_button_classnames + classnames_add\nclassname = self.finalise_classname(classnames, classnames_exclude)\nreturn {'url': self.url_helper.get_action_url('select_field', pk), 'label... | <|body_start_0|>
if classnames_add is None:
classnames_add = []
if classnames_exclude is None:
classnames_exclude = []
classnames = self.edit_button_classnames + classnames_add
classname = self.finalise_classname(classnames, classnames_exclude)
return {'ur... | Custom button helper class Allows us to add a button to items on the list display for adding a field to the omni form | WagtailOmniFormButtonHelper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WagtailOmniFormButtonHelper:
"""Custom button helper class Allows us to add a button to items on the list display for adding a field to the omni form"""
def add_field_button(self, pk, classnames_add=None, classnames_exclude=None):
"""Helper method for generating a button to display i... | stack_v2_sparse_classes_36k_train_023463 | 22,300 | permissive | [
{
"docstring": "Helper method for generating a button to display in the list view for the WagtailOmniForm ModelAdmin class. The button itself will be displayed in each row, next to the edit and delete buttons :param pk: The primary key of the OmniForm model instance :param classnames_add: List of extra class na... | 4 | stack_v2_sparse_classes_30k_train_004126 | Implement the Python class `WagtailOmniFormButtonHelper` described below.
Class description:
Custom button helper class Allows us to add a button to items on the list display for adding a field to the omni form
Method signatures and docstrings:
- def add_field_button(self, pk, classnames_add=None, classnames_exclude=... | Implement the Python class `WagtailOmniFormButtonHelper` described below.
Class description:
Custom button helper class Allows us to add a button to items on the list display for adding a field to the omni form
Method signatures and docstrings:
- def add_field_button(self, pk, classnames_add=None, classnames_exclude=... | 0c96162445f8b5ddf7f326f6b0a2e6ec239c4bd5 | <|skeleton|>
class WagtailOmniFormButtonHelper:
"""Custom button helper class Allows us to add a button to items on the list display for adding a field to the omni form"""
def add_field_button(self, pk, classnames_add=None, classnames_exclude=None):
"""Helper method for generating a button to display i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WagtailOmniFormButtonHelper:
"""Custom button helper class Allows us to add a button to items on the list display for adding a field to the omni form"""
def add_field_button(self, pk, classnames_add=None, classnames_exclude=None):
"""Helper method for generating a button to display in the list vi... | the_stack_v2_python_sparse | omniforms/wagtail/wagtail_hooks.py | omni-digital/omni-forms | train | 6 |
010a5eda3d42169112042145140e28c0d5d19a12 | [
"room_list = []\nrooms = models.Room.objects.all()\nfor room in rooms:\n if room.state == 0:\n room_list.append(room.roomId)\nreturn render(request, 'usermgr/order/neworder.html', locals())",
"resultData = {'ret': None}\nif request.is_ajax():\n room = models.Room.objects.filter(roomId=request.POST.ge... | <|body_start_0|>
room_list = []
rooms = models.Room.objects.all()
for room in rooms:
if room.state == 0:
room_list.append(room.roomId)
return render(request, 'usermgr/order/neworder.html', locals())
<|end_body_0|>
<|body_start_1|>
resultData = {'ret':... | 处理新预约订单 | NewOrder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewOrder:
"""处理新预约订单"""
def get(self, request):
"""获取新预约订单页面 :param request: django路由响应默认携带request对象 :return: 返回新预约订单页面"""
<|body_0|>
def post(self, request):
"""获取新预约数据 :param request: django路由响应默认携带request对象 :return: 返回预约结果"""
<|body_1|>
def databa... | stack_v2_sparse_classes_36k_train_023464 | 12,349 | no_license | [
{
"docstring": "获取新预约订单页面 :param request: django路由响应默认携带request对象 :return: 返回新预约订单页面",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "获取新预约数据 :param request: django路由响应默认携带request对象 :return: 返回预约结果",
"name": "post",
"signature": "def post(self, request)"
},
{... | 3 | stack_v2_sparse_classes_30k_train_012866 | Implement the Python class `NewOrder` described below.
Class description:
处理新预约订单
Method signatures and docstrings:
- def get(self, request): 获取新预约订单页面 :param request: django路由响应默认携带request对象 :return: 返回新预约订单页面
- def post(self, request): 获取新预约数据 :param request: django路由响应默认携带request对象 :return: 返回预约结果
- def database_u... | Implement the Python class `NewOrder` described below.
Class description:
处理新预约订单
Method signatures and docstrings:
- def get(self, request): 获取新预约订单页面 :param request: django路由响应默认携带request对象 :return: 返回新预约订单页面
- def post(self, request): 获取新预约数据 :param request: django路由响应默认携带request对象 :return: 返回预约结果
- def database_u... | 26c49e8f525ca57dca27f8de53d15bcab24d00e4 | <|skeleton|>
class NewOrder:
"""处理新预约订单"""
def get(self, request):
"""获取新预约订单页面 :param request: django路由响应默认携带request对象 :return: 返回新预约订单页面"""
<|body_0|>
def post(self, request):
"""获取新预约数据 :param request: django路由响应默认携带request对象 :return: 返回预约结果"""
<|body_1|>
def databa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NewOrder:
"""处理新预约订单"""
def get(self, request):
"""获取新预约订单页面 :param request: django路由响应默认携带request对象 :return: 返回新预约订单页面"""
room_list = []
rooms = models.Room.objects.all()
for room in rooms:
if room.state == 0:
room_list.append(room.roomId)
... | the_stack_v2_python_sparse | iframe_api/views.py | A35-Zhou/Rental-House-Manager | train | 0 |
e89f563b6524e8ea8bf829625580de482cdc923d | [
"if value is None:\n return None\nreturn str(self.container((str(item) for item in value)))",
"if value is None:\n return None\nreturn self.container((str(item) for item in value))",
"if isinstance(value, str):\n if value and value[0] in self.open:\n value = value[1:]\n if value and value[-1]... | <|body_start_0|>
if value is None:
return None
return str(self.container((str(item) for item in value)))
<|end_body_0|>
<|body_start_1|>
if value is None:
return None
return self.container((str(item) for item in value))
<|end_body_1|>
<|body_start_2|>
if... | The base class for type declarators that are sequences of other types | Sequence | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sequence:
"""The base class for type declarators that are sequences of other types"""
def str(self, value):
"""Render value as a string that can be persisted for later coercion"""
<|body_0|>
def json(self, value):
"""Generate a JSON representation of {value}"""
... | stack_v2_sparse_classes_36k_train_023465 | 3,102 | permissive | [
{
"docstring": "Render value as a string that can be persisted for later coercion",
"name": "str",
"signature": "def str(self, value)"
},
{
"docstring": "Generate a JSON representation of {value}",
"name": "json",
"signature": "def json(self, value)"
},
{
"docstring": "Convert {v... | 3 | stack_v2_sparse_classes_30k_train_001754 | Implement the Python class `Sequence` described below.
Class description:
The base class for type declarators that are sequences of other types
Method signatures and docstrings:
- def str(self, value): Render value as a string that can be persisted for later coercion
- def json(self, value): Generate a JSON represent... | Implement the Python class `Sequence` described below.
Class description:
The base class for type declarators that are sequences of other types
Method signatures and docstrings:
- def str(self, value): Render value as a string that can be persisted for later coercion
- def json(self, value): Generate a JSON represent... | d741c44ffb3e9e1f726bf492202ac8738bb4aa1c | <|skeleton|>
class Sequence:
"""The base class for type declarators that are sequences of other types"""
def str(self, value):
"""Render value as a string that can be persisted for later coercion"""
<|body_0|>
def json(self, value):
"""Generate a JSON representation of {value}"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Sequence:
"""The base class for type declarators that are sequences of other types"""
def str(self, value):
"""Render value as a string that can be persisted for later coercion"""
if value is None:
return None
return str(self.container((str(item) for item in value)))
... | the_stack_v2_python_sparse | packages/pyre/schemata/Sequence.py | pyre/pyre | train | 27 |
d1f6321444eebb293c4c5b7e242eeb6170c23217 | [
"future_question = create_question(question_text='Future question.', days=5)\nurl = reverse('polls:detail', args=(future_question.id,))\nresponse = self.client.get(url)\nself.assertEqual(response.status_code, 404)",
"past_question = create_question(question_text='Past question.', days=-5)\nurl = reverse('polls:de... | <|body_start_0|>
future_question = create_question(question_text='Future question.', days=5)
url = reverse('polls:detail', args=(future_question.id,))
response = self.client.get(url)
self.assertEqual(response.status_code, 404)
<|end_body_0|>
<|body_start_1|>
past_question = crea... | QuestionDetailViewTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionDetailViewTests:
def test_detail_view_with_a_future_question(self):
"""The detail view of a question with a pub_date in the future should return a 404 not found."""
<|body_0|>
def test_detail_view_with_a_past_question(self):
"""The detail view of a question w... | stack_v2_sparse_classes_36k_train_023466 | 7,438 | no_license | [
{
"docstring": "The detail view of a question with a pub_date in the future should return a 404 not found.",
"name": "test_detail_view_with_a_future_question",
"signature": "def test_detail_view_with_a_future_question(self)"
},
{
"docstring": "The detail view of a question with a pub_date in the... | 2 | stack_v2_sparse_classes_30k_train_009612 | Implement the Python class `QuestionDetailViewTests` described below.
Class description:
Implement the QuestionDetailViewTests class.
Method signatures and docstrings:
- def test_detail_view_with_a_future_question(self): The detail view of a question with a pub_date in the future should return a 404 not found.
- def ... | Implement the Python class `QuestionDetailViewTests` described below.
Class description:
Implement the QuestionDetailViewTests class.
Method signatures and docstrings:
- def test_detail_view_with_a_future_question(self): The detail view of a question with a pub_date in the future should return a 404 not found.
- def ... | a7e7fc72abe357172f5aa49b03c5b9298d92d6e8 | <|skeleton|>
class QuestionDetailViewTests:
def test_detail_view_with_a_future_question(self):
"""The detail view of a question with a pub_date in the future should return a 404 not found."""
<|body_0|>
def test_detail_view_with_a_past_question(self):
"""The detail view of a question w... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuestionDetailViewTests:
def test_detail_view_with_a_future_question(self):
"""The detail view of a question with a pub_date in the future should return a 404 not found."""
future_question = create_question(question_text='Future question.', days=5)
url = reverse('polls:detail', args=(f... | the_stack_v2_python_sparse | firstdjango/polls/tests.py | thewritingstew/lpthw | train | 0 | |
2805a1c497e4f93966678b95a82387d37a5da1a9 | [
"super(PixelSetEncoder, self).__init__()\nself.input_dim = input_dim\nself.mlp1_dim = copy.deepcopy(mlp1)\nself.mlp2_dim = copy.deepcopy(mlp2)\nself.pooling = pooling\nself.with_extra = with_extra\nself.extra_size = extra_size\nself.name = 'PSE-{}-{}-{}'.format('|'.join(list(map(str, self.mlp1_dim))), pooling, '|'.... | <|body_start_0|>
super(PixelSetEncoder, self).__init__()
self.input_dim = input_dim
self.mlp1_dim = copy.deepcopy(mlp1)
self.mlp2_dim = copy.deepcopy(mlp2)
self.pooling = pooling
self.with_extra = with_extra
self.extra_size = extra_size
self.name = 'PSE-{}... | PixelSetEncoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PixelSetEncoder:
def __init__(self, input_dim, mlp1=[10, 32, 64], pooling='mean_std', mlp2=[64, 128], with_extra=True, extra_size=4):
"""Pixel-set encoder. Args: input_dim (int): Number of channels of the input tensors mlp1 (list): Dimensions of the successive feature spaces of MLP1 pool... | stack_v2_sparse_classes_36k_train_023467 | 19,964 | no_license | [
{
"docstring": "Pixel-set encoder. Args: input_dim (int): Number of channels of the input tensors mlp1 (list): Dimensions of the successive feature spaces of MLP1 pooling (str): Pixel-embedding pooling strategy, can be chosen in ('mean','std','max,'min') or any underscore-separated combination thereof. mlp2 (li... | 2 | null | Implement the Python class `PixelSetEncoder` described below.
Class description:
Implement the PixelSetEncoder class.
Method signatures and docstrings:
- def __init__(self, input_dim, mlp1=[10, 32, 64], pooling='mean_std', mlp2=[64, 128], with_extra=True, extra_size=4): Pixel-set encoder. Args: input_dim (int): Numbe... | Implement the Python class `PixelSetEncoder` described below.
Class description:
Implement the PixelSetEncoder class.
Method signatures and docstrings:
- def __init__(self, input_dim, mlp1=[10, 32, 64], pooling='mean_std', mlp2=[64, 128], with_extra=True, extra_size=4): Pixel-set encoder. Args: input_dim (int): Numbe... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class PixelSetEncoder:
def __init__(self, input_dim, mlp1=[10, 32, 64], pooling='mean_std', mlp2=[64, 128], with_extra=True, extra_size=4):
"""Pixel-set encoder. Args: input_dim (int): Number of channels of the input tensors mlp1 (list): Dimensions of the successive feature spaces of MLP1 pool... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PixelSetEncoder:
def __init__(self, input_dim, mlp1=[10, 32, 64], pooling='mean_std', mlp2=[64, 128], with_extra=True, extra_size=4):
"""Pixel-set encoder. Args: input_dim (int): Number of channels of the input tensors mlp1 (list): Dimensions of the successive feature spaces of MLP1 pooling (str): Pix... | the_stack_v2_python_sparse | generated/test_VSainteuf_pytorch_psetae.py | jansel/pytorch-jit-paritybench | train | 35 | |
341d8807eb407681ac4a7202b209f63a5642d24b | [
"super().__init__()\nself.message_function = SchnetMessageFunction(node_size, edge_size)\nself.state_transition_function = nn.Sequential(nn.Linear(node_size, node_size), ShiftedSoftplus(), nn.Linear(node_size, node_size))",
"nodes = node_state[edges[:, 0]]\nmessages = self.message_function(nodes, edge_state)\nmes... | <|body_start_0|>
super().__init__()
self.message_function = SchnetMessageFunction(node_size, edge_size)
self.state_transition_function = nn.Sequential(nn.Linear(node_size, node_size), ShiftedSoftplus(), nn.Linear(node_size, node_size))
<|end_body_0|>
<|body_start_1|>
nodes = node_state[... | Interaction network | Interaction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Interaction:
"""Interaction network"""
def __init__(self, node_size, edge_size):
"""Args: node_size (int): Size of node state edge_size (int): Size of edge state"""
<|body_0|>
def forward(self, node_state, edges, edge_state):
"""Args: node_state (tensor): Node st... | stack_v2_sparse_classes_36k_train_023468 | 7,647 | no_license | [
{
"docstring": "Args: node_size (int): Size of node state edge_size (int): Size of edge state",
"name": "__init__",
"signature": "def __init__(self, node_size, edge_size)"
},
{
"docstring": "Args: node_state (tensor): Node states (num_nodes, node_size) edges (tensor): Directed edges with node in... | 2 | stack_v2_sparse_classes_30k_train_017801 | Implement the Python class `Interaction` described below.
Class description:
Interaction network
Method signatures and docstrings:
- def __init__(self, node_size, edge_size): Args: node_size (int): Size of node state edge_size (int): Size of edge state
- def forward(self, node_state, edges, edge_state): Args: node_st... | Implement the Python class `Interaction` described below.
Class description:
Interaction network
Method signatures and docstrings:
- def __init__(self, node_size, edge_size): Args: node_size (int): Size of node state edge_size (int): Size of edge state
- def forward(self, node_state, edges, edge_state): Args: node_st... | 117b1898d389b4b1727f0531c1f7eb827384f5c8 | <|skeleton|>
class Interaction:
"""Interaction network"""
def __init__(self, node_size, edge_size):
"""Args: node_size (int): Size of node state edge_size (int): Size of edge state"""
<|body_0|>
def forward(self, node_state, edges, edge_state):
"""Args: node_state (tensor): Node st... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Interaction:
"""Interaction network"""
def __init__(self, node_size, edge_size):
"""Args: node_size (int): Size of node state edge_size (int): Size of edge state"""
super().__init__()
self.message_function = SchnetMessageFunction(node_size, edge_size)
self.state_transition... | the_stack_v2_python_sparse | models/layer.py | bhastrup/RL-on-energy-surfaces | train | 0 |
05668b57bdb7acb5d38f6d265e74ea38e2cb1b71 | [
"try:\n plugin = module.Plugin\nexcept AttributeError:\n return False\ncommand = data[invocation_length:]\ntry:\n result = plugin.run(self, command)\nexcept TypeError:\n result = plugin().run(self, command)\nplugin_ran = True\nreturn (plugin_ran, result)",
"if plugin_list:\n plugin_ran = False\n ... | <|body_start_0|>
try:
plugin = module.Plugin
except AttributeError:
return False
command = data[invocation_length:]
try:
result = plugin.run(self, command)
except TypeError:
result = plugin().run(self, command)
plugin_ran = ... | PluginRunner | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PluginRunner:
def run_plugin(self, module, data, invocation_length):
"""Run the plugin in the given module. :param self: :param module: :param data: :param invocation_length: :return:"""
<|body_0|>
def process_plugins(self, plugin_list, data, help_mode_on=False):
"""... | stack_v2_sparse_classes_36k_train_023469 | 4,870 | no_license | [
{
"docstring": "Run the plugin in the given module. :param self: :param module: :param data: :param invocation_length: :return:",
"name": "run_plugin",
"signature": "def run_plugin(self, module, data, invocation_length)"
},
{
"docstring": "Process plugins to see if the data should be intercepted... | 2 | stack_v2_sparse_classes_30k_train_020345 | Implement the Python class `PluginRunner` described below.
Class description:
Implement the PluginRunner class.
Method signatures and docstrings:
- def run_plugin(self, module, data, invocation_length): Run the plugin in the given module. :param self: :param module: :param data: :param invocation_length: :return:
- d... | Implement the Python class `PluginRunner` described below.
Class description:
Implement the PluginRunner class.
Method signatures and docstrings:
- def run_plugin(self, module, data, invocation_length): Run the plugin in the given module. :param self: :param module: :param data: :param invocation_length: :return:
- d... | fb0aa92ea05dc05416a0a2cf3cc7a698b25f1d38 | <|skeleton|>
class PluginRunner:
def run_plugin(self, module, data, invocation_length):
"""Run the plugin in the given module. :param self: :param module: :param data: :param invocation_length: :return:"""
<|body_0|>
def process_plugins(self, plugin_list, data, help_mode_on=False):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PluginRunner:
def run_plugin(self, module, data, invocation_length):
"""Run the plugin in the given module. :param self: :param module: :param data: :param invocation_length: :return:"""
try:
plugin = module.Plugin
except AttributeError:
return False
com... | the_stack_v2_python_sparse | common.py | RattleyCooper/Oyster | train | 2 | |
01c9db7579414146eeebc69c1e6fed90c1c42d27 | [
"self.face_feature_reader_obj = GET_face_feature_reader_obj()\nself.input_type = input_type\nif input_type == 'file':\n self.cap = cv2.VideoCapture(file_path)\nelse:\n self.cap = cv2.VideoCapture(0)\n ret, frame = self.cap.read()\ncascPath = configuration.MODEL_PATH + 'haarcascade_frontalface_alt.xml'\nsel... | <|body_start_0|>
self.face_feature_reader_obj = GET_face_feature_reader_obj()
self.input_type = input_type
if input_type == 'file':
self.cap = cv2.VideoCapture(file_path)
else:
self.cap = cv2.VideoCapture(0)
ret, frame = self.cap.read()
cascPat... | This class is used to return the face data in real time. Attribute: cap: the capture stream faceCascade: model for detecting where the face is. file_name: the file name of the current frame in hard disk delete_queue: the queue is used to save all the delete file name faces: the faces for predicting the emotion, we used... | FaceReader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FaceReader:
"""This class is used to return the face data in real time. Attribute: cap: the capture stream faceCascade: model for detecting where the face is. file_name: the file name of the current frame in hard disk delete_queue: the queue is used to save all the delete file name faces: the fac... | stack_v2_sparse_classes_36k_train_023470 | 4,944 | permissive | [
{
"docstring": "Arguments: input_type: 'file' indicates that the stream is from file. In other case, the stream will from the default camera.",
"name": "__init__",
"signature": "def __init__(self, input_type, file_path=None)"
},
{
"docstring": "delete files for releasing the resourse.",
"nam... | 5 | stack_v2_sparse_classes_30k_train_004170 | Implement the Python class `FaceReader` described below.
Class description:
This class is used to return the face data in real time. Attribute: cap: the capture stream faceCascade: model for detecting where the face is. file_name: the file name of the current frame in hard disk delete_queue: the queue is used to save ... | Implement the Python class `FaceReader` described below.
Class description:
This class is used to return the face data in real time. Attribute: cap: the capture stream faceCascade: model for detecting where the face is. file_name: the file name of the current frame in hard disk delete_queue: the queue is used to save ... | 531f646dcb493dce2575af3b9d77403ebc1f4a35 | <|skeleton|>
class FaceReader:
"""This class is used to return the face data in real time. Attribute: cap: the capture stream faceCascade: model for detecting where the face is. file_name: the file name of the current frame in hard disk delete_queue: the queue is used to save all the delete file name faces: the fac... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FaceReader:
"""This class is used to return the face data in real time. Attribute: cap: the capture stream faceCascade: model for detecting where the face is. file_name: the file name of the current frame in hard disk delete_queue: the queue is used to save all the delete file name faces: the faces for predic... | the_stack_v2_python_sparse | MindLink-Eumpy/real_time_detection/GUI/MLE_tool/FaceReader.py | wozu-dichter/MindLink-Explorer | train | 0 |
df473fce83bb935312de116901da74fbd15bb3ca | [
"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!')"
] | <|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... | Service to upload conversions. | ConversionUploadServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConversionUploadServiceServicer:
"""Service to upload conversions."""
def UploadClickConversions(self, request, context):
"""Processes the given click conversions."""
<|body_0|>
def UploadCallConversions(self, request, context):
"""Processes the given call conver... | stack_v2_sparse_classes_36k_train_023471 | 3,273 | permissive | [
{
"docstring": "Processes the given click conversions.",
"name": "UploadClickConversions",
"signature": "def UploadClickConversions(self, request, context)"
},
{
"docstring": "Processes the given call conversions.",
"name": "UploadCallConversions",
"signature": "def UploadCallConversions... | 2 | null | Implement the Python class `ConversionUploadServiceServicer` described below.
Class description:
Service to upload conversions.
Method signatures and docstrings:
- def UploadClickConversions(self, request, context): Processes the given click conversions.
- def UploadCallConversions(self, request, context): Processes ... | Implement the Python class `ConversionUploadServiceServicer` described below.
Class description:
Service to upload conversions.
Method signatures and docstrings:
- def UploadClickConversions(self, request, context): Processes the given click conversions.
- def UploadCallConversions(self, request, context): Processes ... | a5b6cede64f4d9912ae6ad26927a54e40448c9fe | <|skeleton|>
class ConversionUploadServiceServicer:
"""Service to upload conversions."""
def UploadClickConversions(self, request, context):
"""Processes the given click conversions."""
<|body_0|>
def UploadCallConversions(self, request, context):
"""Processes the given call conver... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConversionUploadServiceServicer:
"""Service to upload conversions."""
def UploadClickConversions(self, request, context):
"""Processes the given click conversions."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotIm... | the_stack_v2_python_sparse | google/ads/google_ads/v3/proto/services/conversion_upload_service_pb2_grpc.py | fiboknacky/google-ads-python | train | 0 |
1d22ff6c1ea90a61579ee9997bf5aa6b76f4742b | [
"assert fibonacci(-1) is None\nassert fibonacci(0) == 0\nassert fibonacci(1) == 1\nassert fibonacci(5) == 5\nassert fibonacci(10) == 55",
"assert lucas(-14) is None\nassert lucas(0) == 2\nassert lucas(1) == 1\nassert lucas(6) == 18"
] | <|body_start_0|>
assert fibonacci(-1) is None
assert fibonacci(0) == 0
assert fibonacci(1) == 1
assert fibonacci(5) == 5
assert fibonacci(10) == 55
<|end_body_0|>
<|body_start_1|>
assert lucas(-14) is None
assert lucas(0) == 2
assert lucas(1) == 1
... | A class to run unittests on series.py | MyTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyTests:
"""A class to run unittests on series.py"""
def test_fib(self):
"""Test the outputs of the fibonnaci function"""
<|body_0|>
def test_lucas(self):
"""Test the outputs of the lucas function"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_023472 | 645 | no_license | [
{
"docstring": "Test the outputs of the fibonnaci function",
"name": "test_fib",
"signature": "def test_fib(self)"
},
{
"docstring": "Test the outputs of the lucas function",
"name": "test_lucas",
"signature": "def test_lucas(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016783 | Implement the Python class `MyTests` described below.
Class description:
A class to run unittests on series.py
Method signatures and docstrings:
- def test_fib(self): Test the outputs of the fibonnaci function
- def test_lucas(self): Test the outputs of the lucas function | Implement the Python class `MyTests` described below.
Class description:
A class to run unittests on series.py
Method signatures and docstrings:
- def test_fib(self): Test the outputs of the fibonnaci function
- def test_lucas(self): Test the outputs of the lucas function
<|skeleton|>
class MyTests:
"""A class t... | 4ae3d9e87dcdce17e44135c2d478f0b023d68b88 | <|skeleton|>
class MyTests:
"""A class to run unittests on series.py"""
def test_fib(self):
"""Test the outputs of the fibonnaci function"""
<|body_0|>
def test_lucas(self):
"""Test the outputs of the lucas function"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyTests:
"""A class to run unittests on series.py"""
def test_fib(self):
"""Test the outputs of the fibonnaci function"""
assert fibonacci(-1) is None
assert fibonacci(0) == 0
assert fibonacci(1) == 1
assert fibonacci(5) == 5
assert fibonacci(10) == 55
... | the_stack_v2_python_sparse | students/KimNighelli/session07/test_series.py | finddeniseonline/sea-c34-python.old | train | 0 |
48737ba6844677b67d3eef585426400a94766527 | [
"foo_bytes = b'\\xf0\\x0b\\xa4'\nbar_bytes = b'\\x0b\\xa4\\x99'\nbaz_bytes = b'\\xbaY\\x06'\nqux_bytes = b'\\x8a\\xf3\\x12'\nwith tempfile.TemporaryDirectory() as tempdir_name:\n temp_root = Path(tempdir_name)\n (temp_root / 'foo.bin').write_bytes(foo_bytes)\n (temp_root / 'bar.bin').write_bytes(bar_bytes)... | <|body_start_0|>
foo_bytes = b'\xf0\x0b\xa4'
bar_bytes = b'\x0b\xa4\x99'
baz_bytes = b'\xbaY\x06'
qux_bytes = b'\x8a\xf3\x12'
with tempfile.TemporaryDirectory() as tempdir_name:
temp_root = Path(tempdir_name)
(temp_root / 'foo.bin').write_bytes(foo_bytes)
... | Test the generation of unsigned update bundles. | GenUnsignedUpdateBundleTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenUnsignedUpdateBundleTest:
"""Test the generation of unsigned update bundles."""
def test_bundle_generation(self):
"""Tests basic creation of an UpdateBundle from temp dir."""
<|body_0|>
def test_excludes(self):
"""Checks that excludes are excluded from update ... | stack_v2_sparse_classes_36k_train_023473 | 6,153 | permissive | [
{
"docstring": "Tests basic creation of an UpdateBundle from temp dir.",
"name": "test_bundle_generation",
"signature": "def test_bundle_generation(self)"
},
{
"docstring": "Checks that excludes are excluded from update bundles.",
"name": "test_excludes",
"signature": "def test_excludes(... | 5 | stack_v2_sparse_classes_30k_train_019016 | Implement the Python class `GenUnsignedUpdateBundleTest` described below.
Class description:
Test the generation of unsigned update bundles.
Method signatures and docstrings:
- def test_bundle_generation(self): Tests basic creation of an UpdateBundle from temp dir.
- def test_excludes(self): Checks that excludes are ... | Implement the Python class `GenUnsignedUpdateBundleTest` described below.
Class description:
Test the generation of unsigned update bundles.
Method signatures and docstrings:
- def test_bundle_generation(self): Tests basic creation of an UpdateBundle from temp dir.
- def test_excludes(self): Checks that excludes are ... | 7f3590b58e8398aad68c1e59702c459d2f8ca38e | <|skeleton|>
class GenUnsignedUpdateBundleTest:
"""Test the generation of unsigned update bundles."""
def test_bundle_generation(self):
"""Tests basic creation of an UpdateBundle from temp dir."""
<|body_0|>
def test_excludes(self):
"""Checks that excludes are excluded from update ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GenUnsignedUpdateBundleTest:
"""Test the generation of unsigned update bundles."""
def test_bundle_generation(self):
"""Tests basic creation of an UpdateBundle from temp dir."""
foo_bytes = b'\xf0\x0b\xa4'
bar_bytes = b'\x0b\xa4\x99'
baz_bytes = b'\xbaY\x06'
qux_by... | the_stack_v2_python_sparse | pw_software_update/py/update_bundle_test.py | waelbarakat/pigweed | train | 0 |
fa799cea89bfb17f5a23c9035105bbc576b79085 | [
"def dfs(node):\n if node is None:\n return 0\n l = dfs(node.left)\n r = dfs(node.right)\n if node.left and node.right:\n return min(l, r) + 1\n if node.left is None and node.right is None:\n return 1\n return max(l, r) + 1\nreturn dfs(root)",
"from collections import deque\... | <|body_start_0|>
def dfs(node):
if node is None:
return 0
l = dfs(node.left)
r = dfs(node.right)
if node.left and node.right:
return min(l, r) + 1
if node.left is None and node.right is None:
return 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minDepth(self, root) -> int:
"""DFS, Time: O(n), Space: O(n)"""
<|body_0|>
def minDepth(self, root) -> int:
"""BFS, Time: O(n), Space: O(n)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def dfs(node):
if node is None:
... | stack_v2_sparse_classes_36k_train_023474 | 1,176 | no_license | [
{
"docstring": "DFS, Time: O(n), Space: O(n)",
"name": "minDepth",
"signature": "def minDepth(self, root) -> int"
},
{
"docstring": "BFS, Time: O(n), Space: O(n)",
"name": "minDepth",
"signature": "def minDepth(self, root) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_007951 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDepth(self, root) -> int: DFS, Time: O(n), Space: O(n)
- def minDepth(self, root) -> int: BFS, Time: O(n), Space: O(n) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDepth(self, root) -> int: DFS, Time: O(n), Space: O(n)
- def minDepth(self, root) -> int: BFS, Time: O(n), Space: O(n)
<|skeleton|>
class Solution:
def minDepth(self... | 72136e3487d239f5b37e2d6393e034262a6bf599 | <|skeleton|>
class Solution:
def minDepth(self, root) -> int:
"""DFS, Time: O(n), Space: O(n)"""
<|body_0|>
def minDepth(self, root) -> int:
"""BFS, Time: O(n), Space: O(n)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minDepth(self, root) -> int:
"""DFS, Time: O(n), Space: O(n)"""
def dfs(node):
if node is None:
return 0
l = dfs(node.left)
r = dfs(node.right)
if node.left and node.right:
return min(l, r) + 1
... | the_stack_v2_python_sparse | python/111-Minimum Depth of Binary Tree.py | cwza/leetcode | train | 0 | |
c0ed0f130613f3b72db6f39d65f0330a43ba6d4a | [
"self.algorithm = type(algorithm).__name__\nself.alg_args = algorithm.get_parameters()\nself.problem = type(algorithm.problem).__name__\nself.num_data = 0\nself.list_of_samples = []\nself.list_of_accepts = []\nself.list_of_sim_calls = []\nself.list_of_sim_locs = []",
"self.list_of_samples.append(algorithm.samples... | <|body_start_0|>
self.algorithm = type(algorithm).__name__
self.alg_args = algorithm.get_parameters()
self.problem = type(algorithm.problem).__name__
self.num_data = 0
self.list_of_samples = []
self.list_of_accepts = []
self.list_of_sim_calls = []
self.lis... | Storage class for abc-data. | ABCData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ABCData:
"""Storage class for abc-data."""
def __init__(self, algorithm):
"""Create a data-container for this combination."""
<|body_0|>
def add_datum(self, algorithm):
"""Add data to the database."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_023475 | 3,110 | no_license | [
{
"docstring": "Create a data-container for this combination.",
"name": "__init__",
"signature": "def __init__(self, algorithm)"
},
{
"docstring": "Add data to the database.",
"name": "add_datum",
"signature": "def add_datum(self, algorithm)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009908 | Implement the Python class `ABCData` described below.
Class description:
Storage class for abc-data.
Method signatures and docstrings:
- def __init__(self, algorithm): Create a data-container for this combination.
- def add_datum(self, algorithm): Add data to the database. | Implement the Python class `ABCData` described below.
Class description:
Storage class for abc-data.
Method signatures and docstrings:
- def __init__(self, algorithm): Create a data-container for this combination.
- def add_datum(self, algorithm): Add data to the database.
<|skeleton|>
class ABCData:
"""Storage ... | b20a328c0e3b5459fd99fc1ad8d05d6baa62483c | <|skeleton|>
class ABCData:
"""Storage class for abc-data."""
def __init__(self, algorithm):
"""Create a data-container for this combination."""
<|body_0|>
def add_datum(self, algorithm):
"""Add data to the database."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ABCData:
"""Storage class for abc-data."""
def __init__(self, algorithm):
"""Create a data-container for this combination."""
self.algorithm = type(algorithm).__name__
self.alg_args = algorithm.get_parameters()
self.problem = type(algorithm.problem).__name__
self.n... | the_stack_v2_python_sparse | pythonABC/data_manipulation.py | mehdisebbar/kl-aggregation | train | 0 |
059420fdbde8613115f5caea91c98c6dda2788c9 | [
"super().__init__(classifier_name=classifier_name, data=data, labels=labels, ids=ids)\nself.regexes = regexes\nself.capture_biases = {capture: capture_biases[capture] for capture in capture_biases} if capture_biases else {}\nself.capture_biases.update({negative_label: 0})\nself.regexes.update({negative_label: []})\... | <|body_start_0|>
super().__init__(classifier_name=classifier_name, data=data, labels=labels, ids=ids)
self.regexes = regexes
self.capture_biases = {capture: capture_biases[capture] for capture in capture_biases} if capture_biases else {}
self.capture_biases.update({negative_label: 0})
... | Class specialized in capturing information of interest. E.g Country of Birth | CaptureClassifier | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CaptureClassifier:
"""Class specialized in capturing information of interest. E.g Country of Birth"""
def __init__(self, classifier_name='CaptureClassifier', regexes=None, data=None, labels=None, ids=None, capture_biases=None, handler=CaptureHandler(), negative_label='None'):
"""Keyw... | stack_v2_sparse_classes_36k_train_023476 | 5,707 | permissive | [
{
"docstring": "Keyword Arguments: classifier_name {str} -- Name of classifier (default: {\"CaptureClassifier\"}) regexes {dictionary} -- A dictionary of regex_name to a list of Regex objects (default: {None}) data {list} -- List of data (default: {None}) labels {list} -- List of labels (default: {None}) ids {l... | 3 | null | Implement the Python class `CaptureClassifier` described below.
Class description:
Class specialized in capturing information of interest. E.g Country of Birth
Method signatures and docstrings:
- def __init__(self, classifier_name='CaptureClassifier', regexes=None, data=None, labels=None, ids=None, capture_biases=Non... | Implement the Python class `CaptureClassifier` described below.
Class description:
Class specialized in capturing information of interest. E.g Country of Birth
Method signatures and docstrings:
- def __init__(self, classifier_name='CaptureClassifier', regexes=None, data=None, labels=None, ids=None, capture_biases=Non... | 12c4f06e91de8f96e0f5a98ddf72e6771a996d9a | <|skeleton|>
class CaptureClassifier:
"""Class specialized in capturing information of interest. E.g Country of Birth"""
def __init__(self, classifier_name='CaptureClassifier', regexes=None, data=None, labels=None, ids=None, capture_biases=None, handler=CaptureHandler(), negative_label='None'):
"""Keyw... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CaptureClassifier:
"""Class specialized in capturing information of interest. E.g Country of Birth"""
def __init__(self, classifier_name='CaptureClassifier', regexes=None, data=None, labels=None, ids=None, capture_biases=None, handler=CaptureHandler(), negative_label='None'):
"""Keyword Arguments... | the_stack_v2_python_sparse | RegexNLP-py/classifier/simple_capture_classifier.py | Express50/CHARTextract | train | 0 |
915eff02d8d652cd86dfcb3270527ebd24fa7949 | [
"self.data_path = str(dataset_params['path'])\nself.width = int(common_params['image_size'])\nself.height = int(common_params['image_size'])\nself.batch_size = int(common_params['batch_size'])",
"with open(self.data_path, 'rb') as f:\n images = pickle.load(f)\nwith open(self.data_path + '_labels', 'rb') as f:\... | <|body_start_0|>
self.data_path = str(dataset_params['path'])
self.width = int(common_params['image_size'])
self.height = int(common_params['image_size'])
self.batch_size = int(common_params['batch_size'])
<|end_body_0|>
<|body_start_1|>
with open(self.data_path, 'rb') as f:
... | ImageDataset | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageDataset:
def __init__(self, common_params, dataset_params):
"""Args: common_params: A dict dataset_params: A dict"""
<|body_0|>
def batch(self):
"""get batch Returns: images: 4-D ndarray [batch_size, height, width, 3] labels: 3-D ndarray [batch_size, max_objects... | stack_v2_sparse_classes_36k_train_023477 | 1,630 | no_license | [
{
"docstring": "Args: common_params: A dict dataset_params: A dict",
"name": "__init__",
"signature": "def __init__(self, common_params, dataset_params)"
},
{
"docstring": "get batch Returns: images: 4-D ndarray [batch_size, height, width, 3] labels: 3-D ndarray [batch_size, max_objects, 5]",
... | 2 | stack_v2_sparse_classes_30k_train_004606 | Implement the Python class `ImageDataset` described below.
Class description:
Implement the ImageDataset class.
Method signatures and docstrings:
- def __init__(self, common_params, dataset_params): Args: common_params: A dict dataset_params: A dict
- def batch(self): get batch Returns: images: 4-D ndarray [batch_siz... | Implement the Python class `ImageDataset` described below.
Class description:
Implement the ImageDataset class.
Method signatures and docstrings:
- def __init__(self, common_params, dataset_params): Args: common_params: A dict dataset_params: A dict
- def batch(self): get batch Returns: images: 4-D ndarray [batch_siz... | 7f555727c4761cce933da953fbe14685e7263179 | <|skeleton|>
class ImageDataset:
def __init__(self, common_params, dataset_params):
"""Args: common_params: A dict dataset_params: A dict"""
<|body_0|>
def batch(self):
"""get batch Returns: images: 4-D ndarray [batch_size, height, width, 3] labels: 3-D ndarray [batch_size, max_objects... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageDataset:
def __init__(self, common_params, dataset_params):
"""Args: common_params: A dict dataset_params: A dict"""
self.data_path = str(dataset_params['path'])
self.width = int(common_params['image_size'])
self.height = int(common_params['image_size'])
self.batch... | the_stack_v2_python_sparse | CNN/classicNetwork/leNet/leNetDataset.py | sadiq18/tensorflow | train | 0 | |
523180d9ca36ae28f02cb325e7ff8bdde9ad6886 | [
"with mock.patch('SConsArguments.Importer._import_argmod') as mock_import_argmod, mock.patch('SConsArguments.Importer._load_decls', side_effect=tested._load_decls) as mock_load_decls:\n mock_mod = mock.MagicMock()\n mock_mod.arguments = mock.MagicMock()\n mock_mod.arguments.return_value = {'arg1': {'help':... | <|body_start_0|>
with mock.patch('SConsArguments.Importer._import_argmod') as mock_import_argmod, mock.patch('SConsArguments.Importer._load_decls', side_effect=tested._load_decls) as mock_load_decls:
mock_mod = mock.MagicMock()
mock_mod.arguments = mock.MagicMock()
mock_mod.a... | Test_ImportArguments | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_ImportArguments:
def test_ImportArguments_1(self):
"""Test ImportArguments()"""
<|body_0|>
def test_ImportArguments_2(self):
"""Test ImportArguments()"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
with mock.patch('SConsArguments.Importer._imp... | stack_v2_sparse_classes_36k_train_023478 | 42,804 | permissive | [
{
"docstring": "Test ImportArguments()",
"name": "test_ImportArguments_1",
"signature": "def test_ImportArguments_1(self)"
},
{
"docstring": "Test ImportArguments()",
"name": "test_ImportArguments_2",
"signature": "def test_ImportArguments_2(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002897 | Implement the Python class `Test_ImportArguments` described below.
Class description:
Implement the Test_ImportArguments class.
Method signatures and docstrings:
- def test_ImportArguments_1(self): Test ImportArguments()
- def test_ImportArguments_2(self): Test ImportArguments() | Implement the Python class `Test_ImportArguments` described below.
Class description:
Implement the Test_ImportArguments class.
Method signatures and docstrings:
- def test_ImportArguments_1(self): Test ImportArguments()
- def test_ImportArguments_2(self): Test ImportArguments()
<|skeleton|>
class Test_ImportArgumen... | f4b783fc79fe3fc16e8d0f58308099a67752d299 | <|skeleton|>
class Test_ImportArguments:
def test_ImportArguments_1(self):
"""Test ImportArguments()"""
<|body_0|>
def test_ImportArguments_2(self):
"""Test ImportArguments()"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_ImportArguments:
def test_ImportArguments_1(self):
"""Test ImportArguments()"""
with mock.patch('SConsArguments.Importer._import_argmod') as mock_import_argmod, mock.patch('SConsArguments.Importer._load_decls', side_effect=tested._load_decls) as mock_load_decls:
mock_mod = moc... | the_stack_v2_python_sparse | unit_tests/SConsArgumentsT/ImporterTests.py | mcqueen256/scons-arguments | train | 0 | |
d7c2199cb0604fb803804f5ca9de01f0d9afcab8 | [
"self._Ms = (Fsum(), Fsum())\nif name:\n self.name = name\nif xs:\n self.fadd(xs)",
"if isinstance(other, Fwelford):\n nb = len(other)\n if nb > 0:\n na = len(self)\n if na > 0:\n M, S = self._Ms\n M_, S_ = other._Ms\n n = na + nb\n n_ = float(... | <|body_start_0|>
self._Ms = (Fsum(), Fsum())
if name:
self.name = name
if xs:
self.fadd(xs)
<|end_body_0|>
<|body_start_1|>
if isinstance(other, Fwelford):
nb = len(other)
if nb > 0:
na = len(self)
if na > 0... | U{Welford<https://WikiPedia.org/wiki/Algorithms_for_calculating_variance>}'s accumulator computing the running mean, (sample) variance and standard deviation. @see: U{Cook<https://www.JohnDCook.com/blog/standard_deviation/>} and L{Fcook}. | Fwelford | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fwelford:
"""U{Welford<https://WikiPedia.org/wiki/Algorithms_for_calculating_variance>}'s accumulator computing the running mean, (sample) variance and standard deviation. @see: U{Cook<https://www.JohnDCook.com/blog/standard_deviation/>} and L{Fcook}."""
def __init__(self, xs=None, name=NN):... | stack_v2_sparse_classes_36k_train_023479 | 25,484 | permissive | [
{
"docstring": "New L{Fwelford} stats accumulator. @kwarg xs: Iterable with initial values (C{Scalar}s). @kwarg name: Optional name (C{str}). @see: Method L{Fwelford.fadd}.",
"name": "__init__",
"signature": "def __init__(self, xs=None, name=NN)"
},
{
"docstring": "Add B{C{other}} to this L{Fwel... | 3 | stack_v2_sparse_classes_30k_train_013792 | Implement the Python class `Fwelford` described below.
Class description:
U{Welford<https://WikiPedia.org/wiki/Algorithms_for_calculating_variance>}'s accumulator computing the running mean, (sample) variance and standard deviation. @see: U{Cook<https://www.JohnDCook.com/blog/standard_deviation/>} and L{Fcook}.
Metho... | Implement the Python class `Fwelford` described below.
Class description:
U{Welford<https://WikiPedia.org/wiki/Algorithms_for_calculating_variance>}'s accumulator computing the running mean, (sample) variance and standard deviation. @see: U{Cook<https://www.JohnDCook.com/blog/standard_deviation/>} and L{Fcook}.
Metho... | eba35704b248a7a0388b30f3cea19793921e99b7 | <|skeleton|>
class Fwelford:
"""U{Welford<https://WikiPedia.org/wiki/Algorithms_for_calculating_variance>}'s accumulator computing the running mean, (sample) variance and standard deviation. @see: U{Cook<https://www.JohnDCook.com/blog/standard_deviation/>} and L{Fcook}."""
def __init__(self, xs=None, name=NN):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Fwelford:
"""U{Welford<https://WikiPedia.org/wiki/Algorithms_for_calculating_variance>}'s accumulator computing the running mean, (sample) variance and standard deviation. @see: U{Cook<https://www.JohnDCook.com/blog/standard_deviation/>} and L{Fcook}."""
def __init__(self, xs=None, name=NN):
"""N... | the_stack_v2_python_sparse | pygeodesy/fstats.py | mrJean1/PyGeodesy | train | 283 |
341c9408d0606b00a640efc1abc4d1a19f69955c | [
"if value is not None:\n if isinstance(value, dict):\n return value\n else:\n return value.to_dict()",
"try:\n if isinstance(value, dict):\n sub_instance = kwargs['obj_type']()\n sub_instance.from_dict(value)\n sub_instance.validate_dict(value)\n return sub_insta... | <|body_start_0|>
if value is not None:
if isinstance(value, dict):
return value
else:
return value.to_dict()
<|end_body_0|>
<|body_start_1|>
try:
if isinstance(value, dict):
sub_instance = kwargs['obj_type']()
... | ObjectType | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectType:
def serialize(value, **kwargs):
"""Convert a value to a JSON serializable value"""
<|body_0|>
def deserialize(value, **kwargs):
"""Convert value to object"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if value is not None:
... | stack_v2_sparse_classes_36k_train_023480 | 1,336 | no_license | [
{
"docstring": "Convert a value to a JSON serializable value",
"name": "serialize",
"signature": "def serialize(value, **kwargs)"
},
{
"docstring": "Convert value to object",
"name": "deserialize",
"signature": "def deserialize(value, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000865 | Implement the Python class `ObjectType` described below.
Class description:
Implement the ObjectType class.
Method signatures and docstrings:
- def serialize(value, **kwargs): Convert a value to a JSON serializable value
- def deserialize(value, **kwargs): Convert value to object | Implement the Python class `ObjectType` described below.
Class description:
Implement the ObjectType class.
Method signatures and docstrings:
- def serialize(value, **kwargs): Convert a value to a JSON serializable value
- def deserialize(value, **kwargs): Convert value to object
<|skeleton|>
class ObjectType:
... | e2ef4c7b56c4e7e06964fe6f64ae6c497ac31727 | <|skeleton|>
class ObjectType:
def serialize(value, **kwargs):
"""Convert a value to a JSON serializable value"""
<|body_0|>
def deserialize(value, **kwargs):
"""Convert value to object"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ObjectType:
def serialize(value, **kwargs):
"""Convert a value to a JSON serializable value"""
if value is not None:
if isinstance(value, dict):
return value
else:
return value.to_dict()
def deserialize(value, **kwargs):
"""C... | the_stack_v2_python_sparse | nio/properties/util/object_type.py | niolabs/nio | train | 5 | |
b5d82ea0e76bed4a3ff1776d22f9d61046db1387 | [
"@sync_performer\ndef succeed(dispatcher, intent):\n return intent\ndispatcher = lambda _: succeed\nresult = sync_perform(dispatcher, Effect('foo'))\nself.assertEqual(result, 'foo')",
"@sync_performer\ndef fail(dispatcher, intent):\n raise intent\ndispatcher = lambda _: fail\nself.assertThat(sync_perform(di... | <|body_start_0|>
@sync_performer
def succeed(dispatcher, intent):
return intent
dispatcher = lambda _: succeed
result = sync_perform(dispatcher, Effect('foo'))
self.assertEqual(result, 'foo')
<|end_body_0|>
<|body_start_1|>
@sync_performer
def fail(di... | Tests for :func:`sync_performer`. | SyncPerformerTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SyncPerformerTests:
"""Tests for :func:`sync_performer`."""
def test_success(self):
"""Return value of the performer becomes the result of the Effect."""
<|body_0|>
def test_failure(self):
"""Errors are caught and cause the effect to fail with the exception info.... | stack_v2_sparse_classes_36k_train_023481 | 4,009 | permissive | [
{
"docstring": "Return value of the performer becomes the result of the Effect.",
"name": "test_success",
"signature": "def test_success(self)"
},
{
"docstring": "Errors are caught and cause the effect to fail with the exception info.",
"name": "test_failure",
"signature": "def test_fail... | 6 | stack_v2_sparse_classes_30k_train_018314 | Implement the Python class `SyncPerformerTests` described below.
Class description:
Tests for :func:`sync_performer`.
Method signatures and docstrings:
- def test_success(self): Return value of the performer becomes the result of the Effect.
- def test_failure(self): Errors are caught and cause the effect to fail wit... | Implement the Python class `SyncPerformerTests` described below.
Class description:
Tests for :func:`sync_performer`.
Method signatures and docstrings:
- def test_success(self): Return value of the performer becomes the result of the Effect.
- def test_failure(self): Errors are caught and cause the effect to fail wit... | cd21859ad2babebcbf12fa372aef34b9cd25a10e | <|skeleton|>
class SyncPerformerTests:
"""Tests for :func:`sync_performer`."""
def test_success(self):
"""Return value of the performer becomes the result of the Effect."""
<|body_0|>
def test_failure(self):
"""Errors are caught and cause the effect to fail with the exception info.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SyncPerformerTests:
"""Tests for :func:`sync_performer`."""
def test_success(self):
"""Return value of the performer becomes the result of the Effect."""
@sync_performer
def succeed(dispatcher, intent):
return intent
dispatcher = lambda _: succeed
resul... | the_stack_v2_python_sparse | effect/test_sync.py | python-effect/effect | train | 289 |
3c69d82bf70110373a00967ffdbbbe65837f441f | [
"serializer = serializers_anio.CreateSingleCursoSerializer(data=request.data)\ndata = {}\nif serializer.is_valid(raise_exception=True):\n get_object_or_404(Anio.objects.filter(carrera__institucion_id=request.user.institucion.id), pk=serializer.validated_data['anio'].pk)\n try:\n instance = serializer.c... | <|body_start_0|>
serializer = serializers_anio.CreateSingleCursoSerializer(data=request.data)
data = {}
if serializer.is_valid(raise_exception=True):
get_object_or_404(Anio.objects.filter(carrera__institucion_id=request.user.institucion.id), pk=serializer.validated_data['anio'].pk)
... | CursoViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CursoViewSet:
def create(self, request):
"""Crear un curso"""
<|body_0|>
def destroy(self, request, pk=None):
"""Elimina un Curso"""
<|body_1|>
def update(self, request, pk=None):
"""Edita un curso"""
<|body_2|>
def get(self, request... | stack_v2_sparse_classes_36k_train_023482 | 9,416 | no_license | [
{
"docstring": "Crear un curso",
"name": "create",
"signature": "def create(self, request)"
},
{
"docstring": "Elimina un Curso",
"name": "destroy",
"signature": "def destroy(self, request, pk=None)"
},
{
"docstring": "Edita un curso",
"name": "update",
"signature": "def ... | 5 | stack_v2_sparse_classes_30k_train_000906 | Implement the Python class `CursoViewSet` described below.
Class description:
Implement the CursoViewSet class.
Method signatures and docstrings:
- def create(self, request): Crear un curso
- def destroy(self, request, pk=None): Elimina un Curso
- def update(self, request, pk=None): Edita un curso
- def get(self, req... | Implement the Python class `CursoViewSet` described below.
Class description:
Implement the CursoViewSet class.
Method signatures and docstrings:
- def create(self, request): Crear un curso
- def destroy(self, request, pk=None): Elimina un Curso
- def update(self, request, pk=None): Edita un curso
- def get(self, req... | be80b2d15f84a8eeba898e753efee348de6ce998 | <|skeleton|>
class CursoViewSet:
def create(self, request):
"""Crear un curso"""
<|body_0|>
def destroy(self, request, pk=None):
"""Elimina un Curso"""
<|body_1|>
def update(self, request, pk=None):
"""Edita un curso"""
<|body_2|>
def get(self, request... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CursoViewSet:
def create(self, request):
"""Crear un curso"""
serializer = serializers_anio.CreateSingleCursoSerializer(data=request.data)
data = {}
if serializer.is_valid(raise_exception=True):
get_object_or_404(Anio.objects.filter(carrera__institucion_id=request.u... | the_stack_v2_python_sparse | curricula/api/views/anio.py | Clear-Education/ontrack_backend | train | 1 | |
cc9753df9c090889a48e633164808dbba243702c | [
"skeinforge_profile.addListsToCraftTypeRepository('skeinforge_application.skeinforge_plugins.craft_plugins.temperature.html', self)\nself.fileNameInput = settings.FileNameInput().getFromFileName(fabmetheus_interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Temperature', self, '')\nself.activateTemperat... | <|body_start_0|>
skeinforge_profile.addListsToCraftTypeRepository('skeinforge_application.skeinforge_plugins.craft_plugins.temperature.html', self)
self.fileNameInput = settings.FileNameInput().getFromFileName(fabmetheus_interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Temperature', self,... | A class to handle the temperature settings. | TemperatureRepository | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TemperatureRepository:
"""A class to handle the temperature settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
<|body_0|>
def execute(self):
"""Temperature button has been clicked."""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k_train_023483 | 9,160 | no_license | [
{
"docstring": "Set the default settings, execute title & settings fileName.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Temperature button has been clicked.",
"name": "execute",
"signature": "def execute(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015115 | Implement the Python class `TemperatureRepository` described below.
Class description:
A class to handle the temperature settings.
Method signatures and docstrings:
- def __init__(self): Set the default settings, execute title & settings fileName.
- def execute(self): Temperature button has been clicked. | Implement the Python class `TemperatureRepository` described below.
Class description:
A class to handle the temperature settings.
Method signatures and docstrings:
- def __init__(self): Set the default settings, execute title & settings fileName.
- def execute(self): Temperature button has been clicked.
<|skeleton|... | c1b00a76f1550df2cbb457248205159e51fd4308 | <|skeleton|>
class TemperatureRepository:
"""A class to handle the temperature settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
<|body_0|>
def execute(self):
"""Temperature button has been clicked."""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TemperatureRepository:
"""A class to handle the temperature settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
skeinforge_profile.addListsToCraftTypeRepository('skeinforge_application.skeinforge_plugins.craft_plugins.temperature.html', self... | the_stack_v2_python_sparse | skeinforge_application/skeinforge_plugins/craft_plugins/temperature.py | amsler/skeinforge | train | 10 |
90b02c7a59df10a5065a06330612e332db064d74 | [
"with PROCESSING_GO_PATH.open() as file:\n j = json.load(file)\nreturn j['skip']",
"rv = {'name': external_entry['name']}\ndescription = external_entry.get('description')\nif description:\n rv['description'] = description\nhomepages = [homepage for homepage in external_entry.get('generic_urls', []) if not a... | <|body_start_0|>
with PROCESSING_GO_PATH.open() as file:
j = json.load(file)
return j['skip']
<|end_body_0|>
<|body_start_1|>
rv = {'name': external_entry['name']}
description = external_entry.get('description')
if description:
rv['description'] = descrip... | An aligner for the Gene Ontology (GO) registry. | GoAligner | [
"MIT",
"CC0-1.0",
"CC-PDDC",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoAligner:
"""An aligner for the Gene Ontology (GO) registry."""
def get_skip(self) -> Mapping[str, str]:
"""Get the skipped GO identifiers."""
<|body_0|>
def prepare_external(self, external_id: str, external_entry: Mapping[str, Any]) -> Dict[str, Any]:
"""Prepar... | stack_v2_sparse_classes_36k_train_023484 | 2,544 | permissive | [
{
"docstring": "Get the skipped GO identifiers.",
"name": "get_skip",
"signature": "def get_skip(self) -> Mapping[str, str]"
},
{
"docstring": "Prepare GO data to be added to the bioregistry for each GO registry entry.",
"name": "prepare_external",
"signature": "def prepare_external(self... | 2 | null | Implement the Python class `GoAligner` described below.
Class description:
An aligner for the Gene Ontology (GO) registry.
Method signatures and docstrings:
- def get_skip(self) -> Mapping[str, str]: Get the skipped GO identifiers.
- def prepare_external(self, external_id: str, external_entry: Mapping[str, Any]) -> D... | Implement the Python class `GoAligner` described below.
Class description:
An aligner for the Gene Ontology (GO) registry.
Method signatures and docstrings:
- def get_skip(self) -> Mapping[str, str]: Get the skipped GO identifiers.
- def prepare_external(self, external_id: str, external_entry: Mapping[str, Any]) -> D... | a05af7e42f60109f01133e3072bb673423b74dd3 | <|skeleton|>
class GoAligner:
"""An aligner for the Gene Ontology (GO) registry."""
def get_skip(self) -> Mapping[str, str]:
"""Get the skipped GO identifiers."""
<|body_0|>
def prepare_external(self, external_id: str, external_entry: Mapping[str, Any]) -> Dict[str, Any]:
"""Prepar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GoAligner:
"""An aligner for the Gene Ontology (GO) registry."""
def get_skip(self) -> Mapping[str, str]:
"""Get the skipped GO identifiers."""
with PROCESSING_GO_PATH.open() as file:
j = json.load(file)
return j['skip']
def prepare_external(self, external_id: str... | the_stack_v2_python_sparse | src/bioregistry/align/go.py | biopragmatics/bioregistry | train | 77 |
da04639a85eacda4fe96f3646033f00cf0c74b84 | [
"super(CtrTrainerCallback, self).__init__()\nself.sieve_board = pd.DataFrame(columns=['selected_feature_pairs', 'score'])\nself.selected_pairs = list()\nlogging.info('init autogate s2 trainer callback')",
"super().before_train(logs)\n'Be called before the training process.'\nhpo_result = FileOps.load_pickle(FileO... | <|body_start_0|>
super(CtrTrainerCallback, self).__init__()
self.sieve_board = pd.DataFrame(columns=['selected_feature_pairs', 'score'])
self.selected_pairs = list()
logging.info('init autogate s2 trainer callback')
<|end_body_0|>
<|body_start_1|>
super().before_train(logs)
... | AutoGateS2TrainerCallback module. | AutoGateS2TrainerCallback | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutoGateS2TrainerCallback:
"""AutoGateS2TrainerCallback module."""
def __init__(self):
"""Construct AutoGateS2TrainerCallback class."""
<|body_0|>
def before_train(self, logs=None):
"""Call before_train of the managed callbacks."""
<|body_1|>
def aft... | stack_v2_sparse_classes_36k_train_023485 | 3,088 | permissive | [
{
"docstring": "Construct AutoGateS2TrainerCallback class.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Call before_train of the managed callbacks.",
"name": "before_train",
"signature": "def before_train(self, logs=None)"
},
{
"docstring": "Call aft... | 3 | stack_v2_sparse_classes_30k_train_013779 | Implement the Python class `AutoGateS2TrainerCallback` described below.
Class description:
AutoGateS2TrainerCallback module.
Method signatures and docstrings:
- def __init__(self): Construct AutoGateS2TrainerCallback class.
- def before_train(self, logs=None): Call before_train of the managed callbacks.
- def after_t... | Implement the Python class `AutoGateS2TrainerCallback` described below.
Class description:
AutoGateS2TrainerCallback module.
Method signatures and docstrings:
- def __init__(self): Construct AutoGateS2TrainerCallback class.
- def before_train(self, logs=None): Call before_train of the managed callbacks.
- def after_t... | 12e37a1991eb6771a2999fe0a46ddda920c47948 | <|skeleton|>
class AutoGateS2TrainerCallback:
"""AutoGateS2TrainerCallback module."""
def __init__(self):
"""Construct AutoGateS2TrainerCallback class."""
<|body_0|>
def before_train(self, logs=None):
"""Call before_train of the managed callbacks."""
<|body_1|>
def aft... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AutoGateS2TrainerCallback:
"""AutoGateS2TrainerCallback module."""
def __init__(self):
"""Construct AutoGateS2TrainerCallback class."""
super(CtrTrainerCallback, self).__init__()
self.sieve_board = pd.DataFrame(columns=['selected_feature_pairs', 'score'])
self.selected_pai... | the_stack_v2_python_sparse | vega/algorithms/nas/fis/autogate_s2_trainer_callback.py | huawei-noah/vega | train | 850 |
41e8396ba1c06a3b4a247e21b820dd317eb59f3a | [
"self.headerF = glob.glob(os.path.join(self.dataPath, '*.hdr'))\nself.dataF = glob.glob(os.path.join(self.dataPath, '*.ascii'))\nself.dataByteOffset = 0\nself.dataByteSize = 4",
"options = self.parseGetDataKeywords(kwargs)\ndSamples = options['endSample'] - options['startSample'] + 1\ndata = {}\nfor chan in optio... | <|body_start_0|>
self.headerF = glob.glob(os.path.join(self.dataPath, '*.hdr'))
self.dataF = glob.glob(os.path.join(self.dataPath, '*.ascii'))
self.dataByteOffset = 0
self.dataByteSize = 4
<|end_body_0|>
<|body_start_1|>
options = self.parseGetDataKeywords(kwargs)
dSampl... | Data reader for ascii formatted data The ASCII data reader reads ascii data files and internally formatted header files. No further scaling is applied to the data values in either getUnscaledSamples or getPhysicalSamples. All the data is assumed to be in the correct units. In fact, if the data does not have to be calib... | TimeReaderAscii | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeReaderAscii:
"""Data reader for ascii formatted data The ASCII data reader reads ascii data files and internally formatted header files. No further scaling is applied to the data values in either getUnscaledSamples or getPhysicalSamples. All the data is assumed to be in the correct units. In ... | stack_v2_sparse_classes_36k_train_023486 | 5,926 | permissive | [
{
"docstring": "Set data reader parameters This will vary for the different data formats. By default, setup for the internal data format.",
"name": "setParameters",
"signature": "def setParameters(self) -> None"
},
{
"docstring": "Get raw data from ascii data file This function simply reads the ... | 3 | null | Implement the Python class `TimeReaderAscii` described below.
Class description:
Data reader for ascii formatted data The ASCII data reader reads ascii data files and internally formatted header files. No further scaling is applied to the data values in either getUnscaledSamples or getPhysicalSamples. All the data is ... | Implement the Python class `TimeReaderAscii` described below.
Class description:
Data reader for ascii formatted data The ASCII data reader reads ascii data files and internally formatted header files. No further scaling is applied to the data values in either getUnscaledSamples or getPhysicalSamples. All the data is ... | a93040521fd6506929a59c363ee58b7ca073bac1 | <|skeleton|>
class TimeReaderAscii:
"""Data reader for ascii formatted data The ASCII data reader reads ascii data files and internally formatted header files. No further scaling is applied to the data values in either getUnscaledSamples or getPhysicalSamples. All the data is assumed to be in the correct units. In ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TimeReaderAscii:
"""Data reader for ascii formatted data The ASCII data reader reads ascii data files and internally formatted header files. No further scaling is applied to the data values in either getUnscaledSamples or getPhysicalSamples. All the data is assumed to be in the correct units. In fact, if the ... | the_stack_v2_python_sparse | resistics/time/reader_ascii.py | Nishikinor/resistics | train | 0 |
59551646e073634dc008c85098da7705f2741d83 | [
"counts = {}\nfor x in nums:\n counts[x] = counts.setdefault(x, 0) + 1\n if counts[x] > len(nums) / 2:\n return x",
"majority, count = (None, 0)\nfor x in nums:\n if count == 0:\n majority = x\n count = 1\n elif x == majority:\n count += 1\n else:\n count -= 1\nre... | <|body_start_0|>
counts = {}
for x in nums:
counts[x] = counts.setdefault(x, 0) + 1
if counts[x] > len(nums) / 2:
return x
<|end_body_0|>
<|body_start_1|>
majority, count = (None, 0)
for x in nums:
if count == 0:
majori... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def majorityElement(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def majorityElement(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
counts = {}
for x in nums:
... | stack_v2_sparse_classes_36k_train_023487 | 1,029 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "majorityElement",
"signature": "def majorityElement(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "majorityElement",
"signature": "def majorityElement(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014013 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def majorityElement(self, nums): :type nums: List[int] :rtype: int
- def majorityElement(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 majorityElement(self, nums): :type nums: List[int] :rtype: int
- def majorityElement(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def maj... | 18ed31a3edf20a3e5a0b7a0b56acca5b98939693 | <|skeleton|>
class Solution:
def majorityElement(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def majorityElement(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def majorityElement(self, nums):
""":type nums: List[int] :rtype: int"""
counts = {}
for x in nums:
counts[x] = counts.setdefault(x, 0) + 1
if counts[x] > len(nums) / 2:
return x
def majorityElement(self, nums):
""":type nu... | the_stack_v2_python_sparse | exercises/array/majority_element.py | nahgnaw/data-structure | train | 0 | |
457696dbf9305fb2ccb0ba48472035f52276cab8 | [
"assert isinstance(node, nuke.Node), 'Expect a node, got: {}'.format(node)\nknob_name = cls.knob_name\nknobs = node.knobs()\nif knob_name not in knobs:\n n = node.input(1)\n raw_hash = cls.hash(n)\n k = nuke.Int_Knob(knob_name)\n k.setValue(raw_hash)\n node.addKnob(k)\nelse:\n k = knobs[knob_name]... | <|body_start_0|>
assert isinstance(node, nuke.Node), 'Expect a node, got: {}'.format(node)
knob_name = cls.knob_name
knobs = node.knobs()
if knob_name not in knobs:
n = node.input(1)
raw_hash = cls.hash(n)
k = nuke.Int_Knob(knob_name)
k.set... | Modified switch node for precomp. | __PrecompSwitch | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class __PrecompSwitch:
"""Modified switch node for precomp."""
def init(cls, node):
"""Add necessary knobs."""
<|body_0|>
def hash(cls, node):
"""Node hash result of @node up to upstream start."""
<|body_1|>
def get_which(cls, node):
"""Return auto... | stack_v2_sparse_classes_36k_train_023488 | 10,392 | no_license | [
{
"docstring": "Add necessary knobs.",
"name": "init",
"signature": "def init(cls, node)"
},
{
"docstring": "Node hash result of @node up to upstream start.",
"name": "hash",
"signature": "def hash(cls, node)"
},
{
"docstring": "Return auto input choice for @node.",
"name": "... | 3 | stack_v2_sparse_classes_30k_train_011606 | Implement the Python class `__PrecompSwitch` described below.
Class description:
Modified switch node for precomp.
Method signatures and docstrings:
- def init(cls, node): Add necessary knobs.
- def hash(cls, node): Node hash result of @node up to upstream start.
- def get_which(cls, node): Return auto input choice f... | Implement the Python class `__PrecompSwitch` described below.
Class description:
Modified switch node for precomp.
Method signatures and docstrings:
- def init(cls, node): Add necessary knobs.
- def hash(cls, node): Node hash result of @node up to upstream start.
- def get_which(cls, node): Return auto input choice f... | e346c61db83397da1a8d80ed3a0e33aa7f677533 | <|skeleton|>
class __PrecompSwitch:
"""Modified switch node for precomp."""
def init(cls, node):
"""Add necessary knobs."""
<|body_0|>
def hash(cls, node):
"""Node hash result of @node up to upstream start."""
<|body_1|>
def get_which(cls, node):
"""Return auto... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class __PrecompSwitch:
"""Modified switch node for precomp."""
def init(cls, node):
"""Add necessary knobs."""
assert isinstance(node, nuke.Node), 'Expect a node, got: {}'.format(node)
knob_name = cls.knob_name
knobs = node.knobs()
if knob_name not in knobs:
... | the_stack_v2_python_sparse | lib/comp/precomp.py | tws0002/Nuke-2 | train | 1 |
e5c0b9f73e38ff3c0cd7262782cc558afc8c4545 | [
"password1 = self.cleaned_data.get('password1')\npassword2 = self.cleaned_data.get('password2')\nif password1 and password2 and (password1 != password2):\n raise forms.ValidationError(\"The passwords don't match!\")\nreturn password2",
"member = super(MemberCreationForm, self).save(commit=False)\nmember.set_pa... | <|body_start_0|>
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and (password1 != password2):
raise forms.ValidationError("The passwords don't match!")
return password2
<|end_body_0|>
<|body_start_1|>
... | Admin form for creating new users. Includes vital fields. | MemberCreationForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MemberCreationForm:
"""Admin form for creating new users. Includes vital fields."""
def clean_password2(self):
"""Checks for matching password and password confirmation"""
<|body_0|>
def save(self, commit=True):
"""Save the hashed passwords"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_023489 | 1,417 | no_license | [
{
"docstring": "Checks for matching password and password confirmation",
"name": "clean_password2",
"signature": "def clean_password2(self)"
},
{
"docstring": "Save the hashed passwords",
"name": "save",
"signature": "def save(self, commit=True)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015347 | Implement the Python class `MemberCreationForm` described below.
Class description:
Admin form for creating new users. Includes vital fields.
Method signatures and docstrings:
- def clean_password2(self): Checks for matching password and password confirmation
- def save(self, commit=True): Save the hashed passwords | Implement the Python class `MemberCreationForm` described below.
Class description:
Admin form for creating new users. Includes vital fields.
Method signatures and docstrings:
- def clean_password2(self): Checks for matching password and password confirmation
- def save(self, commit=True): Save the hashed passwords
... | e5d9767c2dabd969d31d39fc74fe84cc2fc4f45d | <|skeleton|>
class MemberCreationForm:
"""Admin form for creating new users. Includes vital fields."""
def clean_password2(self):
"""Checks for matching password and password confirmation"""
<|body_0|>
def save(self, commit=True):
"""Save the hashed passwords"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MemberCreationForm:
"""Admin form for creating new users. Includes vital fields."""
def clean_password2(self):
"""Checks for matching password and password confirmation"""
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if pass... | the_stack_v2_python_sparse | team/forms.py | ethanperez/lance | train | 0 |
ad9e716393b8df9ef1396fb0b04c3bcb39c6b415 | [
"jobqueue = JobQueue.query.filter_by(name=g.json['name']).first()\nif jobqueue:\n return (jsonify(error='Job queue %s already exists' % g.json['name']), CONFLICT)\njobqueue = JobQueue(**g.json)\ndb.session.add(jobqueue)\ndb.session.flush()\njobqueue.fullpath = jobqueue.path()\ndb.session.add(jobqueue)\ndb.sessio... | <|body_start_0|>
jobqueue = JobQueue.query.filter_by(name=g.json['name']).first()
if jobqueue:
return (jsonify(error='Job queue %s already exists' % g.json['name']), CONFLICT)
jobqueue = JobQueue(**g.json)
db.session.add(jobqueue)
db.session.flush()
jobqueue.f... | JobQueueIndexAPI | [
"BSD-3-Clause",
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JobQueueIndexAPI:
def post(self):
"""A ``POST`` to this endpoint will create a new job queue. .. http:post:: /api/v1/jobqueues/ HTTP/1.1 **Request** .. sourcecode:: http POST /api/v1/jobqueues/ HTTP/1.1 Accept: application/json { "name": "Test Queue" } **Response** .. sourcecode:: http H... | stack_v2_sparse_classes_36k_train_023490 | 11,392 | permissive | [
{
"docstring": "A ``POST`` to this endpoint will create a new job queue. .. http:post:: /api/v1/jobqueues/ HTTP/1.1 **Request** .. sourcecode:: http POST /api/v1/jobqueues/ HTTP/1.1 Accept: application/json { \"name\": \"Test Queue\" } **Response** .. sourcecode:: http HTTP/1.1 201 CREATED Content-Type: applica... | 2 | stack_v2_sparse_classes_30k_train_011716 | Implement the Python class `JobQueueIndexAPI` described below.
Class description:
Implement the JobQueueIndexAPI class.
Method signatures and docstrings:
- def post(self): A ``POST`` to this endpoint will create a new job queue. .. http:post:: /api/v1/jobqueues/ HTTP/1.1 **Request** .. sourcecode:: http POST /api/v1/... | Implement the Python class `JobQueueIndexAPI` described below.
Class description:
Implement the JobQueueIndexAPI class.
Method signatures and docstrings:
- def post(self): A ``POST`` to this endpoint will create a new job queue. .. http:post:: /api/v1/jobqueues/ HTTP/1.1 **Request** .. sourcecode:: http POST /api/v1/... | ea04bbcb807eb669415c569417b4b1b68e75d29d | <|skeleton|>
class JobQueueIndexAPI:
def post(self):
"""A ``POST`` to this endpoint will create a new job queue. .. http:post:: /api/v1/jobqueues/ HTTP/1.1 **Request** .. sourcecode:: http POST /api/v1/jobqueues/ HTTP/1.1 Accept: application/json { "name": "Test Queue" } **Response** .. sourcecode:: http H... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JobQueueIndexAPI:
def post(self):
"""A ``POST`` to this endpoint will create a new job queue. .. http:post:: /api/v1/jobqueues/ HTTP/1.1 **Request** .. sourcecode:: http POST /api/v1/jobqueues/ HTTP/1.1 Accept: application/json { "name": "Test Queue" } **Response** .. sourcecode:: http HTTP/1.1 201 CR... | the_stack_v2_python_sparse | pyfarm/master/api/jobqueues.py | pyfarm/pyfarm-master | train | 2 | |
b8c80844b883a41b90f6a6a0804e6319e8381189 | [
"Thread.__init__(self, name=name, daemon=daemon)\nself.study_name = study_name\nself.model_name = metric\nself.runs = runs\nself.budget = budget\nself.num_suggestions = num_suggestions\nself.dataset = dataset\nself.algorithm = Algorithm.instance(alg_name)\nself.space = self.__space(study_name)",
"data = Parameter... | <|body_start_0|>
Thread.__init__(self, name=name, daemon=daemon)
self.study_name = study_name
self.model_name = metric
self.runs = runs
self.budget = budget
self.num_suggestions = num_suggestions
self.dataset = dataset
self.algorithm = Algorithm.instance(a... | Suggestion | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Suggestion:
def __init__(self, study_name, alg_name, metric, dataset, runs=5, budget=30, num_suggestions=10, name=None, daemon=True):
"""Initialize the suggestion worker. Args: :param study_name: name of the study :param alg_name: name of the algorithm :param metric: name of the model to... | stack_v2_sparse_classes_36k_train_023491 | 6,300 | no_license | [
{
"docstring": "Initialize the suggestion worker. Args: :param study_name: name of the study :param alg_name: name of the algorithm :param metric: name of the model to use as a metric :param dataset: name of the dataset to use with the model :param runs: how many times the algorithm is launched :param budget: b... | 4 | stack_v2_sparse_classes_30k_test_000456 | Implement the Python class `Suggestion` described below.
Class description:
Implement the Suggestion class.
Method signatures and docstrings:
- def __init__(self, study_name, alg_name, metric, dataset, runs=5, budget=30, num_suggestions=10, name=None, daemon=True): Initialize the suggestion worker. Args: :param study... | Implement the Python class `Suggestion` described below.
Class description:
Implement the Suggestion class.
Method signatures and docstrings:
- def __init__(self, study_name, alg_name, metric, dataset, runs=5, budget=30, num_suggestions=10, name=None, daemon=True): Initialize the suggestion worker. Args: :param study... | 27f861c09615aedfd96cffdebf7d9653f72b4d7b | <|skeleton|>
class Suggestion:
def __init__(self, study_name, alg_name, metric, dataset, runs=5, budget=30, num_suggestions=10, name=None, daemon=True):
"""Initialize the suggestion worker. Args: :param study_name: name of the study :param alg_name: name of the algorithm :param metric: name of the model to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Suggestion:
def __init__(self, study_name, alg_name, metric, dataset, runs=5, budget=30, num_suggestions=10, name=None, daemon=True):
"""Initialize the suggestion worker. Args: :param study_name: name of the study :param alg_name: name of the algorithm :param metric: name of the model to use as a metr... | the_stack_v2_python_sparse | API/tasks.py | AndreaCorsini1/Ahmet | train | 1 | |
bed4ddab30c502587b3b6bd89274bfc8ff1e3a9f | [
"forest = RandomForestClassifier(n_estimators=num_trees)\nprint('Fitting random forest to training data....')\nforest = forest.fit(training_data_vecs, train_labels[col_name])\nreturn forest",
"result = model.predict(test_vector)\noutput = pd.DataFrame(data={'id': test_data['id'], test_col_name: result})\noutput.t... | <|body_start_0|>
forest = RandomForestClassifier(n_estimators=num_trees)
print('Fitting random forest to training data....')
forest = forest.fit(training_data_vecs, train_labels[col_name])
return forest
<|end_body_0|>
<|body_start_1|>
result = model.predict(test_vector)
... | RunRandomForest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunRandomForest:
def train_random_forest(self, training_data_vecs, train_labels, col_name, num_trees):
"""Return random forest model"""
<|body_0|>
def predict_random_forest(self, model, test_vector, test_data, test_id_col, test_col_name, output_name):
"""Return outpu... | stack_v2_sparse_classes_36k_train_023492 | 806 | no_license | [
{
"docstring": "Return random forest model",
"name": "train_random_forest",
"signature": "def train_random_forest(self, training_data_vecs, train_labels, col_name, num_trees)"
},
{
"docstring": "Return output of random forest prediction and save to csv",
"name": "predict_random_forest",
... | 2 | stack_v2_sparse_classes_30k_val_000762 | Implement the Python class `RunRandomForest` described below.
Class description:
Implement the RunRandomForest class.
Method signatures and docstrings:
- def train_random_forest(self, training_data_vecs, train_labels, col_name, num_trees): Return random forest model
- def predict_random_forest(self, model, test_vecto... | Implement the Python class `RunRandomForest` described below.
Class description:
Implement the RunRandomForest class.
Method signatures and docstrings:
- def train_random_forest(self, training_data_vecs, train_labels, col_name, num_trees): Return random forest model
- def predict_random_forest(self, model, test_vecto... | 141fa19637bd34854fe07b670a6103f69c085700 | <|skeleton|>
class RunRandomForest:
def train_random_forest(self, training_data_vecs, train_labels, col_name, num_trees):
"""Return random forest model"""
<|body_0|>
def predict_random_forest(self, model, test_vector, test_data, test_id_col, test_col_name, output_name):
"""Return outpu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RunRandomForest:
def train_random_forest(self, training_data_vecs, train_labels, col_name, num_trees):
"""Return random forest model"""
forest = RandomForestClassifier(n_estimators=num_trees)
print('Fitting random forest to training data....')
forest = forest.fit(training_data_... | the_stack_v2_python_sparse | RunRandomForest.py | ianovski/customer-review-sentiment | train | 0 | |
17d34a929989b4b488eba8e8a7f08a996b3ae995 | [
"assert training_percent + validation_percent <= 1.0, 'Training and validation percentages more than 100 percent'\nself.train_examples = []\nself.validation_examples = []\nself.test_examples = []\nself.training_percent = training_percent\nself.validation_percent = validation_percent",
"placement_rand = random.Ran... | <|body_start_0|>
assert training_percent + validation_percent <= 1.0, 'Training and validation percentages more than 100 percent'
self.train_examples = []
self.validation_examples = []
self.test_examples = []
self.training_percent = training_percent
self.validation_percen... | Manage a grouping of Training Examples. This is meant to make it easy to split a bunch of training examples into three types of data: o Training Data -- These are the data used to do the actual training of the network. o Validation Data -- These data are used to validate the network while training. They provide an inde... | ExampleManager | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExampleManager:
"""Manage a grouping of Training Examples. This is meant to make it easy to split a bunch of training examples into three types of data: o Training Data -- These are the data used to do the actual training of the network. o Validation Data -- These data are used to validate the ne... | stack_v2_sparse_classes_36k_train_023493 | 3,043 | permissive | [
{
"docstring": "Initialize the manager with the training examples. Arguments: o training_percent - The percentage of the training examples that should be used for training the network. o validation_percent - Percent of training examples for validating a network during training. Attributes: o train_examples - A ... | 2 | null | Implement the Python class `ExampleManager` described below.
Class description:
Manage a grouping of Training Examples. This is meant to make it easy to split a bunch of training examples into three types of data: o Training Data -- These are the data used to do the actual training of the network. o Validation Data --... | Implement the Python class `ExampleManager` described below.
Class description:
Manage a grouping of Training Examples. This is meant to make it easy to split a bunch of training examples into three types of data: o Training Data -- These are the data used to do the actual training of the network. o Validation Data --... | 1d9a8e84a8572809ee3260ede44290e14de3bdd1 | <|skeleton|>
class ExampleManager:
"""Manage a grouping of Training Examples. This is meant to make it easy to split a bunch of training examples into three types of data: o Training Data -- These are the data used to do the actual training of the network. o Validation Data -- These data are used to validate the ne... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExampleManager:
"""Manage a grouping of Training Examples. This is meant to make it easy to split a bunch of training examples into three types of data: o Training Data -- These are the data used to do the actual training of the network. o Validation Data -- These data are used to validate the network while t... | the_stack_v2_python_sparse | bin/last_wrapper/Bio/NeuralNetwork/Training.py | LyonsLab/coge | train | 41 |
40cc93c73c7358a03e501acc0f7007eb0f1a487d | [
"family, face, font = self.match(fontStyle, mode)\nbitmapFont = wxBitmapFont(fontStyle, font=font)\nself.addFont(fontStyle, bitmapFont)\nreturn bitmapFont",
"family, face = self.FAMILYMAPPING.get('SERIF')\nif fontStyle and fontStyle.family:\n for specifier in fontStyle.family:\n specifier = specifier.lo... | <|body_start_0|>
family, face, font = self.match(fontStyle, mode)
bitmapFont = wxBitmapFont(fontStyle, font=font)
self.addFont(fontStyle, bitmapFont)
return bitmapFont
<|end_body_0|>
<|body_start_1|>
family, face = self.FAMILYMAPPING.get('SERIF')
if fontStyle and fontSty... | Singleton for creating new wxBitmapFonts Note: This provider MUST NOT be used under a non-wxPython context under Linux/GTK, as it WILL cause segmentation faults when the wxPython system tries to access the font list from the wxPython application. | _wxFontProvider | [
"MIT",
"GPL-1.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-copyleft",
"LGPL-2.1-or-later",
"GPL-3.0-only",
"LGPL-2.0-or-later",
"GPL-3.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _wxFontProvider:
"""Singleton for creating new wxBitmapFonts Note: This provider MUST NOT be used under a non-wxPython context under Linux/GTK, as it WILL cause segmentation faults when the wxPython system tries to access the font list from the wxPython application."""
def create(self, fontS... | stack_v2_sparse_classes_36k_train_023494 | 11,262 | permissive | [
{
"docstring": "Create a new font for the given fontStyle and mode",
"name": "create",
"signature": "def create(self, fontStyle, mode=None)"
},
{
"docstring": "Attempt to find matching wxFont for our fontstyle This is a really stupid implementation, it just takes the first font that includes the... | 4 | stack_v2_sparse_classes_30k_train_010264 | Implement the Python class `_wxFontProvider` described below.
Class description:
Singleton for creating new wxBitmapFonts Note: This provider MUST NOT be used under a non-wxPython context under Linux/GTK, as it WILL cause segmentation faults when the wxPython system tries to access the font list from the wxPython appl... | Implement the Python class `_wxFontProvider` described below.
Class description:
Singleton for creating new wxBitmapFonts Note: This provider MUST NOT be used under a non-wxPython context under Linux/GTK, as it WILL cause segmentation faults when the wxPython system tries to access the font list from the wxPython appl... | 7f600ad153270feff12aa7aa86d7ed0a49ebc71c | <|skeleton|>
class _wxFontProvider:
"""Singleton for creating new wxBitmapFonts Note: This provider MUST NOT be used under a non-wxPython context under Linux/GTK, as it WILL cause segmentation faults when the wxPython system tries to access the font list from the wxPython application."""
def create(self, fontS... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _wxFontProvider:
"""Singleton for creating new wxBitmapFonts Note: This provider MUST NOT be used under a non-wxPython context under Linux/GTK, as it WILL cause segmentation faults when the wxPython system tries to access the font list from the wxPython application."""
def create(self, fontStyle, mode=No... | the_stack_v2_python_sparse | pythonAnimations/pyOpenGLChess/engineDirectory/oglc-env/lib/python2.7/site-packages/OpenGLContext/scenegraph/text/wxfont.py | alexus37/AugmentedRealityChess | train | 1 |
e9ff5459df5adb326802b73e7a2c6cde500e1ac0 | [
"super().__init__()\nself._tokenizer = tokenizer\nself._batch_size = batch_size\nself._timesteps = timesteps\nself._subset = subset\nself._shuffle_data = shuffle_data\nself._data_dir = data_dir\nself._repeat = repeat\nself._debug = debug\nself._dataset = None",
"if not self._dataset:\n raw_dataset = RawDataset... | <|body_start_0|>
super().__init__()
self._tokenizer = tokenizer
self._batch_size = batch_size
self._timesteps = timesteps
self._subset = subset
self._shuffle_data = shuffle_data
self._data_dir = data_dir
self._repeat = repeat
self._debug = debug
... | Tokenized dataset for wikitext-103. | WikitextDataset | [
"Apache-2.0",
"CC-BY-SA-4.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WikitextDataset:
"""Tokenized dataset for wikitext-103."""
def __init__(self, tokenizer: tokenizers.Tokenizer, batch_size: int=1, timesteps: int=128, subset: str='train', shuffle_data: bool=True, data_dir: str=None, repeat: bool=False, debug: bool=False, **kwargs):
"""Constructor. Ar... | stack_v2_sparse_classes_36k_train_023495 | 7,525 | permissive | [
{
"docstring": "Constructor. Args: tokenizer: a tokenizer for text data. batch_size: number of sequences to put into a batch. timesteps: length of the sequences. subset: which subset to load, one of {\"train\", \"valid\", \"test\"}. shuffle_data: if set to True the data will be randomly shuffled. data_dir: if p... | 3 | null | Implement the Python class `WikitextDataset` described below.
Class description:
Tokenized dataset for wikitext-103.
Method signatures and docstrings:
- def __init__(self, tokenizer: tokenizers.Tokenizer, batch_size: int=1, timesteps: int=128, subset: str='train', shuffle_data: bool=True, data_dir: str=None, repeat: ... | Implement the Python class `WikitextDataset` described below.
Class description:
Tokenized dataset for wikitext-103.
Method signatures and docstrings:
- def __init__(self, tokenizer: tokenizers.Tokenizer, batch_size: int=1, timesteps: int=128, subset: str='train', shuffle_data: bool=True, data_dir: str=None, repeat: ... | a6ef8053380d6aa19aaae14b93f013ae9762d057 | <|skeleton|>
class WikitextDataset:
"""Tokenized dataset for wikitext-103."""
def __init__(self, tokenizer: tokenizers.Tokenizer, batch_size: int=1, timesteps: int=128, subset: str='train', shuffle_data: bool=True, data_dir: str=None, repeat: bool=False, debug: bool=False, **kwargs):
"""Constructor. Ar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WikitextDataset:
"""Tokenized dataset for wikitext-103."""
def __init__(self, tokenizer: tokenizers.Tokenizer, batch_size: int=1, timesteps: int=128, subset: str='train', shuffle_data: bool=True, data_dir: str=None, repeat: bool=False, debug: bool=False, **kwargs):
"""Constructor. Args: tokenizer... | the_stack_v2_python_sparse | wikigraphs/wikigraphs/data/wikitext.py | sethuramanio/deepmind-research | train | 1 |
9460e0b622315a90436fe0d416efbe32e6443515 | [
"from collections import deque\nself.queue = deque()\nself.cache = set()",
"if timestamp > 10:\n while self.queue and timestamp - self.queue[0][1] >= 10:\n self.cache.remove(self.queue.popleft()[0])\nif message in self.cache:\n return False\nself.cache.add(message)\nself.queue.append((message, timest... | <|body_start_0|>
from collections import deque
self.queue = deque()
self.cache = set()
<|end_body_0|>
<|body_start_1|>
if timestamp > 10:
while self.queue and timestamp - self.queue[0][1] >= 10:
self.cache.remove(self.queue.popleft()[0])
if message in... | Logger | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Logger:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def shouldPrintMessage(self, timestamp, message):
"""Returns true if the message should be printed in the given timestamp, otherwise returns false. If this method returns false, the mes... | stack_v2_sparse_classes_36k_train_023496 | 1,808 | permissive | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Returns true if the message should be printed in the given timestamp, otherwise returns false. If this method returns false, the message will not be printed. The timest... | 2 | null | Implement the Python class `Logger` described below.
Class description:
Implement the Logger class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def shouldPrintMessage(self, timestamp, message): Returns true if the message should be printed in the given timestamp, oth... | Implement the Python class `Logger` described below.
Class description:
Implement the Logger class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def shouldPrintMessage(self, timestamp, message): Returns true if the message should be printed in the given timestamp, oth... | fd4cf122cfd4920f3bd8dce40ba7487a170a1b57 | <|skeleton|>
class Logger:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def shouldPrintMessage(self, timestamp, message):
"""Returns true if the message should be printed in the given timestamp, otherwise returns false. If this method returns false, the mes... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Logger:
def __init__(self):
"""Initialize your data structure here."""
from collections import deque
self.queue = deque()
self.cache = set()
def shouldPrintMessage(self, timestamp, message):
"""Returns true if the message should be printed in the given timestamp, o... | the_stack_v2_python_sparse | 0359_Logger_Rate_Limiter.py | coldmanck/leetcode-python | train | 6 | |
14dbac7d934140293822ea5317f8a3c8ebf086a8 | [
"self.high_time = None\nself.short_press_time = float(dev_cfg.get('Short_Press-Threshold', 0))\nself.long_press_time = float(dev_cfg.get('Long_Press-Threshold', 0))\ntry:\n self.state_when_pressed = GPIO.LOW if dev_cfg['Btn_Pressed_State'] == 'LOW' else GPIO.HIGH\nexcept KeyError:\n self.state_when_pressed = ... | <|body_start_0|>
self.high_time = None
self.short_press_time = float(dev_cfg.get('Short_Press-Threshold', 0))
self.long_press_time = float(dev_cfg.get('Long_Press-Threshold', 0))
try:
self.state_when_pressed = GPIO.LOW if dev_cfg['Btn_Pressed_State'] == 'LOW' else GPIO.HIGH
... | stores all button related parameters | ButtonPressCfg | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ButtonPressCfg:
"""stores all button related parameters"""
def __init__(self, dev_cfg, caller):
"""read optional button press related parametes from the config Parameters: - dev_cfg : the dictionary that stores the config values for a sensor - caller : the objetc of the calling senso... | stack_v2_sparse_classes_36k_train_023497 | 18,086 | permissive | [
{
"docstring": "read optional button press related parametes from the config Parameters: - dev_cfg : the dictionary that stores the config values for a sensor - caller : the objetc of the calling sensor",
"name": "__init__",
"signature": "def __init__(self, dev_cfg, caller)"
},
{
"docstring": "c... | 2 | stack_v2_sparse_classes_30k_train_017254 | Implement the Python class `ButtonPressCfg` described below.
Class description:
stores all button related parameters
Method signatures and docstrings:
- def __init__(self, dev_cfg, caller): read optional button press related parametes from the config Parameters: - dev_cfg : the dictionary that stores the config value... | Implement the Python class `ButtonPressCfg` described below.
Class description:
stores all button related parameters
Method signatures and docstrings:
- def __init__(self, dev_cfg, caller): read optional button press related parametes from the config Parameters: - dev_cfg : the dictionary that stores the config value... | 6f8888ddef413fb8d58ef0ebc8fe89144c914a22 | <|skeleton|>
class ButtonPressCfg:
"""stores all button related parameters"""
def __init__(self, dev_cfg, caller):
"""read optional button press related parametes from the config Parameters: - dev_cfg : the dictionary that stores the config values for a sensor - caller : the objetc of the calling senso... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ButtonPressCfg:
"""stores all button related parameters"""
def __init__(self, dev_cfg, caller):
"""read optional button press related parametes from the config Parameters: - dev_cfg : the dictionary that stores the config values for a sensor - caller : the objetc of the calling sensor"""
... | the_stack_v2_python_sparse | gpio/rpi_gpio.py | rkoshak/sensorReporter | train | 104 |
4452bdd6dfb8fc893905d51d144a1ef8303241ac | [
"self.weight_model = weight_model\nif survival_model is None:\n self.survival_model = UnivariateCurveFitter()\nelif isinstance(survival_model, SKLearnBaseEstimator):\n self.survival_model = UnivariateCurveFitter(survival_model)\nelse:\n self.survival_model = survival_model",
"a, _, y, _, X = canonize_dty... | <|body_start_0|>
self.weight_model = weight_model
if survival_model is None:
self.survival_model = UnivariateCurveFitter()
elif isinstance(survival_model, SKLearnBaseEstimator):
self.survival_model = UnivariateCurveFitter(survival_model)
else:
self.sur... | Weighted survival estimator | WeightedSurvival | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WeightedSurvival:
"""Weighted survival estimator"""
def __init__(self, weight_model: WeightEstimator=None, survival_model: Any=None):
"""Weighted survival estimator. Args: weight_model: causallib compatible weight model (e.g., IPW) survival_model: Three alternatives: 1. None - comput... | stack_v2_sparse_classes_36k_train_023498 | 5,765 | permissive | [
{
"docstring": "Weighted survival estimator. Args: weight_model: causallib compatible weight model (e.g., IPW) survival_model: Three alternatives: 1. None - compute non-parametric KaplanMeier survival curve 2. Scikit-Learn estimator (needs to implement `predict_proba`) - compute parametric curve by fitting a ti... | 3 | stack_v2_sparse_classes_30k_train_004541 | Implement the Python class `WeightedSurvival` described below.
Class description:
Weighted survival estimator
Method signatures and docstrings:
- def __init__(self, weight_model: WeightEstimator=None, survival_model: Any=None): Weighted survival estimator. Args: weight_model: causallib compatible weight model (e.g., ... | Implement the Python class `WeightedSurvival` described below.
Class description:
Weighted survival estimator
Method signatures and docstrings:
- def __init__(self, weight_model: WeightEstimator=None, survival_model: Any=None): Weighted survival estimator. Args: weight_model: causallib compatible weight model (e.g., ... | 9f0ddb4696d580cf0a529a6c6ce98b40b34e3796 | <|skeleton|>
class WeightedSurvival:
"""Weighted survival estimator"""
def __init__(self, weight_model: WeightEstimator=None, survival_model: Any=None):
"""Weighted survival estimator. Args: weight_model: causallib compatible weight model (e.g., IPW) survival_model: Three alternatives: 1. None - comput... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WeightedSurvival:
"""Weighted survival estimator"""
def __init__(self, weight_model: WeightEstimator=None, survival_model: Any=None):
"""Weighted survival estimator. Args: weight_model: causallib compatible weight model (e.g., IPW) survival_model: Three alternatives: 1. None - compute non-paramet... | the_stack_v2_python_sparse | causallib/survival/weighted_survival.py | vishalbelsare/causallib | train | 0 |
61325577656387bc487c8ca5f2332c587406c418 | [
"order = []\n\ndef preorder(node):\n if not node:\n return\n order.append(str(node.val))\n for child in node.children:\n preorder(child)\n order.append('#')\n return\npreorder(root)\nreturn ' '.join(order)",
"stack = []\nnodes = data.split(' ')\nif not nodes[0]:\n return None\nroot... | <|body_start_0|>
order = []
def preorder(node):
if not node:
return
order.append(str(node.val))
for child in node.children:
preorder(child)
order.append('#')
return
preorder(root)
return ' '.join... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_023499 | 3,003 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def deserialize(self, ... | 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: Node :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: Nod... | 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: Node :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: Nod... | 8e116c21f91c87a9dc8526d8be93c443e79469bf | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
order = []
def preorder(node):
if not node:
return
order.append(str(node.val))
for child in node.children:
preord... | the_stack_v2_python_sparse | Hard/428_hard_serialize-and-deserialize-n-ary-tree.py | sarahgonsalves223/DSA_Python | train | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.