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
098ca878c22181e967649c49a8a71045cdf1a85b
[ "self._block_specs = block_specs\nself._batch_norm_activation = batch_norm_activation\nself._data_format = data_format", "x = images\nwith tf.variable_scope('efficientnet'):\n x = nn_ops.conv2d_fixed_padding(inputs=x, filters=32, kernel_size=3, strides=2, data_format=self._data_format)\n x = tf.identity(x, ...
<|body_start_0|> self._block_specs = block_specs self._batch_norm_activation = batch_norm_activation self._data_format = data_format <|end_body_0|> <|body_start_1|> x = images with tf.variable_scope('efficientnet'): x = nn_ops.conv2d_fixed_padding(inputs=x, filters=3...
Class to build EfficientNet and X family models.
EfficientNetX
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EfficientNetX: """Class to build EfficientNet and X family models.""" def __init__(self, block_specs=build_block_specs(), batch_norm_activation=nn_ops.BatchNormActivation(), data_format='channels_last'): """EfficientNet initialization function. Args: block_specs: a list of BlockSpec ...
stack_v2_sparse_classes_36k_train_031000
7,394
permissive
[ { "docstring": "EfficientNet initialization function. Args: block_specs: a list of BlockSpec objects that specifies the EfficientNet network. By default, the previously discovered EfficientNet-A1 is used. batch_norm_activation: an operation that includes a batch normalization layer followed by an optional activ...
2
null
Implement the Python class `EfficientNetX` described below. Class description: Class to build EfficientNet and X family models. Method signatures and docstrings: - def __init__(self, block_specs=build_block_specs(), batch_norm_activation=nn_ops.BatchNormActivation(), data_format='channels_last'): EfficientNet initial...
Implement the Python class `EfficientNetX` described below. Class description: Class to build EfficientNet and X family models. Method signatures and docstrings: - def __init__(self, block_specs=build_block_specs(), batch_norm_activation=nn_ops.BatchNormActivation(), data_format='channels_last'): EfficientNet initial...
0f7adb97a93ec3e3485c261d030c507eb16b33e4
<|skeleton|> class EfficientNetX: """Class to build EfficientNet and X family models.""" def __init__(self, block_specs=build_block_specs(), batch_norm_activation=nn_ops.BatchNormActivation(), data_format='channels_last'): """EfficientNet initialization function. Args: block_specs: a list of BlockSpec ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EfficientNetX: """Class to build EfficientNet and X family models.""" def __init__(self, block_specs=build_block_specs(), batch_norm_activation=nn_ops.BatchNormActivation(), data_format='channels_last'): """EfficientNet initialization function. Args: block_specs: a list of BlockSpec objects that ...
the_stack_v2_python_sparse
models/official/detection/modeling/architecture/efficientnet.py
tensorflow/tpu
train
5,627
de5cc6767c3f9066a3bc76aa323be54addad780c
[ "try:\n firewallController = FirewallController()\n json_data = json.dumps(firewallController.get_interface_ipv4Configuration_netmask(id))\n resp = Response(json_data, status=200, mimetype='application/json')\n return resp\nexcept ValueError as ve:\n return Response(json.dumps(str(ve)), status=404, m...
<|body_start_0|> try: firewallController = FirewallController() json_data = json.dumps(firewallController.get_interface_ipv4Configuration_netmask(id)) resp = Response(json_data, status=200, mimetype='application/json') return resp except ValueError as ve: ...
Interface_ifEntry_Ipv4Configuration_Netmask
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Interface_ifEntry_Ipv4Configuration_Netmask: def get(self, id): """Get the netmask of an interface""" <|body_0|> def put(self, id): """Update the netmask of an interface""" <|body_1|> <|end_skeleton|> <|body_start_0|> try: firewallContro...
stack_v2_sparse_classes_36k_train_031001
12,460
no_license
[ { "docstring": "Get the netmask of an interface", "name": "get", "signature": "def get(self, id)" }, { "docstring": "Update the netmask of an interface", "name": "put", "signature": "def put(self, id)" } ]
2
null
Implement the Python class `Interface_ifEntry_Ipv4Configuration_Netmask` described below. Class description: Implement the Interface_ifEntry_Ipv4Configuration_Netmask class. Method signatures and docstrings: - def get(self, id): Get the netmask of an interface - def put(self, id): Update the netmask of an interface
Implement the Python class `Interface_ifEntry_Ipv4Configuration_Netmask` described below. Class description: Implement the Interface_ifEntry_Ipv4Configuration_Netmask class. Method signatures and docstrings: - def get(self, id): Get the netmask of an interface - def put(self, id): Update the netmask of an interface ...
6070e3cb6bf957e04f5d8267db11f3296410e18e
<|skeleton|> class Interface_ifEntry_Ipv4Configuration_Netmask: def get(self, id): """Get the netmask of an interface""" <|body_0|> def put(self, id): """Update the netmask of an interface""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Interface_ifEntry_Ipv4Configuration_Netmask: def get(self, id): """Get the netmask of an interface""" try: firewallController = FirewallController() json_data = json.dumps(firewallController.get_interface_ipv4Configuration_netmask(id)) resp = Response(json_d...
the_stack_v2_python_sparse
configuration-agent/firewall/rest_api/resources/interface.py
ReliableLion/frog4-configurable-vnf
train
0
d31699dfa2483d5123ba0ee8986c3de272dc8e94
[ "query = kwargs.get('query', '')\nsite_domains = cherrypy.engine.publish('registry:search:valuelist', 'logindex:site_domain').pop()\nsaved_queries = cherrypy.engine.publish('registry:search:dict', 'visitors*', key_slice=1).pop()\nregistry_url = cherrypy.engine.publish('app_url', '/registry').pop()\nif 'default' in ...
<|body_start_0|> query = kwargs.get('query', '') site_domains = cherrypy.engine.publish('registry:search:valuelist', 'logindex:site_domain').pop() saved_queries = cherrypy.engine.publish('registry:search:dict', 'visitors*', key_slice=1).pop() registry_url = cherrypy.engine.publish('app_u...
Controller
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Controller: def GET(self, **kwargs: str) -> bytes: """Display a search interface, and the results of the default query""" <|body_0|> def get_active_date(log_records: List[sqlite3.Row], query: str) -> Union[date, datetime]: """Figure out which date the query pertains ...
stack_v2_sparse_classes_36k_train_031002
4,492
no_license
[ { "docstring": "Display a search interface, and the results of the default query", "name": "GET", "signature": "def GET(self, **kwargs: str) -> bytes" }, { "docstring": "Figure out which date the query pertains to.", "name": "get_active_date", "signature": "def get_active_date(log_record...
3
null
Implement the Python class `Controller` described below. Class description: Implement the Controller class. Method signatures and docstrings: - def GET(self, **kwargs: str) -> bytes: Display a search interface, and the results of the default query - def get_active_date(log_records: List[sqlite3.Row], query: str) -> U...
Implement the Python class `Controller` described below. Class description: Implement the Controller class. Method signatures and docstrings: - def GET(self, **kwargs: str) -> bytes: Display a search interface, and the results of the default query - def get_active_date(log_records: List[sqlite3.Row], query: str) -> U...
7129415303b94d5d10b2c29ec432f0c7d41cc651
<|skeleton|> class Controller: def GET(self, **kwargs: str) -> bytes: """Display a search interface, and the results of the default query""" <|body_0|> def get_active_date(log_records: List[sqlite3.Row], query: str) -> Union[date, datetime]: """Figure out which date the query pertains ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Controller: def GET(self, **kwargs: str) -> bytes: """Display a search interface, and the results of the default query""" query = kwargs.get('query', '') site_domains = cherrypy.engine.publish('registry:search:valuelist', 'logindex:site_domain').pop() saved_queries = cherrypy.e...
the_stack_v2_python_sparse
apps/visitors/main.py
lovett/medley
train
6
be9b3144f5dce329f9ae784186b5c33bc8d408d7
[ "sensor = Sensor('127.0.0.1', 8000)\npump = Pump('127.0.0.1', 8000)\ndecider = Decider(10, 0.1)\ncontroller = Controller(sensor, pump, decider)\nsensor.measure = MagicMock(return_value=10)\npump.get_state = MagicMock(return_value=pump.PUMP_OFF)\npump.set_state = MagicMock(return_value=True)\nself.assertTrue(control...
<|body_start_0|> sensor = Sensor('127.0.0.1', 8000) pump = Pump('127.0.0.1', 8000) decider = Decider(10, 0.1) controller = Controller(sensor, pump, decider) sensor.measure = MagicMock(return_value=10) pump.get_state = MagicMock(return_value=pump.PUMP_OFF) pump.set...
Unit tests for the Controller class
ControllerTests
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ControllerTests: """Unit tests for the Controller class""" def test_tick_true(self): """Test that tick return True if pump.set_state returns True""" <|body_0|> def test_tick_false(self): """Test that tick return False if pump.set_state returns False""" <|...
stack_v2_sparse_classes_36k_train_031003
4,700
no_license
[ { "docstring": "Test that tick return True if pump.set_state returns True", "name": "test_tick_true", "signature": "def test_tick_true(self)" }, { "docstring": "Test that tick return False if pump.set_state returns False", "name": "test_tick_false", "signature": "def test_tick_false(self...
2
null
Implement the Python class `ControllerTests` described below. Class description: Unit tests for the Controller class Method signatures and docstrings: - def test_tick_true(self): Test that tick return True if pump.set_state returns True - def test_tick_false(self): Test that tick return False if pump.set_state return...
Implement the Python class `ControllerTests` described below. Class description: Unit tests for the Controller class Method signatures and docstrings: - def test_tick_true(self): Test that tick return True if pump.set_state returns True - def test_tick_false(self): Test that tick return False if pump.set_state return...
b1fea0309b3495b3e1dc167d7029bc9e4b6f00f1
<|skeleton|> class ControllerTests: """Unit tests for the Controller class""" def test_tick_true(self): """Test that tick return True if pump.set_state returns True""" <|body_0|> def test_tick_false(self): """Test that tick return False if pump.set_state returns False""" <|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ControllerTests: """Unit tests for the Controller class""" def test_tick_true(self): """Test that tick return True if pump.set_state returns True""" sensor = Sensor('127.0.0.1', 8000) pump = Pump('127.0.0.1', 8000) decider = Decider(10, 0.1) controller = Controller...
the_stack_v2_python_sparse
students/CocoKaku/lesson6/water-regulation/waterregulation/test.py
UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018
train
4
c6c2d01db5c4093f6b325c8dd9fd8c5501ba34dc
[ "mock_client = Taxii2FeedClient(url='', collection_to_fetch='default', proxies=[], verify=False, objects_to_fetch='')\ndefault_id = 1\nnondefault_id = 2\nmock_client.collections = [MockCollection(default_id, 'default'), MockCollection(nondefault_id, 'not_default')]\nmock_client.collection_to_fetch = mock_client.col...
<|body_start_0|> mock_client = Taxii2FeedClient(url='', collection_to_fetch='default', proxies=[], verify=False, objects_to_fetch='') default_id = 1 nondefault_id = 2 mock_client.collections = [MockCollection(default_id, 'default'), MockCollection(nondefault_id, 'not_default')] m...
Scenario: Test fetch_indicators_command
TestFetchIndicators
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestFetchIndicators: """Scenario: Test fetch_indicators_command""" def test_single_no_context(self, mocker): """Scenario: Test single collection fetch with no last run Given: - collection to fetch is available and set to 'default' - there is no integration context - limit is -1 - ini...
stack_v2_sparse_classes_36k_train_031004
9,956
permissive
[ { "docstring": "Scenario: Test single collection fetch with no last run Given: - collection to fetch is available and set to 'default' - there is no integration context - limit is -1 - initial interval is `1 day` When: - fetch_indicators_command is called Then: - update last run with latest collection fetch tim...
4
stack_v2_sparse_classes_30k_train_019030
Implement the Python class `TestFetchIndicators` described below. Class description: Scenario: Test fetch_indicators_command Method signatures and docstrings: - def test_single_no_context(self, mocker): Scenario: Test single collection fetch with no last run Given: - collection to fetch is available and set to 'defau...
Implement the Python class `TestFetchIndicators` described below. Class description: Scenario: Test fetch_indicators_command Method signatures and docstrings: - def test_single_no_context(self, mocker): Scenario: Test single collection fetch with no last run Given: - collection to fetch is available and set to 'defau...
01b57f8c658c2faed047313d3034e8052ffa83ce
<|skeleton|> class TestFetchIndicators: """Scenario: Test fetch_indicators_command""" def test_single_no_context(self, mocker): """Scenario: Test single collection fetch with no last run Given: - collection to fetch is available and set to 'default' - there is no integration context - limit is -1 - ini...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestFetchIndicators: """Scenario: Test fetch_indicators_command""" def test_single_no_context(self, mocker): """Scenario: Test single collection fetch with no last run Given: - collection to fetch is available and set to 'default' - there is no integration context - limit is -1 - initial interval...
the_stack_v2_python_sparse
Packs/FeedTAXII/Integrations/FeedTAXII2/FeedTAXII2_test.py
adambaumeister/content
train
2
776fb4718fbe54b8cd0b5d71d83a3f59ffba5a18
[ "self.entity_id = _slug(name)\nself._attr_name = name\nself._attr_unique_id = topic\nself._state_key = state_key\nself._attr_native_unit_of_measurement = units\nself._attr_icon = icon\nself._attr_device_class = device_class", "ev = {}\nev.update(event)\nself._attr_extra_state_attributes = ev\nself._attr_native_va...
<|body_start_0|> self.entity_id = _slug(name) self._attr_name = name self._attr_unique_id = topic self._state_key = state_key self._attr_native_unit_of_measurement = units self._attr_icon = icon self._attr_device_class = device_class <|end_body_0|> <|body_start_1...
Representation of an ARWN sensor.
ArwnSensor
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ArwnSensor: """Representation of an ARWN sensor.""" def __init__(self, topic, name, state_key, units, icon=None, device_class=None): """Initialize the sensor.""" <|body_0|> def set_event(self, event): """Update the sensor with the most recent event.""" <|...
stack_v2_sparse_classes_36k_train_031005
5,948
permissive
[ { "docstring": "Initialize the sensor.", "name": "__init__", "signature": "def __init__(self, topic, name, state_key, units, icon=None, device_class=None)" }, { "docstring": "Update the sensor with the most recent event.", "name": "set_event", "signature": "def set_event(self, event)" ...
2
null
Implement the Python class `ArwnSensor` described below. Class description: Representation of an ARWN sensor. Method signatures and docstrings: - def __init__(self, topic, name, state_key, units, icon=None, device_class=None): Initialize the sensor. - def set_event(self, event): Update the sensor with the most recent...
Implement the Python class `ArwnSensor` described below. Class description: Representation of an ARWN sensor. Method signatures and docstrings: - def __init__(self, topic, name, state_key, units, icon=None, device_class=None): Initialize the sensor. - def set_event(self, event): Update the sensor with the most recent...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class ArwnSensor: """Representation of an ARWN sensor.""" def __init__(self, topic, name, state_key, units, icon=None, device_class=None): """Initialize the sensor.""" <|body_0|> def set_event(self, event): """Update the sensor with the most recent event.""" <|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ArwnSensor: """Representation of an ARWN sensor.""" def __init__(self, topic, name, state_key, units, icon=None, device_class=None): """Initialize the sensor.""" self.entity_id = _slug(name) self._attr_name = name self._attr_unique_id = topic self._state_key = stat...
the_stack_v2_python_sparse
homeassistant/components/arwn/sensor.py
home-assistant/core
train
35,501
f6797c753535093d995b1fea07443c77cb3058f7
[ "if input_type == 'f':\n file = open(path, 'r')\nelif input_type == 's':\n file = path\nelse:\n raise exceptions.BadInputError(f'invalid input type {input_type}')\npdl = yaml.safe_load(file)\nself.type_checks = {'typedef': self.validate_typedef, 'component': self.validate_component, 'graph': self.validate_...
<|body_start_0|> if input_type == 'f': file = open(path, 'r') elif input_type == 's': file = path else: raise exceptions.BadInputError(f'invalid input type {input_type}') pdl = yaml.safe_load(file) self.type_checks = {'typedef': self.validate_t...
Represents a single PDL file.
File
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class File: """Represents a single PDL file.""" def __init__(self, path, input_type='f'): """Initialize a File object from a file's worth of PDL. The PDL file should contain exactly three fields: - name: the namespace that the file's contents belong in, - imports: a list of imports that th...
stack_v2_sparse_classes_36k_train_031006
5,874
permissive
[ { "docstring": "Initialize a File object from a file's worth of PDL. The PDL file should contain exactly three fields: - name: the namespace that the file's contents belong in, - imports: a list of imports that the file's contents use, - body: the body of PDL. Parameters ---------- path: string path should cont...
6
stack_v2_sparse_classes_30k_train_004552
Implement the Python class `File` described below. Class description: Represents a single PDL file. Method signatures and docstrings: - def __init__(self, path, input_type='f'): Initialize a File object from a file's worth of PDL. The PDL file should contain exactly three fields: - name: the namespace that the file's...
Implement the Python class `File` described below. Class description: Represents a single PDL file. Method signatures and docstrings: - def __init__(self, path, input_type='f'): Initialize a File object from a file's worth of PDL. The PDL file should contain exactly three fields: - name: the namespace that the file's...
345e7d47efdac04c2c5f70d55f83bd77acdbb511
<|skeleton|> class File: """Represents a single PDL file.""" def __init__(self, path, input_type='f'): """Initialize a File object from a file's worth of PDL. The PDL file should contain exactly three fields: - name: the namespace that the file's contents belong in, - imports: a list of imports that th...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class File: """Represents a single PDL file.""" def __init__(self, path, input_type='f'): """Initialize a File object from a file's worth of PDL. The PDL file should contain exactly three fields: - name: the namespace that the file's contents belong in, - imports: a list of imports that the file's cont...
the_stack_v2_python_sparse
topside/pdl/file.py
roguextech/Waterloo-Rocketry-topside
train
0
cf0bf8ecf962cec11a35a563aa67f1b038a1709d
[ "ExecutionElement.__init__(self, uid)\nself.action = action\nself._args_api, self._data_in_api = get_filter_api(self.action)\nif isinstance(args, list):\n args = {arg['name']: arg['value'] for arg in args}\nelif isinstance(args, dict):\n args = args\nelse:\n args = {}\nself.args = validate_filter_parameter...
<|body_start_0|> ExecutionElement.__init__(self, uid) self.action = action self._args_api, self._data_in_api = get_filter_api(self.action) if isinstance(args, list): args = {arg['name']: arg['value'] for arg in args} elif isinstance(args, dict): args = arg...
Filter
[ "CC0-1.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Filter: def __init__(self, action, args=None, uid=None): """Initializes a new Filter object. A Filter is used to filter input into a workflow. Args: action (str, optional): The action name for the filter. Defaults to an empty string. args (dict[str:str], optional): Dictionary of Argument...
stack_v2_sparse_classes_36k_train_031007
2,894
permissive
[ { "docstring": "Initializes a new Filter object. A Filter is used to filter input into a workflow. Args: action (str, optional): The action name for the filter. Defaults to an empty string. args (dict[str:str], optional): Dictionary of Argument keys to Argument values. This dictionary will be converted to a dic...
2
null
Implement the Python class `Filter` described below. Class description: Implement the Filter class. Method signatures and docstrings: - def __init__(self, action, args=None, uid=None): Initializes a new Filter object. A Filter is used to filter input into a workflow. Args: action (str, optional): The action name for ...
Implement the Python class `Filter` described below. Class description: Implement the Filter class. Method signatures and docstrings: - def __init__(self, action, args=None, uid=None): Initializes a new Filter object. A Filter is used to filter input into a workflow. Args: action (str, optional): The action name for ...
18cd8b6d10241955bea5422947af9cf67f73aead
<|skeleton|> class Filter: def __init__(self, action, args=None, uid=None): """Initializes a new Filter object. A Filter is used to filter input into a workflow. Args: action (str, optional): The action name for the filter. Defaults to an empty string. args (dict[str:str], optional): Dictionary of Argument...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Filter: def __init__(self, action, args=None, uid=None): """Initializes a new Filter object. A Filter is used to filter input into a workflow. Args: action (str, optional): The action name for the filter. Defaults to an empty string. args (dict[str:str], optional): Dictionary of Argument keys to Argum...
the_stack_v2_python_sparse
core/executionelements/filter.py
JustinTervala/WALKOFF
train
0
cc15e2111cd96a422debe0d6bf491ae7cdd6723a
[ "self.actor_id = kwargs.get('actor_id')\nself.name = kwargs.get('name')\nself.level = kwargs.get('level')\nself.gold = kwargs.get('gold')\nself.experience = kwargs.get('experience')\nself.max_hp = kwargs.get('max_hp')\nself.hp = kwargs.get('hp')\nself.max_ammo = kwargs.get('max_ammo')\nself.ammo = kwargs.get('ammo'...
<|body_start_0|> self.actor_id = kwargs.get('actor_id') self.name = kwargs.get('name') self.level = kwargs.get('level') self.gold = kwargs.get('gold') self.experience = kwargs.get('experience') self.max_hp = kwargs.get('max_hp') self.hp = kwargs.get('hp') ...
Actor
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Actor: def __init__(self, **kwargs): """Params: actor_id: int name: str level: int gold: int experience: int max_hp: int hp: int max_ammo: int ammo: int""" <|body_0|> def load(self, **kwargs): """load from dict Exception: KeyError""" <|body_1|> def dump(...
stack_v2_sparse_classes_36k_train_031008
26,590
no_license
[ { "docstring": "Params: actor_id: int name: str level: int gold: int experience: int max_hp: int hp: int max_ammo: int ammo: int", "name": "__init__", "signature": "def __init__(self, **kwargs)" }, { "docstring": "load from dict Exception: KeyError", "name": "load", "signature": "def loa...
3
stack_v2_sparse_classes_30k_train_007130
Implement the Python class `Actor` described below. Class description: Implement the Actor class. Method signatures and docstrings: - def __init__(self, **kwargs): Params: actor_id: int name: str level: int gold: int experience: int max_hp: int hp: int max_ammo: int ammo: int - def load(self, **kwargs): load from dic...
Implement the Python class `Actor` described below. Class description: Implement the Actor class. Method signatures and docstrings: - def __init__(self, **kwargs): Params: actor_id: int name: str level: int gold: int experience: int max_hp: int hp: int max_ammo: int ammo: int - def load(self, **kwargs): load from dic...
aa0b2697e295889e8c23a7104889ea95f2a4b6b1
<|skeleton|> class Actor: def __init__(self, **kwargs): """Params: actor_id: int name: str level: int gold: int experience: int max_hp: int hp: int max_ammo: int ammo: int""" <|body_0|> def load(self, **kwargs): """load from dict Exception: KeyError""" <|body_1|> def dump(...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Actor: def __init__(self, **kwargs): """Params: actor_id: int name: str level: int gold: int experience: int max_hp: int hp: int max_ammo: int ammo: int""" self.actor_id = kwargs.get('actor_id') self.name = kwargs.get('name') self.level = kwargs.get('level') self.gold =...
the_stack_v2_python_sparse
message.py
songhui17/Server
train
0
c4144cf04301498932689276bc72f74e97b9f3ff
[ "self._schema = customer_schema\nself._provider = provider\nself._months_to_keep = num_of_months_to_keep\nif self._months_to_keep is None:\n self._months_to_keep = Config.MASU_RETAIN_NUM_MONTHS\nself._line_items_months = line_items_month_to_keep\nif self._line_items_months is None:\n self._line_items_months =...
<|body_start_0|> self._schema = customer_schema self._provider = provider self._months_to_keep = num_of_months_to_keep if self._months_to_keep is None: self._months_to_keep = Config.MASU_RETAIN_NUM_MONTHS self._line_items_months = line_items_month_to_keep if s...
Removes expired report data based on masu's retention policy. Retention policy can be configured via environment variable.
ExpiredDataRemover
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExpiredDataRemover: """Removes expired report data based on masu's retention policy. Retention policy can be configured via environment variable.""" def __init__(self, customer_schema, provider, num_of_months_to_keep=None, line_items_month_to_keep=None): """Initializer. Args: custome...
stack_v2_sparse_classes_36k_train_031009
5,846
permissive
[ { "docstring": "Initializer. Args: customer_schema (String): Schema name for given customer. num_of_months_to_keep (Int): Number of months to retain in database.", "name": "__init__", "signature": "def __init__(self, customer_schema, provider, num_of_months_to_keep=None, line_items_month_to_keep=None)" ...
4
stack_v2_sparse_classes_30k_train_002966
Implement the Python class `ExpiredDataRemover` described below. Class description: Removes expired report data based on masu's retention policy. Retention policy can be configured via environment variable. Method signatures and docstrings: - def __init__(self, customer_schema, provider, num_of_months_to_keep=None, l...
Implement the Python class `ExpiredDataRemover` described below. Class description: Removes expired report data based on masu's retention policy. Retention policy can be configured via environment variable. Method signatures and docstrings: - def __init__(self, customer_schema, provider, num_of_months_to_keep=None, l...
0416e5216eb1ec4b41c8dd4999adde218b1ab2e1
<|skeleton|> class ExpiredDataRemover: """Removes expired report data based on masu's retention policy. Retention policy can be configured via environment variable.""" def __init__(self, customer_schema, provider, num_of_months_to_keep=None, line_items_month_to_keep=None): """Initializer. Args: custome...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ExpiredDataRemover: """Removes expired report data based on masu's retention policy. Retention policy can be configured via environment variable.""" def __init__(self, customer_schema, provider, num_of_months_to_keep=None, line_items_month_to_keep=None): """Initializer. Args: customer_schema (Str...
the_stack_v2_python_sparse
koku/masu/processor/expired_data_remover.py
project-koku/koku
train
225
6a85e86260d833c5bdacebb6338f77072fdcca23
[ "try:\n self._authenticate_user_dn(password)\n self._check_requirements()\nexcept self.AuthenticationFailed as e:\n logger.debug(u'Authentication failed for %s: %s' % (self._username, e))\n return False\nexcept ldap.LDAPError as e:\n logger.warning(u'Caught LDAPError while authenticating %s: %s', sel...
<|body_start_0|> try: self._authenticate_user_dn(password) self._check_requirements() except self.AuthenticationFailed as e: logger.debug(u'Authentication failed for %s: %s' % (self._username, e)) return False except ldap.LDAPError as e: ...
_PolyauthenticationLDAPUser
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _PolyauthenticationLDAPUser: def ldap_authenticate(self, password): """Searches LDAP user and populates his attributes""" <|body_0|> def add_user_to_db(self): """Creating user id DB""" <|body_1|> <|end_skeleton|> <|body_start_0|> try: se...
stack_v2_sparse_classes_36k_train_031010
3,949
no_license
[ { "docstring": "Searches LDAP user and populates his attributes", "name": "ldap_authenticate", "signature": "def ldap_authenticate(self, password)" }, { "docstring": "Creating user id DB", "name": "add_user_to_db", "signature": "def add_user_to_db(self)" } ]
2
stack_v2_sparse_classes_30k_train_002014
Implement the Python class `_PolyauthenticationLDAPUser` described below. Class description: Implement the _PolyauthenticationLDAPUser class. Method signatures and docstrings: - def ldap_authenticate(self, password): Searches LDAP user and populates his attributes - def add_user_to_db(self): Creating user id DB
Implement the Python class `_PolyauthenticationLDAPUser` described below. Class description: Implement the _PolyauthenticationLDAPUser class. Method signatures and docstrings: - def ldap_authenticate(self, password): Searches LDAP user and populates his attributes - def add_user_to_db(self): Creating user id DB <|sk...
3bbf6d6347f8615f2d6a3052017f8f69a4244476
<|skeleton|> class _PolyauthenticationLDAPUser: def ldap_authenticate(self, password): """Searches LDAP user and populates his attributes""" <|body_0|> def add_user_to_db(self): """Creating user id DB""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _PolyauthenticationLDAPUser: def ldap_authenticate(self, password): """Searches LDAP user and populates his attributes""" try: self._authenticate_user_dn(password) self._check_requirements() except self.AuthenticationFailed as e: logger.debug(u'Authe...
the_stack_v2_python_sparse
src/polyana-web-authentication/polyauthentication/backends.py
KirpichenkovPavel/merger
train
0
76c4de2c83b3e3ebbf01af528bdaae6c4d9795a0
[ "est = clone(self.clf)\nest.fit(X.to_numpy(), y)\nif hasattr(est, 'coef_'):\n importance = est.coef_\nelif hasattr(est, 'feature_importances_'):\n importance = est.feature_importances_\nelse:\n raise AttributeError('{} do not has coef_ or feature_importance_'.format(self.clf.__class__.__name__))\nreturn (i...
<|body_start_0|> est = clone(self.clf) est.fit(X.to_numpy(), y) if hasattr(est, 'coef_'): importance = est.coef_ elif hasattr(est, 'feature_importances_'): importance = est.feature_importances_ else: raise AttributeError('{} do not has coef_ or...
FeatureImportanceSelect
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FeatureImportanceSelect: def get_thres(self, X, y): """得到不同特征的重要程度和最小值。""" <|body_0|> def choose(self, X, y, to_select=None): """不断出去最不重要的特征,最终选取结果最好的作为最终选择的特征进行后续建模。""" <|body_1|> def plot_process(self): """可视化在不断去除掉最不重要特征的情况下,结果的变化过程。""" ...
stack_v2_sparse_classes_36k_train_031011
15,365
no_license
[ { "docstring": "得到不同特征的重要程度和最小值。", "name": "get_thres", "signature": "def get_thres(self, X, y)" }, { "docstring": "不断出去最不重要的特征,最终选取结果最好的作为最终选择的特征进行后续建模。", "name": "choose", "signature": "def choose(self, X, y, to_select=None)" }, { "docstring": "可视化在不断去除掉最不重要特征的情况下,结果的变化过程。", ...
3
stack_v2_sparse_classes_30k_train_021632
Implement the Python class `FeatureImportanceSelect` described below. Class description: Implement the FeatureImportanceSelect class. Method signatures and docstrings: - def get_thres(self, X, y): 得到不同特征的重要程度和最小值。 - def choose(self, X, y, to_select=None): 不断出去最不重要的特征,最终选取结果最好的作为最终选择的特征进行后续建模。 - def plot_process(self)...
Implement the Python class `FeatureImportanceSelect` described below. Class description: Implement the FeatureImportanceSelect class. Method signatures and docstrings: - def get_thres(self, X, y): 得到不同特征的重要程度和最小值。 - def choose(self, X, y, to_select=None): 不断出去最不重要的特征,最终选取结果最好的作为最终选择的特征进行后续建模。 - def plot_process(self)...
823184005a3a2ed70a32b37c0afc2066e6e8907a
<|skeleton|> class FeatureImportanceSelect: def get_thres(self, X, y): """得到不同特征的重要程度和最小值。""" <|body_0|> def choose(self, X, y, to_select=None): """不断出去最不重要的特征,最终选取结果最好的作为最终选择的特征进行后续建模。""" <|body_1|> def plot_process(self): """可视化在不断去除掉最不重要特征的情况下,结果的变化过程。""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FeatureImportanceSelect: def get_thres(self, X, y): """得到不同特征的重要程度和最小值。""" est = clone(self.clf) est.fit(X.to_numpy(), y) if hasattr(est, 'coef_'): importance = est.coef_ elif hasattr(est, 'feature_importances_'): importance = est.feature_importa...
the_stack_v2_python_sparse
WorkCode/Models/UserFunc/FeatureEngineering.py
johngolt/gitln
train
1
58f65d75ad373949cf0198f5c14d8a296cf06d03
[ "super().__init__(coordinator=coordinator, kind=kind, name=name, item_id=item_id, icon=icon)\nself._state_key = state_key\nself._state = None\nself._last_action = 0\nself._state_delay = 30", "state_int = 0\nif self._last_action < time.time() - self._state_delay:\n state_int = int(self.coordinator.data[self._it...
<|body_start_0|> super().__init__(coordinator=coordinator, kind=kind, name=name, item_id=item_id, icon=icon) self._state_key = state_key self._state = None self._last_action = 0 self._state_delay = 30 <|end_body_0|> <|body_start_1|> state_int = 0 if self._last_ac...
Define an Omnilogic Base Switch entity to be extended.
OmniLogicSwitch
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OmniLogicSwitch: """Define an Omnilogic Base Switch entity to be extended.""" def __init__(self, coordinator: OmniLogicUpdateCoordinator, kind: str, name: str, icon: str, item_id: tuple, state_key: str) -> None: """Initialize Entities.""" <|body_0|> def is_on(self): ...
stack_v2_sparse_classes_36k_train_031012
8,137
permissive
[ { "docstring": "Initialize Entities.", "name": "__init__", "signature": "def __init__(self, coordinator: OmniLogicUpdateCoordinator, kind: str, name: str, icon: str, item_id: tuple, state_key: str) -> None" }, { "docstring": "Return the on/off state of the switch.", "name": "is_on", "sig...
2
stack_v2_sparse_classes_30k_train_021135
Implement the Python class `OmniLogicSwitch` described below. Class description: Define an Omnilogic Base Switch entity to be extended. Method signatures and docstrings: - def __init__(self, coordinator: OmniLogicUpdateCoordinator, kind: str, name: str, icon: str, item_id: tuple, state_key: str) -> None: Initialize E...
Implement the Python class `OmniLogicSwitch` described below. Class description: Define an Omnilogic Base Switch entity to be extended. Method signatures and docstrings: - def __init__(self, coordinator: OmniLogicUpdateCoordinator, kind: str, name: str, icon: str, item_id: tuple, state_key: str) -> None: Initialize E...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class OmniLogicSwitch: """Define an Omnilogic Base Switch entity to be extended.""" def __init__(self, coordinator: OmniLogicUpdateCoordinator, kind: str, name: str, icon: str, item_id: tuple, state_key: str) -> None: """Initialize Entities.""" <|body_0|> def is_on(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OmniLogicSwitch: """Define an Omnilogic Base Switch entity to be extended.""" def __init__(self, coordinator: OmniLogicUpdateCoordinator, kind: str, name: str, icon: str, item_id: tuple, state_key: str) -> None: """Initialize Entities.""" super().__init__(coordinator=coordinator, kind=kin...
the_stack_v2_python_sparse
homeassistant/components/omnilogic/switch.py
home-assistant/core
train
35,501
d9f78fa6ebc41ee8e75a732c1f55f9f6ce179d65
[ "if not self.create_time:\n self.create_time = datetime.datetime.now()\nreturn super(Message, self).save(*args, **kwargs)", "user = User.objects.get(id=self.user_id)\nres = {'id': str(self.id), 'msgType': self.msg_type, 'content': self.content, 'createTime': self.create_time.strftime('%s'), 'company': user.com...
<|body_start_0|> if not self.create_time: self.create_time = datetime.datetime.now() return super(Message, self).save(*args, **kwargs) <|end_body_0|> <|body_start_1|> user = User.objects.get(id=self.user_id) res = {'id': str(self.id), 'msgType': self.msg_type, 'content': sel...
消息类
Message
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Message: """消息类""" def save(self, *args, **kwargs): """改写save函数,自动保存create_time""" <|body_0|> def get_json(self): """获取动态""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not self.create_time: self.create_time = datetime.datetime.n...
stack_v2_sparse_classes_36k_train_031013
19,588
no_license
[ { "docstring": "改写save函数,自动保存create_time", "name": "save", "signature": "def save(self, *args, **kwargs)" }, { "docstring": "获取动态", "name": "get_json", "signature": "def get_json(self)" } ]
2
stack_v2_sparse_classes_30k_train_016197
Implement the Python class `Message` described below. Class description: 消息类 Method signatures and docstrings: - def save(self, *args, **kwargs): 改写save函数,自动保存create_time - def get_json(self): 获取动态
Implement the Python class `Message` described below. Class description: 消息类 Method signatures and docstrings: - def save(self, *args, **kwargs): 改写save函数,自动保存create_time - def get_json(self): 获取动态 <|skeleton|> class Message: """消息类""" def save(self, *args, **kwargs): """改写save函数,自动保存create_time""" ...
e31b674d38ce62c0ee30bf3dda4462060631974e
<|skeleton|> class Message: """消息类""" def save(self, *args, **kwargs): """改写save函数,自动保存create_time""" <|body_0|> def get_json(self): """获取动态""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Message: """消息类""" def save(self, *args, **kwargs): """改写save函数,自动保存create_time""" if not self.create_time: self.create_time = datetime.datetime.now() return super(Message, self).save(*args, **kwargs) def get_json(self): """获取动态""" user = User.obje...
the_stack_v2_python_sparse
taotao/api/models.py
leolinf/tornado-demo
train
3
1be1ad830133b06647b37ac28e34bafe2fb59976
[ "entity.name = domain.name\nentity.time = domain.time\nentity.width = domain.width\nentity.height = domain.height\nentity.spawnX = domain.spawn[0]\nentity.spawnY = domain.spawn[1]\nentity.worldSurface = domain.worldSurface\nentity.rockLayer = domain.rockLayer\nentity.isDay = domain.isDay\nentity.isBloodMoon = domai...
<|body_start_0|> entity.name = domain.name entity.time = domain.time entity.width = domain.width entity.height = domain.height entity.spawnX = domain.spawn[0] entity.spawnY = domain.spawn[1] entity.worldSurface = domain.worldSurface entity.rockLayer = doma...
Maps L{World} and L{WorldEntity} objects
WorldMapper
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WorldMapper: """Maps L{World} and L{WorldEntity} objects""" def domainToEntity(self, domain, entity): """Maps a L{World} domain object to a L{WorldEntity} object""" <|body_0|> def entityToDomain(self, entity, domain): """Maps a L{WorldEntity} to a L{World} object...
stack_v2_sparse_classes_36k_train_031014
2,701
no_license
[ { "docstring": "Maps a L{World} domain object to a L{WorldEntity} object", "name": "domainToEntity", "signature": "def domainToEntity(self, domain, entity)" }, { "docstring": "Maps a L{WorldEntity} to a L{World} object", "name": "entityToDomain", "signature": "def entityToDomain(self, en...
2
stack_v2_sparse_classes_30k_train_010728
Implement the Python class `WorldMapper` described below. Class description: Maps L{World} and L{WorldEntity} objects Method signatures and docstrings: - def domainToEntity(self, domain, entity): Maps a L{World} domain object to a L{WorldEntity} object - def entityToDomain(self, entity, domain): Maps a L{WorldEntity}...
Implement the Python class `WorldMapper` described below. Class description: Maps L{World} and L{WorldEntity} objects Method signatures and docstrings: - def domainToEntity(self, domain, entity): Maps a L{World} domain object to a L{WorldEntity} object - def entityToDomain(self, entity, domain): Maps a L{WorldEntity}...
020ee14a28d61af9660d5d84d575c2e6302ce748
<|skeleton|> class WorldMapper: """Maps L{World} and L{WorldEntity} objects""" def domainToEntity(self, domain, entity): """Maps a L{World} domain object to a L{WorldEntity} object""" <|body_0|> def entityToDomain(self, entity, domain): """Maps a L{WorldEntity} to a L{World} object...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WorldMapper: """Maps L{World} and L{WorldEntity} objects""" def domainToEntity(self, domain, entity): """Maps a L{World} domain object to a L{WorldEntity} object""" entity.name = domain.name entity.time = domain.time entity.width = domain.width entity.height = doma...
the_stack_v2_python_sparse
db/mappers.py
smoak/TPS
train
9
2ac2bcfc80ea029601d99032b74cfea42f683920
[ "self.assertEqual(list_copy([7, 8, 9, 10]), [7, 8, 9, 10])\nself.assertEqual(list_copy(['Rohan', '6,7,8', 7]), ['Rohan', '6,7,8', 7])\nself.assertEqual(list_copy([]), [])\nself.assertNotEqual(list_copy([10, 11, 12, 13]), [])\nself.assertNotEqual(list_copy([10, 11, 12, 13]), [10, 12])", "self.assertEqual(list_inte...
<|body_start_0|> self.assertEqual(list_copy([7, 8, 9, 10]), [7, 8, 9, 10]) self.assertEqual(list_copy(['Rohan', '6,7,8', 7]), ['Rohan', '6,7,8', 7]) self.assertEqual(list_copy([]), []) self.assertNotEqual(list_copy([10, 11, 12, 13]), []) self.assertNotEqual(list_copy([10, 11, 12,...
MyTestCase
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyTestCase: def test_list_copy(self): """Function is used to test copy of list""" <|body_0|> def test_list_intersect(self): """Function is used to test intersection between two lists""" <|body_1|> def test_list_difference(self): """Function is us...
stack_v2_sparse_classes_36k_train_031015
2,888
no_license
[ { "docstring": "Function is used to test copy of list", "name": "test_list_copy", "signature": "def test_list_copy(self)" }, { "docstring": "Function is used to test intersection between two lists", "name": "test_list_intersect", "signature": "def test_list_intersect(self)" }, { ...
5
stack_v2_sparse_classes_30k_train_012416
Implement the Python class `MyTestCase` described below. Class description: Implement the MyTestCase class. Method signatures and docstrings: - def test_list_copy(self): Function is used to test copy of list - def test_list_intersect(self): Function is used to test intersection between two lists - def test_list_diffe...
Implement the Python class `MyTestCase` described below. Class description: Implement the MyTestCase class. Method signatures and docstrings: - def test_list_copy(self): Function is used to test copy of list - def test_list_intersect(self): Function is used to test intersection between two lists - def test_list_diffe...
7fe7bb8518584cc98f00f16d6b1cd0a288254ee3
<|skeleton|> class MyTestCase: def test_list_copy(self): """Function is used to test copy of list""" <|body_0|> def test_list_intersect(self): """Function is used to test intersection between two lists""" <|body_1|> def test_list_difference(self): """Function is us...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MyTestCase: def test_list_copy(self): """Function is used to test copy of list""" self.assertEqual(list_copy([7, 8, 9, 10]), [7, 8, 9, 10]) self.assertEqual(list_copy(['Rohan', '6,7,8', 7]), ['Rohan', '6,7,8', 7]) self.assertEqual(list_copy([]), []) self.assertNotEqual(...
the_stack_v2_python_sparse
HW_06_Rohan_Ratwani/HW06_Test_Rohan_Ratwani.py
RohanRatwani/SSW-810
train
0
8d801c45749ab7d46487f78945e58aa10e87c108
[ "if not isinstance(model_grid, RasterModelGrid):\n raise TypeError('model_grid must be a Landlab RasterModelGrid')\nself.number_of_orientations = 2\nsuper().__init__(model_grid, node_state_dict, transition_list, initial_node_states, prop_data, prop_reset_value, seed)", "self.link_orientation = np.zeros(self.gr...
<|body_start_0|> if not isinstance(model_grid, RasterModelGrid): raise TypeError('model_grid must be a Landlab RasterModelGrid') self.number_of_orientations = 2 super().__init__(model_grid, node_state_dict, transition_list, initial_node_states, prop_data, prop_reset_value, seed) <|en...
Oriented raster CellLab-CTS model. RasterCTS constructor: sets number of orientations to 2 and calls base-class constructor. Parameters ---------- model_grid : Landlab ModelGrid object Reference to the model's grid node_state_dict : dict Keys are node-state codes, values are the names associated with these codes transi...
OrientedRasterCTS
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OrientedRasterCTS: """Oriented raster CellLab-CTS model. RasterCTS constructor: sets number of orientations to 2 and calls base-class constructor. Parameters ---------- model_grid : Landlab ModelGrid object Reference to the model's grid node_state_dict : dict Keys are node-state codes, values are...
stack_v2_sparse_classes_36k_train_031016
4,813
permissive
[ { "docstring": "RasterCTS constructor: sets number of orientations to 2 and calls base-class constructor. Parameters ---------- model_grid : Landlab ModelGrid object Reference to the model's grid node_state_dict : dict Keys are node-state codes, values are the names associated with these codes transition_list :...
2
null
Implement the Python class `OrientedRasterCTS` described below. Class description: Oriented raster CellLab-CTS model. RasterCTS constructor: sets number of orientations to 2 and calls base-class constructor. Parameters ---------- model_grid : Landlab ModelGrid object Reference to the model's grid node_state_dict : dic...
Implement the Python class `OrientedRasterCTS` described below. Class description: Oriented raster CellLab-CTS model. RasterCTS constructor: sets number of orientations to 2 and calls base-class constructor. Parameters ---------- model_grid : Landlab ModelGrid object Reference to the model's grid node_state_dict : dic...
1cd72e5832ece1aa922cd1b239e2e94ed0f11f8b
<|skeleton|> class OrientedRasterCTS: """Oriented raster CellLab-CTS model. RasterCTS constructor: sets number of orientations to 2 and calls base-class constructor. Parameters ---------- model_grid : Landlab ModelGrid object Reference to the model's grid node_state_dict : dict Keys are node-state codes, values are...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OrientedRasterCTS: """Oriented raster CellLab-CTS model. RasterCTS constructor: sets number of orientations to 2 and calls base-class constructor. Parameters ---------- model_grid : Landlab ModelGrid object Reference to the model's grid node_state_dict : dict Keys are node-state codes, values are the names as...
the_stack_v2_python_sparse
landlab/ca/oriented_raster_cts.py
landlab/landlab
train
326
b4001cba7380517627fdb854f4ea2af66ce9e553
[ "left = right = max_sum = float('-inf')\nfor a in arr:\n left, right = (max(a, left + a), max(left, right + a))\n max_sum = max(max_sum, right, left)\nreturn max_sum", "n = len(arr)\ndp = [[float('-inf')] * 2 for _ in range(n)]\nres = float('-inf')\nfor i, a in enumerate(arr):\n dp[i][0] = max(a, dp[i - ...
<|body_start_0|> left = right = max_sum = float('-inf') for a in arr: left, right = (max(a, left + a), max(left, right + a)) max_sum = max(max_sum, right, left) return max_sum <|end_body_0|> <|body_start_1|> n = len(arr) dp = [[float('-inf')] * 2 for _ in...
Array
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Array: def maximum_sum(self, arr: List[int]) -> int: """Approach: DP (contant space) Time Complexity: O(N) Space Complexity: O(1) :param arr: :return:""" <|body_0|> def maximum_sum_(self, arr: List[int]) -> int: """Approach: DP Formulae: --------- dp(i,0) = max(arr(i...
stack_v2_sparse_classes_36k_train_031017
2,196
no_license
[ { "docstring": "Approach: DP (contant space) Time Complexity: O(N) Space Complexity: O(1) :param arr: :return:", "name": "maximum_sum", "signature": "def maximum_sum(self, arr: List[int]) -> int" }, { "docstring": "Approach: DP Formulae: --------- dp(i,0) = max(arr(i), dp(i - 1, 0) + arr(i)) dp(...
3
null
Implement the Python class `Array` described below. Class description: Implement the Array class. Method signatures and docstrings: - def maximum_sum(self, arr: List[int]) -> int: Approach: DP (contant space) Time Complexity: O(N) Space Complexity: O(1) :param arr: :return: - def maximum_sum_(self, arr: List[int]) ->...
Implement the Python class `Array` described below. Class description: Implement the Array class. Method signatures and docstrings: - def maximum_sum(self, arr: List[int]) -> int: Approach: DP (contant space) Time Complexity: O(N) Space Complexity: O(1) :param arr: :return: - def maximum_sum_(self, arr: List[int]) ->...
65cc78b5afa0db064f9fe8f06597e3e120f7363d
<|skeleton|> class Array: def maximum_sum(self, arr: List[int]) -> int: """Approach: DP (contant space) Time Complexity: O(N) Space Complexity: O(1) :param arr: :return:""" <|body_0|> def maximum_sum_(self, arr: List[int]) -> int: """Approach: DP Formulae: --------- dp(i,0) = max(arr(i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Array: def maximum_sum(self, arr: List[int]) -> int: """Approach: DP (contant space) Time Complexity: O(N) Space Complexity: O(1) :param arr: :return:""" left = right = max_sum = float('-inf') for a in arr: left, right = (max(a, left + a), max(left, right + a)) ...
the_stack_v2_python_sparse
revisited_2021/arrays/max_sub_sum_with_one_deletion.py
Shiv2157k/leet_code
train
1
fe1b68be12c5b5606e3c516dd1543be259d091e3
[ "data_list = []\nresults = self.query.all()\nformatter = self.request.locale.dates.getFormatter('date', 'short')\nfor result in results:\n data = {}\n data['qid'] = 'i-' + str(result.parliamentary_item_id)\n if type(result) == domain.AgendaItem:\n g = u' ' + result.group.type + u' ' + result.group.s...
<|body_start_0|> data_list = [] results = self.query.all() formatter = self.request.locale.dates.getFormatter('date', 'short') for result in results: data = {} data['qid'] = 'i-' + str(result.parliamentary_item_id) if type(result) == domain.AgendaItem:...
Group parliamentary items per stage: e.g. action required, in progress, answered/debated, 'dead' (withdrawn, elapsed, inadmissible)
ItemInStageViewlet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ItemInStageViewlet: """Group parliamentary items per stage: e.g. action required, in progress, answered/debated, 'dead' (withdrawn, elapsed, inadmissible)""" def getData(self): """return the data of the query""" <|body_0|> def update(self): """refresh the query""...
stack_v2_sparse_classes_36k_train_031018
35,739
no_license
[ { "docstring": "return the data of the query", "name": "getData", "signature": "def getData(self)" }, { "docstring": "refresh the query", "name": "update", "signature": "def update(self)" } ]
2
stack_v2_sparse_classes_30k_train_019543
Implement the Python class `ItemInStageViewlet` described below. Class description: Group parliamentary items per stage: e.g. action required, in progress, answered/debated, 'dead' (withdrawn, elapsed, inadmissible) Method signatures and docstrings: - def getData(self): return the data of the query - def update(self)...
Implement the Python class `ItemInStageViewlet` described below. Class description: Group parliamentary items per stage: e.g. action required, in progress, answered/debated, 'dead' (withdrawn, elapsed, inadmissible) Method signatures and docstrings: - def getData(self): return the data of the query - def update(self)...
5cf0ba31dfbff8d2c1b4aa8ab6f69c7a0ae9870d
<|skeleton|> class ItemInStageViewlet: """Group parliamentary items per stage: e.g. action required, in progress, answered/debated, 'dead' (withdrawn, elapsed, inadmissible)""" def getData(self): """return the data of the query""" <|body_0|> def update(self): """refresh the query""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ItemInStageViewlet: """Group parliamentary items per stage: e.g. action required, in progress, answered/debated, 'dead' (withdrawn, elapsed, inadmissible)""" def getData(self): """return the data of the query""" data_list = [] results = self.query.all() formatter = self.re...
the_stack_v2_python_sparse
bungeni.buildout/branches/bungeni.buildout-refactor-2010-06-02/src/bungeni.main/bungeni/ui/viewlets/workspace.py
malangalanga/bungeni-portal
train
0
06c1a0d84c8db317d092edc8460a589020d15641
[ "context = super().get_context_data(**kwargs)\ncontext['key'], _ = list(self.workflow.attributes.items())[kwargs['pk']]\nreturn context", "wf_attributes = self.workflow.attributes\nkey = sorted(wf_attributes.keys())[kwargs['pk']]\nwf_attributes.pop(key, None)\nself.workflow.attributes = wf_attributes\nself.workfl...
<|body_start_0|> context = super().get_context_data(**kwargs) context['key'], _ = list(self.workflow.attributes.items())[kwargs['pk']] return context <|end_body_0|> <|body_start_1|> wf_attributes = self.workflow.attributes key = sorted(wf_attributes.keys())[kwargs['pk']] ...
View to delete an existing attribute in a workflow.
WorkflowAttributeDeleteView
[ "LGPL-2.0-or-later", "BSD-3-Clause", "MIT", "Apache-2.0", "LGPL-2.1-only", "Python-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WorkflowAttributeDeleteView: """View to delete an existing attribute in a workflow.""" def get_context_data(self, **kwargs): """Add pk and the key name to the context.""" <|body_0|> def post(self, request, *args, **kwargs): """Perform the attribute delete operati...
stack_v2_sparse_classes_36k_train_031019
2,934
permissive
[ { "docstring": "Add pk and the key name to the context.", "name": "get_context_data", "signature": "def get_context_data(self, **kwargs)" }, { "docstring": "Perform the attribute delete operation.", "name": "post", "signature": "def post(self, request, *args, **kwargs)" } ]
2
null
Implement the Python class `WorkflowAttributeDeleteView` described below. Class description: View to delete an existing attribute in a workflow. Method signatures and docstrings: - def get_context_data(self, **kwargs): Add pk and the key name to the context. - def post(self, request, *args, **kwargs): Perform the att...
Implement the Python class `WorkflowAttributeDeleteView` described below. Class description: View to delete an existing attribute in a workflow. Method signatures and docstrings: - def get_context_data(self, **kwargs): Add pk and the key name to the context. - def post(self, request, *args, **kwargs): Perform the att...
c432745dfff932cbe7397100422d49df78f0a882
<|skeleton|> class WorkflowAttributeDeleteView: """View to delete an existing attribute in a workflow.""" def get_context_data(self, **kwargs): """Add pk and the key name to the context.""" <|body_0|> def post(self, request, *args, **kwargs): """Perform the attribute delete operati...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WorkflowAttributeDeleteView: """View to delete an existing attribute in a workflow.""" def get_context_data(self, **kwargs): """Add pk and the key name to the context.""" context = super().get_context_data(**kwargs) context['key'], _ = list(self.workflow.attributes.items())[kwargs...
the_stack_v2_python_sparse
ontask/workflow/views/attribute.py
abelardopardo/ontask_b
train
43
671849ab2adf46447ae6df8a0ff3220cc0aaa574
[ "self.window = window\nworkspace = window.application.get_service(IWorkspace)\nself.pages = [ProjectWizardPage(id='project_page', location=workspace.absolute_path)]\nsuper(ProjectWizard, self).__init__(**traits)", "workspace = self.window.application.get_service(IWorkspace)\npwp = self.pages[0]\nproject = workspa...
<|body_start_0|> self.window = window workspace = window.application.get_service(IWorkspace) self.pages = [ProjectWizardPage(id='project_page', location=workspace.absolute_path)] super(ProjectWizard, self).__init__(**traits) <|end_body_0|> <|body_start_1|> workspace = self.windo...
A wizard for project creation.
ProjectWizard
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProjectWizard: """A wizard for project creation.""" def __init__(self, window, **traits): """Returns a ProjectWizard.""" <|body_0|> def _finished_fired(self): """Performs the project resource creation if the wizard is finished successfully.""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_031020
7,796
permissive
[ { "docstring": "Returns a ProjectWizard.", "name": "__init__", "signature": "def __init__(self, window, **traits)" }, { "docstring": "Performs the project resource creation if the wizard is finished successfully.", "name": "_finished_fired", "signature": "def _finished_fired(self)" } ]
2
null
Implement the Python class `ProjectWizard` described below. Class description: A wizard for project creation. Method signatures and docstrings: - def __init__(self, window, **traits): Returns a ProjectWizard. - def _finished_fired(self): Performs the project resource creation if the wizard is finished successfully.
Implement the Python class `ProjectWizard` described below. Class description: A wizard for project creation. Method signatures and docstrings: - def __init__(self, window, **traits): Returns a ProjectWizard. - def _finished_fired(self): Performs the project resource creation if the wizard is finished successfully. ...
e8fc0b2d6b9b08e60389fc4714a5cf51f628b57f
<|skeleton|> class ProjectWizard: """A wizard for project creation.""" def __init__(self, window, **traits): """Returns a ProjectWizard.""" <|body_0|> def _finished_fired(self): """Performs the project resource creation if the wizard is finished successfully.""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProjectWizard: """A wizard for project creation.""" def __init__(self, window, **traits): """Returns a ProjectWizard.""" self.window = window workspace = window.application.get_service(IWorkspace) self.pages = [ProjectWizardPage(id='project_page', location=workspace.absolu...
the_stack_v2_python_sparse
puddle/resource/wizard/project_wizard.py
rwl/puddle
train
2
38c276fda97a8f5b43ee444929d3c7103c8e2d6e
[ "if categories_filter is None:\n categories_filter = {'Default': IMultiprocessChildPlugin}\nPluginManager.__init__(self, categories_filter=categories_filter, directories_list=directories_list, plugin_info_ext=plugin_info_ext, plugin_locator=plugin_locator)", "instanciated_element = MultiprocessPluginProxy()\np...
<|body_start_0|> if categories_filter is None: categories_filter = {'Default': IMultiprocessChildPlugin} PluginManager.__init__(self, categories_filter=categories_filter, directories_list=directories_list, plugin_info_ext=plugin_info_ext, plugin_locator=plugin_locator) <|end_body_0|> <|body...
Subclass of the PluginManager that runs each plugin in a different process
MultiprocessPluginManager
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiprocessPluginManager: """Subclass of the PluginManager that runs each plugin in a different process""" def __init__(self, categories_filter=None, directories_list=None, plugin_info_ext=None, plugin_locator=None): """init""" <|body_0|> def instanciateElement(self, el...
stack_v2_sparse_classes_36k_train_031021
1,628
permissive
[ { "docstring": "init", "name": "__init__", "signature": "def __init__(self, categories_filter=None, directories_list=None, plugin_info_ext=None, plugin_locator=None)" }, { "docstring": "This method instanciate each plugin in a new process and link it to the parent with a pipe. In the parent proc...
2
stack_v2_sparse_classes_30k_train_003563
Implement the Python class `MultiprocessPluginManager` described below. Class description: Subclass of the PluginManager that runs each plugin in a different process Method signatures and docstrings: - def __init__(self, categories_filter=None, directories_list=None, plugin_info_ext=None, plugin_locator=None): init -...
Implement the Python class `MultiprocessPluginManager` described below. Class description: Subclass of the PluginManager that runs each plugin in a different process Method signatures and docstrings: - def __init__(self, categories_filter=None, directories_list=None, plugin_info_ext=None, plugin_locator=None): init -...
7c3d9e975dae3835e2ccf42c425d65b26466e82a
<|skeleton|> class MultiprocessPluginManager: """Subclass of the PluginManager that runs each plugin in a different process""" def __init__(self, categories_filter=None, directories_list=None, plugin_info_ext=None, plugin_locator=None): """init""" <|body_0|> def instanciateElement(self, el...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultiprocessPluginManager: """Subclass of the PluginManager that runs each plugin in a different process""" def __init__(self, categories_filter=None, directories_list=None, plugin_info_ext=None, plugin_locator=None): """init""" if categories_filter is None: categories_filter ...
the_stack_v2_python_sparse
venv/lib/python2.7/site-packages/yapsy/MultiprocessPluginManager.py
WhySoGeeky/DroidPot
train
6
8202b65efd2e9414410d73fc04decc39c5fd5749
[ "self.graph = graph\nself.distance = dict()\nfor source in self.graph.iternodes():\n self.distance[source] = dict()\n for target in self.graph.iternodes():\n self.distance[source][target] = float('inf')\n self.distance[source][source] = 0\nif self.graph.is_directed():\n for edge in self.graph.ite...
<|body_start_0|> self.graph = graph self.distance = dict() for source in self.graph.iternodes(): self.distance[source] = dict() for target in self.graph.iternodes(): self.distance[source][target] = float('inf') self.distance[source][source] = 0...
The Floyd-Warshall algorithm, nonnegative edge weights. Negative cycles are forbidden. Attributes ---------- graph : input weighted graph (directed or undirected) distance : dict-of-dict Examples -------- >>> from graphtheory.structures.edges import Edge >>> from graphtheory.structures.graphs import Graph >>> from grap...
FloydWarshallAllGraphs
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FloydWarshallAllGraphs: """The Floyd-Warshall algorithm, nonnegative edge weights. Negative cycles are forbidden. Attributes ---------- graph : input weighted graph (directed or undirected) distance : dict-of-dict Examples -------- >>> from graphtheory.structures.edges import Edge >>> from grapht...
stack_v2_sparse_classes_36k_train_031022
7,754
permissive
[ { "docstring": "The algorithm initialization. Parameters ---------- graph : directed or undirected weighted graph", "name": "__init__", "signature": "def __init__(self, graph)" }, { "docstring": "Finding all shortest paths.", "name": "run", "signature": "def run(self)" } ]
2
stack_v2_sparse_classes_30k_train_019603
Implement the Python class `FloydWarshallAllGraphs` described below. Class description: The Floyd-Warshall algorithm, nonnegative edge weights. Negative cycles are forbidden. Attributes ---------- graph : input weighted graph (directed or undirected) distance : dict-of-dict Examples -------- >>> from graphtheory.struc...
Implement the Python class `FloydWarshallAllGraphs` described below. Class description: The Floyd-Warshall algorithm, nonnegative edge weights. Negative cycles are forbidden. Attributes ---------- graph : input weighted graph (directed or undirected) distance : dict-of-dict Examples -------- >>> from graphtheory.struc...
0ff4ae303e8824e6bb8474d23b29a7b3e5ed8e60
<|skeleton|> class FloydWarshallAllGraphs: """The Floyd-Warshall algorithm, nonnegative edge weights. Negative cycles are forbidden. Attributes ---------- graph : input weighted graph (directed or undirected) distance : dict-of-dict Examples -------- >>> from graphtheory.structures.edges import Edge >>> from grapht...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FloydWarshallAllGraphs: """The Floyd-Warshall algorithm, nonnegative edge weights. Negative cycles are forbidden. Attributes ---------- graph : input weighted graph (directed or undirected) distance : dict-of-dict Examples -------- >>> from graphtheory.structures.edges import Edge >>> from graphtheory.structu...
the_stack_v2_python_sparse
graphtheory/shortestpaths/floydwarshall.py
kgashok/graphs-dict
train
0
903e295630fefb53f60a3ce3ada21975eb918d51
[ "tree = deepcopy(obj.__dict__)\npath = tree.pop('path', None)\nbuffer = tree.pop('buffer', None)\nsave_content = tree.pop('asdf_save_content')\nalgorithm = tree.pop('hashing_algorithm')\nhash_value = tree.pop('hash')\nif save_content:\n if buffer is None:\n buffer = obj.get_file_content()\n tree['conte...
<|body_start_0|> tree = deepcopy(obj.__dict__) path = tree.pop('path', None) buffer = tree.pop('buffer', None) save_content = tree.pop('asdf_save_content') algorithm = tree.pop('hashing_algorithm') hash_value = tree.pop('hash') if save_content: if buff...
Serialization class for `weldx.core.ExternalFile`.
ExternalFileConverter
[ "BSD-3-Clause", "LicenseRef-scancode-free-unknown" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExternalFileConverter: """Serialization class for `weldx.core.ExternalFile`.""" def to_yaml_tree(self, obj: ExternalFile, tag: str, ctx) -> dict: """Convert to python dict.""" <|body_0|> def from_yaml_tree(self, node: dict, tag: str, ctx): """Construct from tree....
stack_v2_sparse_classes_36k_train_031023
2,357
permissive
[ { "docstring": "Convert to python dict.", "name": "to_yaml_tree", "signature": "def to_yaml_tree(self, obj: ExternalFile, tag: str, ctx) -> dict" }, { "docstring": "Construct from tree.", "name": "from_yaml_tree", "signature": "def from_yaml_tree(self, node: dict, tag: str, ctx)" } ]
2
null
Implement the Python class `ExternalFileConverter` described below. Class description: Serialization class for `weldx.core.ExternalFile`. Method signatures and docstrings: - def to_yaml_tree(self, obj: ExternalFile, tag: str, ctx) -> dict: Convert to python dict. - def from_yaml_tree(self, node: dict, tag: str, ctx):...
Implement the Python class `ExternalFileConverter` described below. Class description: Serialization class for `weldx.core.ExternalFile`. Method signatures and docstrings: - def to_yaml_tree(self, obj: ExternalFile, tag: str, ctx) -> dict: Convert to python dict. - def from_yaml_tree(self, node: dict, tag: str, ctx):...
7bc16a196ee669822f3663f3c7a08f6bbd0c76d5
<|skeleton|> class ExternalFileConverter: """Serialization class for `weldx.core.ExternalFile`.""" def to_yaml_tree(self, obj: ExternalFile, tag: str, ctx) -> dict: """Convert to python dict.""" <|body_0|> def from_yaml_tree(self, node: dict, tag: str, ctx): """Construct from tree....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ExternalFileConverter: """Serialization class for `weldx.core.ExternalFile`.""" def to_yaml_tree(self, obj: ExternalFile, tag: str, ctx) -> dict: """Convert to python dict.""" tree = deepcopy(obj.__dict__) path = tree.pop('path', None) buffer = tree.pop('buffer', None) ...
the_stack_v2_python_sparse
weldx/tags/core/file.py
BAMWelDX/weldx
train
20
a8177b63ea2691590ff458a622d3e25a401bfa99
[ "if not root or root == p or root == q:\n return root\nleft = self.lowestCommonAncestor(root.left, p, q)\nright = self.lowestCommonAncestor(root.right, p, q)\nif not left:\n return right\nif not right:\n return left\nif left and right:\n return root\nreturn None", "if not root or root == p or root == ...
<|body_start_0|> if not root or root == p or root == q: return root left = self.lowestCommonAncestor(root.left, p, q) right = self.lowestCommonAncestor(root.right, p, q) if not left: return right if not right: return left if left and ri...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': """1、读题:节点值唯一,p、q不同节点均存在二叉树,求二者的最近公共祖先,可能为自己。 2、思路: 递归、分治: 1)从根节点出发,记录每个节点找到p或者q的状态然后往父节点传。 2)找p或者q都可以返回的逻辑是: 2.1 找到一个节点p(或者q),就确定了该节点一定与最终结果有关: 2.1.1 p是最终结果,比如找到p,包含了后裔节点q,此时返回了p。 2.1...
stack_v2_sparse_classes_36k_train_031024
2,380
no_license
[ { "docstring": "1、读题:节点值唯一,p、q不同节点均存在二叉树,求二者的最近公共祖先,可能为自己。 2、思路: 递归、分治: 1)从根节点出发,记录每个节点找到p或者q的状态然后往父节点传。 2)找p或者q都可以返回的逻辑是: 2.1 找到一个节点p(或者q),就确定了该节点一定与最终结果有关: 2.1.1 p是最终结果,比如找到p,包含了后裔节点q,此时返回了p。 2.1.2 p不是最终结果,返回该节点的结果后,通过q节点的返回结果合并即可找到最终结果。", "name": "lowestCommonAncestor", "signature": "def lowestCommon...
2
stack_v2_sparse_classes_30k_train_013297
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 1、读题:节点值唯一,p、q不同节点均存在二叉树,求二者的最近公共祖先,可能为自己。 2、思路: 递归、分治: 1)从根节点出发,记录每个节点找到p或者q的状态然后往父...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 1、读题:节点值唯一,p、q不同节点均存在二叉树,求二者的最近公共祖先,可能为自己。 2、思路: 递归、分治: 1)从根节点出发,记录每个节点找到p或者q的状态然后往父...
7fde3c1dddf8ca6b89924ca13d0aa5ffc03a1545
<|skeleton|> class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': """1、读题:节点值唯一,p、q不同节点均存在二叉树,求二者的最近公共祖先,可能为自己。 2、思路: 递归、分治: 1)从根节点出发,记录每个节点找到p或者q的状态然后往父节点传。 2)找p或者q都可以返回的逻辑是: 2.1 找到一个节点p(或者q),就确定了该节点一定与最终结果有关: 2.1.1 p是最终结果,比如找到p,包含了后裔节点q,此时返回了p。 2.1...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': """1、读题:节点值唯一,p、q不同节点均存在二叉树,求二者的最近公共祖先,可能为自己。 2、思路: 递归、分治: 1)从根节点出发,记录每个节点找到p或者q的状态然后往父节点传。 2)找p或者q都可以返回的逻辑是: 2.1 找到一个节点p(或者q),就确定了该节点一定与最终结果有关: 2.1.1 p是最终结果,比如找到p,包含了后裔节点q,此时返回了p。 2.1.2 p不是最终结果,返回该...
the_stack_v2_python_sparse
Week_03/236.lowest-common-ancestor-of-a-binary-tree.py
liubio0/algorithm022
train
0
9f2bccb03081cbc1a28beaa34f1547455e602dd9
[ "threading.Thread.__init__(self)\nself.daemon = True\nself.queue = queue\nself.processedUrls = processedUrls\nself.selectedDomains = selectedDomains\nself.selectedUrls = selectedUrls\nself.baseFileName = baseFileName\nself.parseTimeout = parseTimeout", "global parseCancelled\nstartTime = time.time()\nlastActionTi...
<|body_start_0|> threading.Thread.__init__(self) self.daemon = True self.queue = queue self.processedUrls = processedUrls self.selectedDomains = selectedDomains self.selectedUrls = selectedUrls self.baseFileName = baseFileName self.parseTimeout = parseTime...
SpiderMonitor
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SpiderMonitor: def __init__(self, queue, processedUrls, selectedDomains, selectedUrls, baseFileName, parseTimeout): """Инициализация""" <|body_0|> def run(self): """Каждые 5 секунд сохраняем базу в файл и выводим текущую информацию. По истечении тайматута завершаем в...
stack_v2_sparse_classes_36k_train_031025
5,227
no_license
[ { "docstring": "Инициализация", "name": "__init__", "signature": "def __init__(self, queue, processedUrls, selectedDomains, selectedUrls, baseFileName, parseTimeout)" }, { "docstring": "Каждые 5 секунд сохраняем базу в файл и выводим текущую информацию. По истечении тайматута завершаем выполнени...
2
stack_v2_sparse_classes_30k_train_010093
Implement the Python class `SpiderMonitor` described below. Class description: Implement the SpiderMonitor class. Method signatures and docstrings: - def __init__(self, queue, processedUrls, selectedDomains, selectedUrls, baseFileName, parseTimeout): Инициализация - def run(self): Каждые 5 секунд сохраняем базу в фай...
Implement the Python class `SpiderMonitor` described below. Class description: Implement the SpiderMonitor class. Method signatures and docstrings: - def __init__(self, queue, processedUrls, selectedDomains, selectedUrls, baseFileName, parseTimeout): Инициализация - def run(self): Каждые 5 секунд сохраняем базу в фай...
d2771bf04aa187dda6d468883a5a167237589369
<|skeleton|> class SpiderMonitor: def __init__(self, queue, processedUrls, selectedDomains, selectedUrls, baseFileName, parseTimeout): """Инициализация""" <|body_0|> def run(self): """Каждые 5 секунд сохраняем базу в файл и выводим текущую информацию. По истечении тайматута завершаем в...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SpiderMonitor: def __init__(self, queue, processedUrls, selectedDomains, selectedUrls, baseFileName, parseTimeout): """Инициализация""" threading.Thread.__init__(self) self.daemon = True self.queue = queue self.processedUrls = processedUrls self.selectedDomains ...
the_stack_v2_python_sparse
doorsagents/baseparser.py
cash2one/doorscenter
train
0
8fd103c2892d529f5fd66ed603ad285900c9f5c9
[ "nbm = self.notebook_manager\ncheckpoints = nbm.list_checkpoints(notebook_id)\ndata = jsonapi.dumps(checkpoints, default=date_default)\nself.finish(data)", "nbm = self.notebook_manager\ncheckpoint = nbm.create_checkpoint(notebook_id)\ndata = jsonapi.dumps(checkpoint, default=date_default)\nself.set_header('Locati...
<|body_start_0|> nbm = self.notebook_manager checkpoints = nbm.list_checkpoints(notebook_id) data = jsonapi.dumps(checkpoints, default=date_default) self.finish(data) <|end_body_0|> <|body_start_1|> nbm = self.notebook_manager checkpoint = nbm.create_checkpoint(notebook_...
NotebookCheckpointsHandler
[ "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-unknown" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NotebookCheckpointsHandler: def get(self, notebook_id): """get lists checkpoints for a notebook""" <|body_0|> def post(self, notebook_id): """post creates a new checkpoint""" <|body_1|> <|end_skeleton|> <|body_start_0|> nbm = self.notebook_manager ...
stack_v2_sparse_classes_36k_train_031026
5,267
permissive
[ { "docstring": "get lists checkpoints for a notebook", "name": "get", "signature": "def get(self, notebook_id)" }, { "docstring": "post creates a new checkpoint", "name": "post", "signature": "def post(self, notebook_id)" } ]
2
stack_v2_sparse_classes_30k_train_005772
Implement the Python class `NotebookCheckpointsHandler` described below. Class description: Implement the NotebookCheckpointsHandler class. Method signatures and docstrings: - def get(self, notebook_id): get lists checkpoints for a notebook - def post(self, notebook_id): post creates a new checkpoint
Implement the Python class `NotebookCheckpointsHandler` described below. Class description: Implement the NotebookCheckpointsHandler class. Method signatures and docstrings: - def get(self, notebook_id): get lists checkpoints for a notebook - def post(self, notebook_id): post creates a new checkpoint <|skeleton|> cl...
2c9002f16bb5c265e0d14f4a2314c86eeaa35cb6
<|skeleton|> class NotebookCheckpointsHandler: def get(self, notebook_id): """get lists checkpoints for a notebook""" <|body_0|> def post(self, notebook_id): """post creates a new checkpoint""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NotebookCheckpointsHandler: def get(self, notebook_id): """get lists checkpoints for a notebook""" nbm = self.notebook_manager checkpoints = nbm.list_checkpoints(notebook_id) data = jsonapi.dumps(checkpoints, default=date_default) self.finish(data) def post(self, n...
the_stack_v2_python_sparse
pkgs/ipython-1.2.1-py27_0/lib/python2.7/site-packages/IPython/html/services/notebooks/handlers.py
wangyum/Anaconda
train
11
72b4cb5b5edc245b3a7cd791a5beba5b5c960e7b
[ "stock = StockModel.query.filter_by(id=stock_id).first()\nif not stock:\n stock_api.abort(404, 'Stock {} not found'.format(stock_id))\nelse:\n return stock", "stock = StockModel.query.filter_by(id=stock_id).first()\nif not stock:\n stock_api.abort(404, 'Stock {} not found'.format(stock_id))\nstock.delete...
<|body_start_0|> stock = StockModel.query.filter_by(id=stock_id).first() if not stock: stock_api.abort(404, 'Stock {} not found'.format(stock_id)) else: return stock <|end_body_0|> <|body_start_1|> stock = StockModel.query.filter_by(id=stock_id).first() i...
Stock
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Stock: def get(self, stock_id): """Get a stock given its identifier""" <|body_0|> def delete(self, stock_id): """Delete a stock given its identifier""" <|body_1|> def put(self, stock_id): """Update a stock given its identifier""" <|body_2...
stack_v2_sparse_classes_36k_train_031027
3,211
no_license
[ { "docstring": "Get a stock given its identifier", "name": "get", "signature": "def get(self, stock_id)" }, { "docstring": "Delete a stock given its identifier", "name": "delete", "signature": "def delete(self, stock_id)" }, { "docstring": "Update a stock given its identifier", ...
3
stack_v2_sparse_classes_30k_train_014588
Implement the Python class `Stock` described below. Class description: Implement the Stock class. Method signatures and docstrings: - def get(self, stock_id): Get a stock given its identifier - def delete(self, stock_id): Delete a stock given its identifier - def put(self, stock_id): Update a stock given its identifi...
Implement the Python class `Stock` described below. Class description: Implement the Stock class. Method signatures and docstrings: - def get(self, stock_id): Get a stock given its identifier - def delete(self, stock_id): Delete a stock given its identifier - def put(self, stock_id): Update a stock given its identifi...
f380164e92b70874042364ad4b5b20c5793d6921
<|skeleton|> class Stock: def get(self, stock_id): """Get a stock given its identifier""" <|body_0|> def delete(self, stock_id): """Delete a stock given its identifier""" <|body_1|> def put(self, stock_id): """Update a stock given its identifier""" <|body_2...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Stock: def get(self, stock_id): """Get a stock given its identifier""" stock = StockModel.query.filter_by(id=stock_id).first() if not stock: stock_api.abort(404, 'Stock {} not found'.format(stock_id)) else: return stock def delete(self, stock_id): ...
the_stack_v2_python_sparse
project/app/main/controllers/stock.py
ArielVilleda/docker-flask-postgres
train
0
cbf1708b5a64a01c4426122e5f958f52d22f31c3
[ "record = set()\nj = i = 0\nmaxlth = 0\nwhile i < len(s) and j < len(s):\n if s[j] not in record:\n record.add(s[j])\n j += 1\n maxlth = max(maxlth, j - i)\n else:\n record.remove(s[i])\n i += 1\nreturn maxlth", "record = collections.Counter()\ni = 0\nmaxlth = 0\nfor j in ...
<|body_start_0|> record = set() j = i = 0 maxlth = 0 while i < len(s) and j < len(s): if s[j] not in record: record.add(s[j]) j += 1 maxlth = max(maxlth, j - i) else: record.remove(s[i]) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def lengthOfLongestSubstring_1(self, s): """:type s: str :rtype: int""" <|body_0|> def lengthOfLongestSubstring_2(self, s): """:type s: str :rtype: int""" <|body_1|> def lengthOfLongestSubstring_3(self, s): """:type s: str :rtype: int""...
stack_v2_sparse_classes_36k_train_031028
2,038
no_license
[ { "docstring": ":type s: str :rtype: int", "name": "lengthOfLongestSubstring_1", "signature": "def lengthOfLongestSubstring_1(self, s)" }, { "docstring": ":type s: str :rtype: int", "name": "lengthOfLongestSubstring_2", "signature": "def lengthOfLongestSubstring_2(self, s)" }, { ...
4
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def lengthOfLongestSubstring_1(self, s): :type s: str :rtype: int - def lengthOfLongestSubstring_2(self, s): :type s: str :rtype: int - def lengthOfLongestSubstring_3(self, s): :...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def lengthOfLongestSubstring_1(self, s): :type s: str :rtype: int - def lengthOfLongestSubstring_2(self, s): :type s: str :rtype: int - def lengthOfLongestSubstring_3(self, s): :...
0e99f9a5226507706b3ee66fd04bae813755ef40
<|skeleton|> class Solution: def lengthOfLongestSubstring_1(self, s): """:type s: str :rtype: int""" <|body_0|> def lengthOfLongestSubstring_2(self, s): """:type s: str :rtype: int""" <|body_1|> def lengthOfLongestSubstring_3(self, s): """:type s: str :rtype: int""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def lengthOfLongestSubstring_1(self, s): """:type s: str :rtype: int""" record = set() j = i = 0 maxlth = 0 while i < len(s) and j < len(s): if s[j] not in record: record.add(s[j]) j += 1 maxlth = max...
the_stack_v2_python_sparse
medium/twopointer/test_3_Longest_Substring_Without_Repeating_Characters.py
wuxu1019/leetcode_sophia
train
1
518f3d02e49c396960bcde24a98ffc6ff8d6b94e
[ "super(PlainParamsFile, self).__init__(path)\nlines = self.read().split('\\n')\nlines = (l.strip() for l in lines)\nself._lines = [l for l in lines if l and (not l.startswith('#'))]\nself._names = get_names(self._lines)", "info = {}\nfor line in self._lines:\n key, value = get_key_value(line)\n info[key] = ...
<|body_start_0|> super(PlainParamsFile, self).__init__(path) lines = self.read().split('\n') lines = (l.strip() for l in lines) self._lines = [l for l in lines if l and (not l.startswith('#'))] self._names = get_names(self._lines) <|end_body_0|> <|body_start_1|> info = {...
.
PlainParamsFile
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PlainParamsFile: """.""" def __init__(self, path): """.""" <|body_0|> def get_info(self): """.""" <|body_1|> <|end_skeleton|> <|body_start_0|> super(PlainParamsFile, self).__init__(path) lines = self.read().split('\n') lines = (l...
stack_v2_sparse_classes_36k_train_031029
7,197
permissive
[ { "docstring": ".", "name": "__init__", "signature": "def __init__(self, path)" }, { "docstring": ".", "name": "get_info", "signature": "def get_info(self)" } ]
2
stack_v2_sparse_classes_30k_train_003199
Implement the Python class `PlainParamsFile` described below. Class description: . Method signatures and docstrings: - def __init__(self, path): . - def get_info(self): .
Implement the Python class `PlainParamsFile` described below. Class description: . Method signatures and docstrings: - def __init__(self, path): . - def get_info(self): . <|skeleton|> class PlainParamsFile: """.""" def __init__(self, path): """.""" <|body_0|> def get_info(self): ...
a94831cd1bf40a59587a7b6cc2e9b5c4306b1bf2
<|skeleton|> class PlainParamsFile: """.""" def __init__(self, path): """.""" <|body_0|> def get_info(self): """.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PlainParamsFile: """.""" def __init__(self, path): """.""" super(PlainParamsFile, self).__init__(path) lines = self.read().split('\n') lines = (l.strip() for l in lines) self._lines = [l for l in lines if l and (not l.startswith('#'))] self._names = get_nam...
the_stack_v2_python_sparse
libs/base_utils/plain_params_file.py
RichardWeng/Stino
train
0
c704ba7e09d5b635926f3f81fe2620e89f8f5c84
[ "self.src = src\nself.dst = dst\nself.smtp = None\nself.default_message = 'Your post processsing job has completed successfully'\nself.default_status = 'SUCCEESS'", "if not msg:\n msg = self.default_message\nif not status:\n status = self.default_status\nself.smtp = smtplib.SMTP('localhost')\nmessage = MIME...
<|body_start_0|> self.src = src self.dst = dst self.smtp = None self.default_message = 'Your post processsing job has completed successfully' self.default_status = 'SUCCEESS' <|end_body_0|> <|body_start_1|> if not msg: msg = self.default_message if no...
A simple class for sending email
Mailer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Mailer: """A simple class for sending email""" def __init__(self, src, dst): """Initialize the mailer with source = src and destination = dst Parameters: src (str): the source email address dst (str): the destination email address""" <|body_0|> def send(self, status=None...
stack_v2_sparse_classes_36k_train_031030
1,584
permissive
[ { "docstring": "Initialize the mailer with source = src and destination = dst Parameters: src (str): the source email address dst (str): the destination email address", "name": "__init__", "signature": "def __init__(self, src, dst)" }, { "docstring": "Send the email with contents = msg and subje...
2
stack_v2_sparse_classes_30k_train_018189
Implement the Python class `Mailer` described below. Class description: A simple class for sending email Method signatures and docstrings: - def __init__(self, src, dst): Initialize the mailer with source = src and destination = dst Parameters: src (str): the source email address dst (str): the destination email addr...
Implement the Python class `Mailer` described below. Class description: A simple class for sending email Method signatures and docstrings: - def __init__(self, src, dst): Initialize the mailer with source = src and destination = dst Parameters: src (str): the source email address dst (str): the destination email addr...
84110cab08f7897d1489a6dc925258580a5d2bff
<|skeleton|> class Mailer: """A simple class for sending email""" def __init__(self, src, dst): """Initialize the mailer with source = src and destination = dst Parameters: src (str): the source email address dst (str): the destination email address""" <|body_0|> def send(self, status=None...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Mailer: """A simple class for sending email""" def __init__(self, src, dst): """Initialize the mailer with source = src and destination = dst Parameters: src (str): the source email address dst (str): the destination email address""" self.src = src self.dst = dst self.smtp...
the_stack_v2_python_sparse
processflow/lib/mailer.py
E3SM-Project/processflow
train
4
2619c35a0c04efc0995553f410c5c4bc14682c75
[ "dp_max = [nums[0]] * len(nums)\ndp_min = [nums[0]] * len(nums)\nfor i in range(1, len(nums)):\n dp_max[i] = max(dp_max[i - 1] * nums[i], dp_min[i - 1] * nums[i], nums[i])\n dp_min[i] = min(dp_max[i - 1] * nums[i], dp_min[i - 1] * nums[i], nums[i])\nreturn max(dp_max)", "max_now = min_now = max_prodcut = nu...
<|body_start_0|> dp_max = [nums[0]] * len(nums) dp_min = [nums[0]] * len(nums) for i in range(1, len(nums)): dp_max[i] = max(dp_max[i - 1] * nums[i], dp_min[i - 1] * nums[i], nums[i]) dp_min[i] = min(dp_max[i - 1] * nums[i], dp_min[i - 1] * nums[i], nums[i]) retur...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxProduct1(self, nums: List[int]) -> int: """dp[i]记录num[i]的最优解。 由于存在负数,会导致最大的变最小的,最小的变最大的。 所以维护两个数组,分别记录最大值和最小值。""" <|body_0|> def maxProduct2(self, nums: List[int]) -> int: """Kadane算法,类似053题解。 无需记录所有的dp,只需记录前一个最优解即可。""" <|body_1|> <|end_skel...
stack_v2_sparse_classes_36k_train_031031
2,021
no_license
[ { "docstring": "dp[i]记录num[i]的最优解。 由于存在负数,会导致最大的变最小的,最小的变最大的。 所以维护两个数组,分别记录最大值和最小值。", "name": "maxProduct1", "signature": "def maxProduct1(self, nums: List[int]) -> int" }, { "docstring": "Kadane算法,类似053题解。 无需记录所有的dp,只需记录前一个最优解即可。", "name": "maxProduct2", "signature": "def maxProduct2(se...
2
stack_v2_sparse_classes_30k_train_010661
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProduct1(self, nums: List[int]) -> int: dp[i]记录num[i]的最优解。 由于存在负数,会导致最大的变最小的,最小的变最大的。 所以维护两个数组,分别记录最大值和最小值。 - def maxProduct2(self, nums: List[int]) -> int: Kadane算法,类似053...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProduct1(self, nums: List[int]) -> int: dp[i]记录num[i]的最优解。 由于存在负数,会导致最大的变最小的,最小的变最大的。 所以维护两个数组,分别记录最大值和最小值。 - def maxProduct2(self, nums: List[int]) -> int: Kadane算法,类似053...
2bbb1640589aab34f2bc42489283033cc11fb885
<|skeleton|> class Solution: def maxProduct1(self, nums: List[int]) -> int: """dp[i]记录num[i]的最优解。 由于存在负数,会导致最大的变最小的,最小的变最大的。 所以维护两个数组,分别记录最大值和最小值。""" <|body_0|> def maxProduct2(self, nums: List[int]) -> int: """Kadane算法,类似053题解。 无需记录所有的dp,只需记录前一个最优解即可。""" <|body_1|> <|end_skel...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxProduct1(self, nums: List[int]) -> int: """dp[i]记录num[i]的最优解。 由于存在负数,会导致最大的变最小的,最小的变最大的。 所以维护两个数组,分别记录最大值和最小值。""" dp_max = [nums[0]] * len(nums) dp_min = [nums[0]] * len(nums) for i in range(1, len(nums)): dp_max[i] = max(dp_max[i - 1] * nums[i], dp...
the_stack_v2_python_sparse
152_maximum-product-subarray.py
helloocc/algorithm
train
1
f1f2ab8a2dd361b8dd32ad5e25f9c3c0393a02d9
[ "if controller is not None:\n if not is_string(controller):\n raise ValueError('Controller name must be a string')\n controller = controller.strip()\n if not controller:\n _logger.warning('Empty controller name given')\n controller = None\n elif ' ' in controller:\n raise Val...
<|body_start_0|> if controller is not None: if not is_string(controller): raise ValueError('Controller name must be a string') controller = controller.strip() if not controller: _logger.warning('Empty controller name given') con...
@Provides decorator Defines an interface exported by a component.
Provides
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Provides: """@Provides decorator Defines an interface exported by a component.""" def __init__(self, specifications, controller=None): """Sets up a provided service. A service controller can be defined to enable or disable the service. :param specifications: A list of provided interf...
stack_v2_sparse_classes_36k_train_031032
41,418
permissive
[ { "docstring": "Sets up a provided service. A service controller can be defined to enable or disable the service. :param specifications: A list of provided interface(s) name(s) (can't be empty) :param controller: Name of the service controller class field (optional) :raise ValueError: If the specifications are ...
2
stack_v2_sparse_classes_30k_train_015168
Implement the Python class `Provides` described below. Class description: @Provides decorator Defines an interface exported by a component. Method signatures and docstrings: - def __init__(self, specifications, controller=None): Sets up a provided service. A service controller can be defined to enable or disable the ...
Implement the Python class `Provides` described below. Class description: @Provides decorator Defines an interface exported by a component. Method signatures and docstrings: - def __init__(self, specifications, controller=None): Sets up a provided service. A service controller can be defined to enable or disable the ...
686556cdde20beba77ae202de9969be46feed5e2
<|skeleton|> class Provides: """@Provides decorator Defines an interface exported by a component.""" def __init__(self, specifications, controller=None): """Sets up a provided service. A service controller can be defined to enable or disable the service. :param specifications: A list of provided interf...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Provides: """@Provides decorator Defines an interface exported by a component.""" def __init__(self, specifications, controller=None): """Sets up a provided service. A service controller can be defined to enable or disable the service. :param specifications: A list of provided interface(s) name(s...
the_stack_v2_python_sparse
python/src/lib/python/pelix/ipopo/decorators.py
cohorte/cohorte-runtime
train
3
1eed389327923e79e16725c9ccc56787dfe0d9c4
[ "self.se = set()\nself.di = {}\nfor i in dictionary:\n if i not in self.se:\n self.se.update([i])\n else:\n continue\n if len(i) <= 2:\n key = i\n elif len(i) == 3:\n key = i[0] + '1' + i[-1]\n else:\n key = i[0] + str(len(i) - 2) + i[-1]\n self.di[key] = self.di...
<|body_start_0|> self.se = set() self.di = {} for i in dictionary: if i not in self.se: self.se.update([i]) else: continue if len(i) <= 2: key = i elif len(i) == 3: key = i[0] + '1' + ...
https://leetcode.com/problems/unique-word-abbreviation/description/
ValidWordAbbr
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ValidWordAbbr: """https://leetcode.com/problems/unique-word-abbreviation/description/""" def __init__(self, dictionary): """:type dictionary: List[str]""" <|body_0|> def isUnique(self, i): """:type word: str :rtype: bool""" <|body_1|> <|end_skeleton|> <...
stack_v2_sparse_classes_36k_train_031033
1,576
no_license
[ { "docstring": ":type dictionary: List[str]", "name": "__init__", "signature": "def __init__(self, dictionary)" }, { "docstring": ":type word: str :rtype: bool", "name": "isUnique", "signature": "def isUnique(self, i)" } ]
2
stack_v2_sparse_classes_30k_train_019532
Implement the Python class `ValidWordAbbr` described below. Class description: https://leetcode.com/problems/unique-word-abbreviation/description/ Method signatures and docstrings: - def __init__(self, dictionary): :type dictionary: List[str] - def isUnique(self, i): :type word: str :rtype: bool
Implement the Python class `ValidWordAbbr` described below. Class description: https://leetcode.com/problems/unique-word-abbreviation/description/ Method signatures and docstrings: - def __init__(self, dictionary): :type dictionary: List[str] - def isUnique(self, i): :type word: str :rtype: bool <|skeleton|> class V...
30bfafb6a7727c9305b22933b63d9d645182c633
<|skeleton|> class ValidWordAbbr: """https://leetcode.com/problems/unique-word-abbreviation/description/""" def __init__(self, dictionary): """:type dictionary: List[str]""" <|body_0|> def isUnique(self, i): """:type word: str :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ValidWordAbbr: """https://leetcode.com/problems/unique-word-abbreviation/description/""" def __init__(self, dictionary): """:type dictionary: List[str]""" self.se = set() self.di = {} for i in dictionary: if i not in self.se: self.se.update([i])...
the_stack_v2_python_sparse
leetcode/Hash-Table/unique-word-abbreviation.py
iCodeIN/competitive-programming-5
train
0
4860c833e40934d1965efedb528f15911f820ba4
[ "self.noise = noise\nif seed != -1:\n numpy.random.seed(seed)", "if self.noise == 0:\n return\ninputSize = data.size\nflipBits = numpy.random.randint(0, inputSize, self.noise * inputSize)\ndata[flipBits] = numpy.logical_not(data[flipBits])" ]
<|body_start_0|> self.noise = noise if seed != -1: numpy.random.seed(seed) <|end_body_0|> <|body_start_1|> if self.noise == 0: return inputSize = data.size flipBits = numpy.random.randint(0, inputSize, self.noise * inputSize) data[flipBits] = nump...
This RecordSensor filter adds noise to the input
AddNoise
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AddNoise: """This RecordSensor filter adds noise to the input""" def __init__(self, noise=0.0, seed=-1): """Construct the filter Parameters: ------------------------------------------------- noise: Amount of noise to add, from 0 to 1.0""" <|body_0|> def process(self, enc...
stack_v2_sparse_classes_36k_train_031034
1,686
no_license
[ { "docstring": "Construct the filter Parameters: ------------------------------------------------- noise: Amount of noise to add, from 0 to 1.0", "name": "__init__", "signature": "def __init__(self, noise=0.0, seed=-1)" }, { "docstring": "Modify the data in place, adding noise", "name": "pro...
2
stack_v2_sparse_classes_30k_train_019404
Implement the Python class `AddNoise` described below. Class description: This RecordSensor filter adds noise to the input Method signatures and docstrings: - def __init__(self, noise=0.0, seed=-1): Construct the filter Parameters: ------------------------------------------------- noise: Amount of noise to add, from ...
Implement the Python class `AddNoise` described below. Class description: This RecordSensor filter adds noise to the input Method signatures and docstrings: - def __init__(self, noise=0.0, seed=-1): Construct the filter Parameters: ------------------------------------------------- noise: Amount of noise to add, from ...
d494b3041069d377d6a7a9c296a14334f2fa5acc
<|skeleton|> class AddNoise: """This RecordSensor filter adds noise to the input""" def __init__(self, noise=0.0, seed=-1): """Construct the filter Parameters: ------------------------------------------------- noise: Amount of noise to add, from 0 to 1.0""" <|body_0|> def process(self, enc...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AddNoise: """This RecordSensor filter adds noise to the input""" def __init__(self, noise=0.0, seed=-1): """Construct the filter Parameters: ------------------------------------------------- noise: Amount of noise to add, from 0 to 1.0""" self.noise = noise if seed != -1: ...
the_stack_v2_python_sparse
python/numenta_nupic/nupic-master/src/nupic/regions/RecordSensorFilters/AddNoise.py
LiuFang816/SALSTM_py_data
train
10
a373bbff6e100d62b0a6e31ced7ebe390ecdeb8b
[ "list_dict = []\nlist_date = []\nfor niv1 in data:\n for niv2 in niv1:\n list_dict.append(niv2)\nstring_dict = list_dict[0]\ndictionary = ast.literal_eval(string_dict)\nvalues = dictionary.get('media_likes')\nfor i in range(len(values)):\n list_date.append(values[i][0])\nreturn list_date", "list_dict...
<|body_start_0|> list_dict = [] list_date = [] for niv1 in data: for niv2 in niv1: list_dict.append(niv2) string_dict = list_dict[0] dictionary = ast.literal_eval(string_dict) values = dictionary.get('media_likes') for i in range(len(va...
InstagramLikeReader
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InstagramLikeReader: def list_date(self, data): """From the "raw" data sent this function return a list containing all the date related to a "like": --> data at the right level are put in a list (list of dictionaries) --> from this str(dictionries) ast.literal_eval recognise a dictionary...
stack_v2_sparse_classes_36k_train_031035
3,835
permissive
[ { "docstring": "From the \"raw\" data sent this function return a list containing all the date related to a \"like\": --> data at the right level are put in a list (list of dictionaries) --> from this str(dictionries) ast.literal_eval recognise a dictionary --> values related to 'media_likes' (ie the one of the...
3
null
Implement the Python class `InstagramLikeReader` described below. Class description: Implement the InstagramLikeReader class. Method signatures and docstrings: - def list_date(self, data): From the "raw" data sent this function return a list containing all the date related to a "like": --> data at the right level are...
Implement the Python class `InstagramLikeReader` described below. Class description: Implement the InstagramLikeReader class. Method signatures and docstrings: - def list_date(self, data): From the "raw" data sent this function return a list containing all the date related to a "like": --> data at the right level are...
179dd4f04713026656c0849916166fd1ed0d6f31
<|skeleton|> class InstagramLikeReader: def list_date(self, data): """From the "raw" data sent this function return a list containing all the date related to a "like": --> data at the right level are put in a list (list of dictionaries) --> from this str(dictionries) ast.literal_eval recognise a dictionary...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InstagramLikeReader: def list_date(self, data): """From the "raw" data sent this function return a list containing all the date related to a "like": --> data at the right level are put in a list (list of dictionaries) --> from this str(dictionries) ast.literal_eval recognise a dictionary --> values re...
the_stack_v2_python_sparse
Package/instagram_sub_readers/like.py
AdrienCarthoblaz/Master-Thesis
train
2
643419eba6bcc4560189b253d6b9f5ba348cefc0
[ "Weight.__init__(self, *args, **kwargs)\nself._ranges = ranges if ranges is not None else []\nself._initial = initial", "self.log.info('Creating weights for spectrum from given ranges...')\nweights = np.zeros(len(spectrum)) + self._initial\nfor start, end, weight in self._ranges:\n w = (spectrum.wave >= start)...
<|body_start_0|> Weight.__init__(self, *args, **kwargs) self._ranges = ranges if ranges is not None else [] self._initial = initial <|end_body_0|> <|body_start_1|> self.log.info('Creating weights for spectrum from given ranges...') weights = np.zeros(len(spectrum)) + self._initi...
Creates a weights array from given ranges. This class, when called, creates a weights array from the given wavelength ranges.
WeightRanges
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WeightRanges: """Creates a weights array from given ranges. This class, when called, creates a weights array from the given wavelength ranges.""" def __init__(self, ranges: List[Tuple[float, float, float]]=None, initial: float=1.0, *args, **kwargs): """Initializes a new weight. Args:...
stack_v2_sparse_classes_36k_train_031036
1,626
permissive
[ { "docstring": "Initializes a new weight. Args: ranges: List of tuples of (wave start, wave end, weight). initial: Initial value for whole array.", "name": "__init__", "signature": "def __init__(self, ranges: List[Tuple[float, float, float]]=None, initial: float=1.0, *args, **kwargs)" }, { "docs...
2
null
Implement the Python class `WeightRanges` described below. Class description: Creates a weights array from given ranges. This class, when called, creates a weights array from the given wavelength ranges. Method signatures and docstrings: - def __init__(self, ranges: List[Tuple[float, float, float]]=None, initial: flo...
Implement the Python class `WeightRanges` described below. Class description: Creates a weights array from given ranges. This class, when called, creates a weights array from the given wavelength ranges. Method signatures and docstrings: - def __init__(self, ranges: List[Tuple[float, float, float]]=None, initial: flo...
648eb1758e3744d9e3d6669edc4a0c4753559f17
<|skeleton|> class WeightRanges: """Creates a weights array from given ranges. This class, when called, creates a weights array from the given wavelength ranges.""" def __init__(self, ranges: List[Tuple[float, float, float]]=None, initial: float=1.0, *args, **kwargs): """Initializes a new weight. Args:...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WeightRanges: """Creates a weights array from given ranges. This class, when called, creates a weights array from the given wavelength ranges.""" def __init__(self, ranges: List[Tuple[float, float, float]]=None, initial: float=1.0, *args, **kwargs): """Initializes a new weight. Args: ranges: List...
the_stack_v2_python_sparse
spexxy/weight/ranges.py
thusser/spexxy
train
4
49b57c1a8342f9fdd5c1f14e35b13225dbde0b55
[ "if not isinstance(record_id, int):\n raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: record_id EXPECTED TYPE: int', None, None)\nif not isinstance(module_api_name, str):\n raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: module_api_name EXPECTED TYPE: str', None, None)\nself.__record_id = record_id\ns...
<|body_start_0|> if not isinstance(record_id, int): raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: record_id EXPECTED TYPE: int', None, None) if not isinstance(module_api_name, str): raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: module_api_name EXPECTED TYPE: str', Non...
BluePrintOperations
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BluePrintOperations: def __init__(self, record_id, module_api_name): """Creates an instance of BluePrintOperations with the given parameters Parameters: record_id (int) : An int representing the record_id module_api_name (string) : A string representing the module_api_name""" <|b...
stack_v2_sparse_classes_36k_train_031037
3,177
no_license
[ { "docstring": "Creates an instance of BluePrintOperations with the given parameters Parameters: record_id (int) : An int representing the record_id module_api_name (string) : A string representing the module_api_name", "name": "__init__", "signature": "def __init__(self, record_id, module_api_name)" ...
3
null
Implement the Python class `BluePrintOperations` described below. Class description: Implement the BluePrintOperations class. Method signatures and docstrings: - def __init__(self, record_id, module_api_name): Creates an instance of BluePrintOperations with the given parameters Parameters: record_id (int) : An int re...
Implement the Python class `BluePrintOperations` described below. Class description: Implement the BluePrintOperations class. Method signatures and docstrings: - def __init__(self, record_id, module_api_name): Creates an instance of BluePrintOperations with the given parameters Parameters: record_id (int) : An int re...
bba7328de07b137d2cb6e2aac31b8f57e0803026
<|skeleton|> class BluePrintOperations: def __init__(self, record_id, module_api_name): """Creates an instance of BluePrintOperations with the given parameters Parameters: record_id (int) : An int representing the record_id module_api_name (string) : A string representing the module_api_name""" <|b...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BluePrintOperations: def __init__(self, record_id, module_api_name): """Creates an instance of BluePrintOperations with the given parameters Parameters: record_id (int) : An int representing the record_id module_api_name (string) : A string representing the module_api_name""" if not isinstance...
the_stack_v2_python_sparse
zcrmsdk/src/com/zoho/crm/api/blue_print/blue_print_operations.py
L1nuxFNC/zohocrm-python-sdk
train
0
399e33108e8183e8a5a282f9388dd0dc383ea088
[ "super(PeriodicUpsample1D, self).__init__()\nself.in_channel = in_channel\nself.out_channel = out_channel\nself.conv1d = nn.Conv1d(in_channel, out_channel, 3, 1, 0)", "x = torch.stack((torch.zeros_like(x), x), dim=-1).view(x.shape[0], x.shape[1], -1)\nx = torch.cat((x[..., -1:], x, x[..., :1]), dim=-1)\nx = self....
<|body_start_0|> super(PeriodicUpsample1D, self).__init__() self.in_channel = in_channel self.out_channel = out_channel self.conv1d = nn.Conv1d(in_channel, out_channel, 3, 1, 0) <|end_body_0|> <|body_start_1|> x = torch.stack((torch.zeros_like(x), x), dim=-1).view(x.shape[0], x....
PeriodicUpsample1D
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PeriodicUpsample1D: def __init__(self, in_channel, out_channel): """:param in_channel: input planes :param out_channel: output planes""" <|body_0|> def forward(self, x): """:param x: tensor of shape (N, C, L) :return tensor of shape (N, C, 2L)""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_031038
7,677
no_license
[ { "docstring": ":param in_channel: input planes :param out_channel: output planes", "name": "__init__", "signature": "def __init__(self, in_channel, out_channel)" }, { "docstring": ":param x: tensor of shape (N, C, L) :return tensor of shape (N, C, 2L)", "name": "forward", "signature": "...
2
stack_v2_sparse_classes_30k_train_018815
Implement the Python class `PeriodicUpsample1D` described below. Class description: Implement the PeriodicUpsample1D class. Method signatures and docstrings: - def __init__(self, in_channel, out_channel): :param in_channel: input planes :param out_channel: output planes - def forward(self, x): :param x: tensor of sha...
Implement the Python class `PeriodicUpsample1D` described below. Class description: Implement the PeriodicUpsample1D class. Method signatures and docstrings: - def __init__(self, in_channel, out_channel): :param in_channel: input planes :param out_channel: output planes - def forward(self, x): :param x: tensor of sha...
666bbecd9f9b2c9bebaf82deab3ccb8586d60dca
<|skeleton|> class PeriodicUpsample1D: def __init__(self, in_channel, out_channel): """:param in_channel: input planes :param out_channel: output planes""" <|body_0|> def forward(self, x): """:param x: tensor of shape (N, C, L) :return tensor of shape (N, C, 2L)""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PeriodicUpsample1D: def __init__(self, in_channel, out_channel): """:param in_channel: input planes :param out_channel: output planes""" super(PeriodicUpsample1D, self).__init__() self.in_channel = in_channel self.out_channel = out_channel self.conv1d = nn.Conv1d(in_cha...
the_stack_v2_python_sparse
experiments/exp3_segmentation/model.py
maxjiang93/DDSL
train
55
a9beb82e56f0b8ee7a2bf550c126d906789ddf08
[ "self.X_train = None\nself.y_train = None\nself.trees = []\nself.N = N\nself.M = M\nself.F = F", "header = ['att' + str(i) for i in range(len(X_train[0]))]\nattribute_domains = {}\nfor i, val in enumerate(header):\n attribute_domains[val] = myutils.unique_index(X_train, i)\nself.X_train = X_train\nself.y_train...
<|body_start_0|> self.X_train = None self.y_train = None self.trees = [] self.N = N self.M = M self.F = F <|end_body_0|> <|body_start_1|> header = ['att' + str(i) for i in range(len(X_train[0]))] attribute_domains = {} for i, val in enumerate(head...
Represents a decision tree classifier. Attributes: X_train(list of list of obj): The list of training instances (samples). The shape of X_train is (n_train_samples, n_features) y_train(list of obj): The target y values (parallel to X_train). The shape of y_train is n_samples tree(nested list): The extracted tree model....
MyRandomForestClassifier
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyRandomForestClassifier: """Represents a decision tree classifier. Attributes: X_train(list of list of obj): The list of training instances (samples). The shape of X_train is (n_train_samples, n_features) y_train(list of obj): The target y values (parallel to X_train). The shape of y_train is n_...
stack_v2_sparse_classes_36k_train_031039
10,235
no_license
[ { "docstring": "Initializer for MyDecisionTreeClassifier.", "name": "__init__", "signature": "def __init__(self, F=2, N=4, M=3)" }, { "docstring": "Fits a decision tree classifier to X_train and y_train using the TDIDT (top down induction of decision tree) algorithm. Args: X_train(list of list o...
3
stack_v2_sparse_classes_30k_test_000433
Implement the Python class `MyRandomForestClassifier` described below. Class description: Represents a decision tree classifier. Attributes: X_train(list of list of obj): The list of training instances (samples). The shape of X_train is (n_train_samples, n_features) y_train(list of obj): The target y values (parallel ...
Implement the Python class `MyRandomForestClassifier` described below. Class description: Represents a decision tree classifier. Attributes: X_train(list of list of obj): The list of training instances (samples). The shape of X_train is (n_train_samples, n_features) y_train(list of obj): The target y values (parallel ...
e1c9bd77026dadb993361e79514a295edd5775f3
<|skeleton|> class MyRandomForestClassifier: """Represents a decision tree classifier. Attributes: X_train(list of list of obj): The list of training instances (samples). The shape of X_train is (n_train_samples, n_features) y_train(list of obj): The target y values (parallel to X_train). The shape of y_train is n_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MyRandomForestClassifier: """Represents a decision tree classifier. Attributes: X_train(list of list of obj): The list of training instances (samples). The shape of X_train is (n_train_samples, n_features) y_train(list of obj): The target y values (parallel to X_train). The shape of y_train is n_samples tree(...
the_stack_v2_python_sparse
mysklearn/myclassifiers.py
CarterKekoa/SpotifyRecommendationApp
train
1
d382542dc331a95aa328f5919b4186324ec647a0
[ "Package.__init__(self, model, extension, 'MPBAS', unitnumber)\nnrow, ncol, nlay, nper = self.parent.mf.nrow_ncol_nlay_nper\nself.parent.mf.get_name_file_entries()\nself.heading1 = '# MPBAS for Modpath, generated by hataripy.'\nself.heading2 = '#'\nself.hnoflo = hnoflo\nself.hdry = hdry\nself.def_face_ct = def_face...
<|body_start_0|> Package.__init__(self, model, extension, 'MPBAS', unitnumber) nrow, ncol, nlay, nper = self.parent.mf.nrow_ncol_nlay_nper self.parent.mf.get_name_file_entries() self.heading1 = '# MPBAS for Modpath, generated by hataripy.' self.heading2 = '#' self.hnoflo ...
MODPATH Basic Package Class. Parameters ---------- model : model object The model object (of type :class:`hataripy.modpath.mp.Modpath`) to which this package will be added. hnoflo : float Head value assigned to inactive cells (default is -9999.). hdry : float Head value assigned to dry cells (default is -8888.). def_fa...
ModpathBas
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ModpathBas: """MODPATH Basic Package Class. Parameters ---------- model : model object The model object (of type :class:`hataripy.modpath.mp.Modpath`) to which this package will be added. hnoflo : float Head value assigned to inactive cells (default is -9999.). hdry : float Head value assigned to...
stack_v2_sparse_classes_36k_train_031040
5,451
permissive
[ { "docstring": "Package constructor.", "name": "__init__", "signature": "def __init__(self, model, hnoflo=-9999.0, hdry=-8888.0, def_face_ct=0, bud_label=None, def_iface=None, laytyp=0, ibound=1, prsity=0.3, prsityCB=0.3, extension='mpbas', unitnumber=86)" }, { "docstring": "Write the package fi...
2
null
Implement the Python class `ModpathBas` described below. Class description: MODPATH Basic Package Class. Parameters ---------- model : model object The model object (of type :class:`hataripy.modpath.mp.Modpath`) to which this package will be added. hnoflo : float Head value assigned to inactive cells (default is -9999...
Implement the Python class `ModpathBas` described below. Class description: MODPATH Basic Package Class. Parameters ---------- model : model object The model object (of type :class:`hataripy.modpath.mp.Modpath`) to which this package will be added. hnoflo : float Head value assigned to inactive cells (default is -9999...
7db7869f34b875c9f76d42b7a4801b0c23738448
<|skeleton|> class ModpathBas: """MODPATH Basic Package Class. Parameters ---------- model : model object The model object (of type :class:`hataripy.modpath.mp.Modpath`) to which this package will be added. hnoflo : float Head value assigned to inactive cells (default is -9999.). hdry : float Head value assigned to...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ModpathBas: """MODPATH Basic Package Class. Parameters ---------- model : model object The model object (of type :class:`hataripy.modpath.mp.Modpath`) to which this package will be added. hnoflo : float Head value assigned to inactive cells (default is -9999.). hdry : float Head value assigned to dry cells (d...
the_stack_v2_python_sparse
hataripy/modpath/mpbas.py
hatarilabs/hataripy
train
4
3ffad6484813466dce3cc5e9f1615a99324427c4
[ "super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=TIME_BETWEEN_UPDATES)\nself._train_api = TrafikverketTrain(async_get_clientsession(hass), entry.data[CONF_API_KEY])\nself.from_station: StationInfo = from_station\nself.to_station: StationInfo = to_station\nself._time: time | None = dt_util.parse_time(en...
<|body_start_0|> super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=TIME_BETWEEN_UPDATES) self._train_api = TrafikverketTrain(async_get_clientsession(hass), entry.data[CONF_API_KEY]) self.from_station: StationInfo = from_station self.to_station: StationInfo = to_station ...
A Trafikverket Data Update Coordinator.
TVDataUpdateCoordinator
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TVDataUpdateCoordinator: """A Trafikverket Data Update Coordinator.""" def __init__(self, hass: HomeAssistant, entry: ConfigEntry, to_station: StationInfo, from_station: StationInfo, filter_product: str | None) -> None: """Initialize the Trafikverket coordinator.""" <|body_0|...
stack_v2_sparse_classes_36k_train_031041
4,898
permissive
[ { "docstring": "Initialize the Trafikverket coordinator.", "name": "__init__", "signature": "def __init__(self, hass: HomeAssistant, entry: ConfigEntry, to_station: StationInfo, from_station: StationInfo, filter_product: str | None) -> None" }, { "docstring": "Fetch data from Trafikverket.", ...
2
null
Implement the Python class `TVDataUpdateCoordinator` described below. Class description: A Trafikverket Data Update Coordinator. Method signatures and docstrings: - def __init__(self, hass: HomeAssistant, entry: ConfigEntry, to_station: StationInfo, from_station: StationInfo, filter_product: str | None) -> None: Init...
Implement the Python class `TVDataUpdateCoordinator` described below. Class description: A Trafikverket Data Update Coordinator. Method signatures and docstrings: - def __init__(self, hass: HomeAssistant, entry: ConfigEntry, to_station: StationInfo, from_station: StationInfo, filter_product: str | None) -> None: Init...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class TVDataUpdateCoordinator: """A Trafikverket Data Update Coordinator.""" def __init__(self, hass: HomeAssistant, entry: ConfigEntry, to_station: StationInfo, from_station: StationInfo, filter_product: str | None) -> None: """Initialize the Trafikverket coordinator.""" <|body_0|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TVDataUpdateCoordinator: """A Trafikverket Data Update Coordinator.""" def __init__(self, hass: HomeAssistant, entry: ConfigEntry, to_station: StationInfo, from_station: StationInfo, filter_product: str | None) -> None: """Initialize the Trafikverket coordinator.""" super().__init__(hass,...
the_stack_v2_python_sparse
homeassistant/components/trafikverket_train/coordinator.py
home-assistant/core
train
35,501
67dd26601b07be3466c1b76aeb13a9ace7633425
[ "super(Export, self).__init__(config=config, args=args)\nself.host = None\nself.port = None\nself.user = None\nself.password = None\nself.db = None\nself.prefix = None\nself.tags = None\nself.export_enable = self.load_conf()\nif not self.export_enable:\n sys.exit(2)\nself.client = self.init()", "if self.config...
<|body_start_0|> super(Export, self).__init__(config=config, args=args) self.host = None self.port = None self.user = None self.password = None self.db = None self.prefix = None self.tags = None self.export_enable = self.load_conf() if not ...
This class manages the InfluxDB export module.
Export
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Export: """This class manages the InfluxDB export module.""" def __init__(self, config=None, args=None): """Init the InfluxDB export IF.""" <|body_0|> def load_conf(self, section='influxdb'): """Load the InfluxDb configuration in the Glances configuration file.""...
stack_v2_sparse_classes_36k_train_031042
5,114
no_license
[ { "docstring": "Init the InfluxDB export IF.", "name": "__init__", "signature": "def __init__(self, config=None, args=None)" }, { "docstring": "Load the InfluxDb configuration in the Glances configuration file.", "name": "load_conf", "signature": "def load_conf(self, section='influxdb')"...
4
stack_v2_sparse_classes_30k_train_002552
Implement the Python class `Export` described below. Class description: This class manages the InfluxDB export module. Method signatures and docstrings: - def __init__(self, config=None, args=None): Init the InfluxDB export IF. - def load_conf(self, section='influxdb'): Load the InfluxDb configuration in the Glances ...
Implement the Python class `Export` described below. Class description: This class manages the InfluxDB export module. Method signatures and docstrings: - def __init__(self, config=None, args=None): Init the InfluxDB export IF. - def load_conf(self, section='influxdb'): Load the InfluxDb configuration in the Glances ...
babafa44bbf8234b9d579282de18e382e5499a9b
<|skeleton|> class Export: """This class manages the InfluxDB export module.""" def __init__(self, config=None, args=None): """Init the InfluxDB export IF.""" <|body_0|> def load_conf(self, section='influxdb'): """Load the InfluxDb configuration in the Glances configuration file.""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Export: """This class manages the InfluxDB export module.""" def __init__(self, config=None, args=None): """Init the InfluxDB export IF.""" super(Export, self).__init__(config=config, args=args) self.host = None self.port = None self.user = None self.passwo...
the_stack_v2_python_sparse
gl/exports/glances_influxdb.py
mondo0/testgl
train
0
ad5481e9b26a8ea9f9d56a19ed369ce6fad3ce59
[ "user = request.user\ncheck_user_status(user)\nuser_id = user.id\nrestaurant = PendingRestaurant.get_by_owner(user_id)\nrest_id = restaurant._id\ndishes = PendingFood.get_by_restaurant(rest_id)\nresponse = {'Dishes': models_to_json(dishes)}\nreturn JsonResponse(response)", "user = request.user\ncheck_user_status(...
<|body_start_0|> user = request.user check_user_status(user) user_id = user.id restaurant = PendingRestaurant.get_by_owner(user_id) rest_id = restaurant._id dishes = PendingFood.get_by_restaurant(rest_id) response = {'Dishes': models_to_json(dishes)} retur...
pending dish view
PendingDishView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PendingDishView: """pending dish view""" def get(self, request): """Retrieve all dishes from restaurant owned by user""" <|body_0|> def post(self, request): """Insert dish into database""" <|body_1|> <|end_skeleton|> <|body_start_0|> user = requ...
stack_v2_sparse_classes_36k_train_031043
19,356
no_license
[ { "docstring": "Retrieve all dishes from restaurant owned by user", "name": "get", "signature": "def get(self, request)" }, { "docstring": "Insert dish into database", "name": "post", "signature": "def post(self, request)" } ]
2
stack_v2_sparse_classes_30k_val_000252
Implement the Python class `PendingDishView` described below. Class description: pending dish view Method signatures and docstrings: - def get(self, request): Retrieve all dishes from restaurant owned by user - def post(self, request): Insert dish into database
Implement the Python class `PendingDishView` described below. Class description: pending dish view Method signatures and docstrings: - def get(self, request): Retrieve all dishes from restaurant owned by user - def post(self, request): Insert dish into database <|skeleton|> class PendingDishView: """pending dish...
2707062c9a9a8bb4baca955e8a60ba08cc9f8953
<|skeleton|> class PendingDishView: """pending dish view""" def get(self, request): """Retrieve all dishes from restaurant owned by user""" <|body_0|> def post(self, request): """Insert dish into database""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PendingDishView: """pending dish view""" def get(self, request): """Retrieve all dishes from restaurant owned by user""" user = request.user check_user_status(user) user_id = user.id restaurant = PendingRestaurant.get_by_owner(user_id) rest_id = restaurant....
the_stack_v2_python_sparse
backend/restaurant/views.py
MochiTarts/Find-Dining-The-Bridge
train
1
237301f707617ec931ab8dc4acd3b066752d3196
[ "digits = digits[::-1]\nprint(digits)\nl = len(digits)\np = l - 1\nf = False\nwhile p >= 0:\n if digits[p] != 9:\n digits[p] += 1\n if f == True or p == l - 1:\n return digits\n else:\n f = True\n digits[p] = 0\n p -= 1\n if p == -1:\n digits.ins...
<|body_start_0|> digits = digits[::-1] print(digits) l = len(digits) p = l - 1 f = False while p >= 0: if digits[p] != 9: digits[p] += 1 if f == True or p == l - 1: return digits else: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def plusOne(self, digits): """:type digits: List[int] :rtype: List[int] 正序计算""" <|body_0|> def plusOne2(self, digits): """:type digits: List[int] :rtype: List[int] 反转数组,从左往右计算 反转后第一位+1小于10,则+1即可退出循环 反转后第一位+1=10,则当前位=0,继续循环;最后一位时直接=0且最后增加一位1""" <|bod...
stack_v2_sparse_classes_36k_train_031044
2,450
no_license
[ { "docstring": ":type digits: List[int] :rtype: List[int] 正序计算", "name": "plusOne", "signature": "def plusOne(self, digits)" }, { "docstring": ":type digits: List[int] :rtype: List[int] 反转数组,从左往右计算 反转后第一位+1小于10,则+1即可退出循环 反转后第一位+1=10,则当前位=0,继续循环;最后一位时直接=0且最后增加一位1", "name": "plusOne2", "si...
3
stack_v2_sparse_classes_30k_val_000023
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def plusOne(self, digits): :type digits: List[int] :rtype: List[int] 正序计算 - def plusOne2(self, digits): :type digits: List[int] :rtype: List[int] 反转数组,从左往右计算 反转后第一位+1小于10,则+1即可退出...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def plusOne(self, digits): :type digits: List[int] :rtype: List[int] 正序计算 - def plusOne2(self, digits): :type digits: List[int] :rtype: List[int] 反转数组,从左往右计算 反转后第一位+1小于10,则+1即可退出...
b0f498ebe84e46b7e17e94759dd462891dcc8f85
<|skeleton|> class Solution: def plusOne(self, digits): """:type digits: List[int] :rtype: List[int] 正序计算""" <|body_0|> def plusOne2(self, digits): """:type digits: List[int] :rtype: List[int] 反转数组,从左往右计算 反转后第一位+1小于10,则+1即可退出循环 反转后第一位+1=10,则当前位=0,继续循环;最后一位时直接=0且最后增加一位1""" <|bod...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def plusOne(self, digits): """:type digits: List[int] :rtype: List[int] 正序计算""" digits = digits[::-1] print(digits) l = len(digits) p = l - 1 f = False while p >= 0: if digits[p] != 9: digits[p] += 1 ...
the_stack_v2_python_sparse
初级算法/array_7.py
wulinlw/leetcode_cn
train
0
4f53eebf489d79c775025a3b2a251a5d34039a3a
[ "basic_url = 'https://math.ly/api/v1/'\nbasic_url += area + '/' + topic + '.json'\nif difficulty:\n basic_url += '?difficulty=' + difficulty\nres = requests.get(basic_url).json()\nchoices = [re.sub('</math>, <math>', ', ', choice) for choice in res['choices']]\nchoices = [i.replace('<math>', '<math xmlns=\"http:...
<|body_start_0|> basic_url = 'https://math.ly/api/v1/' basic_url += area + '/' + topic + '.json' if difficulty: basic_url += '?difficulty=' + difficulty res = requests.get(basic_url).json() choices = [re.sub('</math>, <math>', ', ', choice) for choice in res['choices'...
A class that represents a Math.ly problem receiver.
Receiver
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Receiver: """A class that represents a Math.ly problem receiver.""" def get_random_problem(self, area, topic, difficulty=None): """(str, str, str) -> Problem :param area: area of the problem(e.g. 'algebra') :param topic: topic of the problem (e.g. 'linear-equations') :param difficult...
stack_v2_sparse_classes_36k_train_031045
9,855
no_license
[ { "docstring": "(str, str, str) -> Problem :param area: area of the problem(e.g. 'algebra') :param topic: topic of the problem (e.g. 'linear-equations') :param difficulty: difficulty(beginner, intermediate, advanced) (Default value = None) :returns: a Problem object of current problem", "name": "get_random_...
3
stack_v2_sparse_classes_30k_train_005671
Implement the Python class `Receiver` described below. Class description: A class that represents a Math.ly problem receiver. Method signatures and docstrings: - def get_random_problem(self, area, topic, difficulty=None): (str, str, str) -> Problem :param area: area of the problem(e.g. 'algebra') :param topic: topic ...
Implement the Python class `Receiver` described below. Class description: A class that represents a Math.ly problem receiver. Method signatures and docstrings: - def get_random_problem(self, area, topic, difficulty=None): (str, str, str) -> Problem :param area: area of the problem(e.g. 'algebra') :param topic: topic ...
43ea67af67bd9ceb9a2dd0ce7cf4ee342c3e13a2
<|skeleton|> class Receiver: """A class that represents a Math.ly problem receiver.""" def get_random_problem(self, area, topic, difficulty=None): """(str, str, str) -> Problem :param area: area of the problem(e.g. 'algebra') :param topic: topic of the problem (e.g. 'linear-equations') :param difficult...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Receiver: """A class that represents a Math.ly problem receiver.""" def get_random_problem(self, area, topic, difficulty=None): """(str, str, str) -> Problem :param area: area of the problem(e.g. 'algebra') :param topic: topic of the problem (e.g. 'linear-equations') :param difficulty: difficulty...
the_stack_v2_python_sparse
flask-app/my_modules/classes.py
Centurion256/ProjectLogos
train
1
d43b7ebba3c8d859469b2168efecb696a855bdf9
[ "if not prices:\n return 0\nn = len(prices)\ndp, min_buy_stock_value = ([0] * n, prices[0])\nfor i in range(1, n):\n min_buy_stock_value = min(prices[i], min_buy_stock_value)\n dp[i] = max(prices[i] - min_buy_stock_value, dp[i - 1])\nreturn dp[n - 1]", "if not prices:\n return 0\nn, min_buy_stock_valu...
<|body_start_0|> if not prices: return 0 n = len(prices) dp, min_buy_stock_value = ([0] * n, prices[0]) for i in range(1, n): min_buy_stock_value = min(prices[i], min_buy_stock_value) dp[i] = max(prices[i] - min_buy_stock_value, dp[i - 1]) retu...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxProfit(self, prices: list) -> int: """动态规划 先找到最小的买入价格,然后和当前价格相减,得出利润,再和之前的利润比较,得出最大利润 dp[i]就表示第i天的利润 dp[i] = max(prices[i] - min_buy_stock_value, dp[i-1])""" <|body_0|> def maxProfit_1(self, prices: list) -> int: """迭代""" <|body_1|> def ...
stack_v2_sparse_classes_36k_train_031046
3,964
no_license
[ { "docstring": "动态规划 先找到最小的买入价格,然后和当前价格相减,得出利润,再和之前的利润比较,得出最大利润 dp[i]就表示第i天的利润 dp[i] = max(prices[i] - min_buy_stock_value, dp[i-1])", "name": "maxProfit", "signature": "def maxProfit(self, prices: list) -> int" }, { "docstring": "迭代", "name": "maxProfit_1", "signature": "def maxProfit_1...
4
stack_v2_sparse_classes_30k_train_007738
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit(self, prices: list) -> int: 动态规划 先找到最小的买入价格,然后和当前价格相减,得出利润,再和之前的利润比较,得出最大利润 dp[i]就表示第i天的利润 dp[i] = max(prices[i] - min_buy_stock_value, dp[i-1]) - def maxProfit_1(s...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit(self, prices: list) -> int: 动态规划 先找到最小的买入价格,然后和当前价格相减,得出利润,再和之前的利润比较,得出最大利润 dp[i]就表示第i天的利润 dp[i] = max(prices[i] - min_buy_stock_value, dp[i-1]) - def maxProfit_1(s...
3508e1ce089131b19603c3206aab4cf43023bb19
<|skeleton|> class Solution: def maxProfit(self, prices: list) -> int: """动态规划 先找到最小的买入价格,然后和当前价格相减,得出利润,再和之前的利润比较,得出最大利润 dp[i]就表示第i天的利润 dp[i] = max(prices[i] - min_buy_stock_value, dp[i-1])""" <|body_0|> def maxProfit_1(self, prices: list) -> int: """迭代""" <|body_1|> def ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxProfit(self, prices: list) -> int: """动态规划 先找到最小的买入价格,然后和当前价格相减,得出利润,再和之前的利润比较,得出最大利润 dp[i]就表示第i天的利润 dp[i] = max(prices[i] - min_buy_stock_value, dp[i-1])""" if not prices: return 0 n = len(prices) dp, min_buy_stock_value = ([0] * n, prices[0]) ...
the_stack_v2_python_sparse
algorithm/leetcode/dp/08-买卖股票的最佳时机.py
lxconfig/UbuntuCode_bak
train
0
d7c7e62165a52178590ade734048b8f292472f7f
[ "assert model_name in ['Resnet50_FPN', 'MobileNetV3_largeFPN', 'MobileNetV3_largeFPN_320', 'MaskRCNN', 'YOLOv5x'], 'Error: model not found'\nweights_path += 'best_' + model_name + '.pt'\nself.model = get_object_detection_model(num_classes=2, mtype=model_name, weights_path=weights_path, device=torch.device('cpu'))\n...
<|body_start_0|> assert model_name in ['Resnet50_FPN', 'MobileNetV3_largeFPN', 'MobileNetV3_largeFPN_320', 'MaskRCNN', 'YOLOv5x'], 'Error: model not found' weights_path += 'best_' + model_name + '.pt' self.model = get_object_detection_model(num_classes=2, mtype=model_name, weights_path=weights_p...
ObjectPredictor
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ObjectPredictor: def __init__(self, model_name='MobileNetV3_largeFPN', weights_path='/home/phil/Documents/Projects/CV_SLAM_project/cv_lib/models/'): """Constructor :param model_name: name of the pre trained model to load :param weights_path: from where to load the trained weights""" ...
stack_v2_sparse_classes_36k_train_031047
11,558
no_license
[ { "docstring": "Constructor :param model_name: name of the pre trained model to load :param weights_path: from where to load the trained weights", "name": "__init__", "signature": "def __init__(self, model_name='MobileNetV3_largeFPN', weights_path='/home/phil/Documents/Projects/CV_SLAM_project/cv_lib/mo...
2
stack_v2_sparse_classes_30k_val_001056
Implement the Python class `ObjectPredictor` described below. Class description: Implement the ObjectPredictor class. Method signatures and docstrings: - def __init__(self, model_name='MobileNetV3_largeFPN', weights_path='/home/phil/Documents/Projects/CV_SLAM_project/cv_lib/models/'): Constructor :param model_name: n...
Implement the Python class `ObjectPredictor` described below. Class description: Implement the ObjectPredictor class. Method signatures and docstrings: - def __init__(self, model_name='MobileNetV3_largeFPN', weights_path='/home/phil/Documents/Projects/CV_SLAM_project/cv_lib/models/'): Constructor :param model_name: n...
7101da99d0744405b9faa0ef6c9c98f4e3adf148
<|skeleton|> class ObjectPredictor: def __init__(self, model_name='MobileNetV3_largeFPN', weights_path='/home/phil/Documents/Projects/CV_SLAM_project/cv_lib/models/'): """Constructor :param model_name: name of the pre trained model to load :param weights_path: from where to load the trained weights""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ObjectPredictor: def __init__(self, model_name='MobileNetV3_largeFPN', weights_path='/home/phil/Documents/Projects/CV_SLAM_project/cv_lib/models/'): """Constructor :param model_name: name of the pre trained model to load :param weights_path: from where to load the trained weights""" assert mod...
the_stack_v2_python_sparse
cv_lib/src/object_prediction.py
PhiCtl/Object-pose-estimation
train
0
2b895cf4392273b689ddafc6f26c5ab11f737a5a
[ "super(CustomSmoothL1Loss, self).__init__()\nself.beta = beta\nself.reduction = reduction\nself.loss_weight = loss_weight", "reduction = reduction_override if reduction_override else self.reduction\nif target.numel() > 0:\n loss_bbox = self.loss_weight * smooth_l1_loss(pred, target, weight, beta=self.beta, red...
<|body_start_0|> super(CustomSmoothL1Loss, self).__init__() self.beta = beta self.reduction = reduction self.loss_weight = loss_weight <|end_body_0|> <|body_start_1|> reduction = reduction_override if reduction_override else self.reduction if target.numel() > 0: ...
Smooth L1 Loss.
CustomSmoothL1Loss
[ "Apache-2.0", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CustomSmoothL1Loss: """Smooth L1 Loss.""" def __init__(self, beta=1.0, reduction='mean', loss_weight=1.0): """Init smooth l1 loss.""" <|body_0|> def forward(self, pred, target, weight=None, avg_factor=None, reduction_override=None, **kwargs): """Forward compute. ...
stack_v2_sparse_classes_36k_train_031048
13,829
permissive
[ { "docstring": "Init smooth l1 loss.", "name": "__init__", "signature": "def __init__(self, beta=1.0, reduction='mean', loss_weight=1.0)" }, { "docstring": "Forward compute. :param pred: predict :param target: target :param weight: weight :param avg_factor: avg factor :param reduction_override: ...
2
stack_v2_sparse_classes_30k_train_017843
Implement the Python class `CustomSmoothL1Loss` described below. Class description: Smooth L1 Loss. Method signatures and docstrings: - def __init__(self, beta=1.0, reduction='mean', loss_weight=1.0): Init smooth l1 loss. - def forward(self, pred, target, weight=None, avg_factor=None, reduction_override=None, **kwarg...
Implement the Python class `CustomSmoothL1Loss` described below. Class description: Smooth L1 Loss. Method signatures and docstrings: - def __init__(self, beta=1.0, reduction='mean', loss_weight=1.0): Init smooth l1 loss. - def forward(self, pred, target, weight=None, avg_factor=None, reduction_override=None, **kwarg...
df51ed9c1d6dbde1deef63f2a037a369f8554406
<|skeleton|> class CustomSmoothL1Loss: """Smooth L1 Loss.""" def __init__(self, beta=1.0, reduction='mean', loss_weight=1.0): """Init smooth l1 loss.""" <|body_0|> def forward(self, pred, target, weight=None, avg_factor=None, reduction_override=None, **kwargs): """Forward compute. ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CustomSmoothL1Loss: """Smooth L1 Loss.""" def __init__(self, beta=1.0, reduction='mean', loss_weight=1.0): """Init smooth l1 loss.""" super(CustomSmoothL1Loss, self).__init__() self.beta = beta self.reduction = reduction self.loss_weight = loss_weight def forw...
the_stack_v2_python_sparse
built-in/TensorFlow/Research/cv/image_classification/Darts_for_TensorFlow/automl/vega/search_space/networks/pytorch/operator/rpn.py
Huawei-Ascend/modelzoo
train
1
9abace3e504e8347a1a27059c908a1c3d4ee3e4f
[ "ReporterFactory.__init__(self, reporter_type=reporter_type)\nPersistenceExecutor.__init__(self)\nself.interval = interval\nself.reporter_args = reporter_args\nself.log = ''\nself.send_report = self.create_reporter()\nself.persistent = persistent", "self.send_report(host='smtp.gmail.com', port=587, email=self.rep...
<|body_start_0|> ReporterFactory.__init__(self, reporter_type=reporter_type) PersistenceExecutor.__init__(self) self.interval = interval self.reporter_args = reporter_args self.log = '' self.send_report = self.create_reporter() self.persistent = persistent <|end_b...
Implements a keylogger that sends reports to the given Reporter `reporter_type` Inherits: ReporterFactory PersistenceExecutor
Keylogger
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Keylogger: """Implements a keylogger that sends reports to the given Reporter `reporter_type` Inherits: ReporterFactory PersistenceExecutor""" def __init__(self, interval: int, persistent: bool=True, reporter_type: ReportMethod=ReportMethod.EMAIL, **reporter_args: list): """Args: int...
stack_v2_sparse_classes_36k_train_031049
2,682
permissive
[ { "docstring": "Args: interval (int): Report interval persistent (bool): Setting this flag will cause the keylogger to be persistent reporter_type (ReportMethod): The Reporter type. Defaults to email via Gmail reporter_args (list): Keyword arguments to be passed to the Reporter; these will vary", "name": "_...
4
stack_v2_sparse_classes_30k_train_011213
Implement the Python class `Keylogger` described below. Class description: Implements a keylogger that sends reports to the given Reporter `reporter_type` Inherits: ReporterFactory PersistenceExecutor Method signatures and docstrings: - def __init__(self, interval: int, persistent: bool=True, reporter_type: ReportMet...
Implement the Python class `Keylogger` described below. Class description: Implements a keylogger that sends reports to the given Reporter `reporter_type` Inherits: ReporterFactory PersistenceExecutor Method signatures and docstrings: - def __init__(self, interval: int, persistent: bool=True, reporter_type: ReportMet...
89cba5bf07ec579aa6987e4866db446c8457927f
<|skeleton|> class Keylogger: """Implements a keylogger that sends reports to the given Reporter `reporter_type` Inherits: ReporterFactory PersistenceExecutor""" def __init__(self, interval: int, persistent: bool=True, reporter_type: ReportMethod=ReportMethod.EMAIL, **reporter_args: list): """Args: int...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Keylogger: """Implements a keylogger that sends reports to the given Reporter `reporter_type` Inherits: ReporterFactory PersistenceExecutor""" def __init__(self, interval: int, persistent: bool=True, reporter_type: ReportMethod=ReportMethod.EMAIL, **reporter_args: list): """Args: interval (int): ...
the_stack_v2_python_sparse
brutus/payloads/keylogger/Keylogger.py
RakhithJK/brutus
train
0
82b347d25fc817ec12056895c869a0641b61e92d
[ "if cached_dependencies is not None:\n value = cached_dependencies.get(name)\nelse:\n value = super(NumpyState, self)._lookup_dependency(name)\nif value is None:\n value = _NumpyWrapper(np.array([]))\n new_reference = base.TrackableReference(name=name, ref=value)\n self._unconditional_checkpoint_depe...
<|body_start_0|> if cached_dependencies is not None: value = cached_dependencies.get(name) else: value = super(NumpyState, self)._lookup_dependency(name) if value is None: value = _NumpyWrapper(np.array([])) new_reference = base.TrackableReference(...
A checkpointable object whose NumPy array attributes are saved/restored. Example usage: ```python arrays = numpy_storage.NumpyState() checkpoint = tf.train.Checkpoint(numpy_arrays=arrays) arrays.x = np.ones([3, 4]) directory = self.get_temp_dir() prefix = os.path.join(directory, 'ckpt') save_path = checkpoint.save(pref...
NumpyState
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NumpyState: """A checkpointable object whose NumPy array attributes are saved/restored. Example usage: ```python arrays = numpy_storage.NumpyState() checkpoint = tf.train.Checkpoint(numpy_arrays=arrays) arrays.x = np.ones([3, 4]) directory = self.get_temp_dir() prefix = os.path.join(directory, 'c...
stack_v2_sparse_classes_36k_train_031050
9,502
permissive
[ { "docstring": "Create placeholder NumPy arrays for to-be-restored attributes. Typically `_lookup_dependency` is used to check by name whether a dependency exists. We cheat slightly by creating a checkpointable object for `name` if we don't already have one, giving us attribute re-creation behavior when loading...
3
null
Implement the Python class `NumpyState` described below. Class description: A checkpointable object whose NumPy array attributes are saved/restored. Example usage: ```python arrays = numpy_storage.NumpyState() checkpoint = tf.train.Checkpoint(numpy_arrays=arrays) arrays.x = np.ones([3, 4]) directory = self.get_temp_di...
Implement the Python class `NumpyState` described below. Class description: A checkpointable object whose NumPy array attributes are saved/restored. Example usage: ```python arrays = numpy_storage.NumpyState() checkpoint = tf.train.Checkpoint(numpy_arrays=arrays) arrays.x = np.ones([3, 4]) directory = self.get_temp_di...
eca1093d3a047e538f17f6ab92ab4d8144284f23
<|skeleton|> class NumpyState: """A checkpointable object whose NumPy array attributes are saved/restored. Example usage: ```python arrays = numpy_storage.NumpyState() checkpoint = tf.train.Checkpoint(numpy_arrays=arrays) arrays.x = np.ones([3, 4]) directory = self.get_temp_dir() prefix = os.path.join(directory, 'c...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NumpyState: """A checkpointable object whose NumPy array attributes are saved/restored. Example usage: ```python arrays = numpy_storage.NumpyState() checkpoint = tf.train.Checkpoint(numpy_arrays=arrays) arrays.x = np.ones([3, 4]) directory = self.get_temp_dir() prefix = os.path.join(directory, 'ckpt') save_pa...
the_stack_v2_python_sparse
tf_agents/utils/numpy_storage.py
tensorflow/agents
train
2,755
c97067a23527757ba5364863fe6c33b4bffd55d4
[ "super().__init__(**kwargs)\nif align_file_name != '':\n try:\n self.align_file = open(align_file_name, 'r')\n except FileNotFoundError:\n print('ERROR: Alignment file ' + align_file_name + ' not found.')\n exit()\nself.a_frame_extractor = Frame_extractor()\nself.b_frame_extractor = Frame...
<|body_start_0|> super().__init__(**kwargs) if align_file_name != '': try: self.align_file = open(align_file_name, 'r') except FileNotFoundError: print('ERROR: Alignment file ' + align_file_name + ' not found.') exit() self....
Main_link_control
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Main_link_control: def __init__(self, align_file_name='', a_lang_mark='', b_lang_mark='', **kwargs): """overriden block method""" <|body_0|> def process_bundle(self, bundle): """overriden block method""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_031051
1,839
no_license
[ { "docstring": "overriden block method", "name": "__init__", "signature": "def __init__(self, align_file_name='', a_lang_mark='', b_lang_mark='', **kwargs)" }, { "docstring": "overriden block method", "name": "process_bundle", "signature": "def process_bundle(self, bundle)" } ]
2
stack_v2_sparse_classes_30k_train_018586
Implement the Python class `Main_link_control` described below. Class description: Implement the Main_link_control class. Method signatures and docstrings: - def __init__(self, align_file_name='', a_lang_mark='', b_lang_mark='', **kwargs): overriden block method - def process_bundle(self, bundle): overriden block met...
Implement the Python class `Main_link_control` described below. Class description: Implement the Main_link_control class. Method signatures and docstrings: - def __init__(self, align_file_name='', a_lang_mark='', b_lang_mark='', **kwargs): overriden block method - def process_bundle(self, bundle): overriden block met...
194446ec1adeec5ef85db3f96b6d8d2876cc8811
<|skeleton|> class Main_link_control: def __init__(self, align_file_name='', a_lang_mark='', b_lang_mark='', **kwargs): """overriden block method""" <|body_0|> def process_bundle(self, bundle): """overriden block method""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Main_link_control: def __init__(self, align_file_name='', a_lang_mark='', b_lang_mark='', **kwargs): """overriden block method""" super().__init__(**kwargs) if align_file_name != '': try: self.align_file = open(align_file_name, 'r') except FileNo...
the_stack_v2_python_sparse
udapi-python/udapi/block/valency/control/main_link_control.py
Jankus1994/ud-valency
train
0
217e353e2c7c3f7dbcea52ef8addc8cd4310b080
[ "test = '2\\n-1 5\\n1 5'\nself.assertEqual(calculate(test), '10')\nself.assertEqual(get_inputs(test)[0], 2)\nself.assertEqual(list(get_inputs(test)[1]), [-1, 5, 1, 5])\ntest = '3\\n-2 2\\n1 4\\n-1 3'\nself.assertEqual(calculate(test), '9')\ntest = '3\\n1 9\\n3 5\\n7 10'\nself.assertEqual(calculate(test), '9')\ntest...
<|body_start_0|> test = '2\n-1 5\n1 5' self.assertEqual(calculate(test), '10') self.assertEqual(get_inputs(test)[0], 2) self.assertEqual(list(get_inputs(test)[1]), [-1, 5, 1, 5]) test = '3\n-2 2\n1 4\n-1 3' self.assertEqual(calculate(test), '9') test = '3\n1 9\n3 ...
unitTests
[ "Unlicense", "LicenseRef-scancode-public-domain" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class unitTests: def test_sample_tests(self): """Quiz sample tests. Add to separate lines""" <|body_0|> def test_Apple_class__basic_functions(self): """Apple class basic functions testing""" <|body_1|> <|end_skeleton|> <|body_start_0|> test = '2\n-1 5\n1 ...
stack_v2_sparse_classes_36k_train_031052
4,316
permissive
[ { "docstring": "Quiz sample tests. Add to separate lines", "name": "test_sample_tests", "signature": "def test_sample_tests(self)" }, { "docstring": "Apple class basic functions testing", "name": "test_Apple_class__basic_functions", "signature": "def test_Apple_class__basic_functions(sel...
2
stack_v2_sparse_classes_30k_train_014265
Implement the Python class `unitTests` described below. Class description: Implement the unitTests class. Method signatures and docstrings: - def test_sample_tests(self): Quiz sample tests. Add to separate lines - def test_Apple_class__basic_functions(self): Apple class basic functions testing
Implement the Python class `unitTests` described below. Class description: Implement the unitTests class. Method signatures and docstrings: - def test_sample_tests(self): Quiz sample tests. Add to separate lines - def test_Apple_class__basic_functions(self): Apple class basic functions testing <|skeleton|> class uni...
ae02ea872ca91ef98630cc172a844b82cc56f621
<|skeleton|> class unitTests: def test_sample_tests(self): """Quiz sample tests. Add to separate lines""" <|body_0|> def test_Apple_class__basic_functions(self): """Apple class basic functions testing""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class unitTests: def test_sample_tests(self): """Quiz sample tests. Add to separate lines""" test = '2\n-1 5\n1 5' self.assertEqual(calculate(test), '10') self.assertEqual(get_inputs(test)[0], 2) self.assertEqual(list(get_inputs(test)[1]), [-1, 5, 1, 5]) test = '3\n-2...
the_stack_v2_python_sparse
codeforces/558A_apple.py
snsokolov/contests
train
1
e3d7d5ffe762e18f302fb7898241c2c8a22e5ade
[ "super(GitDiff, self).__init__(path)\nself.path = path\nself.branch = branch\nself.diff_branch = diff_branch\nself.debug = []\nos.chdir(path)", "current_branch_results = self._get_current_branch()\nif current_branch_results['results'] == self.branch:\n return True\ncurrent_branch_results = self._checkout(self....
<|body_start_0|> super(GitDiff, self).__init__(path) self.path = path self.branch = branch self.diff_branch = diff_branch self.debug = [] os.chdir(path) <|end_body_0|> <|body_start_1|> current_branch_results = self._get_current_branch() if current_branch_...
Class to wrap the git merge line tools
GitDiff
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GitDiff: """Class to wrap the git merge line tools""" def __init__(self, path, branch, diff_branch): """Constructor for GitDiff""" <|body_0|> def checkout_branch(self): """check out the desired branch""" <|body_1|> def diff(self): """perform ...
stack_v2_sparse_classes_36k_train_031053
1,101
permissive
[ { "docstring": "Constructor for GitDiff", "name": "__init__", "signature": "def __init__(self, path, branch, diff_branch)" }, { "docstring": "check out the desired branch", "name": "checkout_branch", "signature": "def checkout_branch(self)" }, { "docstring": "perform a git diff",...
3
null
Implement the Python class `GitDiff` described below. Class description: Class to wrap the git merge line tools Method signatures and docstrings: - def __init__(self, path, branch, diff_branch): Constructor for GitDiff - def checkout_branch(self): check out the desired branch - def diff(self): perform a git diff
Implement the Python class `GitDiff` described below. Class description: Class to wrap the git merge line tools Method signatures and docstrings: - def __init__(self, path, branch, diff_branch): Constructor for GitDiff - def checkout_branch(self): check out the desired branch - def diff(self): perform a git diff <|s...
e342f6659a4ef1a188ff403e2fc6b06ac6d119c7
<|skeleton|> class GitDiff: """Class to wrap the git merge line tools""" def __init__(self, path, branch, diff_branch): """Constructor for GitDiff""" <|body_0|> def checkout_branch(self): """check out the desired branch""" <|body_1|> def diff(self): """perform ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GitDiff: """Class to wrap the git merge line tools""" def __init__(self, path, branch, diff_branch): """Constructor for GitDiff""" super(GitDiff, self).__init__(path) self.path = path self.branch = branch self.diff_branch = diff_branch self.debug = [] ...
the_stack_v2_python_sparse
ansible/roles/lib_git/build/src/git_diff.py
openshift/openshift-tools
train
170
64fcdc388482f2f40acca078d6d6aa8f8149c8f2
[ "stack = []\nans = []\nwhile stack or root:\n if root:\n ans.append(str(root.val))\n stack.append(root)\n root = root.left\n else:\n node = stack.pop()\n root = node.right\nreturn ' '.join(ans)", "if not data:\n return None\ndata = map(int, data.split(' '))\ndummy = roo...
<|body_start_0|> stack = [] ans = [] while stack or root: if root: ans.append(str(root.val)) stack.append(root) root = root.left else: node = stack.pop() root = node.right return ' '.j...
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_031054
2,343
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
null
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
e5d8ce9c8a9d43ce791655183f6c7cc713da004e
<|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""" stack = [] ans = [] while stack or root: if root: ans.append(str(root.val)) stack.append(root) root = root.lef...
the_stack_v2_python_sparse
Q449-Serialize and Deserialize BST-Medium.py
ChenxiiCheng/Python-LC-Solution
train
1
a468aa8b0a6d86d3a8df14de7dafffb8d82f1bc3
[ "self.bot = bot\nself.cmd = CommandCooldown()\nself.db = self.bot.db\nself.cds = self.db[self.bot.cfg.db.database].CooldownSystem", "if isinstance(user, str):\n cd_name = f'cd_{cmd}_{user}'\nelse:\n cd_name = f'cd_{cmd}_{user.id}'\nentry = self.cds.find_one({'name': cd_name})\nif entry:\n end_stamp = ent...
<|body_start_0|> self.bot = bot self.cmd = CommandCooldown() self.db = self.bot.db self.cds = self.db[self.bot.cfg.db.database].CooldownSystem <|end_body_0|> <|body_start_1|> if isinstance(user, str): cd_name = f'cd_{cmd}_{user}' else: cd_name = f...
CooldownControl
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CooldownControl: def __init__(self, bot): """The cooldown control core. A collection of functions to read cooldown data from mongo. Cooldowns are stored as MongoDB files so they persist. :param bot:""" <|body_0|> def on_cooldown(self, cmd, user): """A quick check to ...
stack_v2_sparse_classes_36k_train_031055
4,155
no_license
[ { "docstring": "The cooldown control core. A collection of functions to read cooldown data from mongo. Cooldowns are stored as MongoDB files so they persist. :param bot:", "name": "__init__", "signature": "def __init__(self, bot)" }, { "docstring": "A quick check to see if a user is on cool-down...
4
stack_v2_sparse_classes_30k_train_019364
Implement the Python class `CooldownControl` described below. Class description: Implement the CooldownControl class. Method signatures and docstrings: - def __init__(self, bot): The cooldown control core. A collection of functions to read cooldown data from mongo. Cooldowns are stored as MongoDB files so they persis...
Implement the Python class `CooldownControl` described below. Class description: Implement the CooldownControl class. Method signatures and docstrings: - def __init__(self, bot): The cooldown control core. A collection of functions to read cooldown data from mongo. Cooldowns are stored as MongoDB files so they persis...
72175c0f58e36c7b6325a6cb2224731434781aca
<|skeleton|> class CooldownControl: def __init__(self, bot): """The cooldown control core. A collection of functions to read cooldown data from mongo. Cooldowns are stored as MongoDB files so they persist. :param bot:""" <|body_0|> def on_cooldown(self, cmd, user): """A quick check to ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CooldownControl: def __init__(self, bot): """The cooldown control core. A collection of functions to read cooldown data from mongo. Cooldowns are stored as MongoDB files so they persist. :param bot:""" self.bot = bot self.cmd = CommandCooldown() self.db = self.bot.db se...
the_stack_v2_python_sparse
marshmallow/core/mechanics/cooldown.py
bretzle/Marshmallow-Bot
train
0
72f802d8f52419c39180f2005c7d5d769a5baf24
[ "initial = super().get_initial()\ninitial['product_id'] = self.kwargs['product_pk']\ninitial['purchaser'] = self.request.user.staff_member.id\nreturn initial", "context = super().get_context_data(*args, **kwargs)\ncontext['product'] = get_object_or_404(BaseProduct, pk=self.kwargs['product_pk'])\npurchase_charge =...
<|body_start_0|> initial = super().get_initial() initial['product_id'] = self.kwargs['product_pk'] initial['purchaser'] = self.request.user.staff_member.id return initial <|end_body_0|> <|body_start_1|> context = super().get_context_data(*args, **kwargs) context['product...
View for creating new purchases.
CreatePurchase
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CreatePurchase: """View for creating new purchases.""" def get_initial(self): """Return initial values for the form.""" <|body_0|> def get_context_data(self, *args, **kwargs): """Return context for the template.""" <|body_1|> def form_valid(self, for...
stack_v2_sparse_classes_36k_train_031056
5,763
no_license
[ { "docstring": "Return initial values for the form.", "name": "get_initial", "signature": "def get_initial(self)" }, { "docstring": "Return context for the template.", "name": "get_context_data", "signature": "def get_context_data(self, *args, **kwargs)" }, { "docstring": "Create...
3
stack_v2_sparse_classes_30k_val_001053
Implement the Python class `CreatePurchase` described below. Class description: View for creating new purchases. Method signatures and docstrings: - def get_initial(self): Return initial values for the form. - def get_context_data(self, *args, **kwargs): Return context for the template. - def form_valid(self, form): ...
Implement the Python class `CreatePurchase` described below. Class description: View for creating new purchases. Method signatures and docstrings: - def get_initial(self): Return initial values for the form. - def get_context_data(self, *args, **kwargs): Return context for the template. - def form_valid(self, form): ...
ba51d4e304b1aeb296fa2fe16611c892fcdbd471
<|skeleton|> class CreatePurchase: """View for creating new purchases.""" def get_initial(self): """Return initial values for the form.""" <|body_0|> def get_context_data(self, *args, **kwargs): """Return context for the template.""" <|body_1|> def form_valid(self, for...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CreatePurchase: """View for creating new purchases.""" def get_initial(self): """Return initial values for the form.""" initial = super().get_initial() initial['product_id'] = self.kwargs['product_pk'] initial['purchaser'] = self.request.user.staff_member.id return...
the_stack_v2_python_sparse
purchases/views.py
stcstores/stcadmin
train
0
05828022f8847c36214b54c9fda2dab4a3e07b67
[ "parser.add_argument('-u', '--username', default='User Name', help='User name')\nparser.add_argument('-e', '--email', default='user@bogus.com', help='User email')\nparser.add_argument('-i', '--instructor', action='store_true', help='Include in instructor group')\nparser.add_argument('-p', default='boguspwd', help='...
<|body_start_0|> parser.add_argument('-u', '--username', default='User Name', help='User name') parser.add_argument('-e', '--email', default='user@bogus.com', help='User email') parser.add_argument('-i', '--instructor', action='store_true', help='Include in instructor group') parser.add_...
Class implementing a command to create a single user.
Command
[ "LGPL-2.0-or-later", "BSD-3-Clause", "MIT", "Apache-2.0", "LGPL-2.1-only", "Python-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Command: """Class implementing a command to create a single user.""" def add_arguments(self, parser): """Parse command arguments.""" <|body_0|> def handle(self, *args, **options): """Execute command to create a single user. :param args: Arguments given to the com...
stack_v2_sparse_classes_36k_train_031057
2,328
permissive
[ { "docstring": "Parse command arguments.", "name": "add_arguments", "signature": "def add_arguments(self, parser)" }, { "docstring": "Execute command to create a single user. :param args: Arguments given to the command :param options: Options parsed :return: Nothing", "name": "handle", "...
2
null
Implement the Python class `Command` described below. Class description: Class implementing a command to create a single user. Method signatures and docstrings: - def add_arguments(self, parser): Parse command arguments. - def handle(self, *args, **options): Execute command to create a single user. :param args: Argum...
Implement the Python class `Command` described below. Class description: Class implementing a command to create a single user. Method signatures and docstrings: - def add_arguments(self, parser): Parse command arguments. - def handle(self, *args, **options): Execute command to create a single user. :param args: Argum...
c432745dfff932cbe7397100422d49df78f0a882
<|skeleton|> class Command: """Class implementing a command to create a single user.""" def add_arguments(self, parser): """Parse command arguments.""" <|body_0|> def handle(self, *args, **options): """Execute command to create a single user. :param args: Arguments given to the com...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Command: """Class implementing a command to create a single user.""" def add_arguments(self, parser): """Parse command arguments.""" parser.add_argument('-u', '--username', default='User Name', help='User name') parser.add_argument('-e', '--email', default='user@bogus.com', help='...
the_stack_v2_python_sparse
ontask/management/commands/create_user.py
abelardopardo/ontask_b
train
43
2b551172bf54fd9244d467e6079151b001a79ddf
[ "super(PositionalEncoding, self).__init__()\nself.dropout: nn.Dropout = nn.Dropout(p=dropout)\npe = torch.zeros(seq_len, d_model)\nposition = torch.arange(0, seq_len, dtype=torch.float).unsqueeze(1)\ndiv_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))\npe[:, 0::2] = torch.sin(...
<|body_start_0|> super(PositionalEncoding, self).__init__() self.dropout: nn.Dropout = nn.Dropout(p=dropout) pe = torch.zeros(seq_len, d_model) position = torch.arange(0, seq_len, dtype=torch.float).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.lo...
``Positional Encoding`` used in the ``Transformer`` model proposed in `Attention is all you need`. References: `Sequence-to-Sequence Modeling with nn.Transformer and TorchText <https://pytorch.org/tutorials/beginner/transformer_tutorial.html#define-the-model>`_
PositionalEncoding
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PositionalEncoding: """``Positional Encoding`` used in the ``Transformer`` model proposed in `Attention is all you need`. References: `Sequence-to-Sequence Modeling with nn.Transformer and TorchText <https://pytorch.org/tutorials/beginner/transformer_tutorial.html#define-the-model>`_""" def ...
stack_v2_sparse_classes_36k_train_031058
1,939
permissive
[ { "docstring": "Args: d_model: the number of expected features in the encoder/decoder inputs. seq_len: length of input sequence. dropout: dropout rate.", "name": "__init__", "signature": "def __init__(self, d_model: int, seq_len: int, dropout: float=0.1) -> None" }, { "docstring": "Forward propa...
2
stack_v2_sparse_classes_30k_train_006823
Implement the Python class `PositionalEncoding` described below. Class description: ``Positional Encoding`` used in the ``Transformer`` model proposed in `Attention is all you need`. References: `Sequence-to-Sequence Modeling with nn.Transformer and TorchText <https://pytorch.org/tutorials/beginner/transformer_tutoria...
Implement the Python class `PositionalEncoding` described below. Class description: ``Positional Encoding`` used in the ``Transformer`` model proposed in `Attention is all you need`. References: `Sequence-to-Sequence Modeling with nn.Transformer and TorchText <https://pytorch.org/tutorials/beginner/transformer_tutoria...
454d72a51daf8fab6419ceaa62c72d932fef2a61
<|skeleton|> class PositionalEncoding: """``Positional Encoding`` used in the ``Transformer`` model proposed in `Attention is all you need`. References: `Sequence-to-Sequence Modeling with nn.Transformer and TorchText <https://pytorch.org/tutorials/beginner/transformer_tutorial.html#define-the-model>`_""" def ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PositionalEncoding: """``Positional Encoding`` used in the ``Transformer`` model proposed in `Attention is all you need`. References: `Sequence-to-Sequence Modeling with nn.Transformer and TorchText <https://pytorch.org/tutorials/beginner/transformer_tutorial.html#define-the-model>`_""" def __init__(self...
the_stack_v2_python_sparse
enchanter/addons/layers/positional_encoding.py
khirotaka/enchanter
train
8
5716b5f02e9f550df441f371313598e695e5933e
[ "serializer = Serializer(REGISTER_ENCRYPT_KEY, 3600)\ntry:\n user_id = serializer.loads(token)\n user = User.objects.get(id=user_id)\n if user.is_active == 1:\n return render(request, 'active.html', {'user': user, 'error_msg': 'your email has been verified, Please login in directly!'})\n return r...
<|body_start_0|> serializer = Serializer(REGISTER_ENCRYPT_KEY, 3600) try: user_id = serializer.loads(token) user = User.objects.get(id=user_id) if user.is_active == 1: return render(request, 'active.html', {'user': user, 'error_msg': 'your email has be...
user activation
ActiveView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ActiveView: """user activation""" def get(self, request, token): """get user activation page""" <|body_0|> def post(self, request, token): """get the user information to activate it""" <|body_1|> <|end_skeleton|> <|body_start_0|> serializer = Se...
stack_v2_sparse_classes_36k_train_031059
28,206
no_license
[ { "docstring": "get user activation page", "name": "get", "signature": "def get(self, request, token)" }, { "docstring": "get the user information to activate it", "name": "post", "signature": "def post(self, request, token)" } ]
2
stack_v2_sparse_classes_30k_train_011164
Implement the Python class `ActiveView` described below. Class description: user activation Method signatures and docstrings: - def get(self, request, token): get user activation page - def post(self, request, token): get the user information to activate it
Implement the Python class `ActiveView` described below. Class description: user activation Method signatures and docstrings: - def get(self, request, token): get user activation page - def post(self, request, token): get the user information to activate it <|skeleton|> class ActiveView: """user activation""" ...
5efeebedd4695ef9d904beb707a1538ba049b187
<|skeleton|> class ActiveView: """user activation""" def get(self, request, token): """get user activation page""" <|body_0|> def post(self, request, token): """get the user information to activate it""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ActiveView: """user activation""" def get(self, request, token): """get user activation page""" serializer = Serializer(REGISTER_ENCRYPT_KEY, 3600) try: user_id = serializer.loads(token) user = User.objects.get(id=user_id) if user.is_active == 1...
the_stack_v2_python_sparse
dbbus/apps/user/views.py
mofiebiger/DublinBus
train
1
8c9a5abaf56e2c958ad44fd406c96d65f3833360
[ "if not hasattr(self, '_image'):\n img_dts = {}\n pname = self.product.name\n sname = self.sector.name\n img_dts['start_fullext' + sname + pname] = datetime.utcnow()\n log.info('Entering external data-based algorithm.')\n \"\\n Products are mapped one to one from productfiles/<platform_...
<|body_start_0|> if not hasattr(self, '_image'): img_dts = {} pname = self.product.name sname = self.sector.name img_dts['start_fullext' + sname + pname] = datetime.utcnow() log.info('Entering external data-based algorithm.') "\n ...
ExternalAlg
[ "LicenseRef-scancode-public-domain" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExternalAlg: def image(self): """ExternalAlg is different than ExternalImg in that it takes in the entire datafile for processing (rather than pre-registered data), and returns an arbitrary array or dictionary of arrays instead of an RGB image array). If a dictionary is returned, one ima...
stack_v2_sparse_classes_36k_train_031060
7,441
permissive
[ { "docstring": "ExternalAlg is different than ExternalImg in that it takes in the entire datafile for processing (rather than pre-registered data), and returns an arbitrary array or dictionary of arrays instead of an RGB image array). If a dictionary is returned, one image will be created per dictionary entry (...
3
stack_v2_sparse_classes_30k_train_002164
Implement the Python class `ExternalAlg` described below. Class description: Implement the ExternalAlg class. Method signatures and docstrings: - def image(self): ExternalAlg is different than ExternalImg in that it takes in the entire datafile for processing (rather than pre-registered data), and returns an arbitrar...
Implement the Python class `ExternalAlg` described below. Class description: Implement the ExternalAlg class. Method signatures and docstrings: - def image(self): ExternalAlg is different than ExternalImg in that it takes in the entire datafile for processing (rather than pre-registered data), and returns an arbitrar...
a07e128467b71a5bff25ba0215e020bfe57706dd
<|skeleton|> class ExternalAlg: def image(self): """ExternalAlg is different than ExternalImg in that it takes in the entire datafile for processing (rather than pre-registered data), and returns an arbitrary array or dictionary of arrays instead of an RGB image array). If a dictionary is returned, one ima...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ExternalAlg: def image(self): """ExternalAlg is different than ExternalImg in that it takes in the entire datafile for processing (rather than pre-registered data), and returns an arbitrary array or dictionary of arrays instead of an RGB image array). If a dictionary is returned, one image will be cre...
the_stack_v2_python_sparse
geoips/geoimg/plot/externalalg.py
WIEQLI/GeoIPS
train
0
6247bec60a0bc31fb748744866b29c2632956aa9
[ "legalMoves = gameState.getLegalActions()\nscores = [self.evaluationFunction(gameState, action) for action in legalMoves]\nbestScore = max(scores)\nbestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]\nchosenIndex = random.choice(bestIndices)\n'Add more of your code here if you want t...
<|body_start_0|> legalMoves = gameState.getLegalActions() scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestInd...
A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers.
ReflexAgent
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReflexAgent: """A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers.""" def getAction(sel...
stack_v2_sparse_classes_36k_train_031061
12,585
permissive
[ { "docstring": "You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {NORTH, SOUTH, WEST, EAST, STOP}", "...
2
stack_v2_sparse_classes_30k_train_012576
Implement the Python class `ReflexAgent` described below. Class description: A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our me...
Implement the Python class `ReflexAgent` described below. Class description: A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our me...
f0fa32a4af9354177af0af9e5792c5136173f0b8
<|skeleton|> class ReflexAgent: """A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers.""" def getAction(sel...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ReflexAgent: """A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers.""" def getAction(self, gameState)...
the_stack_v2_python_sparse
ArtificialIntelligence/Project2/multiagent/multiAgents.py
iuuuuuaena/CUG-Practice
train
7
df525bd38c608465b9fbf4899b120d90ed4cbcc5
[ "data = requests.get(url).text\nhtml = BeautifulSoup(data)\ntr = html.find_all('tr')\nhy = tr[0].find_all('td')[0].text.split('\\t')[0]\ntitle = [i.text for i in tr[1].find_all('td')]\ntitle = title[:2] + title[3:10]\ntitle.append('行业')\nres = []\nBM = {'B': 1000000000, 'M': 1000000}\nfor td in tr[2:-2]:\n td = ...
<|body_start_0|> data = requests.get(url).text html = BeautifulSoup(data) tr = html.find_all('tr') hy = tr[0].find_all('td')[0].text.split('\t')[0] title = [i.text for i in tr[1].find_all('td')] title = title[:2] + title[3:10] title.append('行业') res = [] ...
市值、货币、行业
BanKuai
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BanKuai: """市值、货币、行业""" def get_hyl(self, url): """以指定行业的URL获取其下所属的股票数据""" <|body_0|> def get_hys(self, url='http://www.etnet.com.hk/www/sc/stocks/industry_adu.php'): """获取所有的行业URL""" <|body_1|> def get_all(self): """获得所有数据""" <|body_...
stack_v2_sparse_classes_36k_train_031062
11,353
no_license
[ { "docstring": "以指定行业的URL获取其下所属的股票数据", "name": "get_hyl", "signature": "def get_hyl(self, url)" }, { "docstring": "获取所有的行业URL", "name": "get_hys", "signature": "def get_hys(self, url='http://www.etnet.com.hk/www/sc/stocks/industry_adu.php')" }, { "docstring": "获得所有数据", "name"...
3
stack_v2_sparse_classes_30k_train_015806
Implement the Python class `BanKuai` described below. Class description: 市值、货币、行业 Method signatures and docstrings: - def get_hyl(self, url): 以指定行业的URL获取其下所属的股票数据 - def get_hys(self, url='http://www.etnet.com.hk/www/sc/stocks/industry_adu.php'): 获取所有的行业URL - def get_all(self): 获得所有数据
Implement the Python class `BanKuai` described below. Class description: 市值、货币、行业 Method signatures and docstrings: - def get_hyl(self, url): 以指定行业的URL获取其下所属的股票数据 - def get_hys(self, url='http://www.etnet.com.hk/www/sc/stocks/industry_adu.php'): 获取所有的行业URL - def get_all(self): 获得所有数据 <|skeleton|> class BanKuai: ...
818ae04b6f2ca00495c73fd9b3810f083aa3339e
<|skeleton|> class BanKuai: """市值、货币、行业""" def get_hyl(self, url): """以指定行业的URL获取其下所属的股票数据""" <|body_0|> def get_hys(self, url='http://www.etnet.com.hk/www/sc/stocks/industry_adu.php'): """获取所有的行业URL""" <|body_1|> def get_all(self): """获得所有数据""" <|body_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BanKuai: """市值、货币、行业""" def get_hyl(self, url): """以指定行业的URL获取其下所属的股票数据""" data = requests.get(url).text html = BeautifulSoup(data) tr = html.find_all('tr') hy = tr[0].find_all('td')[0].text.split('\t')[0] title = [i.text for i in tr[1].find_all('td')] ...
the_stack_v2_python_sparse
2019/港股回购数据获取/huigou_guben.py
hunaghaikong/CodeAll
train
0
cb56898ebeae70e1c76faeaf5afa14abf8fccc75
[ "self.full_backup_script = full_backup_script\nself.incremental_backup_script = incremental_backup_script\nself.log_backup_script = log_backup_script\nself.remote_host = remote_host\nself.username = username", "if dictionary is None:\n return None\nfull_backup_script = cohesity_management_sdk.models.remote_scr...
<|body_start_0|> self.full_backup_script = full_backup_script self.incremental_backup_script = incremental_backup_script self.log_backup_script = log_backup_script self.remote_host = remote_host self.username = username <|end_body_0|> <|body_start_1|> if dictionary is No...
Implementation of the 'RemoteJobScript' model. Provides details about the Remote Adapter associated with a 'kPuppeteer' Protection Job. Attributes: full_backup_script (RemoteScriptPathAndParams): Specifies the script that should run for the Full (no CBT) backup schedule of a Remote Adapter 'kPuppeteer' Job. This field ...
RemoteJobScript
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RemoteJobScript: """Implementation of the 'RemoteJobScript' model. Provides details about the Remote Adapter associated with a 'kPuppeteer' Protection Job. Attributes: full_backup_script (RemoteScriptPathAndParams): Specifies the script that should run for the Full (no CBT) backup schedule of a R...
stack_v2_sparse_classes_36k_train_031063
4,552
permissive
[ { "docstring": "Constructor for the RemoteJobScript class", "name": "__init__", "signature": "def __init__(self, full_backup_script=None, incremental_backup_script=None, log_backup_script=None, remote_host=None, username=None)" }, { "docstring": "Creates an instance of this model from a dictiona...
2
stack_v2_sparse_classes_30k_train_005210
Implement the Python class `RemoteJobScript` described below. Class description: Implementation of the 'RemoteJobScript' model. Provides details about the Remote Adapter associated with a 'kPuppeteer' Protection Job. Attributes: full_backup_script (RemoteScriptPathAndParams): Specifies the script that should run for t...
Implement the Python class `RemoteJobScript` described below. Class description: Implementation of the 'RemoteJobScript' model. Provides details about the Remote Adapter associated with a 'kPuppeteer' Protection Job. Attributes: full_backup_script (RemoteScriptPathAndParams): Specifies the script that should run for t...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class RemoteJobScript: """Implementation of the 'RemoteJobScript' model. Provides details about the Remote Adapter associated with a 'kPuppeteer' Protection Job. Attributes: full_backup_script (RemoteScriptPathAndParams): Specifies the script that should run for the Full (no CBT) backup schedule of a R...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RemoteJobScript: """Implementation of the 'RemoteJobScript' model. Provides details about the Remote Adapter associated with a 'kPuppeteer' Protection Job. Attributes: full_backup_script (RemoteScriptPathAndParams): Specifies the script that should run for the Full (no CBT) backup schedule of a Remote Adapter...
the_stack_v2_python_sparse
cohesity_management_sdk/models/remote_job_script.py
cohesity/management-sdk-python
train
24
8e857d658f73fabc750a023ba5b9bc74ddb70530
[ "if type(description) is not dict or args or kwargs:\n raise RuntimeError('You appear to want the old DMA driver which has been deprecated and moved to pynq.lib.deprecated')\nsuper().__init__(description=description)\nself.description = description\nif 'parameters' not in description:\n raise RuntimeError('Un...
<|body_start_0|> if type(description) is not dict or args or kwargs: raise RuntimeError('You appear to want the old DMA driver which has been deprecated and moved to pynq.lib.deprecated') super().__init__(description=description) self.description = description if 'parameters'...
Class for Interacting with the AXI Simple DMA Engine This class provides two attributes for the read and write channels. The read channel copies data from the stream into memory and the write channel copies data from memory to the output stream. Both channels have an identical API consisting of `transfer` and `wait` fu...
DMA
[ "BSD-3-Clause", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DMA: """Class for Interacting with the AXI Simple DMA Engine This class provides two attributes for the read and write channels. The read channel copies data from the stream into memory and the write channel copies data from memory to the output stream. Both channels have an identical API consist...
stack_v2_sparse_classes_36k_train_031064
25,817
permissive
[ { "docstring": "Create an instance of the DMA Driver For DMA, max transfer length is (2^sg_length_width -1). See PG021 tables 2-15, 2-25, 2-31 and 2-38. Parameters ---------- description : dict The entry in the IP dict describing the DMA engine", "name": "__init__", "signature": "def __init__(self, desc...
3
null
Implement the Python class `DMA` described below. Class description: Class for Interacting with the AXI Simple DMA Engine This class provides two attributes for the read and write channels. The read channel copies data from the stream into memory and the write channel copies data from memory to the output stream. Both...
Implement the Python class `DMA` described below. Class description: Class for Interacting with the AXI Simple DMA Engine This class provides two attributes for the read and write channels. The read channel copies data from the stream into memory and the write channel copies data from memory to the output stream. Both...
38e9fcee46f0839e83e123cf22af76b13671a574
<|skeleton|> class DMA: """Class for Interacting with the AXI Simple DMA Engine This class provides two attributes for the read and write channels. The read channel copies data from the stream into memory and the write channel copies data from memory to the output stream. Both channels have an identical API consist...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DMA: """Class for Interacting with the AXI Simple DMA Engine This class provides two attributes for the read and write channels. The read channel copies data from the stream into memory and the write channel copies data from memory to the output stream. Both channels have an identical API consisting of `trans...
the_stack_v2_python_sparse
pynq/lib/dma.py
yunqu/PYNQ
train
8
1e756284afa662f793a74c7800a347180f7d95a9
[ "if not root:\n return []\nq = deque([root])\nres = []\nwhile q:\n size = len(q)\n while size > 0:\n size -= 1\n node = q.popleft()\n res.append(node.val)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\nreturn res", "...
<|body_start_0|> if not root: return [] q = deque([root]) res = [] while q: size = len(q) while size > 0: size -= 1 node = q.popleft() res.append(node.val) if node.left: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def levelOrder(self, root: TreeNode) -> List[int]: """Level order using a queue. BFS""" <|body_0|> def levelOrder2(self, root: TreeNode) -> List[List[int]]: """Level order using a queue. BFS""" <|body_1|> def levelOrder3(self, root: TreeNode) -...
stack_v2_sparse_classes_36k_train_031065
2,359
no_license
[ { "docstring": "Level order using a queue. BFS", "name": "levelOrder", "signature": "def levelOrder(self, root: TreeNode) -> List[int]" }, { "docstring": "Level order using a queue. BFS", "name": "levelOrder2", "signature": "def levelOrder2(self, root: TreeNode) -> List[List[int]]" }, ...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def levelOrder(self, root: TreeNode) -> List[int]: Level order using a queue. BFS - def levelOrder2(self, root: TreeNode) -> List[List[int]]: Level order using a queue. BFS - def...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def levelOrder(self, root: TreeNode) -> List[int]: Level order using a queue. BFS - def levelOrder2(self, root: TreeNode) -> List[List[int]]: Level order using a queue. BFS - def...
0f16635de49dc63a207d34f7e612546977a5753e
<|skeleton|> class Solution: def levelOrder(self, root: TreeNode) -> List[int]: """Level order using a queue. BFS""" <|body_0|> def levelOrder2(self, root: TreeNode) -> List[List[int]]: """Level order using a queue. BFS""" <|body_1|> def levelOrder3(self, root: TreeNode) -...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def levelOrder(self, root: TreeNode) -> List[int]: """Level order using a queue. BFS""" if not root: return [] q = deque([root]) res = [] while q: size = len(q) while size > 0: size -= 1 node ...
the_stack_v2_python_sparse
jianzhioffer/32-1levelOrderTraverse.py
bycxw/coder
train
0
a24fd9e3332d60a70c72263725aa8fc42f9bb77c
[ "a = []\n\ndef helper(root):\n if not root:\n a.append('#')\n return\n a.append(str(root.val))\n helper(root.left)\n helper(root.right)\nhelper(root)\nreturn ' '.join(a)", "a = data.split()\nself.i = 0\n\ndef helper():\n if a[self.i] == '#':\n self.i += 1\n return None\n...
<|body_start_0|> a = [] def helper(root): if not root: a.append('#') return a.append(str(root.val)) helper(root.left) helper(root.right) helper(root) return ' '.join(a) <|end_body_0|> <|body_start_1|> ...
Codec_DFS
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec_DFS: 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|> <|b...
stack_v2_sparse_classes_36k_train_031066
5,078
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_020344
Implement the Python class `Codec_DFS` described below. Class description: Implement the Codec_DFS 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...
Implement the Python class `Codec_DFS` described below. Class description: Implement the Codec_DFS 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...
635af6e22aa8eef8e7920a585d43a45a891a8157
<|skeleton|> class Codec_DFS: 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_DFS: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" a = [] def helper(root): if not root: a.append('#') return a.append(str(root.val)) helper(root.left) ...
the_stack_v2_python_sparse
code297SerializeAndDeserializeBinaryTree.py
cybelewang/leetcode-python
train
0
5bf508a5d1476c83e97a645f47e391f00f0ca9da
[ "res = []\nif not root:\n return res\nres.append(root.val)\nfrontier = deque([root])\nwhile frontier:\n expand = frontier.popleft()\n for kid in (expand.left, expand.right):\n if kid is None:\n res.append(None)\n else:\n res.append(kid.val)\n frontier.append(k...
<|body_start_0|> res = [] if not root: return res res.append(root.val) frontier = deque([root]) while frontier: expand = frontier.popleft() for kid in (expand.left, expand.right): if kid is None: res.append(N...
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_031067
2,351
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_007817
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:...
11d6bf2ba7b50c07e048df37c4e05c8f46b92241
<|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""" res = [] if not root: return res res.append(root.val) frontier = deque([root]) while frontier: expand = frontier.popleft() ...
the_stack_v2_python_sparse
LeetCodes/facebook/Serialize and Deserialize Binary Tree.py
chutianwen/LeetCodes
train
0
3dfb196226adeb20568b0a7048d1859a22168fcb
[ "self.config = config\nself.classifier = classifier\nself.orig_image = orig_image\nwith tf.variable_scope('taint'):\n self.taint = tf.Variable(tf.random_uniform([self.config['img_height'], self.config['img_width']], dtype=tf.float64))\nself.loss = self.add_loss_op(self.taint)\nself.train_op = self.add_train_op(s...
<|body_start_0|> self.config = config self.classifier = classifier self.orig_image = orig_image with tf.variable_scope('taint'): self.taint = tf.Variable(tf.random_uniform([self.config['img_height'], self.config['img_width']], dtype=tf.float64)) self.loss = self.add_l...
Represents an adversarial system that uses gradient descent to minimize the loss (-1 * <classifier loss>) + lambda * <norm of taint>^2. This loss maximizes the classifier's probability of the tainted image being the target letter while keeping the "amount of taint" small.
GradAdv
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GradAdv: """Represents an adversarial system that uses gradient descent to minimize the loss (-1 * <classifier loss>) + lambda * <norm of taint>^2. This loss maximizes the classifier's probability of the tainted image being the target letter while keeping the "amount of taint" small.""" def ...
stack_v2_sparse_classes_36k_train_031068
6,004
permissive
[ { "docstring": "Initializes the GradAdv object with a configuration, classifier, and original image Args: config: a dictionary containing hyperparameters and settings such as img_height, img_width, num_classes (26 for just identifying letters), epochs, learning_rate, norm_constant (lambda in the GradAdv descrip...
5
stack_v2_sparse_classes_30k_train_013547
Implement the Python class `GradAdv` described below. Class description: Represents an adversarial system that uses gradient descent to minimize the loss (-1 * <classifier loss>) + lambda * <norm of taint>^2. This loss maximizes the classifier's probability of the tainted image being the target letter while keeping th...
Implement the Python class `GradAdv` described below. Class description: Represents an adversarial system that uses gradient descent to minimize the loss (-1 * <classifier loss>) + lambda * <norm of taint>^2. This loss maximizes the classifier's probability of the tainted image being the target letter while keeping th...
2159e8891c7b60b0d947ea6310e8a52ef8b4392f
<|skeleton|> class GradAdv: """Represents an adversarial system that uses gradient descent to minimize the loss (-1 * <classifier loss>) + lambda * <norm of taint>^2. This loss maximizes the classifier's probability of the tainted image being the target letter while keeping the "amount of taint" small.""" def ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GradAdv: """Represents an adversarial system that uses gradient descent to minimize the loss (-1 * <classifier loss>) + lambda * <norm of taint>^2. This loss maximizes the classifier's probability of the tainted image being the target letter while keeping the "amount of taint" small.""" def __init__(self...
the_stack_v2_python_sparse
src/grad_adv.py
asjchen/taint
train
1
0a1ee42ef5d5173186bf631d9190e131b4c34ea3
[ "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...
Missing associated documentation comment in .proto file.
BufferServicer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BufferServicer: """Missing associated documentation comment in .proto file.""" def SendTrajectories(self, request_iterator, context): """Missing associated documentation comment in .proto file.""" <|body_0|> def SendExperiences(self, request_iterator, context): "...
stack_v2_sparse_classes_36k_train_031069
3,945
permissive
[ { "docstring": "Missing associated documentation comment in .proto file.", "name": "SendTrajectories", "signature": "def SendTrajectories(self, request_iterator, context)" }, { "docstring": "Missing associated documentation comment in .proto file.", "name": "SendExperiences", "signature"...
2
stack_v2_sparse_classes_30k_train_019350
Implement the Python class `BufferServicer` described below. Class description: Missing associated documentation comment in .proto file. Method signatures and docstrings: - def SendTrajectories(self, request_iterator, context): Missing associated documentation comment in .proto file. - def SendExperiences(self, reque...
Implement the Python class `BufferServicer` described below. Class description: Missing associated documentation comment in .proto file. Method signatures and docstrings: - def SendTrajectories(self, request_iterator, context): Missing associated documentation comment in .proto file. - def SendExperiences(self, reque...
28723664cd408e3e33c40658284ed24b0068027f
<|skeleton|> class BufferServicer: """Missing associated documentation comment in .proto file.""" def SendTrajectories(self, request_iterator, context): """Missing associated documentation comment in .proto file.""" <|body_0|> def SendExperiences(self, request_iterator, context): "...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BufferServicer: """Missing associated documentation comment in .proto file.""" def SendTrajectories(self, request_iterator, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not impl...
the_stack_v2_python_sparse
rls/distribute/pb2/apex_buffer_pb2_grpc.py
nisheethjaiswal/RLs
train
0
0f9d262f05dfe04e665c7bf42067f34b368712d6
[ "super(SelfAttention, self).__init__()\nself.W = tf.keras.layers.Dense(units)\nself.U = tf.keras.layers.Dense(units)\nself.V = tf.keras.layers.Dense(1)", "new_s_prev = tf.expand_dims(s_prev, axis=1)\nscore = self.V(tf.nn.tanh(self.W(new_s_prev) + self.U(hidden_states)))\nweights = tf.nn.softmax(score, axis=1)\nco...
<|body_start_0|> super(SelfAttention, self).__init__() self.W = tf.keras.layers.Dense(units) self.U = tf.keras.layers.Dense(units) self.V = tf.keras.layers.Dense(1) <|end_body_0|> <|body_start_1|> new_s_prev = tf.expand_dims(s_prev, axis=1) score = self.V(tf.nn.tanh(self...
Class Self attention
SelfAttention
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SelfAttention: """Class Self attention""" def __init__(self, units): """method initializer Args: units: Integer representing the number of hidden units in the alignment model W - Dense layer with units units, to be applied to the previous decoder hidden state U - Dense layer with uni...
stack_v2_sparse_classes_36k_train_031070
1,833
no_license
[ { "docstring": "method initializer Args: units: Integer representing the number of hidden units in the alignment model W - Dense layer with units units, to be applied to the previous decoder hidden state U - Dense layer with units units, to be applied to the encoder hidden states V - Dense layer with 1 units, t...
2
stack_v2_sparse_classes_30k_train_013133
Implement the Python class `SelfAttention` described below. Class description: Class Self attention Method signatures and docstrings: - def __init__(self, units): method initializer Args: units: Integer representing the number of hidden units in the alignment model W - Dense layer with units units, to be applied to t...
Implement the Python class `SelfAttention` described below. Class description: Class Self attention Method signatures and docstrings: - def __init__(self, units): method initializer Args: units: Integer representing the number of hidden units in the alignment model W - Dense layer with units units, to be applied to t...
7f9a040f23eda32c5aa154c991c930a01b490f0f
<|skeleton|> class SelfAttention: """Class Self attention""" def __init__(self, units): """method initializer Args: units: Integer representing the number of hidden units in the alignment model W - Dense layer with units units, to be applied to the previous decoder hidden state U - Dense layer with uni...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SelfAttention: """Class Self attention""" def __init__(self, units): """method initializer Args: units: Integer representing the number of hidden units in the alignment model W - Dense layer with units units, to be applied to the previous decoder hidden state U - Dense layer with units units, to ...
the_stack_v2_python_sparse
supervised_learning/0x11-attention/1-self_attention.py
dbaroli/holbertonschool-machine_learning
train
0
ecfd7d5871bde42a25414b22df1aecb02b5ffc5d
[ "codec = cls()\ncodec_info = {'encode': codec.encode, 'decode': codec.decode, '_is_text_encoding': False}\nreturn CodecInfo(**codec_info)", "if isinstance(input, memoryview):\n input = input.tobytes()\nif not isinstance(input, (bytes, bytearray)):\n raise with_context(exc=TypeError(\"Can't encode {type}; by...
<|body_start_0|> codec = cls() codec_info = {'encode': codec.encode, 'decode': codec.decode, '_is_text_encoding': False} return CodecInfo(**codec_info) <|end_body_0|> <|body_start_1|> if isinstance(input, memoryview): input = input.tobytes() if not isinstance(input, ...
Legacy codec for converting byte strings into trytes, and vice versa. This method encodes each pair of trytes as an ASCII code point (and vice versa when decoding). The end result requires more space than if the trytes were converted mathematically, but because the result is ASCII, it's easier to work with. Think of th...
AsciiTrytesCodec
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AsciiTrytesCodec: """Legacy codec for converting byte strings into trytes, and vice versa. This method encodes each pair of trytes as an ASCII code point (and vice versa when decoding). The end result requires more space than if the trytes were converted mathematically, but because the result is ...
stack_v2_sparse_classes_36k_train_031071
6,409
permissive
[ { "docstring": "Returns information used by the codecs library to configure the codec for use.", "name": "get_codec_info", "signature": "def get_codec_info(cls) -> CodecInfo" }, { "docstring": "Encodes a byte string into trytes.", "name": "encode", "signature": "def encode(self, input: U...
3
stack_v2_sparse_classes_30k_train_015105
Implement the Python class `AsciiTrytesCodec` described below. Class description: Legacy codec for converting byte strings into trytes, and vice versa. This method encodes each pair of trytes as an ASCII code point (and vice versa when decoding). The end result requires more space than if the trytes were converted mat...
Implement the Python class `AsciiTrytesCodec` described below. Class description: Legacy codec for converting byte strings into trytes, and vice versa. This method encodes each pair of trytes as an ASCII code point (and vice versa when decoding). The end result requires more space than if the trytes were converted mat...
d7b4c923fd3aec045b94719ad9a747ac8253541c
<|skeleton|> class AsciiTrytesCodec: """Legacy codec for converting byte strings into trytes, and vice versa. This method encodes each pair of trytes as an ASCII code point (and vice versa when decoding). The end result requires more space than if the trytes were converted mathematically, but because the result is ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AsciiTrytesCodec: """Legacy codec for converting byte strings into trytes, and vice versa. This method encodes each pair of trytes as an ASCII code point (and vice versa when decoding). The end result requires more space than if the trytes were converted mathematically, but because the result is ASCII, it's e...
the_stack_v2_python_sparse
iota/codecs.py
fprotopapa/iota.py
train
0
90446aafea8231211b56868c9247836ee15be91b
[ "my_wifi = self.driver.find_element_by_xpath('/html/body/div[1]/div/div/div/header/div[2]/ul/li[1]/div/div')\nActionChains(self.driver).move_to_element(my_wifi).perform()\ntime.sleep(1)\ndecices = self.driver.find_element_by_xpath('/html/body/div[1]/div/div/div/header/div[2]/ul/li[1]/ul/li[2]')\nActionChains(self.d...
<|body_start_0|> my_wifi = self.driver.find_element_by_xpath('/html/body/div[1]/div/div/div/header/div[2]/ul/li[1]/div/div') ActionChains(self.driver).move_to_element(my_wifi).perform() time.sleep(1) decices = self.driver.find_element_by_xpath('/html/body/div[1]/div/div/div/header/div[2]...
MyWifi
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyWifi: def test_access_devices_limit_time(self): """接入设备-限时""" <|body_0|> def test_access_devices_limit_speed(self): """接入设备-限速""" <|body_1|> <|end_skeleton|> <|body_start_0|> my_wifi = self.driver.find_element_by_xpath('/html/body/div[1]/div/div/d...
stack_v2_sparse_classes_36k_train_031072
3,434
no_license
[ { "docstring": "接入设备-限时", "name": "test_access_devices_limit_time", "signature": "def test_access_devices_limit_time(self)" }, { "docstring": "接入设备-限速", "name": "test_access_devices_limit_speed", "signature": "def test_access_devices_limit_speed(self)" } ]
2
stack_v2_sparse_classes_30k_train_017457
Implement the Python class `MyWifi` described below. Class description: Implement the MyWifi class. Method signatures and docstrings: - def test_access_devices_limit_time(self): 接入设备-限时 - def test_access_devices_limit_speed(self): 接入设备-限速
Implement the Python class `MyWifi` described below. Class description: Implement the MyWifi class. Method signatures and docstrings: - def test_access_devices_limit_time(self): 接入设备-限时 - def test_access_devices_limit_speed(self): 接入设备-限速 <|skeleton|> class MyWifi: def test_access_devices_limit_time(self): ...
794cae756d4316c2ad75399e57b24bbce5776210
<|skeleton|> class MyWifi: def test_access_devices_limit_time(self): """接入设备-限时""" <|body_0|> def test_access_devices_limit_speed(self): """接入设备-限速""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MyWifi: def test_access_devices_limit_time(self): """接入设备-限时""" my_wifi = self.driver.find_element_by_xpath('/html/body/div[1]/div/div/div/header/div[2]/ul/li[1]/div/div') ActionChains(self.driver).move_to_element(my_wifi).perform() time.sleep(1) decices = self.driver.f...
the_stack_v2_python_sparse
WebAuto/test_my_wifi.py
jungaohzz/Practice_1
train
0
09664f8a4cce173651142202ebfab6d36a157a55
[ "data = super().read()\nprint(f'Read and decompressed {data}')\nreturn data", "print(f'Compressing {data}')\nsuper().write(data)\nprint(f'Compressed {data} written')" ]
<|body_start_0|> data = super().read() print(f'Read and decompressed {data}') return data <|end_body_0|> <|body_start_1|> print(f'Compressing {data}') super().write(data) print(f'Compressed {data} written') <|end_body_1|>
This is a decorator (read: wrapper) adds compression/decompression behaviour to a datasource (just place holder print statements for this example). This decorator can wrap around a concrete DataSource (like FileDataSource) or it can also wrap around another Decorator (like the EncryptionDataSourceDecorator).
CompressedDataSourceDecorator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CompressedDataSourceDecorator: """This is a decorator (read: wrapper) adds compression/decompression behaviour to a datasource (just place holder print statements for this example). This decorator can wrap around a concrete DataSource (like FileDataSource) or it can also wrap around another Decor...
stack_v2_sparse_classes_36k_train_031073
6,195
no_license
[ { "docstring": "\"Decompress\" the data read from the object that this decorator is wrapped around. :return: the data read as a string", "name": "read", "signature": "def read(self)" }, { "docstring": "\"Compress\" data before writing it to a data source that this decorator is wrapped around. :p...
2
stack_v2_sparse_classes_30k_train_009899
Implement the Python class `CompressedDataSourceDecorator` described below. Class description: This is a decorator (read: wrapper) adds compression/decompression behaviour to a datasource (just place holder print statements for this example). This decorator can wrap around a concrete DataSource (like FileDataSource) o...
Implement the Python class `CompressedDataSourceDecorator` described below. Class description: This is a decorator (read: wrapper) adds compression/decompression behaviour to a datasource (just place holder print statements for this example). This decorator can wrap around a concrete DataSource (like FileDataSource) o...
68ad3a22646c5433e395fbee2c1fbb972b805c09
<|skeleton|> class CompressedDataSourceDecorator: """This is a decorator (read: wrapper) adds compression/decompression behaviour to a datasource (just place holder print statements for this example). This decorator can wrap around a concrete DataSource (like FileDataSource) or it can also wrap around another Decor...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CompressedDataSourceDecorator: """This is a decorator (read: wrapper) adds compression/decompression behaviour to a datasource (just place holder print statements for this example). This decorator can wrap around a concrete DataSource (like FileDataSource) or it can also wrap around another Decorator (like th...
the_stack_v2_python_sparse
Lectures/1028/decorator_example.py
usop7/Python_OOP_Projects
train
0
f4cbea656d5fb9c9e504d6f88f971acebd218660
[ "q = kwd.get('q', '')\nif not q:\n raise NotImplemented('Listing of all the tools is not implemented. Provide parameter \"q\" to search instead.')\nelse:\n page = kwd.get('page', 1)\n page_size = kwd.get('page_size', 10)\n try:\n page = int(page)\n page_size = int(page_size)\n except Va...
<|body_start_0|> q = kwd.get('q', '') if not q: raise NotImplemented('Listing of all the tools is not implemented. Provide parameter "q" to search instead.') else: page = kwd.get('page', 1) page_size = kwd.get('page_size', 10) try: ...
RESTful controller for interactions with tools in the Tool Shed.
ToolsController
[ "CC-BY-2.5", "AFL-2.1", "AFL-3.0", "CC-BY-3.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ToolsController: """RESTful controller for interactions with tools in the Tool Shed.""" def index(self, trans, **kwd): """GET /api/tools Displays a collection of tools with optional criteria. :param q: (optional)if present search on the given query will be performed :type q: str :par...
stack_v2_sparse_classes_36k_train_031074
4,493
permissive
[ { "docstring": "GET /api/tools Displays a collection of tools with optional criteria. :param q: (optional)if present search on the given query will be performed :type q: str :param page: (optional)requested page of the search :type page: int :param page_size: (optional)requested page_size of the search :type pa...
2
null
Implement the Python class `ToolsController` described below. Class description: RESTful controller for interactions with tools in the Tool Shed. Method signatures and docstrings: - def index(self, trans, **kwd): GET /api/tools Displays a collection of tools with optional criteria. :param q: (optional)if present sear...
Implement the Python class `ToolsController` described below. Class description: RESTful controller for interactions with tools in the Tool Shed. Method signatures and docstrings: - def index(self, trans, **kwd): GET /api/tools Displays a collection of tools with optional criteria. :param q: (optional)if present sear...
1ad89511540e6800cd2d0da5d878c1c77d8ccfe9
<|skeleton|> class ToolsController: """RESTful controller for interactions with tools in the Tool Shed.""" def index(self, trans, **kwd): """GET /api/tools Displays a collection of tools with optional criteria. :param q: (optional)if present search on the given query will be performed :type q: str :par...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ToolsController: """RESTful controller for interactions with tools in the Tool Shed.""" def index(self, trans, **kwd): """GET /api/tools Displays a collection of tools with optional criteria. :param q: (optional)if present search on the given query will be performed :type q: str :param page: (opt...
the_stack_v2_python_sparse
lib/galaxy/webapps/tool_shed/api/tools.py
abretaud/galaxy
train
0
568da508e4482fe744c0a69277722f462e92e847
[ "list_dict = []\ndata = pd.read_json(self.path, encoding='utf-8')\nfor t in data.iterrows():\n d = dict(t[1])\n list_dict.append(d)\ndf = pd.DataFrame.from_dict(self.dropnested(list_dict))\ndf['date'] = df['acquisitionTime'].apply(lambda t: parser.isoparse(t))\ndf['date'] = df.date.dt.tz_localize(None)\ndf['d...
<|body_start_0|> list_dict = [] data = pd.read_json(self.path, encoding='utf-8') for t in data.iterrows(): d = dict(t[1]) list_dict.append(d) df = pd.DataFrame.from_dict(self.dropnested(list_dict)) df['date'] = df['acquisitionTime'].apply(lambda t: parser....
GoogleAppsReader
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GoogleAppsReader: def read(self): """Read json file and give a panda dataframe cleaned ---> encoding utf-8 to avoid special character not readable (é, ü etc...) ---> all nested dictionnaries (ie. each app) is put in a list ---> the dataframe is constructed from the returned dictionnary f...
stack_v2_sparse_classes_36k_train_031075
3,240
permissive
[ { "docstring": "Read json file and give a panda dataframe cleaned ---> encoding utf-8 to avoid special character not readable (é, ü etc...) ---> all nested dictionnaries (ie. each app) is put in a list ---> the dataframe is constructed from the returned dictionnary from dropnested ---> parser.isoparse transform...
2
stack_v2_sparse_classes_30k_train_002324
Implement the Python class `GoogleAppsReader` described below. Class description: Implement the GoogleAppsReader class. Method signatures and docstrings: - def read(self): Read json file and give a panda dataframe cleaned ---> encoding utf-8 to avoid special character not readable (é, ü etc...) ---> all nested dictio...
Implement the Python class `GoogleAppsReader` described below. Class description: Implement the GoogleAppsReader class. Method signatures and docstrings: - def read(self): Read json file and give a panda dataframe cleaned ---> encoding utf-8 to avoid special character not readable (é, ü etc...) ---> all nested dictio...
179dd4f04713026656c0849916166fd1ed0d6f31
<|skeleton|> class GoogleAppsReader: def read(self): """Read json file and give a panda dataframe cleaned ---> encoding utf-8 to avoid special character not readable (é, ü etc...) ---> all nested dictionnaries (ie. each app) is put in a list ---> the dataframe is constructed from the returned dictionnary f...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GoogleAppsReader: def read(self): """Read json file and give a panda dataframe cleaned ---> encoding utf-8 to avoid special character not readable (é, ü etc...) ---> all nested dictionnaries (ie. each app) is put in a list ---> the dataframe is constructed from the returned dictionnary from dropnested...
the_stack_v2_python_sparse
Package/google_sub_readers/apps.py
AdrienCarthoblaz/Master-Thesis
train
2
51c625dbc71a1250e342d1b2144940129cf285e6
[ "base.DataLayer.__init__(self, **kwargs)\nself._filenames = self.spec['puff']\nself._use_mpi = self.spec.get('use_mpi', True)\nself._minibatch = self.spec['minibatch']\nself._puffs = [base.Puff(filename) for filename in self._filenames]\nnum_data = [puff.num_data() for puff in self._puffs]\nif len(set(num_data)) ==...
<|body_start_0|> base.DataLayer.__init__(self, **kwargs) self._filenames = self.spec['puff'] self._use_mpi = self.spec.get('use_mpi', True) self._minibatch = self.spec['minibatch'] self._puffs = [base.Puff(filename) for filename in self._filenames] num_data = [puff.num_da...
A layer that loads data from a set of puff files.
PuffSamplerLayer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PuffSamplerLayer: """A layer that loads data from a set of puff files.""" def __init__(self, **kwargs): """Initializes the Puff sampling layer. kwargs: minibatch: the minibatch size. puff: a list of puff files to be read. These files should have the same number of data points, and th...
stack_v2_sparse_classes_36k_train_031076
2,104
no_license
[ { "docstring": "Initializes the Puff sampling layer. kwargs: minibatch: the minibatch size. puff: a list of puff files to be read. These files should have the same number of data points, and the sampler will return data points from different points with the same index. use_mpi: if set True, when the code is run...
2
stack_v2_sparse_classes_30k_train_021281
Implement the Python class `PuffSamplerLayer` described below. Class description: A layer that loads data from a set of puff files. Method signatures and docstrings: - def __init__(self, **kwargs): Initializes the Puff sampling layer. kwargs: minibatch: the minibatch size. puff: a list of puff files to be read. These...
Implement the Python class `PuffSamplerLayer` described below. Class description: A layer that loads data from a set of puff files. Method signatures and docstrings: - def __init__(self, **kwargs): Initializes the Puff sampling layer. kwargs: minibatch: the minibatch size. puff: a list of puff files to be read. These...
6fa4cdfbd0d0b8d486d7146bf1e32edd3662fec4
<|skeleton|> class PuffSamplerLayer: """A layer that loads data from a set of puff files.""" def __init__(self, **kwargs): """Initializes the Puff sampling layer. kwargs: minibatch: the minibatch size. puff: a list of puff files to be read. These files should have the same number of data points, and th...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PuffSamplerLayer: """A layer that loads data from a set of puff files.""" def __init__(self, **kwargs): """Initializes the Puff sampling layer. kwargs: minibatch: the minibatch size. puff: a list of puff files to be read. These files should have the same number of data points, and the sampler wil...
the_stack_v2_python_sparse
decaf/layers/puffsampler.py
UCBAIR/decaf-release
train
62
86f281e80929c33a34ec8dc63e07c5478c3947c3
[ "super().__init__(reduce, transfer_attributes)\nself._time_window = time_window\nself._cluster_method = DBSCAN(self._time_window, min_samples=1)\nself._keys = keys\nself._time_key = time_key", "dom_index = group_by(data, self._keys)\nif data.batch is not None:\n features = data.features[0]\nelse:\n features...
<|body_start_0|> super().__init__(reduce, transfer_attributes) self._time_window = time_window self._cluster_method = DBSCAN(self._time_window, min_samples=1) self._keys = keys self._time_key = time_key <|end_body_0|> <|body_start_1|> dom_index = group_by(data, self._key...
Coarsen pulses to DOM-level, with additional time-window clustering.
DOMAndTimeWindowCoarsening
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DOMAndTimeWindowCoarsening: """Coarsen pulses to DOM-level, with additional time-window clustering.""" def __init__(self, time_window: float, reduce: str='avg', transfer_attributes: bool=True, keys: List[str]=['dom_x', 'dom_y', 'dom_z', 'rde', 'pmt_area'], time_key: str='dom_time'): ...
stack_v2_sparse_classes_36k_train_031077
11,190
permissive
[ { "docstring": "Cluster pulses on the same DOM within `time_window`.", "name": "__init__", "signature": "def __init__(self, time_window: float, reduce: str='avg', transfer_attributes: bool=True, keys: List[str]=['dom_x', 'dom_y', 'dom_z', 'rde', 'pmt_area'], time_key: str='dom_time')" }, { "docs...
2
stack_v2_sparse_classes_30k_train_018223
Implement the Python class `DOMAndTimeWindowCoarsening` described below. Class description: Coarsen pulses to DOM-level, with additional time-window clustering. Method signatures and docstrings: - def __init__(self, time_window: float, reduce: str='avg', transfer_attributes: bool=True, keys: List[str]=['dom_x', 'dom_...
Implement the Python class `DOMAndTimeWindowCoarsening` described below. Class description: Coarsen pulses to DOM-level, with additional time-window clustering. Method signatures and docstrings: - def __init__(self, time_window: float, reduce: str='avg', transfer_attributes: bool=True, keys: List[str]=['dom_x', 'dom_...
f6e03282dd665c81d06eaa1ab55a07d138064e9a
<|skeleton|> class DOMAndTimeWindowCoarsening: """Coarsen pulses to DOM-level, with additional time-window clustering.""" def __init__(self, time_window: float, reduce: str='avg', transfer_attributes: bool=True, keys: List[str]=['dom_x', 'dom_y', 'dom_z', 'rde', 'pmt_area'], time_key: str='dom_time'): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DOMAndTimeWindowCoarsening: """Coarsen pulses to DOM-level, with additional time-window clustering.""" def __init__(self, time_window: float, reduce: str='avg', transfer_attributes: bool=True, keys: List[str]=['dom_x', 'dom_y', 'dom_z', 'rde', 'pmt_area'], time_key: str='dom_time'): """Cluster pu...
the_stack_v2_python_sparse
src/graphnet/models/coarsening.py
graphnet-team/graphnet
train
55
ae0c89122b0b25bb91f45d8b43586a5d87704185
[ "res = []\nself.dfs(root, res)\nreturn res", "if root:\n self.dfs(root.left, res)\n self.dfs(root.right, res)\n res.append(root.val)", "if not root:\n return []\nstack, res = ([root], [])\nwhile stack:\n node = stack.pop()\n if node.left:\n stack.append(node.left)\n if node.right:\n ...
<|body_start_0|> res = [] self.dfs(root, res) return res <|end_body_0|> <|body_start_1|> if root: self.dfs(root.left, res) self.dfs(root.right, res) res.append(root.val) <|end_body_1|> <|body_start_2|> if not root: return [] ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def postorderTraversal(self, root): """:type root: TreeNode :rtype: List[int]""" <|body_0|> def dfs(self, root, res): """:type root: TreeNode :type res: List[int] :rtype: None""" <|body_1|> def postorderTraversal_1(self, root): """:type...
stack_v2_sparse_classes_36k_train_031078
2,233
no_license
[ { "docstring": ":type root: TreeNode :rtype: List[int]", "name": "postorderTraversal", "signature": "def postorderTraversal(self, root)" }, { "docstring": ":type root: TreeNode :type res: List[int] :rtype: None", "name": "dfs", "signature": "def dfs(self, root, res)" }, { "docstr...
3
stack_v2_sparse_classes_30k_train_010678
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def postorderTraversal(self, root): :type root: TreeNode :rtype: List[int] - def dfs(self, root, res): :type root: TreeNode :type res: List[int] :rtype: None - def postorderTrave...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def postorderTraversal(self, root): :type root: TreeNode :rtype: List[int] - def dfs(self, root, res): :type root: TreeNode :type res: List[int] :rtype: None - def postorderTrave...
3d9e0ad2f6ed92ec969556f75d97c51ea4854719
<|skeleton|> class Solution: def postorderTraversal(self, root): """:type root: TreeNode :rtype: List[int]""" <|body_0|> def dfs(self, root, res): """:type root: TreeNode :type res: List[int] :rtype: None""" <|body_1|> def postorderTraversal_1(self, root): """:type...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def postorderTraversal(self, root): """:type root: TreeNode :rtype: List[int]""" res = [] self.dfs(root, res) return res def dfs(self, root, res): """:type root: TreeNode :type res: List[int] :rtype: None""" if root: self.dfs(root.left...
the_stack_v2_python_sparse
Solutions/0145_postorderTraversal.py
YoupengLi/leetcode-sorting
train
3
669ba5d3ddcb833f1e01465ccec198b7daee4b80
[ "super(BertLayerNorm, self).__init__()\nself.reducemean = P.ReduceMean(keep_dims=True)\nself.sub = P.Sub()\nself.pow = P.Pow()\nself.add = P.Add()\nself.sqrt = P.Sqrt()\nself.div = P.Div()\nself.mul = P.Mul()\nself.variance_epsilon = eps\nself.bert_layer_norm_weight = Parameter(Tensor(np.random.uniform(0, 1, bert_l...
<|body_start_0|> super(BertLayerNorm, self).__init__() self.reducemean = P.ReduceMean(keep_dims=True) self.sub = P.Sub() self.pow = P.Pow() self.add = P.Add() self.sqrt = P.Sqrt() self.div = P.Div() self.mul = P.Mul() self.variance_epsilon = eps ...
Normalization module of reader downstream
BertLayerNorm
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BertLayerNorm: """Normalization module of reader downstream""" def __init__(self, bert_layer_norm_weight_shape, bert_layer_norm_bias_shape, eps=1e-12): """init function""" <|body_0|> def construct(self, x): """construct function""" <|body_1|> <|end_skele...
stack_v2_sparse_classes_36k_train_031079
9,011
permissive
[ { "docstring": "init function", "name": "__init__", "signature": "def __init__(self, bert_layer_norm_weight_shape, bert_layer_norm_bias_shape, eps=1e-12)" }, { "docstring": "construct function", "name": "construct", "signature": "def construct(self, x)" } ]
2
stack_v2_sparse_classes_30k_train_003505
Implement the Python class `BertLayerNorm` described below. Class description: Normalization module of reader downstream Method signatures and docstrings: - def __init__(self, bert_layer_norm_weight_shape, bert_layer_norm_bias_shape, eps=1e-12): init function - def construct(self, x): construct function
Implement the Python class `BertLayerNorm` described below. Class description: Normalization module of reader downstream Method signatures and docstrings: - def __init__(self, bert_layer_norm_weight_shape, bert_layer_norm_bias_shape, eps=1e-12): init function - def construct(self, x): construct function <|skeleton|>...
eab643f51336dbf7d711f02d27e6516e5affee59
<|skeleton|> class BertLayerNorm: """Normalization module of reader downstream""" def __init__(self, bert_layer_norm_weight_shape, bert_layer_norm_bias_shape, eps=1e-12): """init function""" <|body_0|> def construct(self, x): """construct function""" <|body_1|> <|end_skele...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BertLayerNorm: """Normalization module of reader downstream""" def __init__(self, bert_layer_norm_weight_shape, bert_layer_norm_bias_shape, eps=1e-12): """init function""" super(BertLayerNorm, self).__init__() self.reducemean = P.ReduceMean(keep_dims=True) self.sub = P.Sub...
the_stack_v2_python_sparse
research/nlp/tprr/src/reader_downstream.py
mindspore-ai/models
train
301
96647a534284a3a0c57ba511cb75f8bb8cd45ddb
[ "session = db_apis.get_session()\nwith session.begin():\n db_lb = self.loadbalancer_repo.get(session, id=loadbalancer[constants.LOADBALANCER_ID])\nif db_lb.listeners:\n if amphora is not None:\n with session.begin():\n db_amp = self.amphora_repo.get(session, id=amphora[constants.ID])\n el...
<|body_start_0|> session = db_apis.get_session() with session.begin(): db_lb = self.loadbalancer_repo.get(session, id=loadbalancer[constants.LOADBALANCER_ID]) if db_lb.listeners: if amphora is not None: with session.begin(): db_amp = se...
Task to start all listeners on the vip.
ListenersStart
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ListenersStart: """Task to start all listeners on the vip.""" def execute(self, loadbalancer, amphora=None): """Execute listener start routines for listeners on an amphora.""" <|body_0|> def revert(self, loadbalancer, *args, **kwargs): """Handle failed listeners ...
stack_v2_sparse_classes_36k_train_031080
28,773
permissive
[ { "docstring": "Execute listener start routines for listeners on an amphora.", "name": "execute", "signature": "def execute(self, loadbalancer, amphora=None)" }, { "docstring": "Handle failed listeners starts.", "name": "revert", "signature": "def revert(self, loadbalancer, *args, **kwar...
2
null
Implement the Python class `ListenersStart` described below. Class description: Task to start all listeners on the vip. Method signatures and docstrings: - def execute(self, loadbalancer, amphora=None): Execute listener start routines for listeners on an amphora. - def revert(self, loadbalancer, *args, **kwargs): Han...
Implement the Python class `ListenersStart` described below. Class description: Task to start all listeners on the vip. Method signatures and docstrings: - def execute(self, loadbalancer, amphora=None): Execute listener start routines for listeners on an amphora. - def revert(self, loadbalancer, *args, **kwargs): Han...
0426285a41464a5015494584f109eed35a0d44db
<|skeleton|> class ListenersStart: """Task to start all listeners on the vip.""" def execute(self, loadbalancer, amphora=None): """Execute listener start routines for listeners on an amphora.""" <|body_0|> def revert(self, loadbalancer, *args, **kwargs): """Handle failed listeners ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ListenersStart: """Task to start all listeners on the vip.""" def execute(self, loadbalancer, amphora=None): """Execute listener start routines for listeners on an amphora.""" session = db_apis.get_session() with session.begin(): db_lb = self.loadbalancer_repo.get(sess...
the_stack_v2_python_sparse
octavia/controller/worker/v2/tasks/amphora_driver_tasks.py
openstack/octavia
train
147
507e922530dd635f124b537ffb3bb4025c52a744
[ "bucket = self._table[j]\nif bucket is None:\n raise KeyError('Key Error: Map has no key-value entry for ' + repr(key))\nreturn bucket[key]", "if self._table[j] is None:\n self._table[j] = UnsortedTableMap()\noldsize = len(self._table[j])\nself._table[j][key] = value\nif len(self._table[j]) > oldsize:\n ...
<|body_start_0|> bucket = self._table[j] if bucket is None: raise KeyError('Key Error: Map has no key-value entry for ' + repr(key)) return bucket[key] <|end_body_0|> <|body_start_1|> if self._table[j] is None: self._table[j] = UnsortedTableMap() oldsize ...
Hash map with separate chaining for collision resolution
ChainHashMap
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ChainHashMap: """Hash map with separate chaining for collision resolution""" def _bucket_getitem(self, j, key): """Get an item associated with key from a bucket at index j of bucket array""" <|body_0|> def _bucket_setitem(self, j, key, value): """Set a key-value ...
stack_v2_sparse_classes_36k_train_031081
2,213
no_license
[ { "docstring": "Get an item associated with key from a bucket at index j of bucket array", "name": "_bucket_getitem", "signature": "def _bucket_getitem(self, j, key)" }, { "docstring": "Set a key-value into bucket at index j of bucket array", "name": "_bucket_setitem", "signature": "def ...
4
null
Implement the Python class `ChainHashMap` described below. Class description: Hash map with separate chaining for collision resolution Method signatures and docstrings: - def _bucket_getitem(self, j, key): Get an item associated with key from a bucket at index j of bucket array - def _bucket_setitem(self, j, key, val...
Implement the Python class `ChainHashMap` described below. Class description: Hash map with separate chaining for collision resolution Method signatures and docstrings: - def _bucket_getitem(self, j, key): Get an item associated with key from a bucket at index j of bucket array - def _bucket_setitem(self, j, key, val...
96e2cf2bdfe615042fbf64576167d5cae24d622e
<|skeleton|> class ChainHashMap: """Hash map with separate chaining for collision resolution""" def _bucket_getitem(self, j, key): """Get an item associated with key from a bucket at index j of bucket array""" <|body_0|> def _bucket_setitem(self, j, key, value): """Set a key-value ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ChainHashMap: """Hash map with separate chaining for collision resolution""" def _bucket_getitem(self, j, key): """Get an item associated with key from a bucket at index j of bucket array""" bucket = self._table[j] if bucket is None: raise KeyError('Key Error: Map has ...
the_stack_v2_python_sparse
hashmaps/chainhashmap.py
Pato91/msft
train
0
f5420dd5ed9ac7615ed7cb322de376eadbb4352f
[ "logger.info(f'SvgAndImageFormField.to_py :: {data} :: {type(data)}')\ntry:\n test_file = super().to_python(data)\nexcept ValidationError:\n if not self.is_svg(data):\n raise\n else:\n test_file = data\nif test_file is None:\n return None\nif hasattr(data, 'temporary_file_path'):\n ifil...
<|body_start_0|> logger.info(f'SvgAndImageFormField.to_py :: {data} :: {type(data)}') try: test_file = super().to_python(data) except ValidationError: if not self.is_svg(data): raise else: test_file = data if test_file i...
SvgAndImageFormField
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SvgAndImageFormField: def to_python(self, data): """Checks that the file-upload field data contains a valid image (GIF, JPG, PNG, possibly others -- whatever the Python Imaging Library supports).""" <|body_0|> def is_svg(self, f): """Check if provided file is svg""" ...
stack_v2_sparse_classes_36k_train_031082
3,303
permissive
[ { "docstring": "Checks that the file-upload field data contains a valid image (GIF, JPG, PNG, possibly others -- whatever the Python Imaging Library supports).", "name": "to_python", "signature": "def to_python(self, data)" }, { "docstring": "Check if provided file is svg", "name": "is_svg",...
2
null
Implement the Python class `SvgAndImageFormField` described below. Class description: Implement the SvgAndImageFormField class. Method signatures and docstrings: - def to_python(self, data): Checks that the file-upload field data contains a valid image (GIF, JPG, PNG, possibly others -- whatever the Python Imaging Li...
Implement the Python class `SvgAndImageFormField` described below. Class description: Implement the SvgAndImageFormField class. Method signatures and docstrings: - def to_python(self, data): Checks that the file-upload field data contains a valid image (GIF, JPG, PNG, possibly others -- whatever the Python Imaging Li...
1055300216619c30cb06d58e51d78f739beb6483
<|skeleton|> class SvgAndImageFormField: def to_python(self, data): """Checks that the file-upload field data contains a valid image (GIF, JPG, PNG, possibly others -- whatever the Python Imaging Library supports).""" <|body_0|> def is_svg(self, f): """Check if provided file is svg""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SvgAndImageFormField: def to_python(self, data): """Checks that the file-upload field data contains a valid image (GIF, JPG, PNG, possibly others -- whatever the Python Imaging Library supports).""" logger.info(f'SvgAndImageFormField.to_py :: {data} :: {type(data)}') try: t...
the_stack_v2_python_sparse
foundation/core/svg.py
okfn/website
train
83
9ea20f6c82956b473b8bd9fb7619a1b50bd8de74
[ "params = [10000, 5, 10, 15]\nheight = 100\nwidth = 200\nworld_map = gen.generate_map(height=height, width=width, params=params)\nimage = img.get_map_overview(world_map)\npixels = image.load()\nfor x in range(width):\n for y in range(height):\n color = tuple(img.get_color(world_map[x][y]))\n self.a...
<|body_start_0|> params = [10000, 5, 10, 15] height = 100 width = 200 world_map = gen.generate_map(height=height, width=width, params=params) image = img.get_map_overview(world_map) pixels = image.load() for x in range(width): for y in range(height): ...
MapCase
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MapCase: def test_map_overview_accuracy(self): """Test if image of map overview properly represents generated map matrix.""" <|body_0|> def test_spreading_players(self): """Test if players are properly spread across.""" <|body_1|> <|end_skeleton|> <|body_st...
stack_v2_sparse_classes_36k_train_031083
1,357
permissive
[ { "docstring": "Test if image of map overview properly represents generated map matrix.", "name": "test_map_overview_accuracy", "signature": "def test_map_overview_accuracy(self)" }, { "docstring": "Test if players are properly spread across.", "name": "test_spreading_players", "signatur...
2
stack_v2_sparse_classes_30k_train_013293
Implement the Python class `MapCase` described below. Class description: Implement the MapCase class. Method signatures and docstrings: - def test_map_overview_accuracy(self): Test if image of map overview properly represents generated map matrix. - def test_spreading_players(self): Test if players are properly sprea...
Implement the Python class `MapCase` described below. Class description: Implement the MapCase class. Method signatures and docstrings: - def test_map_overview_accuracy(self): Test if image of map overview properly represents generated map matrix. - def test_spreading_players(self): Test if players are properly sprea...
1edad57d47ad975950639fc391b645e47509cf58
<|skeleton|> class MapCase: def test_map_overview_accuracy(self): """Test if image of map overview properly represents generated map matrix.""" <|body_0|> def test_spreading_players(self): """Test if players are properly spread across.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MapCase: def test_map_overview_accuracy(self): """Test if image of map overview properly represents generated map matrix.""" params = [10000, 5, 10, 15] height = 100 width = 200 world_map = gen.generate_map(height=height, width=width, params=params) image = img....
the_stack_v2_python_sparse
map_generation/test_map_generation.py
GabrielWechta/age-of-divisiveness
train
0
538d445e457171953756acf0f1e21677ba0b26a1
[ "self.width, self.height = dim\nself.width = self.width // 2\nself.height = self.height // 2\nself.ruleset = ruleset\nself.surface = pygame.Surface(dim)\nself.generation = [0] + [random.randint(0, 1) for i in range(self.width - 1)] + [0]", "number = left * 4 + center * 2 + right\nif number == 7:\n if self.rule...
<|body_start_0|> self.width, self.height = dim self.width = self.width // 2 self.height = self.height // 2 self.ruleset = ruleset self.surface = pygame.Surface(dim) self.generation = [0] + [random.randint(0, 1) for i in range(self.width - 1)] + [0] <|end_body_0|> <|body_...
simple Cellular Automata - Wolfram Elementary
WolframElementary
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WolframElementary: """simple Cellular Automata - Wolfram Elementary""" def __init__(self, dim: tuple, ruleset: int): """:param dim: dimension of surface to draw on :param ruleset: ruleset to use""" <|body_0|> def rule(self, left: int, center: int, right: int) -> int: ...
stack_v2_sparse_classes_36k_train_031084
3,015
no_license
[ { "docstring": ":param dim: dimension of surface to draw on :param ruleset: ruleset to use", "name": "__init__", "signature": "def __init__(self, dim: tuple, ruleset: int)" }, { "docstring": "apply ruleset", "name": "rule", "signature": "def rule(self, left: int, center: int, right: int)...
3
stack_v2_sparse_classes_30k_train_003372
Implement the Python class `WolframElementary` described below. Class description: simple Cellular Automata - Wolfram Elementary Method signatures and docstrings: - def __init__(self, dim: tuple, ruleset: int): :param dim: dimension of surface to draw on :param ruleset: ruleset to use - def rule(self, left: int, cent...
Implement the Python class `WolframElementary` described below. Class description: simple Cellular Automata - Wolfram Elementary Method signatures and docstrings: - def __init__(self, dim: tuple, ruleset: int): :param dim: dimension of surface to draw on :param ruleset: ruleset to use - def rule(self, left: int, cent...
1fd421195a2888c0588a49f5a043a1110eedcdbf
<|skeleton|> class WolframElementary: """simple Cellular Automata - Wolfram Elementary""" def __init__(self, dim: tuple, ruleset: int): """:param dim: dimension of surface to draw on :param ruleset: ruleset to use""" <|body_0|> def rule(self, left: int, center: int, right: int) -> int: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WolframElementary: """simple Cellular Automata - Wolfram Elementary""" def __init__(self, dim: tuple, ruleset: int): """:param dim: dimension of surface to draw on :param ruleset: ruleset to use""" self.width, self.height = dim self.width = self.width // 2 self.height = se...
the_stack_v2_python_sparse
effects/WolframElementary.py
gunny26/pygame
train
5
c6a550a378f2cda7e85b6bd609568186edf62a06
[ "filters, keywords = rest_utils.parse_filters_kwargs(request, ['session'])\nsession = keywords.get('session')\nif not session:\n session = env_api.Session.get_or_create_or_delete(request, environment)\ncomponent = api.muranoclient(request).services.get(environment, '/' + component, session)\nif component:\n r...
<|body_start_0|> filters, keywords = rest_utils.parse_filters_kwargs(request, ['session']) session = keywords.get('session') if not session: session = env_api.Session.get_or_create_or_delete(request, environment) component = api.muranoclient(request).services.get(environment,...
API for Murano components Metadata
ComponentsMetadata
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ComponentsMetadata: """API for Murano components Metadata""" def get(self, request, environment, component): """Get a metadata object for a component in a given environment Example GET: http://localhost/api/app-catalog/environments/123/components/456/metadata The following get parame...
stack_v2_sparse_classes_36k_train_031085
6,096
permissive
[ { "docstring": "Get a metadata object for a component in a given environment Example GET: http://localhost/api/app-catalog/environments/123/components/456/metadata The following get parameters may be passed in the GET request: :param environment: identifier of the environment :param component: identifier of the...
2
null
Implement the Python class `ComponentsMetadata` described below. Class description: API for Murano components Metadata Method signatures and docstrings: - def get(self, request, environment, component): Get a metadata object for a component in a given environment Example GET: http://localhost/api/app-catalog/environm...
Implement the Python class `ComponentsMetadata` described below. Class description: API for Murano components Metadata Method signatures and docstrings: - def get(self, request, environment, component): Get a metadata object for a component in a given environment Example GET: http://localhost/api/app-catalog/environm...
54e2ea8a71385b1c7624b3d2c8056bd8a2c2e2f7
<|skeleton|> class ComponentsMetadata: """API for Murano components Metadata""" def get(self, request, environment, component): """Get a metadata object for a component in a given environment Example GET: http://localhost/api/app-catalog/environments/123/components/456/metadata The following get parame...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ComponentsMetadata: """API for Murano components Metadata""" def get(self, request, environment, component): """Get a metadata object for a component in a given environment Example GET: http://localhost/api/app-catalog/environments/123/components/456/metadata The following get parameters may be p...
the_stack_v2_python_sparse
muranodashboard/api/rest/environments.py
openstack/murano-dashboard
train
38
22eab1ad986beb1fd7a5fdea21e6ee70e044ea06
[ "for row in range(0, len(board)):\n for col in range(0, len(board[0])):\n board_copy = deepcopy(board)\n if self.existRecu(board_copy, word, row, col):\n return True\nreturn False", "if len(word) == 0:\n return True\nelif row < 0 or row == len(board):\n return False\nelif col < 0...
<|body_start_0|> for row in range(0, len(board)): for col in range(0, len(board[0])): board_copy = deepcopy(board) if self.existRecu(board_copy, word, row, col): return True return False <|end_body_0|> <|body_start_1|> if len(word)...
Solution_A
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution_A: def exist(self, board: List[List[str]], word: str) -> bool: """Use a recursive finder to recursively find the word in the matrix This is still an brutal force method to check every route until find the correct one. Exceeded max time limit when case is long.""" <|body_...
stack_v2_sparse_classes_36k_train_031086
10,401
permissive
[ { "docstring": "Use a recursive finder to recursively find the word in the matrix This is still an brutal force method to check every route until find the correct one. Exceeded max time limit when case is long.", "name": "exist", "signature": "def exist(self, board: List[List[str]], word: str) -> bool" ...
2
stack_v2_sparse_classes_30k_train_004174
Implement the Python class `Solution_A` described below. Class description: Implement the Solution_A class. Method signatures and docstrings: - def exist(self, board: List[List[str]], word: str) -> bool: Use a recursive finder to recursively find the word in the matrix This is still an brutal force method to check ev...
Implement the Python class `Solution_A` described below. Class description: Implement the Solution_A class. Method signatures and docstrings: - def exist(self, board: List[List[str]], word: str) -> bool: Use a recursive finder to recursively find the word in the matrix This is still an brutal force method to check ev...
143422321cbc3715ca08f6c3af8f960a55887ced
<|skeleton|> class Solution_A: def exist(self, board: List[List[str]], word: str) -> bool: """Use a recursive finder to recursively find the word in the matrix This is still an brutal force method to check every route until find the correct one. Exceeded max time limit when case is long.""" <|body_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution_A: def exist(self, board: List[List[str]], word: str) -> bool: """Use a recursive finder to recursively find the word in the matrix This is still an brutal force method to check every route until find the correct one. Exceeded max time limit when case is long.""" for row in range(0, l...
the_stack_v2_python_sparse
LeetCode/LC079_word_search.py
jxie0755/Learning_Python
train
0
75340e4ccb2c340859344f55936952cbe6794341
[ "providers = pq.get_providers()\nif not providers:\n return self.bad_response('Internal error')\nres = [{'id': p.id, 'title': p.title, 'link': p.link} for p in providers]\nreturn self.success_response({'providers': res})", "data = request.get_json()\ntitle = data.get('title')\nlink = data.get('link')\nif not t...
<|body_start_0|> providers = pq.get_providers() if not providers: return self.bad_response('Internal error') res = [{'id': p.id, 'title': p.title, 'link': p.link} for p in providers] return self.success_response({'providers': res}) <|end_body_0|> <|body_start_1|> dat...
ProviderHandler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProviderHandler: def get(self): """Get providers list.""" <|body_0|> def post(self): """{ 'title': str, 'link': str }""" <|body_1|> <|end_skeleton|> <|body_start_0|> providers = pq.get_providers() if not providers: return self.ba...
stack_v2_sparse_classes_36k_train_031087
1,028
no_license
[ { "docstring": "Get providers list.", "name": "get", "signature": "def get(self)" }, { "docstring": "{ 'title': str, 'link': str }", "name": "post", "signature": "def post(self)" } ]
2
stack_v2_sparse_classes_30k_train_018831
Implement the Python class `ProviderHandler` described below. Class description: Implement the ProviderHandler class. Method signatures and docstrings: - def get(self): Get providers list. - def post(self): { 'title': str, 'link': str }
Implement the Python class `ProviderHandler` described below. Class description: Implement the ProviderHandler class. Method signatures and docstrings: - def get(self): Get providers list. - def post(self): { 'title': str, 'link': str } <|skeleton|> class ProviderHandler: def get(self): """Get providers...
8d3dfc06e0738e3e9547604d421788b4145fd971
<|skeleton|> class ProviderHandler: def get(self): """Get providers list.""" <|body_0|> def post(self): """{ 'title': str, 'link': str }""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProviderHandler: def get(self): """Get providers list.""" providers = pq.get_providers() if not providers: return self.bad_response('Internal error') res = [{'id': p.id, 'title': p.title, 'link': p.link} for p in providers] return self.success_response({'pro...
the_stack_v2_python_sparse
app/handlers/provider.py
AleksandrFrolov/BackofficeSS
train
0
de1a59e11cf5e04112c8a67b84e527ba273b8d34
[ "if not nums:\n return 0\nmydict = {}\nres = 1\nfor num in nums:\n if num in mydict.keys():\n continue\n mydict[num] = 1\n ll = num\n rr = num\n val = 1\n if num - 1 in mydict.keys():\n ll = num - mydict[num - 1]\n val += mydict[num - 1]\n if num + 1 in mydict.keys():\n ...
<|body_start_0|> if not nums: return 0 mydict = {} res = 1 for num in nums: if num in mydict.keys(): continue mydict[num] = 1 ll = num rr = num val = 1 if num - 1 in mydict.keys(): ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def longestConsecutive(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def longestConsecutive2(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> def longestConsecutive3(self, nums): """:type nums: List[int]...
stack_v2_sparse_classes_36k_train_031088
2,537
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "longestConsecutive", "signature": "def longestConsecutive(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "longestConsecutive2", "signature": "def longestConsecutive2(self, nums)" }, { "docst...
3
stack_v2_sparse_classes_30k_train_019806
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestConsecutive(self, nums): :type nums: List[int] :rtype: int - def longestConsecutive2(self, nums): :type nums: List[int] :rtype: int - def longestConsecutive3(self, num...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestConsecutive(self, nums): :type nums: List[int] :rtype: int - def longestConsecutive2(self, nums): :type nums: List[int] :rtype: int - def longestConsecutive3(self, num...
690b685048c8e89d26047b6bc48b5f9af7d59cbb
<|skeleton|> class Solution: def longestConsecutive(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def longestConsecutive2(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> def longestConsecutive3(self, nums): """:type nums: List[int]...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def longestConsecutive(self, nums): """:type nums: List[int] :rtype: int""" if not nums: return 0 mydict = {} res = 1 for num in nums: if num in mydict.keys(): continue mydict[num] = 1 ll = num ...
the_stack_v2_python_sparse
数组/128. 最长连续序列.py
SimmonsChen/LeetCode
train
0
13cba416c87f67fb9e755b41b823511d7a8db3fa
[ "self.host = host\nself.port = port\nself.data = None", "try:\n connection = Telnet(host=self.host, port=self.port, timeout=DEFAULT_TIMEOUT)\n data = connection.read_all().decode('ascii').lstrip('|').rstrip('|').split('||')\n self.data = {data[i].split('|')[0]: data[i] for i in range(0, len(data), 1)}\ne...
<|body_start_0|> self.host = host self.port = port self.data = None <|end_body_0|> <|body_start_1|> try: connection = Telnet(host=self.host, port=self.port, timeout=DEFAULT_TIMEOUT) data = connection.read_all().decode('ascii').lstrip('|').rstrip('|').split('||') ...
Get the latest data from HDDTemp and update the states.
HddTempData
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HddTempData: """Get the latest data from HDDTemp and update the states.""" def __init__(self, host, port): """Initialize the data object.""" <|body_0|> def update(self): """Get the latest data from HDDTemp running as daemon.""" <|body_1|> <|end_skeleton|...
stack_v2_sparse_classes_36k_train_031089
4,109
permissive
[ { "docstring": "Initialize the data object.", "name": "__init__", "signature": "def __init__(self, host, port)" }, { "docstring": "Get the latest data from HDDTemp running as daemon.", "name": "update", "signature": "def update(self)" } ]
2
stack_v2_sparse_classes_30k_train_011423
Implement the Python class `HddTempData` described below. Class description: Get the latest data from HDDTemp and update the states. Method signatures and docstrings: - def __init__(self, host, port): Initialize the data object. - def update(self): Get the latest data from HDDTemp running as daemon.
Implement the Python class `HddTempData` described below. Class description: Get the latest data from HDDTemp and update the states. Method signatures and docstrings: - def __init__(self, host, port): Initialize the data object. - def update(self): Get the latest data from HDDTemp running as daemon. <|skeleton|> cla...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class HddTempData: """Get the latest data from HDDTemp and update the states.""" def __init__(self, host, port): """Initialize the data object.""" <|body_0|> def update(self): """Get the latest data from HDDTemp running as daemon.""" <|body_1|> <|end_skeleton|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HddTempData: """Get the latest data from HDDTemp and update the states.""" def __init__(self, host, port): """Initialize the data object.""" self.host = host self.port = port self.data = None def update(self): """Get the latest data from HDDTemp running as dae...
the_stack_v2_python_sparse
homeassistant/components/hddtemp/sensor.py
home-assistant/core
train
35,501
1c5fa355bff71df7a5c204eebc2ef78d4c101d54
[ "arg_is_iter = False\nif len(args) == 1:\n arg_is_iter = True\n args = args[0]\nsymb_args = []\nres = initial_val\nnum_non_symbolic_args = 0\nfor x in args:\n if isinstance(x, Expression):\n symb_args.append(x)\n else:\n num_non_symbolic_args += 1\n res = builtin_f(res, x)\nif len(s...
<|body_start_0|> arg_is_iter = False if len(args) == 1: arg_is_iter = True args = args[0] symb_args = [] res = initial_val num_non_symbolic_args = 0 for x in args: if isinstance(x, Expression): symb_args.append(x) ...
MinMax_base
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MinMax_base: def eval_helper(self, this_f, builtin_f, initial_val, args): """EXAMPLES:: sage: max_symbolic(3,5,x) # indirect doctest max(x, 5) sage: min_symbolic(3,5,x) min(x, 3)""" <|body_0|> def __call__(self, *args, **kwds): """EXAMPLES:: sage: max_symbolic(3,5,x)...
stack_v2_sparse_classes_36k_train_031090
10,190
no_license
[ { "docstring": "EXAMPLES:: sage: max_symbolic(3,5,x) # indirect doctest max(x, 5) sage: min_symbolic(3,5,x) min(x, 3)", "name": "eval_helper", "signature": "def eval_helper(self, this_f, builtin_f, initial_val, args)" }, { "docstring": "EXAMPLES:: sage: max_symbolic(3,5,x) max(x, 5) sage: max_sy...
2
null
Implement the Python class `MinMax_base` described below. Class description: Implement the MinMax_base class. Method signatures and docstrings: - def eval_helper(self, this_f, builtin_f, initial_val, args): EXAMPLES:: sage: max_symbolic(3,5,x) # indirect doctest max(x, 5) sage: min_symbolic(3,5,x) min(x, 3) - def __c...
Implement the Python class `MinMax_base` described below. Class description: Implement the MinMax_base class. Method signatures and docstrings: - def eval_helper(self, this_f, builtin_f, initial_val, args): EXAMPLES:: sage: max_symbolic(3,5,x) # indirect doctest max(x, 5) sage: min_symbolic(3,5,x) min(x, 3) - def __c...
0d9eacbf74e2acffefde93e39f8bcbec745cdaba
<|skeleton|> class MinMax_base: def eval_helper(self, this_f, builtin_f, initial_val, args): """EXAMPLES:: sage: max_symbolic(3,5,x) # indirect doctest max(x, 5) sage: min_symbolic(3,5,x) min(x, 3)""" <|body_0|> def __call__(self, *args, **kwds): """EXAMPLES:: sage: max_symbolic(3,5,x)...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MinMax_base: def eval_helper(self, this_f, builtin_f, initial_val, args): """EXAMPLES:: sage: max_symbolic(3,5,x) # indirect doctest max(x, 5) sage: min_symbolic(3,5,x) min(x, 3)""" arg_is_iter = False if len(args) == 1: arg_is_iter = True args = args[0] ...
the_stack_v2_python_sparse
sage/src/sage/functions/min_max.py
bopopescu/geosci
train
0
df6de79959ed641a6accf7e227db5a3351d3a684
[ "Turtle.__init__(self, shape='square', visible=False)\nself.speed(0)\nself.color(outlineColor, fillColor)\nself.up()\nself.goto(xPos, yPos)\nself.resizemode(rmode='user')\nself.shapesize(stretch_wid=length / 20, stretch_len=length / 20)\nself._text = text\nself._index = index\nself._grid = grid\nself.onclick(lambda...
<|body_start_0|> Turtle.__init__(self, shape='square', visible=False) self.speed(0) self.color(outlineColor, fillColor) self.up() self.goto(xPos, yPos) self.resizemode(rmode='user') self.shapesize(stretch_wid=length / 20, stretch_len=length / 20) self._tex...
Represents a Tic-Tac-Toe square.
Square
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Square: """Represents a Tic-Tac-Toe square.""" def __init__(self, index, grid, length, xPos, yPos, outlineColor='black', fillColor='white', text=EMPTY): """Sets the initial state of the Tic-Tac-Toe square.""" <|body_0|> def text(self, text=None): """Getter, sette...
stack_v2_sparse_classes_36k_train_031091
1,091
no_license
[ { "docstring": "Sets the initial state of the Tic-Tac-Toe square.", "name": "__init__", "signature": "def __init__(self, index, grid, length, xPos, yPos, outlineColor='black', fillColor='white', text=EMPTY)" }, { "docstring": "Getter, setter for _text", "name": "text", "signature": "def ...
2
stack_v2_sparse_classes_30k_train_009249
Implement the Python class `Square` described below. Class description: Represents a Tic-Tac-Toe square. Method signatures and docstrings: - def __init__(self, index, grid, length, xPos, yPos, outlineColor='black', fillColor='white', text=EMPTY): Sets the initial state of the Tic-Tac-Toe square. - def text(self, text...
Implement the Python class `Square` described below. Class description: Represents a Tic-Tac-Toe square. Method signatures and docstrings: - def __init__(self, index, grid, length, xPos, yPos, outlineColor='black', fillColor='white', text=EMPTY): Sets the initial state of the Tic-Tac-Toe square. - def text(self, text...
eb4c49115d100ff8cf0f77523db126b503a6611a
<|skeleton|> class Square: """Represents a Tic-Tac-Toe square.""" def __init__(self, index, grid, length, xPos, yPos, outlineColor='black', fillColor='white', text=EMPTY): """Sets the initial state of the Tic-Tac-Toe square.""" <|body_0|> def text(self, text=None): """Getter, sette...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Square: """Represents a Tic-Tac-Toe square.""" def __init__(self, index, grid, length, xPos, yPos, outlineColor='black', fillColor='white', text=EMPTY): """Sets the initial state of the Tic-Tac-Toe square.""" Turtle.__init__(self, shape='square', visible=False) self.speed(0) ...
the_stack_v2_python_sparse
ticktactoe/square.py
chivitc1/python-turtle-learning
train
0
d97991577af3fa405d7995ae49df4886b0476482
[ "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...
Missing associated documentation comment in .proto file
AuthenticationServicer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AuthenticationServicer: """Missing associated documentation comment in .proto file""" def authenticate(self, request, context): """Missing associated documentation comment in .proto file""" <|body_0|> def validateToken(self, request, context): """Missing associat...
stack_v2_sparse_classes_36k_train_031092
7,766
no_license
[ { "docstring": "Missing associated documentation comment in .proto file", "name": "authenticate", "signature": "def authenticate(self, request, context)" }, { "docstring": "Missing associated documentation comment in .proto file", "name": "validateToken", "signature": "def validateToken(...
2
stack_v2_sparse_classes_30k_train_005596
Implement the Python class `AuthenticationServicer` described below. Class description: Missing associated documentation comment in .proto file Method signatures and docstrings: - def authenticate(self, request, context): Missing associated documentation comment in .proto file - def validateToken(self, request, conte...
Implement the Python class `AuthenticationServicer` described below. Class description: Missing associated documentation comment in .proto file Method signatures and docstrings: - def authenticate(self, request, context): Missing associated documentation comment in .proto file - def validateToken(self, request, conte...
626dae0efa20a66d1f69f49be15ab90c623ec33b
<|skeleton|> class AuthenticationServicer: """Missing associated documentation comment in .proto file""" def authenticate(self, request, context): """Missing associated documentation comment in .proto file""" <|body_0|> def validateToken(self, request, context): """Missing associat...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AuthenticationServicer: """Missing associated documentation comment in .proto file""" def authenticate(self, request, context): """Missing associated documentation comment in .proto file""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented...
the_stack_v2_python_sparse
svms-job-module-service/backup/connectors/vms_profile_manager/protoc/profile_manager_pb2_grpc.py
shankarmahato/Job_module
train
0
039c842ad5c69d4b5fc35be04ef62a1ab981ae2c
[ "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...
Proto file describing the keyword plan campaign keyword service. Service to manage Keyword Plan campaign keywords. KeywordPlanCampaign is required to add the campaign keywords. Only negative keywords are supported. A maximum of 1000 negative keywords are allowed per plan. This includes both campaign negative keywords a...
KeywordPlanCampaignKeywordServiceServicer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KeywordPlanCampaignKeywordServiceServicer: """Proto file describing the keyword plan campaign keyword service. Service to manage Keyword Plan campaign keywords. KeywordPlanCampaign is required to add the campaign keywords. Only negative keywords are supported. A maximum of 1000 negative keywords ...
stack_v2_sparse_classes_36k_train_031093
4,515
permissive
[ { "docstring": "Returns the requested plan in full detail.", "name": "GetKeywordPlanCampaignKeyword", "signature": "def GetKeywordPlanCampaignKeyword(self, request, context)" }, { "docstring": "Creates, updates, or removes Keyword Plan campaign keywords. Operation statuses are returned.", "n...
2
null
Implement the Python class `KeywordPlanCampaignKeywordServiceServicer` described below. Class description: Proto file describing the keyword plan campaign keyword service. Service to manage Keyword Plan campaign keywords. KeywordPlanCampaign is required to add the campaign keywords. Only negative keywords are supporte...
Implement the Python class `KeywordPlanCampaignKeywordServiceServicer` described below. Class description: Proto file describing the keyword plan campaign keyword service. Service to manage Keyword Plan campaign keywords. KeywordPlanCampaign is required to add the campaign keywords. Only negative keywords are supporte...
a5b6cede64f4d9912ae6ad26927a54e40448c9fe
<|skeleton|> class KeywordPlanCampaignKeywordServiceServicer: """Proto file describing the keyword plan campaign keyword service. Service to manage Keyword Plan campaign keywords. KeywordPlanCampaign is required to add the campaign keywords. Only negative keywords are supported. A maximum of 1000 negative keywords ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class KeywordPlanCampaignKeywordServiceServicer: """Proto file describing the keyword plan campaign keyword service. Service to manage Keyword Plan campaign keywords. KeywordPlanCampaign is required to add the campaign keywords. Only negative keywords are supported. A maximum of 1000 negative keywords are allowed p...
the_stack_v2_python_sparse
google/ads/google_ads/v4/proto/services/keyword_plan_campaign_keyword_service_pb2_grpc.py
fiboknacky/google-ads-python
train
0
310410e29abccbba00f653f0a1a27c482c9f8aab
[ "def rec(res, index, nums, path, k):\n if len(path) == k:\n path.sort()\n res.append(path)\n for i in range(index, len(nums)):\n if len(path + [nums[i]]) > k:\n continue\n rec(res, i + 1, nums, path + [nums[i]], k)\nnums = [i + 1 for i in range(n)]\nans = []\nrec(ans, 0,...
<|body_start_0|> def rec(res, index, nums, path, k): if len(path) == k: path.sort() res.append(path) for i in range(index, len(nums)): if len(path + [nums[i]]) > k: continue rec(res, i + 1, nums, path + [...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def combine(self, n, k): """:type n: int :type k: int :rtype: List[List[int]]""" <|body_0|> def combine2(self, n, k): """:type n: int :type k: int :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|> <|body_start_0|> def rec(res, index, ...
stack_v2_sparse_classes_36k_train_031094
1,299
no_license
[ { "docstring": ":type n: int :type k: int :rtype: List[List[int]]", "name": "combine", "signature": "def combine(self, n, k)" }, { "docstring": ":type n: int :type k: int :rtype: List[List[int]]", "name": "combine2", "signature": "def combine2(self, n, k)" } ]
2
stack_v2_sparse_classes_30k_train_015113
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def combine(self, n, k): :type n: int :type k: int :rtype: List[List[int]] - def combine2(self, n, k): :type n: int :type k: int :rtype: List[List[int]]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def combine(self, n, k): :type n: int :type k: int :rtype: List[List[int]] - def combine2(self, n, k): :type n: int :type k: int :rtype: List[List[int]] <|skeleton|> class Solut...
2d5fa4cd696d5035ea8859befeadc5cc436959c9
<|skeleton|> class Solution: def combine(self, n, k): """:type n: int :type k: int :rtype: List[List[int]]""" <|body_0|> def combine2(self, n, k): """:type n: int :type k: int :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def combine(self, n, k): """:type n: int :type k: int :rtype: List[List[int]]""" def rec(res, index, nums, path, k): if len(path) == k: path.sort() res.append(path) for i in range(index, len(nums)): if len(path +...
the_stack_v2_python_sparse
SourceCode/Python/Problem/00077.Combinations.py
roger6blog/LeetCode
train
0
100da2ddcf49bdf1bdacb19482975c831c77fc6d
[ "try:\n result = data.HbaseManager().create_table(baseid, tb)\n return_data = {'status': '200', 'result': result}\n return Response(json.dumps(return_data))\nexcept Exception as e:\n return_data = {'status': '400', 'result': str(e)}\n return Response(json.dumps(return_data))", "try:\n result = d...
<|body_start_0|> try: result = data.HbaseManager().create_table(baseid, tb) return_data = {'status': '200', 'result': result} return Response(json.dumps(return_data)) except Exception as e: return_data = {'status': '400', 'result': str(e)} retu...
1. Name : DataFrameTable (step 4) 2. Steps - WDNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/job/{nnid}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/data/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/data/{args}...
DataFrameTable
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataFrameTable: """1. Name : DataFrameTable (step 4) 2. Steps - WDNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/job/{nnid}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/data/ - post /api/v1/type/data...
stack_v2_sparse_classes_36k_train_031095
3,100
no_license
[ { "docstring": "- desc :create table with given name", "name": "post", "signature": "def post(self, request, baseid, tb)" }, { "docstring": "- desc : return all table", "name": "get", "signature": "def get(self, request, baseid)" }, { "docstring": "- desc : rename table - Request...
4
null
Implement the Python class `DataFrameTable` described below. Class description: 1. Name : DataFrameTable (step 4) 2. Steps - WDNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/job/{nnid}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/ - post /api/v1/type/dataframe/base/{baseid}/ta...
Implement the Python class `DataFrameTable` described below. Class description: 1. Name : DataFrameTable (step 4) 2. Steps - WDNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/job/{nnid}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/ - post /api/v1/type/dataframe/base/{baseid}/ta...
ef058737f391de817c74398ef9a5d3a28f973c98
<|skeleton|> class DataFrameTable: """1. Name : DataFrameTable (step 4) 2. Steps - WDNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/job/{nnid}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/data/ - post /api/v1/type/data...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DataFrameTable: """1. Name : DataFrameTable (step 4) 2. Steps - WDNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/job/{nnid}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/data/ - post /api/v1/type/dataframe/base/{b...
the_stack_v2_python_sparse
tfmsarest/views/dataframe_table.py
TensorMSA/tensormsa_old
train
6
ac5c682e4e85ebd08c4afb0951cb85232014b83b
[ "self.smtp_server = settings.SMTP_HOST\nself.port = settings.SMTP_PORT\nself.sender_email = settings.SMTP_USER\nself.password = settings.SMTP_PASS\nself.receiver_email = to\nself.message = MIMEMultipart('alternative')\nself.message['Subject'] = subject\nself.message['From'] = self.sender_email\nself.message['To'] =...
<|body_start_0|> self.smtp_server = settings.SMTP_HOST self.port = settings.SMTP_PORT self.sender_email = settings.SMTP_USER self.password = settings.SMTP_PASS self.receiver_email = to self.message = MIMEMultipart('alternative') self.message['Subject'] = subject ...
Class to support the mailing settings and actions
MailSender
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MailSender: """Class to support the mailing settings and actions""" def __init__(self, html, subject, text, to): """This method will facilitate the setup of the mail service, as well as the message building process :param html: message in html format :param subject: message subject :...
stack_v2_sparse_classes_36k_train_031096
2,143
no_license
[ { "docstring": "This method will facilitate the setup of the mail service, as well as the message building process :param html: message in html format :param subject: message subject :param text: message in plain text :param to: destination mail info", "name": "__init__", "signature": "def __init__(self...
2
stack_v2_sparse_classes_30k_train_011516
Implement the Python class `MailSender` described below. Class description: Class to support the mailing settings and actions Method signatures and docstrings: - def __init__(self, html, subject, text, to): This method will facilitate the setup of the mail service, as well as the message building process :param html:...
Implement the Python class `MailSender` described below. Class description: Class to support the mailing settings and actions Method signatures and docstrings: - def __init__(self, html, subject, text, to): This method will facilitate the setup of the mail service, as well as the message building process :param html:...
e4c228b90add962640b04b66e2952ce2502215c5
<|skeleton|> class MailSender: """Class to support the mailing settings and actions""" def __init__(self, html, subject, text, to): """This method will facilitate the setup of the mail service, as well as the message building process :param html: message in html format :param subject: message subject :...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MailSender: """Class to support the mailing settings and actions""" def __init__(self, html, subject, text, to): """This method will facilitate the setup of the mail service, as well as the message building process :param html: message in html format :param subject: message subject :param text: m...
the_stack_v2_python_sparse
status/mail_sender.py
Ampath-Summer-2020/Ampath-Summer-2020
train
1
f477fc0823af961884e87f5a90b3f8a698e20024
[ "super(RtuQuery, self).__init__()\nself._request_address = 0\nself._response_address = 0", "self._request_address = slave\nif self._request_address < 0 or self._request_address > 255:\n raise InvalidArgumentError('Invalid address {0}'.format(self._request_address))\ndata = struct.pack('>B', self._request_addre...
<|body_start_0|> super(RtuQuery, self).__init__() self._request_address = 0 self._response_address = 0 <|end_body_0|> <|body_start_1|> self._request_address = slave if self._request_address < 0 or self._request_address > 255: raise InvalidArgumentError('Invalid addre...
Subclass of a Query. Adds the Modbus RTU specific part of the protocol
RtuQuery
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RtuQuery: """Subclass of a Query. Adds the Modbus RTU specific part of the protocol""" def __init__(self): """Constructor""" <|body_0|> def build_request(self, pdu, slave): """Add the Modbus RTU part to the request""" <|body_1|> def parse_response(se...
stack_v2_sparse_classes_36k_train_031097
9,056
permissive
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Add the Modbus RTU part to the request", "name": "build_request", "signature": "def build_request(self, pdu, slave)" }, { "docstring": "Extract the pdu from the Modbus RTU respo...
5
null
Implement the Python class `RtuQuery` described below. Class description: Subclass of a Query. Adds the Modbus RTU specific part of the protocol Method signatures and docstrings: - def __init__(self): Constructor - def build_request(self, pdu, slave): Add the Modbus RTU part to the request - def parse_response(self, ...
Implement the Python class `RtuQuery` described below. Class description: Subclass of a Query. Adds the Modbus RTU specific part of the protocol Method signatures and docstrings: - def __init__(self): Constructor - def build_request(self, pdu, slave): Add the Modbus RTU part to the request - def parse_response(self, ...
a5aeb1238b26c1af55cf3a82787ed347dff1fb86
<|skeleton|> class RtuQuery: """Subclass of a Query. Adds the Modbus RTU specific part of the protocol""" def __init__(self): """Constructor""" <|body_0|> def build_request(self, pdu, slave): """Add the Modbus RTU part to the request""" <|body_1|> def parse_response(se...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RtuQuery: """Subclass of a Query. Adds the Modbus RTU specific part of the protocol""" def __init__(self): """Constructor""" super(RtuQuery, self).__init__() self._request_address = 0 self._response_address = 0 def build_request(self, pdu, slave): """Add the M...
the_stack_v2_python_sparse
external/modbus_tk/modbus_tk/modbus_rtu.py
intel/intel-device-resource-mgt-lib
train
2
1b78c7d9d8a926db4786577ea8ebd650eecd1d3c
[ "super(LandmarkGeneratorHeatmap, self).__init__(dim, output_size, landmark_indizes, landmark_flip_pairs, data_format, pre_transformation, post_transformation)\nself.output_size_np = list(reversed(self.output_size))\nself.sigma = sigma\nself.scale_factor = scale_factor\nself.normalize_center = normalize_center", "...
<|body_start_0|> super(LandmarkGeneratorHeatmap, self).__init__(dim, output_size, landmark_indizes, landmark_flip_pairs, data_format, pre_transformation, post_transformation) self.output_size_np = list(reversed(self.output_size)) self.sigma = sigma self.scale_factor = scale_factor ...
Generates images of Gaussian heatmaps
LandmarkGeneratorHeatmap
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LandmarkGeneratorHeatmap: """Generates images of Gaussian heatmaps""" def __init__(self, dim, output_size, sigma, scale_factor, normalize_center, landmark_indizes=None, landmark_flip_pairs=None, data_format='channels_first', pre_transformation=None, post_transformation=None): """Init...
stack_v2_sparse_classes_36k_train_031098
16,690
no_license
[ { "docstring": "Initializer :param output_size: output image size :param sigma: Gaussian sigma :param scale_factor: heatmap scale factor, each value of the Gaussian will be multiplied with this value :param normalize_center: if True, the value on the center is set to scale_factor otherwise, the default gaussian...
2
stack_v2_sparse_classes_30k_train_015575
Implement the Python class `LandmarkGeneratorHeatmap` described below. Class description: Generates images of Gaussian heatmaps Method signatures and docstrings: - def __init__(self, dim, output_size, sigma, scale_factor, normalize_center, landmark_indizes=None, landmark_flip_pairs=None, data_format='channels_first',...
Implement the Python class `LandmarkGeneratorHeatmap` described below. Class description: Generates images of Gaussian heatmaps Method signatures and docstrings: - def __init__(self, dim, output_size, sigma, scale_factor, normalize_center, landmark_indizes=None, landmark_flip_pairs=None, data_format='channels_first',...
ef6cee91264ba1fe6b40d9823a07647b95bcc2c4
<|skeleton|> class LandmarkGeneratorHeatmap: """Generates images of Gaussian heatmaps""" def __init__(self, dim, output_size, sigma, scale_factor, normalize_center, landmark_indizes=None, landmark_flip_pairs=None, data_format='channels_first', pre_transformation=None, post_transformation=None): """Init...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LandmarkGeneratorHeatmap: """Generates images of Gaussian heatmaps""" def __init__(self, dim, output_size, sigma, scale_factor, normalize_center, landmark_indizes=None, landmark_flip_pairs=None, data_format='channels_first', pre_transformation=None, post_transformation=None): """Initializer :para...
the_stack_v2_python_sparse
generators/landmark_generator.py
XiaoweiXu/MedicalDataAugmentationTool
train
1
594de2f782273a947aab6a1e2a3b48b02493c2af
[ "self.mesh_name = mesh_name\nself.repo_mesh_name = mesh_name + 'Repo'\nprint('[MeshInfo] Repository name: {0:s}'.format(self.repo_mesh_name))\nif int(sv.Repository.Exists(self.repo_mesh_name)):\n print('[MeshInfo] {0:s} is already in the repository.'.format(self.repo_mesh_name))\nelse:\n sv.GUI.ExportMeshToRe...
<|body_start_0|> self.mesh_name = mesh_name self.repo_mesh_name = mesh_name + 'Repo' print('[MeshInfo] Repository name: {0:s}'.format(self.repo_mesh_name)) if int(sv.Repository.Exists(self.repo_mesh_name)): print('[MeshInfo] {0:s} is already in the repository.'.format(self.re...
This class is used to print mesh information.
MeshInfo
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MeshInfo: """This class is used to print mesh information.""" def __init__(self, mesh_name): """Initialize the MeshInfo object Args: mesh_name (string): The name of a SimVascular Meshes data node.""" <|body_0|> def print_nodes(self, ofile=sys.stdout): """Print th...
stack_v2_sparse_classes_36k_train_031099
6,127
no_license
[ { "docstring": "Initialize the MeshInfo object Args: mesh_name (string): The name of a SimVascular Meshes data node.", "name": "__init__", "signature": "def __init__(self, mesh_name)" }, { "docstring": "Print the mesh nodal coordinates.", "name": "print_nodes", "signature": "def print_no...
5
stack_v2_sparse_classes_30k_train_002141
Implement the Python class `MeshInfo` described below. Class description: This class is used to print mesh information. Method signatures and docstrings: - def __init__(self, mesh_name): Initialize the MeshInfo object Args: mesh_name (string): The name of a SimVascular Meshes data node. - def print_nodes(self, ofile=...
Implement the Python class `MeshInfo` described below. Class description: This class is used to print mesh information. Method signatures and docstrings: - def __init__(self, mesh_name): Initialize the MeshInfo object Args: mesh_name (string): The name of a SimVascular Meshes data node. - def print_nodes(self, ofile=...
d2db6cdec30225fd89a37e9ef7dc99dfdb25d4a3
<|skeleton|> class MeshInfo: """This class is used to print mesh information.""" def __init__(self, mesh_name): """Initialize the MeshInfo object Args: mesh_name (string): The name of a SimVascular Meshes data node.""" <|body_0|> def print_nodes(self, ofile=sys.stdout): """Print th...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MeshInfo: """This class is used to print mesh information.""" def __init__(self, mesh_name): """Initialize the MeshInfo object Args: mesh_name (string): The name of a SimVascular Meshes data node.""" self.mesh_name = mesh_name self.repo_mesh_name = mesh_name + 'Repo' print...
the_stack_v2_python_sparse
simvascular-python-scripts/mesh_info.py
Arash67/cardiovascular
train
0