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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c1be3b6f21ccbf8fdf053412d3a910fc58fd8956 | [
"if create and extracted:\n for moira_list in extracted:\n self.admin_lists.add(moira_list)",
"if create and extracted:\n for moira_list in extracted:\n self.view_lists.add(moira_list)"
] | <|body_start_0|>
if create and extracted:
for moira_list in extracted:
self.admin_lists.add(moira_list)
<|end_body_0|>
<|body_start_1|>
if create and extracted:
for moira_list in extracted:
self.view_lists.add(moira_list)
<|end_body_1|>
| Factory for a Collection | CollectionFactory | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CollectionFactory:
"""Factory for a Collection"""
def admin_lists(self, create, extracted, **kwargs):
"""Post-generation hook to handle admin_lists (if provided)"""
<|body_0|>
def view_lists(self, create, extracted, **kwargs):
"""Post-generation hook to handle ad... | stack_v2_sparse_classes_36k_train_029300 | 5,608 | permissive | [
{
"docstring": "Post-generation hook to handle admin_lists (if provided)",
"name": "admin_lists",
"signature": "def admin_lists(self, create, extracted, **kwargs)"
},
{
"docstring": "Post-generation hook to handle admin_lists (if provided)",
"name": "view_lists",
"signature": "def view_l... | 2 | stack_v2_sparse_classes_30k_train_004022 | Implement the Python class `CollectionFactory` described below.
Class description:
Factory for a Collection
Method signatures and docstrings:
- def admin_lists(self, create, extracted, **kwargs): Post-generation hook to handle admin_lists (if provided)
- def view_lists(self, create, extracted, **kwargs): Post-generat... | Implement the Python class `CollectionFactory` described below.
Class description:
Factory for a Collection
Method signatures and docstrings:
- def admin_lists(self, create, extracted, **kwargs): Post-generation hook to handle admin_lists (if provided)
- def view_lists(self, create, extracted, **kwargs): Post-generat... | 7d731ce94b1fa4baba1c1b3752e2d03949a88ea0 | <|skeleton|>
class CollectionFactory:
"""Factory for a Collection"""
def admin_lists(self, create, extracted, **kwargs):
"""Post-generation hook to handle admin_lists (if provided)"""
<|body_0|>
def view_lists(self, create, extracted, **kwargs):
"""Post-generation hook to handle ad... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CollectionFactory:
"""Factory for a Collection"""
def admin_lists(self, create, extracted, **kwargs):
"""Post-generation hook to handle admin_lists (if provided)"""
if create and extracted:
for moira_list in extracted:
self.admin_lists.add(moira_list)
def ... | the_stack_v2_python_sparse | ui/factories.py | mitodl/odl-video-service | train | 4 |
28ad38201b4a9520ccba38a4bffae3aad1b083f9 | [
"args = {'value': '[{ \"name\": \"מה זה\", \"type\": \"IP\" }, { \"name\": \"myFile.txt\", \"type\": \"File\" }, { \"name\": \"172.0.0.2\", \"type\": \"IP\" }, \"somestring\"]', 'field': 'type', 'equalTo': 'IP', 'getField': 'name'}\nexpected_result = '[\"מה זה\",\"172.0.0.2\"]'\nreceived_result = where_field_equa... | <|body_start_0|>
args = {'value': '[{ "name": "מה זה", "type": "IP" }, { "name": "myFile.txt", "type": "File" }, { "name": "172.0.0.2", "type": "IP" }, "somestring"]', 'field': 'type', 'equalTo': 'IP', 'getField': 'name'}
expected_result = '["מה זה","172.0.0.2"]'
received_result = where_field_... | WhereFieldEquals | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WhereFieldEquals:
def test_where_field_equals_hebrew():
"""Given: list of dictionaries containing hebrew characters When: Finding fields that contain the given value under the given key. Then: Return properly formatted tuple containing a human readable representation and a dictionary con... | stack_v2_sparse_classes_36k_train_029301 | 5,646 | permissive | [
{
"docstring": "Given: list of dictionaries containing hebrew characters When: Finding fields that contain the given value under the given key. Then: Return properly formatted tuple containing a human readable representation and a dictionary containing the correct context.",
"name": "test_where_field_equals... | 6 | stack_v2_sparse_classes_30k_train_013247 | Implement the Python class `WhereFieldEquals` described below.
Class description:
Implement the WhereFieldEquals class.
Method signatures and docstrings:
- def test_where_field_equals_hebrew(): Given: list of dictionaries containing hebrew characters When: Finding fields that contain the given value under the given k... | Implement the Python class `WhereFieldEquals` described below.
Class description:
Implement the WhereFieldEquals class.
Method signatures and docstrings:
- def test_where_field_equals_hebrew(): Given: list of dictionaries containing hebrew characters When: Finding fields that contain the given value under the given k... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class WhereFieldEquals:
def test_where_field_equals_hebrew():
"""Given: list of dictionaries containing hebrew characters When: Finding fields that contain the given value under the given key. Then: Return properly formatted tuple containing a human readable representation and a dictionary con... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WhereFieldEquals:
def test_where_field_equals_hebrew():
"""Given: list of dictionaries containing hebrew characters When: Finding fields that contain the given value under the given key. Then: Return properly formatted tuple containing a human readable representation and a dictionary containing the co... | the_stack_v2_python_sparse | Packs/FiltersAndTransformers/Scripts/WhereFieldEquals/WhereFieldEquals_test.py | demisto/content | train | 1,023 | |
b0fef18bc85261295a96ed0ea4ebf9644dcb369f | [
"if not root1 or not root2:\n return not root1 and (not root2)\n\ndef dfs(root1, root2):\n if root1.val != root2.val:\n return False\n if not root1.left and (not root1.right) and (not root2.left) and (not root2.right):\n return True\n if not root1.right and (not root2.left) and root1.left ... | <|body_start_0|>
if not root1 or not root2:
return not root1 and (not root2)
def dfs(root1, root2):
if root1.val != root2.val:
return False
if not root1.left and (not root1.right) and (not root2.left) and (not root2.right):
return True... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def flipEquiv(self, root1, root2):
""":type root1: TreeNode :type root2: TreeNode :rtype: bool 32 ms"""
<|body_0|>
def flipEquiv_1(self, root1, root2):
""":type root1: TreeNode :type root2: TreeNode :rtype: bool 40ms"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_029302 | 3,450 | no_license | [
{
"docstring": ":type root1: TreeNode :type root2: TreeNode :rtype: bool 32 ms",
"name": "flipEquiv",
"signature": "def flipEquiv(self, root1, root2)"
},
{
"docstring": ":type root1: TreeNode :type root2: TreeNode :rtype: bool 40ms",
"name": "flipEquiv_1",
"signature": "def flipEquiv_1(s... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flipEquiv(self, root1, root2): :type root1: TreeNode :type root2: TreeNode :rtype: bool 32 ms
- def flipEquiv_1(self, root1, root2): :type root1: TreeNode :type root2: TreeNo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flipEquiv(self, root1, root2): :type root1: TreeNode :type root2: TreeNode :rtype: bool 32 ms
- def flipEquiv_1(self, root1, root2): :type root1: TreeNode :type root2: TreeNo... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def flipEquiv(self, root1, root2):
""":type root1: TreeNode :type root2: TreeNode :rtype: bool 32 ms"""
<|body_0|>
def flipEquiv_1(self, root1, root2):
""":type root1: TreeNode :type root2: TreeNode :rtype: bool 40ms"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def flipEquiv(self, root1, root2):
""":type root1: TreeNode :type root2: TreeNode :rtype: bool 32 ms"""
if not root1 or not root2:
return not root1 and (not root2)
def dfs(root1, root2):
if root1.val != root2.val:
return False
... | the_stack_v2_python_sparse | FlipEquivalentBinaryTrees_MID_951.py | 953250587/leetcode-python | train | 2 | |
0c8b2001ba30966217b9835fbb308c0d7148523e | [
"if not isinstance(data, bytes):\n raise TypeError('Data needs to be bytes.')\ntry:\n token_dict = json.loads(data.decode('utf-8'))\nexcept ValueError as exc:\n raise TypeError('Unable to parse the byte string.') from exc\nself._credential = credentials.Credentials(token=token_dict.get('token'), refresh_to... | <|body_start_0|>
if not isinstance(data, bytes):
raise TypeError('Data needs to be bytes.')
try:
token_dict = json.loads(data.decode('utf-8'))
except ValueError as exc:
raise TypeError('Unable to parse the byte string.') from exc
self._credential = cre... | OAUTH credentials for Timesketch authentication. | TimesketchOAuthCredentials | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimesketchOAuthCredentials:
"""OAUTH credentials for Timesketch authentication."""
def from_bytes(self, data):
"""Deserialize a credential object from bytes. Args: data (bytes): serialized credential object. Raises: TypeError: if the data is not in bytes."""
<|body_0|>
d... | stack_v2_sparse_classes_36k_train_029303 | 5,273 | permissive | [
{
"docstring": "Deserialize a credential object from bytes. Args: data (bytes): serialized credential object. Raises: TypeError: if the data is not in bytes.",
"name": "from_bytes",
"signature": "def from_bytes(self, data)"
},
{
"docstring": "Convert the credential object into bytes for storage.... | 2 | null | Implement the Python class `TimesketchOAuthCredentials` described below.
Class description:
OAUTH credentials for Timesketch authentication.
Method signatures and docstrings:
- def from_bytes(self, data): Deserialize a credential object from bytes. Args: data (bytes): serialized credential object. Raises: TypeError: ... | Implement the Python class `TimesketchOAuthCredentials` described below.
Class description:
OAUTH credentials for Timesketch authentication.
Method signatures and docstrings:
- def from_bytes(self, data): Deserialize a credential object from bytes. Args: data (bytes): serialized credential object. Raises: TypeError: ... | 24f471b58ca4a87cb053961b5f05c07a544ca7b8 | <|skeleton|>
class TimesketchOAuthCredentials:
"""OAUTH credentials for Timesketch authentication."""
def from_bytes(self, data):
"""Deserialize a credential object from bytes. Args: data (bytes): serialized credential object. Raises: TypeError: if the data is not in bytes."""
<|body_0|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TimesketchOAuthCredentials:
"""OAUTH credentials for Timesketch authentication."""
def from_bytes(self, data):
"""Deserialize a credential object from bytes. Args: data (bytes): serialized credential object. Raises: TypeError: if the data is not in bytes."""
if not isinstance(data, bytes)... | the_stack_v2_python_sparse | api_client/python/timesketch_api_client/credentials.py | google/timesketch | train | 2,263 |
7641960a108076227ad77c3b8252b259324a67d4 | [
"if not quota_max_calls:\n use_rate_limiter = False\nself._projects = None\nself._datasets = None\nself._tables = None\nsuper(BigQueryRepositoryClient, self).__init__(API_NAME, versions=['v2'], quota_max_calls=quota_max_calls, quota_period=quota_period, use_rate_limiter=use_rate_limiter)",
"if not self._projec... | <|body_start_0|>
if not quota_max_calls:
use_rate_limiter = False
self._projects = None
self._datasets = None
self._tables = None
super(BigQueryRepositoryClient, self).__init__(API_NAME, versions=['v2'], quota_max_calls=quota_max_calls, quota_period=quota_period, use_... | Big Query API Respository. | BigQueryRepositoryClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BigQueryRepositoryClient:
"""Big Query API Respository."""
def __init__(self, quota_max_calls=None, quota_period=100.0, use_rate_limiter=True):
"""Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period> for the API. quota_period (float): The time period to track... | stack_v2_sparse_classes_36k_train_029304 | 9,404 | permissive | [
{
"docstring": "Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period> for the API. quota_period (float): The time period to track requests over. use_rate_limiter (bool): Set to false to disable the use of a rate limiter for this service.",
"name": "__init__",
"signature": "def __... | 4 | null | Implement the Python class `BigQueryRepositoryClient` described below.
Class description:
Big Query API Respository.
Method signatures and docstrings:
- def __init__(self, quota_max_calls=None, quota_period=100.0, use_rate_limiter=True): Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period> fo... | Implement the Python class `BigQueryRepositoryClient` described below.
Class description:
Big Query API Respository.
Method signatures and docstrings:
- def __init__(self, quota_max_calls=None, quota_period=100.0, use_rate_limiter=True): Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period> fo... | d4421afa50a17ed47cbebe942044ebab3720e0f5 | <|skeleton|>
class BigQueryRepositoryClient:
"""Big Query API Respository."""
def __init__(self, quota_max_calls=None, quota_period=100.0, use_rate_limiter=True):
"""Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period> for the API. quota_period (float): The time period to track... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BigQueryRepositoryClient:
"""Big Query API Respository."""
def __init__(self, quota_max_calls=None, quota_period=100.0, use_rate_limiter=True):
"""Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period> for the API. quota_period (float): The time period to track requests ove... | the_stack_v2_python_sparse | google/cloud/forseti/common/gcp_api/bigquery.py | kevensen/forseti-security | train | 1 |
ba27a28459cec5d4cb0e1625216740d6beb93efb | [
"body = request.json\ncalendar_type = body['type']\napi_key = body['api_key']\nurl = body['calendar_url']\nresult = calendar_service.set_configuration(calendar_type, api_key, url)\nif result is not False:\n return {'error': 'Success'}\nreturn {'error': 'Unable to set calendar configuration'}",
"config = calend... | <|body_start_0|>
body = request.json
calendar_type = body['type']
api_key = body['api_key']
url = body['calendar_url']
result = calendar_service.set_configuration(calendar_type, api_key, url)
if result is not False:
return {'error': 'Success'}
return {... | CalendarConfigResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CalendarConfigResource:
def post(self):
"""Set the active calendar configuration."""
<|body_0|>
def get(self):
"""Get the active calendar configuration"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
body = request.json
calendar_type = body[... | stack_v2_sparse_classes_36k_train_029305 | 2,090 | no_license | [
{
"docstring": "Set the active calendar configuration.",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Get the active calendar configuration",
"name": "get",
"signature": "def get(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011096 | Implement the Python class `CalendarConfigResource` described below.
Class description:
Implement the CalendarConfigResource class.
Method signatures and docstrings:
- def post(self): Set the active calendar configuration.
- def get(self): Get the active calendar configuration | Implement the Python class `CalendarConfigResource` described below.
Class description:
Implement the CalendarConfigResource class.
Method signatures and docstrings:
- def post(self): Set the active calendar configuration.
- def get(self): Get the active calendar configuration
<|skeleton|>
class CalendarConfigResour... | 0b760c062275e4d265cfbd8caacd23c36042f8d3 | <|skeleton|>
class CalendarConfigResource:
def post(self):
"""Set the active calendar configuration."""
<|body_0|>
def get(self):
"""Get the active calendar configuration"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CalendarConfigResource:
def post(self):
"""Set the active calendar configuration."""
body = request.json
calendar_type = body['type']
api_key = body['api_key']
url = body['calendar_url']
result = calendar_service.set_configuration(calendar_type, api_key, url)
... | the_stack_v2_python_sparse | api/controllers/calendar.py | otter-pond/backend | train | 0 | |
4823514f4ca9e347025c51f8b110ad4e551ecd9e | [
"self.src_dirname = src_dirname\nmetadata_filename = os.path.join(src_dirname, 'swda-metadata.csv')\nself.metadata = Metadata(metadata_filename)",
"i = 1\nfor filename in glob.glob(os.path.join(self.src_dirname, 'sw*', '*.csv')):\n if display_progress:\n sys.stderr.write('\\r')\n sys.stderr.write... | <|body_start_0|>
self.src_dirname = src_dirname
metadata_filename = os.path.join(src_dirname, 'swda-metadata.csv')
self.metadata = Metadata(metadata_filename)
<|end_body_0|>
<|body_start_1|>
i = 1
for filename in glob.glob(os.path.join(self.src_dirname, 'sw*', '*.csv')):
... | Class for reading in the corpus and iterating through its values. | CorpusReader | [
"Apache-2.0",
"GPL-2.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CorpusReader:
"""Class for reading in the corpus and iterating through its values."""
def __init__(self, src_dirname):
"""Reads in the data from `src_dirname` (should be the root of the corpus). Assumes that the metadata file `swda-metadata.csv` is in the main directory of the corpus... | stack_v2_sparse_classes_36k_train_029306 | 19,441 | permissive | [
{
"docstring": "Reads in the data from `src_dirname` (should be the root of the corpus). Assumes that the metadata file `swda-metadata.csv` is in the main directory of the corpus, using that file to build the `Metadata` object used throughout.",
"name": "__init__",
"signature": "def __init__(self, src_d... | 3 | stack_v2_sparse_classes_30k_train_006523 | Implement the Python class `CorpusReader` described below.
Class description:
Class for reading in the corpus and iterating through its values.
Method signatures and docstrings:
- def __init__(self, src_dirname): Reads in the data from `src_dirname` (should be the root of the corpus). Assumes that the metadata file `... | Implement the Python class `CorpusReader` described below.
Class description:
Class for reading in the corpus and iterating through its values.
Method signatures and docstrings:
- def __init__(self, src_dirname): Reads in the data from `src_dirname` (should be the root of the corpus). Assumes that the metadata file `... | a62ff717cd4e0f8dadd5fff7aa8d2fb06ec6566b | <|skeleton|>
class CorpusReader:
"""Class for reading in the corpus and iterating through its values."""
def __init__(self, src_dirname):
"""Reads in the data from `src_dirname` (should be the root of the corpus). Assumes that the metadata file `swda-metadata.csv` is in the main directory of the corpus... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CorpusReader:
"""Class for reading in the corpus and iterating through its values."""
def __init__(self, src_dirname):
"""Reads in the data from `src_dirname` (should be the root of the corpus). Assumes that the metadata file `swda-metadata.csv` is in the main directory of the corpus, using that ... | the_stack_v2_python_sparse | src/corpora/swda/swda_reader/swda.py | ZHAOTING/dialog-processing | train | 48 |
2e75f3f70ab13799d3b163d4f2873035a0de5839 | [
"self.active = False\nLabel.__init__(self, name, None, rect, background_color)\nself.return_callback = return_callback\nreturn",
"if len(keydown_event.unicode) and unicodedata.category(keydown_event.unicode)[0] in 'LNPSZ':\n self.text = self.text + keydown_event.unicode\nelif keydown_event.key == pygame.K_BACK... | <|body_start_0|>
self.active = False
Label.__init__(self, name, None, rect, background_color)
self.return_callback = return_callback
return
<|end_body_0|>
<|body_start_1|>
if len(keydown_event.unicode) and unicodedata.category(keydown_event.unicode)[0] in 'LNPSZ':
se... | A box where the user can type text. To actually receive key events, the TextBox must be registered with the Display using Display.key_sensitive(TextBox). Attributes: TextBox.text Standard Label attribute, holding the text typed so far. TextBox.active Boolean flag whether this TextBox is active, initally False. | TextBox | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextBox:
"""A box where the user can type text. To actually receive key events, the TextBox must be registered with the Display using Display.key_sensitive(TextBox). Attributes: TextBox.text Standard Label attribute, holding the text typed so far. TextBox.active Boolean flag whether this TextBox ... | stack_v2_sparse_classes_36k_train_029307 | 27,668 | permissive | [
{
"docstring": "Initialise the TextBox. If return_callback is given, return_callback(TextBox.text) will be called when [RETURN] is pressed.",
"name": "__init__",
"signature": "def __init__(self, name, rect, return_callback=None, background_color=(250, 250, 250))"
},
{
"docstring": "If printable,... | 5 | stack_v2_sparse_classes_30k_train_011918 | Implement the Python class `TextBox` described below.
Class description:
A box where the user can type text. To actually receive key events, the TextBox must be registered with the Display using Display.key_sensitive(TextBox). Attributes: TextBox.text Standard Label attribute, holding the text typed so far. TextBox.ac... | Implement the Python class `TextBox` described below.
Class description:
A box where the user can type text. To actually receive key events, the TextBox must be registered with the Display using Display.key_sensitive(TextBox). Attributes: TextBox.text Standard Label attribute, holding the text typed so far. TextBox.ac... | c2fc3d4e9beedb8487cfa4bfa13bdf55ec36af97 | <|skeleton|>
class TextBox:
"""A box where the user can type text. To actually receive key events, the TextBox must be registered with the Display using Display.key_sensitive(TextBox). Attributes: TextBox.text Standard Label attribute, holding the text typed so far. TextBox.active Boolean flag whether this TextBox ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TextBox:
"""A box where the user can type text. To actually receive key events, the TextBox must be registered with the Display using Display.key_sensitive(TextBox). Attributes: TextBox.text Standard Label attribute, holding the text typed so far. TextBox.active Boolean flag whether this TextBox is active, in... | the_stack_v2_python_sparse | reference_scripts/clickndrag-0.4.1/clickndrag/gui.py | stivosaurus/rpi-snippets | train | 1 |
88000392ff7ed945a764d5d379e590379727bad8 | [
"super().__init__()\nself.enc = enc\nself.mlp = mlp",
"_, (hn, _) = self.enc(*args)\ny_pred = self.mlp(hn)\nreturn y_pred",
"data = (seq_cont_data, seq_cat_data, non_seq_cont_data, non_seq_cat_data)\nnonempty_tensors, nonempty_idx = get_nonempty_tensors(data)\ny_pred = self(*nonempty_tensors, nonempty_idx)\nlos... | <|body_start_0|>
super().__init__()
self.enc = enc
self.mlp = mlp
<|end_body_0|>
<|body_start_1|>
_, (hn, _) = self.enc(*args)
y_pred = self.mlp(hn)
return y_pred
<|end_body_1|>
<|body_start_2|>
data = (seq_cont_data, seq_cat_data, non_seq_cont_data, non_seq_cat... | ChurnModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChurnModel:
def __init__(self, enc, mlp):
"""Initialize model with params."""
<|body_0|>
def forward(self, *args):
"""Run a forward pass of model over the data."""
<|body_1|>
def run(self, y, seq_cont_data, seq_cat_data, non_seq_cont_data, non_seq_cat_da... | stack_v2_sparse_classes_36k_train_029308 | 15,906 | permissive | [
{
"docstring": "Initialize model with params.",
"name": "__init__",
"signature": "def __init__(self, enc, mlp)"
},
{
"docstring": "Run a forward pass of model over the data.",
"name": "forward",
"signature": "def forward(self, *args)"
},
{
"docstring": "Run model on data and prop... | 3 | stack_v2_sparse_classes_30k_train_002120 | Implement the Python class `ChurnModel` described below.
Class description:
Implement the ChurnModel class.
Method signatures and docstrings:
- def __init__(self, enc, mlp): Initialize model with params.
- def forward(self, *args): Run a forward pass of model over the data.
- def run(self, y, seq_cont_data, seq_cat_d... | Implement the Python class `ChurnModel` described below.
Class description:
Implement the ChurnModel class.
Method signatures and docstrings:
- def __init__(self, enc, mlp): Initialize model with params.
- def forward(self, *args): Run a forward pass of model over the data.
- def run(self, y, seq_cont_data, seq_cat_d... | 9cdbf270487751a0ad6862b2fea2ccc0e23a0b67 | <|skeleton|>
class ChurnModel:
def __init__(self, enc, mlp):
"""Initialize model with params."""
<|body_0|>
def forward(self, *args):
"""Run a forward pass of model over the data."""
<|body_1|>
def run(self, y, seq_cont_data, seq_cat_data, non_seq_cont_data, non_seq_cat_da... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChurnModel:
def __init__(self, enc, mlp):
"""Initialize model with params."""
super().__init__()
self.enc = enc
self.mlp = mlp
def forward(self, *args):
"""Run a forward pass of model over the data."""
_, (hn, _) = self.enc(*args)
y_pred = self.mlp(... | the_stack_v2_python_sparse | caspr/models/model_wrapper.py | microsoft/CASPR | train | 29 | |
cc8c544a641c5f9b93e06de114d2b92c0884d917 | [
"self._sub_input_topic = None\nself._sub_output_topic = None\nself._publisher = None\nself._time_received_input = 0\nself.node = node\nself.callback_lock = threading.RLock()",
"try:\n self._publisher = self.node.create_publisher(Int64, publish_topic, qos_profile=QoSProfile(depth=1))\n input_topic_type = get... | <|body_start_0|>
self._sub_input_topic = None
self._sub_output_topic = None
self._publisher = None
self._time_received_input = 0
self.node = node
self.callback_lock = threading.RLock()
<|end_body_0|>
<|body_start_1|>
try:
self._publisher = self.node.c... | The TimeEstimatorTopic class. It measures the time elapsed between the reception of a message from an input topic to an output topic and publish the measure in millisecond resolution to another topic. | TimeEstimatorTopic | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeEstimatorTopic:
"""The TimeEstimatorTopic class. It measures the time elapsed between the reception of a message from an input topic to an output topic and publish the measure in millisecond resolution to another topic."""
def __init__(self, node):
"""Create a TimeEstimatorTopic ... | stack_v2_sparse_classes_36k_train_029309 | 5,018 | permissive | [
{
"docstring": "Create a TimeEstimatorTopic object. @param node: ROS2 node @type node: rclpy.node.Node",
"name": "__init__",
"signature": "def __init__(self, node)"
},
{
"docstring": "Start the time measurement. @param input_topic: Topic to be listened to start the time measurement @type input_t... | 4 | stack_v2_sparse_classes_30k_train_005528 | Implement the Python class `TimeEstimatorTopic` described below.
Class description:
The TimeEstimatorTopic class. It measures the time elapsed between the reception of a message from an input topic to an output topic and publish the measure in millisecond resolution to another topic.
Method signatures and docstrings:... | Implement the Python class `TimeEstimatorTopic` described below.
Class description:
The TimeEstimatorTopic class. It measures the time elapsed between the reception of a message from an input topic to an output topic and publish the measure in millisecond resolution to another topic.
Method signatures and docstrings:... | ff8950abbb72366ed3072de790c405de8875ecc3 | <|skeleton|>
class TimeEstimatorTopic:
"""The TimeEstimatorTopic class. It measures the time elapsed between the reception of a message from an input topic to an output topic and publish the measure in millisecond resolution to another topic."""
def __init__(self, node):
"""Create a TimeEstimatorTopic ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TimeEstimatorTopic:
"""The TimeEstimatorTopic class. It measures the time elapsed between the reception of a message from an input topic to an output topic and publish the measure in millisecond resolution to another topic."""
def __init__(self, node):
"""Create a TimeEstimatorTopic object. @para... | the_stack_v2_python_sparse | src/tools/benchmark_tool/benchmark_tool/time_estimator/time_estimator_topic.py | bytetok/vde | train | 0 |
bbf63ddffef889806ebccd73d7b4b878fd19454e | [
"self.mainconfig = mainconfig\nself.dataconfig = dataconfig\nif mainconfig.get('atlas_list', None) is None or mainconfig.get('atlas_list', None) == 'all':\n self.atlas_list = load_txt(os.path.join(rootconfig.path.atlas, 'atlas_list.txt'))\nelif type(mainconfig['atlas_list']) is list:\n self.atlas_list = mainc... | <|body_start_0|>
self.mainconfig = mainconfig
self.dataconfig = dataconfig
if mainconfig.get('atlas_list', None) is None or mainconfig.get('atlas_list', None) == 'all':
self.atlas_list = load_txt(os.path.join(rootconfig.path.atlas, 'atlas_list.txt'))
elif type(mainconfig['atl... | The feature exporter. Export features in all mriscans. | MRIScanProcExporter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MRIScanProcExporter:
"""The feature exporter. Export features in all mriscans."""
def __init__(self, mainconfig, dataconfig, modal=None, database=False, data_source=None, force=False):
"""Init the exporter using mainconfig and dataconfig."""
<|body_0|>
def run_mriscan_at... | stack_v2_sparse_classes_36k_train_029310 | 10,193 | no_license | [
{
"docstring": "Init the exporter using mainconfig and dataconfig.",
"name": "__init__",
"signature": "def __init__(self, mainconfig, dataconfig, modal=None, database=False, data_source=None, force=False)"
},
{
"docstring": "Run one mriscan and one atlas to export.",
"name": "run_mriscan_atl... | 3 | null | Implement the Python class `MRIScanProcExporter` described below.
Class description:
The feature exporter. Export features in all mriscans.
Method signatures and docstrings:
- def __init__(self, mainconfig, dataconfig, modal=None, database=False, data_source=None, force=False): Init the exporter using mainconfig and ... | Implement the Python class `MRIScanProcExporter` described below.
Class description:
The feature exporter. Export features in all mriscans.
Method signatures and docstrings:
- def __init__(self, mainconfig, dataconfig, modal=None, database=False, data_source=None, force=False): Init the exporter using mainconfig and ... | dabfabdeb2f922a3dcbdaf3fc46f0c4b40598279 | <|skeleton|>
class MRIScanProcExporter:
"""The feature exporter. Export features in all mriscans."""
def __init__(self, mainconfig, dataconfig, modal=None, database=False, data_source=None, force=False):
"""Init the exporter using mainconfig and dataconfig."""
<|body_0|>
def run_mriscan_at... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MRIScanProcExporter:
"""The feature exporter. Export features in all mriscans."""
def __init__(self, mainconfig, dataconfig, modal=None, database=False, data_source=None, force=False):
"""Init the exporter using mainconfig and dataconfig."""
self.mainconfig = mainconfig
self.datac... | the_stack_v2_python_sparse | mmdps/dms/feature_exporter.py | geyunxiang/mmdps | train | 5 |
7e9c7980f15c1ceb926fd185489a13e483643af5 | [
"if not p:\n return 0\nsbs = collections.defaultdict(int)\nfor i in range(len(p)):\n s = p[i]\n if i + sbs[s] >= len(p):\n continue\n if p[i + sbs[s]] != chr((ord(p[i]) - ord('a') + sbs[s]) % 26 + ord('a')):\n continue\n l = 1\n for j in range(i + 1, len(p) + 1):\n l = j - i\n... | <|body_start_0|>
if not p:
return 0
sbs = collections.defaultdict(int)
for i in range(len(p)):
s = p[i]
if i + sbs[s] >= len(p):
continue
if p[i + sbs[s]] != chr((ord(p[i]) - ord('a') + sbs[s]) % 26 + ord('a')):
cont... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findSubstringInWraproundString1(self, p):
""":type p: str :rtype: int"""
<|body_0|>
def findSubstringInWraproundString(self, p):
""":type p: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not p:
return 0... | stack_v2_sparse_classes_36k_train_029311 | 4,903 | permissive | [
{
"docstring": ":type p: str :rtype: int",
"name": "findSubstringInWraproundString1",
"signature": "def findSubstringInWraproundString1(self, p)"
},
{
"docstring": ":type p: str :rtype: int",
"name": "findSubstringInWraproundString",
"signature": "def findSubstringInWraproundString(self,... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findSubstringInWraproundString1(self, p): :type p: str :rtype: int
- def findSubstringInWraproundString(self, p): :type p: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findSubstringInWraproundString1(self, p): :type p: str :rtype: int
- def findSubstringInWraproundString(self, p): :type p: str :rtype: int
<|skeleton|>
class Solution:
... | 2830c7e2ada8dfd3dcdda7c06846116d4f944a27 | <|skeleton|>
class Solution:
def findSubstringInWraproundString1(self, p):
""":type p: str :rtype: int"""
<|body_0|>
def findSubstringInWraproundString(self, p):
""":type p: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findSubstringInWraproundString1(self, p):
""":type p: str :rtype: int"""
if not p:
return 0
sbs = collections.defaultdict(int)
for i in range(len(p)):
s = p[i]
if i + sbs[s] >= len(p):
continue
if p[i... | the_stack_v2_python_sparse | leetcode/medium/Unique_Substrings_in_Wraparound_String.py | shhuan/algorithms | train | 0 | |
f2ac35d04c79d012edcaaeda2572541ae557533e | [
"if flip:\n return [flip_lr(inv_depth) for inv_depth in model(flip_lr(image))]\nelse:\n return model(image)",
"if shape is None:\n shape = images[0].shape\nif len(shape) > 2:\n shape = shape[-2:]\nreturn [F.interpolate(image, shape, mode=mode, align_corners=align_corners) for image in images]",
"inv... | <|body_start_0|>
if flip:
return [flip_lr(inv_depth) for inv_depth in model(flip_lr(image))]
else:
return model(image)
<|end_body_0|>
<|body_start_1|>
if shape is None:
shape = images[0].shape
if len(shape) > 2:
shape = shape[-2:]
... | Model class encapsulating a pose and depth networks. Parameters ---------- depth_net : nn.Module Depth network to be used pose_net : nn.Module Pose network to be used rotation_mode : str Rotation mode for the pose network flip_lr_prob : float Probability of flipping when using the depth network upsample_depth_maps : bo... | GenericSfmModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenericSfmModel:
"""Model class encapsulating a pose and depth networks. Parameters ---------- depth_net : nn.Module Depth network to be used pose_net : nn.Module Pose network to be used rotation_mode : str Rotation mode for the pose network flip_lr_prob : float Probability of flipping when using... | stack_v2_sparse_classes_36k_train_029312 | 4,019 | permissive | [
{
"docstring": "Flip input image and flip output inverse depth map Parameters ---------- model : nn.Module Module to be used image : torch.Tensor [B,3,H,W] Input image flip : bool True if the flip is happening Returns ------- inv_depths : list of torch.Tensor [B,1,H,W] List of predicted inverse depth maps",
... | 4 | stack_v2_sparse_classes_30k_train_003333 | Implement the Python class `GenericSfmModel` described below.
Class description:
Model class encapsulating a pose and depth networks. Parameters ---------- depth_net : nn.Module Depth network to be used pose_net : nn.Module Pose network to be used rotation_mode : str Rotation mode for the pose network flip_lr_prob : f... | Implement the Python class `GenericSfmModel` described below.
Class description:
Model class encapsulating a pose and depth networks. Parameters ---------- depth_net : nn.Module Depth network to be used pose_net : nn.Module Pose network to be used rotation_mode : str Rotation mode for the pose network flip_lr_prob : f... | de53b310533ff6b01eaa23a8ba5ac01bac5587b1 | <|skeleton|>
class GenericSfmModel:
"""Model class encapsulating a pose and depth networks. Parameters ---------- depth_net : nn.Module Depth network to be used pose_net : nn.Module Pose network to be used rotation_mode : str Rotation mode for the pose network flip_lr_prob : float Probability of flipping when using... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GenericSfmModel:
"""Model class encapsulating a pose and depth networks. Parameters ---------- depth_net : nn.Module Depth network to be used pose_net : nn.Module Pose network to be used rotation_mode : str Rotation mode for the pose network flip_lr_prob : float Probability of flipping when using the depth ne... | the_stack_v2_python_sparse | packnet_sfm/models/GenericSfmModel.py | TRI-ML/packnet-sfm | train | 1,226 |
a1d16f974aac0fa1a42d7330830ddb2b6dcdbef4 | [
"self.identifier = identifier\nself.name = name\nself.created_at = created_at\nself.last_modified_at = last_modified_at\nself.workflows = workflows",
"name = None\nfor prop in obj['properties']:\n if prop['key'] == 'name':\n name = prop['value']\n break\nworkflows = None\nif 'workflows' in obj:\n... | <|body_start_0|>
self.identifier = identifier
self.name = name
self.created_at = created_at
self.last_modified_at = last_modified_at
self.workflows = workflows
<|end_body_0|>
<|body_start_1|>
name = None
for prop in obj['properties']:
if prop['key'] =... | A project branch in a remote vizier instance. | BranchResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BranchResource:
"""A project branch in a remote vizier instance."""
def __init__(self, identifier: str, name: Optional[str], created_at: datetime, last_modified_at: datetime, workflows: Optional[List[WorkflowResource]]=None):
"""Initialize the branch attributes."""
<|body_0|>... | stack_v2_sparse_classes_36k_train_029313 | 2,603 | permissive | [
{
"docstring": "Initialize the branch attributes.",
"name": "__init__",
"signature": "def __init__(self, identifier: str, name: Optional[str], created_at: datetime, last_modified_at: datetime, workflows: Optional[List[WorkflowResource]]=None)"
},
{
"docstring": "Get a branch resource instance fr... | 2 | stack_v2_sparse_classes_30k_train_019351 | Implement the Python class `BranchResource` described below.
Class description:
A project branch in a remote vizier instance.
Method signatures and docstrings:
- def __init__(self, identifier: str, name: Optional[str], created_at: datetime, last_modified_at: datetime, workflows: Optional[List[WorkflowResource]]=None)... | Implement the Python class `BranchResource` described below.
Class description:
A project branch in a remote vizier instance.
Method signatures and docstrings:
- def __init__(self, identifier: str, name: Optional[str], created_at: datetime, last_modified_at: datetime, workflows: Optional[List[WorkflowResource]]=None)... | e99f43df3df80ad5647f57d805c339257336ac73 | <|skeleton|>
class BranchResource:
"""A project branch in a remote vizier instance."""
def __init__(self, identifier: str, name: Optional[str], created_at: datetime, last_modified_at: datetime, workflows: Optional[List[WorkflowResource]]=None):
"""Initialize the branch attributes."""
<|body_0|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BranchResource:
"""A project branch in a remote vizier instance."""
def __init__(self, identifier: str, name: Optional[str], created_at: datetime, last_modified_at: datetime, workflows: Optional[List[WorkflowResource]]=None):
"""Initialize the branch attributes."""
self.identifier = ident... | the_stack_v2_python_sparse | vizier/api/client/resources/branch.py | VizierDB/web-api-async | train | 2 |
14dccef513cd0ad11ec43fdbc81e4be9fee48c21 | [
"event_type = self._GetJSONValue(json_dict, 'type')\nif not event_type:\n parser_mediator.ProduceExtractionWarning('Missing event type.')\n return\nif event_type not in ('access', 'networkActivity'):\n parser_mediator.ProduceExtractionWarning('Unsupported event type: {0:s}.'.format(event_type))\n return... | <|body_start_0|>
event_type = self._GetJSONValue(json_dict, 'type')
if not event_type:
parser_mediator.ProduceExtractionWarning('Missing event type.')
return
if event_type not in ('access', 'networkActivity'):
parser_mediator.ProduceExtractionWarning('Unsuppor... | JSON-L parser plugin for iOS application privacy report files. | IOSAppPrivacPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IOSAppPrivacPlugin:
"""JSON-L parser plugin for iOS application privacy report files."""
def _ParseRecord(self, parser_mediator, json_dict):
"""Parses an iOS application privacy report record. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other com... | stack_v2_sparse_classes_36k_train_029314 | 5,927 | permissive | [
{
"docstring": "Parses an iOS application privacy report record. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfVFS. json_dict (dict): JSON dictionary of the log record.",
"name": "_ParseRecord",
"signature": "def _ParseRecord(se... | 4 | stack_v2_sparse_classes_30k_val_001085 | Implement the Python class `IOSAppPrivacPlugin` described below.
Class description:
JSON-L parser plugin for iOS application privacy report files.
Method signatures and docstrings:
- def _ParseRecord(self, parser_mediator, json_dict): Parses an iOS application privacy report record. Args: parser_mediator (ParserMedia... | Implement the Python class `IOSAppPrivacPlugin` described below.
Class description:
JSON-L parser plugin for iOS application privacy report files.
Method signatures and docstrings:
- def _ParseRecord(self, parser_mediator, json_dict): Parses an iOS application privacy report record. Args: parser_mediator (ParserMedia... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class IOSAppPrivacPlugin:
"""JSON-L parser plugin for iOS application privacy report files."""
def _ParseRecord(self, parser_mediator, json_dict):
"""Parses an iOS application privacy report record. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other com... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IOSAppPrivacPlugin:
"""JSON-L parser plugin for iOS application privacy report files."""
def _ParseRecord(self, parser_mediator, json_dict):
"""Parses an iOS application privacy report record. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such... | the_stack_v2_python_sparse | plaso/parsers/jsonl_plugins/ios_app_privacy.py | log2timeline/plaso | train | 1,506 |
6f6870151ebbf72ecb5d3e189273246add327513 | [
"tf.logging.info('Creating LoadFromRunner ...')\ntf.logging.info('\\t Iteration: %d', original_agent_iteration_number)\ntf.logging.info('\\t Load from Many: %s', load_from_many)\ntf.logging.info('\\t Initialize Value Function: %s', original_agent_weights)\nassert original_base_dir is not None, 'Must pass in origina... | <|body_start_0|>
tf.logging.info('Creating LoadFromRunner ...')
tf.logging.info('\t Iteration: %d', original_agent_iteration_number)
tf.logging.info('\t Load from Many: %s', load_from_many)
tf.logging.info('\t Initialize Value Function: %s', original_agent_weights)
assert origina... | The Memento Runner. This runner initializes a Memento agent, which starts at the best state seen by the original agent, and makes further progress. | LoadFromRunner | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoadFromRunner:
"""The Memento Runner. This runner initializes a Memento agent, which starts at the best state seen by the original agent, and makes further progress."""
def __init__(self, base_dir, create_agent_fn, create_environment_fn=atari_lib.create_atari_environment, original_base_dir=... | stack_v2_sparse_classes_36k_train_029315 | 11,029 | permissive | [
{
"docstring": "Initialize the Runner object in charge of running the Memento agent. Args: base_dir: str, the base directory to host all required sub-directories. create_agent_fn: A function that takes as args a Tensorflow session and an environment, and returns an agent. create_environment_fn: A function which... | 4 | null | Implement the Python class `LoadFromRunner` described below.
Class description:
The Memento Runner. This runner initializes a Memento agent, which starts at the best state seen by the original agent, and makes further progress.
Method signatures and docstrings:
- def __init__(self, base_dir, create_agent_fn, create_e... | Implement the Python class `LoadFromRunner` described below.
Class description:
The Memento Runner. This runner initializes a Memento agent, which starts at the best state seen by the original agent, and makes further progress.
Method signatures and docstrings:
- def __init__(self, base_dir, create_agent_fn, create_e... | 727ec399ad17b4dd1f71ce69a26fc3b0371d9fa7 | <|skeleton|>
class LoadFromRunner:
"""The Memento Runner. This runner initializes a Memento agent, which starts at the best state seen by the original agent, and makes further progress."""
def __init__(self, base_dir, create_agent_fn, create_environment_fn=atari_lib.create_atari_environment, original_base_dir=... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoadFromRunner:
"""The Memento Runner. This runner initializes a Memento agent, which starts at the best state seen by the original agent, and makes further progress."""
def __init__(self, base_dir, create_agent_fn, create_environment_fn=atari_lib.create_atari_environment, original_base_dir=None, origina... | the_stack_v2_python_sparse | memento/run_experiment_from_checkpoint.py | Ayoob7/google-research | train | 2 |
15e9d6855f50fbdf03672b1d72d70bcf19a0a59b | [
"import openalpr_api\nsuper().__init__(region=region, confidence=confidence)\nself._api = openalpr_api.DefaultApi()\nself._api_key = api_key",
"result = self._api.recognize_post(self._api_key, 'plate', image='', image_bytes=str(b64encode(image), 'utf-8'), country=self._region)\nf_plates = {}\nfor object_plate in ... | <|body_start_0|>
import openalpr_api
super().__init__(region=region, confidence=confidence)
self._api = openalpr_api.DefaultApi()
self._api_key = api_key
<|end_body_0|>
<|body_start_1|>
result = self._api.recognize_post(self._api_key, 'plate', image='', image_bytes=str(b64encode... | Use the cloud openalpr api to parse licences plate. | OpenalprApiCloud | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpenalprApiCloud:
"""Use the cloud openalpr api to parse licences plate."""
def __init__(self, region, confidence, api_key):
"""Init cloud api processing."""
<|body_0|>
def process_image(self, image, event_callback):
"""Callback for processing image."""
<... | stack_v2_sparse_classes_36k_train_029316 | 14,090 | permissive | [
{
"docstring": "Init cloud api processing.",
"name": "__init__",
"signature": "def __init__(self, region, confidence, api_key)"
},
{
"docstring": "Callback for processing image.",
"name": "process_image",
"signature": "def process_image(self, image, event_callback)"
}
] | 2 | null | Implement the Python class `OpenalprApiCloud` described below.
Class description:
Use the cloud openalpr api to parse licences plate.
Method signatures and docstrings:
- def __init__(self, region, confidence, api_key): Init cloud api processing.
- def process_image(self, image, event_callback): Callback for processin... | Implement the Python class `OpenalprApiCloud` described below.
Class description:
Use the cloud openalpr api to parse licences plate.
Method signatures and docstrings:
- def __init__(self, region, confidence, api_key): Init cloud api processing.
- def process_image(self, image, event_callback): Callback for processin... | ca0e92aba83de2fd6cb1cc4d14f3b4471f17cf3d | <|skeleton|>
class OpenalprApiCloud:
"""Use the cloud openalpr api to parse licences plate."""
def __init__(self, region, confidence, api_key):
"""Init cloud api processing."""
<|body_0|>
def process_image(self, image, event_callback):
"""Callback for processing image."""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OpenalprApiCloud:
"""Use the cloud openalpr api to parse licences plate."""
def __init__(self, region, confidence, api_key):
"""Init cloud api processing."""
import openalpr_api
super().__init__(region=region, confidence=confidence)
self._api = openalpr_api.DefaultApi()
... | the_stack_v2_python_sparse | homeassistant/components/openalpr.py | Smart-Torvy/torvy-home-assistant | train | 2 |
983a0b96ac9950db9ebbc7e5b27b212bd5a7aebe | [
"QMainWindow.__init__(self, parent)\nself.setupUi(self)\nself.lineEdit_last.setEchoMode(QtGui.QLineEdit.Password)\nself.lineEdit_new1.setEchoMode(QtGui.QLineEdit.Password)\nself.lineEdit_new2.setEchoMode(QtGui.QLineEdit.Password)\nself.sql_client = globalvar.get_client()",
"last = unicode(self.lineEdit_last.text(... | <|body_start_0|>
QMainWindow.__init__(self, parent)
self.setupUi(self)
self.lineEdit_last.setEchoMode(QtGui.QLineEdit.Password)
self.lineEdit_new1.setEchoMode(QtGui.QLineEdit.Password)
self.lineEdit_new2.setEchoMode(QtGui.QLineEdit.Password)
self.sql_client = globalvar.ge... | Class documentation goes here. | ManageUserWindow | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ManageUserWindow:
"""Class documentation goes here."""
def __init__(self, parent=None):
"""Constructor @param parent reference to the parent widget @type QWidget"""
<|body_0|>
def on_pushButton_clicked(self):
"""Slot documentation goes here."""
<|body_1|>... | stack_v2_sparse_classes_36k_train_029317 | 1,704 | no_license | [
{
"docstring": "Constructor @param parent reference to the parent widget @type QWidget",
"name": "__init__",
"signature": "def __init__(self, parent=None)"
},
{
"docstring": "Slot documentation goes here.",
"name": "on_pushButton_clicked",
"signature": "def on_pushButton_clicked(self)"
... | 2 | stack_v2_sparse_classes_30k_train_004697 | Implement the Python class `ManageUserWindow` described below.
Class description:
Class documentation goes here.
Method signatures and docstrings:
- def __init__(self, parent=None): Constructor @param parent reference to the parent widget @type QWidget
- def on_pushButton_clicked(self): Slot documentation goes here. | Implement the Python class `ManageUserWindow` described below.
Class description:
Class documentation goes here.
Method signatures and docstrings:
- def __init__(self, parent=None): Constructor @param parent reference to the parent widget @type QWidget
- def on_pushButton_clicked(self): Slot documentation goes here.
... | 389a2a9862e496f491ff6c3eb33ca5f5053322f2 | <|skeleton|>
class ManageUserWindow:
"""Class documentation goes here."""
def __init__(self, parent=None):
"""Constructor @param parent reference to the parent widget @type QWidget"""
<|body_0|>
def on_pushButton_clicked(self):
"""Slot documentation goes here."""
<|body_1|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ManageUserWindow:
"""Class documentation goes here."""
def __init__(self, parent=None):
"""Constructor @param parent reference to the parent widget @type QWidget"""
QMainWindow.__init__(self, parent)
self.setupUi(self)
self.lineEdit_last.setEchoMode(QtGui.QLineEdit.Passwor... | the_stack_v2_python_sparse | manage_user.py | SuperSaiyanSSS/DatabaseHIT | train | 1 |
f7ac0c24b999710288fa4acd6e663b5b6e71df72 | [
"cursor = presto_client.connect(config_name.PRESTO_DOMAIN, port=config_name.PRESTO_PORT, username=config_name.PRESTO_USER, group=config_name.PRESTO_GROUP, password=config_name.PRESTO_PASSWORD, catalog=config_name.PRESTO_CATALOG, schema=config_name.PRESTO_SCHEMA).cursor()\ncursor.execute(sql)\nresult = cursor.fetcha... | <|body_start_0|>
cursor = presto_client.connect(config_name.PRESTO_DOMAIN, port=config_name.PRESTO_PORT, username=config_name.PRESTO_USER, group=config_name.PRESTO_GROUP, password=config_name.PRESTO_PASSWORD, catalog=config_name.PRESTO_CATALOG, schema=config_name.PRESTO_SCHEMA).cursor()
cursor.execute(s... | Define Presto query | Presto_query | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Presto_query:
"""Define Presto query"""
def sql_query(self, sql):
"""Define sql query"""
<|body_0|>
def presto_Tuple_to_list(self, sql, fields):
"""将presto元祖数据转换为列表数据"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cursor = presto_client.connect... | stack_v2_sparse_classes_36k_train_029318 | 4,991 | no_license | [
{
"docstring": "Define sql query",
"name": "sql_query",
"signature": "def sql_query(self, sql)"
},
{
"docstring": "将presto元祖数据转换为列表数据",
"name": "presto_Tuple_to_list",
"signature": "def presto_Tuple_to_list(self, sql, fields)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003906 | Implement the Python class `Presto_query` described below.
Class description:
Define Presto query
Method signatures and docstrings:
- def sql_query(self, sql): Define sql query
- def presto_Tuple_to_list(self, sql, fields): 将presto元祖数据转换为列表数据 | Implement the Python class `Presto_query` described below.
Class description:
Define Presto query
Method signatures and docstrings:
- def sql_query(self, sql): Define sql query
- def presto_Tuple_to_list(self, sql, fields): 将presto元祖数据转换为列表数据
<|skeleton|>
class Presto_query:
"""Define Presto query"""
def sq... | 2de82e898524194b3b735835c044f078cc6ee5ba | <|skeleton|>
class Presto_query:
"""Define Presto query"""
def sql_query(self, sql):
"""Define sql query"""
<|body_0|>
def presto_Tuple_to_list(self, sql, fields):
"""将presto元祖数据转换为列表数据"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Presto_query:
"""Define Presto query"""
def sql_query(self, sql):
"""Define sql query"""
cursor = presto_client.connect(config_name.PRESTO_DOMAIN, port=config_name.PRESTO_PORT, username=config_name.PRESTO_USER, group=config_name.PRESTO_GROUP, password=config_name.PRESTO_PASSWORD, catalog=... | the_stack_v2_python_sparse | project/business_0321/app/db.py | visionguo/python | train | 0 |
fb24cec1aa24f392fb95df2a52f84369e87c5a90 | [
"employee = Employee.objects.get(user=request.auth.user)\nbug_priority = BugPriority.objects.get(pk=request.data['priority'])\nbug_type = BugType.objects.get(pk=request.data['type'])\nbug = Bug()\nbug.title = request.data['title']\nbug.description = request.data['description']\nbug.entry_date = request.data['entry_... | <|body_start_0|>
employee = Employee.objects.get(user=request.auth.user)
bug_priority = BugPriority.objects.get(pk=request.data['priority'])
bug_type = BugType.objects.get(pk=request.data['type'])
bug = Bug()
bug.title = request.data['title']
bug.description = request.dat... | Bugbo bugs/tikcets | BugView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BugView:
"""Bugbo bugs/tikcets"""
def create(self, request):
"""Handle POST operations Returns: Response -- JSON serialized bug/ticket instance"""
<|body_0|>
def retrieve(self, request, pk=None):
"""Handle GET requests for single bug/ticket Returns: Response -- J... | stack_v2_sparse_classes_36k_train_029319 | 6,207 | no_license | [
{
"docstring": "Handle POST operations Returns: Response -- JSON serialized bug/ticket instance",
"name": "create",
"signature": "def create(self, request)"
},
{
"docstring": "Handle GET requests for single bug/ticket Returns: Response -- JSON serialized bug instance",
"name": "retrieve",
... | 6 | stack_v2_sparse_classes_30k_train_002785 | Implement the Python class `BugView` described below.
Class description:
Bugbo bugs/tikcets
Method signatures and docstrings:
- def create(self, request): Handle POST operations Returns: Response -- JSON serialized bug/ticket instance
- def retrieve(self, request, pk=None): Handle GET requests for single bug/ticket R... | Implement the Python class `BugView` described below.
Class description:
Bugbo bugs/tikcets
Method signatures and docstrings:
- def create(self, request): Handle POST operations Returns: Response -- JSON serialized bug/ticket instance
- def retrieve(self, request, pk=None): Handle GET requests for single bug/ticket R... | 2a74a967bf891d5ddd212f371abef1bf72ebb327 | <|skeleton|>
class BugView:
"""Bugbo bugs/tikcets"""
def create(self, request):
"""Handle POST operations Returns: Response -- JSON serialized bug/ticket instance"""
<|body_0|>
def retrieve(self, request, pk=None):
"""Handle GET requests for single bug/ticket Returns: Response -- J... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BugView:
"""Bugbo bugs/tikcets"""
def create(self, request):
"""Handle POST operations Returns: Response -- JSON serialized bug/ticket instance"""
employee = Employee.objects.get(user=request.auth.user)
bug_priority = BugPriority.objects.get(pk=request.data['priority'])
bu... | the_stack_v2_python_sparse | bugboapi/views/bug.py | S-L-Murphey/Bugbo-server | train | 1 |
523180d9ca36ae28f02cb325e7ff8bdde9ad6886 | [
"with mock.patch('os.path.exists', return_value=False):\n tested._defaultArgpath = ['initial']\n tested._handle_site_scons_dir('top/dir')\n self.assertEqual(tested._defaultArgpath, ['initial'])",
"with mock.patch('os.path.exists', return_value=True):\n tested._defaultArgpath = ['initial']\n tested.... | <|body_start_0|>
with mock.patch('os.path.exists', return_value=False):
tested._defaultArgpath = ['initial']
tested._handle_site_scons_dir('top/dir')
self.assertEqual(tested._defaultArgpath, ['initial'])
<|end_body_0|>
<|body_start_1|>
with mock.patch('os.path.exists... | Test__handle_site_scons_dir | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test__handle_site_scons_dir:
def test__handle_site_scons_dir_1(self):
"""Test SConsArguments.Importer._handle_site_scons_dir()"""
<|body_0|>
def test__handle_site_scons_dir_2(self):
"""Test SConsArguments.Importer._handle_site_scons_dir()"""
<|body_1|>
d... | stack_v2_sparse_classes_36k_train_029320 | 42,804 | permissive | [
{
"docstring": "Test SConsArguments.Importer._handle_site_scons_dir()",
"name": "test__handle_site_scons_dir_1",
"signature": "def test__handle_site_scons_dir_1(self)"
},
{
"docstring": "Test SConsArguments.Importer._handle_site_scons_dir()",
"name": "test__handle_site_scons_dir_2",
"sig... | 4 | stack_v2_sparse_classes_30k_val_000479 | Implement the Python class `Test__handle_site_scons_dir` described below.
Class description:
Implement the Test__handle_site_scons_dir class.
Method signatures and docstrings:
- def test__handle_site_scons_dir_1(self): Test SConsArguments.Importer._handle_site_scons_dir()
- def test__handle_site_scons_dir_2(self): Te... | Implement the Python class `Test__handle_site_scons_dir` described below.
Class description:
Implement the Test__handle_site_scons_dir class.
Method signatures and docstrings:
- def test__handle_site_scons_dir_1(self): Test SConsArguments.Importer._handle_site_scons_dir()
- def test__handle_site_scons_dir_2(self): Te... | f4b783fc79fe3fc16e8d0f58308099a67752d299 | <|skeleton|>
class Test__handle_site_scons_dir:
def test__handle_site_scons_dir_1(self):
"""Test SConsArguments.Importer._handle_site_scons_dir()"""
<|body_0|>
def test__handle_site_scons_dir_2(self):
"""Test SConsArguments.Importer._handle_site_scons_dir()"""
<|body_1|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test__handle_site_scons_dir:
def test__handle_site_scons_dir_1(self):
"""Test SConsArguments.Importer._handle_site_scons_dir()"""
with mock.patch('os.path.exists', return_value=False):
tested._defaultArgpath = ['initial']
tested._handle_site_scons_dir('top/dir')
... | the_stack_v2_python_sparse | unit_tests/SConsArgumentsT/ImporterTests.py | mcqueen256/scons-arguments | train | 0 | |
e8e05023d5d3a4d7d689422fe3aae4b55299e097 | [
"ip_dict = {'Address': ['1.1.1.1', '1.2.3.4'], 'Range': ['1.1.1.3-1.1.2.1']}\ndicts = create_ip_list_dicts(ip_dict)\nassert len(dicts[0]) == 2\nassert len(dicts[1]) == 1",
"ip_dict = {'Address': '1.1.1.1'}\ndicts = create_ip_list_dicts(ip_dict)\nassert len(dicts) == 1\nassert len(dicts[0]) == 1",
"ip_dict = {'A... | <|body_start_0|>
ip_dict = {'Address': ['1.1.1.1', '1.2.3.4'], 'Range': ['1.1.1.3-1.1.2.1']}
dicts = create_ip_list_dicts(ip_dict)
assert len(dicts[0]) == 2
assert len(dicts[1]) == 1
<|end_body_0|>
<|body_start_1|>
ip_dict = {'Address': '1.1.1.1'}
dicts = create_ip_list_... | TestCreateIPListDicts | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCreateIPListDicts:
def test_create_ip_list_dicts_expected_format(self):
"""Given - dictionary of ip list command result When - the dictionary has the expected format Then - create a list of dictionaries"""
<|body_0|>
def test_create_ip_list_dicts_expected_format_single_v... | stack_v2_sparse_classes_36k_train_029321 | 44,285 | permissive | [
{
"docstring": "Given - dictionary of ip list command result When - the dictionary has the expected format Then - create a list of dictionaries",
"name": "test_create_ip_list_dicts_expected_format",
"signature": "def test_create_ip_list_dicts_expected_format(self)"
},
{
"docstring": "Given - dic... | 6 | stack_v2_sparse_classes_30k_train_021579 | Implement the Python class `TestCreateIPListDicts` described below.
Class description:
Implement the TestCreateIPListDicts class.
Method signatures and docstrings:
- def test_create_ip_list_dicts_expected_format(self): Given - dictionary of ip list command result When - the dictionary has the expected format Then - c... | Implement the Python class `TestCreateIPListDicts` described below.
Class description:
Implement the TestCreateIPListDicts class.
Method signatures and docstrings:
- def test_create_ip_list_dicts_expected_format(self): Given - dictionary of ip list command result When - the dictionary has the expected format Then - c... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class TestCreateIPListDicts:
def test_create_ip_list_dicts_expected_format(self):
"""Given - dictionary of ip list command result When - the dictionary has the expected format Then - create a list of dictionaries"""
<|body_0|>
def test_create_ip_list_dicts_expected_format_single_v... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestCreateIPListDicts:
def test_create_ip_list_dicts_expected_format(self):
"""Given - dictionary of ip list command result When - the dictionary has the expected format Then - create a list of dictionaries"""
ip_dict = {'Address': ['1.1.1.1', '1.2.3.4'], 'Range': ['1.1.1.3-1.1.2.1']}
... | the_stack_v2_python_sparse | Packs/qualys/Integrations/Qualysv2/Qualysv2_test.py | demisto/content | train | 1,023 | |
f8c6779dc06695de427980421e97cf95ffdbc1e3 | [
"if len(gas) == 0 or len(cost) == 0 or sum(gas) < sum(cost):\n return -1\nposition = 0\nbalance = 0\nfor i in range(len(gas)):\n balance += gas[i] - cost[i]\n if balance < 0:\n balance = 0\n position = i + 1\nreturn position",
"len_gas = len(gas)\nlen_cost = len(cost)\nif len_gas == 0 or le... | <|body_start_0|>
if len(gas) == 0 or len(cost) == 0 or sum(gas) < sum(cost):
return -1
position = 0
balance = 0
for i in range(len(gas)):
balance += gas[i] - cost[i]
if balance < 0:
balance = 0
position = i + 1
r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canCompleteCircuit(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int gas = [3, 4, 3, 6, 7, 1, 2] cost = [2, 4, 5, 1, 5, 1, 3] start = 4 (gas[4] = 7, cost[4] = 5) beats 18.86%"""
<|body_0|>
def canCompleteCircuit1(self, gas, cost):
... | stack_v2_sparse_classes_36k_train_029322 | 1,495 | no_license | [
{
"docstring": ":type gas: List[int] :type cost: List[int] :rtype: int gas = [3, 4, 3, 6, 7, 1, 2] cost = [2, 4, 5, 1, 5, 1, 3] start = 4 (gas[4] = 7, cost[4] = 5) beats 18.86%",
"name": "canCompleteCircuit",
"signature": "def canCompleteCircuit(self, gas, cost)"
},
{
"docstring": ":type gas: Li... | 2 | stack_v2_sparse_classes_30k_train_017126 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canCompleteCircuit(self, gas, cost): :type gas: List[int] :type cost: List[int] :rtype: int gas = [3, 4, 3, 6, 7, 1, 2] cost = [2, 4, 5, 1, 5, 1, 3] start = 4 (gas[4] = 7, co... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canCompleteCircuit(self, gas, cost): :type gas: List[int] :type cost: List[int] :rtype: int gas = [3, 4, 3, 6, 7, 1, 2] cost = [2, 4, 5, 1, 5, 1, 3] start = 4 (gas[4] = 7, co... | 7e0e917c15d3e35f49da3a00ef395bd5ff180d79 | <|skeleton|>
class Solution:
def canCompleteCircuit(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int gas = [3, 4, 3, 6, 7, 1, 2] cost = [2, 4, 5, 1, 5, 1, 3] start = 4 (gas[4] = 7, cost[4] = 5) beats 18.86%"""
<|body_0|>
def canCompleteCircuit1(self, gas, cost):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canCompleteCircuit(self, gas, cost):
""":type gas: List[int] :type cost: List[int] :rtype: int gas = [3, 4, 3, 6, 7, 1, 2] cost = [2, 4, 5, 1, 5, 1, 3] start = 4 (gas[4] = 7, cost[4] = 5) beats 18.86%"""
if len(gas) == 0 or len(cost) == 0 or sum(gas) < sum(cost):
retu... | the_stack_v2_python_sparse | LeetCode/134_gas_station.py | yao23/Machine_Learning_Playground | train | 12 | |
f601805f857b6297fc9105263e68618298551a31 | [
"ArgsUtils.addIfMissing('yLabel', 'Frequency', kwargs)\nsuper(FillPlot, self).__init__(**kwargs)\nself.color = kwargs.get('color', 'b')\nself.lineColor = kwargs.get('lineColor', 'none')\nself.data = kwargs.get('data', [])\nself.isLog = kwargs.get('isLog', False)",
"if not self.xLimits or not len(self.xLimits) == ... | <|body_start_0|>
ArgsUtils.addIfMissing('yLabel', 'Frequency', kwargs)
super(FillPlot, self).__init__(**kwargs)
self.color = kwargs.get('color', 'b')
self.lineColor = kwargs.get('lineColor', 'none')
self.data = kwargs.get('data', [])
self.isLog = kwargs.get('isLog', False... | A class for... | FillPlot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FillPlot:
"""A class for..."""
def __init__(self, **kwargs):
"""Creates a new instance of FillPlot."""
<|body_0|>
def shaveDataToXLimits(self):
"""shaveData doc..."""
<|body_1|>
def _plot(self):
"""_plot doc..."""
<|body_2|>
def ... | stack_v2_sparse_classes_36k_train_029323 | 3,050 | no_license | [
{
"docstring": "Creates a new instance of FillPlot.",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "shaveData doc...",
"name": "shaveDataToXLimits",
"signature": "def shaveDataToXLimits(self)"
},
{
"docstring": "_plot doc...",
"name": "_pl... | 4 | stack_v2_sparse_classes_30k_train_014354 | Implement the Python class `FillPlot` described below.
Class description:
A class for...
Method signatures and docstrings:
- def __init__(self, **kwargs): Creates a new instance of FillPlot.
- def shaveDataToXLimits(self): shaveData doc...
- def _plot(self): _plot doc...
- def _dataItemToValue(cls, value): _dataItemT... | Implement the Python class `FillPlot` described below.
Class description:
A class for...
Method signatures and docstrings:
- def __init__(self, **kwargs): Creates a new instance of FillPlot.
- def shaveDataToXLimits(self): shaveData doc...
- def _plot(self): _plot doc...
- def _dataItemToValue(cls, value): _dataItemT... | bcd0d80077c68cf4bb515d643e51f62dd6c4caaa | <|skeleton|>
class FillPlot:
"""A class for..."""
def __init__(self, **kwargs):
"""Creates a new instance of FillPlot."""
<|body_0|>
def shaveDataToXLimits(self):
"""shaveData doc..."""
<|body_1|>
def _plot(self):
"""_plot doc..."""
<|body_2|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FillPlot:
"""A class for..."""
def __init__(self, **kwargs):
"""Creates a new instance of FillPlot."""
ArgsUtils.addIfMissing('yLabel', 'Frequency', kwargs)
super(FillPlot, self).__init__(**kwargs)
self.color = kwargs.get('color', 'b')
self.lineColor = kwargs.get('... | the_stack_v2_python_sparse | src/cadence/analysis/shared/plotting/FillPlot.py | sernst/Cadence | train | 2 |
33fd18a91f91bc4856853f1c6b5e06ebbedc8c5a | [
"if num == 0:\n return 'Zero'\nunitCount = 0\nremainder = num\nwords = []\nwhile remainder > 999:\n quotient, remainder = divmod(remainder, 1000)\n if remainder > 0:\n Solution._numberToWords(remainder, words, unitCount)\n remainder = quotient\n unitCount += 1\nSolution._numberToWords(remainde... | <|body_start_0|>
if num == 0:
return 'Zero'
unitCount = 0
remainder = num
words = []
while remainder > 999:
quotient, remainder = divmod(remainder, 1000)
if remainder > 0:
Solution._numberToWords(remainder, words, unitCount)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numberToWords(self, num):
""":type num: int :rtype: str"""
<|body_0|>
def _numberToWords(num, words, unitCount):
"""1 <= num <= 999 :type num: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if num == 0:
return 'Zero'
... | stack_v2_sparse_classes_36k_train_029324 | 1,872 | no_license | [
{
"docstring": ":type num: int :rtype: str",
"name": "numberToWords",
"signature": "def numberToWords(self, num)"
},
{
"docstring": "1 <= num <= 999 :type num: int",
"name": "_numberToWords",
"signature": "def _numberToWords(num, words, unitCount)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012988 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numberToWords(self, num): :type num: int :rtype: str
- def _numberToWords(num, words, unitCount): 1 <= num <= 999 :type num: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numberToWords(self, num): :type num: int :rtype: str
- def _numberToWords(num, words, unitCount): 1 <= num <= 999 :type num: int
<|skeleton|>
class Solution:
def number... | 903578f119d2dc8c287f225becf80673eddb26d8 | <|skeleton|>
class Solution:
def numberToWords(self, num):
""":type num: int :rtype: str"""
<|body_0|>
def _numberToWords(num, words, unitCount):
"""1 <= num <= 999 :type num: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numberToWords(self, num):
""":type num: int :rtype: str"""
if num == 0:
return 'Zero'
unitCount = 0
remainder = num
words = []
while remainder > 999:
quotient, remainder = divmod(remainder, 1000)
if remainder > 0... | the_stack_v2_python_sparse | 273_integer_to_english_words/self.py | XiaochenCui/leetcode | train | 0 | |
d8fecb0d4462ddac46d66dee450e2a46743a1eef | [
"self.sim_thread = sim_thread\nself.diagn_open = True\nThread.__init__(self)",
"sleep(self.sim_thread.diagn_interval)\nlogging.basicConfig()\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\nwhile self.diagn_open:\n pd = {}\n for place in self.sim_thread.net.places:\n if place.se... | <|body_start_0|>
self.sim_thread = sim_thread
self.diagn_open = True
Thread.__init__(self)
<|end_body_0|>
<|body_start_1|>
sleep(self.sim_thread.diagn_interval)
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
whil... | SimulationDiagnostics | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimulationDiagnostics:
def __init__(self, sim_thread):
"""Initializes the diagnostics thread (for logging purposes) Parameters ------------- sim_thread Simulation thread"""
<|body_0|>
def run(self):
"""Runs the diagnostics up to the point in which diagn_open becomes ... | stack_v2_sparse_classes_36k_train_029325 | 17,319 | no_license | [
{
"docstring": "Initializes the diagnostics thread (for logging purposes) Parameters ------------- sim_thread Simulation thread",
"name": "__init__",
"signature": "def __init__(self, sim_thread)"
},
{
"docstring": "Runs the diagnostics up to the point in which diagn_open becomes False",
"nam... | 2 | stack_v2_sparse_classes_30k_train_003446 | Implement the Python class `SimulationDiagnostics` described below.
Class description:
Implement the SimulationDiagnostics class.
Method signatures and docstrings:
- def __init__(self, sim_thread): Initializes the diagnostics thread (for logging purposes) Parameters ------------- sim_thread Simulation thread
- def ru... | Implement the Python class `SimulationDiagnostics` described below.
Class description:
Implement the SimulationDiagnostics class.
Method signatures and docstrings:
- def __init__(self, sim_thread): Initializes the diagnostics thread (for logging purposes) Parameters ------------- sim_thread Simulation thread
- def ru... | 6bf84d727ab0bae76716a04ad28c7de73250c89d | <|skeleton|>
class SimulationDiagnostics:
def __init__(self, sim_thread):
"""Initializes the diagnostics thread (for logging purposes) Parameters ------------- sim_thread Simulation thread"""
<|body_0|>
def run(self):
"""Runs the diagnostics up to the point in which diagn_open becomes ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimulationDiagnostics:
def __init__(self, sim_thread):
"""Initializes the diagnostics thread (for logging purposes) Parameters ------------- sim_thread Simulation thread"""
self.sim_thread = sim_thread
self.diagn_open = True
Thread.__init__(self)
def run(self):
"""... | the_stack_v2_python_sparse | pm4py/simulation/montecarlo/variants/petri_semaph_fifo.py | niklasadams/explainable_concept_drift_pm | train | 4 | |
31af731c2ae4684547d1cea07576063b83e7432c | [
"url = 'http://www.example.com/?foo=bar'\ndomain = utils.get_domain_from_url(url)\nself.assertEqual(domain, 'www.example.com')",
"domain = 'this.is.a.subdomain.example.com'\ntld = utils.get_tld_from_domain(domain)\nself.assertEqual(tld, 'example.com')\ndomain = 'a'\ntld = utils.get_tld_from_domain(domain)\nself.a... | <|body_start_0|>
url = 'http://www.example.com/?foo=bar'
domain = utils.get_domain_from_url(url)
self.assertEqual(domain, 'www.example.com')
<|end_body_0|>
<|body_start_1|>
domain = 'this.is.a.subdomain.example.com'
tld = utils.get_tld_from_domain(domain)
self.assertEqua... | Tests the functionality of the utilities. | TestAnalyzerUtils | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAnalyzerUtils:
"""Tests the functionality of the utilities."""
def test_get_domain_from_url(self):
"""Test get_domain_from_url function."""
<|body_0|>
def test_get_tld_from_domain(self):
"""Test get_tld_from_domain function."""
<|body_1|>
def tes... | stack_v2_sparse_classes_36k_train_029326 | 3,995 | permissive | [
{
"docstring": "Test get_domain_from_url function.",
"name": "test_get_domain_from_url",
"signature": "def test_get_domain_from_url(self)"
},
{
"docstring": "Test get_tld_from_domain function.",
"name": "test_get_tld_from_domain",
"signature": "def test_get_tld_from_domain(self)"
},
... | 6 | null | Implement the Python class `TestAnalyzerUtils` described below.
Class description:
Tests the functionality of the utilities.
Method signatures and docstrings:
- def test_get_domain_from_url(self): Test get_domain_from_url function.
- def test_get_tld_from_domain(self): Test get_tld_from_domain function.
- def test_st... | Implement the Python class `TestAnalyzerUtils` described below.
Class description:
Tests the functionality of the utilities.
Method signatures and docstrings:
- def test_get_domain_from_url(self): Test get_domain_from_url function.
- def test_get_tld_from_domain(self): Test get_tld_from_domain function.
- def test_st... | 24f471b58ca4a87cb053961b5f05c07a544ca7b8 | <|skeleton|>
class TestAnalyzerUtils:
"""Tests the functionality of the utilities."""
def test_get_domain_from_url(self):
"""Test get_domain_from_url function."""
<|body_0|>
def test_get_tld_from_domain(self):
"""Test get_tld_from_domain function."""
<|body_1|>
def tes... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestAnalyzerUtils:
"""Tests the functionality of the utilities."""
def test_get_domain_from_url(self):
"""Test get_domain_from_url function."""
url = 'http://www.example.com/?foo=bar'
domain = utils.get_domain_from_url(url)
self.assertEqual(domain, 'www.example.com')
... | the_stack_v2_python_sparse | timesketch/lib/analyzers/utils_test.py | google/timesketch | train | 2,263 |
f77e4a6a531897333011cdc2b314447b56386524 | [
"with mock.patch('sys.stdout.buffer.write') as mock_write:\n utils.binary_print('hello')\n mock_write.assert_called_with('hello\\n')",
"with mock.patch('sys.stdout.buffer.write') as mock_write:\n utils.binary_print(b'hello')\n mock_write.assert_called_with(b'hello\\n')"
] | <|body_start_0|>
with mock.patch('sys.stdout.buffer.write') as mock_write:
utils.binary_print('hello')
mock_write.assert_called_with('hello\n')
<|end_body_0|>
<|body_start_1|>
with mock.patch('sys.stdout.buffer.write') as mock_write:
utils.binary_print(b'hello')
... | Tests for utils.binary_print. | BinaryPrintTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinaryPrintTest:
"""Tests for utils.binary_print."""
def test_string(self):
"""Tests that utils.binary_print can print a regular string."""
<|body_0|>
def test_binary_string(self):
"""Tests that utils.binary_print can print a bianry string."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_029327 | 5,775 | permissive | [
{
"docstring": "Tests that utils.binary_print can print a regular string.",
"name": "test_string",
"signature": "def test_string(self)"
},
{
"docstring": "Tests that utils.binary_print can print a bianry string.",
"name": "test_binary_string",
"signature": "def test_binary_string(self)"
... | 2 | stack_v2_sparse_classes_30k_train_016110 | Implement the Python class `BinaryPrintTest` described below.
Class description:
Tests for utils.binary_print.
Method signatures and docstrings:
- def test_string(self): Tests that utils.binary_print can print a regular string.
- def test_binary_string(self): Tests that utils.binary_print can print a bianry string. | Implement the Python class `BinaryPrintTest` described below.
Class description:
Tests for utils.binary_print.
Method signatures and docstrings:
- def test_string(self): Tests that utils.binary_print can print a regular string.
- def test_binary_string(self): Tests that utils.binary_print can print a bianry string.
... | f0275421f84b8f80ee767fb9230134ac97cb687b | <|skeleton|>
class BinaryPrintTest:
"""Tests for utils.binary_print."""
def test_string(self):
"""Tests that utils.binary_print can print a regular string."""
<|body_0|>
def test_binary_string(self):
"""Tests that utils.binary_print can print a bianry string."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BinaryPrintTest:
"""Tests for utils.binary_print."""
def test_string(self):
"""Tests that utils.binary_print can print a regular string."""
with mock.patch('sys.stdout.buffer.write') as mock_write:
utils.binary_print('hello')
mock_write.assert_called_with('hello\n'... | the_stack_v2_python_sparse | infra/utils_test.py | google/oss-fuzz | train | 9,438 |
434450a1c71925ea66525c121d373108f945a6bf | [
"if self.OPERATION in line:\n return True\nreturn False",
"JUMP = len(output_ds)\noutput_ds.append('@SP')\noutput_ds.append('A=M')\noutput_ds.append('A=A-1')\noutput_ds.append('D=M')\noutput_ds.append('A=A-1')\noutput_ds.append('D=M-D')\noutput_ds.append('@JUMP' + str(JUMP))\noutput_ds.append('D;' + self.jump_... | <|body_start_0|>
if self.OPERATION in line:
return True
return False
<|end_body_0|>
<|body_start_1|>
JUMP = len(output_ds)
output_ds.append('@SP')
output_ds.append('A=M')
output_ds.append('A=A-1')
output_ds.append('D=M')
output_ds.append('A=A-... | a parser that convert vm operation command to assembly | ConditionsOp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConditionsOp:
"""a parser that convert vm operation command to assembly"""
def is_triggered(self, line):
""":param line: an vm line :return: true if this line refer to given operation command"""
<|body_0|>
def parse(self, line, output_ds):
"""convert vm operation... | stack_v2_sparse_classes_36k_train_029328 | 1,331 | no_license | [
{
"docstring": ":param line: an vm line :return: true if this line refer to given operation command",
"name": "is_triggered",
"signature": "def is_triggered(self, line)"
},
{
"docstring": "convert vm operation command to assembly code :param output_ds: assembly commands output :param line: line ... | 2 | stack_v2_sparse_classes_30k_val_000401 | Implement the Python class `ConditionsOp` described below.
Class description:
a parser that convert vm operation command to assembly
Method signatures and docstrings:
- def is_triggered(self, line): :param line: an vm line :return: true if this line refer to given operation command
- def parse(self, line, output_ds):... | Implement the Python class `ConditionsOp` described below.
Class description:
a parser that convert vm operation command to assembly
Method signatures and docstrings:
- def is_triggered(self, line): :param line: an vm line :return: true if this line refer to given operation command
- def parse(self, line, output_ds):... | 2170c0fd15afc950a8f5ef2289716a01515daaaf | <|skeleton|>
class ConditionsOp:
"""a parser that convert vm operation command to assembly"""
def is_triggered(self, line):
""":param line: an vm line :return: true if this line refer to given operation command"""
<|body_0|>
def parse(self, line, output_ds):
"""convert vm operation... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConditionsOp:
"""a parser that convert vm operation command to assembly"""
def is_triggered(self, line):
""":param line: an vm line :return: true if this line refer to given operation command"""
if self.OPERATION in line:
return True
return False
def parse(self, l... | the_stack_v2_python_sparse | projects/07/VMtranslator/ConditionsOp.py | DaniNem/N2T_Zilber_Neimark | train | 0 |
bd732d86b45709b43ad278de6e218ec87471797b | [
"self.variables = variables\nself.ode_expressions = ode_expressions\nself.parameters = parameters\nself.shape = (len(variables), len(ode_expressions))\nparameters = [x for x in self.parameters]\nvariables = [x for x in variables]\nsym_vars = list(symbols(variables + parameters))\nself.expressions = make_symbolic_ja... | <|body_start_0|>
self.variables = variables
self.ode_expressions = ode_expressions
self.parameters = parameters
self.shape = (len(variables), len(ode_expressions))
parameters = [x for x in self.parameters]
variables = [x for x in variables]
sym_vars = list(symbols... | SymbolicJacobianFunction | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SymbolicJacobianFunction:
def __init__(self, variables, ode_expressions, parameters, pool=None):
"""Constructor for a precompiled function to compute epxressions numerically :param variables: a list of strings with variables names :param expr: dict of sympy expressions for the rate of ch... | stack_v2_sparse_classes_36k_train_029329 | 4,487 | permissive | [
{
"docstring": "Constructor for a precompiled function to compute epxressions numerically :param variables: a list of strings with variables names :param expr: dict of sympy expressions for the rate of change of a variable indexed by the variable name :param parameters: dict of parameters",
"name": "__init_... | 2 | null | Implement the Python class `SymbolicJacobianFunction` described below.
Class description:
Implement the SymbolicJacobianFunction class.
Method signatures and docstrings:
- def __init__(self, variables, ode_expressions, parameters, pool=None): Constructor for a precompiled function to compute epxressions numerically :... | Implement the Python class `SymbolicJacobianFunction` described below.
Class description:
Implement the SymbolicJacobianFunction class.
Method signatures and docstrings:
- def __init__(self, variables, ode_expressions, parameters, pool=None): Constructor for a precompiled function to compute epxressions numerically :... | 8cbb82c4bc53d87c347dd8fe8256479ed83ea3cd | <|skeleton|>
class SymbolicJacobianFunction:
def __init__(self, variables, ode_expressions, parameters, pool=None):
"""Constructor for a precompiled function to compute epxressions numerically :param variables: a list of strings with variables names :param expr: dict of sympy expressions for the rate of ch... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SymbolicJacobianFunction:
def __init__(self, variables, ode_expressions, parameters, pool=None):
"""Constructor for a precompiled function to compute epxressions numerically :param variables: a list of strings with variables names :param expr: dict of sympy expressions for the rate of change of a vari... | the_stack_v2_python_sparse | analysis/ode/symbolic_jacobian_fun.py | EPFL-LCSB/rekindle | train | 3 | |
3be513771724309a8a785e878d0decfbd64c5bb6 | [
"if not root:\n return []\nstack = []\nresult = []\ncur = root\nwhile cur or len(stack) != 0:\n result.append(cur.val)\n stack.append(cur)\n cur = cur.left\n while cur is None and len(stack) != 0:\n cur = stack.pop()\n cur = cur.right\nreturn result",
"if not root:\n return []\nsta... | <|body_start_0|>
if not root:
return []
stack = []
result = []
cur = root
while cur or len(stack) != 0:
result.append(cur.val)
stack.append(cur)
cur = cur.left
while cur is None and len(stack) != 0:
cur =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def pre_travel(self, root):
"""前序遍历"""
<|body_0|>
def pre_travel2(self, root):
"""第二种前序遍历的方法"""
<|body_1|>
def in_travel(self, root):
"""中序遍历"""
<|body_2|>
def after_travel(self, root):
"""后序遍历"""
<|body_3|>... | stack_v2_sparse_classes_36k_train_029330 | 4,251 | no_license | [
{
"docstring": "前序遍历",
"name": "pre_travel",
"signature": "def pre_travel(self, root)"
},
{
"docstring": "第二种前序遍历的方法",
"name": "pre_travel2",
"signature": "def pre_travel2(self, root)"
},
{
"docstring": "中序遍历",
"name": "in_travel",
"signature": "def in_travel(self, root)"... | 6 | stack_v2_sparse_classes_30k_train_005875 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pre_travel(self, root): 前序遍历
- def pre_travel2(self, root): 第二种前序遍历的方法
- def in_travel(self, root): 中序遍历
- def after_travel(self, root): 后序遍历
- def layer_travel(self, root): ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pre_travel(self, root): 前序遍历
- def pre_travel2(self, root): 第二种前序遍历的方法
- def in_travel(self, root): 中序遍历
- def after_travel(self, root): 后序遍历
- def layer_travel(self, root): ... | ef6aee94c7990d734271c204034ec273b665226d | <|skeleton|>
class Solution:
def pre_travel(self, root):
"""前序遍历"""
<|body_0|>
def pre_travel2(self, root):
"""第二种前序遍历的方法"""
<|body_1|>
def in_travel(self, root):
"""中序遍历"""
<|body_2|>
def after_travel(self, root):
"""后序遍历"""
<|body_3|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def pre_travel(self, root):
"""前序遍历"""
if not root:
return []
stack = []
result = []
cur = root
while cur or len(stack) != 0:
result.append(cur.val)
stack.append(cur)
cur = cur.left
while cur ... | the_stack_v2_python_sparse | 剑指offer/二叉树的遍历递归与非递归.py | godzzbboss/leetcode | train | 0 | |
b524d88baff6bdcc47fa3486a383a688a967b9fa | [
"try:\n from bokeh.plotting import Figure\nexcept (ModuleNotFoundError, ImportError) as Error:\n raise Error(\"Using 'BokehArtifact' requires bokeh package. Use pip install mlrun[bokeh] to install it.\")\nif figure is not None and (not isinstance(figure, Figure)):\n raise ValueError(\"BokehArtifact require... | <|body_start_0|>
try:
from bokeh.plotting import Figure
except (ModuleNotFoundError, ImportError) as Error:
raise Error("Using 'BokehArtifact' requires bokeh package. Use pip install mlrun[bokeh] to install it.")
if figure is not None and (not isinstance(figure, Figure)):... | Bokeh artifact is an artifact for saving Bokeh generated figures. They will be stored in a html format. | LegacyBokehArtifact | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LegacyBokehArtifact:
"""Bokeh artifact is an artifact for saving Bokeh generated figures. They will be stored in a html format."""
def __init__(self, figure=None, key: str=None, target_path: str=None):
"""Initialize a Bokeh artifact with the given figure. :param figure: Bokeh figure ... | stack_v2_sparse_classes_36k_train_029331 | 15,717 | permissive | [
{
"docstring": "Initialize a Bokeh artifact with the given figure. :param figure: Bokeh figure ('bokeh.plotting.Figure' object) to save as an artifact. :param key: Key for the artifact to be stored in the database. :param target_path: Path to save the artifact.",
"name": "__init__",
"signature": "def __... | 2 | stack_v2_sparse_classes_30k_train_012040 | Implement the Python class `LegacyBokehArtifact` described below.
Class description:
Bokeh artifact is an artifact for saving Bokeh generated figures. They will be stored in a html format.
Method signatures and docstrings:
- def __init__(self, figure=None, key: str=None, target_path: str=None): Initialize a Bokeh art... | Implement the Python class `LegacyBokehArtifact` described below.
Class description:
Bokeh artifact is an artifact for saving Bokeh generated figures. They will be stored in a html format.
Method signatures and docstrings:
- def __init__(self, figure=None, key: str=None, target_path: str=None): Initialize a Bokeh art... | b5fe0c05ae7f5818a4a5a5a40245c851ff9b2c77 | <|skeleton|>
class LegacyBokehArtifact:
"""Bokeh artifact is an artifact for saving Bokeh generated figures. They will be stored in a html format."""
def __init__(self, figure=None, key: str=None, target_path: str=None):
"""Initialize a Bokeh artifact with the given figure. :param figure: Bokeh figure ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LegacyBokehArtifact:
"""Bokeh artifact is an artifact for saving Bokeh generated figures. They will be stored in a html format."""
def __init__(self, figure=None, key: str=None, target_path: str=None):
"""Initialize a Bokeh artifact with the given figure. :param figure: Bokeh figure ('bokeh.plott... | the_stack_v2_python_sparse | mlrun/artifacts/plots.py | mlrun/mlrun | train | 1,093 |
4d3c384f28e82e7d8bbf15f6e790950c54d74afd | [
"self.COOLDOWN_RESET = packet_len - 1\nself.HEADER = hex_to_bool_list(header)\nself.DELAY = 1\nself.cooldown = 0\nself.shr = [False] * 16",
"self.shr = self.shr[1:] + [din]\nif self.cooldown > 0:\n self.cooldown = self.cooldown - 1\n return False\nif self.shr != self.HEADER:\n return False\nself.cooldown... | <|body_start_0|>
self.COOLDOWN_RESET = packet_len - 1
self.HEADER = hex_to_bool_list(header)
self.DELAY = 1
self.cooldown = 0
self.shr = [False] * 16
<|end_body_0|>
<|body_start_1|>
self.shr = self.shr[1:] + [din]
if self.cooldown > 0:
self.cooldown =... | Correlate against 16 bit header Once header is found, 'packet_len' bits are skipped before next header can be correlated! In general you would use this block to reset the CRC calculation. | HeaderCorrelator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HeaderCorrelator:
"""Correlate against 16 bit header Once header is found, 'packet_len' bits are skipped before next header can be correlated! In general you would use this block to reset the CRC calculation."""
def __init__(self, header, packet_len):
""":param header: 16 bit header ... | stack_v2_sparse_classes_36k_train_029332 | 2,253 | permissive | [
{
"docstring": ":param header: 16 bit header :param packet_len: this is used as a cooldown, to not discover packets inside packets",
"name": "__init__",
"signature": "def __init__(self, header, packet_len)"
},
{
"docstring": ":param din: bit in :return: True if 100% correlation",
"name": "ma... | 2 | stack_v2_sparse_classes_30k_val_000564 | Implement the Python class `HeaderCorrelator` described below.
Class description:
Correlate against 16 bit header Once header is found, 'packet_len' bits are skipped before next header can be correlated! In general you would use this block to reset the CRC calculation.
Method signatures and docstrings:
- def __init__... | Implement the Python class `HeaderCorrelator` described below.
Class description:
Correlate against 16 bit header Once header is found, 'packet_len' bits are skipped before next header can be correlated! In general you would use this block to reset the CRC calculation.
Method signatures and docstrings:
- def __init__... | 16c186fbbf90385f2ba3498395123e79b6fcf340 | <|skeleton|>
class HeaderCorrelator:
"""Correlate against 16 bit header Once header is found, 'packet_len' bits are skipped before next header can be correlated! In general you would use this block to reset the CRC calculation."""
def __init__(self, header, packet_len):
""":param header: 16 bit header ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HeaderCorrelator:
"""Correlate against 16 bit header Once header is found, 'packet_len' bits are skipped before next header can be correlated! In general you would use this block to reset the CRC calculation."""
def __init__(self, header, packet_len):
""":param header: 16 bit header :param packet... | the_stack_v2_python_sparse | pyhacores/packet/header_correlator.py | gasparka/pyhacores | train | 1 |
5ff97bdb7eaa3beab6321e83670a39942034a76d | [
"url = self.client.get_url('exchange-rates')\nparams = {'format': format}\nresp = requests.get(url, params=params)\nif resp.status_code == 200:\n return resp.json()\nelse:\n return resp.text",
"url = self.client.get_url('exchange-rates/history')\nparams = {'currency': currency, 'start': start, 'end': end}\n... | <|body_start_0|>
url = self.client.get_url('exchange-rates')
params = {'format': format}
resp = requests.get(url, params=params)
if resp.status_code == 200:
return resp.json()
else:
return resp.text
<|end_body_0|>
<|body_start_1|>
url = self.clien... | ExchangeRates | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExchangeRates:
def get_rates(self, format=None):
"""Returns the current exchange rates used by Nomics to convert prices from markets into USD. This contains Fiat currencies as well as a BTC and ETH quote prices. :param str format: Format of the response. Defaults to JSON when blank."""
... | stack_v2_sparse_classes_36k_train_029333 | 1,399 | permissive | [
{
"docstring": "Returns the current exchange rates used by Nomics to convert prices from markets into USD. This contains Fiat currencies as well as a BTC and ETH quote prices. :param str format: Format of the response. Defaults to JSON when blank.",
"name": "get_rates",
"signature": "def get_rates(self,... | 2 | stack_v2_sparse_classes_30k_train_015586 | Implement the Python class `ExchangeRates` described below.
Class description:
Implement the ExchangeRates class.
Method signatures and docstrings:
- def get_rates(self, format=None): Returns the current exchange rates used by Nomics to convert prices from markets into USD. This contains Fiat currencies as well as a ... | Implement the Python class `ExchangeRates` described below.
Class description:
Implement the ExchangeRates class.
Method signatures and docstrings:
- def get_rates(self, format=None): Returns the current exchange rates used by Nomics to convert prices from markets into USD. This contains Fiat currencies as well as a ... | 70d864b83a0384be2120cbfddc26d55cc1e22065 | <|skeleton|>
class ExchangeRates:
def get_rates(self, format=None):
"""Returns the current exchange rates used by Nomics to convert prices from markets into USD. This contains Fiat currencies as well as a BTC and ETH quote prices. :param str format: Format of the response. Defaults to JSON when blank."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExchangeRates:
def get_rates(self, format=None):
"""Returns the current exchange rates used by Nomics to convert prices from markets into USD. This contains Fiat currencies as well as a BTC and ETH quote prices. :param str format: Format of the response. Defaults to JSON when blank."""
url = s... | the_stack_v2_python_sparse | nomics/api/exchange_rates.py | luisriverag/nomics-python | train | 0 | |
ad348972f1000131c537436478b1d79b9c00950b | [
"self.num_filters = num_filters\nself.input_dim = input_dim\nself._build_layer_components()\nsuper(InceptionResnetA, self).__init__(**kwargs)",
"self.conv_block1 = [Conv2D(self.num_filters, kernel_size=(1, 1), strides=1, padding='same', activation=tf.nn.relu)]\nself.conv_block2 = [Conv2D(filters=self.num_filters,... | <|body_start_0|>
self.num_filters = num_filters
self.input_dim = input_dim
self._build_layer_components()
super(InceptionResnetA, self).__init__(**kwargs)
<|end_body_0|>
<|body_start_1|>
self.conv_block1 = [Conv2D(self.num_filters, kernel_size=(1, 1), strides=1, padding='same', ... | Variant A of the three InceptionResNet layers described in https://arxiv.org/abs/1710.02238. All variants use multiple convolutional blocks with varying kernel sizes and number of filters. This allows capturing patterns over different scales in the inputs. Residual connections are additionally used and have been shown ... | InceptionResnetA | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InceptionResnetA:
"""Variant A of the three InceptionResNet layers described in https://arxiv.org/abs/1710.02238. All variants use multiple convolutional blocks with varying kernel sizes and number of filters. This allows capturing patterns over different scales in the inputs. Residual connection... | stack_v2_sparse_classes_36k_train_029334 | 17,354 | permissive | [
{
"docstring": "Parameters ---------- num_filters: int, Number of convolutional filters input_dim: int, Number of channels in the input.",
"name": "__init__",
"signature": "def __init__(self, num_filters, input_dim, **kwargs)"
},
{
"docstring": "Builds the layers components and set _layers attri... | 3 | null | Implement the Python class `InceptionResnetA` described below.
Class description:
Variant A of the three InceptionResNet layers described in https://arxiv.org/abs/1710.02238. All variants use multiple convolutional blocks with varying kernel sizes and number of filters. This allows capturing patterns over different sc... | Implement the Python class `InceptionResnetA` described below.
Class description:
Variant A of the three InceptionResNet layers described in https://arxiv.org/abs/1710.02238. All variants use multiple convolutional blocks with varying kernel sizes and number of filters. This allows capturing patterns over different sc... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class InceptionResnetA:
"""Variant A of the three InceptionResNet layers described in https://arxiv.org/abs/1710.02238. All variants use multiple convolutional blocks with varying kernel sizes and number of filters. This allows capturing patterns over different scales in the inputs. Residual connection... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InceptionResnetA:
"""Variant A of the three InceptionResNet layers described in https://arxiv.org/abs/1710.02238. All variants use multiple convolutional blocks with varying kernel sizes and number of filters. This allows capturing patterns over different scales in the inputs. Residual connections are additio... | the_stack_v2_python_sparse | deepchem/models/chemnet_layers.py | deepchem/deepchem | train | 4,876 |
7880ff5909acaf97cca2c01e0eb6c92056a5296c | [
"self.result = 0\nself.dfs(root)\nreturn self.result",
"if not node:\n return 0\nl = self.dfs(node.left)\nr = self.dfs(node.right)\nself.result = max(self.result, l + r)\nreturn max(l, r) + 1"
] | <|body_start_0|>
self.result = 0
self.dfs(root)
return self.result
<|end_body_0|>
<|body_start_1|>
if not node:
return 0
l = self.dfs(node.left)
r = self.dfs(node.right)
self.result = max(self.result, l + r)
return max(l, r) + 1
<|end_body_1|>... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def diameterOfBinaryTree(self, root):
"""Improved solution. Original solution had a very useless `diam` variable with an unneccessary block for computing it. We don't need to check if node.left and node.right exist since we've already configured them to return zero if they are ... | stack_v2_sparse_classes_36k_train_029335 | 1,795 | no_license | [
{
"docstring": "Improved solution. Original solution had a very useless `diam` variable with an unneccessary block for computing it. We don't need to check if node.left and node.right exist since we've already configured them to return zero if they are null. :type root: TreeNode :rtype: int",
"name": "diame... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def diameterOfBinaryTree(self, root): Improved solution. Original solution had a very useless `diam` variable with an unneccessary block for computing it. We don't need to check ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def diameterOfBinaryTree(self, root): Improved solution. Original solution had a very useless `diam` variable with an unneccessary block for computing it. We don't need to check ... | f4cd43f082b58d4410008af49325770bc84d3aba | <|skeleton|>
class Solution:
def diameterOfBinaryTree(self, root):
"""Improved solution. Original solution had a very useless `diam` variable with an unneccessary block for computing it. We don't need to check if node.left and node.right exist since we've already configured them to return zero if they are ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def diameterOfBinaryTree(self, root):
"""Improved solution. Original solution had a very useless `diam` variable with an unneccessary block for computing it. We don't need to check if node.left and node.right exist since we've already configured them to return zero if they are null. :type ro... | the_stack_v2_python_sparse | 543.Diameter_of_a_Binary_Tree.py | welsny/solutions | train | 1 | |
33fc360860547960c65e76bb30190fcea9e56237 | [
"def total(node):\n if not node:\n return 0\n return node.val + total(node.left) + total(node.right)\nsm = total(root)\nres = [0]\n\ndef helper(node):\n if not node:\n return 0\n left = helper(node.left)\n right = helper(node.right)\n res[0] = max(res[0], right * (sm - right))\n r... | <|body_start_0|>
def total(node):
if not node:
return 0
return node.val + total(node.left) + total(node.right)
sm = total(root)
res = [0]
def helper(node):
if not node:
return 0
left = helper(node.left)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProduct(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def maxProductDP(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def total(node):
if not node:
... | stack_v2_sparse_classes_36k_train_029336 | 2,445 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "maxProduct",
"signature": "def maxProduct(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "maxProductDP",
"signature": "def maxProductDP(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProduct(self, root): :type root: TreeNode :rtype: int
- def maxProductDP(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProduct(self, root): :type root: TreeNode :rtype: int
- def maxProductDP(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
def maxProduct(se... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def maxProduct(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def maxProductDP(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProduct(self, root):
""":type root: TreeNode :rtype: int"""
def total(node):
if not node:
return 0
return node.val + total(node.left) + total(node.right)
sm = total(root)
res = [0]
def helper(node):
i... | the_stack_v2_python_sparse | M/MaximumProductofSplittedBinaryTree.py | bssrdf/pyleet | train | 2 | |
b607cab0befa0d2d17fe31950f60a2bfa01ba1e9 | [
"self.sensor = Sensor('http://127.0.0.1', '8000')\nself.pump = Pump('http://127.0.0.1', '8000')\nself.decider = Decider(100, 0.05)\nself.controller = Controller(self.sensor, self.pump, self.decider)\nself.actions = {'PUMP_IN': self.pump.PUMP_IN, 'PUMP_OUT': self.pump.PUMP_OUT, 'PUMP_OFF': self.pump.PUMP_OFF}",
"s... | <|body_start_0|>
self.sensor = Sensor('http://127.0.0.1', '8000')
self.pump = Pump('http://127.0.0.1', '8000')
self.decider = Decider(100, 0.05)
self.controller = Controller(self.sensor, self.pump, self.decider)
self.actions = {'PUMP_IN': self.pump.PUMP_IN, 'PUMP_OUT': self.pump.... | Module tests for the water-regulation module | ModuleTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModuleTests:
"""Module tests for the water-regulation module"""
def setUp(self):
"""Run each time before any test method"""
<|body_0|>
def test_module_true(self):
"""True state: Write an integration test that combines controller and decider, using a MOCKED sensor... | stack_v2_sparse_classes_36k_train_029337 | 1,573 | no_license | [
{
"docstring": "Run each time before any test method",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "True state: Write an integration test that combines controller and decider, using a MOCKED sensor and pump.",
"name": "test_module_true",
"signature": "def test_modul... | 3 | null | Implement the Python class `ModuleTests` described below.
Class description:
Module tests for the water-regulation module
Method signatures and docstrings:
- def setUp(self): Run each time before any test method
- def test_module_true(self): True state: Write an integration test that combines controller and decider, ... | Implement the Python class `ModuleTests` described below.
Class description:
Module tests for the water-regulation module
Method signatures and docstrings:
- def setUp(self): Run each time before any test method
- def test_module_true(self): True state: Write an integration test that combines controller and decider, ... | 263685ca90110609bfd05d621516727f8cd0028f | <|skeleton|>
class ModuleTests:
"""Module tests for the water-regulation module"""
def setUp(self):
"""Run each time before any test method"""
<|body_0|>
def test_module_true(self):
"""True state: Write an integration test that combines controller and decider, using a MOCKED sensor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModuleTests:
"""Module tests for the water-regulation module"""
def setUp(self):
"""Run each time before any test method"""
self.sensor = Sensor('http://127.0.0.1', '8000')
self.pump = Pump('http://127.0.0.1', '8000')
self.decider = Decider(100, 0.05)
self.controll... | the_stack_v2_python_sparse | students/ScottL/lesson06/water-regulation-master/waterregulation/integrationtest.py | aurel1212/Sp2018-Online | train | 0 |
e5c29bae50d7d74e28ecdf98fd623de321ccfafe | [
"parser.add_argument('--batch_size', nargs='?', type=int, default=64, help='batch_size for experiment')\nparser.add_argument('--epochs', type=int, nargs='?', default=100, help='Number of epochs to train for')\nparser.add_argument('--logs_path', type=str, nargs='?', default='classification_logs/', help='Experiment l... | <|body_start_0|>
parser.add_argument('--batch_size', nargs='?', type=int, default=64, help='batch_size for experiment')
parser.add_argument('--epochs', type=int, nargs='?', default=100, help='Number of epochs to train for')
parser.add_argument('--logs_path', type=str, nargs='?', default='classif... | KerasParserClass | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KerasParserClass:
def __init__(self, parser):
"""Parses arguments and saves them in the Parser Class :param parser: A parser to get input from"""
<|body_0|>
def get_argument_variables(self):
"""Processes the parsed arguments and produces variables of specific types n... | stack_v2_sparse_classes_36k_train_029338 | 5,172 | permissive | [
{
"docstring": "Parses arguments and saves them in the Parser Class :param parser: A parser to get input from",
"name": "__init__",
"signature": "def __init__(self, parser)"
},
{
"docstring": "Processes the parsed arguments and produces variables of specific types needed for the experiments :ret... | 2 | null | Implement the Python class `KerasParserClass` described below.
Class description:
Implement the KerasParserClass class.
Method signatures and docstrings:
- def __init__(self, parser): Parses arguments and saves them in the Parser Class :param parser: A parser to get input from
- def get_argument_variables(self): Proc... | Implement the Python class `KerasParserClass` described below.
Class description:
Implement the KerasParserClass class.
Method signatures and docstrings:
- def __init__(self, parser): Parses arguments and saves them in the Parser Class :param parser: A parser to get input from
- def get_argument_variables(self): Proc... | 2831df3ef210cb3e259bbc43dd39159533f4a33e | <|skeleton|>
class KerasParserClass:
def __init__(self, parser):
"""Parses arguments and saves them in the Parser Class :param parser: A parser to get input from"""
<|body_0|>
def get_argument_variables(self):
"""Processes the parsed arguments and produces variables of specific types n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KerasParserClass:
def __init__(self, parser):
"""Parses arguments and saves them in the Parser Class :param parser: A parser to get input from"""
parser.add_argument('--batch_size', nargs='?', type=int, default=64, help='batch_size for experiment')
parser.add_argument('--epochs', type=... | the_stack_v2_python_sparse | utils/parser_utils.py | comRamona/ACL-2018-Multimodal-Sentiment-Analysis-Multicomp | train | 0 | |
774f871c6924b3adc5cee488b2beb7128509d8eb | [
"Thread.__init__(self)\nself.name = name\nself.url = url",
"handle = urllib.request.urlopen(self.url)\nfname = os.path.basename(self.url)\nwith open(fname, 'wb') as f_handler:\n while True:\n chunk = handle.read(1024)\n if not chunk:\n break\n f_handler.write(chunk)\nmsg = '%s h... | <|body_start_0|>
Thread.__init__(self)
self.name = name
self.url = url
<|end_body_0|>
<|body_start_1|>
handle = urllib.request.urlopen(self.url)
fname = os.path.basename(self.url)
with open(fname, 'wb') as f_handler:
while True:
chunk = handle... | A threading example that can download a file | DownloadThread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DownloadThread:
"""A threading example that can download a file"""
def __init__(self, url, name):
"""Initialize the thread"""
<|body_0|>
def run(self):
"""Run the thread"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Thread.__init__(self)
... | stack_v2_sparse_classes_36k_train_029339 | 3,234 | no_license | [
{
"docstring": "Initialize the thread",
"name": "__init__",
"signature": "def __init__(self, url, name)"
},
{
"docstring": "Run the thread",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006186 | Implement the Python class `DownloadThread` described below.
Class description:
A threading example that can download a file
Method signatures and docstrings:
- def __init__(self, url, name): Initialize the thread
- def run(self): Run the thread | Implement the Python class `DownloadThread` described below.
Class description:
A threading example that can download a file
Method signatures and docstrings:
- def __init__(self, url, name): Initialize the thread
- def run(self): Run the thread
<|skeleton|>
class DownloadThread:
"""A threading example that can ... | 8ea0871c3d7ca86327424562e1b04daca6d54054 | <|skeleton|>
class DownloadThread:
"""A threading example that can download a file"""
def __init__(self, url, name):
"""Initialize the thread"""
<|body_0|>
def run(self):
"""Run the thread"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DownloadThread:
"""A threading example that can download a file"""
def __init__(self, url, name):
"""Initialize the thread"""
Thread.__init__(self)
self.name = name
self.url = url
def run(self):
"""Run the thread"""
handle = urllib.request.urlopen(self... | the_stack_v2_python_sparse | metaverse/utils/scheduler_example.py | CyberChad/Metaverse | train | 3 |
e6fa0384178cfe926aab3b216143dfcd9578cfc3 | [
"self.resource_name = str_attr\nCDevice.__init__(self, self.resource_name)\nself.obj_parent = obj_device\nself.set_logger(self.obj_parent.obj_logger)\nself.set_rest_agent(self.obj_parent.obj_rest_agent)\nself.str_device_type = self.obj_parent.str_device_type\nself.uri = '{}/{}'.format(self.obj_parent.uri, self.reso... | <|body_start_0|>
self.resource_name = str_attr
CDevice.__init__(self, self.resource_name)
self.obj_parent = obj_device
self.set_logger(self.obj_parent.obj_logger)
self.set_rest_agent(self.obj_parent.obj_rest_agent)
self.str_device_type = self.obj_parent.str_device_type
... | CCatalog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CCatalog:
def __init__(self, obj_device, str_attr):
"""@param obj_device: Parent device that init this one @type obj_device: CDevice @param str_attr: attribute of this catalog, could be: - id for catalog in catalogs - source for catalog in nodes @type str_attr: string"""
<|body_0... | stack_v2_sparse_classes_36k_train_029340 | 2,652 | no_license | [
{
"docstring": "@param obj_device: Parent device that init this one @type obj_device: CDevice @param str_attr: attribute of this catalog, could be: - id for catalog in catalogs - source for catalog in nodes @type str_attr: string",
"name": "__init__",
"signature": "def __init__(self, obj_device, str_att... | 3 | null | Implement the Python class `CCatalog` described below.
Class description:
Implement the CCatalog class.
Method signatures and docstrings:
- def __init__(self, obj_device, str_attr): @param obj_device: Parent device that init this one @type obj_device: CDevice @param str_attr: attribute of this catalog, could be: - id... | Implement the Python class `CCatalog` described below.
Class description:
Implement the CCatalog class.
Method signatures and docstrings:
- def __init__(self, obj_device, str_attr): @param obj_device: Parent device that init this one @type obj_device: CDevice @param str_attr: attribute of this catalog, could be: - id... | 8290fc0ccbde0a6a7d8784aec04c88cc325cfa4c | <|skeleton|>
class CCatalog:
def __init__(self, obj_device, str_attr):
"""@param obj_device: Parent device that init this one @type obj_device: CDevice @param str_attr: attribute of this catalog, could be: - id for catalog in catalogs - source for catalog in nodes @type str_attr: string"""
<|body_0... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CCatalog:
def __init__(self, obj_device, str_attr):
"""@param obj_device: Parent device that init this one @type obj_device: CDevice @param str_attr: attribute of this catalog, could be: - id for catalog in catalogs - source for catalog in nodes @type str_attr: string"""
self.resource_name = s... | the_stack_v2_python_sparse | idic/monorail/Catalog.py | InfraSIM/test | train | 1 | |
48a0521ca3c8fc3c9073ca61e28ed10a44717261 | [
"super(ResBlock, self).__init__()\nself.conv1 = nn.Conv2d(ch_in, ch_out, kernel_size=3, stride=1, padding=1)\nself.bn1 = nn.BatchNorm2d(ch_out)\nself.conv2 = nn.Conv2d(ch_out, ch_out, kernel_size=3, stride=1, padding=1)\nself.bn2 = nn.BatchNorm2d(ch_out)\nself.extra = nn.Sequential()\nif ch_out != ch_in:\n self.... | <|body_start_0|>
super(ResBlock, self).__init__()
self.conv1 = nn.Conv2d(ch_in, ch_out, kernel_size=3, stride=1, padding=1)
self.bn1 = nn.BatchNorm2d(ch_out)
self.conv2 = nn.Conv2d(ch_out, ch_out, kernel_size=3, stride=1, padding=1)
self.bn2 = nn.BatchNorm2d(ch_out)
self.... | ResBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResBlock:
def __init__(self, ch_in, ch_out):
""":param ch_in: 输入通道数 :param ch_out: 输出通道数"""
<|body_0|>
def forward(self, x):
""":param x: [b,ch,h,w] :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(ResBlock, self).__init__()
se... | stack_v2_sparse_classes_36k_train_029341 | 3,933 | no_license | [
{
"docstring": ":param ch_in: 输入通道数 :param ch_out: 输出通道数",
"name": "__init__",
"signature": "def __init__(self, ch_in, ch_out)"
},
{
"docstring": ":param x: [b,ch,h,w] :return:",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | null | Implement the Python class `ResBlock` described below.
Class description:
Implement the ResBlock class.
Method signatures and docstrings:
- def __init__(self, ch_in, ch_out): :param ch_in: 输入通道数 :param ch_out: 输出通道数
- def forward(self, x): :param x: [b,ch,h,w] :return: | Implement the Python class `ResBlock` described below.
Class description:
Implement the ResBlock class.
Method signatures and docstrings:
- def __init__(self, ch_in, ch_out): :param ch_in: 输入通道数 :param ch_out: 输出通道数
- def forward(self, x): :param x: [b,ch,h,w] :return:
<|skeleton|>
class ResBlock:
def __init__(... | 09681c674657b87fb11a282400051643b27a63e1 | <|skeleton|>
class ResBlock:
def __init__(self, ch_in, ch_out):
""":param ch_in: 输入通道数 :param ch_out: 输出通道数"""
<|body_0|>
def forward(self, x):
""":param x: [b,ch,h,w] :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResBlock:
def __init__(self, ch_in, ch_out):
""":param ch_in: 输入通道数 :param ch_out: 输出通道数"""
super(ResBlock, self).__init__()
self.conv1 = nn.Conv2d(ch_in, ch_out, kernel_size=3, stride=1, padding=1)
self.bn1 = nn.BatchNorm2d(ch_out)
self.conv2 = nn.Conv2d(ch_out, ch_out... | the_stack_v2_python_sparse | pytorch/part2_resnet_cifar10.py | songyuanping/syp_muke | train | 0 | |
6c4a57222cf587b476cf1c6fe6a184e5b8c021ee | [
"self.page.open()\npo = LoginPage(self.mydriver)\npo.Login_action('昆明万睿房地产开发有限公司', '1234')\nsleep(3)\nself.assertEqual(po.type_loginPass_hint(), '退出系统')\nprint('test_login1_normal is test end')",
"self.page.open()\npo = LoginPage(self.mydriver)\npo.Login_action('administrator27878', '1234')\nsleep(3)\nself.assert... | <|body_start_0|>
self.page.open()
po = LoginPage(self.mydriver)
po.Login_action('昆明万睿房地产开发有限公司', '1234')
sleep(3)
self.assertEqual(po.type_loginPass_hint(), '退出系统')
print('test_login1_normal is test end')
<|end_body_0|>
<|body_start_1|>
self.page.open()
p... | LoginTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoginTest:
def test_login1_normal(self):
"""用户名密码正确登录"""
<|body_0|>
def test_login2_passwdError(self):
"""用户名正确密码错误登录"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.page.open()
po = LoginPage(self.mydriver)
po.Login_action('昆明万... | stack_v2_sparse_classes_36k_train_029342 | 1,819 | no_license | [
{
"docstring": "用户名密码正确登录",
"name": "test_login1_normal",
"signature": "def test_login1_normal(self)"
},
{
"docstring": "用户名正确密码错误登录",
"name": "test_login2_passwdError",
"signature": "def test_login2_passwdError(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009522 | Implement the Python class `LoginTest` described below.
Class description:
Implement the LoginTest class.
Method signatures and docstrings:
- def test_login1_normal(self): 用户名密码正确登录
- def test_login2_passwdError(self): 用户名正确密码错误登录 | Implement the Python class `LoginTest` described below.
Class description:
Implement the LoginTest class.
Method signatures and docstrings:
- def test_login1_normal(self): 用户名密码正确登录
- def test_login2_passwdError(self): 用户名正确密码错误登录
<|skeleton|>
class LoginTest:
def test_login1_normal(self):
"""用户名密码正确登录"... | c9fb6ad8c837b58a35e53b98758b242710354a35 | <|skeleton|>
class LoginTest:
def test_login1_normal(self):
"""用户名密码正确登录"""
<|body_0|>
def test_login2_passwdError(self):
"""用户名正确密码错误登录"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoginTest:
def test_login1_normal(self):
"""用户名密码正确登录"""
self.page.open()
po = LoginPage(self.mydriver)
po.Login_action('昆明万睿房地产开发有限公司', '1234')
sleep(3)
self.assertEqual(po.type_loginPass_hint(), '退出系统')
print('test_login1_normal is test end')
def ... | the_stack_v2_python_sparse | untitled5/venv/fdczzxt_test2/Website/test_case/test_login.py | sack1986/python_interface | train | 0 | |
761d059bc51ee29c9b235411e3002479972c7202 | [
"adm = ProjectAdministration()\nstat = adm.get_state_by_id(state_id)\nreturn stat",
"adm = ProjectAdministration()\nstat = adm.get_state_by_id(state_id)\nif stat is not None:\n adm.delete_state(stat)\n return ('gelöscht', 200)\nelse:\n return ('There was some error', 500)"
] | <|body_start_0|>
adm = ProjectAdministration()
stat = adm.get_state_by_id(state_id)
return stat
<|end_body_0|>
<|body_start_1|>
adm = ProjectAdministration()
stat = adm.get_state_by_id(state_id)
if stat is not None:
adm.delete_state(stat)
return (... | StateOperations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StateOperations:
def get(self, state_id):
"""Auslesen eines bestimmten State-Objektes, welches durch die state_id in dem URI bestimmt wird."""
<|body_0|>
def delete(self, state_id):
"""Löschen eines bestimmten State-Objekts, welches durch die state_id in dem URI best... | stack_v2_sparse_classes_36k_train_029343 | 44,493 | no_license | [
{
"docstring": "Auslesen eines bestimmten State-Objektes, welches durch die state_id in dem URI bestimmt wird.",
"name": "get",
"signature": "def get(self, state_id)"
},
{
"docstring": "Löschen eines bestimmten State-Objekts, welches durch die state_id in dem URI bestimmt wird.",
"name": "de... | 2 | stack_v2_sparse_classes_30k_train_013345 | Implement the Python class `StateOperations` described below.
Class description:
Implement the StateOperations class.
Method signatures and docstrings:
- def get(self, state_id): Auslesen eines bestimmten State-Objektes, welches durch die state_id in dem URI bestimmt wird.
- def delete(self, state_id): Löschen eines ... | Implement the Python class `StateOperations` described below.
Class description:
Implement the StateOperations class.
Method signatures and docstrings:
- def get(self, state_id): Auslesen eines bestimmten State-Objektes, welches durch die state_id in dem URI bestimmt wird.
- def delete(self, state_id): Löschen eines ... | 4b2826225525ae855e15e1174f5cf90466097021 | <|skeleton|>
class StateOperations:
def get(self, state_id):
"""Auslesen eines bestimmten State-Objektes, welches durch die state_id in dem URI bestimmt wird."""
<|body_0|>
def delete(self, state_id):
"""Löschen eines bestimmten State-Objekts, welches durch die state_id in dem URI best... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StateOperations:
def get(self, state_id):
"""Auslesen eines bestimmten State-Objektes, welches durch die state_id in dem URI bestimmt wird."""
adm = ProjectAdministration()
stat = adm.get_state_by_id(state_id)
return stat
def delete(self, state_id):
"""Löschen eine... | the_stack_v2_python_sparse | src/main.py | KieserChristian/SW_Praktikum_Gruppe1 | train | 0 | |
a55c085a810c709d1b031bf3f3a532a41d49359f | [
"self.recycle_view.data = []\nfor country_name in self.default_countries_list:\n if self.language == 'pl':\n country = country_name[0]\n else:\n country = country_name[1]\n capital_text = text.capitalize()\n if search:\n if capital_text in country:\n self.recycle_view.dat... | <|body_start_0|>
self.recycle_view.data = []
for country_name in self.default_countries_list:
if self.language == 'pl':
country = country_name[0]
else:
country = country_name[1]
capital_text = text.capitalize()
if search:
... | CountryFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CountryFilter:
def set_country_filter(self, text='', search=False):
"""Klasa filtrująca kraje"""
<|body_0|>
def set_default_country(self, country_name):
"""Funkcja ustawiająca koordynaty na wybrane państwo"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_029344 | 7,178 | no_license | [
{
"docstring": "Klasa filtrująca kraje",
"name": "set_country_filter",
"signature": "def set_country_filter(self, text='', search=False)"
},
{
"docstring": "Funkcja ustawiająca koordynaty na wybrane państwo",
"name": "set_default_country",
"signature": "def set_default_country(self, coun... | 2 | stack_v2_sparse_classes_30k_train_018150 | Implement the Python class `CountryFilter` described below.
Class description:
Implement the CountryFilter class.
Method signatures and docstrings:
- def set_country_filter(self, text='', search=False): Klasa filtrująca kraje
- def set_default_country(self, country_name): Funkcja ustawiająca koordynaty na wybrane pań... | Implement the Python class `CountryFilter` described below.
Class description:
Implement the CountryFilter class.
Method signatures and docstrings:
- def set_country_filter(self, text='', search=False): Klasa filtrująca kraje
- def set_default_country(self, country_name): Funkcja ustawiająca koordynaty na wybrane pań... | a30d20e8c3cedab89f749a4ffa87c9a4b9636641 | <|skeleton|>
class CountryFilter:
def set_country_filter(self, text='', search=False):
"""Klasa filtrująca kraje"""
<|body_0|>
def set_default_country(self, country_name):
"""Funkcja ustawiająca koordynaty na wybrane państwo"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CountryFilter:
def set_country_filter(self, text='', search=False):
"""Klasa filtrująca kraje"""
self.recycle_view.data = []
for country_name in self.default_countries_list:
if self.language == 'pl':
country = country_name[0]
else:
... | the_stack_v2_python_sparse | news.py | GawronDev/Zdrowie | train | 2 | |
fdc076cf75d4a5ebee1530c1297cf59870bb95bf | [
"ticker = pero.FixTicker(major_values=(2, 4, 8, 16))\nticker(start=5, end=10)\nticks = ticker.major_ticks()\nself.assertEqual(ticks, (8,))\nticker(start=100, end=1000)\nticks = ticker.major_ticks()\nself.assertEqual(ticks, ())\nticker(start=5, end=1000)\nticks = ticker.major_ticks()\nself.assertEqual(ticks, (8, 16)... | <|body_start_0|>
ticker = pero.FixTicker(major_values=(2, 4, 8, 16))
ticker(start=5, end=10)
ticks = ticker.major_ticks()
self.assertEqual(ticks, (8,))
ticker(start=100, end=1000)
ticks = ticker.major_ticks()
self.assertEqual(ticks, ())
ticker(start=5, end... | Test case for fixed values ticker. | TestCase | [
"LicenseRef-scancode-philippe-de-muyter",
"LicenseRef-scancode-commercial-license",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCase:
"""Test case for fixed values ticker."""
def test_major_ticks(self):
"""Tests whether major ticks are calculated correctly."""
<|body_0|>
def test_minor_ticks(self):
"""Tests whether minor ticks are calculated correctly."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k_train_029345 | 1,811 | permissive | [
{
"docstring": "Tests whether major ticks are calculated correctly.",
"name": "test_major_ticks",
"signature": "def test_major_ticks(self)"
},
{
"docstring": "Tests whether minor ticks are calculated correctly.",
"name": "test_minor_ticks",
"signature": "def test_minor_ticks(self)"
}
] | 2 | null | Implement the Python class `TestCase` described below.
Class description:
Test case for fixed values ticker.
Method signatures and docstrings:
- def test_major_ticks(self): Tests whether major ticks are calculated correctly.
- def test_minor_ticks(self): Tests whether minor ticks are calculated correctly. | Implement the Python class `TestCase` described below.
Class description:
Test case for fixed values ticker.
Method signatures and docstrings:
- def test_major_ticks(self): Tests whether major ticks are calculated correctly.
- def test_minor_ticks(self): Tests whether minor ticks are calculated correctly.
<|skeleton... | d59b1bc056f3037b7b7ab635b6deb41120612965 | <|skeleton|>
class TestCase:
"""Test case for fixed values ticker."""
def test_major_ticks(self):
"""Tests whether major ticks are calculated correctly."""
<|body_0|>
def test_minor_ticks(self):
"""Tests whether minor ticks are calculated correctly."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestCase:
"""Test case for fixed values ticker."""
def test_major_ticks(self):
"""Tests whether major ticks are calculated correctly."""
ticker = pero.FixTicker(major_values=(2, 4, 8, 16))
ticker(start=5, end=10)
ticks = ticker.major_ticks()
self.assertEqual(ticks,... | the_stack_v2_python_sparse | unittests/tickers/test_fixed.py | xxao/pero | train | 31 |
62825cf6115febdb7dcd6a634d078090eb301e33 | [
"existing = User.objects.filter(username__iexact=self.cleaned_data['username'])\nif existing.exists():\n raise forms.ValidationError(_('A user with that username already exists.'))\nelse:\n return self.cleaned_data['username']",
"existing_email = User.objects.filter(email__iexact=self.cleaned_data['email'])... | <|body_start_0|>
existing = User.objects.filter(username__iexact=self.cleaned_data['username'])
if existing.exists():
raise forms.ValidationError(_('A user with that username already exists.'))
else:
return self.cleaned_data['username']
<|end_body_0|>
<|body_start_1|>
... | Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but should avoid defining a ``save()`` method -- the actual saving of collected user... | RegistrationForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistrationForm:
"""Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but should avoid defining a ``save()`` m... | stack_v2_sparse_classes_36k_train_029346 | 5,469 | no_license | [
{
"docstring": "Validate that the username is alphanumeric and is not already in use.",
"name": "clean_username",
"signature": "def clean_username(self)"
},
{
"docstring": "Validate that the email is unique.",
"name": "clean_email",
"signature": "def clean_email(self)"
},
{
"docs... | 3 | stack_v2_sparse_classes_30k_train_014547 | Implement the Python class `RegistrationForm` described below.
Class description:
Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, b... | Implement the Python class `RegistrationForm` described below.
Class description:
Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, b... | 4a38ec61f3642c0fdb28f8d6436639024b61fa03 | <|skeleton|>
class RegistrationForm:
"""Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but should avoid defining a ``save()`` m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegistrationForm:
"""Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but should avoid defining a ``save()`` method -- the ... | the_stack_v2_python_sparse | coursereviews/apps/registration/forms.py | Nicholas-Sliter/coursereviews | train | 0 |
85cb5b165a4e67d3020c946edd5a7ab75a94b5e8 | [
"res = []\n\ndef dfs(path, g):\n curr = path[-1]\n if curr == len(graph) - 1:\n res.append(path)\n adjs = g[curr]\n for i, adj in enumerate(adjs):\n g[curr] = adjs[:i] + adjs[i + 1:]\n dfs(path + [adj], g)\n g[curr] = adjs\ndfs([0], graph)\nreturn res",
"res = []\n\ndef dfs... | <|body_start_0|>
res = []
def dfs(path, g):
curr = path[-1]
if curr == len(graph) - 1:
res.append(path)
adjs = g[curr]
for i, adj in enumerate(adjs):
g[curr] = adjs[:i] + adjs[i + 1:]
dfs(path + [adj], g)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
"""First approach that removes edges once we've traversed them:"""
<|body_0|>
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
"""Since they tell us that th... | stack_v2_sparse_classes_36k_train_029347 | 1,001 | no_license | [
{
"docstring": "First approach that removes edges once we've traversed them:",
"name": "allPathsSourceTarget",
"signature": "def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]"
},
{
"docstring": "Since they tell us that the graph is acyclical, we don't need to remove verti... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: First approach that removes edges once we've traversed them:
- def allPathsSourceTarget(self, graph: Li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: First approach that removes edges once we've traversed them:
- def allPathsSourceTarget(self, graph: Li... | f4cd43f082b58d4410008af49325770bc84d3aba | <|skeleton|>
class Solution:
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
"""First approach that removes edges once we've traversed them:"""
<|body_0|>
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
"""Since they tell us that th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
"""First approach that removes edges once we've traversed them:"""
res = []
def dfs(path, g):
curr = path[-1]
if curr == len(graph) - 1:
res.append(path)
... | the_stack_v2_python_sparse | 797.All_Paths_From_Source_to_Target.py | welsny/solutions | train | 1 | |
3f3b7edd48c2133ca8c765295f66b72f84e28500 | [
"if not os.path.exists(obj):\n raise MLRunInvalidArgumentError(f\"The given path do not exist: '{obj}'\")\nif os.path.isfile(obj):\n artifact = Artifact(key=key, src_path=os.path.abspath(obj))\n instructions = {'is_directory': False}\nelif os.path.isdir(obj):\n output_path = tempfile.mkdtemp()\n arch... | <|body_start_0|>
if not os.path.exists(obj):
raise MLRunInvalidArgumentError(f"The given path do not exist: '{obj}'")
if os.path.isfile(obj):
artifact = Artifact(key=key, src_path=os.path.abspath(obj))
instructions = {'is_directory': False}
elif os.path.isdir(... | ``builtins.str`` packager. | StrPackager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StrPackager:
"""``builtins.str`` packager."""
def pack_path(cls, obj: str, key: str, archive_format: str=DEFAULT_ARCHIVE_FORMAT) -> Tuple[Artifact, dict]:
"""Pack a path string value content (pack the file or directory in that path). :param obj: The string path value to pack. :param ... | stack_v2_sparse_classes_36k_train_029348 | 22,787 | permissive | [
{
"docstring": "Pack a path string value content (pack the file or directory in that path). :param obj: The string path value to pack. :param key: The key to use for the artifact. :param archive_format: The archive format to use in case the path is of a directory. Default is zip. :return: The packed artifact an... | 2 | null | Implement the Python class `StrPackager` described below.
Class description:
``builtins.str`` packager.
Method signatures and docstrings:
- def pack_path(cls, obj: str, key: str, archive_format: str=DEFAULT_ARCHIVE_FORMAT) -> Tuple[Artifact, dict]: Pack a path string value content (pack the file or directory in that ... | Implement the Python class `StrPackager` described below.
Class description:
``builtins.str`` packager.
Method signatures and docstrings:
- def pack_path(cls, obj: str, key: str, archive_format: str=DEFAULT_ARCHIVE_FORMAT) -> Tuple[Artifact, dict]: Pack a path string value content (pack the file or directory in that ... | b5fe0c05ae7f5818a4a5a5a40245c851ff9b2c77 | <|skeleton|>
class StrPackager:
"""``builtins.str`` packager."""
def pack_path(cls, obj: str, key: str, archive_format: str=DEFAULT_ARCHIVE_FORMAT) -> Tuple[Artifact, dict]:
"""Pack a path string value content (pack the file or directory in that path). :param obj: The string path value to pack. :param ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StrPackager:
"""``builtins.str`` packager."""
def pack_path(cls, obj: str, key: str, archive_format: str=DEFAULT_ARCHIVE_FORMAT) -> Tuple[Artifact, dict]:
"""Pack a path string value content (pack the file or directory in that path). :param obj: The string path value to pack. :param key: The key ... | the_stack_v2_python_sparse | mlrun/package/packagers/python_standard_library_packagers.py | mlrun/mlrun | train | 1,093 |
11727e9a5c0974e8121cfb322ec3e3b3bcffabe3 | [
"if isinstance(yaml, dict):\n self.projects: Optional[List[Project]] = None\n self.sections: Optional[List[Section]] = [Section(name, section) for name, section in yaml.items()]\nelif isinstance(yaml, list):\n self.projects: Optional[List[Project]] = [Project(p) for p in yaml]\n self.sections: Optional[... | <|body_start_0|>
if isinstance(yaml, dict):
self.projects: Optional[List[Project]] = None
self.sections: Optional[List[Section]] = [Section(name, section) for name, section in yaml.items()]
elif isinstance(yaml, list):
self.projects: Optional[List[Project]] = [Project... | clowder yaml Clowder model class :ivar Optional[List[Project]] projects: Projects :ivar Optional[List[Group]] sections: Groups | Clowder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Clowder:
"""clowder yaml Clowder model class :ivar Optional[List[Project]] projects: Projects :ivar Optional[List[Group]] sections: Groups"""
def __init__(self, yaml: Union[dict, List[Project]]):
"""Upstream __init__ :param Union[dict, List[Project]] yaml: Parsed YAML python object f... | stack_v2_sparse_classes_36k_train_029349 | 1,715 | permissive | [
{
"docstring": "Upstream __init__ :param Union[dict, List[Project]] yaml: Parsed YAML python object for clowder",
"name": "__init__",
"signature": "def __init__(self, yaml: Union[dict, List[Project]])"
},
{
"docstring": "Return python object representation for saving yaml :param bool resolved: W... | 2 | null | Implement the Python class `Clowder` described below.
Class description:
clowder yaml Clowder model class :ivar Optional[List[Project]] projects: Projects :ivar Optional[List[Group]] sections: Groups
Method signatures and docstrings:
- def __init__(self, yaml: Union[dict, List[Project]]): Upstream __init__ :param Uni... | Implement the Python class `Clowder` described below.
Class description:
clowder yaml Clowder model class :ivar Optional[List[Project]] projects: Projects :ivar Optional[List[Group]] sections: Groups
Method signatures and docstrings:
- def __init__(self, yaml: Union[dict, List[Project]]): Upstream __init__ :param Uni... | 1438fc8b1bb7379de66142ffcb0e20b459b59159 | <|skeleton|>
class Clowder:
"""clowder yaml Clowder model class :ivar Optional[List[Project]] projects: Projects :ivar Optional[List[Group]] sections: Groups"""
def __init__(self, yaml: Union[dict, List[Project]]):
"""Upstream __init__ :param Union[dict, List[Project]] yaml: Parsed YAML python object f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Clowder:
"""clowder yaml Clowder model class :ivar Optional[List[Project]] projects: Projects :ivar Optional[List[Group]] sections: Groups"""
def __init__(self, yaml: Union[dict, List[Project]]):
"""Upstream __init__ :param Union[dict, List[Project]] yaml: Parsed YAML python object for clowder"""... | the_stack_v2_python_sparse | clowder/model/clowder.py | JrGoodle/clowder | train | 17 |
e1f2c067e1b18b0688adaa425b177c218225e8e7 | [
"super(ResNet, self).__init__()\nself.blocks = blocks\nself.in_channels = in_channels\nself.num_classes = num_classes\nself.global_pool = global_pool\nself.output_stride = output_stride\nself.include_root_block = include_root_block\nself.conv2d_same = Conv2dSame(self.in_channels, 64, 7, 2)\nself.max_pool2d = nn.Max... | <|body_start_0|>
super(ResNet, self).__init__()
self.blocks = blocks
self.in_channels = in_channels
self.num_classes = num_classes
self.global_pool = global_pool
self.output_stride = output_stride
self.include_root_block = include_root_block
self.conv2d_sa... | Resnet | ResNet | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResNet:
"""Resnet"""
def __init__(self, blocks, in_channels, num_classes=None, global_pool=True, output_stride=None, include_root_block=True):
"""Args: blocks: blocks config. should be generated by _make_block in_channels: in channels num_classes: the number of classes global_pool: I... | stack_v2_sparse_classes_36k_train_029350 | 11,719 | permissive | [
{
"docstring": "Args: blocks: blocks config. should be generated by _make_block in_channels: in channels num_classes: the number of classes global_pool: If True, we perform global average pooling before computing the logits. Set to True for image classification, False for dense prediction. output_stride: If Non... | 2 | null | Implement the Python class `ResNet` described below.
Class description:
Resnet
Method signatures and docstrings:
- def __init__(self, blocks, in_channels, num_classes=None, global_pool=True, output_stride=None, include_root_block=True): Args: blocks: blocks config. should be generated by _make_block in_channels: in c... | Implement the Python class `ResNet` described below.
Class description:
Resnet
Method signatures and docstrings:
- def __init__(self, blocks, in_channels, num_classes=None, global_pool=True, output_stride=None, include_root_block=True): Args: blocks: blocks config. should be generated by _make_block in_channels: in c... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class ResNet:
"""Resnet"""
def __init__(self, blocks, in_channels, num_classes=None, global_pool=True, output_stride=None, include_root_block=True):
"""Args: blocks: blocks config. should be generated by _make_block in_channels: in channels num_classes: the number of classes global_pool: I... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResNet:
"""Resnet"""
def __init__(self, blocks, in_channels, num_classes=None, global_pool=True, output_stride=None, include_root_block=True):
"""Args: blocks: blocks config. should be generated by _make_block in_channels: in channels num_classes: the number of classes global_pool: If True, we pe... | the_stack_v2_python_sparse | research/cv/ArtTrack/src/model/resnet/resnet.py | mindspore-ai/models | train | 301 |
c25cb8e395a20cd0760a9a4a5cf81bff503a3c6f | [
"self.storages = []\nself.main_storage = None\nself.stores = {}\nif storages is not None:\n map(self.add, storages)",
"if type(storage) is list:\n [self.add(st) for st in storage]\n return\nif not hasattr(storage, 'use_uuid'):\n raise RuntimeError('The storage to be added does not use UUIDs!')\nfor st... | <|body_start_0|>
self.storages = []
self.main_storage = None
self.stores = {}
if storages is not None:
map(self.add, storages)
<|end_body_0|>
<|body_start_1|>
if type(storage) is list:
[self.add(st) for st in storage]
return
if not has... | A View on a storage that only changes the iteration over steps. Can be used for bootstrapping on subsets of steps and pass this object to analysis routines. | DistributedUUIDStorage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DistributedUUIDStorage:
"""A View on a storage that only changes the iteration over steps. Can be used for bootstrapping on subsets of steps and pass this object to analysis routines."""
def __init__(self, storages=None):
"""Parameters ---------- storages : list of :class:`openpathsa... | stack_v2_sparse_classes_36k_train_029351 | 3,665 | permissive | [
{
"docstring": "Parameters ---------- storages : list of :class:`openpathsampling.storage.Storage` The storages to be used",
"name": "__init__",
"signature": "def __init__(self, storages=None)"
},
{
"docstring": "Add a (read-only) file to the set of storages Parameters ---------- storage",
"... | 2 | null | Implement the Python class `DistributedUUIDStorage` described below.
Class description:
A View on a storage that only changes the iteration over steps. Can be used for bootstrapping on subsets of steps and pass this object to analysis routines.
Method signatures and docstrings:
- def __init__(self, storages=None): Pa... | Implement the Python class `DistributedUUIDStorage` described below.
Class description:
A View on a storage that only changes the iteration over steps. Can be used for bootstrapping on subsets of steps and pass this object to analysis routines.
Method signatures and docstrings:
- def __init__(self, storages=None): Pa... | 3d02df4ccdeb6d62030a28e371a6b4ea9aaee5fe | <|skeleton|>
class DistributedUUIDStorage:
"""A View on a storage that only changes the iteration over steps. Can be used for bootstrapping on subsets of steps and pass this object to analysis routines."""
def __init__(self, storages=None):
"""Parameters ---------- storages : list of :class:`openpathsa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DistributedUUIDStorage:
"""A View on a storage that only changes the iteration over steps. Can be used for bootstrapping on subsets of steps and pass this object to analysis routines."""
def __init__(self, storages=None):
"""Parameters ---------- storages : list of :class:`openpathsampling.storag... | the_stack_v2_python_sparse | openpathsampling/storage/distributed.py | dwhswenson/openpathsampling | train | 3 |
35d88e8923e9d0bbb66a45df3b66939759d0a77b | [
"self._datafolder = datafolder\nself._tectonic_grid = os.path.join(datafolder, 'tectonic_global.grd')\nself._oceanic_grid = os.path.join(datafolder, 'oceanic_global.grd')",
"config = get_config()\ndatadir = config['DATA']['folder']\nreturn cls(datadir)",
"regions = OrderedDict()\ngd = GeoDict.createDictFromCent... | <|body_start_0|>
self._datafolder = datafolder
self._tectonic_grid = os.path.join(datafolder, 'tectonic_global.grd')
self._oceanic_grid = os.path.join(datafolder, 'oceanic_global.grd')
<|end_body_0|>
<|body_start_1|>
config = get_config()
datadir = config['DATA']['folder']
... | Regionalizer | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-public-domain-disclaimer",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Regionalizer:
def __init__(self, datafolder):
"""Determine tectonic region information given epicenter and depth. Args: datafolder (str): Path to directory containing spatial data for tectonic regions."""
<|body_0|>
def load(cls):
"""Load regionalizer data from data ... | stack_v2_sparse_classes_36k_train_029352 | 7,330 | permissive | [
{
"docstring": "Determine tectonic region information given epicenter and depth. Args: datafolder (str): Path to directory containing spatial data for tectonic regions.",
"name": "__init__",
"signature": "def __init__(self, datafolder)"
},
{
"docstring": "Load regionalizer data from data in the ... | 3 | stack_v2_sparse_classes_30k_train_014973 | Implement the Python class `Regionalizer` described below.
Class description:
Implement the Regionalizer class.
Method signatures and docstrings:
- def __init__(self, datafolder): Determine tectonic region information given epicenter and depth. Args: datafolder (str): Path to directory containing spatial data for tec... | Implement the Python class `Regionalizer` described below.
Class description:
Implement the Regionalizer class.
Method signatures and docstrings:
- def __init__(self, datafolder): Determine tectonic region information given epicenter and depth. Args: datafolder (str): Path to directory containing spatial data for tec... | 6e13af7f76d52adfeefbd74dbe647705e92db7d0 | <|skeleton|>
class Regionalizer:
def __init__(self, datafolder):
"""Determine tectonic region information given epicenter and depth. Args: datafolder (str): Path to directory containing spatial data for tectonic regions."""
<|body_0|>
def load(cls):
"""Load regionalizer data from data ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Regionalizer:
def __init__(self, datafolder):
"""Determine tectonic region information given epicenter and depth. Args: datafolder (str): Path to directory containing spatial data for tectonic regions."""
self._datafolder = datafolder
self._tectonic_grid = os.path.join(datafolder, 'tec... | the_stack_v2_python_sparse | strec/gmreg.py | emthompson-usgs/strec | train | 0 | |
9911f23ea74923f761e418b77068e790ab2767ba | [
"if not root:\n return ''\nline, ret = ([root], [str(root.val)])\nwhile line:\n next_line = []\n for node in line:\n if not node.left:\n ret.append('')\n else:\n next_line.append(node.left)\n ret.append(str(node.left.val))\n if not node.right:\n ... | <|body_start_0|>
if not root:
return ''
line, ret = ([root], [str(root.val)])
while line:
next_line = []
for node in line:
if not node.left:
ret.append('')
else:
next_line.append(node.left... | 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_029353 | 3,283 | 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_009293 | 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:... | fe9fb43fca35ba493c2c57baa66f126571450ef9 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
line, ret = ([root], [str(root.val)])
while line:
next_line = []
for node in line:
if not node.... | the_stack_v2_python_sparse | Week_02/id_26/LeetCode_297_26.py | xiaoluome/algorithm | train | 1 | |
d432e984af7eb38249f0dff6e64a80b5abd8e86a | [
"import bisect\nif len(nums) == 0:\n return []\nres = []\ns = nums[:k]\ns.sort()\nfor i in range(k, len(nums)):\n res.append(s[-1])\n s.remove(nums[i - k])\n bisect.insort(s, nums[i])\nres.append(s[-1])\nreturn res",
"from collections import deque\ns = deque()\nl = len(nums)\nif l == 0:\n return []... | <|body_start_0|>
import bisect
if len(nums) == 0:
return []
res = []
s = nums[:k]
s.sort()
for i in range(k, len(nums)):
res.append(s[-1])
s.remove(nums[i - k])
bisect.insort(s, nums[i])
res.append(s[-1])
ret... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSlidingWindow(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_0|>
def maxSlidingWindow(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_029354 | 2,118 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: List[int]",
"name": "maxSlidingWindow",
"signature": "def maxSlidingWindow(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: List[int]",
"name": "maxSlidingWindow",
"signature": "def maxSlidingWindow(s... | 2 | stack_v2_sparse_classes_30k_train_012608 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSlidingWindow(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
- def maxSlidingWindow(self, nums, k): :type nums: List[int] :type k: int :rtype: List[i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSlidingWindow(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
- def maxSlidingWindow(self, nums, k): :type nums: List[int] :type k: int :rtype: List[i... | a56efa191b075f25793aafbf7e6d100a06011cb7 | <|skeleton|>
class Solution:
def maxSlidingWindow(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_0|>
def maxSlidingWindow(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxSlidingWindow(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
import bisect
if len(nums) == 0:
return []
res = []
s = nums[:k]
s.sort()
for i in range(k, len(nums)):
res.append(s[-1])
... | the_stack_v2_python_sparse | 000SlidingWindowMaximum.py | JustinNew/LeetCode2 | train | 0 | |
e3f1e91a022165a526299378047d7249c65a6eaa | [
"username = request.GET.get('username', None)\nif username is not None:\n student = get_object_or_404(Student, user__username=username)\n serializer = StudentSerializer(student)\n return JsonResponse({'students': [serializer.data]}, safe=False)\nsquad_id = request.GET.get('squad_id', None)\nif squad_id is ... | <|body_start_0|>
username = request.GET.get('username', None)
if username is not None:
student = get_object_or_404(Student, user__username=username)
serializer = StudentSerializer(student)
return JsonResponse({'students': [serializer.data]}, safe=False)
squad_... | 学生view | Students | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Students:
"""学生view"""
def get(self, request):
"""查询学生"""
<|body_0|>
def put(self, request):
"""修改学生"""
<|body_1|>
def post(self, request):
"""增加学生"""
<|body_2|>
def delete(self, request):
"""删除学生"""
<|body_3|>
<... | stack_v2_sparse_classes_36k_train_029355 | 16,053 | permissive | [
{
"docstring": "查询学生",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "修改学生",
"name": "put",
"signature": "def put(self, request)"
},
{
"docstring": "增加学生",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "删除学生",
... | 4 | stack_v2_sparse_classes_30k_train_003791 | Implement the Python class `Students` described below.
Class description:
学生view
Method signatures and docstrings:
- def get(self, request): 查询学生
- def put(self, request): 修改学生
- def post(self, request): 增加学生
- def delete(self, request): 删除学生 | Implement the Python class `Students` described below.
Class description:
学生view
Method signatures and docstrings:
- def get(self, request): 查询学生
- def put(self, request): 修改学生
- def post(self, request): 增加学生
- def delete(self, request): 删除学生
<|skeleton|>
class Students:
"""学生view"""
def get(self, request):... | 7aaa1be773718de1beb3ce0080edca7c4114b7ad | <|skeleton|>
class Students:
"""学生view"""
def get(self, request):
"""查询学生"""
<|body_0|>
def put(self, request):
"""修改学生"""
<|body_1|>
def post(self, request):
"""增加学生"""
<|body_2|>
def delete(self, request):
"""删除学生"""
<|body_3|>
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Students:
"""学生view"""
def get(self, request):
"""查询学生"""
username = request.GET.get('username', None)
if username is not None:
student = get_object_or_404(Student, user__username=username)
serializer = StudentSerializer(student)
return JsonResp... | the_stack_v2_python_sparse | user/views.py | MIXISAMA/MIS-backend | train | 0 |
b658115773c033c3dffda07704a8cca6417cdce3 | [
"self.rule_blacklist = rule_blacklist\nself.rule_index = rule_index\nself.rules = rules",
"ipaddrb = struct.unpack('!I', socket.inet_aton(ipaddr))[0]\nnetstr, bits = net.split('/')\nnetaddr = struct.unpack('!I', socket.inet_aton(netstr))[0]\nmask = 4294967295 << 32 - int(bits) & 4294967295\nreturn ipaddrb & mask ... | <|body_start_0|>
self.rule_blacklist = rule_blacklist
self.rule_index = rule_index
self.rules = rules
<|end_body_0|>
<|body_start_1|>
ipaddrb = struct.unpack('!I', socket.inet_aton(ipaddr))[0]
netstr, bits = net.split('/')
netaddr = struct.unpack('!I', socket.inet_aton(n... | The rules class for instance_network_interface. | Rule | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rule:
"""The rules class for instance_network_interface."""
def __init__(self, rule_blacklist, rule_index, rules):
"""Initialize. Args: rule_blacklist (str): Name of the loaded blacklist rule_index (int): The index of the rule from the definitions rules (dict): The resources associat... | stack_v2_sparse_classes_36k_train_029356 | 9,509 | permissive | [
{
"docstring": "Initialize. Args: rule_blacklist (str): Name of the loaded blacklist rule_index (int): The index of the rule from the definitions rules (dict): The resources associated with the rules like the whitelist",
"name": "__init__",
"signature": "def __init__(self, rule_blacklist, rule_index, ru... | 4 | stack_v2_sparse_classes_30k_train_016177 | Implement the Python class `Rule` described below.
Class description:
The rules class for instance_network_interface.
Method signatures and docstrings:
- def __init__(self, rule_blacklist, rule_index, rules): Initialize. Args: rule_blacklist (str): Name of the loaded blacklist rule_index (int): The index of the rule ... | Implement the Python class `Rule` described below.
Class description:
The rules class for instance_network_interface.
Method signatures and docstrings:
- def __init__(self, rule_blacklist, rule_index, rules): Initialize. Args: rule_blacklist (str): Name of the loaded blacklist rule_index (int): The index of the rule ... | d4421afa50a17ed47cbebe942044ebab3720e0f5 | <|skeleton|>
class Rule:
"""The rules class for instance_network_interface."""
def __init__(self, rule_blacklist, rule_index, rules):
"""Initialize. Args: rule_blacklist (str): Name of the loaded blacklist rule_index (int): The index of the rule from the definitions rules (dict): The resources associat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Rule:
"""The rules class for instance_network_interface."""
def __init__(self, rule_blacklist, rule_index, rules):
"""Initialize. Args: rule_blacklist (str): Name of the loaded blacklist rule_index (int): The index of the rule from the definitions rules (dict): The resources associated with the r... | the_stack_v2_python_sparse | google/cloud/forseti/scanner/audit/blacklist_rules_engine.py | kevensen/forseti-security | train | 1 |
83d8934243fca224c7e1a80afeeea578b846d601 | [
"self.random_init = cgmm is None\nself.obs = np.einsum('mft->fmt', obs)\nF, M, T = self.obs.shape\nlogger.info(f'CGMM instance: F = {F:d}, T = {T:}, M = {M}')\nif self.random_init:\n cg = CgDistribution()\n if gamma is None:\n Rs = np.einsum('...dt,...et->...de', self.obs, self.obs.conj()) / T\n ... | <|body_start_0|>
self.random_init = cgmm is None
self.obs = np.einsum('mft->fmt', obs)
F, M, T = self.obs.shape
logger.info(f'CGMM instance: F = {F:d}, T = {T:}, M = {M}')
if self.random_init:
cg = CgDistribution()
if gamma is None:
Rs = np... | Cgmm Trainer | CgmmTrainer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CgmmTrainer:
"""Cgmm Trainer"""
def __init__(self, obs, gamma=None, cgmm=None):
"""Arguments: obs: mixture observation, M x F x T gamma: initial gamma, K x F x T"""
<|body_0|>
def train(self, num_epoches=20):
"""Train in EM progress"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k_train_029357 | 16,663 | permissive | [
{
"docstring": "Arguments: obs: mixture observation, M x F x T gamma: initial gamma, K x F x T",
"name": "__init__",
"signature": "def __init__(self, obs, gamma=None, cgmm=None)"
},
{
"docstring": "Train in EM progress",
"name": "train",
"signature": "def train(self, num_epoches=20)"
}... | 2 | stack_v2_sparse_classes_30k_train_010751 | Implement the Python class `CgmmTrainer` described below.
Class description:
Cgmm Trainer
Method signatures and docstrings:
- def __init__(self, obs, gamma=None, cgmm=None): Arguments: obs: mixture observation, M x F x T gamma: initial gamma, K x F x T
- def train(self, num_epoches=20): Train in EM progress | Implement the Python class `CgmmTrainer` described below.
Class description:
Cgmm Trainer
Method signatures and docstrings:
- def __init__(self, obs, gamma=None, cgmm=None): Arguments: obs: mixture observation, M x F x T gamma: initial gamma, K x F x T
- def train(self, num_epoches=20): Train in EM progress
<|skelet... | e9fd899c50e266e7101c41da646982c4d0777dce | <|skeleton|>
class CgmmTrainer:
"""Cgmm Trainer"""
def __init__(self, obs, gamma=None, cgmm=None):
"""Arguments: obs: mixture observation, M x F x T gamma: initial gamma, K x F x T"""
<|body_0|>
def train(self, num_epoches=20):
"""Train in EM progress"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CgmmTrainer:
"""Cgmm Trainer"""
def __init__(self, obs, gamma=None, cgmm=None):
"""Arguments: obs: mixture observation, M x F x T gamma: initial gamma, K x F x T"""
self.random_init = cgmm is None
self.obs = np.einsum('mft->fmt', obs)
F, M, T = self.obs.shape
logge... | the_stack_v2_python_sparse | scripts/sptk/libs/cluster.py | JusperLee/setk | train | 1 |
82581e39e73ac21deb62ebef0b3f6e474e1c2833 | [
"kwargs = linkUningested.parse_args(['-m', 'foo.sqlite'])\nself.assertEqual('foo.sqlite', kwargs['mission'])\nself.assertEqual(None, kwargs['products'])\nkwargs = linkUningested.parse_args(['-m', 'foo.sqlite', '-p', '1', '-p', 'level1'])\nself.assertEqual('foo.sqlite', kwargs['mission'])\nself.assertEqual(['1', 'le... | <|body_start_0|>
kwargs = linkUningested.parse_args(['-m', 'foo.sqlite'])
self.assertEqual('foo.sqlite', kwargs['mission'])
self.assertEqual(None, kwargs['products'])
kwargs = linkUningested.parse_args(['-m', 'foo.sqlite', '-p', '1', '-p', 'level1'])
self.assertEqual('foo.sqlite'... | linkUningested tests | LinkUningestedTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinkUningestedTests:
"""linkUningested tests"""
def test_parse_linkuningested_args(self):
"""Parse the command line arguments"""
<|body_0|>
def test_list_files(self):
"""List files for product"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
kwar... | stack_v2_sparse_classes_36k_train_029358 | 3,488 | no_license | [
{
"docstring": "Parse the command line arguments",
"name": "test_parse_linkuningested_args",
"signature": "def test_parse_linkuningested_args(self)"
},
{
"docstring": "List files for product",
"name": "test_list_files",
"signature": "def test_list_files(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002695 | Implement the Python class `LinkUningestedTests` described below.
Class description:
linkUningested tests
Method signatures and docstrings:
- def test_parse_linkuningested_args(self): Parse the command line arguments
- def test_list_files(self): List files for product | Implement the Python class `LinkUningestedTests` described below.
Class description:
linkUningested tests
Method signatures and docstrings:
- def test_parse_linkuningested_args(self): Parse the command line arguments
- def test_list_files(self): List files for product
<|skeleton|>
class LinkUningestedTests:
"""l... | a0bf5e682fb917bb707b4f66787b0ecb860efce1 | <|skeleton|>
class LinkUningestedTests:
"""linkUningested tests"""
def test_parse_linkuningested_args(self):
"""Parse the command line arguments"""
<|body_0|>
def test_list_files(self):
"""List files for product"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinkUningestedTests:
"""linkUningested tests"""
def test_parse_linkuningested_args(self):
"""Parse the command line arguments"""
kwargs = linkUningested.parse_args(['-m', 'foo.sqlite'])
self.assertEqual('foo.sqlite', kwargs['mission'])
self.assertEqual(None, kwargs['produc... | the_stack_v2_python_sparse | unit_tests/test_linkUningested.py | spacepy/dbprocessing | train | 4 |
7f014722a979fc59a01016b085b9ed3765c49804 | [
"super(NoopResetEnv, self).__init__(env)\nself.noop_max = noop_max\nassert env.unwrapped.get_action_meanings()[0] == 'NOOP'",
"self.env.reset()\nnoops = np.random.randint(1, self.noop_max + 1)\nfor _ in range(noops):\n obs, _, _, _ = self.env.step(0)\nreturn obs"
] | <|body_start_0|>
super(NoopResetEnv, self).__init__(env)
self.noop_max = noop_max
assert env.unwrapped.get_action_meanings()[0] == 'NOOP'
<|end_body_0|>
<|body_start_1|>
self.env.reset()
noops = np.random.randint(1, self.noop_max + 1)
for _ in range(noops):
o... | NoopResetEnv | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoopResetEnv:
def __init__(self, env=None, noop_max=30):
"""Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0."""
<|body_0|>
def _reset(self):
"""Do no-op action for a number of steps in [1, noop_max]."""
<|body... | stack_v2_sparse_classes_36k_train_029359 | 7,958 | no_license | [
{
"docstring": "Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0.",
"name": "__init__",
"signature": "def __init__(self, env=None, noop_max=30)"
},
{
"docstring": "Do no-op action for a number of steps in [1, noop_max].",
"name": "_reset",
... | 2 | stack_v2_sparse_classes_30k_train_001330 | Implement the Python class `NoopResetEnv` described below.
Class description:
Implement the NoopResetEnv class.
Method signatures and docstrings:
- def __init__(self, env=None, noop_max=30): Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0.
- def _reset(self): Do no-op... | Implement the Python class `NoopResetEnv` described below.
Class description:
Implement the NoopResetEnv class.
Method signatures and docstrings:
- def __init__(self, env=None, noop_max=30): Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0.
- def _reset(self): Do no-op... | 44fa78bf9c0e03be39d431d2b6d01f11198ab610 | <|skeleton|>
class NoopResetEnv:
def __init__(self, env=None, noop_max=30):
"""Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0."""
<|body_0|>
def _reset(self):
"""Do no-op action for a number of steps in [1, noop_max]."""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NoopResetEnv:
def __init__(self, env=None, noop_max=30):
"""Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0."""
super(NoopResetEnv, self).__init__(env)
self.noop_max = noop_max
assert env.unwrapped.get_action_meanings()[0] == 'N... | the_stack_v2_python_sparse | utils/DQNCore.py | pierresdr/belief_rpz_dmdp_ijcnn_2021 | train | 2 | |
9d8d308307823a5e580f7dccb5e5167e55fdf3d5 | [
"super(BusyOverlay, self).__init__(parent, message=message)\nself.indicator = ftrack_connect.ui.widget.indicator.BusyIndicator()\nself.indicator.setFixedSize(85, 85)\nself.icon.hide()\nself.contentLayout.insertWidget(1, self.indicator, alignment=QtCore.Qt.AlignCenter)",
"if visible:\n self.indicator.start()\ne... | <|body_start_0|>
super(BusyOverlay, self).__init__(parent, message=message)
self.indicator = ftrack_connect.ui.widget.indicator.BusyIndicator()
self.indicator.setFixedSize(85, 85)
self.icon.hide()
self.contentLayout.insertWidget(1, self.indicator, alignment=QtCore.Qt.AlignCenter)... | Display a standard busy overlay over another widget. | BusyOverlay | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BusyOverlay:
"""Display a standard busy overlay over another widget."""
def __init__(self, parent, message='Processing'):
"""Initialise with *parent* and busy *message*."""
<|body_0|>
def setVisible(self, visible):
"""Set whether *visible* or not."""
<|bo... | stack_v2_sparse_classes_36k_train_029360 | 8,378 | permissive | [
{
"docstring": "Initialise with *parent* and busy *message*.",
"name": "__init__",
"signature": "def __init__(self, parent, message='Processing')"
},
{
"docstring": "Set whether *visible* or not.",
"name": "setVisible",
"signature": "def setVisible(self, visible)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000768 | Implement the Python class `BusyOverlay` described below.
Class description:
Display a standard busy overlay over another widget.
Method signatures and docstrings:
- def __init__(self, parent, message='Processing'): Initialise with *parent* and busy *message*.
- def setVisible(self, visible): Set whether *visible* or... | Implement the Python class `BusyOverlay` described below.
Class description:
Display a standard busy overlay over another widget.
Method signatures and docstrings:
- def __init__(self, parent, message='Processing'): Initialise with *parent* and busy *message*.
- def setVisible(self, visible): Set whether *visible* or... | f55f52787484fcf931c4653e7e241791f052c04f | <|skeleton|>
class BusyOverlay:
"""Display a standard busy overlay over another widget."""
def __init__(self, parent, message='Processing'):
"""Initialise with *parent* and busy *message*."""
<|body_0|>
def setVisible(self, visible):
"""Set whether *visible* or not."""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BusyOverlay:
"""Display a standard busy overlay over another widget."""
def __init__(self, parent, message='Processing'):
"""Initialise with *parent* and busy *message*."""
super(BusyOverlay, self).__init__(parent, message=message)
self.indicator = ftrack_connect.ui.widget.indicat... | the_stack_v2_python_sparse | source/ftrack_connect/ui/widget/overlay.py | IngenuityEngine/ftrack-connect | train | 0 |
2d43ee9133a47b53caef7d151d3fb3622d3d8ba1 | [
"self.test_data_true = dictionary_class_helper_true()\nself.test_data_false = dictionary_class_helper_false()\nself.sock_conn = socketconnection.SocketConnection(self.test_data_true.car_id)\nself.valid_dict = self.test_data_true.get_socket_dictionary()\nself.invalid_dict = self.test_data_false.get_socket_dictionary... | <|body_start_0|>
self.test_data_true = dictionary_class_helper_true()
self.test_data_false = dictionary_class_helper_false()
self.sock_conn = socketconnection.SocketConnection(self.test_data_true.car_id)
self.valid_dict = self.test_data_true.get_socket_dictionary()
self.invalid_d... | As in :class:`TestSocketConnection` by implication, but this tests the conditional return of the socketindependent of validation on the AgentPi. The purpose is to edge cases where a single value in the dictionary should determine the result of processing the entire dictionary. Essentially this ensures that only fully v... | TestSocketResponseAction1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSocketResponseAction1:
"""As in :class:`TestSocketConnection` by implication, but this tests the conditional return of the socketindependent of validation on the AgentPi. The purpose is to edge cases where a single value in the dictionary should determine the result of processing the entire d... | stack_v2_sparse_classes_36k_train_029361 | 23,291 | no_license | [
{
"docstring": "It is necessary to instantiate the data classes and extract the relevant dictionaries. It additionally requires a socket connection.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test an incorrect car_id",
"name": "test_a1_invalid_car_id",
"signatur... | 6 | null | Implement the Python class `TestSocketResponseAction1` described below.
Class description:
As in :class:`TestSocketConnection` by implication, but this tests the conditional return of the socketindependent of validation on the AgentPi. The purpose is to edge cases where a single value in the dictionary should determin... | Implement the Python class `TestSocketResponseAction1` described below.
Class description:
As in :class:`TestSocketConnection` by implication, but this tests the conditional return of the socketindependent of validation on the AgentPi. The purpose is to edge cases where a single value in the dictionary should determin... | 8f68cc2a6ca568e803a6bfea49a452a5b0c1a2cf | <|skeleton|>
class TestSocketResponseAction1:
"""As in :class:`TestSocketConnection` by implication, but this tests the conditional return of the socketindependent of validation on the AgentPi. The purpose is to edge cases where a single value in the dictionary should determine the result of processing the entire d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestSocketResponseAction1:
"""As in :class:`TestSocketConnection` by implication, but this tests the conditional return of the socketindependent of validation on the AgentPi. The purpose is to edge cases where a single value in the dictionary should determine the result of processing the entire dictionary. Es... | the_stack_v2_python_sparse | AgentPi/agenttesting.py | JiewenGuan/Iot-Carshare | train | 0 |
9b5e048ca5b6b057a27d78662ead67cea2ef6b21 | [
"super(RoIAlign, self).__init__()\nself.output_size = output_size\nself.scales = scales\nself.sampling_ratio = sampling_ratio\nself.canonical_box_size = canonical_box_size\nself.canonical_level = canonical_level\nself.min_level = min_level\nself.max_level = max_level\nself.aligned = aligned",
"if isinstance(rois_... | <|body_start_0|>
super(RoIAlign, self).__init__()
self.output_size = output_size
self.scales = scales
self.sampling_ratio = sampling_ratio
self.canonical_box_size = canonical_box_size
self.canonical_level = canonical_level
self.min_level = min_level
self.m... | Region of interest feature map pooler that supports pooling from one or more feature maps. | RoIAlign | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoIAlign:
"""Region of interest feature map pooler that supports pooling from one or more feature maps."""
def __init__(self, output_size, scales, sampling_ratio, canonical_box_size=224, canonical_level=4, min_level=0, max_level=3, aligned=True):
"""Attributes: output_size (int): out... | stack_v2_sparse_classes_36k_train_029362 | 22,497 | permissive | [
{
"docstring": "Attributes: output_size (int): output size of the pooled region. scales (list[float]): The scale for each low-level pooling op relative to the input image. For a feature map with stride s relative to the input image, scale is defined as 1/s. The stride must be power of 2. When there are multiple... | 2 | stack_v2_sparse_classes_30k_train_009446 | Implement the Python class `RoIAlign` described below.
Class description:
Region of interest feature map pooler that supports pooling from one or more feature maps.
Method signatures and docstrings:
- def __init__(self, output_size, scales, sampling_ratio, canonical_box_size=224, canonical_level=4, min_level=0, max_l... | Implement the Python class `RoIAlign` described below.
Class description:
Region of interest feature map pooler that supports pooling from one or more feature maps.
Method signatures and docstrings:
- def __init__(self, output_size, scales, sampling_ratio, canonical_box_size=224, canonical_level=4, min_level=0, max_l... | c90a6c8dc3787e69cef3a37b9a260bd59eeff1f7 | <|skeleton|>
class RoIAlign:
"""Region of interest feature map pooler that supports pooling from one or more feature maps."""
def __init__(self, output_size, scales, sampling_ratio, canonical_box_size=224, canonical_level=4, min_level=0, max_level=3, aligned=True):
"""Attributes: output_size (int): out... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RoIAlign:
"""Region of interest feature map pooler that supports pooling from one or more feature maps."""
def __init__(self, output_size, scales, sampling_ratio, canonical_box_size=224, canonical_level=4, min_level=0, max_level=3, aligned=True):
"""Attributes: output_size (int): output size of t... | the_stack_v2_python_sparse | object_detection/PVTv2/det_heads/det_utils/generator_utils.py | Dongsheng-Bi/PaddleViT | train | 1 |
3bde48f2282abf85264468994a7acc12a3b8a8cc | [
"try:\n uid = request['session']['uid']\nexcept KeyError:\n return json({'message': 'wrong session,log in again!'}, 401)\nexcept Exception as e:\n traceback.print_exc(file=sys.stdout)\n return json({'message': str(e)}, 500)\nelse:\n user = await User.get(User.uid == uid)\n print(user.info)\n re... | <|body_start_0|>
try:
uid = request['session']['uid']
except KeyError:
return json({'message': 'wrong session,log in again!'}, 401)
except Exception as e:
traceback.print_exc(file=sys.stdout)
return json({'message': str(e)}, 500)
else:
... | UserProfileView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserProfileView:
async def get(self, request):
"""获取用户的信息. 需要已经有session Raises: message (401): - session错误 message (500): - 未知错误 Returns: message (str): - 用户信息"""
<|body_0|>
async def post(self, request):
"""修改用户的信息. 需要session. Args: URL (str): - 个人主页地址 bio (str): - ... | stack_v2_sparse_classes_36k_train_029363 | 2,351 | no_license | [
{
"docstring": "获取用户的信息. 需要已经有session Raises: message (401): - session错误 message (500): - 未知错误 Returns: message (str): - 用户信息",
"name": "get",
"signature": "async def get(self, request)"
},
{
"docstring": "修改用户的信息. 需要session. Args: URL (str): - 个人主页地址 bio (str): - 个人简介 company (str): - 公司信息 nati... | 2 | stack_v2_sparse_classes_30k_test_000198 | Implement the Python class `UserProfileView` described below.
Class description:
Implement the UserProfileView class.
Method signatures and docstrings:
- async def get(self, request): 获取用户的信息. 需要已经有session Raises: message (401): - session错误 message (500): - 未知错误 Returns: message (str): - 用户信息
- async def post(self, r... | Implement the Python class `UserProfileView` described below.
Class description:
Implement the UserProfileView class.
Method signatures and docstrings:
- async def get(self, request): 获取用户的信息. 需要已经有session Raises: message (401): - session错误 message (500): - 未知错误 Returns: message (str): - 用户信息
- async def post(self, r... | 9d7609e9c2c57f2e849cec70ba306be9be43764e | <|skeleton|>
class UserProfileView:
async def get(self, request):
"""获取用户的信息. 需要已经有session Raises: message (401): - session错误 message (500): - 未知错误 Returns: message (str): - 用户信息"""
<|body_0|>
async def post(self, request):
"""修改用户的信息. 需要session. Args: URL (str): - 个人主页地址 bio (str): - ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserProfileView:
async def get(self, request):
"""获取用户的信息. 需要已经有session Raises: message (401): - session错误 message (500): - 未知错误 Returns: message (str): - 用户信息"""
try:
uid = request['session']['uid']
except KeyError:
return json({'message': 'wrong session,log in... | the_stack_v2_python_sparse | security_center/api/user_source/profile_source.py | Basic-Components/security-center | train | 0 | |
075393f37ebab7107a89794f5ba9785e799f39bb | [
"self.screen_width = 1200\nself.screen_height = 800\nself.bg_color = (230, 230, 230)\nself.ship_limit = 3\nself.bullet_width = 5\nself.bullet_height = 20\nself.bullet_color = (60, 60, 60)\nself.bullets_allowed = 5\nself.fleet_drop_speed = 20\nself.kill_score_speed = 2.2\nself.speedup_scale = 1.1\nself.score_scale =... | <|body_start_0|>
self.screen_width = 1200
self.screen_height = 800
self.bg_color = (230, 230, 230)
self.ship_limit = 3
self.bullet_width = 5
self.bullet_height = 20
self.bullet_color = (60, 60, 60)
self.bullets_allowed = 5
self.fleet_drop_speed = 2... | 存储《外星人入侵》的所有设置 | Settings | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Settings:
"""存储《外星人入侵》的所有设置"""
def __init__(self):
"""初始化游戏的设置"""
<|body_0|>
def initialize_dynamic_settings(self):
"""初始化随游戏进行而变化的设置"""
<|body_1|>
def increase_speed(self):
"""提高速度"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_029364 | 1,661 | no_license | [
{
"docstring": "初始化游戏的设置",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "初始化随游戏进行而变化的设置",
"name": "initialize_dynamic_settings",
"signature": "def initialize_dynamic_settings(self)"
},
{
"docstring": "提高速度",
"name": "increase_speed",
"signature"... | 3 | stack_v2_sparse_classes_30k_train_011837 | Implement the Python class `Settings` described below.
Class description:
存储《外星人入侵》的所有设置
Method signatures and docstrings:
- def __init__(self): 初始化游戏的设置
- def initialize_dynamic_settings(self): 初始化随游戏进行而变化的设置
- def increase_speed(self): 提高速度 | Implement the Python class `Settings` described below.
Class description:
存储《外星人入侵》的所有设置
Method signatures and docstrings:
- def __init__(self): 初始化游戏的设置
- def initialize_dynamic_settings(self): 初始化随游戏进行而变化的设置
- def increase_speed(self): 提高速度
<|skeleton|>
class Settings:
"""存储《外星人入侵》的所有设置"""
def __init__(se... | 981f06b8ed6cc7b43517bee7dc7a5f3226df378d | <|skeleton|>
class Settings:
"""存储《外星人入侵》的所有设置"""
def __init__(self):
"""初始化游戏的设置"""
<|body_0|>
def initialize_dynamic_settings(self):
"""初始化随游戏进行而变化的设置"""
<|body_1|>
def increase_speed(self):
"""提高速度"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Settings:
"""存储《外星人入侵》的所有设置"""
def __init__(self):
"""初始化游戏的设置"""
self.screen_width = 1200
self.screen_height = 800
self.bg_color = (230, 230, 230)
self.ship_limit = 3
self.bullet_width = 5
self.bullet_height = 20
self.bullet_color = (60, 60... | the_stack_v2_python_sparse | alien/settings.py | chrgu000/python-code | train | 0 |
4fc2b22093f1e646718f543f81c39ea07f5ec7ee | [
"self.snake = [[0, 0]]\nself.width = width\nself.height = height\nself.food = food\nself.idx = 0\nself.directions = {'U': [-1, 0], 'L': [0, -1], 'R': [0, 1], 'D': [1, 0]}\nself.score = 0",
"snake = self.snake\npre_x, pre_y = snake[0]\ncur_x = pre_x + self.directions[direction][0]\ncur_y = pre_y + self.directions[... | <|body_start_0|>
self.snake = [[0, 0]]
self.width = width
self.height = height
self.food = food
self.idx = 0
self.directions = {'U': [-1, 0], 'L': [0, -1], 'R': [0, 1], 'D': [1, 0]}
self.score = 0
<|end_body_0|>
<|body_start_1|>
snake = self.snake
... | SnakeGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :typ... | stack_v2_sparse_classes_36k_train_029365 | 4,039 | no_license | [
{
"docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int :type height: int :type food: List[List[int]]",
... | 2 | null | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E... | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E... | e12025e754547d18d5bb50a9dbe5e725fd03fd9c | <|skeleton|>
class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :typ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int :... | the_stack_v2_python_sparse | leetcode/353design_snake_game.py | clovery410/mycode | train | 1 | |
bc937a5af4af0eac11241ae0d0e44631651084a0 | [
"super(ConvEncoder, self).__init__()\nself.obs_dim = obs_dim\nself.act = nn.ReLU()\nlayers = []\nhidden_dim_list = [32, 64, 64]\nkernel_size = [8, 4, 3]\nstride = [4, 2, 1]\ninput_dim = obs_dim[0]\nfor i in range(len(hidden_dim_list)):\n layers.append(nn.Conv2d(input_dim, hidden_dim_list[i], kernel_size[i], stri... | <|body_start_0|>
super(ConvEncoder, self).__init__()
self.obs_dim = obs_dim
self.act = nn.ReLU()
layers = []
hidden_dim_list = [32, 64, 64]
kernel_size = [8, 4, 3]
stride = [4, 2, 1]
input_dim = obs_dim[0]
for i in range(len(hidden_dim_list)):
... | Overview: The Convolution Encoder used in models. Used to encoder raw 2-dim observation. Interfaces: __init__, forward | ConvEncoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvEncoder:
"""Overview: The Convolution Encoder used in models. Used to encoder raw 2-dim observation. Interfaces: __init__, forward"""
def __init__(self, obs_dim: tuple, embedding_dim: int) -> None:
"""Overview: Init the DuelingHead according to arguments. Arguments: - obs_dim (:o... | stack_v2_sparse_classes_36k_train_029366 | 2,393 | permissive | [
{
"docstring": "Overview: Init the DuelingHead according to arguments. Arguments: - obs_dim (:obj:`tuple`): a tuple of observation dim - embedding_dim (:obj:`int`): output dim of this encoder",
"name": "__init__",
"signature": "def __init__(self, obs_dim: tuple, embedding_dim: int) -> None"
},
{
... | 3 | null | Implement the Python class `ConvEncoder` described below.
Class description:
Overview: The Convolution Encoder used in models. Used to encoder raw 2-dim observation. Interfaces: __init__, forward
Method signatures and docstrings:
- def __init__(self, obs_dim: tuple, embedding_dim: int) -> None: Overview: Init the Due... | Implement the Python class `ConvEncoder` described below.
Class description:
Overview: The Convolution Encoder used in models. Used to encoder raw 2-dim observation. Interfaces: __init__, forward
Method signatures and docstrings:
- def __init__(self, obs_dim: tuple, embedding_dim: int) -> None: Overview: Init the Due... | 09d507c412235a2f0cf9c0b3485ec9ed15fb6421 | <|skeleton|>
class ConvEncoder:
"""Overview: The Convolution Encoder used in models. Used to encoder raw 2-dim observation. Interfaces: __init__, forward"""
def __init__(self, obs_dim: tuple, embedding_dim: int) -> None:
"""Overview: Init the DuelingHead according to arguments. Arguments: - obs_dim (:o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConvEncoder:
"""Overview: The Convolution Encoder used in models. Used to encoder raw 2-dim observation. Interfaces: __init__, forward"""
def __init__(self, obs_dim: tuple, embedding_dim: int) -> None:
"""Overview: Init the DuelingHead according to arguments. Arguments: - obs_dim (:obj:`tuple`): ... | the_stack_v2_python_sparse | ctools/model/common_arch/encoder.py | LFhase/DI-star | train | 1 |
019f822d273b12667fb877b26cb9e17c9a34a973 | [
"self.acl = acl\nself.username = username\nself.method = method",
"proto = getattr(BUIacl, self.method)\nargs_name = list(proto.__code__.co_varnames)\nargs_name.pop(0)\nargs_name.pop(0)\nencoded_args = {'username': self.username}\nfor idx, opt in enumerate(args):\n encoded_args[args_name[idx]] = opt\nencoded_a... | <|body_start_0|>
self.acl = acl
self.username = username
self.method = method
<|end_body_0|>
<|body_start_1|>
proto = getattr(BUIacl, self.method)
args_name = list(proto.__code__.co_varnames)
args_name.pop(0)
args_name.pop(0)
encoded_args = {'username': s... | Class that actually calls the ACL method | ProxyACLCall | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProxyACLCall:
"""Class that actually calls the ACL method"""
def __init__(self, acl, username, method):
""":param acl: ACL to use :type acl: :class:`burpui.misc.acl.interface.BUIacl` :param username: username to check ACL for :type username: str :param method: Name of the method to p... | stack_v2_sparse_classes_36k_train_029367 | 10,821 | permissive | [
{
"docstring": ":param acl: ACL to use :type acl: :class:`burpui.misc.acl.interface.BUIacl` :param username: username to check ACL for :type username: str :param method: Name of the method to proxify :type method: str",
"name": "__init__",
"signature": "def __init__(self, acl, username, method)"
},
... | 2 | null | Implement the Python class `ProxyACLCall` described below.
Class description:
Class that actually calls the ACL method
Method signatures and docstrings:
- def __init__(self, acl, username, method): :param acl: ACL to use :type acl: :class:`burpui.misc.acl.interface.BUIacl` :param username: username to check ACL for :... | Implement the Python class `ProxyACLCall` described below.
Class description:
Class that actually calls the ACL method
Method signatures and docstrings:
- def __init__(self, acl, username, method): :param acl: ACL to use :type acl: :class:`burpui.misc.acl.interface.BUIacl` :param username: username to check ACL for :... | 2b8c6e09a4174f2ae3545fa048f59c55c4ae7dba | <|skeleton|>
class ProxyACLCall:
"""Class that actually calls the ACL method"""
def __init__(self, acl, username, method):
""":param acl: ACL to use :type acl: :class:`burpui.misc.acl.interface.BUIacl` :param username: username to check ACL for :type username: str :param method: Name of the method to p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProxyACLCall:
"""Class that actually calls the ACL method"""
def __init__(self, acl, username, method):
""":param acl: ACL to use :type acl: :class:`burpui.misc.acl.interface.BUIacl` :param username: username to check ACL for :type username: str :param method: Name of the method to proxify :type ... | the_stack_v2_python_sparse | burpui/misc/auth/handler.py | ziirish/burp-ui | train | 98 |
7431d4f84a6fcd5d7f86117c0cdf62b63f6da895 | [
"self.prefix = prefix\nself.hub = hubble\nself.size = size\nself.cosmo = FlatLambdaCDM(H0=hubble * 100.0, Om0=0.267, Ob0=0.0449, name='myCosmo')\nself.cm_vol = (self.size / self.hub) ** 3\nif verbose:\n print('Object h={:.2f} with path prefix {}'.format(self.hub, self.prefix))\nself.verbose = verbose\nreturn",
... | <|body_start_0|>
self.prefix = prefix
self.hub = hubble
self.size = size
self.cosmo = FlatLambdaCDM(H0=hubble * 100.0, Om0=0.267, Ob0=0.0449, name='myCosmo')
self.cm_vol = (self.size / self.hub) ** 3
if verbose:
print('Object h={:.2f} with path prefix {}'.form... | This class reads in the data generated by the genStarData-RT python program. The constructor expects the size of the box, the input file path & nbame, as well as the hubble parameter -- which defaults to 0.71. size : float Boxsize in Mpc/h prefix : str ("./") path to the star particle data summary file hubble : float (... | nSFR | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class nSFR:
"""This class reads in the data generated by the genStarData-RT python program. The constructor expects the size of the box, the input file path & nbame, as well as the hubble parameter -- which defaults to 0.71. size : float Boxsize in Mpc/h prefix : str ("./") path to the star particle da... | stack_v2_sparse_classes_36k_train_029368 | 9,121 | no_license | [
{
"docstring": "This constructor sets up the object's cosmology as well as the root path to the file loaded with the load method.",
"name": "__init__",
"signature": "def __init__(self, size, prefix='./', hubble=0.71, verbose=False)"
},
{
"docstring": "Loads data expecting the following columns: ... | 3 | stack_v2_sparse_classes_30k_train_017030 | Implement the Python class `nSFR` described below.
Class description:
This class reads in the data generated by the genStarData-RT python program. The constructor expects the size of the box, the input file path & nbame, as well as the hubble parameter -- which defaults to 0.71. size : float Boxsize in Mpc/h prefix : ... | Implement the Python class `nSFR` described below.
Class description:
This class reads in the data generated by the genStarData-RT python program. The constructor expects the size of the box, the input file path & nbame, as well as the hubble parameter -- which defaults to 0.71. size : float Boxsize in Mpc/h prefix : ... | 9f5deb8ff24e810b7f5d7c57768e1ea0639ac990 | <|skeleton|>
class nSFR:
"""This class reads in the data generated by the genStarData-RT python program. The constructor expects the size of the box, the input file path & nbame, as well as the hubble parameter -- which defaults to 0.71. size : float Boxsize in Mpc/h prefix : str ("./") path to the star particle da... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class nSFR:
"""This class reads in the data generated by the genStarData-RT python program. The constructor expects the size of the box, the input file path & nbame, as well as the hubble parameter -- which defaults to 0.71. size : float Boxsize in Mpc/h prefix : str ("./") path to the star particle data summary fi... | the_stack_v2_python_sparse | nSFR.py | earnric/modules | train | 0 |
7f700fbb4e06c456ec8399d995d0a7541bfb938b | [
"self.x0 = np.atleast_2d(x0)\nself.f = f\nself.df = df\nself.f_df = f_df\nself.context_manager = context_manager\nif not context_manager:\n self.x0_nocontext = x0\n self.f_nocontext = self.f\n self.df_nocontext = self.df\n self.f_df_nocontext = self.f_df\nelse:\n self.x0_nocontext = self.x0[:, self.c... | <|body_start_0|>
self.x0 = np.atleast_2d(x0)
self.f = f
self.df = df
self.f_df = f_df
self.context_manager = context_manager
if not context_manager:
self.x0_nocontext = x0
self.f_nocontext = self.f
self.df_nocontext = self.df
... | OptimizationWithContext | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptimizationWithContext:
def __init__(self, x0, f, df=None, f_df=None, context_manager=None):
"""Constructor of an objective function that takes as input a vector x of the non context variables and retunrs a value in which the context variables have been fixed."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_029369 | 16,782 | permissive | [
{
"docstring": "Constructor of an objective function that takes as input a vector x of the non context variables and retunrs a value in which the context variables have been fixed.",
"name": "__init__",
"signature": "def __init__(self, x0, f, df=None, f_df=None, context_manager=None)"
},
{
"docs... | 4 | stack_v2_sparse_classes_30k_train_003614 | Implement the Python class `OptimizationWithContext` described below.
Class description:
Implement the OptimizationWithContext class.
Method signatures and docstrings:
- def __init__(self, x0, f, df=None, f_df=None, context_manager=None): Constructor of an objective function that takes as input a vector x of the non ... | Implement the Python class `OptimizationWithContext` described below.
Class description:
Implement the OptimizationWithContext class.
Method signatures and docstrings:
- def __init__(self, x0, f, df=None, f_df=None, context_manager=None): Constructor of an objective function that takes as input a vector x of the non ... | 4fb8af1d51e74e3cf3bee5dabd641857b8cf8100 | <|skeleton|>
class OptimizationWithContext:
def __init__(self, x0, f, df=None, f_df=None, context_manager=None):
"""Constructor of an objective function that takes as input a vector x of the non context variables and retunrs a value in which the context variables have been fixed."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OptimizationWithContext:
def __init__(self, x0, f, df=None, f_df=None, context_manager=None):
"""Constructor of an objective function that takes as input a vector x of the non context variables and retunrs a value in which the context variables have been fixed."""
self.x0 = np.atleast_2d(x0)
... | the_stack_v2_python_sparse | bopl/aux_software/GPyOpt/optimization/optimizer.py | RaulAstudillo06/BOPL | train | 3 | |
eb441bded980d8d5b60ad1eb9aae1c1da830aa92 | [
"self.adder = Adder()\nself.subtracter = Subtracter()\nself.multiplier = Multiplier()\nself.divider = Divider()\nself.calculator = Calculator(self.adder, self.subtracter, self.multiplier, self.divider)",
"self.calculator.enter_number(0)\nwith self.assertRaises(InsufficientOperands):\n self.calculator.add()",
... | <|body_start_0|>
self.adder = Adder()
self.subtracter = Subtracter()
self.multiplier = Multiplier()
self.divider = Divider()
self.calculator = Calculator(self.adder, self.subtracter, self.multiplier, self.divider)
<|end_body_0|>
<|body_start_1|>
self.calculator.enter_num... | Contain tests for Calculator class. | CalculatorTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CalculatorTests:
"""Contain tests for Calculator class."""
def setUp(self):
"""Initialize calculator with new operator objects."""
<|body_0|>
def test_insufficient_operands(self):
"""Test Insufficient Operands exception."""
<|body_1|>
def test_adder_... | stack_v2_sparse_classes_36k_train_029370 | 2,991 | no_license | [
{
"docstring": "Initialize calculator with new operator objects.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test Insufficient Operands exception.",
"name": "test_insufficient_operands",
"signature": "def test_insufficient_operands(self)"
},
{
"docstring"... | 4 | stack_v2_sparse_classes_30k_train_015266 | Implement the Python class `CalculatorTests` described below.
Class description:
Contain tests for Calculator class.
Method signatures and docstrings:
- def setUp(self): Initialize calculator with new operator objects.
- def test_insufficient_operands(self): Test Insufficient Operands exception.
- def test_adder_call... | Implement the Python class `CalculatorTests` described below.
Class description:
Contain tests for Calculator class.
Method signatures and docstrings:
- def setUp(self): Initialize calculator with new operator objects.
- def test_insufficient_operands(self): Test Insufficient Operands exception.
- def test_adder_call... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class CalculatorTests:
"""Contain tests for Calculator class."""
def setUp(self):
"""Initialize calculator with new operator objects."""
<|body_0|>
def test_insufficient_operands(self):
"""Test Insufficient Operands exception."""
<|body_1|>
def test_adder_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CalculatorTests:
"""Contain tests for Calculator class."""
def setUp(self):
"""Initialize calculator with new operator objects."""
self.adder = Adder()
self.subtracter = Subtracter()
self.multiplier = Multiplier()
self.divider = Divider()
self.calculator = ... | the_stack_v2_python_sparse | students/alexander_boone/lesson01/activity/test_unit.py | JavaRod/SP_Python220B_2019 | train | 1 |
e96945fababa77d483574550ab01855da9d66d98 | [
"request_data = request.get_json()\nplan = request_data['plan']\nsuccess_url = request_data.get('success_url')\ncancel_url = request_data.get('cancel_url')\nif not success_url or not cancel_url:\n raise InvalidRequest()\nuser = get_authenticated_user()\nif not user.stripe_id:\n try:\n cus = billing.Cus... | <|body_start_0|>
request_data = request.get_json()
plan = request_data['plan']
success_url = request_data.get('success_url')
cancel_url = request_data.get('cancel_url')
if not success_url or not cancel_url:
raise InvalidRequest()
user = get_authenticated_user(... | Resource for managing a user's subscription. | UserPlan | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserPlan:
"""Resource for managing a user's subscription."""
def post(self):
"""Create the user's subscription. Returns a Stripe checkout session."""
<|body_0|>
def put(self):
"""Update the user's existing subscription."""
<|body_1|>
def get(self):
... | stack_v2_sparse_classes_36k_train_029371 | 33,890 | permissive | [
{
"docstring": "Create the user's subscription. Returns a Stripe checkout session.",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Update the user's existing subscription.",
"name": "put",
"signature": "def put(self)"
},
{
"docstring": "Fetch any existing subsc... | 3 | stack_v2_sparse_classes_30k_train_004050 | Implement the Python class `UserPlan` described below.
Class description:
Resource for managing a user's subscription.
Method signatures and docstrings:
- def post(self): Create the user's subscription. Returns a Stripe checkout session.
- def put(self): Update the user's existing subscription.
- def get(self): Fetch... | Implement the Python class `UserPlan` described below.
Class description:
Resource for managing a user's subscription.
Method signatures and docstrings:
- def post(self): Create the user's subscription. Returns a Stripe checkout session.
- def put(self): Update the user's existing subscription.
- def get(self): Fetch... | e400a0c22c5f89dd35d571654b13d262b1f6e3b3 | <|skeleton|>
class UserPlan:
"""Resource for managing a user's subscription."""
def post(self):
"""Create the user's subscription. Returns a Stripe checkout session."""
<|body_0|>
def put(self):
"""Update the user's existing subscription."""
<|body_1|>
def get(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserPlan:
"""Resource for managing a user's subscription."""
def post(self):
"""Create the user's subscription. Returns a Stripe checkout session."""
request_data = request.get_json()
plan = request_data['plan']
success_url = request_data.get('success_url')
cancel_... | the_stack_v2_python_sparse | endpoints/api/billing.py | quay/quay | train | 2,363 |
3141d9ca784492daaa725d83922d5a64712ac371 | [
"self.share_param = share_param\nself.path_param = path_param\nself.write = write",
"def wrapped_f(*args, **kwargs):\n from bioshareX.models import Share\n share = kwargs.get(self.share_param, None)\n if share:\n if not isinstance(kwargs[self.share_param], Share):\n try:\n ... | <|body_start_0|>
self.share_param = share_param
self.path_param = path_param
self.write = write
<|end_body_0|>
<|body_start_1|>
def wrapped_f(*args, **kwargs):
from bioshareX.models import Share
share = kwargs.get(self.share_param, None)
if share:
... | safe_path_decorator | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class safe_path_decorator:
def __init__(self, share_param='share', path_param='subpath', write=False):
"""If there are decorator arguments, the function to be decorated is not passed to the constructor!"""
<|body_0|>
def __call__(self, f):
"""If there are decorator argumen... | stack_v2_sparse_classes_36k_train_029372 | 21,345 | permissive | [
{
"docstring": "If there are decorator arguments, the function to be decorated is not passed to the constructor!",
"name": "__init__",
"signature": "def __init__(self, share_param='share', path_param='subpath', write=False)"
},
{
"docstring": "If there are decorator arguments, __call__() is only... | 2 | stack_v2_sparse_classes_30k_train_010298 | Implement the Python class `safe_path_decorator` described below.
Class description:
Implement the safe_path_decorator class.
Method signatures and docstrings:
- def __init__(self, share_param='share', path_param='subpath', write=False): If there are decorator arguments, the function to be decorated is not passed to ... | Implement the Python class `safe_path_decorator` described below.
Class description:
Implement the safe_path_decorator class.
Method signatures and docstrings:
- def __init__(self, share_param='share', path_param='subpath', write=False): If there are decorator arguments, the function to be decorated is not passed to ... | 03ad22c6ecd02c75b58234795c1c84736768d4af | <|skeleton|>
class safe_path_decorator:
def __init__(self, share_param='share', path_param='subpath', write=False):
"""If there are decorator arguments, the function to be decorated is not passed to the constructor!"""
<|body_0|>
def __call__(self, f):
"""If there are decorator argumen... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class safe_path_decorator:
def __init__(self, share_param='share', path_param='subpath', write=False):
"""If there are decorator arguments, the function to be decorated is not passed to the constructor!"""
self.share_param = share_param
self.path_param = path_param
self.write = write... | the_stack_v2_python_sparse | bioshareX/utils.py | amschaal/bioshare | train | 11 | |
a7a5bce87b1042419b8f56d55c83e6bdcc0f30f9 | [
"super().__init__(*args)\nself.async_see = async_see\nself.hass = hass",
"await self.async_update()\nnode = self.gateway.sensors[self.node_id]\nchild = node.children[self.child_id]\nposition = child.values[self.value_type]\nlatitude, longitude, _ = position.split(',')\nawait self.async_see(dev_id=slugify(self.nam... | <|body_start_0|>
super().__init__(*args)
self.async_see = async_see
self.hass = hass
<|end_body_0|>
<|body_start_1|>
await self.async_update()
node = self.gateway.sensors[self.node_id]
child = node.children[self.child_id]
position = child.values[self.value_type]
... | Represent a MySensors scanner. | MySensorsDeviceScanner | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MySensorsDeviceScanner:
"""Represent a MySensors scanner."""
def __init__(self, hass: HomeAssistant, async_see: Callable, *args: Any) -> None:
"""Set up instance."""
<|body_0|>
async def _async_update_callback(self) -> None:
"""Update the device."""
<|bod... | stack_v2_sparse_classes_36k_train_029373 | 2,675 | permissive | [
{
"docstring": "Set up instance.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, async_see: Callable, *args: Any) -> None"
},
{
"docstring": "Update the device.",
"name": "_async_update_callback",
"signature": "async def _async_update_callback(self) -> None"
... | 2 | null | Implement the Python class `MySensorsDeviceScanner` described below.
Class description:
Represent a MySensors scanner.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, async_see: Callable, *args: Any) -> None: Set up instance.
- async def _async_update_callback(self) -> None: Update the dev... | Implement the Python class `MySensorsDeviceScanner` described below.
Class description:
Represent a MySensors scanner.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, async_see: Callable, *args: Any) -> None: Set up instance.
- async def _async_update_callback(self) -> None: Update the dev... | 2fee32fce03bc49e86cf2e7b741a15621a97cce5 | <|skeleton|>
class MySensorsDeviceScanner:
"""Represent a MySensors scanner."""
def __init__(self, hass: HomeAssistant, async_see: Callable, *args: Any) -> None:
"""Set up instance."""
<|body_0|>
async def _async_update_callback(self) -> None:
"""Update the device."""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MySensorsDeviceScanner:
"""Represent a MySensors scanner."""
def __init__(self, hass: HomeAssistant, async_see: Callable, *args: Any) -> None:
"""Set up instance."""
super().__init__(*args)
self.async_see = async_see
self.hass = hass
async def _async_update_callback(s... | the_stack_v2_python_sparse | homeassistant/components/mysensors/device_tracker.py | BenWoodford/home-assistant | train | 11 |
4c29cfab1a6a56ffd77b38a30eb5e8d509caf948 | [
"mpuser = get_system_user_binded_mpuser(request.user)\nwebapp_id = request.user_profile.webapp_id\nstatus = request.GET.get('status', '1')\nmember_tags = MemberTag.get_member_tags(webapp_id)\ntags = []\nfor tag in member_tags:\n if tag.name == '未分组':\n tags = [tag] + tags\n else:\n tags.append(t... | <|body_start_0|>
mpuser = get_system_user_binded_mpuser(request.user)
webapp_id = request.user_profile.webapp_id
status = request.GET.get('status', '1')
member_tags = MemberTag.get_member_tags(webapp_id)
tags = []
for tag in member_tags:
if tag.name == '未分组':
... | MemberList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MemberList:
def get(request):
"""get_memers: 会员列表"""
<|body_0|>
def api_get(request):
"""获取会员列表 URL: http://weapp.weizoom.com/member/api/member_list/?design_mode=0&version=1&filter_value=pay_times:0-1|first_pay:2015-04-08%2000:00--2015-04-30%2000:00&page=1&count_per_... | stack_v2_sparse_classes_36k_train_029374 | 36,865 | no_license | [
{
"docstring": "get_memers: 会员列表",
"name": "get",
"signature": "def get(request)"
},
{
"docstring": "获取会员列表 URL: http://weapp.weizoom.com/member/api/member_list/?design_mode=0&version=1&filter_value=pay_times:0-1|first_pay:2015-04-08%2000:00--2015-04-30%2000:00&page=1&count_per_page=50&enable_pa... | 2 | stack_v2_sparse_classes_30k_train_003697 | Implement the Python class `MemberList` described below.
Class description:
Implement the MemberList class.
Method signatures and docstrings:
- def get(request): get_memers: 会员列表
- def api_get(request): 获取会员列表 URL: http://weapp.weizoom.com/member/api/member_list/?design_mode=0&version=1&filter_value=pay_times:0-1|fir... | Implement the Python class `MemberList` described below.
Class description:
Implement the MemberList class.
Method signatures and docstrings:
- def get(request): get_memers: 会员列表
- def api_get(request): 获取会员列表 URL: http://weapp.weizoom.com/member/api/member_list/?design_mode=0&version=1&filter_value=pay_times:0-1|fir... | 8b2f7befe92841bcc35e0e60cac5958ef3f3af54 | <|skeleton|>
class MemberList:
def get(request):
"""get_memers: 会员列表"""
<|body_0|>
def api_get(request):
"""获取会员列表 URL: http://weapp.weizoom.com/member/api/member_list/?design_mode=0&version=1&filter_value=pay_times:0-1|first_pay:2015-04-08%2000:00--2015-04-30%2000:00&page=1&count_per_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MemberList:
def get(request):
"""get_memers: 会员列表"""
mpuser = get_system_user_binded_mpuser(request.user)
webapp_id = request.user_profile.webapp_id
status = request.GET.get('status', '1')
member_tags = MemberTag.get_member_tags(webapp_id)
tags = []
for ... | the_stack_v2_python_sparse | weapp/member/member_list.py | chengdg/weizoom | train | 1 | |
afcb29e6feeb042531c2b3b75b0c46045aefea67 | [
"self.bot: BunkBot = bot\nself.message: Message = None\nself.channels: ChannelService = channels\nself.yt_result: YoutubeResult = YoutubeResult()\nself.yt_link: str = ''",
"try:\n params: List[str] = get_cmd_params(ctx)\n if len(params) == 0:\n await ctx.send('No youtube query given')\n return... | <|body_start_0|>
self.bot: BunkBot = bot
self.message: Message = None
self.channels: ChannelService = channels
self.yt_result: YoutubeResult = YoutubeResult()
self.yt_link: str = ''
<|end_body_0|>
<|body_start_1|>
try:
params: List[str] = get_cmd_params(ctx)
... | Youtube | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Youtube:
def __init__(self, bot: BunkBot, channels: ChannelService):
"""Description ------------ A cog that enables the ability to search and embed youtube videos Parameters ----------- bot: Bunkbot Super class instance of the bot database: DatabaseService Super class instance of the dat... | stack_v2_sparse_classes_36k_train_029375 | 4,093 | permissive | [
{
"docstring": "Description ------------ A cog that enables the ability to search and embed youtube videos Parameters ----------- bot: Bunkbot Super class instance of the bot database: DatabaseService Super class instance of the database service channels: ChannelService Access to the server channels and other c... | 4 | stack_v2_sparse_classes_30k_train_013355 | Implement the Python class `Youtube` described below.
Class description:
Implement the Youtube class.
Method signatures and docstrings:
- def __init__(self, bot: BunkBot, channels: ChannelService): Description ------------ A cog that enables the ability to search and embed youtube videos Parameters ----------- bot: B... | Implement the Python class `Youtube` described below.
Class description:
Implement the Youtube class.
Method signatures and docstrings:
- def __init__(self, bot: BunkBot, channels: ChannelService): Description ------------ A cog that enables the ability to search and embed youtube videos Parameters ----------- bot: B... | f438c6a7d1f2c1797755eb8287bc1499c0cf2a88 | <|skeleton|>
class Youtube:
def __init__(self, bot: BunkBot, channels: ChannelService):
"""Description ------------ A cog that enables the ability to search and embed youtube videos Parameters ----------- bot: Bunkbot Super class instance of the bot database: DatabaseService Super class instance of the dat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Youtube:
def __init__(self, bot: BunkBot, channels: ChannelService):
"""Description ------------ A cog that enables the ability to search and embed youtube videos Parameters ----------- bot: Bunkbot Super class instance of the bot database: DatabaseService Super class instance of the database service ... | the_stack_v2_python_sparse | src/youtube/youtube_cog.py | fugwenna/bunkbot | train | 2 | |
dc6f46607dff4520cfc2334d91b227d487ad7acc | [
"out_put_file = open(PARSE_OUT_FILE, 'w')\ndat_dict = dict()\ndat_dict['last_catch_logs_date'] = self.last_catch_logs_date\ndat_dict['last_catch_logs_line_num'] = self.last_catch_logs_line_num\npickle.dump(dat_dict, out_put_file)\nout_put_file.close()",
"if os.path.exists(PARSE_OUT_FILE):\n out_put_file = open... | <|body_start_0|>
out_put_file = open(PARSE_OUT_FILE, 'w')
dat_dict = dict()
dat_dict['last_catch_logs_date'] = self.last_catch_logs_date
dat_dict['last_catch_logs_line_num'] = self.last_catch_logs_line_num
pickle.dump(dat_dict, out_put_file)
out_put_file.close()
<|end_bod... | CatchData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CatchData:
def put(self):
"""保存配置"""
<|body_0|>
def load(self):
"""加载"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
out_put_file = open(PARSE_OUT_FILE, 'w')
dat_dict = dict()
dat_dict['last_catch_logs_date'] = self.last_catch_logs_... | stack_v2_sparse_classes_36k_train_029376 | 3,325 | no_license | [
{
"docstring": "保存配置",
"name": "put",
"signature": "def put(self)"
},
{
"docstring": "加载",
"name": "load",
"signature": "def load(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007456 | Implement the Python class `CatchData` described below.
Class description:
Implement the CatchData class.
Method signatures and docstrings:
- def put(self): 保存配置
- def load(self): 加载 | Implement the Python class `CatchData` described below.
Class description:
Implement the CatchData class.
Method signatures and docstrings:
- def put(self): 保存配置
- def load(self): 加载
<|skeleton|>
class CatchData:
def put(self):
"""保存配置"""
<|body_0|>
def load(self):
"""加载"""
... | ff2afd6d29e9dce6157a66ff62b4d1ea97d04184 | <|skeleton|>
class CatchData:
def put(self):
"""保存配置"""
<|body_0|>
def load(self):
"""加载"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CatchData:
def put(self):
"""保存配置"""
out_put_file = open(PARSE_OUT_FILE, 'w')
dat_dict = dict()
dat_dict['last_catch_logs_date'] = self.last_catch_logs_date
dat_dict['last_catch_logs_line_num'] = self.last_catch_logs_line_num
pickle.dump(dat_dict, out_put_file)
... | the_stack_v2_python_sparse | apps/logs/catch_game_logs.py | robot-nan/GameLogServer | train | 0 | |
8b25bb19b7c24532966280e80a023442c0cad74d | [
"n = len(prices)\nif n == 0:\n return 0\nmin_price = float('inf')\nmax_profit = 0\nfor p in prices:\n min_price = min(min_price, p)\n max_profit = max(max_profit, p - min_price)\nreturn max_profit",
"n = len(prices)\nif n < 2:\n return 0\nres = 0\nfor i in range(n - 1):\n if prices[i] < prices[i + ... | <|body_start_0|>
n = len(prices)
if n == 0:
return 0
min_price = float('inf')
max_profit = 0
for p in prices:
min_price = min(min_price, p)
max_profit = max(max_profit, p - min_price)
return max_profit
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
"""121. input| prices: List[int] output| int"""
<|body_0|>
def maxProfit_multi(self, prices):
"""122. input| prices: List[int] output| int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(prices)
... | stack_v2_sparse_classes_36k_train_029377 | 727 | no_license | [
{
"docstring": "121. input| prices: List[int] output| int",
"name": "maxProfit",
"signature": "def maxProfit(self, prices)"
},
{
"docstring": "122. input| prices: List[int] output| int",
"name": "maxProfit_multi",
"signature": "def maxProfit_multi(self, prices)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016850 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): 121. input| prices: List[int] output| int
- def maxProfit_multi(self, prices): 122. input| prices: List[int] output| int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): 121. input| prices: List[int] output| int
- def maxProfit_multi(self, prices): 122. input| prices: List[int] output| int
<|skeleton|>
class Solution... | 8290ad1c763d9f7c7f7bed63426b4769b34fd2fc | <|skeleton|>
class Solution:
def maxProfit(self, prices):
"""121. input| prices: List[int] output| int"""
<|body_0|>
def maxProfit_multi(self, prices):
"""122. input| prices: List[int] output| int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit(self, prices):
"""121. input| prices: List[int] output| int"""
n = len(prices)
if n == 0:
return 0
min_price = float('inf')
max_profit = 0
for p in prices:
min_price = min(min_price, p)
max_profit = max... | the_stack_v2_python_sparse | dp_121_stocks.py | screnary/Algorithm_python | train | 0 | |
dad70f49e5a69177b94cefb3d0cfc6e04acf2f16 | [
"try:\n jd = jc.load_obj_json('{}')\n jd.config = 'Y'\n jd.nn_id = nnid\n netconf.update_network(jd)\n netconf.save_conf(nnid, request.body)\n netconf.set_on_net_conf(nnid)\n return_data = {'status': '200', 'result': nnid}\n return Response(json.dumps(return_data))\nexcept Exception as e:\n ... | <|body_start_0|>
try:
jd = jc.load_obj_json('{}')
jd.config = 'Y'
jd.nn_id = nnid
netconf.update_network(jd)
netconf.save_conf(nnid, request.body)
netconf.set_on_net_conf(nnid)
return_data = {'status': '200', 'result': nnid}
... | 1. Name : ConvNeuralNetConfig 2. Steps - CNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/nninfo/{nnid}/ - post /api/v1/type/imagedata/base/{baseid}/ - post /api/v1/type/imagedata/base/{baseid}/table/{tb}/ - post /api/v1/type/imagedata/base/{baseid}/table/{tb}/label/{label}/data/ - post /a... | ConvNeuralNetConfig | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvNeuralNetConfig:
"""1. Name : ConvNeuralNetConfig 2. Steps - CNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/nninfo/{nnid}/ - post /api/v1/type/imagedata/base/{baseid}/ - post /api/v1/type/imagedata/base/{baseid}/table/{tb}/ - post /api/v1/type/imagedata/base/{b... | stack_v2_sparse_classes_36k_train_029378 | 3,143 | no_license | [
{
"docstring": "- desc : insert cnn configuration data",
"name": "post",
"signature": "def post(self, request, nnid)"
},
{
"docstring": "- desc : get cnn configuration data",
"name": "get",
"signature": "def get(self, request, nnid)"
},
{
"docstring": "- desc ; update cnn configu... | 4 | stack_v2_sparse_classes_30k_train_007021 | Implement the Python class `ConvNeuralNetConfig` described below.
Class description:
1. Name : ConvNeuralNetConfig 2. Steps - CNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/nninfo/{nnid}/ - post /api/v1/type/imagedata/base/{baseid}/ - post /api/v1/type/imagedata/base/{baseid}/table/{tb}... | Implement the Python class `ConvNeuralNetConfig` described below.
Class description:
1. Name : ConvNeuralNetConfig 2. Steps - CNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/nninfo/{nnid}/ - post /api/v1/type/imagedata/base/{baseid}/ - post /api/v1/type/imagedata/base/{baseid}/table/{tb}... | ef058737f391de817c74398ef9a5d3a28f973c98 | <|skeleton|>
class ConvNeuralNetConfig:
"""1. Name : ConvNeuralNetConfig 2. Steps - CNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/nninfo/{nnid}/ - post /api/v1/type/imagedata/base/{baseid}/ - post /api/v1/type/imagedata/base/{baseid}/table/{tb}/ - post /api/v1/type/imagedata/base/{b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConvNeuralNetConfig:
"""1. Name : ConvNeuralNetConfig 2. Steps - CNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/nninfo/{nnid}/ - post /api/v1/type/imagedata/base/{baseid}/ - post /api/v1/type/imagedata/base/{baseid}/table/{tb}/ - post /api/v1/type/imagedata/base/{baseid}/table/... | the_stack_v2_python_sparse | tfmsarest/views/cnn_config.py | TensorMSA/tensormsa_old | train | 6 |
b0d943f0dc540313444c75f4aca5fcdfa6815774 | [
"time.sleep(2)\nLoginPage(web_page).login(data['username'], data['password'])\nlogging.info('开始断言')\ntime.sleep(3)\ntry:\n assert LoginPage(web_page).login_success() == data['check']\n assert 1 == 1\n logging.info('登录成功')\nexcept:\n print('登录失败')\n common.save_screenShot(web_page, model_name='登录页面')\... | <|body_start_0|>
time.sleep(2)
LoginPage(web_page).login(data['username'], data['password'])
logging.info('开始断言')
time.sleep(3)
try:
assert LoginPage(web_page).login_success() == data['check']
assert 1 == 1
logging.info('登录成功')
except:
... | TestLogin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestLogin:
def test_login_success(self, data, web_page):
"""成功登录"""
<|body_0|>
def test_usernotin(self, data, web_page):
"""帐号不存在/密码少于6位,密码输入错误"""
<|body_1|>
def test_usernotin2(self, data, web_page):
"""手机号码为空"""
<|body_2|>
<|end_skelet... | stack_v2_sparse_classes_36k_train_029379 | 2,299 | no_license | [
{
"docstring": "成功登录",
"name": "test_login_success",
"signature": "def test_login_success(self, data, web_page)"
},
{
"docstring": "帐号不存在/密码少于6位,密码输入错误",
"name": "test_usernotin",
"signature": "def test_usernotin(self, data, web_page)"
},
{
"docstring": "手机号码为空",
"name": "tes... | 3 | stack_v2_sparse_classes_30k_train_013896 | Implement the Python class `TestLogin` described below.
Class description:
Implement the TestLogin class.
Method signatures and docstrings:
- def test_login_success(self, data, web_page): 成功登录
- def test_usernotin(self, data, web_page): 帐号不存在/密码少于6位,密码输入错误
- def test_usernotin2(self, data, web_page): 手机号码为空 | Implement the Python class `TestLogin` described below.
Class description:
Implement the TestLogin class.
Method signatures and docstrings:
- def test_login_success(self, data, web_page): 成功登录
- def test_usernotin(self, data, web_page): 帐号不存在/密码少于6位,密码输入错误
- def test_usernotin2(self, data, web_page): 手机号码为空
<|skelet... | b262c13e55a6e9eae1d4fa11d50b71814028261c | <|skeleton|>
class TestLogin:
def test_login_success(self, data, web_page):
"""成功登录"""
<|body_0|>
def test_usernotin(self, data, web_page):
"""帐号不存在/密码少于6位,密码输入错误"""
<|body_1|>
def test_usernotin2(self, data, web_page):
"""手机号码为空"""
<|body_2|>
<|end_skelet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestLogin:
def test_login_success(self, data, web_page):
"""成功登录"""
time.sleep(2)
LoginPage(web_page).login(data['username'], data['password'])
logging.info('开始断言')
time.sleep(3)
try:
assert LoginPage(web_page).login_success() == data['check']
... | the_stack_v2_python_sparse | TestCase/test_C_web/test_login.py | xjx985426946/Test_UI | train | 0 | |
d90dd151e51e79badec0aaa67470bb5c62e6428b | [
"if isinstance(request, rest_framework.request.Request):\n return request.data\nreturn super(DRFAuthenticatedGraphQLView, self).parse_body(request)",
"view = super(DRFAuthenticatedGraphQLView, cls).as_view(*args, **kwargs)\nview = permission_classes((AllowAny,))(view)\nview = authentication_classes(api_setting... | <|body_start_0|>
if isinstance(request, rest_framework.request.Request):
return request.data
return super(DRFAuthenticatedGraphQLView, self).parse_body(request)
<|end_body_0|>
<|body_start_1|>
view = super(DRFAuthenticatedGraphQLView, cls).as_view(*args, **kwargs)
view = per... | GRAPH-QL View that utilizes authentication from Django Rest Framework | DRFAuthenticatedGraphQLView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DRFAuthenticatedGraphQLView:
"""GRAPH-QL View that utilizes authentication from Django Rest Framework"""
def parse_body(self, request):
"""Parses Request Data for use in graph-ql"""
<|body_0|>
def as_view(cls, *args, **kwargs):
"""Set DRF attributes in the view""... | stack_v2_sparse_classes_36k_train_029380 | 4,981 | permissive | [
{
"docstring": "Parses Request Data for use in graph-ql",
"name": "parse_body",
"signature": "def parse_body(self, request)"
},
{
"docstring": "Set DRF attributes in the view",
"name": "as_view",
"signature": "def as_view(cls, *args, **kwargs)"
}
] | 2 | null | Implement the Python class `DRFAuthenticatedGraphQLView` described below.
Class description:
GRAPH-QL View that utilizes authentication from Django Rest Framework
Method signatures and docstrings:
- def parse_body(self, request): Parses Request Data for use in graph-ql
- def as_view(cls, *args, **kwargs): Set DRF att... | Implement the Python class `DRFAuthenticatedGraphQLView` described below.
Class description:
GRAPH-QL View that utilizes authentication from Django Rest Framework
Method signatures and docstrings:
- def parse_body(self, request): Parses Request Data for use in graph-ql
- def as_view(cls, *args, **kwargs): Set DRF att... | 6b080039398fb4099a34335317d649dd67783f63 | <|skeleton|>
class DRFAuthenticatedGraphQLView:
"""GRAPH-QL View that utilizes authentication from Django Rest Framework"""
def parse_body(self, request):
"""Parses Request Data for use in graph-ql"""
<|body_0|>
def as_view(cls, *args, **kwargs):
"""Set DRF attributes in the view""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DRFAuthenticatedGraphQLView:
"""GRAPH-QL View that utilizes authentication from Django Rest Framework"""
def parse_body(self, request):
"""Parses Request Data for use in graph-ql"""
if isinstance(request, rest_framework.request.Request):
return request.data
return supe... | the_stack_v2_python_sparse | accounts/views.py | daniel-waruo/e-commerse-api | train | 6 |
d9206700a18cd5e5e971b231ee361dce7f91661c | [
"if not isinstance(self.num_qudits, int) or len(qudit_dimensions) != self.num_qudits:\n raise CircuitError(f'Number of flexible qudits ({self.num_qudits}) does not match number of qudit_dimensions {qudit_dimensions}.')\nsuper().__init__(name=name, qudit_dimensions=qudit_dimensions, num_single_qubits=num_single_q... | <|body_start_0|>
if not isinstance(self.num_qudits, int) or len(qudit_dimensions) != self.num_qudits:
raise CircuitError(f'Number of flexible qudits ({self.num_qudits}) does not match number of qudit_dimensions {qudit_dimensions}.')
super().__init__(name=name, qudit_dimensions=qudit_dimensio... | Qudit gate adjusting to qudit dimensions. Class variable num_qudits must be set as an integer greater than 0. | FlexibleQuditGate | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlexibleQuditGate:
"""Qudit gate adjusting to qudit dimensions. Class variable num_qudits must be set as an integer greater than 0."""
def __init__(self, name: str, qudit_dimensions: List[int], num_single_qubits: int, params: List, label: Optional[str]=None) -> None:
"""Flexible qudi... | stack_v2_sparse_classes_36k_train_029381 | 7,780 | permissive | [
{
"docstring": "Flexible qudit gate. Subclasses should only leave the qudit_dimensions argument in constructor, i.e. def __init__(self, qudit_dimensions): ... Raises: CircuitError: If number of qudits does not equal length of qudit_dimensions.",
"name": "__init__",
"signature": "def __init__(self, name:... | 2 | stack_v2_sparse_classes_30k_train_011626 | Implement the Python class `FlexibleQuditGate` described below.
Class description:
Qudit gate adjusting to qudit dimensions. Class variable num_qudits must be set as an integer greater than 0.
Method signatures and docstrings:
- def __init__(self, name: str, qudit_dimensions: List[int], num_single_qubits: int, params... | Implement the Python class `FlexibleQuditGate` described below.
Class description:
Qudit gate adjusting to qudit dimensions. Class variable num_qudits must be set as an integer greater than 0.
Method signatures and docstrings:
- def __init__(self, name: str, qudit_dimensions: List[int], num_single_qubits: int, params... | 9935eedd7d8258619a35424a98f2a71776b61e28 | <|skeleton|>
class FlexibleQuditGate:
"""Qudit gate adjusting to qudit dimensions. Class variable num_qudits must be set as an integer greater than 0."""
def __init__(self, name: str, qudit_dimensions: List[int], num_single_qubits: int, params: List, label: Optional[str]=None) -> None:
"""Flexible qudi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FlexibleQuditGate:
"""Qudit gate adjusting to qudit dimensions. Class variable num_qudits must be set as an integer greater than 0."""
def __init__(self, name: str, qudit_dimensions: List[int], num_single_qubits: int, params: List, label: Optional[str]=None) -> None:
"""Flexible qudit gate. Subcl... | the_stack_v2_python_sparse | qiskit_qudits/circuit/flexiblequditinstruction.py | q-inho/QuditsTeam-1 | train | 1 |
4f65f17ebe58cf19ed40e665061044e828b6a84d | [
"self.dialogs = dialogs\nself.language = language\nself.styling = styling\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\ndialogs = idfy_rest_client.models.dialogs.Dialogs.from_dictionary(dictionary.get('dialogs')) if dictionary.get('dialogs') else None\nlanguage = ... | <|body_start_0|>
self.dialogs = dialogs
self.language = language
self.styling = styling
self.additional_properties = additional_properties
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
dialogs = idfy_rest_client.models.dialogs.Dialogs.fro... | Implementation of the 'UI' model. TODO: type model description here. Attributes: dialogs (Dialogs): You can create dialogs that will be showed to the signer in the signature process language (Language157): The signers preferred language, this setting is used when signing the document and in email/sms notifications.<spa... | UI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UI:
"""Implementation of the 'UI' model. TODO: type model description here. Attributes: dialogs (Dialogs): You can create dialogs that will be showed to the signer in the signature process language (Language157): The signers preferred language, this setting is used when signing the document and i... | stack_v2_sparse_classes_36k_train_029382 | 3,051 | permissive | [
{
"docstring": "Constructor for the UI class",
"name": "__init__",
"signature": "def __init__(self, dialogs=None, language=None, styling=None, additional_properties={})"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representat... | 2 | null | Implement the Python class `UI` described below.
Class description:
Implementation of the 'UI' model. TODO: type model description here. Attributes: dialogs (Dialogs): You can create dialogs that will be showed to the signer in the signature process language (Language157): The signers preferred language, this setting ... | Implement the Python class `UI` described below.
Class description:
Implementation of the 'UI' model. TODO: type model description here. Attributes: dialogs (Dialogs): You can create dialogs that will be showed to the signer in the signature process language (Language157): The signers preferred language, this setting ... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class UI:
"""Implementation of the 'UI' model. TODO: type model description here. Attributes: dialogs (Dialogs): You can create dialogs that will be showed to the signer in the signature process language (Language157): The signers preferred language, this setting is used when signing the document and i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UI:
"""Implementation of the 'UI' model. TODO: type model description here. Attributes: dialogs (Dialogs): You can create dialogs that will be showed to the signer in the signature process language (Language157): The signers preferred language, this setting is used when signing the document and in email/sms n... | the_stack_v2_python_sparse | idfy_rest_client/models/ui.py | dealflowteam/Idfy | train | 0 |
ce16e9d8babc8da244099aaa477fa63578a40b73 | [
"for k, vs in list(args.items()):\n if k not in self.validators or not vs:\n continue\n if not isinstance(vs, list):\n vs = [vs]\n for v in vs:\n if not self.validators[k].validate(v, args):\n RH_Err.ctl(1100, msgx=f'{self.validators[k].msg} - field={k}', logLevel=logging.IN... | <|body_start_0|>
for k, vs in list(args.items()):
if k not in self.validators or not vs:
continue
if not isinstance(vs, list):
vs = [vs]
for v in vs:
if not self.validators[k].validate(v, args):
RH_Err.ctl(11... | Model of Data. It ensure that key/value stored in *.conf are mapped to storage key/value, key/value shown to user are mapped to interface key/value. | BaseModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseModel:
"""Model of Data. It ensure that key/value stored in *.conf are mapped to storage key/value, key/value shown to user are mapped to interface key/value."""
def validate(self, args):
"""Validate request arguments."""
<|body_0|>
def normalize(self, data):
... | stack_v2_sparse_classes_36k_train_029383 | 24,282 | permissive | [
{
"docstring": "Validate request arguments.",
"name": "validate",
"signature": "def validate(self, args)"
},
{
"docstring": "Normalize request arguments or response data.",
"name": "normalize",
"signature": "def normalize(self, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005926 | Implement the Python class `BaseModel` described below.
Class description:
Model of Data. It ensure that key/value stored in *.conf are mapped to storage key/value, key/value shown to user are mapped to interface key/value.
Method signatures and docstrings:
- def validate(self, args): Validate request arguments.
- de... | Implement the Python class `BaseModel` described below.
Class description:
Model of Data. It ensure that key/value stored in *.conf are mapped to storage key/value, key/value shown to user are mapped to interface key/value.
Method signatures and docstrings:
- def validate(self, args): Validate request arguments.
- de... | bbeb74e681176d5543e1f3b5d94cb4d791c38010 | <|skeleton|>
class BaseModel:
"""Model of Data. It ensure that key/value stored in *.conf are mapped to storage key/value, key/value shown to user are mapped to interface key/value."""
def validate(self, args):
"""Validate request arguments."""
<|body_0|>
def normalize(self, data):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseModel:
"""Model of Data. It ensure that key/value stored in *.conf are mapped to storage key/value, key/value shown to user are mapped to interface key/value."""
def validate(self, args):
"""Validate request arguments."""
for k, vs in list(args.items()):
if k not in self.v... | the_stack_v2_python_sparse | src/TA-opnsense/bin/ta_opnsense/aob_py3/splunktaucclib/rest_handler/base.py | ZachChristensen28/TA-opnsense | train | 13 |
45b8378c9810121788f2ff555b1fb225fd1081dc | [
"if obj:\n return obj.json\nreturn None",
"if obj and obj.task:\n return obj.task.name\nreturn None"
] | <|body_start_0|>
if obj:
return obj.json
return None
<|end_body_0|>
<|body_start_1|>
if obj and obj.task:
return obj.task.name
return None
<|end_body_1|>
| Serializer for XForm Model | XFormSerializer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XFormSerializer:
"""Serializer for XForm Model"""
def get_metadata(self, obj):
"""Get metadata field"""
<|body_0|>
def get_task_name(self, obj):
"""Get the attached task name"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if obj:
re... | stack_v2_sparse_classes_36k_train_029384 | 2,263 | permissive | [
{
"docstring": "Get metadata field",
"name": "get_metadata",
"signature": "def get_metadata(self, obj)"
},
{
"docstring": "Get the attached task name",
"name": "get_task_name",
"signature": "def get_task_name(self, obj)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003516 | Implement the Python class `XFormSerializer` described below.
Class description:
Serializer for XForm Model
Method signatures and docstrings:
- def get_metadata(self, obj): Get metadata field
- def get_task_name(self, obj): Get the attached task name | Implement the Python class `XFormSerializer` described below.
Class description:
Serializer for XForm Model
Method signatures and docstrings:
- def get_metadata(self, obj): Get metadata field
- def get_task_name(self, obj): Get the attached task name
<|skeleton|>
class XFormSerializer:
"""Serializer for XForm Mo... | 3d52571723a10263b634484575aa77796b3ff675 | <|skeleton|>
class XFormSerializer:
"""Serializer for XForm Model"""
def get_metadata(self, obj):
"""Get metadata field"""
<|body_0|>
def get_task_name(self, obj):
"""Get the attached task name"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XFormSerializer:
"""Serializer for XForm Model"""
def get_metadata(self, obj):
"""Get metadata field"""
if obj:
return obj.json
return None
def get_task_name(self, obj):
"""Get the attached task name"""
if obj and obj.task:
return obj.t... | the_stack_v2_python_sparse | kaznet/apps/ona/serializers.py | onaio/kaznet-web | train | 2 |
d8d82bff0f95ee16ca3f4001769161a5a3ddd319 | [
"nums.sort()\nn = len(nums)\nreturn nums[n - k]",
"import random\npivot = random.choice(nums)\nnums1, nums2 = ([], [])\nfor num in nums:\n if num > pivot:\n nums1.append(num)\n elif num < pivot:\n nums2.append(num)\nif k <= len(nums1):\n return self.findKthLargest(nums1, k)\nif k > len(nums... | <|body_start_0|>
nums.sort()
n = len(nums)
return nums[n - k]
<|end_body_0|>
<|body_start_1|>
import random
pivot = random.choice(nums)
nums1, nums2 = ([], [])
for num in nums:
if num > pivot:
nums1.append(num)
elif num < p... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findKthLargest(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def findKthLargest_1(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
def findKthLargest_2(self, nums, k):
... | stack_v2_sparse_classes_36k_train_029385 | 1,788 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "findKthLargest",
"signature": "def findKthLargest(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "findKthLargest_1",
"signature": "def findKthLargest_1(self, nums, k)"
... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findKthLargest(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def findKthLargest_1(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def find... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findKthLargest(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def findKthLargest_1(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def find... | ba58ac60b32e261e43482d7e71b32587700e3719 | <|skeleton|>
class Solution:
def findKthLargest(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def findKthLargest_1(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
def findKthLargest_2(self, nums, k):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findKthLargest(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
nums.sort()
n = len(nums)
return nums[n - k]
def findKthLargest_1(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
import random
pi... | the_stack_v2_python_sparse | python/215_kth_largest_element_in_an_array.py | lingng/Leetcode | train | 0 | |
60eecbc9886dc6e7e022d5c87830e49e1975c31f | [
"self.quark = quark\nself.nucleon = nucleon\nself.ip = input_dict",
"if self.nucleon == 'p':\n if self.quark == 'u':\n return -self.ip['mu_at_2GeV'] * self.ip['BT10up']\n if self.quark == 'd':\n return -self.ip['md_at_2GeV'] * self.ip['BT10dp']\n if self.quark == 's':\n return -self.... | <|body_start_0|>
self.quark = quark
self.nucleon = nucleon
self.ip = input_dict
<|end_body_0|>
<|body_start_1|>
if self.nucleon == 'p':
if self.quark == 'u':
return -self.ip['mu_at_2GeV'] * self.ip['BT10up']
if self.quark == 'd':
r... | FT1 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FT1:
def __init__(self, quark, nucleon, input_dict):
"""The nuclear form factor FT1 Return the nuclear form factor FT1 Arguments --------- quark = 'u', 'd', 's' -- the quark flavor (up, down, strange) nucleon = 'p', 'n' -- the nucleon (proton or neutron) input_dict (optional) -- a dictio... | stack_v2_sparse_classes_36k_train_029386 | 18,337 | permissive | [
{
"docstring": "The nuclear form factor FT1 Return the nuclear form factor FT1 Arguments --------- quark = 'u', 'd', 's' -- the quark flavor (up, down, strange) nucleon = 'p', 'n' -- the nucleon (proton or neutron) input_dict (optional) -- a dictionary of hadronic input parameters (default is Num_input().input_... | 2 | stack_v2_sparse_classes_30k_train_014406 | Implement the Python class `FT1` described below.
Class description:
Implement the FT1 class.
Method signatures and docstrings:
- def __init__(self, quark, nucleon, input_dict): The nuclear form factor FT1 Return the nuclear form factor FT1 Arguments --------- quark = 'u', 'd', 's' -- the quark flavor (up, down, stra... | Implement the Python class `FT1` described below.
Class description:
Implement the FT1 class.
Method signatures and docstrings:
- def __init__(self, quark, nucleon, input_dict): The nuclear form factor FT1 Return the nuclear form factor FT1 Arguments --------- quark = 'u', 'd', 's' -- the quark flavor (up, down, stra... | 4a714e4701f817fdc96e10e461eef7c4756ef71d | <|skeleton|>
class FT1:
def __init__(self, quark, nucleon, input_dict):
"""The nuclear form factor FT1 Return the nuclear form factor FT1 Arguments --------- quark = 'u', 'd', 's' -- the quark flavor (up, down, strange) nucleon = 'p', 'n' -- the nucleon (proton or neutron) input_dict (optional) -- a dictio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FT1:
def __init__(self, quark, nucleon, input_dict):
"""The nuclear form factor FT1 Return the nuclear form factor FT1 Arguments --------- quark = 'u', 'd', 's' -- the quark flavor (up, down, strange) nucleon = 'p', 'n' -- the nucleon (proton or neutron) input_dict (optional) -- a dictionary of hadron... | the_stack_v2_python_sparse | directdm/num/single_nucleon_form_factors.py | DirectDM/directdm-py | train | 6 | |
509a320db4a7b2fc522e52b2ad74c9e8647dee5f | [
"response = super(Verify, self).login_success(*args, **kwargs)\nif not waffle.flag_is_active(self.request, 'voting'):\n return response\ntry:\n video_id = self.request.session['vote_video']\n video = Video.objects.get(id=video_id)\n Vote.objects.get_or_create(user=self.request.user, video=video)\n de... | <|body_start_0|>
response = super(Verify, self).login_success(*args, **kwargs)
if not waffle.flag_is_active(self.request, 'voting'):
return response
try:
video_id = self.request.session['vote_video']
video = Video.objects.get(id=video_id)
Vote.obje... | Verify | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Verify:
def login_success(self, *args, **kwargs):
"""Extend successful login to check if the user was attempting to vote for a video, and create the vote if they were."""
<|body_0|>
def login_failure(self, *args, **kwargs):
"""Extend login failure so that if login fa... | stack_v2_sparse_classes_36k_train_029387 | 2,642 | permissive | [
{
"docstring": "Extend successful login to check if the user was attempting to vote for a video, and create the vote if they were.",
"name": "login_success",
"signature": "def login_success(self, *args, **kwargs)"
},
{
"docstring": "Extend login failure so that if login fails, the user's attempt... | 2 | stack_v2_sparse_classes_30k_train_006066 | Implement the Python class `Verify` described below.
Class description:
Implement the Verify class.
Method signatures and docstrings:
- def login_success(self, *args, **kwargs): Extend successful login to check if the user was attempting to vote for a video, and create the vote if they were.
- def login_failure(self,... | Implement the Python class `Verify` described below.
Class description:
Implement the Verify class.
Method signatures and docstrings:
- def login_success(self, *args, **kwargs): Extend successful login to check if the user was attempting to vote for a video, and create the vote if they were.
- def login_failure(self,... | ad19ed59aac682744badae6d19a149327037f293 | <|skeleton|>
class Verify:
def login_success(self, *args, **kwargs):
"""Extend successful login to check if the user was attempting to vote for a video, and create the vote if they were."""
<|body_0|>
def login_failure(self, *args, **kwargs):
"""Extend login failure so that if login fa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Verify:
def login_success(self, *args, **kwargs):
"""Extend successful login to check if the user was attempting to vote for a video, and create the vote if they were."""
response = super(Verify, self).login_success(*args, **kwargs)
if not waffle.flag_is_active(self.request, 'voting'):... | the_stack_v2_python_sparse | flicks/users/views.py | mozilla/firefox-flicks | train | 3 | |
bd8d2fe72df8f665cf2edcf5e908d5b965109368 | [
"AbstractLayer.__init__(self)\nself.input = InputPort(inputSize)\nself.outputPorts = []\nfor size in outputSizes:\n self.outputPorts.append(OutputPort(size))",
"idx = 0\nfor port in self.outputPorts:\n port.setOutput(self.input.getNetInput()[:, idx:idx + port.size])\n idx += port.size",
"deltas = np.ze... | <|body_start_0|>
AbstractLayer.__init__(self)
self.input = InputPort(inputSize)
self.outputPorts = []
for size in outputSizes:
self.outputPorts.append(OutputPort(size))
<|end_body_0|>
<|body_start_1|>
idx = 0
for port in self.outputPorts:
port.set... | A layer which splits an input port into multiple output ports | SplitLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SplitLayer:
"""A layer which splits an input port into multiple output ports"""
def __init__(self, inputSize, outputSizes):
"""Create a layer which splits the input into the provided output sizes"""
<|body_0|>
def forward(self):
"""Perform a forward step - split ... | stack_v2_sparse_classes_36k_train_029388 | 1,664 | no_license | [
{
"docstring": "Create a layer which splits the input into the provided output sizes",
"name": "__init__",
"signature": "def __init__(self, inputSize, outputSizes)"
},
{
"docstring": "Perform a forward step - split the input to the various outputs",
"name": "forward",
"signature": "def f... | 3 | stack_v2_sparse_classes_30k_train_019312 | Implement the Python class `SplitLayer` described below.
Class description:
A layer which splits an input port into multiple output ports
Method signatures and docstrings:
- def __init__(self, inputSize, outputSizes): Create a layer which splits the input into the provided output sizes
- def forward(self): Perform a ... | Implement the Python class `SplitLayer` described below.
Class description:
A layer which splits an input port into multiple output ports
Method signatures and docstrings:
- def __init__(self, inputSize, outputSizes): Create a layer which splits the input into the provided output sizes
- def forward(self): Perform a ... | dbe2090e50434f33ac7a46845ad67eb5dc7dea87 | <|skeleton|>
class SplitLayer:
"""A layer which splits an input port into multiple output ports"""
def __init__(self, inputSize, outputSizes):
"""Create a layer which splits the input into the provided output sizes"""
<|body_0|>
def forward(self):
"""Perform a forward step - split ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SplitLayer:
"""A layer which splits an input port into multiple output ports"""
def __init__(self, inputSize, outputSizes):
"""Create a layer which splits the input into the provided output sizes"""
AbstractLayer.__init__(self)
self.input = InputPort(inputSize)
self.output... | the_stack_v2_python_sparse | nn/components/layers/SplitLayer.py | danathughes/pyNeuralNetwork | train | 0 |
6bacf45211c6e2e43f0c7f7e15bc69ac4d8fe415 | [
"self.graph = tf.Graph()\ngraph_def = None\ngraph_def = tf.GraphDef.FromString(open(tarball_path + '/frozen_inference_graph.pb', 'rb').read())\nif graph_def is None:\n raise RuntimeError('Cannot find inference graph in tar archive.')\nwith self.graph.as_default():\n tf.import_graph_def(graph_def, name='')\nse... | <|body_start_0|>
self.graph = tf.Graph()
graph_def = None
graph_def = tf.GraphDef.FromString(open(tarball_path + '/frozen_inference_graph.pb', 'rb').read())
if graph_def is None:
raise RuntimeError('Cannot find inference graph in tar archive.')
with self.graph.as_defa... | Class to load deeplab model and run inference. | DeepLabModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeepLabModel:
"""Class to load deeplab model and run inference."""
def __init__(self, tarball_path):
"""Creates and loads pretrained deeplab model."""
<|body_0|>
def run(self, image):
"""Runs inference on a single image. Args: image: A PIL.Image object, raw input... | stack_v2_sparse_classes_36k_train_029389 | 14,437 | permissive | [
{
"docstring": "Creates and loads pretrained deeplab model.",
"name": "__init__",
"signature": "def __init__(self, tarball_path)"
},
{
"docstring": "Runs inference on a single image. Args: image: A PIL.Image object, raw input image. Returns: resized_image: RGB image resized from original input i... | 2 | stack_v2_sparse_classes_30k_val_001187 | Implement the Python class `DeepLabModel` described below.
Class description:
Class to load deeplab model and run inference.
Method signatures and docstrings:
- def __init__(self, tarball_path): Creates and loads pretrained deeplab model.
- def run(self, image): Runs inference on a single image. Args: image: A PIL.Im... | Implement the Python class `DeepLabModel` described below.
Class description:
Class to load deeplab model and run inference.
Method signatures and docstrings:
- def __init__(self, tarball_path): Creates and loads pretrained deeplab model.
- def run(self, image): Runs inference on a single image. Args: image: A PIL.Im... | 20864f88adc2fe52c25538ebb11c5947a85debd3 | <|skeleton|>
class DeepLabModel:
"""Class to load deeplab model and run inference."""
def __init__(self, tarball_path):
"""Creates and loads pretrained deeplab model."""
<|body_0|>
def run(self, image):
"""Runs inference on a single image. Args: image: A PIL.Image object, raw input... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeepLabModel:
"""Class to load deeplab model and run inference."""
def __init__(self, tarball_path):
"""Creates and loads pretrained deeplab model."""
self.graph = tf.Graph()
graph_def = None
graph_def = tf.GraphDef.FromString(open(tarball_path + '/frozen_inference_graph.p... | the_stack_v2_python_sparse | python/FinalModule/edgeGen.py | gana-chocolate/Doodles_Become_Paintings | train | 2 |
2e75f3f70ab13799d3b163d4f2873035a0de5839 | [
"Container.__init__(self, name, padding=5)\nself.callback = callback\nol = OptionList('option_list', option_list, width, lineheight)\nself.sub(ol)\nbutton = Button('OK', pygame.Rect((0, 0), (width, lineheight)), self.selection_made)\nself.sub(button)\nreturn",
"self.callback(self.option_list.selected)\nself.destr... | <|body_start_0|>
Container.__init__(self, name, padding=5)
self.callback = callback
ol = OptionList('option_list', option_list, width, lineheight)
self.sub(ol)
button = Button('OK', pygame.Rect((0, 0), (width, lineheight)), self.selection_made)
self.sub(button)
re... | An OptionSelector wraps an OptionList and an OK button, calling a callback when a selection is confirmed. | OptionSelector | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptionSelector:
"""An OptionSelector wraps an OptionList and an OK button, calling a callback when a selection is confirmed."""
def __init__(self, name, option_list, callback, width=200, lineheight=30):
"""Initialise the OptionList. option_list is a list of strings to be displayed as... | stack_v2_sparse_classes_36k_train_029390 | 27,668 | permissive | [
{
"docstring": "Initialise the OptionList. option_list is a list of strings to be displayed as options. callback is a function to be called with the selected Option instance as argument once the selection is made.",
"name": "__init__",
"signature": "def __init__(self, name, option_list, callback, width=... | 2 | stack_v2_sparse_classes_30k_train_012008 | Implement the Python class `OptionSelector` described below.
Class description:
An OptionSelector wraps an OptionList and an OK button, calling a callback when a selection is confirmed.
Method signatures and docstrings:
- def __init__(self, name, option_list, callback, width=200, lineheight=30): Initialise the Option... | Implement the Python class `OptionSelector` described below.
Class description:
An OptionSelector wraps an OptionList and an OK button, calling a callback when a selection is confirmed.
Method signatures and docstrings:
- def __init__(self, name, option_list, callback, width=200, lineheight=30): Initialise the Option... | c2fc3d4e9beedb8487cfa4bfa13bdf55ec36af97 | <|skeleton|>
class OptionSelector:
"""An OptionSelector wraps an OptionList and an OK button, calling a callback when a selection is confirmed."""
def __init__(self, name, option_list, callback, width=200, lineheight=30):
"""Initialise the OptionList. option_list is a list of strings to be displayed as... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OptionSelector:
"""An OptionSelector wraps an OptionList and an OK button, calling a callback when a selection is confirmed."""
def __init__(self, name, option_list, callback, width=200, lineheight=30):
"""Initialise the OptionList. option_list is a list of strings to be displayed as options. cal... | the_stack_v2_python_sparse | reference_scripts/clickndrag-0.4.1/clickndrag/gui.py | stivosaurus/rpi-snippets | train | 1 |
c63f533f5eac14370143dbe66260ac83c49ee556 | [
"session = DbManager.get_database_session()\nuser = session.query(User).filter_by(id=user_id).first()\nif user.role == 'cliente':\n events = user.created_events\nelif user.role == 'proveedor':\n events = user.get_associated_events_to_services()\nresponse = Utilities.list_to_json(events)\nsession.close()\nretu... | <|body_start_0|>
session = DbManager.get_database_session()
user = session.query(User).filter_by(id=user_id).first()
if user.role == 'cliente':
events = user.created_events
elif user.role == 'proveedor':
events = user.get_associated_events_to_services()
re... | EventsByUser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventsByUser:
def get(self, user_id):
"""Obtener los eventos de un usuario :param user_id: :return:"""
<|body_0|>
def post(self, user_id):
"""Crear un evento :param user_id: :return:"""
<|body_1|>
def delete(self, user_id, event_id):
"""Eliminar ... | stack_v2_sparse_classes_36k_train_029391 | 2,732 | no_license | [
{
"docstring": "Obtener los eventos de un usuario :param user_id: :return:",
"name": "get",
"signature": "def get(self, user_id)"
},
{
"docstring": "Crear un evento :param user_id: :return:",
"name": "post",
"signature": "def post(self, user_id)"
},
{
"docstring": "Eliminar un ev... | 3 | stack_v2_sparse_classes_30k_train_015555 | Implement the Python class `EventsByUser` described below.
Class description:
Implement the EventsByUser class.
Method signatures and docstrings:
- def get(self, user_id): Obtener los eventos de un usuario :param user_id: :return:
- def post(self, user_id): Crear un evento :param user_id: :return:
- def delete(self, ... | Implement the Python class `EventsByUser` described below.
Class description:
Implement the EventsByUser class.
Method signatures and docstrings:
- def get(self, user_id): Obtener los eventos de un usuario :param user_id: :return:
- def post(self, user_id): Crear un evento :param user_id: :return:
- def delete(self, ... | aa16640032cb85340a7d64781e521d752d2b4a95 | <|skeleton|>
class EventsByUser:
def get(self, user_id):
"""Obtener los eventos de un usuario :param user_id: :return:"""
<|body_0|>
def post(self, user_id):
"""Crear un evento :param user_id: :return:"""
<|body_1|>
def delete(self, user_id, event_id):
"""Eliminar ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EventsByUser:
def get(self, user_id):
"""Obtener los eventos de un usuario :param user_id: :return:"""
session = DbManager.get_database_session()
user = session.query(User).filter_by(id=user_id).first()
if user.role == 'cliente':
events = user.created_events
... | the_stack_v2_python_sparse | service/src/resources/events.py | Kaykos/concept | train | 0 | |
0ca722766ea05a0e7c3549fd1ce0fad9b044f265 | [
"super(LabelSmoothing, self).__init__()\nif eps == 0.0:\n self.criterion = nn.CrossEntropyLoss(ignore_index=pad_idx, reduction='sum')\nelse:\n self.criterion = nn.KLDivLoss(reduction='sum')\nself.pad_idx = pad_idx\nself.eps = eps\nself.trg_vocab_size = trg_vocab_size\nself.smoothed_dist = None",
"assert x.s... | <|body_start_0|>
super(LabelSmoothing, self).__init__()
if eps == 0.0:
self.criterion = nn.CrossEntropyLoss(ignore_index=pad_idx, reduction='sum')
else:
self.criterion = nn.KLDivLoss(reduction='sum')
self.pad_idx = pad_idx
self.eps = eps
self.trg_v... | Label Smoothing | LabelSmoothing | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LabelSmoothing:
"""Label Smoothing"""
def __init__(self, trg_vocab_size, pad_idx, eps=0.0):
"""- eps: smoothing parameters, set it 0.0 to use crossentropy ------------------------------------------------- ref: https://arxiv.org/pdf/1512.00567.pdf ref: http://nlp.seas.harvard.edu/2018... | stack_v2_sparse_classes_36k_train_029392 | 2,426 | no_license | [
{
"docstring": "- eps: smoothing parameters, set it 0.0 to use crossentropy ------------------------------------------------- ref: https://arxiv.org/pdf/1512.00567.pdf ref: http://nlp.seas.harvard.edu/2018/04/03/attention.html #7 - k : predict class - y : target class In Cross Entropy H(q, p) = -\\\\sum q(k|x) ... | 2 | stack_v2_sparse_classes_30k_test_000297 | Implement the Python class `LabelSmoothing` described below.
Class description:
Label Smoothing
Method signatures and docstrings:
- def __init__(self, trg_vocab_size, pad_idx, eps=0.0): - eps: smoothing parameters, set it 0.0 to use crossentropy ------------------------------------------------- ref: https://arxiv.org... | Implement the Python class `LabelSmoothing` described below.
Class description:
Label Smoothing
Method signatures and docstrings:
- def __init__(self, trg_vocab_size, pad_idx, eps=0.0): - eps: smoothing parameters, set it 0.0 to use crossentropy ------------------------------------------------- ref: https://arxiv.org... | 9c1e4988e5aba3d2b971074590ce49e50c3aa823 | <|skeleton|>
class LabelSmoothing:
"""Label Smoothing"""
def __init__(self, trg_vocab_size, pad_idx, eps=0.0):
"""- eps: smoothing parameters, set it 0.0 to use crossentropy ------------------------------------------------- ref: https://arxiv.org/pdf/1512.00567.pdf ref: http://nlp.seas.harvard.edu/2018... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LabelSmoothing:
"""Label Smoothing"""
def __init__(self, trg_vocab_size, pad_idx, eps=0.0):
"""- eps: smoothing parameters, set it 0.0 to use crossentropy ------------------------------------------------- ref: https://arxiv.org/pdf/1512.00567.pdf ref: http://nlp.seas.harvard.edu/2018/04/03/attent... | the_stack_v2_python_sparse | transformer/labelsmooth.py | simonjisu/annotated-transformer-kr | train | 17 |
14e5b466d4b5d3e6fe01d956793a48e31f80ebd3 | [
"super().__init__(coordinator)\nself.entity_description = description\nself._attr_name = f'{name} {description.name}'\nuuid = self.coordinator.data.get_uuid()\nself._attr_unique_id = f'{uuid}-{description.key}'",
"if (metric_key := self.entity_description.metric_key) is None:\n return None\nreturn self.coordin... | <|body_start_0|>
super().__init__(coordinator)
self.entity_description = description
self._attr_name = f'{name} {description.name}'
uuid = self.coordinator.data.get_uuid()
self._attr_unique_id = f'{uuid}-{description.key}'
<|end_body_0|>
<|body_start_1|>
if (metric_key :... | Representation of a Vallox sensor. | ValloxSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValloxSensor:
"""Representation of a Vallox sensor."""
def __init__(self, name: str, coordinator: ValloxDataUpdateCoordinator, description: ValloxSensorEntityDescription) -> None:
"""Initialize the Vallox sensor."""
<|body_0|>
def native_value(self) -> StateType | dateti... | stack_v2_sparse_classes_36k_train_029393 | 7,735 | permissive | [
{
"docstring": "Initialize the Vallox sensor.",
"name": "__init__",
"signature": "def __init__(self, name: str, coordinator: ValloxDataUpdateCoordinator, description: ValloxSensorEntityDescription) -> None"
},
{
"docstring": "Return the value reported by the sensor.",
"name": "native_value",... | 2 | null | Implement the Python class `ValloxSensor` described below.
Class description:
Representation of a Vallox sensor.
Method signatures and docstrings:
- def __init__(self, name: str, coordinator: ValloxDataUpdateCoordinator, description: ValloxSensorEntityDescription) -> None: Initialize the Vallox sensor.
- def native_v... | Implement the Python class `ValloxSensor` described below.
Class description:
Representation of a Vallox sensor.
Method signatures and docstrings:
- def __init__(self, name: str, coordinator: ValloxDataUpdateCoordinator, description: ValloxSensorEntityDescription) -> None: Initialize the Vallox sensor.
- def native_v... | 8f4ec89be6c2505d8a59eee44de335abe308ac9f | <|skeleton|>
class ValloxSensor:
"""Representation of a Vallox sensor."""
def __init__(self, name: str, coordinator: ValloxDataUpdateCoordinator, description: ValloxSensorEntityDescription) -> None:
"""Initialize the Vallox sensor."""
<|body_0|>
def native_value(self) -> StateType | dateti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ValloxSensor:
"""Representation of a Vallox sensor."""
def __init__(self, name: str, coordinator: ValloxDataUpdateCoordinator, description: ValloxSensorEntityDescription) -> None:
"""Initialize the Vallox sensor."""
super().__init__(coordinator)
self.entity_description = descripti... | the_stack_v2_python_sparse | homeassistant/components/vallox/sensor.py | JeffLIrion/home-assistant | train | 5 |
796586866a0924c6e2aae0f964067f7e2af7c499 | [
"kwargs = {}\nkwargs['status'] = 1\ntday = datetime.utcnow().replace(tzinfo=utc)\nkwargs['startingdate__lte'] = datetime(tday.year, tday.month, tday.day, tday.hour, tday.minute, tday.second, tday.microsecond).replace(tzinfo=utc)\nkwargs['expirationdate__gte'] = datetime(tday.year, tday.month, tday.day, tday.hour, t... | <|body_start_0|>
kwargs = {}
kwargs['status'] = 1
tday = datetime.utcnow().replace(tzinfo=utc)
kwargs['startingdate__lte'] = datetime(tday.year, tday.month, tday.day, tday.hour, tday.minute, tday.second, tday.microsecond).replace(tzinfo=utc)
kwargs['expirationdate__gte'] = dateti... | Campaign Manager | CampaignManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CampaignManager:
"""Campaign Manager"""
def get_running_campaign(self):
"""Return all the active campaigns which will be running based on the expiry date, the daily start/stop time and days of the week"""
<|body_0|>
def get_expired_campaign(self):
"""Return all t... | stack_v2_sparse_classes_36k_train_029394 | 27,513 | no_license | [
{
"docstring": "Return all the active campaigns which will be running based on the expiry date, the daily start/stop time and days of the week",
"name": "get_running_campaign",
"signature": "def get_running_campaign(self)"
},
{
"docstring": "Return all the campaigns which are expired or going to... | 2 | stack_v2_sparse_classes_30k_train_016521 | Implement the Python class `CampaignManager` described below.
Class description:
Campaign Manager
Method signatures and docstrings:
- def get_running_campaign(self): Return all the active campaigns which will be running based on the expiry date, the daily start/stop time and days of the week
- def get_expired_campaig... | Implement the Python class `CampaignManager` described below.
Class description:
Campaign Manager
Method signatures and docstrings:
- def get_running_campaign(self): Return all the active campaigns which will be running based on the expiry date, the daily start/stop time and days of the week
- def get_expired_campaig... | 2923a7d974f362af91b7c7c8f2e208cb2353c921 | <|skeleton|>
class CampaignManager:
"""Campaign Manager"""
def get_running_campaign(self):
"""Return all the active campaigns which will be running based on the expiry date, the daily start/stop time and days of the week"""
<|body_0|>
def get_expired_campaign(self):
"""Return all t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CampaignManager:
"""Campaign Manager"""
def get_running_campaign(self):
"""Return all the active campaigns which will be running based on the expiry date, the daily start/stop time and days of the week"""
kwargs = {}
kwargs['status'] = 1
tday = datetime.utcnow().replace(tz... | the_stack_v2_python_sparse | dialer_campaign/models.py | goksie/TheFies | train | 0 |
9ea1c2746cd676d8a16df87e9b920ae9f6c52dd6 | [
"top_n = 2\nseq_length = 4\nxlnet_base = _get_xlnet_base()\nxlnet_trainer_model = xlnet.XLNetSpanLabeler(network=xlnet_base, start_n_top=top_n, end_n_top=top_n, initializer=tf.keras.initializers.RandomNormal(stddev=0.1), span_labeling_activation='tanh', dropout_rate=0.1)\ninputs = dict(input_word_ids=tf.keras.layer... | <|body_start_0|>
top_n = 2
seq_length = 4
xlnet_base = _get_xlnet_base()
xlnet_trainer_model = xlnet.XLNetSpanLabeler(network=xlnet_base, start_n_top=top_n, end_n_top=top_n, initializer=tf.keras.initializers.RandomNormal(stddev=0.1), span_labeling_activation='tanh', dropout_rate=0.1)
... | XLNetSpanLabelerTest | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XLNetSpanLabelerTest:
def test_xlnet_trainer(self):
"""Validate that the Keras object can be created."""
<|body_0|>
def test_serialize_deserialize(self):
"""Validates that the XLNet trainer can be serialized and deserialized."""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_029395 | 13,124 | permissive | [
{
"docstring": "Validate that the Keras object can be created.",
"name": "test_xlnet_trainer",
"signature": "def test_xlnet_trainer(self)"
},
{
"docstring": "Validates that the XLNet trainer can be serialized and deserialized.",
"name": "test_serialize_deserialize",
"signature": "def tes... | 2 | stack_v2_sparse_classes_30k_train_007012 | Implement the Python class `XLNetSpanLabelerTest` described below.
Class description:
Implement the XLNetSpanLabelerTest class.
Method signatures and docstrings:
- def test_xlnet_trainer(self): Validate that the Keras object can be created.
- def test_serialize_deserialize(self): Validates that the XLNet trainer can ... | Implement the Python class `XLNetSpanLabelerTest` described below.
Class description:
Implement the XLNetSpanLabelerTest class.
Method signatures and docstrings:
- def test_xlnet_trainer(self): Validate that the Keras object can be created.
- def test_serialize_deserialize(self): Validates that the XLNet trainer can ... | 6fc53292b1d3ce3c0340ce724c2c11c77e663d27 | <|skeleton|>
class XLNetSpanLabelerTest:
def test_xlnet_trainer(self):
"""Validate that the Keras object can be created."""
<|body_0|>
def test_serialize_deserialize(self):
"""Validates that the XLNet trainer can be serialized and deserialized."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XLNetSpanLabelerTest:
def test_xlnet_trainer(self):
"""Validate that the Keras object can be created."""
top_n = 2
seq_length = 4
xlnet_base = _get_xlnet_base()
xlnet_trainer_model = xlnet.XLNetSpanLabeler(network=xlnet_base, start_n_top=top_n, end_n_top=top_n, initiali... | the_stack_v2_python_sparse | models/official/nlp/modeling/models/xlnet_test.py | aboerzel/German_License_Plate_Recognition | train | 34 | |
90ca908e6aa8c2b879eae8b7a43f7c67a125af19 | [
"super().initialize()\nself._remote_buttons_ambient_light = self.args.get('remote_buttons_ambient_light', {})\nfor remote_button_ambient_light in self._remote_buttons_ambient_light:\n self.listen_state(self.__on_ambient_light_button_pressed, remote_button_ambient_light)",
"if new == 'on':\n self.log('FIRE C... | <|body_start_0|>
super().initialize()
self._remote_buttons_ambient_light = self.args.get('remote_buttons_ambient_light', {})
for remote_button_ambient_light in self._remote_buttons_ambient_light:
self.listen_state(self.__on_ambient_light_button_pressed, remote_button_ambient_light)
<... | LightManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LightManager:
def initialize(self) -> None:
"""Initialize."""
<|body_0|>
def __on_ambient_light_button_pressed(self, entity: Union[str, dict], attribute: str, old: dict, new: dict, kwargs: dict) -> None:
"""called when ambient remote that button pressed on controlls"... | stack_v2_sparse_classes_36k_train_029396 | 1,380 | no_license | [
{
"docstring": "Initialize.",
"name": "initialize",
"signature": "def initialize(self) -> None"
},
{
"docstring": "called when ambient remote that button pressed on controlls",
"name": "__on_ambient_light_button_pressed",
"signature": "def __on_ambient_light_button_pressed(self, entity: ... | 2 | stack_v2_sparse_classes_30k_train_003233 | Implement the Python class `LightManager` described below.
Class description:
Implement the LightManager class.
Method signatures and docstrings:
- def initialize(self) -> None: Initialize.
- def __on_ambient_light_button_pressed(self, entity: Union[str, dict], attribute: str, old: dict, new: dict, kwargs: dict) -> N... | Implement the Python class `LightManager` described below.
Class description:
Implement the LightManager class.
Method signatures and docstrings:
- def initialize(self) -> None: Initialize.
- def __on_ambient_light_button_pressed(self, entity: Union[str, dict], attribute: str, old: dict, new: dict, kwargs: dict) -> N... | 2c027d10e0e3aa86d97c83d1b9c3124cf980d160 | <|skeleton|>
class LightManager:
def initialize(self) -> None:
"""Initialize."""
<|body_0|>
def __on_ambient_light_button_pressed(self, entity: Union[str, dict], attribute: str, old: dict, new: dict, kwargs: dict) -> None:
"""called when ambient remote that button pressed on controlls"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LightManager:
def initialize(self) -> None:
"""Initialize."""
super().initialize()
self._remote_buttons_ambient_light = self.args.get('remote_buttons_ambient_light', {})
for remote_button_ambient_light in self._remote_buttons_ambient_light:
self.listen_state(self.__... | the_stack_v2_python_sparse | appdaemon/apps/lights/light_manager.py | forksbot/hassio | train | 0 | |
1b585b2aceb3f79ffa82ffe93720519d8c079ba2 | [
"Simulator.__init__(self, state_set, action_set, modules)\nassert 'auctions' in modules.keys()\nassert 'clicks' in modules.keys()\nassert 'conversions' in modules.keys()\nassert 'revenue' in modules.keys()\nassert 'cpc' in modules.keys()",
"assert a in self.action_set\nN_A = self.modules['auctions'].sample()\nN_c... | <|body_start_0|>
Simulator.__init__(self, state_set, action_set, modules)
assert 'auctions' in modules.keys()
assert 'clicks' in modules.keys()
assert 'conversions' in modules.keys()
assert 'revenue' in modules.keys()
assert 'cpc' in modules.keys()
<|end_body_0|>
<|body_... | Auction simulator using conversion based revenue (a revenue is based on the number of conversions sampled from the number of clicks). :ivar list state_set: List of possible states. :ivar list action_set: List of valid actions. :ivar dict modules: Dictionary of modules used to model stochastic variables in the simulator... | SimulatorConversionBasedRevenue | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimulatorConversionBasedRevenue:
"""Auction simulator using conversion based revenue (a revenue is based on the number of conversions sampled from the number of clicks). :ivar list state_set: List of possible states. :ivar list action_set: List of valid actions. :ivar dict modules: Dictionary of ... | stack_v2_sparse_classes_36k_train_029397 | 40,659 | permissive | [
{
"docstring": ":param list state_set: List of possible states. :param list action_set: List of valid actions. :param dict modules: Dictionary of modules used to model stochastic variables in the simulator.",
"name": "__init__",
"signature": "def __init__(self, state_set, action_set, modules)"
},
{
... | 2 | null | Implement the Python class `SimulatorConversionBasedRevenue` described below.
Class description:
Auction simulator using conversion based revenue (a revenue is based on the number of conversions sampled from the number of clicks). :ivar list state_set: List of possible states. :ivar list action_set: List of valid acti... | Implement the Python class `SimulatorConversionBasedRevenue` described below.
Class description:
Auction simulator using conversion based revenue (a revenue is based on the number of conversions sampled from the number of clicks). :ivar list state_set: List of possible states. :ivar list action_set: List of valid acti... | ade886e9dcbde9fcea218a19f0130cc09f81e55e | <|skeleton|>
class SimulatorConversionBasedRevenue:
"""Auction simulator using conversion based revenue (a revenue is based on the number of conversions sampled from the number of clicks). :ivar list state_set: List of possible states. :ivar list action_set: List of valid actions. :ivar dict modules: Dictionary of ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimulatorConversionBasedRevenue:
"""Auction simulator using conversion based revenue (a revenue is based on the number of conversions sampled from the number of clicks). :ivar list state_set: List of possible states. :ivar list action_set: List of valid actions. :ivar dict modules: Dictionary of modules used ... | the_stack_v2_python_sparse | ssa_sim_v2/simulator/simulator.py | donghun2018/adclick-simulator-v2 | train | 0 |
994230ab0479ed58e3b84eb43673850649f3c682 | [
"data = self.data\ngroups = data.get('groups', [])\nslugs = {g.get('slug', '') for g in groups}\nreturn tuple(slugs)",
"payload = super().transform()\ndata = self.data\npayload[0]['fullname'] = data.get('fullname')\npayload[0]['email'] = data.get('email')\npayload[0]['data'] = {'FIRSTNAME': data.get('first_name')... | <|body_start_0|>
data = self.data
groups = data.get('groups', [])
slugs = {g.get('slug', '') for g in groups}
return tuple(slugs)
<|end_body_0|>
<|body_start_1|>
payload = super().transform()
data = self.data
payload[0]['fullname'] = data.get('fullname')
... | Base class for emails sent on User events. | UserMail | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserMail:
"""Base class for emails sent on User events."""
def user_groups_slugs(self) -> t.Sequence[str]:
"""Given the event data, return a sequence of group slugs. :return: Sequence of group slugs"""
<|body_0|>
def transform(self) -> t.List[dict]:
"""Transform ... | stack_v2_sparse_classes_36k_train_029398 | 4,062 | no_license | [
{
"docstring": "Given the event data, return a sequence of group slugs. :return: Sequence of group slugs",
"name": "user_groups_slugs",
"signature": "def user_groups_slugs(self) -> t.Sequence[str]"
},
{
"docstring": "Transform data.",
"name": "transform",
"signature": "def transform(self... | 2 | null | Implement the Python class `UserMail` described below.
Class description:
Base class for emails sent on User events.
Method signatures and docstrings:
- def user_groups_slugs(self) -> t.Sequence[str]: Given the event data, return a sequence of group slugs. :return: Sequence of group slugs
- def transform(self) -> t.L... | Implement the Python class `UserMail` described below.
Class description:
Base class for emails sent on User events.
Method signatures and docstrings:
- def user_groups_slugs(self) -> t.Sequence[str]: Given the event data, return a sequence of group slugs. :return: Sequence of group slugs
- def transform(self) -> t.L... | cca179f55ebc3c420426eff59b23d7c8963ca9a3 | <|skeleton|>
class UserMail:
"""Base class for emails sent on User events."""
def user_groups_slugs(self) -> t.Sequence[str]:
"""Given the event data, return a sequence of group slugs. :return: Sequence of group slugs"""
<|body_0|>
def transform(self) -> t.List[dict]:
"""Transform ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserMail:
"""Base class for emails sent on User events."""
def user_groups_slugs(self) -> t.Sequence[str]:
"""Given the event data, return a sequence of group slugs. :return: Sequence of group slugs"""
data = self.data
groups = data.get('groups', [])
slugs = {g.get('slug',... | the_stack_v2_python_sparse | src/briefy/choreographer/actions/mail/user.py | BriefyHQ/briefy.choreographer | train | 0 |
c0709abf22677b6e7f3185fdb1cf4b579b0db506 | [
"if not to_date:\n to_date = dt.date.today()\ntry:\n last_entry = self.latest('start_date')\nexcept UsageStats.DoesNotExist:\n start_date = dt.date(2014, 5, 5)\nelse:\n start_date = last_entry.start_date + dt.timedelta(7)\ncourt_list = Court.objects.filter(test_mode=False)\nwhile start_date + dt.timedel... | <|body_start_0|>
if not to_date:
to_date = dt.date.today()
try:
last_entry = self.latest('start_date')
except UsageStats.DoesNotExist:
start_date = dt.date(2014, 5, 5)
else:
start_date = last_entry.start_date + dt.timedelta(7)
court... | UsageStatsManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UsageStatsManager:
def calculate_weekly_stats(self, to_date=None):
"""Occupy UsageStats with the latest weekly aggregate stats. This function will create entries in UsageStats for each Monday from the last inserted date up to today. An associated management command runs this function."""... | stack_v2_sparse_classes_36k_train_029399 | 40,722 | permissive | [
{
"docstring": "Occupy UsageStats with the latest weekly aggregate stats. This function will create entries in UsageStats for each Monday from the last inserted date up to today. An associated management command runs this function.",
"name": "calculate_weekly_stats",
"signature": "def calculate_weekly_s... | 2 | null | Implement the Python class `UsageStatsManager` described below.
Class description:
Implement the UsageStatsManager class.
Method signatures and docstrings:
- def calculate_weekly_stats(self, to_date=None): Occupy UsageStats with the latest weekly aggregate stats. This function will create entries in UsageStats for ea... | Implement the Python class `UsageStatsManager` described below.
Class description:
Implement the UsageStatsManager class.
Method signatures and docstrings:
- def calculate_weekly_stats(self, to_date=None): Occupy UsageStats with the latest weekly aggregate stats. This function will create entries in UsageStats for ea... | 0b584b40a17654118201cac6be8b6ac3f302eda4 | <|skeleton|>
class UsageStatsManager:
def calculate_weekly_stats(self, to_date=None):
"""Occupy UsageStats with the latest weekly aggregate stats. This function will create entries in UsageStats for each Monday from the last inserted date up to today. An associated management command runs this function."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UsageStatsManager:
def calculate_weekly_stats(self, to_date=None):
"""Occupy UsageStats with the latest weekly aggregate stats. This function will create entries in UsageStats for each Monday from the last inserted date up to today. An associated management command runs this function."""
if no... | the_stack_v2_python_sparse | apps/plea/models.py | ministryofjustice/manchester_traffic_offences_pleas | train | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.