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
4fece7da81705a66820b035552fa8b9fa9ddcc6c
[ "super(LinearRegression, self).__init__()\nself.num_steps = 1\nself.define_placeholder(shape_x=[None, para.CONTINUOUS_WINDOW], shape_y=[None, para.NUM_CLASSES])\nself.define_parameters_totrack()", "with tf.name_scope('output'):\n W = self.weight_variable([para.CONTINUOUS_WINDOW, para.NUM_CLASSES])\n b = sel...
<|body_start_0|> super(LinearRegression, self).__init__() self.num_steps = 1 self.define_placeholder(shape_x=[None, para.CONTINUOUS_WINDOW], shape_y=[None, para.NUM_CLASSES]) self.define_parameters_totrack() <|end_body_0|> <|body_start_1|> with tf.name_scope('output'): ...
use linear regression for trend prediction.
LinearRegression
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LinearRegression: """use linear regression for trend prediction.""" def __init__(self): """init.""" <|body_0|> def inference(self, input): """use linear regression to output the result.""" <|body_1|> <|end_skeleton|> <|body_start_0|> super(Linea...
stack_v2_sparse_classes_36k_train_010000
1,122
no_license
[ { "docstring": "init.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "use linear regression to output the result.", "name": "inference", "signature": "def inference(self, input)" } ]
2
stack_v2_sparse_classes_30k_train_019310
Implement the Python class `LinearRegression` described below. Class description: use linear regression for trend prediction. Method signatures and docstrings: - def __init__(self): init. - def inference(self, input): use linear regression to output the result.
Implement the Python class `LinearRegression` described below. Class description: use linear regression for trend prediction. Method signatures and docstrings: - def __init__(self): init. - def inference(self, input): use linear regression to output the result. <|skeleton|> class LinearRegression: """use linear ...
bd792ea4aa052248b65002595c6613a43c63275e
<|skeleton|> class LinearRegression: """use linear regression for trend prediction.""" def __init__(self): """init.""" <|body_0|> def inference(self, input): """use linear regression to output the result.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LinearRegression: """use linear regression for trend prediction.""" def __init__(self): """init.""" super(LinearRegression, self).__init__() self.num_steps = 1 self.define_placeholder(shape_x=[None, para.CONTINUOUS_WINDOW], shape_y=[None, para.NUM_CLASSES]) self.de...
the_stack_v2_python_sparse
model/linearRegression.py
weilai0980/TrendNet
train
6
a5fc04de933383c7358c86eedacf8724925494b3
[ "r = re.compile('\\\\s+')\nsearch_target = r.sub('%20', search_target)\nenc_search_target = urllib.parse.quote_plus(search_target)\nurl = 'http://www.google.com/complete/search?hl=ja&q={}&output=toolbar'.format(enc_search_target)\nresponse = urllib.request.urlopen(url)\ntext = response.readlines()\ntext = text[0].d...
<|body_start_0|> r = re.compile('\\s+') search_target = r.sub('%20', search_target) enc_search_target = urllib.parse.quote_plus(search_target) url = 'http://www.google.com/complete/search?hl=ja&q={}&output=toolbar'.format(enc_search_target) response = urllib.request.urlopen(url) ...
GetGoogleSuggest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GetGoogleSuggest: def __init__(self, search_target, get_max_count=6): """XMLを読み込んでitemタグのリストを作る""" <|body_0|> def get_data(self): """欲しいデータがディクショナリ形式で入ったリストを返す""" <|body_1|> <|end_skeleton|> <|body_start_0|> r = re.compile('\\s+') search_tar...
stack_v2_sparse_classes_36k_train_010001
1,828
no_license
[ { "docstring": "XMLを読み込んでitemタグのリストを作る", "name": "__init__", "signature": "def __init__(self, search_target, get_max_count=6)" }, { "docstring": "欲しいデータがディクショナリ形式で入ったリストを返す", "name": "get_data", "signature": "def get_data(self)" } ]
2
stack_v2_sparse_classes_30k_train_000921
Implement the Python class `GetGoogleSuggest` described below. Class description: Implement the GetGoogleSuggest class. Method signatures and docstrings: - def __init__(self, search_target, get_max_count=6): XMLを読み込んでitemタグのリストを作る - def get_data(self): 欲しいデータがディクショナリ形式で入ったリストを返す
Implement the Python class `GetGoogleSuggest` described below. Class description: Implement the GetGoogleSuggest class. Method signatures and docstrings: - def __init__(self, search_target, get_max_count=6): XMLを読み込んでitemタグのリストを作る - def get_data(self): 欲しいデータがディクショナリ形式で入ったリストを返す <|skeleton|> class GetGoogleSuggest: ...
d70a0c21858e5d37a3cf3fca81b69ea7f73af661
<|skeleton|> class GetGoogleSuggest: def __init__(self, search_target, get_max_count=6): """XMLを読み込んでitemタグのリストを作る""" <|body_0|> def get_data(self): """欲しいデータがディクショナリ形式で入ったリストを返す""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GetGoogleSuggest: def __init__(self, search_target, get_max_count=6): """XMLを読み込んでitemタグのリストを作る""" r = re.compile('\\s+') search_target = r.sub('%20', search_target) enc_search_target = urllib.parse.quote_plus(search_target) url = 'http://www.google.com/complete/search?...
the_stack_v2_python_sparse
application/module/misc/get_googlesuggest.py
fujimisakari/otherbu
train
0
dfa701858419849bdcd76451123b7b224635bba0
[ "if crn is None:\n raise ValueError('crn must be provided')\nif zone_id is None:\n raise ValueError('zone_id must be provided')\nauthenticator = get_authenticator_from_environment(service_name)\nservice = cls(crn, zone_id, authenticator)\nservice.configure_service(service_name)\nreturn service", "if crn is ...
<|body_start_0|> if crn is None: raise ValueError('crn must be provided') if zone_id is None: raise ValueError('zone_id must be provided') authenticator = get_authenticator_from_environment(service_name) service = cls(crn, zone_id, authenticator) service.c...
The Security Events API V1 service.
SecurityEventsApiV1
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SecurityEventsApiV1: """The Security Events API V1 service.""" def new_instance(cls, crn: str, zone_id: str, service_name: str=DEFAULT_SERVICE_NAME) -> 'SecurityEventsApiV1': """Return a new client for the Security Events API service using the specified parameters and external config...
stack_v2_sparse_classes_36k_train_010002
39,687
permissive
[ { "docstring": "Return a new client for the Security Events API service using the specified parameters and external configuration. :param str crn: Full url-encoded cloud resource name (CRN) of resource instance. :param str zone_id: zone identifier.", "name": "new_instance", "signature": "def new_instanc...
3
stack_v2_sparse_classes_30k_train_009809
Implement the Python class `SecurityEventsApiV1` described below. Class description: The Security Events API V1 service. Method signatures and docstrings: - def new_instance(cls, crn: str, zone_id: str, service_name: str=DEFAULT_SERVICE_NAME) -> 'SecurityEventsApiV1': Return a new client for the Security Events API s...
Implement the Python class `SecurityEventsApiV1` described below. Class description: The Security Events API V1 service. Method signatures and docstrings: - def new_instance(cls, crn: str, zone_id: str, service_name: str=DEFAULT_SERVICE_NAME) -> 'SecurityEventsApiV1': Return a new client for the Security Events API s...
7eed5185f1e93a57e43d0d7a1e83ee8c708179e0
<|skeleton|> class SecurityEventsApiV1: """The Security Events API V1 service.""" def new_instance(cls, crn: str, zone_id: str, service_name: str=DEFAULT_SERVICE_NAME) -> 'SecurityEventsApiV1': """Return a new client for the Security Events API service using the specified parameters and external config...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SecurityEventsApiV1: """The Security Events API V1 service.""" def new_instance(cls, crn: str, zone_id: str, service_name: str=DEFAULT_SERVICE_NAME) -> 'SecurityEventsApiV1': """Return a new client for the Security Events API service using the specified parameters and external configuration. :par...
the_stack_v2_python_sparse
ibm_cloud_networking_services/security_events_api_v1.py
mauriceDevsM/networking-python-sdk
train
0
338a23412a8a3b71a47114e91227e4b6ec30f28e
[ "graph = [[1, 3], [0, 2], [1, 3], [0, 2]]\nself.assertEqual(is_bipartite(graph), True)\noutput = '\\n The graph looks like this:\\n 0----1\\n | |\\n | |\\n 3----2\\n We can divide the vertices into two groups: {0, 2} and {1, 3}.\\n '\nprint(f'Ex...
<|body_start_0|> graph = [[1, 3], [0, 2], [1, 3], [0, 2]] self.assertEqual(is_bipartite(graph), True) output = '\n The graph looks like this:\n 0----1\n | |\n | |\n 3----2\n We can divide the vertices into two groups: {0, 2} and {1,...
Unit test for is_bipartite.
TestIsBipartite
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestIsBipartite: """Unit test for is_bipartite.""" def test_1(self): """Test for graph: 0----1 | | | | 3----2""" <|body_0|> def test_2(self): """Test for graph: 0----1 | \\ | | \\ | 3----2""" <|body_1|> <|end_skeleton|> <|body_start_0|> graph = ...
stack_v2_sparse_classes_36k_train_010003
2,565
no_license
[ { "docstring": "Test for graph: 0----1 | | | | 3----2", "name": "test_1", "signature": "def test_1(self)" }, { "docstring": "Test for graph: 0----1 | \\\\ | | \\\\ | 3----2", "name": "test_2", "signature": "def test_2(self)" } ]
2
stack_v2_sparse_classes_30k_train_011083
Implement the Python class `TestIsBipartite` described below. Class description: Unit test for is_bipartite. Method signatures and docstrings: - def test_1(self): Test for graph: 0----1 | | | | 3----2 - def test_2(self): Test for graph: 0----1 | \\ | | \\ | 3----2
Implement the Python class `TestIsBipartite` described below. Class description: Unit test for is_bipartite. Method signatures and docstrings: - def test_1(self): Test for graph: 0----1 | | | | 3----2 - def test_2(self): Test for graph: 0----1 | \\ | | \\ | 3----2 <|skeleton|> class TestIsBipartite: """Unit test...
8105e1b20bf450a03a9bb910f344fc140e5ba703
<|skeleton|> class TestIsBipartite: """Unit test for is_bipartite.""" def test_1(self): """Test for graph: 0----1 | | | | 3----2""" <|body_0|> def test_2(self): """Test for graph: 0----1 | \\ | | \\ | 3----2""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestIsBipartite: """Unit test for is_bipartite.""" def test_1(self): """Test for graph: 0----1 | | | | 3----2""" graph = [[1, 3], [0, 2], [1, 3], [0, 2]] self.assertEqual(is_bipartite(graph), True) output = '\n The graph looks like this:\n 0----1\n ...
the_stack_v2_python_sparse
module_1/python/is_bipartite.py
vprusso/6-Weeks-to-Interview-Ready
train
6
03a92d81b28c99b16053ed2b71e9553298fb6e52
[ "super().__init__(data, batch_size=batch_size, epochs=epochs, input_size=input_size, blacklist=blacklist)\nself.rnd_pool_ = []\nself.rnd = RandomState(seed=random_seed)", "if not self.rnd_pool_:\n self.rnd_pool_ = self.rnd.randint(0, self.input_size - 1, self.batch_size * 10).tolist()\nreturn self.rnd_pool_.po...
<|body_start_0|> super().__init__(data, batch_size=batch_size, epochs=epochs, input_size=input_size, blacklist=blacklist) self.rnd_pool_ = [] self.rnd = RandomState(seed=random_seed) <|end_body_0|> <|body_start_1|> if not self.rnd_pool_: self.rnd_pool_ = self.rnd.randint(0, ...
Random sampling produces samples uniformly distributed from the input data. Individual samples are not guaranteed to be unique in the output, they can be repeated by the process of random sampling. The simplest usage of `RandomSampler` is no different than `OrderedSampler`: ```python sampler = RandomSampler(dataset) ba...
RandomSampler
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RandomSampler: """Random sampling produces samples uniformly distributed from the input data. Individual samples are not guaranteed to be unique in the output, they can be repeated by the process of random sampling. The simplest usage of `RandomSampler` is no different than `OrderedSampler`: ```p...
stack_v2_sparse_classes_36k_train_010004
2,026
permissive
[ { "docstring": "Parameters ---------- data TODO batch_size : int TODO epochs : int TODO input_size : int TODO blacklist : set TODO random_seed : int TODO", "name": "__init__", "signature": "def __init__(self, data, batch_size: int=128, epochs: int=None, input_size: int=None, blacklist: set=None, random_...
2
stack_v2_sparse_classes_30k_train_002254
Implement the Python class `RandomSampler` described below. Class description: Random sampling produces samples uniformly distributed from the input data. Individual samples are not guaranteed to be unique in the output, they can be repeated by the process of random sampling. The simplest usage of `RandomSampler` is n...
Implement the Python class `RandomSampler` described below. Class description: Random sampling produces samples uniformly distributed from the input data. Individual samples are not guaranteed to be unique in the output, they can be repeated by the process of random sampling. The simplest usage of `RandomSampler` is n...
4d37af1713b7f166ead3459a7004748f954d336e
<|skeleton|> class RandomSampler: """Random sampling produces samples uniformly distributed from the input data. Individual samples are not guaranteed to be unique in the output, they can be repeated by the process of random sampling. The simplest usage of `RandomSampler` is no different than `OrderedSampler`: ```p...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RandomSampler: """Random sampling produces samples uniformly distributed from the input data. Individual samples are not guaranteed to be unique in the output, they can be repeated by the process of random sampling. The simplest usage of `RandomSampler` is no different than `OrderedSampler`: ```python sampler...
the_stack_v2_python_sparse
bananas/sampling/random.py
owahltinez/bananas
train
0
2373044a9e7cddcff1bd79b34500cc44ae84909b
[ "def isPalindrome(i, j) -> bool:\n return s[i:j + 1] == s[i:j + 1][::-1]\ni = 0\ncount = 0\nslen = len(s)\nwhile i < slen:\n j = slen - 1\n while j >= i:\n if isPalindrome(i, j):\n count += 1\n j -= 1\n i += 1\nreturn count", "count = 0\nslen = len(s)\ni = 0\n\ndef isPalin(i, ...
<|body_start_0|> def isPalindrome(i, j) -> bool: return s[i:j + 1] == s[i:j + 1][::-1] i = 0 count = 0 slen = len(s) while i < slen: j = slen - 1 while j >= i: if isPalindrome(i, j): count += 1 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def countSubString(self, s) -> int: """:type s: String :return: int""" <|body_0|> def countString2(self, s): """while (i < len(s) -1) : within while loop : call inner method isPalin(i, j) where i = 0, j = len(s) -1 within isPalin - check if the subArray (i....
stack_v2_sparse_classes_36k_train_010005
1,558
no_license
[ { "docstring": ":type s: String :return: int", "name": "countSubString", "signature": "def countSubString(self, s) -> int" }, { "docstring": "while (i < len(s) -1) : within while loop : call inner method isPalin(i, j) where i = 0, j = len(s) -1 within isPalin - check if the subArray (i.e s[i:j] ...
2
stack_v2_sparse_classes_30k_train_007727
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countSubString(self, s) -> int: :type s: String :return: int - def countString2(self, s): while (i < len(s) -1) : within while loop : call inner method isPalin(i, j) where i ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countSubString(self, s) -> int: :type s: String :return: int - def countString2(self, s): while (i < len(s) -1) : within while loop : call inner method isPalin(i, j) where i ...
e3e076206b34ff6edf00596a03bc2b5911051cd8
<|skeleton|> class Solution: def countSubString(self, s) -> int: """:type s: String :return: int""" <|body_0|> def countString2(self, s): """while (i < len(s) -1) : within while loop : call inner method isPalin(i, j) where i = 0, j = len(s) -1 within isPalin - check if the subArray (i....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def countSubString(self, s) -> int: """:type s: String :return: int""" def isPalindrome(i, j) -> bool: return s[i:j + 1] == s[i:j + 1][::-1] i = 0 count = 0 slen = len(s) while i < slen: j = slen - 1 while j >= i: ...
the_stack_v2_python_sparse
Code/DataStructures/python/leetcode_ds/Py_PalindromicSubstrings_1.py
karanalang/technology
train
0
6f417cb8e15460a639c2c39bac57ede471f263c8
[ "node = root\nqueue = [node]\nwhile queue:\n node = queue.pop(0)\n if node.right:\n queue.append(node.right)\n if node.left:\n queue.append(node.left)\nreturn node.val", "queue = [root]\nfor node in queue:\n queue += filter(None, (node.right, node.left))\nreturn node.val" ]
<|body_start_0|> node = root queue = [node] while queue: node = queue.pop(0) if node.right: queue.append(node.right) if node.left: queue.append(node.left) return node.val <|end_body_0|> <|body_start_1|> queue = ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findBottomLeftValue(self, root): """:type root: TreeNode :rtype: int""" <|body_0|> def find_bottom_left_value(self, root): """pythonic :param root: TreeNode :return: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> node = root ...
stack_v2_sparse_classes_36k_train_010006
1,315
no_license
[ { "docstring": ":type root: TreeNode :rtype: int", "name": "findBottomLeftValue", "signature": "def findBottomLeftValue(self, root)" }, { "docstring": "pythonic :param root: TreeNode :return: int", "name": "find_bottom_left_value", "signature": "def find_bottom_left_value(self, root)" ...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findBottomLeftValue(self, root): :type root: TreeNode :rtype: int - def find_bottom_left_value(self, root): pythonic :param root: TreeNode :return: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findBottomLeftValue(self, root): :type root: TreeNode :rtype: int - def find_bottom_left_value(self, root): pythonic :param root: TreeNode :return: int <|skeleton|> class So...
215d513b3564a7a76db3d2b29e4acc341a68e8ee
<|skeleton|> class Solution: def findBottomLeftValue(self, root): """:type root: TreeNode :rtype: int""" <|body_0|> def find_bottom_left_value(self, root): """pythonic :param root: TreeNode :return: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def findBottomLeftValue(self, root): """:type root: TreeNode :rtype: int""" node = root queue = [node] while queue: node = queue.pop(0) if node.right: queue.append(node.right) if node.left: queue.appe...
the_stack_v2_python_sparse
python/tree/find-bottom-left-tree-value.py
euxuoh/leetcode
train
0
0c52e3ae22cfc15f691c9f03c5b58222eed69558
[ "current1 = l1\ncurrent2 = l2\nprev1 = None\nprev2 = None\nhead_of_merged = None\nend_of_merged = None\nwhile current1 is not None and current2 is not None:\n if current1.val <= current2.val:\n prev1 = current1\n current1 = current1.next\n prev1.next = None\n head_of_merged, end_of_me...
<|body_start_0|> current1 = l1 current2 = l2 prev1 = None prev2 = None head_of_merged = None end_of_merged = None while current1 is not None and current2 is not None: if current1.val <= current2.val: prev1 = current1 cur...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: """(Solution, ListNode, ListNode) -> ListNode Given two linked lists whose elements are in sorted order, return a new merged linked list containing elements of both lists in sorted order""" <|body_0|> ...
stack_v2_sparse_classes_36k_train_010007
2,464
no_license
[ { "docstring": "(Solution, ListNode, ListNode) -> ListNode Given two linked lists whose elements are in sorted order, return a new merged linked list containing elements of both lists in sorted order", "name": "mergeTwoLists", "signature": "def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: (Solution, ListNode, ListNode) -> ListNode Given two linked lists whose elements are in sorted order, return a ne...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: (Solution, ListNode, ListNode) -> ListNode Given two linked lists whose elements are in sorted order, return a ne...
6812253b90bdd5a35c6bfba8eac54da9be26d56c
<|skeleton|> class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: """(Solution, ListNode, ListNode) -> ListNode Given two linked lists whose elements are in sorted order, return a new merged linked list containing elements of both lists in sorted order""" <|body_0|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: """(Solution, ListNode, ListNode) -> ListNode Given two linked lists whose elements are in sorted order, return a new merged linked list containing elements of both lists in sorted order""" current1 = l1 current...
the_stack_v2_python_sparse
python3/mergeSortedLists.py
yichuanma95/leetcode-solns
train
2
0a3a6d5b043bf63b1612215436d68c6bf92dca3a
[ "pygame.sprite.Sprite.__init__(self)\nself.image = pygame.Surface((0, 0))\nself.rect = self.image.get_rect()", "too_long: bool = True\nfont: pygame.Font\nsize: int = 38\nif pygame.font:\n while too_long and size >= 10:\n size -= 2\n font = pygame.font.SysFont('Bauhaus 93', size)\n too_long...
<|body_start_0|> pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((0, 0)) self.rect = self.image.get_rect() <|end_body_0|> <|body_start_1|> too_long: bool = True font: pygame.Font size: int = 38 if pygame.font: while too_long and size >...
A message centered in the screen.
Message
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Message: """A message centered in the screen.""" def __init__(self) -> None: """Initialize from parameters.""" <|body_0|> def set_message(self, message: str, screen: pygame.Surface) -> bool: """Change to new message.""" <|body_1|> <|end_skeleton|> <|bod...
stack_v2_sparse_classes_36k_train_010008
15,940
no_license
[ { "docstring": "Initialize from parameters.", "name": "__init__", "signature": "def __init__(self) -> None" }, { "docstring": "Change to new message.", "name": "set_message", "signature": "def set_message(self, message: str, screen: pygame.Surface) -> bool" } ]
2
stack_v2_sparse_classes_30k_train_007268
Implement the Python class `Message` described below. Class description: A message centered in the screen. Method signatures and docstrings: - def __init__(self) -> None: Initialize from parameters. - def set_message(self, message: str, screen: pygame.Surface) -> bool: Change to new message.
Implement the Python class `Message` described below. Class description: A message centered in the screen. Method signatures and docstrings: - def __init__(self) -> None: Initialize from parameters. - def set_message(self, message: str, screen: pygame.Surface) -> bool: Change to new message. <|skeleton|> class Messa...
0fe17edf6ffcb35265032c6449d866b9434fda00
<|skeleton|> class Message: """A message centered in the screen.""" def __init__(self) -> None: """Initialize from parameters.""" <|body_0|> def set_message(self, message: str, screen: pygame.Surface) -> bool: """Change to new message.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Message: """A message centered in the screen.""" def __init__(self) -> None: """Initialize from parameters.""" pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((0, 0)) self.rect = self.image.get_rect() def set_message(self, message: str, screen: pygame....
the_stack_v2_python_sparse
Chapter11TextbookCode/Listing 11-4.py
ProfessorBurke/PythonObjectsGames
train
3
c1fb96d281ff340126642b38e421cb45381803dd
[ "config = current_app.cea_config\ndashboards = cea.plots.read_dashboards(config, current_app.plot_cache)\nreturn dashboard_to_dict(dashboards[dashboard_index])", "config = current_app.cea_config\ncea.plots.delete_dashboard(config, dashboard_index)\nreturn {'message': 'deleted dashboard'}", "form = api.payload\n...
<|body_start_0|> config = current_app.cea_config dashboards = cea.plots.read_dashboards(config, current_app.plot_cache) return dashboard_to_dict(dashboards[dashboard_index]) <|end_body_0|> <|body_start_1|> config = current_app.cea_config cea.plots.delete_dashboard(config, dashbo...
Dashboard
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Dashboard: def get(self, dashboard_index): """Get Dashboard""" <|body_0|> def delete(self, dashboard_index): """Delete Dashboard""" <|body_1|> def patch(self, dashboard_index): """Update Dashboard properties""" <|body_2|> <|end_skeleton|...
stack_v2_sparse_classes_36k_train_010009
9,106
permissive
[ { "docstring": "Get Dashboard", "name": "get", "signature": "def get(self, dashboard_index)" }, { "docstring": "Delete Dashboard", "name": "delete", "signature": "def delete(self, dashboard_index)" }, { "docstring": "Update Dashboard properties", "name": "patch", "signatu...
3
stack_v2_sparse_classes_30k_train_008658
Implement the Python class `Dashboard` described below. Class description: Implement the Dashboard class. Method signatures and docstrings: - def get(self, dashboard_index): Get Dashboard - def delete(self, dashboard_index): Delete Dashboard - def patch(self, dashboard_index): Update Dashboard properties
Implement the Python class `Dashboard` described below. Class description: Implement the Dashboard class. Method signatures and docstrings: - def get(self, dashboard_index): Get Dashboard - def delete(self, dashboard_index): Delete Dashboard - def patch(self, dashboard_index): Update Dashboard properties <|skeleton|...
b84bcefdfdfc2bc0e009b5284b74391a957995ac
<|skeleton|> class Dashboard: def get(self, dashboard_index): """Get Dashboard""" <|body_0|> def delete(self, dashboard_index): """Delete Dashboard""" <|body_1|> def patch(self, dashboard_index): """Update Dashboard properties""" <|body_2|> <|end_skeleton|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Dashboard: def get(self, dashboard_index): """Get Dashboard""" config = current_app.cea_config dashboards = cea.plots.read_dashboards(config, current_app.plot_cache) return dashboard_to_dict(dashboards[dashboard_index]) def delete(self, dashboard_index): """Delete ...
the_stack_v2_python_sparse
cea/interfaces/dashboard/api/dashboard.py
architecture-building-systems/CityEnergyAnalyst
train
166
c7e8906553914cb951cb023b1af42c20752c8be1
[ "assert_pycocotools_installed('PyCOCOWrapper')\nCOCO.__init__(self, annotation_file=None)\nself._eval_type = 'box'\nif gt_dataset:\n self.dataset = gt_dataset\n self.createIndex()", "res = COCO()\nres.dataset['images'] = copy.deepcopy(self.dataset['images'])\nres.dataset['categories'] = copy.deepcopy(self.d...
<|body_start_0|> assert_pycocotools_installed('PyCOCOWrapper') COCO.__init__(self, annotation_file=None) self._eval_type = 'box' if gt_dataset: self.dataset = gt_dataset self.createIndex() <|end_body_0|> <|body_start_1|> res = COCO() res.dataset['...
COCO wrapper class. This class wraps COCO API object, which provides the following additional functionalities: 1. Support string type image id. 2. Support loading the groundtruth dataset using the external annotation dictionary. 3. Support loading the prediction results using the external annotation dictionary.
PyCOCOWrapper
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PyCOCOWrapper: """COCO wrapper class. This class wraps COCO API object, which provides the following additional functionalities: 1. Support string type image id. 2. Support loading the groundtruth dataset using the external annotation dictionary. 3. Support loading the prediction results using th...
stack_v2_sparse_classes_36k_train_010010
8,149
permissive
[ { "docstring": "Instantiates a COCO-style API object. Args: eval_type: either 'box' or 'mask'. annotation_file: a JSON file that stores annotations of the eval dataset. This is required if `gt_dataset` is not provided. gt_dataset: the groundtruth eval dataset in COCO API format.", "name": "__init__", "s...
2
stack_v2_sparse_classes_30k_test_000313
Implement the Python class `PyCOCOWrapper` described below. Class description: COCO wrapper class. This class wraps COCO API object, which provides the following additional functionalities: 1. Support string type image id. 2. Support loading the groundtruth dataset using the external annotation dictionary. 3. Support ...
Implement the Python class `PyCOCOWrapper` described below. Class description: COCO wrapper class. This class wraps COCO API object, which provides the following additional functionalities: 1. Support string type image id. 2. Support loading the groundtruth dataset using the external annotation dictionary. 3. Support ...
e83f229f1b7b847cd712d5cd4810097d3e06d14e
<|skeleton|> class PyCOCOWrapper: """COCO wrapper class. This class wraps COCO API object, which provides the following additional functionalities: 1. Support string type image id. 2. Support loading the groundtruth dataset using the external annotation dictionary. 3. Support loading the prediction results using th...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PyCOCOWrapper: """COCO wrapper class. This class wraps COCO API object, which provides the following additional functionalities: 1. Support string type image id. 2. Support loading the groundtruth dataset using the external annotation dictionary. 3. Support loading the prediction results using the external an...
the_stack_v2_python_sparse
keras_cv/metrics/coco/pycoco_wrapper.py
keras-team/keras-cv
train
818
f30f7723054f61236e0a227abffbe041122e92e5
[ "main.clear_collections()\nresult = main.import_data('./data/', 'products', 'customers', 'rentals')\nself.assertEqual(result[0][1], 1000)\nself.assertEqual(result[0][2], 0)\nself.assertEqual(result[1][0], 'products')\nself.assertEqual(result[1][3], 1000)\nself.assertEqual(result[2][2], 0)\nself.assertGreater(result...
<|body_start_0|> main.clear_collections() result = main.import_data('./data/', 'products', 'customers', 'rentals') self.assertEqual(result[0][1], 1000) self.assertEqual(result[0][2], 0) self.assertEqual(result[1][0], 'products') self.assertEqual(result[1][3], 1000) ...
Class for testing HP Norton database
ModuleTests
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ModuleTests: """Class for testing HP Norton database""" def test_import_data(self): """Test CSV import and correct database insertion functionality""" <|body_0|> def test_failed_import_data(self): """Test CSV import failure""" <|body_1|> def test_sho...
stack_v2_sparse_classes_36k_train_010011
2,539
no_license
[ { "docstring": "Test CSV import and correct database insertion functionality", "name": "test_import_data", "signature": "def test_import_data(self)" }, { "docstring": "Test CSV import failure", "name": "test_failed_import_data", "signature": "def test_failed_import_data(self)" }, { ...
4
null
Implement the Python class `ModuleTests` described below. Class description: Class for testing HP Norton database Method signatures and docstrings: - def test_import_data(self): Test CSV import and correct database insertion functionality - def test_failed_import_data(self): Test CSV import failure - def test_show_av...
Implement the Python class `ModuleTests` described below. Class description: Class for testing HP Norton database Method signatures and docstrings: - def test_import_data(self): Test CSV import and correct database insertion functionality - def test_failed_import_data(self): Test CSV import failure - def test_show_av...
5dac60f39e3909ff05b26721d602ed20f14d6be3
<|skeleton|> class ModuleTests: """Class for testing HP Norton database""" def test_import_data(self): """Test CSV import and correct database insertion functionality""" <|body_0|> def test_failed_import_data(self): """Test CSV import failure""" <|body_1|> def test_sho...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ModuleTests: """Class for testing HP Norton database""" def test_import_data(self): """Test CSV import and correct database insertion functionality""" main.clear_collections() result = main.import_data('./data/', 'products', 'customers', 'rentals') self.assertEqual(result[...
the_stack_v2_python_sparse
students/stellie/lesson07/assignment/test_linear.py
JavaRod/SP_Python220B_2019
train
1
defce6771f3c747bb26af5b3e0de29b0f1874a5e
[ "cross = tensor([[[0, 1, 0], [1, 1, 1], [0, 1, 0]]])\nbound = tensor([[[0, 0, 0], [0, 1, 0], [0, 0, 0]]])\nkernel = stack([bound, cross, bound], 1) * (1 / 7)\nreturn kernel[None]", "if pred.dim() != 5:\n raise ValueError(f'Only 3D images supported. Got {pred.dim()}.')\nreturn super().forward(pred, target)" ]
<|body_start_0|> cross = tensor([[[0, 1, 0], [1, 1, 1], [0, 1, 0]]]) bound = tensor([[[0, 0, 0], [0, 1, 0], [0, 0, 0]]]) kernel = stack([bound, cross, bound], 1) * (1 / 7) return kernel[None] <|end_body_0|> <|body_start_1|> if pred.dim() != 5: raise ValueError(f'Only...
Binary 3D Hausdorff loss based on morphological erosion. Hausdorff Distance loss measures the maximum distance of a predicted segmentation boundary to the nearest ground-truth edge pixel. For two segmentation point sets X and Y , the one-sided HD from X to Y is defined as: .. math:: hd(X,Y) = \\max_{x \\in X} \\min_{y ...
HausdorffERLoss3D
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HausdorffERLoss3D: """Binary 3D Hausdorff loss based on morphological erosion. Hausdorff Distance loss measures the maximum distance of a predicted segmentation boundary to the nearest ground-truth edge pixel. For two segmentation point sets X and Y , the one-sided HD from X to Y is defined as: ....
stack_v2_sparse_classes_36k_train_010012
9,826
permissive
[ { "docstring": "Get kernel for image morphology convolution.", "name": "get_kernel", "signature": "def get_kernel(self) -> Tensor" }, { "docstring": "Compute 3D Hausdorff loss. Args: pred: predicted tensor with a shape of :math:`(B, C, D, H, W)`. Each channel is as binary as: 1 -> fg, 0 -> bg. t...
2
stack_v2_sparse_classes_30k_train_016439
Implement the Python class `HausdorffERLoss3D` described below. Class description: Binary 3D Hausdorff loss based on morphological erosion. Hausdorff Distance loss measures the maximum distance of a predicted segmentation boundary to the nearest ground-truth edge pixel. For two segmentation point sets X and Y , the on...
Implement the Python class `HausdorffERLoss3D` described below. Class description: Binary 3D Hausdorff loss based on morphological erosion. Hausdorff Distance loss measures the maximum distance of a predicted segmentation boundary to the nearest ground-truth edge pixel. For two segmentation point sets X and Y , the on...
1e0f8baa7318c05b17ea6dbb48605691bca8972f
<|skeleton|> class HausdorffERLoss3D: """Binary 3D Hausdorff loss based on morphological erosion. Hausdorff Distance loss measures the maximum distance of a predicted segmentation boundary to the nearest ground-truth edge pixel. For two segmentation point sets X and Y , the one-sided HD from X to Y is defined as: ....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HausdorffERLoss3D: """Binary 3D Hausdorff loss based on morphological erosion. Hausdorff Distance loss measures the maximum distance of a predicted segmentation boundary to the nearest ground-truth edge pixel. For two segmentation point sets X and Y , the one-sided HD from X to Y is defined as: .. math:: hd(X...
the_stack_v2_python_sparse
kornia/losses/hausdorff.py
kornia/kornia
train
7,351
5733999d4b86225b12dfd80042180415e535018e
[ "ans = bal = 0\nfor symbol in S:\n bal += 1 if symbol == '(' else -1\n if bal == -1:\n ans += 1\n bal += 1\nreturn ans + bal", "while '()' in S:\n S = S.replace('()', '')\nreturn len(S)" ]
<|body_start_0|> ans = bal = 0 for symbol in S: bal += 1 if symbol == '(' else -1 if bal == -1: ans += 1 bal += 1 return ans + bal <|end_body_0|> <|body_start_1|> while '()' in S: S = S.replace('()', '') return ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def minAddToMakeValid(self, S): """解法1:利用)不能再匹配成功的原理,用bal计数balance当前的结果。 比较技巧性的解法,bal维持一个balance,一直在-1,0,n之间浮动 symobol = '('则+1,=')'则-1, bal=0,代表目前凑对成功, bal=-1代表目前剩余一个')',此时就ans+=1,把这个多余的')'计数到最后结果,因为)不可能再匹配成功了,且bal+=1置为0 bal=n,代表剩余n个'(',还有希望匹配成功。""" <|body_0|> def...
stack_v2_sparse_classes_36k_train_010013
1,364
no_license
[ { "docstring": "解法1:利用)不能再匹配成功的原理,用bal计数balance当前的结果。 比较技巧性的解法,bal维持一个balance,一直在-1,0,n之间浮动 symobol = '('则+1,=')'则-1, bal=0,代表目前凑对成功, bal=-1代表目前剩余一个')',此时就ans+=1,把这个多余的')'计数到最后结果,因为)不可能再匹配成功了,且bal+=1置为0 bal=n,代表剩余n个'(',还有希望匹配成功。", "name": "minAddToMakeValid", "signature": "def minAddToMakeValid(self, S)...
2
stack_v2_sparse_classes_30k_train_015766
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minAddToMakeValid(self, S): 解法1:利用)不能再匹配成功的原理,用bal计数balance当前的结果。 比较技巧性的解法,bal维持一个balance,一直在-1,0,n之间浮动 symobol = '('则+1,=')'则-1, bal=0,代表目前凑对成功, bal=-1代表目前剩余一个')',此时就ans+=1,...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minAddToMakeValid(self, S): 解法1:利用)不能再匹配成功的原理,用bal计数balance当前的结果。 比较技巧性的解法,bal维持一个balance,一直在-1,0,n之间浮动 symobol = '('则+1,=')'则-1, bal=0,代表目前凑对成功, bal=-1代表目前剩余一个')',此时就ans+=1,...
18c06a96bb14688e4a1d5fb6baf235a6b53bd3ae
<|skeleton|> class Solution: def minAddToMakeValid(self, S): """解法1:利用)不能再匹配成功的原理,用bal计数balance当前的结果。 比较技巧性的解法,bal维持一个balance,一直在-1,0,n之间浮动 symobol = '('则+1,=')'则-1, bal=0,代表目前凑对成功, bal=-1代表目前剩余一个')',此时就ans+=1,把这个多余的')'计数到最后结果,因为)不可能再匹配成功了,且bal+=1置为0 bal=n,代表剩余n个'(',还有希望匹配成功。""" <|body_0|> def...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def minAddToMakeValid(self, S): """解法1:利用)不能再匹配成功的原理,用bal计数balance当前的结果。 比较技巧性的解法,bal维持一个balance,一直在-1,0,n之间浮动 symobol = '('则+1,=')'则-1, bal=0,代表目前凑对成功, bal=-1代表目前剩余一个')',此时就ans+=1,把这个多余的')'计数到最后结果,因为)不可能再匹配成功了,且bal+=1置为0 bal=n,代表剩余n个'(',还有希望匹配成功。""" ans = bal = 0 for symbol ...
the_stack_v2_python_sparse
medium/others/minimum-add-to-make-parentheses-valid.py
congyingTech/Basic-Algorithm
train
10
26ff039ab9f070e6116b9ddffd9e3e28df03564e
[ "super().__init__()\nself.input_channel_size = input_channels\nself.output_channel_size = output_channels\nself.num_nodes = num_nodes\nself.parallel_strategy = parallel_strategy\nself.instance = 0\nself.is_distconv = False\nif parallel_strategy:\n if list(parallel_strategy.values()[0]) > 0:\n self.is_dist...
<|body_start_0|> super().__init__() self.input_channel_size = input_channels self.output_channel_size = output_channels self.num_nodes = num_nodes self.parallel_strategy = parallel_strategy self.instance = 0 self.is_distconv = False if parallel_strategy: ...
GCN Conv later. See: https://arxiv.org/abs/1609.02907
GCNConv
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GCNConv: """GCN Conv later. See: https://arxiv.org/abs/1609.02907""" def __init__(self, input_channels, output_channels, num_nodes, bias=True, activation=lbann.Relu, name=None, parallel_strategy={}): """Initialize GCN layer Args: input_channels (int): The size of the input node featu...
stack_v2_sparse_classes_36k_train_010014
5,080
permissive
[ { "docstring": "Initialize GCN layer Args: input_channels (int): The size of the input node features output_channels (int): The output size of the node features num_nodes (int): Number of vertices in the graph bias (bool): Whether to apply biases after weights transform activation (type): Activation leyer for t...
2
null
Implement the Python class `GCNConv` described below. Class description: GCN Conv later. See: https://arxiv.org/abs/1609.02907 Method signatures and docstrings: - def __init__(self, input_channels, output_channels, num_nodes, bias=True, activation=lbann.Relu, name=None, parallel_strategy={}): Initialize GCN layer Arg...
Implement the Python class `GCNConv` described below. Class description: GCN Conv later. See: https://arxiv.org/abs/1609.02907 Method signatures and docstrings: - def __init__(self, input_channels, output_channels, num_nodes, bias=True, activation=lbann.Relu, name=None, parallel_strategy={}): Initialize GCN layer Arg...
e8cf85eed2acbd3383892bf7cb2d88b44c194f4f
<|skeleton|> class GCNConv: """GCN Conv later. See: https://arxiv.org/abs/1609.02907""" def __init__(self, input_channels, output_channels, num_nodes, bias=True, activation=lbann.Relu, name=None, parallel_strategy={}): """Initialize GCN layer Args: input_channels (int): The size of the input node featu...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GCNConv: """GCN Conv later. See: https://arxiv.org/abs/1609.02907""" def __init__(self, input_channels, output_channels, num_nodes, bias=True, activation=lbann.Relu, name=None, parallel_strategy={}): """Initialize GCN layer Args: input_channels (int): The size of the input node features output_ch...
the_stack_v2_python_sparse
python/lbann/modules/graph/sparse/GCNConv.py
LLNL/lbann
train
225
4d8412de4fc831bfbb7f9eaba085fe5a1788f24c
[ "if not root:\n return ''\nstack = [root]\nres = ''\nwhile stack:\n childs = []\n for node in stack:\n if not node:\n res += ','\n childs.append(None)\n childs.append(None)\n else:\n res += str(node.val) + ','\n childs.append(node.left)\n...
<|body_start_0|> if not root: return '' stack = [root] res = '' while stack: childs = [] for node in stack: if not node: res += ',' childs.append(None) childs.append(None) ...
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_010015
2,077
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
null
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
14dcf9029486283b5e4685d95ebfe9979ade03c3
<|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 '' stack = [root] res = '' while stack: childs = [] for node in stack: if not node: ...
the_stack_v2_python_sparse
449-SerializeandDeserializeBST.py
dq-code/leetcode
train
0
ca7d1013e72b241f8bb21e2ccb9cd40fdf9528bf
[ "try:\n results = self.api.photosets.getList(user_id=self.account.user.nsid, per_page=self.items_per_page, page=self.page_number)\nexcept FlickrError as e:\n raise FetchError('Error when fetching photosets (page %s): %s' % (self.page_number, e))\nif self.page_number == 1 and 'photosets' in results and ('pages...
<|body_start_0|> try: results = self.api.photosets.getList(user_id=self.account.user.nsid, per_page=self.items_per_page, page=self.page_number) except FlickrError as e: raise FetchError('Error when fetching photosets (page %s): %s' % (self.page_number, e)) if self.page_nu...
PhotosetsFetcher
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PhotosetsFetcher: def _call_api(self): """Fetch one page of results. https://www.flickr.com/services/api/flickr.photosets.getList.htm""" <|body_0|> def _fetch_extra(self): """Before saving we need to get the list of photos in each photoset.""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_010016
20,064
permissive
[ { "docstring": "Fetch one page of results. https://www.flickr.com/services/api/flickr.photosets.getList.htm", "name": "_call_api", "signature": "def _call_api(self)" }, { "docstring": "Before saving we need to get the list of photos in each photoset.", "name": "_fetch_extra", "signature"...
4
null
Implement the Python class `PhotosetsFetcher` described below. Class description: Implement the PhotosetsFetcher class. Method signatures and docstrings: - def _call_api(self): Fetch one page of results. https://www.flickr.com/services/api/flickr.photosets.getList.htm - def _fetch_extra(self): Before saving we need t...
Implement the Python class `PhotosetsFetcher` described below. Class description: Implement the PhotosetsFetcher class. Method signatures and docstrings: - def _call_api(self): Fetch one page of results. https://www.flickr.com/services/api/flickr.photosets.getList.htm - def _fetch_extra(self): Before saving we need t...
57ee6f6657b41705af71ef67924d8ef06c60ae4f
<|skeleton|> class PhotosetsFetcher: def _call_api(self): """Fetch one page of results. https://www.flickr.com/services/api/flickr.photosets.getList.htm""" <|body_0|> def _fetch_extra(self): """Before saving we need to get the list of photos in each photoset.""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PhotosetsFetcher: def _call_api(self): """Fetch one page of results. https://www.flickr.com/services/api/flickr.photosets.getList.htm""" try: results = self.api.photosets.getList(user_id=self.account.user.nsid, per_page=self.items_per_page, page=self.page_number) except Fli...
the_stack_v2_python_sparse
ditto/flickr/fetch/fetchers.py
philgyford/django-ditto
train
59
102348c4c95182462ffd019aceb4e040eaee7bbf
[ "if not issubclass(encodable, Encodable):\n msg = 'EncodableRegistry only accepts Encodable subclasses for registration. Got: {encodable}'\n error = ValueError(msg, encodable, reg_args)\n raise self._log_exception(error, msg)\nreturn True", "try:\n name = encodable.type_field()\nexcept NotImplementedE...
<|body_start_0|> if not issubclass(encodable, Encodable): msg = 'EncodableRegistry only accepts Encodable subclasses for registration. Got: {encodable}' error = ValueError(msg, encodable, reg_args) raise self._log_exception(error, msg) return True <|end_body_0|> <|bo...
Registry for all the encodable types.
EncodableRegistry
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EncodableRegistry: """Registry for all the encodable types.""" def _init_register(self, encodable: Type[Encodable], reg_args: Iterable[str]) -> bool: """This is called before anything happens in `register()`. Raise an error if a non-Encodable class tries to register.""" <|bod...
stack_v2_sparse_classes_36k_train_010017
12,550
no_license
[ { "docstring": "This is called before anything happens in `register()`. Raise an error if a non-Encodable class tries to register.", "name": "_init_register", "signature": "def _init_register(self, encodable: Type[Encodable], reg_args: Iterable[str]) -> bool" }, { "docstring": "We want to regist...
5
null
Implement the Python class `EncodableRegistry` described below. Class description: Registry for all the encodable types. Method signatures and docstrings: - def _init_register(self, encodable: Type[Encodable], reg_args: Iterable[str]) -> bool: This is called before anything happens in `register()`. Raise an error if ...
Implement the Python class `EncodableRegistry` described below. Class description: Registry for all the encodable types. Method signatures and docstrings: - def _init_register(self, encodable: Type[Encodable], reg_args: Iterable[str]) -> bool: This is called before anything happens in `register()`. Raise an error if ...
8c9fc1170ceac335985686571568eebf08b0db7a
<|skeleton|> class EncodableRegistry: """Registry for all the encodable types.""" def _init_register(self, encodable: Type[Encodable], reg_args: Iterable[str]) -> bool: """This is called before anything happens in `register()`. Raise an error if a non-Encodable class tries to register.""" <|bod...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EncodableRegistry: """Registry for all the encodable types.""" def _init_register(self, encodable: Type[Encodable], reg_args: Iterable[str]) -> bool: """This is called before anything happens in `register()`. Raise an error if a non-Encodable class tries to register.""" if not issubclass(...
the_stack_v2_python_sparse
data/codec/registry.py
cole-brown/veredi-code
train
1
646d8b468b6646117d08b8bc81eae2e7936ff9e3
[ "result = {}\noutput = []\nfor i in nums:\n result[i] = result.get(i, 0) + 1\nfor k, v in result.items():\n if v == 1:\n output.append(k)\nreturn output", "res1, res2 = (0, 0)\nfor num in nums:\n res1 ^= num\nfor num in nums[::-1]:\n res2 ^= num\nreturn [res1, res2]" ]
<|body_start_0|> result = {} output = [] for i in nums: result[i] = result.get(i, 0) + 1 for k, v in result.items(): if v == 1: output.append(k) return output <|end_body_0|> <|body_start_1|> res1, res2 = (0, 0) for num in n...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def singleNumber_1(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def singleNumber_2(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> result = {} output = [] ...
stack_v2_sparse_classes_36k_train_010018
672
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "singleNumber_1", "signature": "def singleNumber_1(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "singleNumber_2", "signature": "def singleNumber_2(self, nums)" } ]
2
stack_v2_sparse_classes_30k_train_003661
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def singleNumber_1(self, nums): :type nums: List[int] :rtype: int - def singleNumber_2(self, nums): :type nums: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def singleNumber_1(self, nums): :type nums: List[int] :rtype: int - def singleNumber_2(self, nums): :type nums: List[int] :rtype: int <|skeleton|> class Solution: def singl...
8a62b397a5fa107c70efc8ea65d0edfb74f8baa7
<|skeleton|> class Solution: def singleNumber_1(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def singleNumber_2(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def singleNumber_1(self, nums): """:type nums: List[int] :rtype: int""" result = {} output = [] for i in nums: result[i] = result.get(i, 0) + 1 for k, v in result.items(): if v == 1: output.append(k) return outpu...
the_stack_v2_python_sparse
LeetCode-Solution/Algorithms/Single-Number-III.py
LFYG/leetcode-acm-euler-other
train
0
048e1ff72a18e453b02fb3b9308a630fecbbb5a9
[ "if not form.is_valid():\n return\nurl = form.cleaned_data.get('url', None)\nresponse = requests.get(url, stream=True)\ncontent_length = response.headers.get('Content-Length', '0')\ntry:\n content_length = int(content_length)\nexcept ValueError:\n content_length = 0\nMAX_IMG_LENGTH = 10 * 1024 * 1024\nif c...
<|body_start_0|> if not form.is_valid(): return url = form.cleaned_data.get('url', None) response = requests.get(url, stream=True) content_length = response.headers.get('Content-Length', '0') try: content_length = int(content_length) except ValueEr...
View for downloading an image from a provided URL
CompanyImageDownloadFromURL
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CompanyImageDownloadFromURL: """View for downloading an image from a provided URL""" def validate(self, company, form): """Validate that the image data are correct""" <|body_0|> def save(self, company, form, **kwargs): """Save the downloaded image to the company"...
stack_v2_sparse_classes_36k_train_010019
6,294
permissive
[ { "docstring": "Validate that the image data are correct", "name": "validate", "signature": "def validate(self, company, form)" }, { "docstring": "Save the downloaded image to the company", "name": "save", "signature": "def save(self, company, form, **kwargs)" } ]
2
null
Implement the Python class `CompanyImageDownloadFromURL` described below. Class description: View for downloading an image from a provided URL Method signatures and docstrings: - def validate(self, company, form): Validate that the image data are correct - def save(self, company, form, **kwargs): Save the downloaded ...
Implement the Python class `CompanyImageDownloadFromURL` described below. Class description: View for downloading an image from a provided URL Method signatures and docstrings: - def validate(self, company, form): Validate that the image data are correct - def save(self, company, form, **kwargs): Save the downloaded ...
2a0ea66f6591756eeb62da28d24daec3ad4209e8
<|skeleton|> class CompanyImageDownloadFromURL: """View for downloading an image from a provided URL""" def validate(self, company, form): """Validate that the image data are correct""" <|body_0|> def save(self, company, form, **kwargs): """Save the downloaded image to the company"...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CompanyImageDownloadFromURL: """View for downloading an image from a provided URL""" def validate(self, company, form): """Validate that the image data are correct""" if not form.is_valid(): return url = form.cleaned_data.get('url', None) response = requests.ge...
the_stack_v2_python_sparse
InvenTree/company/views.py
MedShift/InvenTree
train
0
6dbf79057eb4f87f921d84257bebf8d3a75b3690
[ "permissions = [AllowAny]\nif self.action in ['update', 'partial_update', 'delete', 'create']:\n permissions = [IsAdminUser, IsAuthenticated]\nreturn [permission() for permission in permissions]", "serializer = MovieCreateSerializer(data=request.data)\nserializer.is_valid(raise_exception=True)\nmovie = seriali...
<|body_start_0|> permissions = [AllowAny] if self.action in ['update', 'partial_update', 'delete', 'create']: permissions = [IsAdminUser, IsAuthenticated] return [permission() for permission in permissions] <|end_body_0|> <|body_start_1|> serializer = MovieCreateSerializer(d...
A Movies view Set
MoviesViewSet
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MoviesViewSet: """A Movies view Set""" def get_permissions(self): """Asign permisions based on actions""" <|body_0|> def create(self, request): """Create a movie""" <|body_1|> <|end_skeleton|> <|body_start_0|> permissions = [AllowAny] if...
stack_v2_sparse_classes_36k_train_010020
2,069
permissive
[ { "docstring": "Asign permisions based on actions", "name": "get_permissions", "signature": "def get_permissions(self)" }, { "docstring": "Create a movie", "name": "create", "signature": "def create(self, request)" } ]
2
stack_v2_sparse_classes_30k_train_012315
Implement the Python class `MoviesViewSet` described below. Class description: A Movies view Set Method signatures and docstrings: - def get_permissions(self): Asign permisions based on actions - def create(self, request): Create a movie
Implement the Python class `MoviesViewSet` described below. Class description: A Movies view Set Method signatures and docstrings: - def get_permissions(self): Asign permisions based on actions - def create(self, request): Create a movie <|skeleton|> class MoviesViewSet: """A Movies view Set""" def get_perm...
d83a9f57223842378e413936d4ccdba0463f1f0a
<|skeleton|> class MoviesViewSet: """A Movies view Set""" def get_permissions(self): """Asign permisions based on actions""" <|body_0|> def create(self, request): """Create a movie""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MoviesViewSet: """A Movies view Set""" def get_permissions(self): """Asign permisions based on actions""" permissions = [AllowAny] if self.action in ['update', 'partial_update', 'delete', 'create']: permissions = [IsAdminUser, IsAuthenticated] return [permissio...
the_stack_v2_python_sparse
cinema/movies/views/movies.py
kevinGarcia15/cinemaAPI
train
0
f128e0c6b367f85e005a274cda3023d9873401ba
[ "self.__base_output_dir = base_output_dir\nself.__satellite_tle = satellite_tle\nself.__ground_station = ground_station\nself.__tz = tz\nself.__report_timezone = tz.tzname(datetime.now())\nself.__start_day = start_day\nself.__end_day = end_day\nself.__out = sys.stdout", "end = start = datetime.now()\nstart = star...
<|body_start_0|> self.__base_output_dir = base_output_dir self.__satellite_tle = satellite_tle self.__ground_station = ground_station self.__tz = tz self.__report_timezone = tz.tzname(datetime.now()) self.__start_day = start_day self.__end_day = end_day se...
Class to create a list of inviews report for a given satellite and ground station for a specific time period
InviewListReportGenerator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InviewListReportGenerator: """Class to create a list of inviews report for a given satellite and ground station for a specific time period""" def __init__(self, base_output_dir, satellite_tle, ground_station, tz, start_day=0, end_day=0): """Constructor""" <|body_0|> def ...
stack_v2_sparse_classes_36k_train_010021
2,403
no_license
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self, base_output_dir, satellite_tle, ground_station, tz, start_day=0, end_day=0)" }, { "docstring": "Method to generate the inview report", "name": "generate_report", "signature": "def generate_report(self)" ...
2
stack_v2_sparse_classes_30k_train_003375
Implement the Python class `InviewListReportGenerator` described below. Class description: Class to create a list of inviews report for a given satellite and ground station for a specific time period Method signatures and docstrings: - def __init__(self, base_output_dir, satellite_tle, ground_station, tz, start_day=0...
Implement the Python class `InviewListReportGenerator` described below. Class description: Class to create a list of inviews report for a given satellite and ground station for a specific time period Method signatures and docstrings: - def __init__(self, base_output_dir, satellite_tle, ground_station, tz, start_day=0...
0eed643eeaa9bcc35020b0b38399c25b616421c2
<|skeleton|> class InviewListReportGenerator: """Class to create a list of inviews report for a given satellite and ground station for a specific time period""" def __init__(self, base_output_dir, satellite_tle, ground_station, tz, start_day=0, end_day=0): """Constructor""" <|body_0|> def ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InviewListReportGenerator: """Class to create a list of inviews report for a given satellite and ground station for a specific time period""" def __init__(self, base_output_dir, satellite_tle, ground_station, tz, start_day=0, end_day=0): """Constructor""" self.__base_output_dir = base_out...
the_stack_v2_python_sparse
scripts/inview_list_report_generator.py
nasa-itc/OrbitInviewPowerPrediction
train
0
2ae12c270e15950e2a9cf86d55e1865b6a2f354f
[ "QMimeData.__init__(self)\nself._local_instance = data\nif data is not None:\n try:\n pdata = dumps(data)\n except:\n return\n self.setData(self.MIME_TYPE, dumps(data.__class__) + pdata)", "if isinstance(md, cls):\n return md\nif not md.hasFormat(cls.MIME_TYPE):\n return None\nnmd = c...
<|body_start_0|> QMimeData.__init__(self) self._local_instance = data if data is not None: try: pdata = dumps(data) except: return self.setData(self.MIME_TYPE, dumps(data.__class__) + pdata) <|end_body_0|> <|body_start_1|> ...
The PyMimeData wraps a Python instance as MIME data.
PyMimeData
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PyMimeData: """The PyMimeData wraps a Python instance as MIME data.""" def __init__(self, data=None): """Initialise the instance.""" <|body_0|> def coerce(cls, md): """Coerce a QMimeData instance to a PyMimeData instance if possible.""" <|body_1|> de...
stack_v2_sparse_classes_36k_train_010022
9,642
permissive
[ { "docstring": "Initialise the instance.", "name": "__init__", "signature": "def __init__(self, data=None)" }, { "docstring": "Coerce a QMimeData instance to a PyMimeData instance if possible.", "name": "coerce", "signature": "def coerce(cls, md)" }, { "docstring": "Return the in...
4
stack_v2_sparse_classes_30k_train_001262
Implement the Python class `PyMimeData` described below. Class description: The PyMimeData wraps a Python instance as MIME data. Method signatures and docstrings: - def __init__(self, data=None): Initialise the instance. - def coerce(cls, md): Coerce a QMimeData instance to a PyMimeData instance if possible. - def in...
Implement the Python class `PyMimeData` described below. Class description: The PyMimeData wraps a Python instance as MIME data. Method signatures and docstrings: - def __init__(self, data=None): Initialise the instance. - def coerce(cls, md): Coerce a QMimeData instance to a PyMimeData instance if possible. - def in...
4d42121e4af850ba1bf9a4140c11fe10ba218cdd
<|skeleton|> class PyMimeData: """The PyMimeData wraps a Python instance as MIME data.""" def __init__(self, data=None): """Initialise the instance.""" <|body_0|> def coerce(cls, md): """Coerce a QMimeData instance to a PyMimeData instance if possible.""" <|body_1|> de...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PyMimeData: """The PyMimeData wraps a Python instance as MIME data.""" def __init__(self, data=None): """Initialise the instance.""" QMimeData.__init__(self) self._local_instance = data if data is not None: try: pdata = dumps(data) e...
the_stack_v2_python_sparse
yy.py
shyamal388/PythonBlocks
train
0
fccee119f790eb0e2de214de35bb39aefe689935
[ "if not root:\n return 0\nreturn 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))", "max_depth = 0\nstack = deque([(root, 0)])\nwhile stack:\n node, depth = stack.pop()\n max_depth = max(max_depth, depth)\n if node:\n stack.append((node.left, depth + 1))\n stack.append((node....
<|body_start_0|> if not root: return 0 return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) <|end_body_0|> <|body_start_1|> max_depth = 0 stack = deque([(root, 0)]) while stack: node, depth = stack.pop() max_depth = max(max_dept...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: """Recursive DFS Time complexity: O(n) Space complexity: O(n)""" <|body_0|> def maxDepthIterativeDFS(self, root: Optional[TreeNode]) -> int: """Iterative DFS Time complexity: O(n) Space complexity: O(n)""...
stack_v2_sparse_classes_36k_train_010023
1,684
permissive
[ { "docstring": "Recursive DFS Time complexity: O(n) Space complexity: O(n)", "name": "maxDepth", "signature": "def maxDepth(self, root: Optional[TreeNode]) -> int" }, { "docstring": "Iterative DFS Time complexity: O(n) Space complexity: O(n)", "name": "maxDepthIterativeDFS", "signature":...
3
stack_v2_sparse_classes_30k_train_001973
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxDepth(self, root: Optional[TreeNode]) -> int: Recursive DFS Time complexity: O(n) Space complexity: O(n) - def maxDepthIterativeDFS(self, root: Optional[TreeNode]) -> int:...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxDepth(self, root: Optional[TreeNode]) -> int: Recursive DFS Time complexity: O(n) Space complexity: O(n) - def maxDepthIterativeDFS(self, root: Optional[TreeNode]) -> int:...
32b0878f63e5edd19a1fbe13bfa4c518a4261e23
<|skeleton|> class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: """Recursive DFS Time complexity: O(n) Space complexity: O(n)""" <|body_0|> def maxDepthIterativeDFS(self, root: Optional[TreeNode]) -> int: """Iterative DFS Time complexity: O(n) Space complexity: O(n)""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: """Recursive DFS Time complexity: O(n) Space complexity: O(n)""" if not root: return 0 return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) def maxDepthIterativeDFS(self, root: Optional[TreeN...
the_stack_v2_python_sparse
leetcode/Trees/104. Maximum Depth of Binary Tree.py
danielfsousa/algorithms-solutions
train
2
d0a128757b94b9c3ee4a33433551fb53148ebf3c
[ "data = NDLabel(**{'annotations': json_data})\nres = data.to_common()\nreturn res", "for example in NDLabel.from_common(labels):\n res = example.dict(by_alias=True)\n for k, v in list(res.items()):\n if k in IGNORE_IF_NONE and v is None:\n del res[k]\n yield res" ]
<|body_start_0|> data = NDLabel(**{'annotations': json_data}) res = data.to_common() return res <|end_body_0|> <|body_start_1|> for example in NDLabel.from_common(labels): res = example.dict(by_alias=True) for k, v in list(res.items()): if k in IG...
NDJsonConverter
[ "Apache-2.0", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NDJsonConverter: def deserialize(json_data: Iterable[Dict[str, Any]]) -> LabelGenerator: """Converts ndjson data (prediction import format) into the common labelbox format. Args: json_data: An iterable representing the ndjson data Returns: LabelGenerator containing the ndjson data.""" ...
stack_v2_sparse_classes_36k_train_010024
1,728
permissive
[ { "docstring": "Converts ndjson data (prediction import format) into the common labelbox format. Args: json_data: An iterable representing the ndjson data Returns: LabelGenerator containing the ndjson data.", "name": "deserialize", "signature": "def deserialize(json_data: Iterable[Dict[str, Any]]) -> La...
2
stack_v2_sparse_classes_30k_train_000154
Implement the Python class `NDJsonConverter` described below. Class description: Implement the NDJsonConverter class. Method signatures and docstrings: - def deserialize(json_data: Iterable[Dict[str, Any]]) -> LabelGenerator: Converts ndjson data (prediction import format) into the common labelbox format. Args: json_...
Implement the Python class `NDJsonConverter` described below. Class description: Implement the NDJsonConverter class. Method signatures and docstrings: - def deserialize(json_data: Iterable[Dict[str, Any]]) -> LabelGenerator: Converts ndjson data (prediction import format) into the common labelbox format. Args: json_...
29f0d3fa19cc62721f5c67022259ded320ae01ed
<|skeleton|> class NDJsonConverter: def deserialize(json_data: Iterable[Dict[str, Any]]) -> LabelGenerator: """Converts ndjson data (prediction import format) into the common labelbox format. Args: json_data: An iterable representing the ndjson data Returns: LabelGenerator containing the ndjson data.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NDJsonConverter: def deserialize(json_data: Iterable[Dict[str, Any]]) -> LabelGenerator: """Converts ndjson data (prediction import format) into the common labelbox format. Args: json_data: An iterable representing the ndjson data Returns: LabelGenerator containing the ndjson data.""" data = N...
the_stack_v2_python_sparse
labelbox/data/serialization/ndjson/converter.py
Labelbox/labelbox-python
train
81
b7965422ed2e90ebb81b5d5af35798dac106e409
[ "import collections\ndicts_row = collections.defaultdict(set)\nfor point in points:\n dicts_row[point[0]].add(point[1])\nl = len(points)\nmin_val = float('inf')\nfor i in range(l - 1):\n for j in range(i + 1, l):\n if points[i][0] != points[j][0] and points[i][1] != points[j][1]:\n if points...
<|body_start_0|> import collections dicts_row = collections.defaultdict(set) for point in points: dicts_row[point[0]].add(point[1]) l = len(points) min_val = float('inf') for i in range(l - 1): for j in range(i + 1, l): if points[i]...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def minAreaRect(self, points): """:type points: List[List[int]] :rtype: int 2028 ms""" <|body_0|> def minAreaRect_1(self, points): """112ms :param points: :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> import collections ...
stack_v2_sparse_classes_36k_train_010025
2,528
no_license
[ { "docstring": ":type points: List[List[int]] :rtype: int 2028 ms", "name": "minAreaRect", "signature": "def minAreaRect(self, points)" }, { "docstring": "112ms :param points: :return:", "name": "minAreaRect_1", "signature": "def minAreaRect_1(self, points)" } ]
2
stack_v2_sparse_classes_30k_train_020243
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minAreaRect(self, points): :type points: List[List[int]] :rtype: int 2028 ms - def minAreaRect_1(self, points): 112ms :param points: :return:
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minAreaRect(self, points): :type points: List[List[int]] :rtype: int 2028 ms - def minAreaRect_1(self, points): 112ms :param points: :return: <|skeleton|> class Solution: ...
679a2b246b8b6bb7fc55ed1c8096d3047d6d4461
<|skeleton|> class Solution: def minAreaRect(self, points): """:type points: List[List[int]] :rtype: int 2028 ms""" <|body_0|> def minAreaRect_1(self, points): """112ms :param points: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def minAreaRect(self, points): """:type points: List[List[int]] :rtype: int 2028 ms""" import collections dicts_row = collections.defaultdict(set) for point in points: dicts_row[point[0]].add(point[1]) l = len(points) min_val = float('inf')...
the_stack_v2_python_sparse
MinimumAreaRectangle_MID_939.py
953250587/leetcode-python
train
2
0aca9c6495fbeea9f85a0da8b67ca4af4231ff7a
[ "ver = state.pop('version')\nassert ver == cls.VERSION\nreturn cls(**state)", "state = attr.asdict(self)\nstate['version'] = self.VERSION\nreturn state" ]
<|body_start_0|> ver = state.pop('version') assert ver == cls.VERSION return cls(**state) <|end_body_0|> <|body_start_1|> state = attr.asdict(self) state['version'] = self.VERSION return state <|end_body_1|>
Base class supplying basic serialization methods and used to mark things that are intended to be serialzable. By serializable, we mean 'able to be rendered to dict of base types' such that this state can be easily pickled.
Serializable
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Serializable: """Base class supplying basic serialization methods and used to mark things that are intended to be serialzable. By serializable, we mean 'able to be rendered to dict of base types' such that this state can be easily pickled.""" def deserialize(cls, state): """Deseriali...
stack_v2_sparse_classes_36k_train_010026
1,206
permissive
[ { "docstring": "Deserialize the object from the dict of basic types. :param state dict: dict (serialized) representation of the object :return Serializable: the deserialized object", "name": "deserialize", "signature": "def deserialize(cls, state)" }, { "docstring": "Serialize object to dict of ...
2
stack_v2_sparse_classes_30k_test_000570
Implement the Python class `Serializable` described below. Class description: Base class supplying basic serialization methods and used to mark things that are intended to be serialzable. By serializable, we mean 'able to be rendered to dict of base types' such that this state can be easily pickled. Method signatures...
Implement the Python class `Serializable` described below. Class description: Base class supplying basic serialization methods and used to mark things that are intended to be serialzable. By serializable, we mean 'able to be rendered to dict of base types' such that this state can be easily pickled. Method signatures...
e2864d88eb971e327d7e886e75d00140673006ef
<|skeleton|> class Serializable: """Base class supplying basic serialization methods and used to mark things that are intended to be serialzable. By serializable, we mean 'able to be rendered to dict of base types' such that this state can be easily pickled.""" def deserialize(cls, state): """Deseriali...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Serializable: """Base class supplying basic serialization methods and used to mark things that are intended to be serialzable. By serializable, we mean 'able to be rendered to dict of base types' such that this state can be easily pickled.""" def deserialize(cls, state): """Deserialize the object...
the_stack_v2_python_sparse
bc_gym_planning_env/utilities/serialize.py
braincorp/bc-gym-planning-env
train
2
fc4a4393d99239b8a52cb01d62501e6de538cbcc
[ "super().__init__(client, info, mac)\nself.entity_description = ButtonEntityDescription(key='identify', name='Identify', icon='mdi:help', entity_category=EntityCategory.CONFIG)\nself._attr_unique_id = f'{info.serial_number}_{self.entity_description.key}'", "try:\n await self.client.identify()\nexcept ElgatoErr...
<|body_start_0|> super().__init__(client, info, mac) self.entity_description = ButtonEntityDescription(key='identify', name='Identify', icon='mdi:help', entity_category=EntityCategory.CONFIG) self._attr_unique_id = f'{info.serial_number}_{self.entity_description.key}' <|end_body_0|> <|body_star...
Defines an Elgato identify button.
ElgatoIdentifyButton
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ElgatoIdentifyButton: """Defines an Elgato identify button.""" def __init__(self, client: Elgato, info: Info, mac: str | None) -> None: """Initialize the button entity.""" <|body_0|> async def async_press(self) -> None: """Identify the light, will make it blink."...
stack_v2_sparse_classes_36k_train_010027
1,925
permissive
[ { "docstring": "Initialize the button entity.", "name": "__init__", "signature": "def __init__(self, client: Elgato, info: Info, mac: str | None) -> None" }, { "docstring": "Identify the light, will make it blink.", "name": "async_press", "signature": "async def async_press(self) -> None...
2
stack_v2_sparse_classes_30k_train_008583
Implement the Python class `ElgatoIdentifyButton` described below. Class description: Defines an Elgato identify button. Method signatures and docstrings: - def __init__(self, client: Elgato, info: Info, mac: str | None) -> None: Initialize the button entity. - async def async_press(self) -> None: Identify the light,...
Implement the Python class `ElgatoIdentifyButton` described below. Class description: Defines an Elgato identify button. Method signatures and docstrings: - def __init__(self, client: Elgato, info: Info, mac: str | None) -> None: Initialize the button entity. - async def async_press(self) -> None: Identify the light,...
dcf68d768e4f628d038f1fdd6e40bad713fbc222
<|skeleton|> class ElgatoIdentifyButton: """Defines an Elgato identify button.""" def __init__(self, client: Elgato, info: Info, mac: str | None) -> None: """Initialize the button entity.""" <|body_0|> async def async_press(self) -> None: """Identify the light, will make it blink."...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ElgatoIdentifyButton: """Defines an Elgato identify button.""" def __init__(self, client: Elgato, info: Info, mac: str | None) -> None: """Initialize the button entity.""" super().__init__(client, info, mac) self.entity_description = ButtonEntityDescription(key='identify', name='I...
the_stack_v2_python_sparse
homeassistant/components/elgato/button.py
Adminiuga/home-assistant
train
5
14388c43e0808f12454f282c0f52bea3563b8e96
[ "log.info('Setup Section verifyProcessorDetails')\nhost_ip = classparam['host_ip']\nboot_order_obj = classparam['boot_order_obj']\nself.host_serial_handle = classparam['host_serial_handle']\nself.host_serial_handle.connect_to_host_serial()\nlog.info('Create boot device from CIMC config and boot from it')\nif boot_o...
<|body_start_0|> log.info('Setup Section verifyProcessorDetails') host_ip = classparam['host_ip'] boot_order_obj = classparam['boot_order_obj'] self.host_serial_handle = classparam['host_serial_handle'] self.host_serial_handle.connect_to_host_serial() log.info('Create boo...
Configure boot device to bios, pxe, hdd, cdrom, floppy drive options in non persistent mode when boot device set from CIMC config and booted from it
CimcConfigIPMICmdNonPersistentBootDevice
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CimcConfigIPMICmdNonPersistentBootDevice: """Configure boot device to bios, pxe, hdd, cdrom, floppy drive options in non persistent mode when boot device set from CIMC config and booted from it""" def setup(self, cimc_util_obj): """Test Case Setup""" <|body_0|> def test(...
stack_v2_sparse_classes_36k_train_010028
19,363
no_license
[ { "docstring": "Test Case Setup", "name": "setup", "signature": "def setup(self, cimc_util_obj)" }, { "docstring": "ipmi command to set boot to bios, pxe, hdd, cdrom, floppy drive options in non-persistent mode", "name": "test", "signature": "def test(self, cimc_util_obj, config, paramet...
3
stack_v2_sparse_classes_30k_train_012209
Implement the Python class `CimcConfigIPMICmdNonPersistentBootDevice` described below. Class description: Configure boot device to bios, pxe, hdd, cdrom, floppy drive options in non persistent mode when boot device set from CIMC config and booted from it Method signatures and docstrings: - def setup(self, cimc_util_o...
Implement the Python class `CimcConfigIPMICmdNonPersistentBootDevice` described below. Class description: Configure boot device to bios, pxe, hdd, cdrom, floppy drive options in non persistent mode when boot device set from CIMC config and booted from it Method signatures and docstrings: - def setup(self, cimc_util_o...
c255e045a4950a0d8868a10012d5ce6e5c6a9c23
<|skeleton|> class CimcConfigIPMICmdNonPersistentBootDevice: """Configure boot device to bios, pxe, hdd, cdrom, floppy drive options in non persistent mode when boot device set from CIMC config and booted from it""" def setup(self, cimc_util_obj): """Test Case Setup""" <|body_0|> def test(...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CimcConfigIPMICmdNonPersistentBootDevice: """Configure boot device to bios, pxe, hdd, cdrom, floppy drive options in non persistent mode when boot device set from CIMC config and booted from it""" def setup(self, cimc_util_obj): """Test Case Setup""" log.info('Setup Section verifyProcesso...
the_stack_v2_python_sparse
ipmi_cmnd_bootorder.py
jrchanda/MyRepo
train
0
d33f5928e4414fbed5d4a09ae32baa2c6f413c19
[ "super(Decoder, self).__init__()\nself.input_size = input_size\nself.hidden_size = hidden_size\nself.num_layers = num_layers\nself.proba_output = proba_output\nif rnn_type == 'LSTM':\n self.model = nn.LSTM(input_size=self.input_size, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=batch_fir...
<|body_start_0|> super(Decoder, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.num_layers = num_layers self.proba_output = proba_output if rnn_type == 'LSTM': self.model = nn.LSTM(input_size=self.input_size, hidden_size=self....
Decoder Network
Decoder
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Decoder: """Decoder Network""" def __init__(self, input_size, hidden_size, num_layers, dropout=0, batch_first=True, rnn_type='LSTM', proba_output=False): """Create Encoder Args: input_size (int): number of features per time step hidden_size (int): number of hidden nodes per time step...
stack_v2_sparse_classes_36k_train_010029
14,969
permissive
[ { "docstring": "Create Encoder Args: input_size (int): number of features per time step hidden_size (int): number of hidden nodes per time step num_layers (int): number of layers dropout (float, optional): percentage of nodes that should switched out at any term. Defaults to 0. batch_first (bool, optional): if ...
2
stack_v2_sparse_classes_30k_train_016472
Implement the Python class `Decoder` described below. Class description: Decoder Network Method signatures and docstrings: - def __init__(self, input_size, hidden_size, num_layers, dropout=0, batch_first=True, rnn_type='LSTM', proba_output=False): Create Encoder Args: input_size (int): number of features per time ste...
Implement the Python class `Decoder` described below. Class description: Decoder Network Method signatures and docstrings: - def __init__(self, input_size, hidden_size, num_layers, dropout=0, batch_first=True, rnn_type='LSTM', proba_output=False): Create Encoder Args: input_size (int): number of features per time ste...
5b4a61b5dd0bc259ffe68223877949ef4ebfa5e3
<|skeleton|> class Decoder: """Decoder Network""" def __init__(self, input_size, hidden_size, num_layers, dropout=0, batch_first=True, rnn_type='LSTM', proba_output=False): """Create Encoder Args: input_size (int): number of features per time step hidden_size (int): number of hidden nodes per time step...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Decoder: """Decoder Network""" def __init__(self, input_size, hidden_size, num_layers, dropout=0, batch_first=True, rnn_type='LSTM', proba_output=False): """Create Encoder Args: input_size (int): number of features per time step hidden_size (int): number of hidden nodes per time step num_layers (...
the_stack_v2_python_sparse
src/models/anomalia/layers.py
maurony/ts-vrae
train
1
979c5a410b0afe485bff6be64e685171bfedb812
[ "self.connection = None\nself.differential_drive = DifferentialDrive()\nself.camera = None\nself.buzzer = None\nself.led = LED()\nself.left_bump_sensor = BumpSensor('left')\nself.right_bump_sensor = BumpSensor('right')\nself.left_proximity_sensor = ProximitySensor('left')\nself.front_proximity_sensor = ProximitySen...
<|body_start_0|> self.connection = None self.differential_drive = DifferentialDrive() self.camera = None self.buzzer = None self.led = LED() self.left_bump_sensor = BumpSensor('left') self.right_bump_sensor = BumpSensor('right') self.left_proximity_sensor ...
RoseBot
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RoseBot: def __init__(self): """Initializes a RoseBot that has: -- self.connection: for Python-to-robot communication -- self.differential_drive: for making the robot move -- self.camera: for doing things with the Pixy camera -- self.buzzer: for making noises -- self.led: for turning the...
stack_v2_sparse_classes_36k_train_010030
14,163
no_license
[ { "docstring": "Initializes a RoseBot that has: -- self.connection: for Python-to-robot communication -- self.differential_drive: for making the robot move -- self.camera: for doing things with the Pixy camera -- self.buzzer: for making noises -- self.led: for turning the LED on and off -- Sensor objects for se...
4
stack_v2_sparse_classes_30k_train_009532
Implement the Python class `RoseBot` described below. Class description: Implement the RoseBot class. Method signatures and docstrings: - def __init__(self): Initializes a RoseBot that has: -- self.connection: for Python-to-robot communication -- self.differential_drive: for making the robot move -- self.camera: for ...
Implement the Python class `RoseBot` described below. Class description: Implement the RoseBot class. Method signatures and docstrings: - def __init__(self): Initializes a RoseBot that has: -- self.connection: for Python-to-robot communication -- self.differential_drive: for making the robot move -- self.camera: for ...
7f5906ce0cde57a5537a3068513575da32b33df5
<|skeleton|> class RoseBot: def __init__(self): """Initializes a RoseBot that has: -- self.connection: for Python-to-robot communication -- self.differential_drive: for making the robot move -- self.camera: for doing things with the Pixy camera -- self.buzzer: for making noises -- self.led: for turning the...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RoseBot: def __init__(self): """Initializes a RoseBot that has: -- self.connection: for Python-to-robot communication -- self.differential_drive: for making the robot move -- self.camera: for doing things with the Pixy camera -- self.buzzer: for making noises -- self.led: for turning the LED on and of...
the_stack_v2_python_sparse
Session20_RobotPixyCamera/src/rosebot.py
rhinomikey/Python-Projects
train
0
46eaff679d7537647f4bc1f3722d59179c6db870
[ "try:\n content_type = decide_content_type(self.request.headers.getall(hdrs.ACCEPT), SUPPORTED_CONTENT_TYPES)\nexcept NoAgreeableContentTypeError as e:\n raise web.HTTPNotAcceptable() from e\nid = self.request.match_info['id']\nlogging.debug(f'Getting catalog with id {id}')\ncatalog = await get_catalog_by_id(...
<|body_start_0|> try: content_type = decide_content_type(self.request.headers.getall(hdrs.ACCEPT), SUPPORTED_CONTENT_TYPES) except NoAgreeableContentTypeError as e: raise web.HTTPNotAcceptable() from e id = self.request.match_info['id'] logging.debug(f'Getting cat...
Class representing catalog resource.
Catalog
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Catalog: """Class representing catalog resource.""" async def get(self) -> web.Response: """Get catalog by id.""" <|body_0|> async def delete(self) -> web.Response: """Delete catalog given by id.""" <|body_1|> <|end_skeleton|> <|body_start_0|> t...
stack_v2_sparse_classes_36k_train_010031
3,608
permissive
[ { "docstring": "Get catalog by id.", "name": "get", "signature": "async def get(self) -> web.Response" }, { "docstring": "Delete catalog given by id.", "name": "delete", "signature": "async def delete(self) -> web.Response" } ]
2
stack_v2_sparse_classes_30k_train_001614
Implement the Python class `Catalog` described below. Class description: Class representing catalog resource. Method signatures and docstrings: - async def get(self) -> web.Response: Get catalog by id. - async def delete(self) -> web.Response: Delete catalog given by id.
Implement the Python class `Catalog` described below. Class description: Class representing catalog resource. Method signatures and docstrings: - async def get(self) -> web.Response: Get catalog by id. - async def delete(self) -> web.Response: Delete catalog given by id. <|skeleton|> class Catalog: """Class repr...
86d1525d9bd58644384e1760711968adb948956e
<|skeleton|> class Catalog: """Class representing catalog resource.""" async def get(self) -> web.Response: """Get catalog by id.""" <|body_0|> async def delete(self) -> web.Response: """Delete catalog given by id.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Catalog: """Class representing catalog resource.""" async def get(self) -> web.Response: """Get catalog by id.""" try: content_type = decide_content_type(self.request.headers.getall(hdrs.ACCEPT), SUPPORTED_CONTENT_TYPES) except NoAgreeableContentTypeError as e: ...
the_stack_v2_python_sparse
dataservice_publisher/resources/catalogs.py
Informasjonsforvaltning/dataservice-publisher
train
1
e995551f989d9afd3ce9a01a19a5ec812d41e6aa
[ "self.__logger = State().getLogger('DetectionCore_Component_Logger')\nself.__logger.info('Starting __init__()', 'HorizontalLineRemoveDetector:__init__')\nself.__indexOfProcessMat = indexOfProcessMat\nself.__anchorPoint = anchorPoint\nself.__kernelWidth = kernelWidth\nself.__kernelHeight = kernelHeight\nself.__morph...
<|body_start_0|> self.__logger = State().getLogger('DetectionCore_Component_Logger') self.__logger.info('Starting __init__()', 'HorizontalLineRemoveDetector:__init__') self.__indexOfProcessMat = indexOfProcessMat self.__anchorPoint = anchorPoint self.__kernelWidth = kernelWidth ...
HorizontalLineRemoveDetector
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HorizontalLineRemoveDetector: def __init__(self, indexOfProcessMat=0, anchorPoint=(-1, -1), kernelWidth=1, kernelHeight=3, morphOfKernel=cv2.MORPH_RECT, showImagesInWindow=True): """To-Do: Bitte Kommentar bzw. Dokumentaion erstellen!""" <|body_0|> def detect(self, mats): ...
stack_v2_sparse_classes_36k_train_010032
3,792
no_license
[ { "docstring": "To-Do: Bitte Kommentar bzw. Dokumentaion erstellen!", "name": "__init__", "signature": "def __init__(self, indexOfProcessMat=0, anchorPoint=(-1, -1), kernelWidth=1, kernelHeight=3, morphOfKernel=cv2.MORPH_RECT, showImagesInWindow=True)" }, { "docstring": "To-Do: Bitte Kommentar b...
2
stack_v2_sparse_classes_30k_train_004233
Implement the Python class `HorizontalLineRemoveDetector` described below. Class description: Implement the HorizontalLineRemoveDetector class. Method signatures and docstrings: - def __init__(self, indexOfProcessMat=0, anchorPoint=(-1, -1), kernelWidth=1, kernelHeight=3, morphOfKernel=cv2.MORPH_RECT, showImagesInWin...
Implement the Python class `HorizontalLineRemoveDetector` described below. Class description: Implement the HorizontalLineRemoveDetector class. Method signatures and docstrings: - def __init__(self, indexOfProcessMat=0, anchorPoint=(-1, -1), kernelWidth=1, kernelHeight=3, morphOfKernel=cv2.MORPH_RECT, showImagesInWin...
3daaa72b193ebfb55894b47b6a752cdc2192bb6b
<|skeleton|> class HorizontalLineRemoveDetector: def __init__(self, indexOfProcessMat=0, anchorPoint=(-1, -1), kernelWidth=1, kernelHeight=3, morphOfKernel=cv2.MORPH_RECT, showImagesInWindow=True): """To-Do: Bitte Kommentar bzw. Dokumentaion erstellen!""" <|body_0|> def detect(self, mats): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HorizontalLineRemoveDetector: def __init__(self, indexOfProcessMat=0, anchorPoint=(-1, -1), kernelWidth=1, kernelHeight=3, morphOfKernel=cv2.MORPH_RECT, showImagesInWindow=True): """To-Do: Bitte Kommentar bzw. Dokumentaion erstellen!""" self.__logger = State().getLogger('DetectionCore_Componen...
the_stack_v2_python_sparse
SheetMusicScanner/DetectionCore_Component/Detector/HorizontalLineRemoveDetector.py
jadeskon/score-scan
train
0
35ada8c093f51a36f07c8045251cfb339c84d5be
[ "if n < 1:\n return False\nwhile n != 1:\n if n % 5 == 0:\n n = n / 5\n elif n % 3 == 0:\n n = n / 3\n elif n % 2 == 0:\n n = n / 2\n else:\n return False\nreturn True", "dp2, dp3, dp5 = (1, 1, 1)\ndp = [0] * (n + 1)\ndp[1] = 1\nfor i in range(2, n + 1):\n dp[i] = min...
<|body_start_0|> if n < 1: return False while n != 1: if n % 5 == 0: n = n / 5 elif n % 3 == 0: n = n / 3 elif n % 2 == 0: n = n / 2 else: return False return True <|end_bo...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isUgly(self, n: int) -> bool: """263 判断 n 是否为丑数""" <|body_0|> def nthUglyNumber(self, n: int) -> int: """264 返回第 n 个丑数 用三个指针dp2,dp3,dp5""" <|body_1|> <|end_skeleton|> <|body_start_0|> if n < 1: return False while n ...
stack_v2_sparse_classes_36k_train_010033
1,417
no_license
[ { "docstring": "263 判断 n 是否为丑数", "name": "isUgly", "signature": "def isUgly(self, n: int) -> bool" }, { "docstring": "264 返回第 n 个丑数 用三个指针dp2,dp3,dp5", "name": "nthUglyNumber", "signature": "def nthUglyNumber(self, n: int) -> int" } ]
2
stack_v2_sparse_classes_30k_train_008312
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isUgly(self, n: int) -> bool: 263 判断 n 是否为丑数 - def nthUglyNumber(self, n: int) -> int: 264 返回第 n 个丑数 用三个指针dp2,dp3,dp5
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isUgly(self, n: int) -> bool: 263 判断 n 是否为丑数 - def nthUglyNumber(self, n: int) -> int: 264 返回第 n 个丑数 用三个指针dp2,dp3,dp5 <|skeleton|> class Solution: def isUgly(self, n: i...
3fd69b85f52af861ff7e2c74d8aacc515b192615
<|skeleton|> class Solution: def isUgly(self, n: int) -> bool: """263 判断 n 是否为丑数""" <|body_0|> def nthUglyNumber(self, n: int) -> int: """264 返回第 n 个丑数 用三个指针dp2,dp3,dp5""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def isUgly(self, n: int) -> bool: """263 判断 n 是否为丑数""" if n < 1: return False while n != 1: if n % 5 == 0: n = n / 5 elif n % 3 == 0: n = n / 3 elif n % 2 == 0: n = n / 2 ...
the_stack_v2_python_sparse
Other/Ugly_263_264.py
helloprogram6/leetcode_Cookbook_python
train
0
bcf1b9c13fa954c345b9ae9778b1cea8e402d049
[ "super(KleinConstraint, self).__init__()\nself.norm = Norm(axis=-1)\nself.min_norm = min_norm\nself.maxnorm = 1 - 0.004\nself.shape = Shape()\nself.reshape = Reshape()", "last_dim_val = self.shape(x)[-1]\nnorm = self.reshape(self.norm(x), (-1, 1))\nmaxnorm = self.maxnorm\ncond = norm > maxnorm\nx_reshape = self.r...
<|body_start_0|> super(KleinConstraint, self).__init__() self.norm = Norm(axis=-1) self.min_norm = min_norm self.maxnorm = 1 - 0.004 self.shape = Shape() self.reshape = Reshape() <|end_body_0|> <|body_start_1|> last_dim_val = self.shape(x)[-1] norm = self...
klein constraint class
KleinConstraint
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KleinConstraint: """klein constraint class""" def __init__(self, min_norm): """init fun""" <|body_0|> def construct(self, x): """class construction""" <|body_1|> <|end_skeleton|> <|body_start_0|> super(KleinConstraint, self).__init__() s...
stack_v2_sparse_classes_36k_train_010034
8,596
permissive
[ { "docstring": "init fun", "name": "__init__", "signature": "def __init__(self, min_norm)" }, { "docstring": "class construction", "name": "construct", "signature": "def construct(self, x)" } ]
2
null
Implement the Python class `KleinConstraint` described below. Class description: klein constraint class Method signatures and docstrings: - def __init__(self, min_norm): init fun - def construct(self, x): class construction
Implement the Python class `KleinConstraint` described below. Class description: klein constraint class Method signatures and docstrings: - def __init__(self, min_norm): init fun - def construct(self, x): class construction <|skeleton|> class KleinConstraint: """klein constraint class""" def __init__(self, ...
eab643f51336dbf7d711f02d27e6516e5affee59
<|skeleton|> class KleinConstraint: """klein constraint class""" def __init__(self, min_norm): """init fun""" <|body_0|> def construct(self, x): """class construction""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class KleinConstraint: """klein constraint class""" def __init__(self, min_norm): """init fun""" super(KleinConstraint, self).__init__() self.norm = Norm(axis=-1) self.min_norm = min_norm self.maxnorm = 1 - 0.004 self.shape = Shape() self.reshape = Reshap...
the_stack_v2_python_sparse
research/nlp/hypertext/src/poincare.py
mindspore-ai/models
train
301
4dbe354bcbb961bd1170a72e3f0b30afc0d11572
[ "ver_inst, rec_type, rec_size = unpack('<HHL', self.stream.read(8))\ninstance, version = divmod(ver_inst, 2 ** 4)\nreturn (rec_type, rec_size, (instance, version))", "if rec_type == PptRecordCurrentUser.TYPE:\n return (PptRecordCurrentUser, True)\nelif rec_type == PptRecordExOleObjAtom.TYPE:\n return (PptRe...
<|body_start_0|> ver_inst, rec_type, rec_size = unpack('<HHL', self.stream.read(8)) instance, version = divmod(ver_inst, 2 ** 4) return (rec_type, rec_size, (instance, version)) <|end_body_0|> <|body_start_1|> if rec_type == PptRecordCurrentUser.TYPE: return (PptRecordCurren...
a stream of records in a ppt file
PptStream
[ "MIT", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PptStream: """a stream of records in a ppt file""" def read_record_head(self): """read first few bytes of record to determine size and type returns (type, size, other) where other is (instance, version)""" <|body_0|> def record_class_for_type(cls, rec_type): """d...
stack_v2_sparse_classes_36k_train_010035
29,559
permissive
[ { "docstring": "read first few bytes of record to determine size and type returns (type, size, other) where other is (instance, version)", "name": "read_record_head", "signature": "def read_record_head(self)" }, { "docstring": "determine a class for given record type returns (clz, force_read)", ...
2
stack_v2_sparse_classes_30k_train_005812
Implement the Python class `PptStream` described below. Class description: a stream of records in a ppt file Method signatures and docstrings: - def read_record_head(self): read first few bytes of record to determine size and type returns (type, size, other) where other is (instance, version) - def record_class_for_t...
Implement the Python class `PptStream` described below. Class description: a stream of records in a ppt file Method signatures and docstrings: - def read_record_head(self): read first few bytes of record to determine size and type returns (type, size, other) where other is (instance, version) - def record_class_for_t...
fb4546ec1be5f46d53856161e46ea53d7b7e532a
<|skeleton|> class PptStream: """a stream of records in a ppt file""" def read_record_head(self): """read first few bytes of record to determine size and type returns (type, size, other) where other is (instance, version)""" <|body_0|> def record_class_for_type(cls, rec_type): """d...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PptStream: """a stream of records in a ppt file""" def read_record_head(self): """read first few bytes of record to determine size and type returns (type, size, other) where other is (instance, version)""" ver_inst, rec_type, rec_size = unpack('<HHL', self.stream.read(8)) instance...
the_stack_v2_python_sparse
oletools/ppt_record_parser.py
decalage2/oletools
train
2,601
893b376d2c61918c5442881d42e813a65d871326
[ "logger_admin = self.setup_logger(logging.INFO, 'scoreboard_admin.log')\n'\\n Use the same configuration file as the python controller. The conf file contains a user\\n name and password that is critical to retrieve hint entitlements. This user and password\\n allows us to retrieve a second ses...
<|body_start_0|> logger_admin = self.setup_logger(logging.INFO, 'scoreboard_admin.log') '\n Use the same configuration file as the python controller. The conf file contains a user\n name and password that is critical to retrieve hint entitlements. This user and password\n allows us ...
getanswerCommand
[ "CC0-1.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class getanswerCommand: def stream(self, records): """Configure the logger. In this custom search command we only need to write to scoreboard_admin.log.""" <|body_0|> def setup_logger(self, level, filename): """Setup a logger for the custom search command.""" <|bod...
stack_v2_sparse_classes_36k_train_010036
3,066
permissive
[ { "docstring": "Configure the logger. In this custom search command we only need to write to scoreboard_admin.log.", "name": "stream", "signature": "def stream(self, records)" }, { "docstring": "Setup a logger for the custom search command.", "name": "setup_logger", "signature": "def set...
2
null
Implement the Python class `getanswerCommand` described below. Class description: Implement the getanswerCommand class. Method signatures and docstrings: - def stream(self, records): Configure the logger. In this custom search command we only need to write to scoreboard_admin.log. - def setup_logger(self, level, file...
Implement the Python class `getanswerCommand` described below. Class description: Implement the getanswerCommand class. Method signatures and docstrings: - def stream(self, records): Configure the logger. In this custom search command we only need to write to scoreboard_admin.log. - def setup_logger(self, level, file...
bef2d5cb254b0d6d4699f4f445e6fc914a35ceed
<|skeleton|> class getanswerCommand: def stream(self, records): """Configure the logger. In this custom search command we only need to write to scoreboard_admin.log.""" <|body_0|> def setup_logger(self, level, filename): """Setup a logger for the custom search command.""" <|bod...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class getanswerCommand: def stream(self, records): """Configure the logger. In this custom search command we only need to write to scoreboard_admin.log.""" logger_admin = self.setup_logger(logging.INFO, 'scoreboard_admin.log') '\n Use the same configuration file as the python controll...
the_stack_v2_python_sparse
bin/validateevents.py
splunk/SA-ctf_scoreboard
train
113
ae15c9a0dc1ab1c8c72b2b91c65eab3e0bb32eac
[ "params = ParamsParser(request.JSON)\npassword = params.str('password', desc='密码', min_length=MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH)\nusername = params.str('username', desc='用户名', max_length=MAX_USERNAME_LENGTH)\naccounts = Account.objects.filter_cache(username=username)\nif len(accounts) == 0 or not ...
<|body_start_0|> params = ParamsParser(request.JSON) password = params.str('password', desc='密码', min_length=MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH) username = params.str('username', desc='用户名', max_length=MAX_USERNAME_LENGTH) accounts = Account.objects.filter_cache(username...
AccountLoginView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AccountLoginView: def post(self, request): """登录 :param request: :return:""" <|body_0|> def get(self, request): """检查是否登录 :param request: :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> params = ParamsParser(request.JSON) password =...
stack_v2_sparse_classes_36k_train_010037
2,013
no_license
[ { "docstring": "登录 :param request: :return:", "name": "post", "signature": "def post(self, request)" }, { "docstring": "检查是否登录 :param request: :return:", "name": "get", "signature": "def get(self, request)" } ]
2
null
Implement the Python class `AccountLoginView` described below. Class description: Implement the AccountLoginView class. Method signatures and docstrings: - def post(self, request): 登录 :param request: :return: - def get(self, request): 检查是否登录 :param request: :return:
Implement the Python class `AccountLoginView` described below. Class description: Implement the AccountLoginView class. Method signatures and docstrings: - def post(self, request): 登录 :param request: :return: - def get(self, request): 检查是否登录 :param request: :return: <|skeleton|> class AccountLoginView: def post...
7467cd66e1fc91f0b3a264f8fc9b93f22f09fe7b
<|skeleton|> class AccountLoginView: def post(self, request): """登录 :param request: :return:""" <|body_0|> def get(self, request): """检查是否登录 :param request: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AccountLoginView: def post(self, request): """登录 :param request: :return:""" params = ParamsParser(request.JSON) password = params.str('password', desc='密码', min_length=MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH) username = params.str('username', desc='用户名', max_length...
the_stack_v2_python_sparse
FireHydrant/server/account/views/login.py
shoogoome/FireHydrant
train
4
2cf542f1d5004fd1181585648b974f5f25dd57ac
[ "Callbacks.current = self\ntry:\n yield\nfinally:\n if Callbacks.current is self:\n Callbacks.current = None", "with self.set_current():\n ret = None\n try:\n for i in self:\n try:\n ret = i(*args, **kwargs) or ret\n except AbortedError:\n ...
<|body_start_0|> Callbacks.current = self try: yield finally: if Callbacks.current is self: Callbacks.current = None <|end_body_0|> <|body_start_1|> with self.set_current(): ret = None try: for i in self: ...
Failsafe callbacks executor.
Callbacks
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Callbacks: """Failsafe callbacks executor.""" def set_current(self): """Set current object during context.""" <|body_0|> def execute(self, *args, **kwargs): """Execute callbacks.""" <|body_1|> <|end_skeleton|> <|body_start_0|> Callbacks.current ...
stack_v2_sparse_classes_36k_train_010038
3,157
no_license
[ { "docstring": "Set current object during context.", "name": "set_current", "signature": "def set_current(self)" }, { "docstring": "Execute callbacks.", "name": "execute", "signature": "def execute(self, *args, **kwargs)" } ]
2
stack_v2_sparse_classes_30k_train_019308
Implement the Python class `Callbacks` described below. Class description: Failsafe callbacks executor. Method signatures and docstrings: - def set_current(self): Set current object during context. - def execute(self, *args, **kwargs): Execute callbacks.
Implement the Python class `Callbacks` described below. Class description: Failsafe callbacks executor. Method signatures and docstrings: - def set_current(self): Set current object during context. - def execute(self, *args, **kwargs): Execute callbacks. <|skeleton|> class Callbacks: """Failsafe callbacks execut...
e346c61db83397da1a8d80ed3a0e33aa7f677533
<|skeleton|> class Callbacks: """Failsafe callbacks executor.""" def set_current(self): """Set current object during context.""" <|body_0|> def execute(self, *args, **kwargs): """Execute callbacks.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Callbacks: """Failsafe callbacks executor.""" def set_current(self): """Set current object during context.""" Callbacks.current = self try: yield finally: if Callbacks.current is self: Callbacks.current = None def execute(self, ...
the_stack_v2_python_sparse
lib/callback.py
tws0002/Nuke-2
train
1
4b81d6fe1efac29ceeb7066b77453049ceb4647b
[ "if not root:\n return []\nlevel = [(root, 0)]\nres = {}\nmincol, maxcol = (1 << 31, -1 << 31)\nwhile level:\n for node, col in level:\n mincol = min(mincol, col)\n maxcol = max(maxcol, col)\n res[col] = res.get(col, []) + [node.val]\n tmp = []\n for node, col in level:\n if ...
<|body_start_0|> if not root: return [] level = [(root, 0)] res = {} mincol, maxcol = (1 << 31, -1 << 31) while level: for node, col in level: mincol = min(mincol, col) maxcol = max(maxcol, col) res[col] = re...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def levelOrdervectical(self, root): """:type root: TreeNode :rtype: List[List[int]]""" <|body_0|> def levelOrder(self, root): """:type root: TreeNode :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not root: ...
stack_v2_sparse_classes_36k_train_010039
1,540
permissive
[ { "docstring": ":type root: TreeNode :rtype: List[List[int]]", "name": "levelOrdervectical", "signature": "def levelOrdervectical(self, root)" }, { "docstring": ":type root: TreeNode :rtype: List[List[int]]", "name": "levelOrder", "signature": "def levelOrder(self, root)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def levelOrdervectical(self, root): :type root: TreeNode :rtype: List[List[int]] - def levelOrder(self, root): :type root: TreeNode :rtype: List[List[int]]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def levelOrdervectical(self, root): :type root: TreeNode :rtype: List[List[int]] - def levelOrder(self, root): :type root: TreeNode :rtype: List[List[int]] <|skeleton|> class So...
86f1cb98de801f58c39d9a48ce9de12df7303d20
<|skeleton|> class Solution: def levelOrdervectical(self, root): """:type root: TreeNode :rtype: List[List[int]]""" <|body_0|> def levelOrder(self, root): """:type root: TreeNode :rtype: List[List[int]]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def levelOrdervectical(self, root): """:type root: TreeNode :rtype: List[List[int]]""" if not root: return [] level = [(root, 0)] res = {} mincol, maxcol = (1 << 31, -1 << 31) while level: for node, col in level: ...
the_stack_v2_python_sparse
102-Binary-Tree-Level-Order-Traversal/solution.py
Tanych/CodeTracking
train
0
1bb69a91efb77ee151f70f2ba35860b4a4cbaaea
[ "os_walk_input_iter = (('a1', ['b1', 'b2'], ['c1', 'd1']), ('a2', ['b3', 'b4'], ['c2', 'd2']), ('a3', ['b5', 'b6'], ['c3', 'd3']))\nos_walk_expected_output = ('a1/b1', 'a1/b2', 'a2/b3', 'a2/b4', 'a3/b5', 'a3/b6')\nos_walk_actual_output = tuple(da.lwc.search._adapt_os_walk_to_dirpath(os_walk_input_iter))\nassert os_...
<|body_start_0|> os_walk_input_iter = (('a1', ['b1', 'b2'], ['c1', 'd1']), ('a2', ['b3', 'b4'], ['c2', 'd2']), ('a3', ['b5', 'b6'], ['c3', 'd3'])) os_walk_expected_output = ('a1/b1', 'a1/b2', 'a2/b3', 'a2/b4', 'a3/b5', 'a3/b6') os_walk_actual_output = tuple(da.lwc.search._adapt_os_walk_to_dirpat...
Tet cases for the _adapt_os_walk_to_dirpath function.
Specify_AdaptOsWalkToDirpath
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Specify_AdaptOsWalkToDirpath: """Tet cases for the _adapt_os_walk_to_dirpath function.""" def it_serialises_a_simple_tree(self): """Test _adapt_os_walk_to_dirpath handles a simple use case as expected. The _adapt_os_walk_to_dirpath should take output in the form provided by os.walk a...
stack_v2_sparse_classes_36k_train_010040
29,518
permissive
[ { "docstring": "Test _adapt_os_walk_to_dirpath handles a simple use case as expected. The _adapt_os_walk_to_dirpath should take output in the form provided by os.walk and should adapt it to produce a sequence of \"flat\" directory-paths.", "name": "it_serialises_a_simple_tree", "signature": "def it_seri...
2
null
Implement the Python class `Specify_AdaptOsWalkToDirpath` described below. Class description: Tet cases for the _adapt_os_walk_to_dirpath function. Method signatures and docstrings: - def it_serialises_a_simple_tree(self): Test _adapt_os_walk_to_dirpath handles a simple use case as expected. The _adapt_os_walk_to_dir...
Implement the Python class `Specify_AdaptOsWalkToDirpath` described below. Class description: Tet cases for the _adapt_os_walk_to_dirpath function. Method signatures and docstrings: - def it_serialises_a_simple_tree(self): Test _adapt_os_walk_to_dirpath handles a simple use case as expected. The _adapt_os_walk_to_dir...
04a13be2792323e3f9fdb83fd236a8e9cfe6aa2d
<|skeleton|> class Specify_AdaptOsWalkToDirpath: """Tet cases for the _adapt_os_walk_to_dirpath function.""" def it_serialises_a_simple_tree(self): """Test _adapt_os_walk_to_dirpath handles a simple use case as expected. The _adapt_os_walk_to_dirpath should take output in the form provided by os.walk a...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Specify_AdaptOsWalkToDirpath: """Tet cases for the _adapt_os_walk_to_dirpath function.""" def it_serialises_a_simple_tree(self): """Test _adapt_os_walk_to_dirpath handles a simple use case as expected. The _adapt_os_walk_to_dirpath should take output in the form provided by os.walk and should ada...
the_stack_v2_python_sparse
a3_src/h70_internal/da/lwc/spec/spec_search.py
wtpayne/hiai
train
5
89535d84d776914b034e79d2f2b27389175f8a03
[ "self.modules = configuration['sed_modules']\nself.parameters = [self._param_dict_combine(configuration['sed_modules_params'][module]) for module in self.modules]\nself.shape = tuple((len(parameter) for parameter in self.parameters))\nself.size = int(np.product(self.shape))", "dictionary = dict(dictionary)\nfor k...
<|body_start_0|> self.modules = configuration['sed_modules'] self.parameters = [self._param_dict_combine(configuration['sed_modules_params'][module]) for module in self.modules] self.shape = tuple((len(parameter) for parameter in self.parameters)) self.size = int(np.product(self.shape)) ...
Class to generate a parameters handler for a systematic grid using the parameters given in the pcigale.ini file.
ParametersHandlerGrid
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ParametersHandlerGrid: """Class to generate a parameters handler for a systematic grid using the parameters given in the pcigale.ini file.""" def __init__(self, configuration): """Instantiate the class. Parameters ---------- configuration: dictionary Contains the modules in the order...
stack_v2_sparse_classes_36k_train_010041
7,942
no_license
[ { "docstring": "Instantiate the class. Parameters ---------- configuration: dictionary Contains the modules in the order they are called", "name": "__init__", "signature": "def __init__(self, configuration)" }, { "docstring": "Given a dictionary associating to each key an array, returns all the ...
4
stack_v2_sparse_classes_30k_train_013404
Implement the Python class `ParametersHandlerGrid` described below. Class description: Class to generate a parameters handler for a systematic grid using the parameters given in the pcigale.ini file. Method signatures and docstrings: - def __init__(self, configuration): Instantiate the class. Parameters ---------- co...
Implement the Python class `ParametersHandlerGrid` described below. Class description: Class to generate a parameters handler for a systematic grid using the parameters given in the pcigale.ini file. Method signatures and docstrings: - def __init__(self, configuration): Instantiate the class. Parameters ---------- co...
9ef9b99425537350b8706fddfe90ed47301107a5
<|skeleton|> class ParametersHandlerGrid: """Class to generate a parameters handler for a systematic grid using the parameters given in the pcigale.ini file.""" def __init__(self, configuration): """Instantiate the class. Parameters ---------- configuration: dictionary Contains the modules in the order...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ParametersHandlerGrid: """Class to generate a parameters handler for a systematic grid using the parameters given in the pcigale.ini file.""" def __init__(self, configuration): """Instantiate the class. Parameters ---------- configuration: dictionary Contains the modules in the order they are cal...
the_stack_v2_python_sparse
pcigale/handlers/parameters_handler.py
JohannesBuchner/cigale
train
5
3cfcee4c5b7fdbea4bc8a26213279457f5ce63e9
[ "self.num_positions = num_positions\nself.num_trials = num_trials\nself.position_value = 1000 / self.num_positions", "uniform_list = np.random.uniform(0, 1, self.num_positions)\nresult = np.zeros(self.num_positions)\nfor i in range(self.num_positions):\n if uniform_list[i] <= 0.49:\n result[i] = self.po...
<|body_start_0|> self.num_positions = num_positions self.num_trials = num_trials self.position_value = 1000 / self.num_positions <|end_body_0|> <|body_start_1|> uniform_list = np.random.uniform(0, 1, self.num_positions) result = np.zeros(self.num_positions) for i in rang...
The investment class inits number of shares to buy(num_positions) and number of times to repeated the test(num_trials). It also contains two methods: get_cumu_ret and get_daily_ret.
investment
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class investment: """The investment class inits number of shares to buy(num_positions) and number of times to repeated the test(num_trials). It also contains two methods: get_cumu_ret and get_daily_ret.""" def __init__(self, num_positions, num_trials): """Constructor""" <|body_0|> ...
stack_v2_sparse_classes_36k_train_010042
2,603
no_license
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self, num_positions, num_trials)" }, { "docstring": "The method returns cumulative return, which is the outcome of simulation of one day's investment for different choice of positions.", "name": "get_cumu_ret", ...
3
stack_v2_sparse_classes_30k_train_007645
Implement the Python class `investment` described below. Class description: The investment class inits number of shares to buy(num_positions) and number of times to repeated the test(num_trials). It also contains two methods: get_cumu_ret and get_daily_ret. Method signatures and docstrings: - def __init__(self, num_p...
Implement the Python class `investment` described below. Class description: The investment class inits number of shares to buy(num_positions) and number of times to repeated the test(num_trials). It also contains two methods: get_cumu_ret and get_daily_ret. Method signatures and docstrings: - def __init__(self, num_p...
5b904060e8bced7f91547ad7f7819773a7450a1e
<|skeleton|> class investment: """The investment class inits number of shares to buy(num_positions) and number of times to repeated the test(num_trials). It also contains two methods: get_cumu_ret and get_daily_ret.""" def __init__(self, num_positions, num_trials): """Constructor""" <|body_0|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class investment: """The investment class inits number of shares to buy(num_positions) and number of times to repeated the test(num_trials). It also contains two methods: get_cumu_ret and get_daily_ret.""" def __init__(self, num_positions, num_trials): """Constructor""" self.num_positions = num...
the_stack_v2_python_sparse
zg475/investment.py
ds-ga-1007/assignment8
train
1
6eeb2d6be78771a9465d6d2e7b9be50ccaa4674f
[ "super().__init__(num_locations, coverages_per_location)\nself.dtypes = OrderedDict([('from_agg_id', 'i'), ('level_id', 'i'), ('to_agg_id', 'i')])\nself.data_length = num_locations * coverages_per_location * 2\nself.file_name = os.path.join(directory, 'fm_programme.bin')", "levels = [1, 10]\nlevels = range(1, len...
<|body_start_0|> super().__init__(num_locations, coverages_per_location) self.dtypes = OrderedDict([('from_agg_id', 'i'), ('level_id', 'i'), ('to_agg_id', 'i')]) self.data_length = num_locations * coverages_per_location * 2 self.file_name = os.path.join(directory, 'fm_programme.bin') <|e...
Generate data for Financial Model Programme dummy model Oasis file. This file shows the level hierarchy. Attributes: generate_data: Generate Financial Model Programme dummy model Oasis file data.
FMProgrammeFile
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FMProgrammeFile: """Generate data for Financial Model Programme dummy model Oasis file. This file shows the level hierarchy. Attributes: generate_data: Generate Financial Model Programme dummy model Oasis file data.""" def __init__(self, num_locations, coverages_per_location, directory): ...
stack_v2_sparse_classes_36k_train_010043
39,722
permissive
[ { "docstring": "Initialise Financial Model Programme file class. Args: num_locations (int): number of locations. coverages_per_location (int): number of coverage types per location. directory (str): dummy model file destination.", "name": "__init__", "signature": "def __init__(self, num_locations, cover...
2
null
Implement the Python class `FMProgrammeFile` described below. Class description: Generate data for Financial Model Programme dummy model Oasis file. This file shows the level hierarchy. Attributes: generate_data: Generate Financial Model Programme dummy model Oasis file data. Method signatures and docstrings: - def _...
Implement the Python class `FMProgrammeFile` described below. Class description: Generate data for Financial Model Programme dummy model Oasis file. This file shows the level hierarchy. Attributes: generate_data: Generate Financial Model Programme dummy model Oasis file data. Method signatures and docstrings: - def _...
23e704c335629ccd010969b1090446cfa3f384d5
<|skeleton|> class FMProgrammeFile: """Generate data for Financial Model Programme dummy model Oasis file. This file shows the level hierarchy. Attributes: generate_data: Generate Financial Model Programme dummy model Oasis file data.""" def __init__(self, num_locations, coverages_per_location, directory): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FMProgrammeFile: """Generate data for Financial Model Programme dummy model Oasis file. This file shows the level hierarchy. Attributes: generate_data: Generate Financial Model Programme dummy model Oasis file data.""" def __init__(self, num_locations, coverages_per_location, directory): """Initi...
the_stack_v2_python_sparse
oasislmf/computation/data/dummy_model/generate.py
OasisLMF/OasisLMF
train
122
60b6733d4e19a6b371aa03ae83f031e09701cc8a
[ "if bib_number <= 0:\n raise ValueError('bib_number must be strictely positive')\nself.bib_number = bib_number\nself.name = name\nif last_state:\n self.current_stage: WatchedProperty = WatchedProperty(last_state.current_stage.get_value())\n self.rank: WatchedProperty = WatchedProperty(last_state.rank.get_v...
<|body_start_0|> if bib_number <= 0: raise ValueError('bib_number must be strictely positive') self.bib_number = bib_number self.name = name if last_state: self.current_stage: WatchedProperty = WatchedProperty(last_state.current_stage.get_value()) self...
Represents the state of a team in a race file A state is a line in the race file
TeamState
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TeamState: """Represents the state of a team in a race file A state is a line in the race file""" def __init__(self, bib_number: int, name: str, last_state: Optional['TeamState']=None): """Creates a new team state A team state represents a line in a race file. The last_state paramete...
stack_v2_sparse_classes_36k_train_010044
5,116
no_license
[ { "docstring": "Creates a new team state A team state represents a line in a race file. The last_state parameter is used to keep old values. :param bib_number: bib number of the team :param name: name of the team :param last_state: previous state from the last reading, could be None :raises ValueError: if bib_n...
3
stack_v2_sparse_classes_30k_train_011124
Implement the Python class `TeamState` described below. Class description: Represents the state of a team in a race file A state is a line in the race file Method signatures and docstrings: - def __init__(self, bib_number: int, name: str, last_state: Optional['TeamState']=None): Creates a new team state A team state ...
Implement the Python class `TeamState` described below. Class description: Represents the state of a team in a race file A state is a line in the race file Method signatures and docstrings: - def __init__(self, bib_number: int, name: str, last_state: Optional['TeamState']=None): Creates a new team state A team state ...
07cff53642f34c0897c81c506ac1c93437de9bca
<|skeleton|> class TeamState: """Represents the state of a team in a race file A state is a line in the race file""" def __init__(self, bib_number: int, name: str, last_state: Optional['TeamState']=None): """Creates a new team state A team state represents a line in a race file. The last_state paramete...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TeamState: """Represents the state of a team in a race file A state is a line in the race file""" def __init__(self, bib_number: int, name: str, last_state: Optional['TeamState']=None): """Creates a new team state A team state represents a line in a race file. The last_state parameter is used to ...
the_stack_v2_python_sparse
uctl2_back/team_state.py
mdesmarais/UCTL2_Broadcaster
train
0
6cd96feb94dd5bcf9262e63c7a84f197ea6f8015
[ "super().__init__()\nassert hidden_size % 2 == 0\nself.hidden_size = hidden_size\nself._forward_lstm = nn.LSTMCell(input_size, hidden_size // 2)\nself._backward_lstm = nn.LSTMCell(input_size, hidden_size // 2)\nself._dropout_in = nn.Dropout(dropout)\nself._dropout_h = nn.Dropout(dropout)", "L, B, _ = x.data.shape...
<|body_start_0|> super().__init__() assert hidden_size % 2 == 0 self.hidden_size = hidden_size self._forward_lstm = nn.LSTMCell(input_size, hidden_size // 2) self._backward_lstm = nn.LSTMCell(input_size, hidden_size // 2) self._dropout_in = nn.Dropout(dropout) sel...
BidirectionalLSTM
[ "MIT", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BidirectionalLSTM: def __init__(self, input_size: int, hidden_size: int, dropout: float=0.0): """Parameters ---------- n_elem: int The number of words including <unknown> label. embedding_size: int The dimention of each embedding hidden_size: int The number of features in LSTM dropout: f...
stack_v2_sparse_classes_36k_train_010045
2,691
permissive
[ { "docstring": "Parameters ---------- n_elem: int The number of words including <unknown> label. embedding_size: int The dimention of each embedding hidden_size: int The number of features in LSTM dropout: float The probability of dropout", "name": "__init__", "signature": "def __init__(self, input_size...
2
stack_v2_sparse_classes_30k_train_013459
Implement the Python class `BidirectionalLSTM` described below. Class description: Implement the BidirectionalLSTM class. Method signatures and docstrings: - def __init__(self, input_size: int, hidden_size: int, dropout: float=0.0): Parameters ---------- n_elem: int The number of words including <unknown> label. embe...
Implement the Python class `BidirectionalLSTM` described below. Class description: Implement the BidirectionalLSTM class. Method signatures and docstrings: - def __init__(self, input_size: int, hidden_size: int, dropout: float=0.0): Parameters ---------- n_elem: int The number of words including <unknown> label. embe...
573e94c567064705fa65267dd83946bf183197de
<|skeleton|> class BidirectionalLSTM: def __init__(self, input_size: int, hidden_size: int, dropout: float=0.0): """Parameters ---------- n_elem: int The number of words including <unknown> label. embedding_size: int The dimention of each embedding hidden_size: int The number of features in LSTM dropout: f...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BidirectionalLSTM: def __init__(self, input_size: int, hidden_size: int, dropout: float=0.0): """Parameters ---------- n_elem: int The number of words including <unknown> label. embedding_size: int The dimention of each embedding hidden_size: int The number of features in LSTM dropout: float The proba...
the_stack_v2_python_sparse
mlprogram/nn/bidirectional_lstm.py
brando90/mlprogram
train
0
3ef97edba459a85ab0d974d3391e0ee7e938875a
[ "adb_monkey2 = 'adb shell pm list packages | find \"%s\" ' % package\nstatus = os.popen(adb_monkey2).read()\nif status:\n return True\nelse:\n return False", "adb = 'adb install %s' % apk_path\nprint(adb)\nos.system(adb)", "time.sleep(5)\nadb = 'adb uninstall %s' % package\nos.system(adb)" ]
<|body_start_0|> adb_monkey2 = 'adb shell pm list packages | find "%s" ' % package status = os.popen(adb_monkey2).read() if status: return True else: return False <|end_body_0|> <|body_start_1|> adb = 'adb install %s' % apk_path print(adb) ...
InstallUninstall
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InstallUninstall: def apk_install_status(self, package): """功能查找是否已经安装此安装包 package:包名 apk_path:包存放路径""" <|body_0|> def apk_install(self, apk_path): """功能安装APP package:包名 apk_path:包存放路径""" <|body_1|> def apk_uninstall(self, package): """功能: 卸载APP ...
stack_v2_sparse_classes_36k_train_010046
951
permissive
[ { "docstring": "功能查找是否已经安装此安装包 package:包名 apk_path:包存放路径", "name": "apk_install_status", "signature": "def apk_install_status(self, package)" }, { "docstring": "功能安装APP package:包名 apk_path:包存放路径", "name": "apk_install", "signature": "def apk_install(self, apk_path)" }, { "docstri...
3
stack_v2_sparse_classes_30k_train_011991
Implement the Python class `InstallUninstall` described below. Class description: Implement the InstallUninstall class. Method signatures and docstrings: - def apk_install_status(self, package): 功能查找是否已经安装此安装包 package:包名 apk_path:包存放路径 - def apk_install(self, apk_path): 功能安装APP package:包名 apk_path:包存放路径 - def apk_uni...
Implement the Python class `InstallUninstall` described below. Class description: Implement the InstallUninstall class. Method signatures and docstrings: - def apk_install_status(self, package): 功能查找是否已经安装此安装包 package:包名 apk_path:包存放路径 - def apk_install(self, apk_path): 功能安装APP package:包名 apk_path:包存放路径 - def apk_uni...
a95d891a8b1204a9e38071b480aae484dd21e70a
<|skeleton|> class InstallUninstall: def apk_install_status(self, package): """功能查找是否已经安装此安装包 package:包名 apk_path:包存放路径""" <|body_0|> def apk_install(self, apk_path): """功能安装APP package:包名 apk_path:包存放路径""" <|body_1|> def apk_uninstall(self, package): """功能: 卸载APP ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InstallUninstall: def apk_install_status(self, package): """功能查找是否已经安装此安装包 package:包名 apk_path:包存放路径""" adb_monkey2 = 'adb shell pm list packages | find "%s" ' % package status = os.popen(adb_monkey2).read() if status: return True else: return ...
the_stack_v2_python_sparse
common/app_common/shell_install_adb.py
lineOneTwo/Test_Api_App
train
0
50137f3a6036d37ad5ac4d14a5f25d2215d4384a
[ "precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')\nfor line in self:\n if not float_is_zero(qty, precision_digits=precision):\n vals = line._prepare_invoice_line(qty=qty)\n vals.update({'invoice_id': invoice_id, 'purchase_line_id': line.id, 'price_unit': self.price...
<|body_start_0|> precision = self.env['decimal.precision'].precision_get('Product Unit of Measure') for line in self: if not float_is_zero(qty, precision_digits=precision): vals = line._prepare_invoice_line(qty=qty) vals.update({'invoice_id': invoice_id, 'purc...
PurchaseOrderLine
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PurchaseOrderLine: def invoice_line_create(self, invoice_id, qty): """Create an invoice line. The quantity to invoice can be positive (invoice) or negative (refund). :param invoice_id: integer :param qty: float quantity to invoice""" <|body_0|> def _prepare_invoice_line(self...
stack_v2_sparse_classes_36k_train_010047
9,530
no_license
[ { "docstring": "Create an invoice line. The quantity to invoice can be positive (invoice) or negative (refund). :param invoice_id: integer :param qty: float quantity to invoice", "name": "invoice_line_create", "signature": "def invoice_line_create(self, invoice_id, qty)" }, { "docstring": "Prepa...
4
stack_v2_sparse_classes_30k_train_020857
Implement the Python class `PurchaseOrderLine` described below. Class description: Implement the PurchaseOrderLine class. Method signatures and docstrings: - def invoice_line_create(self, invoice_id, qty): Create an invoice line. The quantity to invoice can be positive (invoice) or negative (refund). :param invoice_i...
Implement the Python class `PurchaseOrderLine` described below. Class description: Implement the PurchaseOrderLine class. Method signatures and docstrings: - def invoice_line_create(self, invoice_id, qty): Create an invoice line. The quantity to invoice can be positive (invoice) or negative (refund). :param invoice_i...
eea92d44bee76053619be00aa601b1efc4249589
<|skeleton|> class PurchaseOrderLine: def invoice_line_create(self, invoice_id, qty): """Create an invoice line. The quantity to invoice can be positive (invoice) or negative (refund). :param invoice_id: integer :param qty: float quantity to invoice""" <|body_0|> def _prepare_invoice_line(self...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PurchaseOrderLine: def invoice_line_create(self, invoice_id, qty): """Create an invoice line. The quantity to invoice can be positive (invoice) or negative (refund). :param invoice_id: integer :param qty: float quantity to invoice""" precision = self.env['decimal.precision'].precision_get('Pro...
the_stack_v2_python_sparse
linkloving_purchase_invoice/models/purchase_order.py
iverson2937/linklovingaddons
train
1
14d1908f657668fba848745530c877edceb280ed
[ "self.records = records\nself.cheapMetric = cheapDistanceMetric\nif not callable(self.cheapMetric):\n raise ValueError('Cheap distance metric must be callable function.')\nself.method = ermethod\nself.t1 = t1\nself.t2 = t2\nif scoreType == ScoreTypes.DISTANCE:\n self.scoreIsBetter = lambda score, best: score ...
<|body_start_0|> self.records = records self.cheapMetric = cheapDistanceMetric if not callable(self.cheapMetric): raise ValueError('Cheap distance metric must be callable function.') self.method = ermethod self.t1 = t1 self.t2 = t2 if scoreType == Scor...
Class to do blocking using canopies.
CanopiesBlocker
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CanopiesBlocker: """Class to do blocking using canopies.""" def __init__(self, records, cheapDistanceMetric, ermethod, t1, t2, scoreType, randomize=True): """Constructor :param records: all the records to cluster :param cheapDistanceMetric: A cheap distance metric used to form the ca...
stack_v2_sparse_classes_36k_train_010048
6,582
no_license
[ { "docstring": "Constructor :param records: all the records to cluster :param cheapDistanceMetric: A cheap distance metric used to form the canopies. :param ermethod: An ER method to do the full clustering within each canopy. :param t1: First threshold for canopies :param t2: Second threshold for canopies :para...
6
stack_v2_sparse_classes_30k_train_018894
Implement the Python class `CanopiesBlocker` described below. Class description: Class to do blocking using canopies. Method signatures and docstrings: - def __init__(self, records, cheapDistanceMetric, ermethod, t1, t2, scoreType, randomize=True): Constructor :param records: all the records to cluster :param cheapDi...
Implement the Python class `CanopiesBlocker` described below. Class description: Class to do blocking using canopies. Method signatures and docstrings: - def __init__(self, records, cheapDistanceMetric, ermethod, t1, t2, scoreType, randomize=True): Constructor :param records: all the records to cluster :param cheapDi...
8399c88ab0fdc7736dddcf5239eea655d613c61d
<|skeleton|> class CanopiesBlocker: """Class to do blocking using canopies.""" def __init__(self, records, cheapDistanceMetric, ermethod, t1, t2, scoreType, randomize=True): """Constructor :param records: all the records to cluster :param cheapDistanceMetric: A cheap distance metric used to form the ca...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CanopiesBlocker: """Class to do blocking using canopies.""" def __init__(self, records, cheapDistanceMetric, ermethod, t1, t2, scoreType, randomize=True): """Constructor :param records: all the records to cluster :param cheapDistanceMetric: A cheap distance metric used to form the canopies. :para...
the_stack_v2_python_sparse
canopies.py
timdestan/quiz-bowl-entity-resolution
train
1
f6400a1157a563dc0a1162d9bed14478f096afaa
[ "super(ReluNet, self).__init__()\nself.input_dim = input_dim\nself.output_dim = output_dim\nself.hidden_dim = hidden_dim\nself.num_layers = num_layers\nself.num_epochs = num_epochs\nself.threshold = threshold\nself.learning_rate = learning_rate\nself.layers = nn.ModuleList()\nself.layers.append(nn.Linear(input_dim,...
<|body_start_0|> super(ReluNet, self).__init__() self.input_dim = input_dim self.output_dim = output_dim self.hidden_dim = hidden_dim self.num_layers = num_layers self.num_epochs = num_epochs self.threshold = threshold self.learning_rate = learning_rate ...
Fully connected neural network with relu activation
ReluNet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReluNet: """Fully connected neural network with relu activation""" def __init__(self, input_dim, output_dim, hidden_dim=100, num_layers=2, num_epochs=100, learning_rate=0.001, threshold=0.1): """Initilize a Neural Network with Relu activation Args: input_dim: int -- dimension of the ...
stack_v2_sparse_classes_36k_train_010049
4,882
no_license
[ { "docstring": "Initilize a Neural Network with Relu activation Args: input_dim: int -- dimension of the input feature output_dim: int -- dimension of the output feature hidden_dim: int -- number of hidden units at each layer num_layers: int -- number of hidden layers num_epochs: int -- number of epochs to trai...
5
stack_v2_sparse_classes_30k_train_017125
Implement the Python class `ReluNet` described below. Class description: Fully connected neural network with relu activation Method signatures and docstrings: - def __init__(self, input_dim, output_dim, hidden_dim=100, num_layers=2, num_epochs=100, learning_rate=0.001, threshold=0.1): Initilize a Neural Network with ...
Implement the Python class `ReluNet` described below. Class description: Fully connected neural network with relu activation Method signatures and docstrings: - def __init__(self, input_dim, output_dim, hidden_dim=100, num_layers=2, num_epochs=100, learning_rate=0.001, threshold=0.1): Initilize a Neural Network with ...
d7e651024b07587b46497183d90934561a4839e2
<|skeleton|> class ReluNet: """Fully connected neural network with relu activation""" def __init__(self, input_dim, output_dim, hidden_dim=100, num_layers=2, num_epochs=100, learning_rate=0.001, threshold=0.1): """Initilize a Neural Network with Relu activation Args: input_dim: int -- dimension of the ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ReluNet: """Fully connected neural network with relu activation""" def __init__(self, input_dim, output_dim, hidden_dim=100, num_layers=2, num_epochs=100, learning_rate=0.001, threshold=0.1): """Initilize a Neural Network with Relu activation Args: input_dim: int -- dimension of the input feature...
the_stack_v2_python_sparse
model/relunet.py
SSF-climate/SSF
train
7
4f9fe08196bd278eaa4eab75ea0ee1170a17978a
[ "super().__init__()\nlayers = OrderedDict([('inp_layers', nn.Sequential(nn.ReflectionPad2d(3), nn.Conv2d(in_channels=inp_channel_dim, out_channels=hidden_channel_dim, kernel_size=7, bias=False), nn.BatchNorm2d(hidden_channel_dim), nn.ReLU(True)))])\nfor i in range(2):\n cur_inp_dim = 2 ** i * hidden_channel_dim\...
<|body_start_0|> super().__init__() layers = OrderedDict([('inp_layers', nn.Sequential(nn.ReflectionPad2d(3), nn.Conv2d(in_channels=inp_channel_dim, out_channels=hidden_channel_dim, kernel_size=7, bias=False), nn.BatchNorm2d(hidden_channel_dim), nn.ReLU(True)))]) for i in range(2): c...
Generator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Generator: def __init__(self, inp_channel_dim: int, out_channel_dim: int, hidden_channel_dim: int=64, n_blocks: int=6): """Generator with downsampling, residual blocks and upsampling. Args: inp_channel_dim: number of channels of the input image out_channel_dim: number of channels of the ...
stack_v2_sparse_classes_36k_train_010050
6,411
permissive
[ { "docstring": "Generator with downsampling, residual blocks and upsampling. Args: inp_channel_dim: number of channels of the input image out_channel_dim: number of channels of the output image hidden_channel_dim: number of channels after first layer. Number of channels in res_blocks will be 4*hidden_channels_d...
2
stack_v2_sparse_classes_30k_train_004879
Implement the Python class `Generator` described below. Class description: Implement the Generator class. Method signatures and docstrings: - def __init__(self, inp_channel_dim: int, out_channel_dim: int, hidden_channel_dim: int=64, n_blocks: int=6): Generator with downsampling, residual blocks and upsampling. Args: ...
Implement the Python class `Generator` described below. Class description: Implement the Generator class. Method signatures and docstrings: - def __init__(self, inp_channel_dim: int, out_channel_dim: int, hidden_channel_dim: int=64, n_blocks: int=6): Generator with downsampling, residual blocks and upsampling. Args: ...
b6caf28b1d56f9abef80e8fd34eede39f45c8c7d
<|skeleton|> class Generator: def __init__(self, inp_channel_dim: int, out_channel_dim: int, hidden_channel_dim: int=64, n_blocks: int=6): """Generator with downsampling, residual blocks and upsampling. Args: inp_channel_dim: number of channels of the input image out_channel_dim: number of channels of the ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Generator: def __init__(self, inp_channel_dim: int, out_channel_dim: int, hidden_channel_dim: int=64, n_blocks: int=6): """Generator with downsampling, residual blocks and upsampling. Args: inp_channel_dim: number of channels of the input image out_channel_dim: number of channels of the output image h...
the_stack_v2_python_sparse
src/modules/generator.py
elephantmipt/cycle-gan-distillation
train
1
ffb50588b53355aa5e320c30d1631be9fec3b144
[ "self.undo = nuke.Undo\nself.__disabled = self.undo.disabled()\nself.script = script\nif save_func:\n self.save_func = save_func\nelse:\n self.save_func = nuke.scriptSave", "if self.__disabled:\n self.undo.enable()\nself.undo.begin()", "self.save_func(self.script)\nself.undo.cancel()\nif self.__disable...
<|body_start_0|> self.undo = nuke.Undo self.__disabled = self.undo.disabled() self.script = script if save_func: self.save_func = save_func else: self.save_func = nuke.scriptSave <|end_body_0|> <|body_start_1|> if self.__disabled: self...
Given a script to save to, will save all of the changes made in the with block to the script, then undoes those changes in the current script. For example: with WriteChanges('/Volumes/af/show/omg/script.nk'): for node in nuke.allNodes(): node.setYpos(100)
WriteChanges
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WriteChanges: """Given a script to save to, will save all of the changes made in the with block to the script, then undoes those changes in the current script. For example: with WriteChanges('/Volumes/af/show/omg/script.nk'): for node in nuke.allNodes(): node.setYpos(100)""" def __init__(sel...
stack_v2_sparse_classes_36k_train_010051
23,998
no_license
[ { "docstring": "Initialize a WriteChanges context manager. Must provide a script to write to. If you provide a save_func, it will be called instead of the default `nuke.scriptSave`. The function must have the same interface as `nuke.scriptSave`. A possible alternative is `nuke.nodeCopy`.", "name": "__init__...
3
stack_v2_sparse_classes_30k_train_003438
Implement the Python class `WriteChanges` described below. Class description: Given a script to save to, will save all of the changes made in the with block to the script, then undoes those changes in the current script. For example: with WriteChanges('/Volumes/af/show/omg/script.nk'): for node in nuke.allNodes(): nod...
Implement the Python class `WriteChanges` described below. Class description: Given a script to save to, will save all of the changes made in the with block to the script, then undoes those changes in the current script. For example: with WriteChanges('/Volumes/af/show/omg/script.nk'): for node in nuke.allNodes(): nod...
ffd112312632731db53aa94c77a0bb6d63243474
<|skeleton|> class WriteChanges: """Given a script to save to, will save all of the changes made in the with block to the script, then undoes those changes in the current script. For example: with WriteChanges('/Volumes/af/show/omg/script.nk'): for node in nuke.allNodes(): node.setYpos(100)""" def __init__(sel...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WriteChanges: """Given a script to save to, will save all of the changes made in the with block to the script, then undoes those changes in the current script. For example: with WriteChanges('/Volumes/af/show/omg/script.nk'): for node in nuke.allNodes(): node.setYpos(100)""" def __init__(self, script, sa...
the_stack_v2_python_sparse
apps/nuke/scripts/python/zync_nuke.py
tws0002/gs-code
train
1
7ee6d4e52f129fa35d6ec7f568a63af4754ad2aa
[ "positive = (dividend < 0) is (divisor < 0)\ndividend, divisor = (abs(dividend), abs(divisor))\nres = 0\nc, sub = (1, divisor)\nwhile dividend >= divisor:\n '\\n for example, if we want to calc (17/2)\\n ret = 0\\n 17-2 ,ret+=1 left=15\\n 15-4 ,ret+=2 left=11\\n ...
<|body_start_0|> positive = (dividend < 0) is (divisor < 0) dividend, divisor = (abs(dividend), abs(divisor)) res = 0 c, sub = (1, divisor) while dividend >= divisor: '\n for example, if we want to calc (17/2)\n ret = 0\n 17-2 ,ret+=1 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def divide(self, dividend, divisor): """:param dividend: :param divisor: :return:""" <|body_0|> def divide2(self, dividend, divisor): """效率低 :type dividend: int :type divisor: int :rtype: int""" <|body_1|> def divide3(self, dividend, divisor): ...
stack_v2_sparse_classes_36k_train_010052
4,179
no_license
[ { "docstring": ":param dividend: :param divisor: :return:", "name": "divide", "signature": "def divide(self, dividend, divisor)" }, { "docstring": "效率低 :type dividend: int :type divisor: int :rtype: int", "name": "divide2", "signature": "def divide2(self, dividend, divisor)" }, { ...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def divide(self, dividend, divisor): :param dividend: :param divisor: :return: - def divide2(self, dividend, divisor): 效率低 :type dividend: int :type divisor: int :rtype: int - de...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def divide(self, dividend, divisor): :param dividend: :param divisor: :return: - def divide2(self, dividend, divisor): 效率低 :type dividend: int :type divisor: int :rtype: int - de...
5d3574ccd282d0146c83c286ae28d8baaabd4910
<|skeleton|> class Solution: def divide(self, dividend, divisor): """:param dividend: :param divisor: :return:""" <|body_0|> def divide2(self, dividend, divisor): """效率低 :type dividend: int :type divisor: int :rtype: int""" <|body_1|> def divide3(self, dividend, divisor): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def divide(self, dividend, divisor): """:param dividend: :param divisor: :return:""" positive = (dividend < 0) is (divisor < 0) dividend, divisor = (abs(dividend), abs(divisor)) res = 0 c, sub = (1, divisor) while dividend >= divisor: '\n ...
the_stack_v2_python_sparse
29_两数相除.py
lovehhf/LeetCode
train
0
9bd7ec7c5615c33b3a7ee22155991f6dd92cb125
[ "self.info = forq_haplotype\nself.length = len(self.info)\nself.founders = [haplotype_id for position, haplotype_id in self.info]\nself.founders_set = list(set(self.founders))\nself.positions = None\nself.position_map_offset = None\nself.temp_map = None\nself.map = list()", "if self.length == 1:\n self.map.app...
<|body_start_0|> self.info = forq_haplotype self.length = len(self.info) self.founders = [haplotype_id for position, haplotype_id in self.info] self.founders_set = list(set(self.founders)) self.positions = None self.position_map_offset = None self.temp_map = None ...
Forqs Haplotype Object Example [(0, 91), (1235052, 105), (1251805, 105)] or [(0, 91)]
ForqsHaplotype
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ForqsHaplotype: """Forqs Haplotype Object Example [(0, 91), (1235052, 105), (1251805, 105)] or [(0, 91)]""" def __init__(self, forq_haplotype): """Forqs Haplotype Instance Creation""" <|body_0|> def haplotype_map_single(self): """Create the haplotype guide for as...
stack_v2_sparse_classes_36k_train_010053
2,539
no_license
[ { "docstring": "Forqs Haplotype Instance Creation", "name": "__init__", "signature": "def __init__(self, forq_haplotype)" }, { "docstring": "Create the haplotype guide for assembling the recombined forqs haplotype outputs", "name": "haplotype_map_single", "signature": "def haplotype_map_...
2
stack_v2_sparse_classes_30k_test_000396
Implement the Python class `ForqsHaplotype` described below. Class description: Forqs Haplotype Object Example [(0, 91), (1235052, 105), (1251805, 105)] or [(0, 91)] Method signatures and docstrings: - def __init__(self, forq_haplotype): Forqs Haplotype Instance Creation - def haplotype_map_single(self): Create the h...
Implement the Python class `ForqsHaplotype` described below. Class description: Forqs Haplotype Object Example [(0, 91), (1235052, 105), (1251805, 105)] or [(0, 91)] Method signatures and docstrings: - def __init__(self, forq_haplotype): Forqs Haplotype Instance Creation - def haplotype_map_single(self): Create the h...
13ccb51ab30bbd8a45228986017b23038c04357d
<|skeleton|> class ForqsHaplotype: """Forqs Haplotype Object Example [(0, 91), (1235052, 105), (1251805, 105)] or [(0, 91)]""" def __init__(self, forq_haplotype): """Forqs Haplotype Instance Creation""" <|body_0|> def haplotype_map_single(self): """Create the haplotype guide for as...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ForqsHaplotype: """Forqs Haplotype Object Example [(0, 91), (1235052, 105), (1251805, 105)] or [(0, 91)]""" def __init__(self, forq_haplotype): """Forqs Haplotype Instance Creation""" self.info = forq_haplotype self.length = len(self.info) self.founders = [haplotype_id for...
the_stack_v2_python_sparse
simulations/haptools/forqshaplotype.py
transferome/Simulations
train
0
5b162013a237cb549fdf1e577bf7fa9e9048aff4
[ "fast = slow = head\nwhile fast and slow and fast.next:\n fast = fast.next.next\n slow = slow.next\n if fast is slow:\n return True\nreturn False", "cache = set()\nwhile head:\n if head in cache:\n return True\n else:\n cache.add(head)\n head = head.next\nreturn False" ]
<|body_start_0|> fast = slow = head while fast and slow and fast.next: fast = fast.next.next slow = slow.next if fast is slow: return True return False <|end_body_0|> <|body_start_1|> cache = set() while head: if he...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def hasCycle1(self, head: ListNode): """判断链表是否有环: 解法: 快慢指针 :type head: ListNode :rtype: bool""" <|body_0|> def hasCycle2(self, head: ListNode): """判断链表是否有环 解法: 哈希表判重方式 时间复杂度: O(n) 空间复杂度: O(n) :type head: ListNode :rtype: bool""" <|body_1|> <|end_sk...
stack_v2_sparse_classes_36k_train_010054
1,249
no_license
[ { "docstring": "判断链表是否有环: 解法: 快慢指针 :type head: ListNode :rtype: bool", "name": "hasCycle1", "signature": "def hasCycle1(self, head: ListNode)" }, { "docstring": "判断链表是否有环 解法: 哈希表判重方式 时间复杂度: O(n) 空间复杂度: O(n) :type head: ListNode :rtype: bool", "name": "hasCycle2", "signature": "def hasCyc...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def hasCycle1(self, head: ListNode): 判断链表是否有环: 解法: 快慢指针 :type head: ListNode :rtype: bool - def hasCycle2(self, head: ListNode): 判断链表是否有环 解法: 哈希表判重方式 时间复杂度: O(n) 空间复杂度: O(n) :typ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def hasCycle1(self, head: ListNode): 判断链表是否有环: 解法: 快慢指针 :type head: ListNode :rtype: bool - def hasCycle2(self, head: ListNode): 判断链表是否有环 解法: 哈希表判重方式 时间复杂度: O(n) 空间复杂度: O(n) :typ...
c0dd577481b46129d950354d567d332a4d091137
<|skeleton|> class Solution: def hasCycle1(self, head: ListNode): """判断链表是否有环: 解法: 快慢指针 :type head: ListNode :rtype: bool""" <|body_0|> def hasCycle2(self, head: ListNode): """判断链表是否有环 解法: 哈希表判重方式 时间复杂度: O(n) 空间复杂度: O(n) :type head: ListNode :rtype: bool""" <|body_1|> <|end_sk...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def hasCycle1(self, head: ListNode): """判断链表是否有环: 解法: 快慢指针 :type head: ListNode :rtype: bool""" fast = slow = head while fast and slow and fast.next: fast = fast.next.next slow = slow.next if fast is slow: return True ...
the_stack_v2_python_sparse
leetcode/141_环形链表_是否有环.py
tenqaz/crazy_arithmetic
train
0
27446b7a109f296100c0a523f8a2cd544faa817e
[ "data = super(CharacterControl, self).parse(args)\nvalue = data[self.name]\nif value is not None:\n if self.strip is not None:\n value = self.strip.sub('', value)\n data[self.name] = value\n if self.minlen is not None and len(value) < self.minlen:\n m = tr('Input for field %s is too short...
<|body_start_0|> data = super(CharacterControl, self).parse(args) value = data[self.name] if value is not None: if self.strip is not None: value = self.strip.sub('', value) data[self.name] = value if self.minlen is not None and len(value) <...
Base class for text controls.
CharacterControl
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CharacterControl: """Base class for text controls.""" def parse(self, args): """Parse `args' to Python format.""" <|body_0|> def unparse(self, object): """Parse `object' to string format.""" <|body_1|> <|end_skeleton|> <|body_start_0|> data = su...
stack_v2_sparse_classes_36k_train_010055
12,353
permissive
[ { "docstring": "Parse `args' to Python format.", "name": "parse", "signature": "def parse(self, args)" }, { "docstring": "Parse `object' to string format.", "name": "unparse", "signature": "def unparse(self, object)" } ]
2
null
Implement the Python class `CharacterControl` described below. Class description: Base class for text controls. Method signatures and docstrings: - def parse(self, args): Parse `args' to Python format. - def unparse(self, object): Parse `object' to string format.
Implement the Python class `CharacterControl` described below. Class description: Base class for text controls. Method signatures and docstrings: - def parse(self, args): Parse `args' to Python format. - def unparse(self, object): Parse `object' to string format. <|skeleton|> class CharacterControl: """Base clas...
3a533d3158860102866eaf603840691618f39f81
<|skeleton|> class CharacterControl: """Base class for text controls.""" def parse(self, args): """Parse `args' to Python format.""" <|body_0|> def unparse(self, object): """Parse `object' to string format.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CharacterControl: """Base class for text controls.""" def parse(self, args): """Parse `args' to Python format.""" data = super(CharacterControl, self).parse(args) value = data[self.name] if value is not None: if self.strip is not None: value = s...
the_stack_v2_python_sparse
draco2/form/control.py
geertj/draco2
train
0
ad9d35ce66fb9909cee3e2fea5ab582161c4691e
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn RichLongRunningOperation()", "from .long_running_operation import LongRunningOperation\nfrom .public_error import PublicError\nfrom .long_running_operation import LongRunningOperation\nfrom .public_error import PublicError\nfields: Dic...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return RichLongRunningOperation() <|end_body_0|> <|body_start_1|> from .long_running_operation import LongRunningOperation from .public_error import PublicError from .long_running_opera...
RichLongRunningOperation
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RichLongRunningOperation: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RichLongRunningOperation: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and cre...
stack_v2_sparse_classes_36k_train_010056
3,003
permissive
[ { "docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: RichLongRunningOperation", "name": "create_from_discriminator_value", "signature": "def create_from_discrimi...
3
null
Implement the Python class `RichLongRunningOperation` described below. Class description: Implement the RichLongRunningOperation class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RichLongRunningOperation: Creates a new instance of the appropriate c...
Implement the Python class `RichLongRunningOperation` described below. Class description: Implement the RichLongRunningOperation class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RichLongRunningOperation: Creates a new instance of the appropriate c...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class RichLongRunningOperation: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RichLongRunningOperation: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and cre...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RichLongRunningOperation: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RichLongRunningOperation: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object...
the_stack_v2_python_sparse
msgraph/generated/models/rich_long_running_operation.py
microsoftgraph/msgraph-sdk-python
train
135
fe61f19f2b83fd465fb0a05ffb77f3aeec435276
[ "dp = [float('inf')] * len(triangle[-1])\ndp[0] = triangle[0][0]\nfor i in range(1, len(triangle)):\n previous = [n for n in dp]\n for j in range(i + 1):\n if j == 0:\n dp[j] = previous[0] + triangle[i][j]\n elif j == i:\n dp[j] = previous[j - 1] + triangle[i][j]\n e...
<|body_start_0|> dp = [float('inf')] * len(triangle[-1]) dp[0] = triangle[0][0] for i in range(1, len(triangle)): previous = [n for n in dp] for j in range(i + 1): if j == 0: dp[j] = previous[0] + triangle[i][j] elif j =...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def minimumTotal(self, triangle): """:type triangle: List[List[int]] :rtype: int""" <|body_0|> def minimumTotal_dp2(self, triangle): """:type triangle: List[List[int]] :rtype: int""" <|body_1|> def minimumTotal_bottomup(self, triangle): ...
stack_v2_sparse_classes_36k_train_010057
2,435
no_license
[ { "docstring": ":type triangle: List[List[int]] :rtype: int", "name": "minimumTotal", "signature": "def minimumTotal(self, triangle)" }, { "docstring": ":type triangle: List[List[int]] :rtype: int", "name": "minimumTotal_dp2", "signature": "def minimumTotal_dp2(self, triangle)" }, { ...
3
stack_v2_sparse_classes_30k_train_020122
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minimumTotal(self, triangle): :type triangle: List[List[int]] :rtype: int - def minimumTotal_dp2(self, triangle): :type triangle: List[List[int]] :rtype: int - def minimumTot...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minimumTotal(self, triangle): :type triangle: List[List[int]] :rtype: int - def minimumTotal_dp2(self, triangle): :type triangle: List[List[int]] :rtype: int - def minimumTot...
e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59
<|skeleton|> class Solution: def minimumTotal(self, triangle): """:type triangle: List[List[int]] :rtype: int""" <|body_0|> def minimumTotal_dp2(self, triangle): """:type triangle: List[List[int]] :rtype: int""" <|body_1|> def minimumTotal_bottomup(self, triangle): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def minimumTotal(self, triangle): """:type triangle: List[List[int]] :rtype: int""" dp = [float('inf')] * len(triangle[-1]) dp[0] = triangle[0][0] for i in range(1, len(triangle)): previous = [n for n in dp] for j in range(i + 1): ...
the_stack_v2_python_sparse
src/lt_120.py
oxhead/CodingYourWay
train
0
b3f6c4d46220f118e742a1cbcdbb7d90d43eb5d7
[ "self.source_table = None\nself.source_field = None\nself.target_table = None\nself.target_field = None", "tokens = re.findall('[\\\\w]+', lines[0])\ndir = re.findall('<|>', lines[0])\nif dir[0] == '>':\n self.source_table = tokens[0]\n self.source_field = tokens[1]\n self.target_table = tokens[3]\n s...
<|body_start_0|> self.source_table = None self.source_field = None self.target_table = None self.target_field = None <|end_body_0|> <|body_start_1|> tokens = re.findall('[\\w]+', lines[0]) dir = re.findall('<|>', lines[0]) if dir[0] == '>': self.sourc...
Parses a foreign key from PlantUML file.
ForeignKey
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ForeignKey: """Parses a foreign key from PlantUML file.""" def __init__(self): """Constructor.""" <|body_0|> def parse(self, lines): """Parse a foreign key relatinoship. :param lines: The remaining lines of the PUML file.""" <|body_1|> <|end_skeleton|> ...
stack_v2_sparse_classes_36k_train_010058
11,534
no_license
[ { "docstring": "Constructor.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Parse a foreign key relatinoship. :param lines: The remaining lines of the PUML file.", "name": "parse", "signature": "def parse(self, lines)" } ]
2
stack_v2_sparse_classes_30k_train_009902
Implement the Python class `ForeignKey` described below. Class description: Parses a foreign key from PlantUML file. Method signatures and docstrings: - def __init__(self): Constructor. - def parse(self, lines): Parse a foreign key relatinoship. :param lines: The remaining lines of the PUML file.
Implement the Python class `ForeignKey` described below. Class description: Parses a foreign key from PlantUML file. Method signatures and docstrings: - def __init__(self): Constructor. - def parse(self, lines): Parse a foreign key relatinoship. :param lines: The remaining lines of the PUML file. <|skeleton|> class ...
33bf532b397f21290d6f85631466d90964aab4ad
<|skeleton|> class ForeignKey: """Parses a foreign key from PlantUML file.""" def __init__(self): """Constructor.""" <|body_0|> def parse(self, lines): """Parse a foreign key relatinoship. :param lines: The remaining lines of the PUML file.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ForeignKey: """Parses a foreign key from PlantUML file.""" def __init__(self): """Constructor.""" self.source_table = None self.source_field = None self.target_table = None self.target_field = None def parse(self, lines): """Parse a foreign key relatin...
the_stack_v2_python_sparse
SQLite 21/tools/dbdia2sql.py
deadbok/eal_programming
train
1
95d6498de0d4ca1828bfc7dfce95665474176ea1
[ "publisher = Publisher.query.filter_by(id=id).first()\nif publisher is None:\n return ({'message': 'Publisher does not exist'}, 404)\nreturn publisher_schema.dump(publisher)", "req = api.payload\npublisher = Publisher.query.filter_by(id=id).first()\nif publisher is None:\n return ({'message': 'Publisher doe...
<|body_start_0|> publisher = Publisher.query.filter_by(id=id).first() if publisher is None: return ({'message': 'Publisher does not exist'}, 404) return publisher_schema.dump(publisher) <|end_body_0|> <|body_start_1|> req = api.payload publisher = Publisher.query.fil...
SinglePublisher
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SinglePublisher: def get(self, id): """Get Publisher by id""" <|body_0|> def put(self, id): """Update a Publisher""" <|body_1|> def delete(self, id): """Delete a Publisher by id""" <|body_2|> <|end_skeleton|> <|body_start_0|> pu...
stack_v2_sparse_classes_36k_train_010059
3,380
no_license
[ { "docstring": "Get Publisher by id", "name": "get", "signature": "def get(self, id)" }, { "docstring": "Update a Publisher", "name": "put", "signature": "def put(self, id)" }, { "docstring": "Delete a Publisher by id", "name": "delete", "signature": "def delete(self, id)...
3
stack_v2_sparse_classes_30k_train_009703
Implement the Python class `SinglePublisher` described below. Class description: Implement the SinglePublisher class. Method signatures and docstrings: - def get(self, id): Get Publisher by id - def put(self, id): Update a Publisher - def delete(self, id): Delete a Publisher by id
Implement the Python class `SinglePublisher` described below. Class description: Implement the SinglePublisher class. Method signatures and docstrings: - def get(self, id): Get Publisher by id - def put(self, id): Update a Publisher - def delete(self, id): Delete a Publisher by id <|skeleton|> class SinglePublisher:...
ae78fff9888b0f68d9403d7f65cba086dabb3802
<|skeleton|> class SinglePublisher: def get(self, id): """Get Publisher by id""" <|body_0|> def put(self, id): """Update a Publisher""" <|body_1|> def delete(self, id): """Delete a Publisher by id""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SinglePublisher: def get(self, id): """Get Publisher by id""" publisher = Publisher.query.filter_by(id=id).first() if publisher is None: return ({'message': 'Publisher does not exist'}, 404) return publisher_schema.dump(publisher) def put(self, id): """...
the_stack_v2_python_sparse
api/v1/publishers.py
mythril-io/flask-api
train
0
de2402386462a87de1821e7a28ac943a01cfe012
[ "if value is not None and value.tzinfo is None:\n default_tzinfo = pytz.timezone(settings.TIME_ZONE)\n value = default_tzinfo.localize(value)\n value = value.astimezone(pytz.utc)\nreturn super(UTCDateTimeField, self).to_representation(value)", "result = super(UTCDateTimeField, self).to_internal_value(val...
<|body_start_0|> if value is not None and value.tzinfo is None: default_tzinfo = pytz.timezone(settings.TIME_ZONE) value = default_tzinfo.localize(value) value = value.astimezone(pytz.utc) return super(UTCDateTimeField, self).to_representation(value) <|end_body_0|> <...
Like DateTimeField, except it is always in UTC in the API
UTCDateTimeField
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UTCDateTimeField: """Like DateTimeField, except it is always in UTC in the API""" def to_representation(self, value): """Convert outgoing datetimes into UTC strings Input currently saves everything in Pacific time, but without timezone info. So this takes the datetimes and converts t...
stack_v2_sparse_classes_36k_train_010060
3,305
permissive
[ { "docstring": "Convert outgoing datetimes into UTC strings Input currently saves everything in Pacific time, but without timezone info. So this takes the datetimes and converts them from Pacific time to UTC. If this situation ever changes, then we'd change settings.TIME_ZONE and this should continue to work.",...
2
stack_v2_sparse_classes_30k_train_020259
Implement the Python class `UTCDateTimeField` described below. Class description: Like DateTimeField, except it is always in UTC in the API Method signatures and docstrings: - def to_representation(self, value): Convert outgoing datetimes into UTC strings Input currently saves everything in Pacific time, but without ...
Implement the Python class `UTCDateTimeField` described below. Class description: Like DateTimeField, except it is always in UTC in the API Method signatures and docstrings: - def to_representation(self, value): Convert outgoing datetimes into UTC strings Input currently saves everything in Pacific time, but without ...
0fcb81e6a5edaf42c00c64faf001fc43b24e11c0
<|skeleton|> class UTCDateTimeField: """Like DateTimeField, except it is always in UTC in the API""" def to_representation(self, value): """Convert outgoing datetimes into UTC strings Input currently saves everything in Pacific time, but without timezone info. So this takes the datetimes and converts t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UTCDateTimeField: """Like DateTimeField, except it is always in UTC in the API""" def to_representation(self, value): """Convert outgoing datetimes into UTC strings Input currently saves everything in Pacific time, but without timezone info. So this takes the datetimes and converts them from Paci...
the_stack_v2_python_sparse
fjord/base/api_utils.py
mozilla/fjord
train
18
860f137d1e13cc74c627e4ed4df8ede91e3abcec
[ "self.interface_name = interface_name\nself.ip_family = ip_family\nself.ips = ips\nself.node_ids = node_ids\nself.role = role\nself.subnet_gateway = subnet_gateway\nself.subnet_mask_bits = subnet_mask_bits", "if dictionary is None:\n return None\ninterface_name = dictionary.get('interfaceName')\nip_family = di...
<|body_start_0|> self.interface_name = interface_name self.ip_family = ip_family self.ips = ips self.node_ids = node_ids self.role = role self.subnet_gateway = subnet_gateway self.subnet_mask_bits = subnet_mask_bits <|end_body_0|> <|body_start_1|> if dict...
Implementation of the 'IpConfig' model. Specifies the configuration of an IP. Attributes: interface_name (string): The interface name. Specifies which interface to assign IP to. ip_family (int): IpFamily of this config. ips (list of string): The interface ips. node_ids (list of long|int): Node ids. role (string): The i...
IpConfig
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IpConfig: """Implementation of the 'IpConfig' model. Specifies the configuration of an IP. Attributes: interface_name (string): The interface name. Specifies which interface to assign IP to. ip_family (int): IpFamily of this config. ips (list of string): The interface ips. node_ids (list of long|...
stack_v2_sparse_classes_36k_train_010061
2,714
permissive
[ { "docstring": "Constructor for the IpConfig class", "name": "__init__", "signature": "def __init__(self, interface_name=None, ip_family=None, ips=None, node_ids=None, role=None, subnet_gateway=None, subnet_mask_bits=None)" }, { "docstring": "Creates an instance of this model from a dictionary A...
2
stack_v2_sparse_classes_30k_train_015664
Implement the Python class `IpConfig` described below. Class description: Implementation of the 'IpConfig' model. Specifies the configuration of an IP. Attributes: interface_name (string): The interface name. Specifies which interface to assign IP to. ip_family (int): IpFamily of this config. ips (list of string): The...
Implement the Python class `IpConfig` described below. Class description: Implementation of the 'IpConfig' model. Specifies the configuration of an IP. Attributes: interface_name (string): The interface name. Specifies which interface to assign IP to. ip_family (int): IpFamily of this config. ips (list of string): The...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class IpConfig: """Implementation of the 'IpConfig' model. Specifies the configuration of an IP. Attributes: interface_name (string): The interface name. Specifies which interface to assign IP to. ip_family (int): IpFamily of this config. ips (list of string): The interface ips. node_ids (list of long|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class IpConfig: """Implementation of the 'IpConfig' model. Specifies the configuration of an IP. Attributes: interface_name (string): The interface name. Specifies which interface to assign IP to. ip_family (int): IpFamily of this config. ips (list of string): The interface ips. node_ids (list of long|int): Node id...
the_stack_v2_python_sparse
cohesity_management_sdk/models/ip_config.py
cohesity/management-sdk-python
train
24
0a2449e76df8df27abfc4329685d69d939e1530c
[ "startTime = datetime.datetime.now()\nif trial:\n endTime = datetime.datetime.now()\n return {'start': startTime, 'end': endTime}\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate(TEAM_NAME, TEAM_NAME)\nurl = FUSION_TABLE_URL\ncsv_string = urllib.request.urlopen(url).read().decode('ut...
<|body_start_0|> startTime = datetime.datetime.now() if trial: endTime = datetime.datetime.now() return {'start': startTime, 'end': endTime} client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate(TEAM_NAME, TEAM_NAME) url = FUSION_...
countyShapes
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class countyShapes: def execute(trial=False): """Read from Google Fusion table (uploaded to datamechanics.io) to get geoJSON data about each county and insert into collection ex) { "_id" : "7322", "Name" : Barnstable, "Shape" : "<Polygon> ... ", "Geo_ID" : "25001", }""" <|body_0|> ...
stack_v2_sparse_classes_36k_train_010062
4,703
no_license
[ { "docstring": "Read from Google Fusion table (uploaded to datamechanics.io) to get geoJSON data about each county and insert into collection ex) { \"_id\" : \"7322\", \"Name\" : Barnstable, \"Shape\" : \"<Polygon> ... \", \"Geo_ID\" : \"25001\", }", "name": "execute", "signature": "def execute(trial=Fa...
2
stack_v2_sparse_classes_30k_test_000882
Implement the Python class `countyShapes` described below. Class description: Implement the countyShapes class. Method signatures and docstrings: - def execute(trial=False): Read from Google Fusion table (uploaded to datamechanics.io) to get geoJSON data about each county and insert into collection ex) { "_id" : "732...
Implement the Python class `countyShapes` described below. Class description: Implement the countyShapes class. Method signatures and docstrings: - def execute(trial=False): Read from Google Fusion table (uploaded to datamechanics.io) to get geoJSON data about each county and insert into collection ex) { "_id" : "732...
90284cf3debbac36eead07b8d2339cdd191b86cf
<|skeleton|> class countyShapes: def execute(trial=False): """Read from Google Fusion table (uploaded to datamechanics.io) to get geoJSON data about each county and insert into collection ex) { "_id" : "7322", "Name" : Barnstable, "Shape" : "<Polygon> ... ", "Geo_ID" : "25001", }""" <|body_0|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class countyShapes: def execute(trial=False): """Read from Google Fusion table (uploaded to datamechanics.io) to get geoJSON data about each county and insert into collection ex) { "_id" : "7322", "Name" : Barnstable, "Shape" : "<Polygon> ... ", "Geo_ID" : "25001", }""" startTime = datetime.datetime...
the_stack_v2_python_sparse
ldisalvo_skeesara_vidyaap/countyShapes.py
maximega/course-2019-spr-proj
train
2
10ee6eb07536dd1c49755073b616ab1520b23731
[ "try:\n time.sleep(0.5)\n elements = dr.find_visible_elements(selectory[0])\n if len(elements) == 1:\n time.sleep(0.5)\n elements[0].click()\n else:\n element = elements[selectory[1]]\n element.click()\nexcept IndexError:\n elements = dr.find_elements(selectory[0])\n if...
<|body_start_0|> try: time.sleep(0.5) elements = dr.find_visible_elements(selectory[0]) if len(elements) == 1: time.sleep(0.5) elements[0].click() else: element = elements[selectory[1]] element.click(...
MyElements
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyElements: def elements_click(self, dr, selectory): """探针卸载获得的class都是第一个 #elements=dr.find_visible_elements(".ivu-btn.ivu-btn-primary.ivu-btn-large")#确定""" <|body_0|> def elements_text_update(self, dr, selectory, msg): """探针卸载获得的class都是第一个 #elements=dr.find_visible_...
stack_v2_sparse_classes_36k_train_010063
3,395
no_license
[ { "docstring": "探针卸载获得的class都是第一个 #elements=dr.find_visible_elements(\".ivu-btn.ivu-btn-primary.ivu-btn-large\")#确定", "name": "elements_click", "signature": "def elements_click(self, dr, selectory)" }, { "docstring": "探针卸载获得的class都是第一个 #elements=dr.find_visible_elements(\".ivu-btn.ivu-btn-primar...
2
stack_v2_sparse_classes_30k_test_001007
Implement the Python class `MyElements` described below. Class description: Implement the MyElements class. Method signatures and docstrings: - def elements_click(self, dr, selectory): 探针卸载获得的class都是第一个 #elements=dr.find_visible_elements(".ivu-btn.ivu-btn-primary.ivu-btn-large")#确定 - def elements_text_update(self, dr...
Implement the Python class `MyElements` described below. Class description: Implement the MyElements class. Method signatures and docstrings: - def elements_click(self, dr, selectory): 探针卸载获得的class都是第一个 #elements=dr.find_visible_elements(".ivu-btn.ivu-btn-primary.ivu-btn-large")#确定 - def elements_text_update(self, dr...
a5cf2ab372d1e1e09cae1904c22dba2eab3c29de
<|skeleton|> class MyElements: def elements_click(self, dr, selectory): """探针卸载获得的class都是第一个 #elements=dr.find_visible_elements(".ivu-btn.ivu-btn-primary.ivu-btn-large")#确定""" <|body_0|> def elements_text_update(self, dr, selectory, msg): """探针卸载获得的class都是第一个 #elements=dr.find_visible_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MyElements: def elements_click(self, dr, selectory): """探针卸载获得的class都是第一个 #elements=dr.find_visible_elements(".ivu-btn.ivu-btn-primary.ivu-btn-large")#确定""" try: time.sleep(0.5) elements = dr.find_visible_elements(selectory[0]) if len(elements) == 1: ...
the_stack_v2_python_sparse
common/elements_base.py
ItTestKing/Base_test
train
0
10b976bbbe35096eb28886df89f563697ed23780
[ "cls.testDir = os.path.join(originalPath, 'rmg', 'test_data', 'restartTest')\ncls.outputDir = os.path.join(cls.testDir, 'output_w_filters')\ncls.databaseDirectory = settings['database.directory']\nos.mkdir(cls.outputDir)\ninitialize_log(logging.INFO, os.path.join(cls.outputDir, 'RMG.log'))\ncls.rmg = RMG(input_file...
<|body_start_0|> cls.testDir = os.path.join(originalPath, 'rmg', 'test_data', 'restartTest') cls.outputDir = os.path.join(cls.testDir, 'output_w_filters') cls.databaseDirectory = settings['database.directory'] os.mkdir(cls.outputDir) initialize_log(logging.INFO, os.path.join(cls....
TestRestartWithFilters
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestRestartWithFilters: def setUpClass(cls): """A function that is run ONCE before all unit tests in this class.""" <|body_0|> def test_restart_with_filters(self): """Test that the RMG restart job with filters included completed without problems""" <|body_1|>...
stack_v2_sparse_classes_36k_train_010064
15,751
permissive
[ { "docstring": "A function that is run ONCE before all unit tests in this class.", "name": "setUpClass", "signature": "def setUpClass(cls)" }, { "docstring": "Test that the RMG restart job with filters included completed without problems", "name": "test_restart_with_filters", "signature"...
3
null
Implement the Python class `TestRestartWithFilters` described below. Class description: Implement the TestRestartWithFilters class. Method signatures and docstrings: - def setUpClass(cls): A function that is run ONCE before all unit tests in this class. - def test_restart_with_filters(self): Test that the RMG restart...
Implement the Python class `TestRestartWithFilters` described below. Class description: Implement the TestRestartWithFilters class. Method signatures and docstrings: - def setUpClass(cls): A function that is run ONCE before all unit tests in this class. - def test_restart_with_filters(self): Test that the RMG restart...
349a4af759cf8877197772cd7eaca1e51d46eff5
<|skeleton|> class TestRestartWithFilters: def setUpClass(cls): """A function that is run ONCE before all unit tests in this class.""" <|body_0|> def test_restart_with_filters(self): """Test that the RMG restart job with filters included completed without problems""" <|body_1|>...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestRestartWithFilters: def setUpClass(cls): """A function that is run ONCE before all unit tests in this class.""" cls.testDir = os.path.join(originalPath, 'rmg', 'test_data', 'restartTest') cls.outputDir = os.path.join(cls.testDir, 'output_w_filters') cls.databaseDirectory = ...
the_stack_v2_python_sparse
rmgpy/rmg/mainTest.py
CanePan-cc/CanePanWorkshop
train
2
f37caeab91c56167944a7f3ea680647680eedb1b
[ "kwargs = {}\nfor key, value in d.items():\n if key in ('version_check', 'convert_case', 'include_reflection_data'):\n kwargs[key] = value\n elif key == 'text_type':\n kwargs[key] = TextType.parse(value)\n else:\n raise ValueError('Unknown option: %s' % key)\nreturn cls(**kwargs)", "...
<|body_start_0|> kwargs = {} for key, value in d.items(): if key in ('version_check', 'convert_case', 'include_reflection_data'): kwargs[key] = value elif key == 'text_type': kwargs[key] = TextType.parse(value) else: rai...
Options
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Options: def from_dict(cls, d): """Create an Options instance from the given dict. Each option is expressed as either a normal bool or a string; strings are parsed (e.g. "bytes" becomes TextType.bytes)""" <|body_0|> def combine(self, other): """Combine the options of...
stack_v2_sparse_classes_36k_train_010065
2,890
permissive
[ { "docstring": "Create an Options instance from the given dict. Each option is expressed as either a normal bool or a string; strings are parsed (e.g. \"bytes\" becomes TextType.bytes)", "name": "from_dict", "signature": "def from_dict(cls, d)" }, { "docstring": "Combine the options of ``self`` ...
2
stack_v2_sparse_classes_30k_train_014314
Implement the Python class `Options` described below. Class description: Implement the Options class. Method signatures and docstrings: - def from_dict(cls, d): Create an Options instance from the given dict. Each option is expressed as either a normal bool or a string; strings are parsed (e.g. "bytes" becomes TextTy...
Implement the Python class `Options` described below. Class description: Implement the Options class. Method signatures and docstrings: - def from_dict(cls, d): Create an Options instance from the given dict. Each option is expressed as either a normal bool or a string; strings are parsed (e.g. "bytes" becomes TextTy...
618af51656836d6a183e6e8e7b5781074c5fbe85
<|skeleton|> class Options: def from_dict(cls, d): """Create an Options instance from the given dict. Each option is expressed as either a normal bool or a string; strings are parsed (e.g. "bytes" becomes TextType.bytes)""" <|body_0|> def combine(self, other): """Combine the options of...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Options: def from_dict(cls, d): """Create an Options instance from the given dict. Each option is expressed as either a normal bool or a string; strings are parsed (e.g. "bytes" becomes TextType.bytes)""" kwargs = {} for key, value in d.items(): if key in ('version_check', ...
the_stack_v2_python_sparse
capnpy/annotate_extended.py
antocuni/capnpy
train
46
9b0c63d67aca437a5e71ffcde213b9bddcb5220e
[ "self.container_name = container_name\nself.divisor = divisor\nself.resource = resource", "if dictionary is None:\n return None\ncontainer_name = dictionary.get('containerName')\ndivisor = dictionary.get('divisor')\nresource = dictionary.get('resource')\nreturn cls(container_name, divisor, resource)" ]
<|body_start_0|> self.container_name = container_name self.divisor = divisor self.resource = resource <|end_body_0|> <|body_start_1|> if dictionary is None: return None container_name = dictionary.get('containerName') divisor = dictionary.get('divisor') ...
Implementation of the 'PodInfo_PodSpec_VolumeInfo_DownwardAPIVolumeFile_ResourceFieldSelector' model. TODO: type description here. Attributes: container_name (string): TODO: Type description here. divisor (string): TODO: Type description here. resource (string): TODO: Type description here.
PodInfo_PodSpec_VolumeInfo_DownwardAPIVolumeFile_ResourceFieldSelector
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PodInfo_PodSpec_VolumeInfo_DownwardAPIVolumeFile_ResourceFieldSelector: """Implementation of the 'PodInfo_PodSpec_VolumeInfo_DownwardAPIVolumeFile_ResourceFieldSelector' model. TODO: type description here. Attributes: container_name (string): TODO: Type description here. divisor (string): TODO: T...
stack_v2_sparse_classes_36k_train_010066
1,944
permissive
[ { "docstring": "Constructor for the PodInfo_PodSpec_VolumeInfo_DownwardAPIVolumeFile_ResourceFieldSelector class", "name": "__init__", "signature": "def __init__(self, container_name=None, divisor=None, resource=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: ...
2
null
Implement the Python class `PodInfo_PodSpec_VolumeInfo_DownwardAPIVolumeFile_ResourceFieldSelector` described below. Class description: Implementation of the 'PodInfo_PodSpec_VolumeInfo_DownwardAPIVolumeFile_ResourceFieldSelector' model. TODO: type description here. Attributes: container_name (string): TODO: Type desc...
Implement the Python class `PodInfo_PodSpec_VolumeInfo_DownwardAPIVolumeFile_ResourceFieldSelector` described below. Class description: Implementation of the 'PodInfo_PodSpec_VolumeInfo_DownwardAPIVolumeFile_ResourceFieldSelector' model. TODO: type description here. Attributes: container_name (string): TODO: Type desc...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class PodInfo_PodSpec_VolumeInfo_DownwardAPIVolumeFile_ResourceFieldSelector: """Implementation of the 'PodInfo_PodSpec_VolumeInfo_DownwardAPIVolumeFile_ResourceFieldSelector' model. TODO: type description here. Attributes: container_name (string): TODO: Type description here. divisor (string): TODO: T...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PodInfo_PodSpec_VolumeInfo_DownwardAPIVolumeFile_ResourceFieldSelector: """Implementation of the 'PodInfo_PodSpec_VolumeInfo_DownwardAPIVolumeFile_ResourceFieldSelector' model. TODO: type description here. Attributes: container_name (string): TODO: Type description here. divisor (string): TODO: Type descripti...
the_stack_v2_python_sparse
cohesity_management_sdk/models/pod_info_pod_spec_volume_info_downward_api_volume_file_resource_field_selector.py
cohesity/management-sdk-python
train
24
ec767776e8e4ac655759cb1797c499dd083b7d76
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ConditionalAccessGrantControls()", "from .authentication_strength_policy import AuthenticationStrengthPolicy\nfrom .conditional_access_grant_control import ConditionalAccessGrantControl\nfrom .authentication_strength_policy import Auth...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return ConditionalAccessGrantControls() <|end_body_0|> <|body_start_1|> from .authentication_strength_policy import AuthenticationStrengthPolicy from .conditional_access_grant_control import Co...
ConditionalAccessGrantControls
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConditionalAccessGrantControls: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessGrantControls: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator v...
stack_v2_sparse_classes_36k_train_010067
4,649
permissive
[ { "docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ConditionalAccessGrantControls", "name": "create_from_discriminator_value", "signature": "def create_from_di...
3
null
Implement the Python class `ConditionalAccessGrantControls` described below. Class description: Implement the ConditionalAccessGrantControls class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessGrantControls: Creates a new instance of...
Implement the Python class `ConditionalAccessGrantControls` described below. Class description: Implement the ConditionalAccessGrantControls class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessGrantControls: Creates a new instance of...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class ConditionalAccessGrantControls: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessGrantControls: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator v...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ConditionalAccessGrantControls: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessGrantControls: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and creat...
the_stack_v2_python_sparse
msgraph/generated/models/conditional_access_grant_controls.py
microsoftgraph/msgraph-sdk-python
train
135
a2d5ba4a37c7f1b6b066eaa2b252e070df19ea64
[ "super().__init__()\nself.w = nn.Parameter(torch.randn(q_dim, s_dim) * 0.001)\nself.out = nn.Linear(s_dim, out_dim)", "attn_score = torch.einsum('bqi,ij,bsj->bqs', q, self.w, s)\nattn_score.masked_fill_(mask == 0, -10000000000.0)\nattn_w = F.softmax(attn_score, dim=-1)\nattn_out = attn_w @ s\nattn_out = self.out(...
<|body_start_0|> super().__init__() self.w = nn.Parameter(torch.randn(q_dim, s_dim) * 0.001) self.out = nn.Linear(s_dim, out_dim) <|end_body_0|> <|body_start_1|> attn_score = torch.einsum('bqi,ij,bsj->bqs', q, self.w, s) attn_score.masked_fill_(mask == 0, -10000000000.0) ...
Luong attention score = q*W*s [q_len, q_dim] * [q_dim, s_dim] * [s_dim, s_len] = [q_len, s_len]
MultiplicativeAttention
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiplicativeAttention: """Luong attention score = q*W*s [q_len, q_dim] * [q_dim, s_dim] * [s_dim, s_len] = [q_len, s_len]""" def __init__(self, q_dim, s_dim, h_dim, out_dim): """params: q_dim: query dim s_dim: source dim h_dim: attn hidden dim out_dim: final out dim""" <|bo...
stack_v2_sparse_classes_36k_train_010068
4,057
no_license
[ { "docstring": "params: q_dim: query dim s_dim: source dim h_dim: attn hidden dim out_dim: final out dim", "name": "__init__", "signature": "def __init__(self, q_dim, s_dim, h_dim, out_dim)" }, { "docstring": "q: [B, q_len, q_dim] s: [B, s_len, s_dim] mask: [B, 1, s_len]", "name": "forward",...
2
stack_v2_sparse_classes_30k_train_014611
Implement the Python class `MultiplicativeAttention` described below. Class description: Luong attention score = q*W*s [q_len, q_dim] * [q_dim, s_dim] * [s_dim, s_len] = [q_len, s_len] Method signatures and docstrings: - def __init__(self, q_dim, s_dim, h_dim, out_dim): params: q_dim: query dim s_dim: source dim h_di...
Implement the Python class `MultiplicativeAttention` described below. Class description: Luong attention score = q*W*s [q_len, q_dim] * [q_dim, s_dim] * [s_dim, s_len] = [q_len, s_len] Method signatures and docstrings: - def __init__(self, q_dim, s_dim, h_dim, out_dim): params: q_dim: query dim s_dim: source dim h_di...
54dcd23112d452b856e4f8000cf697d352cfec05
<|skeleton|> class MultiplicativeAttention: """Luong attention score = q*W*s [q_len, q_dim] * [q_dim, s_dim] * [s_dim, s_len] = [q_len, s_len]""" def __init__(self, q_dim, s_dim, h_dim, out_dim): """params: q_dim: query dim s_dim: source dim h_dim: attn hidden dim out_dim: final out dim""" <|bo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultiplicativeAttention: """Luong attention score = q*W*s [q_len, q_dim] * [q_dim, s_dim] * [s_dim, s_len] = [q_len, s_len]""" def __init__(self, q_dim, s_dim, h_dim, out_dim): """params: q_dim: query dim s_dim: source dim h_dim: attn hidden dim out_dim: final out dim""" super().__init__(...
the_stack_v2_python_sparse
models/rnn/attention.py
khanrc/pt.seq2seq
train
3
339ca0b9b4c4fc9ad8d09864da097e917006b846
[ "with codecs.open(input_file, mode='r', encoding=enc) as in_f, codecs.open(output_file, mode='w', encoding='utf-8') as out_f:\n reader = csv.DictReader(in_f)\n writer = csv.writer(out_f)\n writer.writerow(remains)\n for row in reader:\n contents = []\n for col in remains:\n cont...
<|body_start_0|> with codecs.open(input_file, mode='r', encoding=enc) as in_f, codecs.open(output_file, mode='w', encoding='utf-8') as out_f: reader = csv.DictReader(in_f) writer = csv.writer(out_f) writer.writerow(remains) for row in reader: conte...
File
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class File: def remove_csv_col(self, input_file, output_file, remains, enc='utf-8'): """Extract only the necessary columns from the CSV data and output a new CSV Args: input_file (str): Input csv file name output_file (str): Output csv file name remains (str[]): Columns which remain for new cs...
stack_v2_sparse_classes_36k_train_010069
2,975
permissive
[ { "docstring": "Extract only the necessary columns from the CSV data and output a new CSV Args: input_file (str): Input csv file name output_file (str): Output csv file name remains (str[]): Columns which remain for new csv enc=utf-8 (str): encording", "name": "remove_csv_col", "signature": "def remove_...
3
stack_v2_sparse_classes_30k_train_000866
Implement the Python class `File` described below. Class description: Implement the File class. Method signatures and docstrings: - def remove_csv_col(self, input_file, output_file, remains, enc='utf-8'): Extract only the necessary columns from the CSV data and output a new CSV Args: input_file (str): Input csv file ...
Implement the Python class `File` described below. Class description: Implement the File class. Method signatures and docstrings: - def remove_csv_col(self, input_file, output_file, remains, enc='utf-8'): Extract only the necessary columns from the CSV data and output a new CSV Args: input_file (str): Input csv file ...
e523653a9f96f84810c06824133c3a146a053b75
<|skeleton|> class File: def remove_csv_col(self, input_file, output_file, remains, enc='utf-8'): """Extract only the necessary columns from the CSV data and output a new CSV Args: input_file (str): Input csv file name output_file (str): Output csv file name remains (str[]): Columns which remain for new cs...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class File: def remove_csv_col(self, input_file, output_file, remains, enc='utf-8'): """Extract only the necessary columns from the CSV data and output a new CSV Args: input_file (str): Input csv file name output_file (str): Output csv file name remains (str[]): Columns which remain for new csv enc=utf-8 (s...
the_stack_v2_python_sparse
cliboa/adapter/file.py
BrainPad/cliboa
train
27
0ae6e7e9df1719abab515aefc60ecfbea54ea66e
[ "self.name = name\nself._address = address\nself._initialized = False\nself._led = SevenSegment.SevenSegment(address=self._address)\ntry:\n self._led.begin()\n self.clear()\n self._initialized = True\nexcept IOError:\n msg = 'Could not connect to %s LED at I2C address %s' % (self.name, hex(self._address...
<|body_start_0|> self.name = name self._address = address self._initialized = False self._led = SevenSegment.SevenSegment(address=self._address) try: self._led.begin() self.clear() self._initialized = True except IOError: ms...
Numeric display uses the Adafruit SevenSegment display with i2c backpack
Numeric_Display_Adapter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Numeric_Display_Adapter: """Numeric display uses the Adafruit SevenSegment display with i2c backpack""" def __init__(self, name, address): """Initalize a seven segment display with i2c""" <|body_0|> def clear(self): """Clear the display""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_010070
1,232
no_license
[ { "docstring": "Initalize a seven segment display with i2c", "name": "__init__", "signature": "def __init__(self, name, address)" }, { "docstring": "Clear the display", "name": "clear", "signature": "def clear(self)" }, { "docstring": "Display value", "name": "display", "...
4
stack_v2_sparse_classes_30k_train_006308
Implement the Python class `Numeric_Display_Adapter` described below. Class description: Numeric display uses the Adafruit SevenSegment display with i2c backpack Method signatures and docstrings: - def __init__(self, name, address): Initalize a seven segment display with i2c - def clear(self): Clear the display - def...
Implement the Python class `Numeric_Display_Adapter` described below. Class description: Numeric display uses the Adafruit SevenSegment display with i2c backpack Method signatures and docstrings: - def __init__(self, name, address): Initalize a seven segment display with i2c - def clear(self): Clear the display - def...
35ef4d55155d7d60ab15113ff068276c29ace510
<|skeleton|> class Numeric_Display_Adapter: """Numeric display uses the Adafruit SevenSegment display with i2c backpack""" def __init__(self, name, address): """Initalize a seven segment display with i2c""" <|body_0|> def clear(self): """Clear the display""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Numeric_Display_Adapter: """Numeric display uses the Adafruit SevenSegment display with i2c backpack""" def __init__(self, name, address): """Initalize a seven segment display with i2c""" self.name = name self._address = address self._initialized = False self._led ...
the_stack_v2_python_sparse
liberty_bell/components/numeric_display_adapter.py
mattgrogan/liberty_bell
train
0
00aebdf3dfd86c7ea7580ca6118a1db55fb135ab
[ "self.y = np.empty(0)\nself.ts_period = ts_period\nself.timestamp_interval = -1\nself.last_timestamp = -1\nself._fitted = False\nself.copy = copy\nif self.ts_period is None:\n raise ValueError(\"'ts_period' must be given.\")", "if X.size != y.size:\n raise ValueError(\"'X' and 'y' size must match.\")\nif se...
<|body_start_0|> self.y = np.empty(0) self.ts_period = ts_period self.timestamp_interval = -1 self.last_timestamp = -1 self._fitted = False self.copy = copy if self.ts_period is None: raise ValueError("'ts_period' must be given.") <|end_body_0|> <|bod...
Seasonal Naive model for time-series forecasting. This model is similar to the Naive model, but instead of using only the very last observation from the fitted time-series, it is used the whole past period. Then, each prediction is equal to the value in the corresponding timestamp of the previous period.
TSNaiveSeasonal
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TSNaiveSeasonal: """Seasonal Naive model for time-series forecasting. This model is similar to the Naive model, but instead of using only the very last observation from the fitted time-series, it is used the whole past period. Then, each prediction is equal to the value in the corresponding times...
stack_v2_sparse_classes_36k_train_010071
12,299
permissive
[ { "docstring": "Init a Seasonal Naive Model.", "name": "__init__", "signature": "def __init__(self, ts_period: int, copy: bool=False)" }, { "docstring": "Fit a Seasonal Naive model.", "name": "fit", "signature": "def fit(self, X: np.ndarray, y: np.ndarray, **kwargs) -> 'TSNaiveSeasonal'"...
3
stack_v2_sparse_classes_30k_train_008277
Implement the Python class `TSNaiveSeasonal` described below. Class description: Seasonal Naive model for time-series forecasting. This model is similar to the Naive model, but instead of using only the very last observation from the fitted time-series, it is used the whole past period. Then, each prediction is equal ...
Implement the Python class `TSNaiveSeasonal` described below. Class description: Seasonal Naive model for time-series forecasting. This model is similar to the Naive model, but instead of using only the very last observation from the fitted time-series, it is used the whole past period. Then, each prediction is equal ...
61cc1f63fa055c7466151cfefa7baff8df1702b7
<|skeleton|> class TSNaiveSeasonal: """Seasonal Naive model for time-series forecasting. This model is similar to the Naive model, but instead of using only the very last observation from the fitted time-series, it is used the whole past period. Then, each prediction is equal to the value in the corresponding times...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TSNaiveSeasonal: """Seasonal Naive model for time-series forecasting. This model is similar to the Naive model, but instead of using only the very last observation from the fitted time-series, it is used the whole past period. Then, each prediction is equal to the value in the corresponding timestamp of the p...
the_stack_v2_python_sparse
tspymfe/_models.py
FelSiq/ts-pymfe
train
9
42c6755132e715958b21025cf490d7e4fad79cfa
[ "self.__run1_file = run1_file\nself.__run2_file = run2_file\nself.__qrels = qrels\nself.__metric = metric", "te_method1 = TrecEval()\nte_method1.evaluate(self.__qrels, self.__run1_file)\nte_method2 = TrecEval()\nte_method2.evaluate(self.__qrels, self.__run2_file)\ndata = []\nfor query_id in te_method1.get_query_i...
<|body_start_0|> self.__run1_file = run1_file self.__run2_file = run2_file self.__qrels = qrels self.__metric = metric <|end_body_0|> <|body_start_1|> te_method1 = TrecEval() te_method1.evaluate(self.__qrels, self.__run1_file) te_method2 = TrecEval() te_m...
QueryDiff
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QueryDiff: def __init__(self, run1_file, run2_file, qrels, metric): """:param run1_file: name of run1 file (baseline) :param run2_file: name of run2 file (new method) :param qrels: name of qrels file :param metric: metric :return:""" <|body_0|> def dump_differences(self, out...
stack_v2_sparse_classes_36k_train_010072
1,678
permissive
[ { "docstring": ":param run1_file: name of run1 file (baseline) :param run2_file: name of run2 file (new method) :param qrels: name of qrels file :param metric: metric :return:", "name": "__init__", "signature": "def __init__(self, run1_file, run2_file, qrels, metric)" }, { "docstring": "Outputs ...
2
stack_v2_sparse_classes_30k_train_001646
Implement the Python class `QueryDiff` described below. Class description: Implement the QueryDiff class. Method signatures and docstrings: - def __init__(self, run1_file, run2_file, qrels, metric): :param run1_file: name of run1 file (baseline) :param run2_file: name of run2 file (new method) :param qrels: name of q...
Implement the Python class `QueryDiff` described below. Class description: Implement the QueryDiff class. Method signatures and docstrings: - def __init__(self, run1_file, run2_file, qrels, metric): :param run1_file: name of run1 file (baseline) :param run2_file: name of run2 file (new method) :param qrels: name of q...
7027699009504c72be4a087cf9730cad3051979b
<|skeleton|> class QueryDiff: def __init__(self, run1_file, run2_file, qrels, metric): """:param run1_file: name of run1 file (baseline) :param run2_file: name of run2 file (new method) :param qrels: name of qrels file :param metric: metric :return:""" <|body_0|> def dump_differences(self, out...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class QueryDiff: def __init__(self, run1_file, run2_file, qrels, metric): """:param run1_file: name of run1 file (baseline) :param run2_file: name of run2 file (new method) :param qrels: name of qrels file :param metric: metric :return:""" self.__run1_file = run1_file self.__run2_file = run2...
the_stack_v2_python_sparse
nordlys/core/eval/query_diff.py
iai-group/nordlys
train
35
757f9f1c376d7191407d1bf2685bb5eb85e33432
[ "max_area = 0\nn = len(coord)\nfor x1 in range(n - 1):\n for x2 in range(x1 + 1, n):\n y1, y2 = (coord[x1], coord[x2])\n curr_area = (x2 - x1) * min(y1, y2)\n max_area = max(max_area, curr_area)\nreturn max_area", "n = len(coord)\ni, j = (0, n - 1)\nmax_area = 0\nwhile i < j:\n curr_are...
<|body_start_0|> max_area = 0 n = len(coord) for x1 in range(n - 1): for x2 in range(x1 + 1, n): y1, y2 = (coord[x1], coord[x2]) curr_area = (x2 - x1) * min(y1, y2) max_area = max(max_area, curr_area) return max_area <|end_body_...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def max_area_brute(self, coord): """Brute force algorithm. Time complexity: O(n ^ 2). Space complexity: O(1), n is len(coord).""" <|body_0|> def max_area_2p(self, coord): """Two pointers algorithm. Time complexity: O(n). Space complexity: O(1), n is len(coo...
stack_v2_sparse_classes_36k_train_010073
2,759
no_license
[ { "docstring": "Brute force algorithm. Time complexity: O(n ^ 2). Space complexity: O(1), n is len(coord).", "name": "max_area_brute", "signature": "def max_area_brute(self, coord)" }, { "docstring": "Two pointers algorithm. Time complexity: O(n). Space complexity: O(1), n is len(coord).", "...
3
stack_v2_sparse_classes_30k_train_014052
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def max_area_brute(self, coord): Brute force algorithm. Time complexity: O(n ^ 2). Space complexity: O(1), n is len(coord). - def max_area_2p(self, coord): Two pointers algorithm...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def max_area_brute(self, coord): Brute force algorithm. Time complexity: O(n ^ 2). Space complexity: O(1), n is len(coord). - def max_area_2p(self, coord): Two pointers algorithm...
71b722ddfe8da04572e527b055cf8723d5c87bbf
<|skeleton|> class Solution: def max_area_brute(self, coord): """Brute force algorithm. Time complexity: O(n ^ 2). Space complexity: O(1), n is len(coord).""" <|body_0|> def max_area_2p(self, coord): """Two pointers algorithm. Time complexity: O(n). Space complexity: O(1), n is len(coo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def max_area_brute(self, coord): """Brute force algorithm. Time complexity: O(n ^ 2). Space complexity: O(1), n is len(coord).""" max_area = 0 n = len(coord) for x1 in range(n - 1): for x2 in range(x1 + 1, n): y1, y2 = (coord[x1], coord[x2]...
the_stack_v2_python_sparse
Arrays/container_with_most_water.py
vladn90/Algorithms
train
0
b5860aa2d88c14a262d25d49adbfd3f20ac760d6
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.accessReviewInstanceDecisionItemAccessPacka...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') try: mapping_value = parse_node.get_child_node('@odata.type').get_str_value() except AttributeError: mapping_value = None if mapping_value and mapping_value.casefold() ==...
AccessReviewInstanceDecisionItemResource
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AccessReviewInstanceDecisionItemResource: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessReviewInstanceDecisionItemResource: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read...
stack_v2_sparse_classes_36k_train_010074
5,643
permissive
[ { "docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: AccessReviewInstanceDecisionItemResource", "name": "create_from_discriminator_value", "signature": "def crea...
3
stack_v2_sparse_classes_30k_train_012826
Implement the Python class `AccessReviewInstanceDecisionItemResource` described below. Class description: Implement the AccessReviewInstanceDecisionItemResource class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessReviewInstanceDecisionItemResou...
Implement the Python class `AccessReviewInstanceDecisionItemResource` described below. Class description: Implement the AccessReviewInstanceDecisionItemResource class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessReviewInstanceDecisionItemResou...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class AccessReviewInstanceDecisionItemResource: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessReviewInstanceDecisionItemResource: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AccessReviewInstanceDecisionItemResource: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AccessReviewInstanceDecisionItemResource: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discrimin...
the_stack_v2_python_sparse
msgraph/generated/models/access_review_instance_decision_item_resource.py
microsoftgraph/msgraph-sdk-python
train
135
c09cbd7e0df64503ede470a8f3622926489627b6
[ "super(StoreProductImages, self).__init__(*args, **kwargs)\nself.endpoint = 'ecommerce/stores'\nself.store_id = None\nself.product_id = None\nself.image_id = None", "self.store_id = store_id\nself.product_id = product_id\nif 'id' not in data:\n raise KeyError('The product image must have an id')\nif 'title' no...
<|body_start_0|> super(StoreProductImages, self).__init__(*args, **kwargs) self.endpoint = 'ecommerce/stores' self.store_id = None self.product_id = None self.image_id = None <|end_body_0|> <|body_start_1|> self.store_id = store_id self.product_id = product_id ...
A Product Image represents a specific product image.
StoreProductImages
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StoreProductImages: """A Product Image represents a specific product image.""" def __init__(self, *args, **kwargs): """Initialize the endpoint""" <|body_0|> def create(self, store_id, product_id, data): """Add a new image to the product. :param store_id: The stor...
stack_v2_sparse_classes_36k_train_010075
4,947
permissive
[ { "docstring": "Initialize the endpoint", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "Add a new image to the product. :param store_id: The store id. :type store_id: :py:class:`str` :param product_id: The id for the product of a store. :type product_i...
6
stack_v2_sparse_classes_30k_train_003927
Implement the Python class `StoreProductImages` described below. Class description: A Product Image represents a specific product image. Method signatures and docstrings: - def __init__(self, *args, **kwargs): Initialize the endpoint - def create(self, store_id, product_id, data): Add a new image to the product. :par...
Implement the Python class `StoreProductImages` described below. Class description: A Product Image represents a specific product image. Method signatures and docstrings: - def __init__(self, *args, **kwargs): Initialize the endpoint - def create(self, store_id, product_id, data): Add a new image to the product. :par...
bf61cd602dc44cbff32fbf6f6dcdd33cf6f782e8
<|skeleton|> class StoreProductImages: """A Product Image represents a specific product image.""" def __init__(self, *args, **kwargs): """Initialize the endpoint""" <|body_0|> def create(self, store_id, product_id, data): """Add a new image to the product. :param store_id: The stor...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StoreProductImages: """A Product Image represents a specific product image.""" def __init__(self, *args, **kwargs): """Initialize the endpoint""" super(StoreProductImages, self).__init__(*args, **kwargs) self.endpoint = 'ecommerce/stores' self.store_id = None self....
the_stack_v2_python_sparse
mailchimp3/entities/storeproductimages.py
VingtCinq/python-mailchimp
train
190
06bcbb512cd57c15b52f386ddd3e751622d36f62
[ "self.row_i = row_i\nself.start_i = start_i\nself.end_i = end_i\nself.n = n\nself.gap = None", "g = self.gap\nif g is not None:\n return abs(g[1] - g[0]) < abs(f - s)\nelse:\n return True", "g = self.gap\nif g is None:\n self.gap = (s, f)\nelif abs(f - s) > abs(g[1] - g[0]):\n self.gap = (s, f)" ]
<|body_start_0|> self.row_i = row_i self.start_i = start_i self.end_i = end_i self.n = n self.gap = None <|end_body_0|> <|body_start_1|> g = self.gap if g is not None: return abs(g[1] - g[0]) < abs(f - s) else: return True <|end_bo...
Private Object that will keep track of current row data.
__GapData
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class __GapData: """Private Object that will keep track of current row data.""" def __init__(self, row_i, start_i, end_i, n): """Parameters ---------- row_i Current row of GapData start_i Starting row end_i End row n""" <|body_0|> def compareGap(self, s, f): """Compare...
stack_v2_sparse_classes_36k_train_010076
4,098
permissive
[ { "docstring": "Parameters ---------- row_i Current row of GapData start_i Starting row end_i End row n", "name": "__init__", "signature": "def __init__(self, row_i, start_i, end_i, n)" }, { "docstring": "Compare start, s, and finish, f, values with that of the current gaps values. If smaller, r...
3
stack_v2_sparse_classes_30k_train_018225
Implement the Python class `__GapData` described below. Class description: Private Object that will keep track of current row data. Method signatures and docstrings: - def __init__(self, row_i, start_i, end_i, n): Parameters ---------- row_i Current row of GapData start_i Starting row end_i End row n - def compareGap...
Implement the Python class `__GapData` described below. Class description: Private Object that will keep track of current row data. Method signatures and docstrings: - def __init__(self, row_i, start_i, end_i, n): Parameters ---------- row_i Current row of GapData start_i Starting row end_i End row n - def compareGap...
08fe54fe37df89ffc7e6378125bb14ad5bead421
<|skeleton|> class __GapData: """Private Object that will keep track of current row data.""" def __init__(self, row_i, start_i, end_i, n): """Parameters ---------- row_i Current row of GapData start_i Starting row end_i End row n""" <|body_0|> def compareGap(self, s, f): """Compare...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class __GapData: """Private Object that will keep track of current row data.""" def __init__(self, row_i, start_i, end_i, n): """Parameters ---------- row_i Current row of GapData start_i Starting row end_i End row n""" self.row_i = row_i self.start_i = start_i self.end_i = end_...
the_stack_v2_python_sparse
Algorithms/gap_detection.py
marioliu/AutonomousQuadblade
train
0
347fc19ffb749ca1d5eab4c51dab41b8cd3c41ce
[ "self.last_i = 0\nself.last_j = 0\nself.last_sum = 0\nself.nums2 = nums\nself.firstcall = 1", "if not firstcall:\n if self.last_i <= i <= self.last_j and self.last_i <= j <= self.last_j:\n res = self.last_sum - sum(self.nums2[self.last_i:i]) - sum(self.nums2[j + 1:self.last_j + 1])\n elif self.last_i...
<|body_start_0|> self.last_i = 0 self.last_j = 0 self.last_sum = 0 self.nums2 = nums self.firstcall = 1 <|end_body_0|> <|body_start_1|> if not firstcall: if self.last_i <= i <= self.last_j and self.last_i <= j <= self.last_j: res = self.last_s...
NumArray
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NumArray: def __init__(self, nums): """initialize your data structure here. :type nums: List[int]""" <|body_0|> def sumRange(self, i, j): """sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_s...
stack_v2_sparse_classes_36k_train_010077
1,794
no_license
[ { "docstring": "initialize your data structure here. :type nums: List[int]", "name": "__init__", "signature": "def __init__(self, nums)" }, { "docstring": "sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int", "name": "sumRange", "signature": "def sumRange(self, ...
2
stack_v2_sparse_classes_30k_train_016105
Implement the Python class `NumArray` described below. Class description: Implement the NumArray class. Method signatures and docstrings: - def __init__(self, nums): initialize your data structure here. :type nums: List[int] - def sumRange(self, i, j): sum of elements nums[i..j], inclusive. :type i: int :type j: int ...
Implement the Python class `NumArray` described below. Class description: Implement the NumArray class. Method signatures and docstrings: - def __init__(self, nums): initialize your data structure here. :type nums: List[int] - def sumRange(self, i, j): sum of elements nums[i..j], inclusive. :type i: int :type j: int ...
7a1c3aba65f338f6e11afd2864dabd2b26142b6c
<|skeleton|> class NumArray: def __init__(self, nums): """initialize your data structure here. :type nums: List[int]""" <|body_0|> def sumRange(self, i, j): """sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NumArray: def __init__(self, nums): """initialize your data structure here. :type nums: List[int]""" self.last_i = 0 self.last_j = 0 self.last_sum = 0 self.nums2 = nums self.firstcall = 1 def sumRange(self, i, j): """sum of elements nums[i..j], incl...
the_stack_v2_python_sparse
exercise/leetcode/python_src/by2017_Sep/Leet303.py
SS4G/AlgorithmTraining
train
2
4da788f91748938da32e1d054e1d85fdf50cbf57
[ "if len(predictions_and_ratings) == 0:\n return 0\ndiffs = map(lambda x: (x[0] - x[1]) * (x[0] - x[1]), predictions_and_ratings)\nreturn math.sqrt(sum(diffs) / float(len(predictions_and_ratings)))", "if len(predictions_and_ratings) == 0:\n return 0\ndiffs = map(lambda x: abs(x[0] - x[1]), predictions_and_ra...
<|body_start_0|> if len(predictions_and_ratings) == 0: return 0 diffs = map(lambda x: (x[0] - x[1]) * (x[0] - x[1]), predictions_and_ratings) return math.sqrt(sum(diffs) / float(len(predictions_and_ratings))) <|end_body_0|> <|body_start_1|> if len(predictions_and_ratings) ==...
AccMetrics
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AccMetrics: def calculate_rmse(predictions_and_ratings): """predictions_and_ratings is list of pairs of predicts and real rating""" <|body_0|> def calculate_mae(predictions_and_ratings): """predictions_and_ratings is list of pairs of predicts and real rating""" ...
stack_v2_sparse_classes_36k_train_010078
963
no_license
[ { "docstring": "predictions_and_ratings is list of pairs of predicts and real rating", "name": "calculate_rmse", "signature": "def calculate_rmse(predictions_and_ratings)" }, { "docstring": "predictions_and_ratings is list of pairs of predicts and real rating", "name": "calculate_mae", "...
2
stack_v2_sparse_classes_30k_train_008648
Implement the Python class `AccMetrics` described below. Class description: Implement the AccMetrics class. Method signatures and docstrings: - def calculate_rmse(predictions_and_ratings): predictions_and_ratings is list of pairs of predicts and real rating - def calculate_mae(predictions_and_ratings): predictions_an...
Implement the Python class `AccMetrics` described below. Class description: Implement the AccMetrics class. Method signatures and docstrings: - def calculate_rmse(predictions_and_ratings): predictions_and_ratings is list of pairs of predicts and real rating - def calculate_mae(predictions_and_ratings): predictions_an...
d27654192efc7063e5d691efae9626775cb91940
<|skeleton|> class AccMetrics: def calculate_rmse(predictions_and_ratings): """predictions_and_ratings is list of pairs of predicts and real rating""" <|body_0|> def calculate_mae(predictions_and_ratings): """predictions_and_ratings is list of pairs of predicts and real rating""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AccMetrics: def calculate_rmse(predictions_and_ratings): """predictions_and_ratings is list of pairs of predicts and real rating""" if len(predictions_and_ratings) == 0: return 0 diffs = map(lambda x: (x[0] - x[1]) * (x[0] - x[1]), predictions_and_ratings) return ma...
the_stack_v2_python_sparse
deployment/scripts/metrics/AccMetrics.py
gmiejski/movies-recommender-api
train
1
08e328e884ead0778f24f6f56efb5ac20dcbab56
[ "super(PlotCellTypeStack, self).__init__(experiment, name='PlotCellTypeStack', label=label)\nself.epoch_start = self.experiment.config.getint(self.config_section, 'epoch_start', 0)\nself.epoch_end = self.experiment.config.getint(self.config_section, 'epoch_end', default=self.experiment.config.getint('Experiment', '...
<|body_start_0|> super(PlotCellTypeStack, self).__init__(experiment, name='PlotCellTypeStack', label=label) self.epoch_start = self.experiment.config.getint(self.config_section, 'epoch_start', 0) self.epoch_end = self.experiment.config.getint(self.config_section, 'epoch_end', default=self.experi...
TODO: description Configuration is done in the [PlotCellTypeStack] section Configuration Options: epoch_start The epoch at which to start executing (default: 0) epoch_end The epoch at which to stop executing (default: end of experiment) frequency The frequency (epochs) at which to execute (default: 1) priority The prio...
PlotCellTypeStack
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PlotCellTypeStack: """TODO: description Configuration is done in the [PlotCellTypeStack] section Configuration Options: epoch_start The epoch at which to start executing (default: 0) epoch_end The epoch at which to stop executing (default: end of experiment) frequency The frequency (epochs) at wh...
stack_v2_sparse_classes_36k_train_010079
3,421
permissive
[ { "docstring": "Initialize the PlotCellTypeStack Action", "name": "__init__", "signature": "def __init__(self, experiment, label=None)" }, { "docstring": "Execute the action", "name": "update", "signature": "def update(self)" }, { "docstring": "Since we're at the end of the run, ...
3
stack_v2_sparse_classes_30k_train_011453
Implement the Python class `PlotCellTypeStack` described below. Class description: TODO: description Configuration is done in the [PlotCellTypeStack] section Configuration Options: epoch_start The epoch at which to start executing (default: 0) epoch_end The epoch at which to stop executing (default: end of experiment)...
Implement the Python class `PlotCellTypeStack` described below. Class description: TODO: description Configuration is done in the [PlotCellTypeStack] section Configuration Options: epoch_start The epoch at which to start executing (default: 0) epoch_end The epoch at which to stop executing (default: end of experiment)...
a114ac66e62a960e18127faf52cff9e48831e212
<|skeleton|> class PlotCellTypeStack: """TODO: description Configuration is done in the [PlotCellTypeStack] section Configuration Options: epoch_start The epoch at which to start executing (default: 0) epoch_end The epoch at which to stop executing (default: end of experiment) frequency The frequency (epochs) at wh...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PlotCellTypeStack: """TODO: description Configuration is done in the [PlotCellTypeStack] section Configuration Options: epoch_start The epoch at which to start executing (default: 0) epoch_end The epoch at which to stop executing (default: end of experiment) frequency The frequency (epochs) at which to execut...
the_stack_v2_python_sparse
contrib/actions/PlotCellTypeStack.py
namlehai/seeds
train
0
9cd339b5d17c52f4fa43920848b7d13b3c406331
[ "comment = PublicComment(**data)\nanon = comment.is_anonymous\nuser = comment.user.user if comment.user else None\nneeds_moderation = user and (not user.has_perm('comments.can_post_directly'))\nfrom_swat = is_from_swat(user=comment.user, ip=comment.ip_address)\nif needs_moderation or (anon and (not from_swat)):\n ...
<|body_start_0|> comment = PublicComment(**data) anon = comment.is_anonymous user = comment.user.user if comment.user else None needs_moderation = user and (not user.has_perm('comments.can_post_directly')) from_swat = is_from_swat(user=comment.user, ip=comment.ip_address) ...
CommentsManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CommentsManager: def new(self, check_spam=True, pre_approved=False, **data): """Makes a new comment, dealing with spam checking and pre-approval as necessary. If spam, raise a CommentIsSpam error, with the unsaved comment in its .comment attribute. This comment is all ready to go; it jus...
stack_v2_sparse_classes_36k_train_010080
13,162
no_license
[ { "docstring": "Makes a new comment, dealing with spam checking and pre-approval as necessary. If spam, raise a CommentIsSpam error, with the unsaved comment in its .comment attribute. This comment is all ready to go; it just needs to be saved, should it be decided that it's not actually spam. Comments from Swa...
2
stack_v2_sparse_classes_30k_train_005094
Implement the Python class `CommentsManager` described below. Class description: Implement the CommentsManager class. Method signatures and docstrings: - def new(self, check_spam=True, pre_approved=False, **data): Makes a new comment, dealing with spam checking and pre-approval as necessary. If spam, raise a CommentI...
Implement the Python class `CommentsManager` described below. Class description: Implement the CommentsManager class. Method signatures and docstrings: - def new(self, check_spam=True, pre_approved=False, **data): Makes a new comment, dealing with spam checking and pre-approval as necessary. If spam, raise a CommentI...
ac19bce192fe2ac29bca7bafcf973109c0d1b43e
<|skeleton|> class CommentsManager: def new(self, check_spam=True, pre_approved=False, **data): """Makes a new comment, dealing with spam checking and pre-approval as necessary. If spam, raise a CommentIsSpam error, with the unsaved comment in its .comment attribute. This comment is all ready to go; it jus...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CommentsManager: def new(self, check_spam=True, pre_approved=False, **data): """Makes a new comment, dealing with spam checking and pre-approval as necessary. If spam, raise a CommentIsSpam error, with the unsaved comment in its .comment attribute. This comment is all ready to go; it just needs to be ...
the_stack_v2_python_sparse
gazjango/comments/models.py
iambikash007/gazjango
train
0
3aa288bcb6ff8ca58a13eb63fec9961fb2fe910e
[ "assert len(prog) == 0\nwith prog.context as q:\n ops.Dgate(0.5) | q[0]\nassert len(prog) == 1\nwith prog.context as q:\n ops.BSgate(0.5, 0.3) | (q[1], q[0])\nassert len(prog) == 2", "identity = program.Command(None, prog.register[0])\nprog.circuit.append(identity)\nassert len(prog) == 1\nprog = prog.compil...
<|body_start_0|> assert len(prog) == 0 with prog.context as q: ops.Dgate(0.5) | q[0] assert len(prog) == 1 with prog.context as q: ops.BSgate(0.5, 0.3) | (q[1], q[0]) assert len(prog) == 2 <|end_body_0|> <|body_start_1|> identity = program.Command...
Tests the Program class.
TestProgram
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestProgram: """Tests the Program class.""" def test_with_block(self, prog): """Gate application using a with block.""" <|body_0|> def test_identity_command(self, prog): """Tests that the None command acts as the identity""" <|body_1|> def test_paren...
stack_v2_sparse_classes_36k_train_010081
19,472
permissive
[ { "docstring": "Gate application using a with block.", "name": "test_with_block", "signature": "def test_with_block(self, prog)" }, { "docstring": "Tests that the None command acts as the identity", "name": "test_identity_command", "signature": "def test_identity_command(self, prog)" }...
4
null
Implement the Python class `TestProgram` described below. Class description: Tests the Program class. Method signatures and docstrings: - def test_with_block(self, prog): Gate application using a with block. - def test_identity_command(self, prog): Tests that the None command acts as the identity - def test_parent_pr...
Implement the Python class `TestProgram` described below. Class description: Tests the Program class. Method signatures and docstrings: - def test_with_block(self, prog): Gate application using a with block. - def test_identity_command(self, prog): Tests that the None command acts as the identity - def test_parent_pr...
0c1c805fd5dfce465a8955ee3faf81037023a23e
<|skeleton|> class TestProgram: """Tests the Program class.""" def test_with_block(self, prog): """Gate application using a with block.""" <|body_0|> def test_identity_command(self, prog): """Tests that the None command acts as the identity""" <|body_1|> def test_paren...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestProgram: """Tests the Program class.""" def test_with_block(self, prog): """Gate application using a with block.""" assert len(prog) == 0 with prog.context as q: ops.Dgate(0.5) | q[0] assert len(prog) == 1 with prog.context as q: ops.BSg...
the_stack_v2_python_sparse
artifacts/old_dataset_versions/original_commits_backup/strawberryfields/strawberryfields#90/after/test_program.py
MattePalte/Bugs-Quantum-Computing-Platforms
train
4
5609f308e6e34a9744fc49cf60a57c3314eeb2e9
[ "supernet = '172.31.0.0/16'\ncidr_bits = 17\nnetwork_factory = DockerClusterNetworkFactory(supernet, cidr_bits)\nprint('*** test_create_network_then_try_creating_it_again ***')\nprint('This test will use the main network %s' % supernet)\nfirst_name = 'shouldbenew'\nsg = network_factory.cluster_network_candidates(fi...
<|body_start_0|> supernet = '172.31.0.0/16' cidr_bits = 17 network_factory = DockerClusterNetworkFactory(supernet, cidr_bits) print('*** test_create_network_then_try_creating_it_again ***') print('This test will use the main network %s' % supernet) first_name = 'shouldben...
Some tests that affect the system. This should not destroy existing networks, but better to make sure that the system is 'clean' before executing these tests!
TestDockerClusterNetworkFactory
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestDockerClusterNetworkFactory: """Some tests that affect the system. This should not destroy existing networks, but better to make sure that the system is 'clean' before executing these tests!""" def test_create_network_then_try_creating_it_again(self): """Tries to create a named n...
stack_v2_sparse_classes_36k_train_010082
15,846
no_license
[ { "docstring": "Tries to create a named network, then tries again (expect error message), then remove the network. If the test succeeds, the system returns to the original state.", "name": "test_create_network_then_try_creating_it_again", "signature": "def test_create_network_then_try_creating_it_again(...
2
stack_v2_sparse_classes_30k_train_013628
Implement the Python class `TestDockerClusterNetworkFactory` described below. Class description: Some tests that affect the system. This should not destroy existing networks, but better to make sure that the system is 'clean' before executing these tests! Method signatures and docstrings: - def test_create_network_th...
Implement the Python class `TestDockerClusterNetworkFactory` described below. Class description: Some tests that affect the system. This should not destroy existing networks, but better to make sure that the system is 'clean' before executing these tests! Method signatures and docstrings: - def test_create_network_th...
a9058d49d166205326cfb5f63d58dd42ef70343d
<|skeleton|> class TestDockerClusterNetworkFactory: """Some tests that affect the system. This should not destroy existing networks, but better to make sure that the system is 'clean' before executing these tests!""" def test_create_network_then_try_creating_it_again(self): """Tries to create a named n...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestDockerClusterNetworkFactory: """Some tests that affect the system. This should not destroy existing networks, but better to make sure that the system is 'clean' before executing these tests!""" def test_create_network_then_try_creating_it_again(self): """Tries to create a named network, then ...
the_stack_v2_python_sparse
dcluster/infra/networking.py
luciorq/dcluster
train
0
14fb1f79292a79bb569ac8b964e3c211c10be157
[ "essential_keys = ['nvars', 'c', 'freq']\nfor key in essential_keys:\n if key not in problem_params:\n msg = 'need %s to instantiate problem, only got %s' % (key, str(problem_params.keys()))\n raise ParameterError(msg)\nif (problem_params['nvars'] + 1) % 2 != 0:\n raise ProblemError('setup requi...
<|body_start_0|> essential_keys = ['nvars', 'c', 'freq'] for key in essential_keys: if key not in problem_params: msg = 'need %s to instantiate problem, only got %s' % (key, str(problem_params.keys())) raise ParameterError(msg) if (problem_params['nvar...
Example implementing the unforced 1D advection equation with periodic BC in [0,1], discretized using upwinding finite differences Attributes: A: FD discretization of the gradient operator using upwinding dx: distance between two spatial nodes
advection1d_dirichlet
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class advection1d_dirichlet: """Example implementing the unforced 1D advection equation with periodic BC in [0,1], discretized using upwinding finite differences Attributes: A: FD discretization of the gradient operator using upwinding dx: distance between two spatial nodes""" def __init__(self, p...
stack_v2_sparse_classes_36k_train_010083
5,002
permissive
[ { "docstring": "Initialization routine Args: problem_params (dict): custom parameters for the example dtype_u: mesh data type (will be passed parent class) dtype_f: mesh data type (will be passed parent class)", "name": "__init__", "signature": "def __init__(self, problem_params, dtype_u=mesh, dtype_f=m...
5
stack_v2_sparse_classes_30k_train_015070
Implement the Python class `advection1d_dirichlet` described below. Class description: Example implementing the unforced 1D advection equation with periodic BC in [0,1], discretized using upwinding finite differences Attributes: A: FD discretization of the gradient operator using upwinding dx: distance between two spa...
Implement the Python class `advection1d_dirichlet` described below. Class description: Example implementing the unforced 1D advection equation with periodic BC in [0,1], discretized using upwinding finite differences Attributes: A: FD discretization of the gradient operator using upwinding dx: distance between two spa...
de2cd523411276083355389d7e7993106cedf93d
<|skeleton|> class advection1d_dirichlet: """Example implementing the unforced 1D advection equation with periodic BC in [0,1], discretized using upwinding finite differences Attributes: A: FD discretization of the gradient operator using upwinding dx: distance between two spatial nodes""" def __init__(self, p...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class advection1d_dirichlet: """Example implementing the unforced 1D advection equation with periodic BC in [0,1], discretized using upwinding finite differences Attributes: A: FD discretization of the gradient operator using upwinding dx: distance between two spatial nodes""" def __init__(self, problem_params...
the_stack_v2_python_sparse
pySDC/implementations/problem_classes/AdvectionEquation_1D_FD_dirichlet.py
ruthschoebel/pySDC
train
0
1864cb01bf4603872053936a47741ae277730906
[ "body = dict(self._body.dirty)\njob = ExecutableJob.new(**dict(job))\nbody['add_jobs'] = [dict(job._body.dirty)]\nendpoint_override = self.service.get_endpoint_override()\nresponse = session.post('/run-job-flow', headers={}, endpoint_filter=self.service, endpoint_override=endpoint_override, json=dict(body))\nself._...
<|body_start_0|> body = dict(self._body.dirty) job = ExecutableJob.new(**dict(job)) body['add_jobs'] = [dict(job._body.dirty)] endpoint_override = self.service.get_endpoint_override() response = session.post('/run-job-flow', headers={}, endpoint_filter=self.service, endpoint_over...
HuaWei Cluster extends
ClusterInfo
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ClusterInfo: """HuaWei Cluster extends""" def create_and_run(self, session, job): """Create a new cluster and run a job on the created cluster :param session: the openstack session :param dict job: Keyword arguments which will be used to create a :class:`~openstack.map_reduce.v1.clus...
stack_v2_sparse_classes_36k_train_010084
18,095
permissive
[ { "docstring": "Create a new cluster and run a job on the created cluster :param session: the openstack session :param dict job: Keyword arguments which will be used to create a :class:`~openstack.map_reduce.v1.cluster.ExecutableJob`, comprised of the properties on the ExecutableJob class. :return:", "name"...
3
null
Implement the Python class `ClusterInfo` described below. Class description: HuaWei Cluster extends Method signatures and docstrings: - def create_and_run(self, session, job): Create a new cluster and run a job on the created cluster :param session: the openstack session :param dict job: Keyword arguments which will ...
Implement the Python class `ClusterInfo` described below. Class description: HuaWei Cluster extends Method signatures and docstrings: - def create_and_run(self, session, job): Create a new cluster and run a job on the created cluster :param session: the openstack session :param dict job: Keyword arguments which will ...
60d75438d71ffb7998f5dc407ffa890cc98d3171
<|skeleton|> class ClusterInfo: """HuaWei Cluster extends""" def create_and_run(self, session, job): """Create a new cluster and run a job on the created cluster :param session: the openstack session :param dict job: Keyword arguments which will be used to create a :class:`~openstack.map_reduce.v1.clus...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ClusterInfo: """HuaWei Cluster extends""" def create_and_run(self, session, job): """Create a new cluster and run a job on the created cluster :param session: the openstack session :param dict job: Keyword arguments which will be used to create a :class:`~openstack.map_reduce.v1.cluster.Executabl...
the_stack_v2_python_sparse
openstack/map_reduce/v1/cluster.py
huaweicloudsdk/sdk-python
train
20
44b74fe503294d161105c92c218f160926cabe17
[ "self.explanation_type = explanation_type\nself._internal_obj = internal_obj\nself.feature_names = feature_names\nself.feature_types = feature_types\nself.name = name\nself.selector = selector", "if key is None:\n return self._internal_obj['overall']\nreturn self._internal_obj['specific'][key]", "from ..visu...
<|body_start_0|> self.explanation_type = explanation_type self._internal_obj = internal_obj self.feature_names = feature_names self.feature_types = feature_types self.name = name self.selector = selector <|end_body_0|> <|body_start_1|> if key is None: ...
Visualizes rules as HTML for both global and local explanations.
RulesExplanation
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RulesExplanation: """Visualizes rules as HTML for both global and local explanations.""" def __init__(self, explanation_type, internal_obj, feature_names=None, feature_types=None, name=None, selector=None): """Initializes class. Args: explanation_type: Type of explanation. internal_o...
stack_v2_sparse_classes_36k_train_010085
14,262
permissive
[ { "docstring": "Initializes class. Args: explanation_type: Type of explanation. internal_obj: A jsonable object that backs the explanation. feature_names: List of feature names. feature_types: List of feature types. name: User-defined name of explanation. selector: A dataframe whose indices correspond to explan...
3
stack_v2_sparse_classes_30k_train_004049
Implement the Python class `RulesExplanation` described below. Class description: Visualizes rules as HTML for both global and local explanations. Method signatures and docstrings: - def __init__(self, explanation_type, internal_obj, feature_names=None, feature_types=None, name=None, selector=None): Initializes class...
Implement the Python class `RulesExplanation` described below. Class description: Visualizes rules as HTML for both global and local explanations. Method signatures and docstrings: - def __init__(self, explanation_type, internal_obj, feature_names=None, feature_types=None, name=None, selector=None): Initializes class...
e6f38ea195aecbbd9d28c7183a83c65ada16e1ae
<|skeleton|> class RulesExplanation: """Visualizes rules as HTML for both global and local explanations.""" def __init__(self, explanation_type, internal_obj, feature_names=None, feature_types=None, name=None, selector=None): """Initializes class. Args: explanation_type: Type of explanation. internal_o...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RulesExplanation: """Visualizes rules as HTML for both global and local explanations.""" def __init__(self, explanation_type, internal_obj, feature_names=None, feature_types=None, name=None, selector=None): """Initializes class. Args: explanation_type: Type of explanation. internal_obj: A jsonabl...
the_stack_v2_python_sparse
python/interpret-core/interpret/glassbox/_skoperules.py
interpretml/interpret
train
3,731
ea9bb0106ff2976431bf2ddba81caa154cd35d80
[ "n = len(nums)\nseen = set()\nfor i in nums:\n seen.add(i)\nfor i in range(n + 1):\n if i not in seen:\n return i\nreturn -1", "for i, n in enumerate(nums):\n if i != n:\n return i + 1\nreturn len(nums) + 1" ]
<|body_start_0|> n = len(nums) seen = set() for i in nums: seen.add(i) for i in range(n + 1): if i not in seen: return i return -1 <|end_body_0|> <|body_start_1|> for i, n in enumerate(nums): if i != n: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def missingNumber(self, nums: List[int]) -> int: """My Solution: O(n) Time IDEA: Create a set of seen numbers. Then, iterate 0...n to see which number is missing. # Time Complexity: O(n) # Space Complexity: O(n)""" <|body_0|> def missingNumber(self, nums: List[int]...
stack_v2_sparse_classes_36k_train_010086
1,355
no_license
[ { "docstring": "My Solution: O(n) Time IDEA: Create a set of seen numbers. Then, iterate 0...n to see which number is missing. # Time Complexity: O(n) # Space Complexity: O(n)", "name": "missingNumber", "signature": "def missingNumber(self, nums: List[int]) -> int" }, { "docstring": "My Solution...
2
stack_v2_sparse_classes_30k_train_012653
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def missingNumber(self, nums: List[int]) -> int: My Solution: O(n) Time IDEA: Create a set of seen numbers. Then, iterate 0...n to see which number is missing. # Time Complexity:...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def missingNumber(self, nums: List[int]) -> int: My Solution: O(n) Time IDEA: Create a set of seen numbers. Then, iterate 0...n to see which number is missing. # Time Complexity:...
8b11ceb675089a12a4a44f9b044dac7c3e666819
<|skeleton|> class Solution: def missingNumber(self, nums: List[int]) -> int: """My Solution: O(n) Time IDEA: Create a set of seen numbers. Then, iterate 0...n to see which number is missing. # Time Complexity: O(n) # Space Complexity: O(n)""" <|body_0|> def missingNumber(self, nums: List[int]...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def missingNumber(self, nums: List[int]) -> int: """My Solution: O(n) Time IDEA: Create a set of seen numbers. Then, iterate 0...n to see which number is missing. # Time Complexity: O(n) # Space Complexity: O(n)""" n = len(nums) seen = set() for i in nums: ...
the_stack_v2_python_sparse
Python_Solutions/268_Missing_Number.py
lw75251/leetcode
train
0
be4c15a46d621582bd8651a5a00a806ea546c6e8
[ "if self.voucher_id and self.voucher_id.pay_now == 'installments':\n if str(fields.datetime.now()) < self.date:\n raise UserError(_(\"you can't post this move yet untill move date come %s\" % self.date))\n else:\n self.line_ids.with_context(check_move_validity=False)._onchange_amount_currency()\...
<|body_start_0|> if self.voucher_id and self.voucher_id.pay_now == 'installments': if str(fields.datetime.now()) < self.date: raise UserError(_("you can't post this move yet untill move date come %s" % self.date)) else: self.line_ids.with_context(check_mov...
AccountMove
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AccountMove: def post(self): """override post func to set required constraints to installment voucher :return:""" <|body_0|> def open_payment_view(self): """open register payment wizard :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> if sel...
stack_v2_sparse_classes_36k_train_010087
40,481
no_license
[ { "docstring": "override post func to set required constraints to installment voucher :return:", "name": "post", "signature": "def post(self)" }, { "docstring": "open register payment wizard :return:", "name": "open_payment_view", "signature": "def open_payment_view(self)" } ]
2
null
Implement the Python class `AccountMove` described below. Class description: Implement the AccountMove class. Method signatures and docstrings: - def post(self): override post func to set required constraints to installment voucher :return: - def open_payment_view(self): open register payment wizard :return:
Implement the Python class `AccountMove` described below. Class description: Implement the AccountMove class. Method signatures and docstrings: - def post(self): override post func to set required constraints to installment voucher :return: - def open_payment_view(self): open register payment wizard :return: <|skele...
0b997095c260d58b026440967fea3a202bef7efb
<|skeleton|> class AccountMove: def post(self): """override post func to set required constraints to installment voucher :return:""" <|body_0|> def open_payment_view(self): """open register payment wizard :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AccountMove: def post(self): """override post func to set required constraints to installment voucher :return:""" if self.voucher_id and self.voucher_id.pay_now == 'installments': if str(fields.datetime.now()) < self.date: raise UserError(_("you can't post this move...
the_stack_v2_python_sparse
v_11/EBS-SVN/branches/ebs/account_voucher_custom/models/account_voucher.py
musabahmed/baba
train
0
9cdb059585a0c8cc794f4e7c24d6d7a451e7e21b
[ "population_size = param_value(graph, parameters, Parameter.POPULATION_SIZE)\nno_of_processes = param_value(graph, parameters, Parameter.NO_OF_PROCESSES)\nindividuals = generate_individuals(graph, parameters)\npopulations = []\nchunks = ChainChunkFactory._list_chunks(individuals, population_size, no_of_processes)\n...
<|body_start_0|> population_size = param_value(graph, parameters, Parameter.POPULATION_SIZE) no_of_processes = param_value(graph, parameters, Parameter.NO_OF_PROCESSES) individuals = generate_individuals(graph, parameters) populations = [] chunks = ChainChunkFactory._list_chunks(...
ChainChunkFactory
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ChainChunkFactory: def create(graph: Graph, parameters: Dict[str, Any]=None) -> Optional[List[Population]]: """Returns a list of no_of_processes populations that have approximately population_size / no_of_processes individuals.""" <|body_0|> def _list_chunks(individuals: Lis...
stack_v2_sparse_classes_36k_train_010088
5,463
permissive
[ { "docstring": "Returns a list of no_of_processes populations that have approximately population_size / no_of_processes individuals.", "name": "create", "signature": "def create(graph: Graph, parameters: Dict[str, Any]=None) -> Optional[List[Population]]" }, { "docstring": "Splits a list into eq...
2
null
Implement the Python class `ChainChunkFactory` described below. Class description: Implement the ChainChunkFactory class. Method signatures and docstrings: - def create(graph: Graph, parameters: Dict[str, Any]=None) -> Optional[List[Population]]: Returns a list of no_of_processes populations that have approximately p...
Implement the Python class `ChainChunkFactory` described below. Class description: Implement the ChainChunkFactory class. Method signatures and docstrings: - def create(graph: Graph, parameters: Dict[str, Any]=None) -> Optional[List[Population]]: Returns a list of no_of_processes populations that have approximately p...
69f0242aceb47fc383d0e56077f08b2b061273b5
<|skeleton|> class ChainChunkFactory: def create(graph: Graph, parameters: Dict[str, Any]=None) -> Optional[List[Population]]: """Returns a list of no_of_processes populations that have approximately population_size / no_of_processes individuals.""" <|body_0|> def _list_chunks(individuals: Lis...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ChainChunkFactory: def create(graph: Graph, parameters: Dict[str, Any]=None) -> Optional[List[Population]]: """Returns a list of no_of_processes populations that have approximately population_size / no_of_processes individuals.""" population_size = param_value(graph, parameters, Parameter.POPU...
the_stack_v2_python_sparse
python/mage/graph_coloring_module/components/chain_chunk.py
gitbuda/mage
train
0
0cfb0517ec15ac37abab6339c68ab3702a128347
[ "super(Attention, self).__init__()\nself.encoder_att = nn.Linear(encoder_dim, attention_dim)\nself.decoder_att = nn.Linear(decoder_dim, attention_dim)\nself.full_att = nn.Linear(attention_dim, 1)\nself.tanh = nn.Tanh()\nself.softmax = nn.Softmax(dim=1)", "att1 = self.encoder_att(encoder_out)\natt2 = self.decoder_...
<|body_start_0|> super(Attention, self).__init__() self.encoder_att = nn.Linear(encoder_dim, attention_dim) self.decoder_att = nn.Linear(decoder_dim, attention_dim) self.full_att = nn.Linear(attention_dim, 1) self.tanh = nn.Tanh() self.softmax = nn.Softmax(dim=1) <|end_bo...
Attention Network.
Attention
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Attention: """Attention Network.""" def __init__(self, encoder_dim, decoder_dim, attention_dim): """:param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the attention network""" <|body_0|> def forward(...
stack_v2_sparse_classes_36k_train_010089
5,269
no_license
[ { "docstring": ":param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the attention network", "name": "__init__", "signature": "def __init__(self, encoder_dim, decoder_dim, attention_dim)" }, { "docstring": "Forward propagation...
2
stack_v2_sparse_classes_30k_train_003212
Implement the Python class `Attention` described below. Class description: Attention Network. Method signatures and docstrings: - def __init__(self, encoder_dim, decoder_dim, attention_dim): :param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the ...
Implement the Python class `Attention` described below. Class description: Attention Network. Method signatures and docstrings: - def __init__(self, encoder_dim, decoder_dim, attention_dim): :param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the ...
02d93ee55bde386455eb1b146810528ffa3739d0
<|skeleton|> class Attention: """Attention Network.""" def __init__(self, encoder_dim, decoder_dim, attention_dim): """:param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the attention network""" <|body_0|> def forward(...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Attention: """Attention Network.""" def __init__(self, encoder_dim, decoder_dim, attention_dim): """:param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the attention network""" super(Attention, self).__init__() ...
the_stack_v2_python_sparse
modules.py
euyniy/785-visual-story-telling
train
0
b9e15a7a0d8ab884552ac29b91dc1c465decd9be
[ "super().__init__(creator, flock_size, buffer_size)\nself._delay_used = delay_used\nself.inputs = self._create_storage('inputs', (flock_size, buffer_size, *input_shape), force_cpu=False)\nself.targets = self._create_storage('targets', (flock_size, buffer_size, *target_shape))\nself.learning_coefficients = self._cre...
<|body_start_0|> super().__init__(creator, flock_size, buffer_size) self._delay_used = delay_used self.inputs = self._create_storage('inputs', (flock_size, buffer_size, *input_shape), force_cpu=False) self.targets = self._create_storage('targets', (flock_size, buffer_size, *target_shape)...
Defines a circular buffer for a flock of neural networks. It has two storages: for inputs (flock_size, buffer_size, input_size) and for outputs. Then there are learning_coefficients (flock_size, 1) determining how much each network should learn the particular IO.
NetworkFlockBuffer
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NetworkFlockBuffer: """Defines a circular buffer for a flock of neural networks. It has two storages: for inputs (flock_size, buffer_size, input_size) and for outputs. Then there are learning_coefficients (flock_size, 1) determining how much each network should learn the particular IO.""" de...
stack_v2_sparse_classes_36k_train_010090
3,879
permissive
[ { "docstring": "Initialize the buffer Args: flock_size (int): Number of networks in the flock buffer_size (int): Number of elements that can be stored in the buffer before rewriting occurs input_shape (Tuple): The shape of the inputs target_shape (Tuple): The shape of the target delay_used (bool): whether any o...
4
stack_v2_sparse_classes_30k_train_013636
Implement the Python class `NetworkFlockBuffer` described below. Class description: Defines a circular buffer for a flock of neural networks. It has two storages: for inputs (flock_size, buffer_size, input_size) and for outputs. Then there are learning_coefficients (flock_size, 1) determining how much each network sho...
Implement the Python class `NetworkFlockBuffer` described below. Class description: Defines a circular buffer for a flock of neural networks. It has two storages: for inputs (flock_size, buffer_size, input_size) and for outputs. Then there are learning_coefficients (flock_size, 1) determining how much each network sho...
81d72b82ec96948c26d292d709f18c9c77a17ba4
<|skeleton|> class NetworkFlockBuffer: """Defines a circular buffer for a flock of neural networks. It has two storages: for inputs (flock_size, buffer_size, input_size) and for outputs. Then there are learning_coefficients (flock_size, 1) determining how much each network should learn the particular IO.""" de...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NetworkFlockBuffer: """Defines a circular buffer for a flock of neural networks. It has two storages: for inputs (flock_size, buffer_size, input_size) and for outputs. Then there are learning_coefficients (flock_size, 1) determining how much each network should learn the particular IO.""" def __init__(se...
the_stack_v2_python_sparse
torchsim/core/models/neural_network/network_flock_buffer.py
andreofner/torchsim
train
0
b84e71ba1220bdb44966376d31cc7b02176e1112
[ "kwargs.setdefault('sheriffs', ['sheriff'])\nkwargs.setdefault('sendToInterestedUsers', True)\nkwargs.setdefault('status_header', 'Automatically closing tree for \"%(steps)s\" on \"%(builder)s\"')\nchromium_notifier.ChromiumNotifier.__init__(self, **kwargs)\nself.tree_status_url = tree_status_url\nself.check_revisi...
<|body_start_0|> kwargs.setdefault('sheriffs', ['sheriff']) kwargs.setdefault('sendToInterestedUsers', True) kwargs.setdefault('status_header', 'Automatically closing tree for "%(steps)s" on "%(builder)s"') chromium_notifier.ChromiumNotifier.__init__(self, **kwargs) self.tree_sta...
This is a status notifier which closes the tree upon failures. See builder.interfaces.IStatusReceiver to have more information about the parameters type.
GateKeeper
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GateKeeper: """This is a status notifier which closes the tree upon failures. See builder.interfaces.IStatusReceiver to have more information about the parameters type.""" def __init__(self, tree_status_url, tree_message=None, check_revisions=True, **kwargs): """Constructor with foll...
stack_v2_sparse_classes_36k_train_010091
8,792
no_license
[ { "docstring": "Constructor with following specific arguments (on top of base class'). @type tree_status_url: String. @param tree_status_url: Web end-point for tree status updates. @type tree_message: String. @param tree_message: Message posted to the tree status site when closed. @type check_revisions: Boolean...
4
null
Implement the Python class `GateKeeper` described below. Class description: This is a status notifier which closes the tree upon failures. See builder.interfaces.IStatusReceiver to have more information about the parameters type. Method signatures and docstrings: - def __init__(self, tree_status_url, tree_message=Non...
Implement the Python class `GateKeeper` described below. Class description: This is a status notifier which closes the tree upon failures. See builder.interfaces.IStatusReceiver to have more information about the parameters type. Method signatures and docstrings: - def __init__(self, tree_status_url, tree_message=Non...
516718f9b7b95c4280257b2d319638d4728a90e1
<|skeleton|> class GateKeeper: """This is a status notifier which closes the tree upon failures. See builder.interfaces.IStatusReceiver to have more information about the parameters type.""" def __init__(self, tree_status_url, tree_message=None, check_revisions=True, **kwargs): """Constructor with foll...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GateKeeper: """This is a status notifier which closes the tree upon failures. See builder.interfaces.IStatusReceiver to have more information about the parameters type.""" def __init__(self, tree_status_url, tree_message=None, check_revisions=True, **kwargs): """Constructor with following specifi...
the_stack_v2_python_sparse
build/scripts/master/gatekeeper.py
mhcchang/chromium30
train
0
a2cace009e5ae6907d422bb2d22796e400f550c1
[ "course = Course.objects.get(id=pk)\nqueryset = course.lecture_set\nserializer = self.lecture_serializer(queryset.all(), many=True)\nreturn Response(serializer.data)", "course = Course.objects.get(id=pk)\nqueryset = course.lecture_set\nserializer = self.emotion_serializer(queryset.all(), many=True)\nreturn Respon...
<|body_start_0|> course = Course.objects.get(id=pk) queryset = course.lecture_set serializer = self.lecture_serializer(queryset.all(), many=True) return Response(serializer.data) <|end_body_0|> <|body_start_1|> course = Course.objects.get(id=pk) queryset = course.lecture...
Viewset for handling course queries
CourseViewSet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CourseViewSet: """Viewset for handling course queries""" def lectures(self, request, pk=None): """Returns all lectures for a particular course""" <|body_0|> def emotions(self, request, pk=None): """Returns all emotions for a particular course""" <|body_1|...
stack_v2_sparse_classes_36k_train_010092
7,767
no_license
[ { "docstring": "Returns all lectures for a particular course", "name": "lectures", "signature": "def lectures(self, request, pk=None)" }, { "docstring": "Returns all emotions for a particular course", "name": "emotions", "signature": "def emotions(self, request, pk=None)" } ]
2
stack_v2_sparse_classes_30k_train_002637
Implement the Python class `CourseViewSet` described below. Class description: Viewset for handling course queries Method signatures and docstrings: - def lectures(self, request, pk=None): Returns all lectures for a particular course - def emotions(self, request, pk=None): Returns all emotions for a particular course
Implement the Python class `CourseViewSet` described below. Class description: Viewset for handling course queries Method signatures and docstrings: - def lectures(self, request, pk=None): Returns all lectures for a particular course - def emotions(self, request, pk=None): Returns all emotions for a particular course...
4254efd246b954538a463c03e56c126ed63beec2
<|skeleton|> class CourseViewSet: """Viewset for handling course queries""" def lectures(self, request, pk=None): """Returns all lectures for a particular course""" <|body_0|> def emotions(self, request, pk=None): """Returns all emotions for a particular course""" <|body_1|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CourseViewSet: """Viewset for handling course queries""" def lectures(self, request, pk=None): """Returns all lectures for a particular course""" course = Course.objects.get(id=pk) queryset = course.lecture_set serializer = self.lecture_serializer(queryset.all(), many=True...
the_stack_v2_python_sparse
backend/fuskar/views.py
deven96/fuskar-backend
train
5
7875dcbd86ab6ab959596c7ee82b35ff816bdfe4
[ "db = conn_mysqldb()\ndb_cursor = db.cursor()\nif id is None:\n sql = '\\n SELECT menu_id, menu_name, stock, note\\n FROM menus;\\n '\n db_cursor.execute(sql)\nelse:\n sql = '\\n SELECT menu_id, menu_name, stock, note\\n ...
<|body_start_0|> db = conn_mysqldb() db_cursor = db.cursor() if id is None: sql = '\n SELECT menu_id, menu_name, stock, note\n FROM menus;\n ' db_cursor.execute(sql) else: sql = '\n ...
StockManagement
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StockManagement: def getStock(id=None): """id(menu_id) 값을 받지 않으면 전체 행을 반환 id가 있을 경우 해당하는 값만 반환 반환 형태 [ { menu_id: "..", menu_name: "..", stock: 0, note: "..", }, { ... } ]""" <|body_0|> def setStock(data: list[dict[str, str]]): """인수 형태 [ { menu_id: "..", menu_name: ...
stack_v2_sparse_classes_36k_train_010093
3,325
no_license
[ { "docstring": "id(menu_id) 값을 받지 않으면 전체 행을 반환 id가 있을 경우 해당하는 값만 반환 반환 형태 [ { menu_id: \"..\", menu_name: \"..\", stock: 0, note: \"..\", }, { ... } ]", "name": "getStock", "signature": "def getStock(id=None)" }, { "docstring": "인수 형태 [ { menu_id: \"..\", menu_name: \"..\", stock: 0, note: \"..\...
2
stack_v2_sparse_classes_30k_train_001492
Implement the Python class `StockManagement` described below. Class description: Implement the StockManagement class. Method signatures and docstrings: - def getStock(id=None): id(menu_id) 값을 받지 않으면 전체 행을 반환 id가 있을 경우 해당하는 값만 반환 반환 형태 [ { menu_id: "..", menu_name: "..", stock: 0, note: "..", }, { ... } ] - def setSto...
Implement the Python class `StockManagement` described below. Class description: Implement the StockManagement class. Method signatures and docstrings: - def getStock(id=None): id(menu_id) 값을 받지 않으면 전체 행을 반환 id가 있을 경우 해당하는 값만 반환 반환 형태 [ { menu_id: "..", menu_name: "..", stock: 0, note: "..", }, { ... } ] - def setSto...
8d8824c89f7f1c60944f972ec8ef178b4b5ad227
<|skeleton|> class StockManagement: def getStock(id=None): """id(menu_id) 값을 받지 않으면 전체 행을 반환 id가 있을 경우 해당하는 값만 반환 반환 형태 [ { menu_id: "..", menu_name: "..", stock: 0, note: "..", }, { ... } ]""" <|body_0|> def setStock(data: list[dict[str, str]]): """인수 형태 [ { menu_id: "..", menu_name: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StockManagement: def getStock(id=None): """id(menu_id) 값을 받지 않으면 전체 행을 반환 id가 있을 경우 해당하는 값만 반환 반환 형태 [ { menu_id: "..", menu_name: "..", stock: 0, note: "..", }, { ... } ]""" db = conn_mysqldb() db_cursor = db.cursor() if id is None: sql = '\n SEL...
the_stack_v2_python_sparse
packages/stock_management/StockManagement.py
Tanney-102/MrDaeBak_back
train
0
2fee95e03bf8acb9aaf31a09fbfd873f737f3553
[ "text = TextBlob(text)\nresult = text.sentiment\nreturn (result[0], result[1])", "txt = pd.Series(textSeries)\ntxt = txt.map(self.__mapfun)\ntxt = txt.apply(pd.Series)\ntxt.columns = ['polar', 'subj']\nreturn txt" ]
<|body_start_0|> text = TextBlob(text) result = text.sentiment return (result[0], result[1]) <|end_body_0|> <|body_start_1|> txt = pd.Series(textSeries) txt = txt.map(self.__mapfun) txt = txt.apply(pd.Series) txt.columns = ['polar', 'subj'] return txt <|e...
Textblob
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Textblob: def __mapfun(self, text): """text: string""" <|body_0|> def fit(self, textSeries): """Input: list/tuple/pandas.Series [sentence, sentence, ...] Output: dataframe with column name "polar", "subj" Explanation of output: (1) The polarity score is a float withi...
stack_v2_sparse_classes_36k_train_010094
2,696
no_license
[ { "docstring": "text: string", "name": "__mapfun", "signature": "def __mapfun(self, text)" }, { "docstring": "Input: list/tuple/pandas.Series [sentence, sentence, ...] Output: dataframe with column name \"polar\", \"subj\" Explanation of output: (1) The polarity score is a float within the range...
2
stack_v2_sparse_classes_30k_train_011364
Implement the Python class `Textblob` described below. Class description: Implement the Textblob class. Method signatures and docstrings: - def __mapfun(self, text): text: string - def fit(self, textSeries): Input: list/tuple/pandas.Series [sentence, sentence, ...] Output: dataframe with column name "polar", "subj" E...
Implement the Python class `Textblob` described below. Class description: Implement the Textblob class. Method signatures and docstrings: - def __mapfun(self, text): text: string - def fit(self, textSeries): Input: list/tuple/pandas.Series [sentence, sentence, ...] Output: dataframe with column name "polar", "subj" E...
1a3d46cee9bc8cae79e076d6336de5de9fb7427b
<|skeleton|> class Textblob: def __mapfun(self, text): """text: string""" <|body_0|> def fit(self, textSeries): """Input: list/tuple/pandas.Series [sentence, sentence, ...] Output: dataframe with column name "polar", "subj" Explanation of output: (1) The polarity score is a float withi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Textblob: def __mapfun(self, text): """text: string""" text = TextBlob(text) result = text.sentiment return (result[0], result[1]) def fit(self, textSeries): """Input: list/tuple/pandas.Series [sentence, sentence, ...] Output: dataframe with column name "polar", "s...
the_stack_v2_python_sparse
scripts/_sentiment/auto_sentiment_app/brexit_sentiment.py
my2582/gep
train
0
d604215a961a6056e05a25bae247bd20231a252f
[ "try:\n args = [self.config.image_converter, '-version']\n logger.debug('Invoking %r ...', args)\n subprocess.run(args, capture_output=True, check=True)\n return True\nexcept OSError as exc:\n logger.warning(__(\"Unable to run the image conversion command %r. 'sphinx.ext.imgconverter' requires ImageM...
<|body_start_0|> try: args = [self.config.image_converter, '-version'] logger.debug('Invoking %r ...', args) subprocess.run(args, capture_output=True, check=True) return True except OSError as exc: logger.warning(__("Unable to run the image con...
ImagemagickConverter
[ "BSD-3-Clause", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ImagemagickConverter: def is_available(self) -> bool: """Confirms the converter is available or not.""" <|body_0|> def convert(self, _from: str, _to: str) -> bool: """Converts the image to expected one.""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_010095
3,620
permissive
[ { "docstring": "Confirms the converter is available or not.", "name": "is_available", "signature": "def is_available(self) -> bool" }, { "docstring": "Converts the image to expected one.", "name": "convert", "signature": "def convert(self, _from: str, _to: str) -> bool" } ]
2
stack_v2_sparse_classes_30k_train_018578
Implement the Python class `ImagemagickConverter` described below. Class description: Implement the ImagemagickConverter class. Method signatures and docstrings: - def is_available(self) -> bool: Confirms the converter is available or not. - def convert(self, _from: str, _to: str) -> bool: Converts the image to expec...
Implement the Python class `ImagemagickConverter` described below. Class description: Implement the ImagemagickConverter class. Method signatures and docstrings: - def is_available(self) -> bool: Confirms the converter is available or not. - def convert(self, _from: str, _to: str) -> bool: Converts the image to expec...
eab54533a56119c5badd5aac647c595a9adae720
<|skeleton|> class ImagemagickConverter: def is_available(self) -> bool: """Confirms the converter is available or not.""" <|body_0|> def convert(self, _from: str, _to: str) -> bool: """Converts the image to expected one.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ImagemagickConverter: def is_available(self) -> bool: """Confirms the converter is available or not.""" try: args = [self.config.image_converter, '-version'] logger.debug('Invoking %r ...', args) subprocess.run(args, capture_output=True, check=True) ...
the_stack_v2_python_sparse
sphinx/ext/imgconverter.py
sphinx-doc/sphinx
train
6,138
ba1045b4a133fee2f842f1993b3470169335c839
[ "Parametre.__init__(self, 'hotboot', 'hotboot')\nself.aide_courte = 'permet de redémarrer les modules du MUD'\nself.aide_longue = \"Cette commande permet de redémarrer un ou plusieurs modules pendant l'exécution du MUD. Cela permet de corriger des bugs, intégrer des modifications, ajouter ou retirer des commandes s...
<|body_start_0|> Parametre.__init__(self, 'hotboot', 'hotboot') self.aide_courte = 'permet de redémarrer les modules du MUD' self.aide_longue = "Cette commande permet de redémarrer un ou plusieurs modules pendant l'exécution du MUD. Cela permet de corriger des bugs, intégrer des modifications, a...
Commande 'module hotboot'.
PrmHotboot
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PrmHotboot: """Commande 'module hotboot'.""" def __init__(self): """Constructeur du paramètre""" <|body_0|> def interpreter(self, personnage, dic_masques): """Interprétation du paramètre""" <|body_1|> <|end_skeleton|> <|body_start_0|> Parametre....
stack_v2_sparse_classes_36k_train_010096
3,062
permissive
[ { "docstring": "Constructeur du paramètre", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Interprétation du paramètre", "name": "interpreter", "signature": "def interpreter(self, personnage, dic_masques)" } ]
2
stack_v2_sparse_classes_30k_train_001650
Implement the Python class `PrmHotboot` described below. Class description: Commande 'module hotboot'. Method signatures and docstrings: - def __init__(self): Constructeur du paramètre - def interpreter(self, personnage, dic_masques): Interprétation du paramètre
Implement the Python class `PrmHotboot` described below. Class description: Commande 'module hotboot'. Method signatures and docstrings: - def __init__(self): Constructeur du paramètre - def interpreter(self, personnage, dic_masques): Interprétation du paramètre <|skeleton|> class PrmHotboot: """Commande 'module...
7e93bff08cdf891352efba587e89c40f3b4a2301
<|skeleton|> class PrmHotboot: """Commande 'module hotboot'.""" def __init__(self): """Constructeur du paramètre""" <|body_0|> def interpreter(self, personnage, dic_masques): """Interprétation du paramètre""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PrmHotboot: """Commande 'module hotboot'.""" def __init__(self): """Constructeur du paramètre""" Parametre.__init__(self, 'hotboot', 'hotboot') self.aide_courte = 'permet de redémarrer les modules du MUD' self.aide_longue = "Cette commande permet de redémarrer un ou plusie...
the_stack_v2_python_sparse
src/primaires/joueur/commandes/module/hotboot.py
vincent-lg/tsunami
train
5
311b4c55f3f2c3d0fbc1a9d7913350227fabc42a
[ "sq_r = 1.0\nc = 4\nshots = 10\nalpha = [0, np.pi / 4] * c\nphi = [np.pi / 2, 0] * c\ntheta = [0, 0] + [0, np.pi / 2] + [np.pi / 2, 0] + [np.pi / 2]\nwith pytest.raises(ValueError, match='Gate-parameter lists must be of equal length.'):\n singleloop(sq_r, alpha, phi, theta, shots)", "prog = tdmprogram.TDMProgr...
<|body_start_0|> sq_r = 1.0 c = 4 shots = 10 alpha = [0, np.pi / 4] * c phi = [np.pi / 2, 0] * c theta = [0, 0] + [0, np.pi / 2] + [np.pi / 2, 0] + [np.pi / 2] with pytest.raises(ValueError, match='Gate-parameter lists must be of equal length.'): singl...
Test that the correct error messages are raised when a TDMProgram is created
TestTDMErrorRaising
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestTDMErrorRaising: """Test that the correct error messages are raised when a TDMProgram is created""" def test_gates_equal_length(self): """Checks gate list parameters have same length""" <|body_0|> def test_passing_list_of_tdmprograms(self): """Test that error...
stack_v2_sparse_classes_36k_train_010097
29,620
permissive
[ { "docstring": "Checks gate list parameters have same length", "name": "test_gates_equal_length", "signature": "def test_gates_equal_length(self)" }, { "docstring": "Test that error is raised when passing a list containing TDM programs", "name": "test_passing_list_of_tdmprograms", "signa...
2
stack_v2_sparse_classes_30k_train_016893
Implement the Python class `TestTDMErrorRaising` described below. Class description: Test that the correct error messages are raised when a TDMProgram is created Method signatures and docstrings: - def test_gates_equal_length(self): Checks gate list parameters have same length - def test_passing_list_of_tdmprograms(s...
Implement the Python class `TestTDMErrorRaising` described below. Class description: Test that the correct error messages are raised when a TDMProgram is created Method signatures and docstrings: - def test_gates_equal_length(self): Checks gate list parameters have same length - def test_passing_list_of_tdmprograms(s...
0c1c805fd5dfce465a8955ee3faf81037023a23e
<|skeleton|> class TestTDMErrorRaising: """Test that the correct error messages are raised when a TDMProgram is created""" def test_gates_equal_length(self): """Checks gate list parameters have same length""" <|body_0|> def test_passing_list_of_tdmprograms(self): """Test that error...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestTDMErrorRaising: """Test that the correct error messages are raised when a TDMProgram is created""" def test_gates_equal_length(self): """Checks gate list parameters have same length""" sq_r = 1.0 c = 4 shots = 10 alpha = [0, np.pi / 4] * c phi = [np.pi...
the_stack_v2_python_sparse
artifacts/old_dataset_versions/original_commits/strawberryfields/strawberryfields#611/before/test_tdmprogram.py
MattePalte/Bugs-Quantum-Computing-Platforms
train
4
067303081f1241503e9e2c984898ab472cccb0f2
[ "self.resolver = resolver\nself.lock_cache = lock_cache\nself.dependency = dependency", "path = self.resolver.resolve()\ncheckout = None\nif self.dependency.git_tag:\n checkout = self.dependency.git_tag\nelif self.dependency.git_commit:\n checkout = self.dependency.git_commit\nelse:\n raise WurfError('No...
<|body_start_0|> self.resolver = resolver self.lock_cache = lock_cache self.dependency = dependency <|end_body_0|> <|body_start_1|> path = self.resolver.resolve() checkout = None if self.dependency.git_tag: checkout = self.dependency.git_tag elif self...
StoreLockVersionResolver
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StoreLockVersionResolver: def __init__(self, resolver, lock_cache, dependency): """Construct an instance. :param resolver: A resolver which will do the actual job :param lock_cache: The lock cache to store the version information in. :param dependency: A Dependency instance.""" <...
stack_v2_sparse_classes_36k_train_010098
1,223
permissive
[ { "docstring": "Construct an instance. :param resolver: A resolver which will do the actual job :param lock_cache: The lock cache to store the version information in. :param dependency: A Dependency instance.", "name": "__init__", "signature": "def __init__(self, resolver, lock_cache, dependency)" }, ...
2
stack_v2_sparse_classes_30k_train_005690
Implement the Python class `StoreLockVersionResolver` described below. Class description: Implement the StoreLockVersionResolver class. Method signatures and docstrings: - def __init__(self, resolver, lock_cache, dependency): Construct an instance. :param resolver: A resolver which will do the actual job :param lock_...
Implement the Python class `StoreLockVersionResolver` described below. Class description: Implement the StoreLockVersionResolver class. Method signatures and docstrings: - def __init__(self, resolver, lock_cache, dependency): Construct an instance. :param resolver: A resolver which will do the actual job :param lock_...
ba94d46ce58ac7e936fc45acaca1168ae0d7780b
<|skeleton|> class StoreLockVersionResolver: def __init__(self, resolver, lock_cache, dependency): """Construct an instance. :param resolver: A resolver which will do the actual job :param lock_cache: The lock cache to store the version information in. :param dependency: A Dependency instance.""" <...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StoreLockVersionResolver: def __init__(self, resolver, lock_cache, dependency): """Construct an instance. :param resolver: A resolver which will do the actual job :param lock_cache: The lock cache to store the version information in. :param dependency: A Dependency instance.""" self.resolver =...
the_stack_v2_python_sparse
src/wurf/store_lock_version_resolver.py
steinwurf/waf
train
15
5ce53657f5e5895538279d88432d3d4e4ad8f5e1
[ "self.directory = directory\nself.function = function\nself.iterable = iterable", "for i, item in enumerate(self.iterable, start=1):\n with open(os.path.join(self.directory, '%d.input' % i), 'wb') as outfile:\n pickle.dump((self.function, item), outfile, protocol=pickle.HIGHEST_PROTOCOL)" ]
<|body_start_0|> self.directory = directory self.function = function self.iterable = iterable <|end_body_0|> <|body_start_1|> for i, item in enumerate(self.iterable, start=1): with open(os.path.join(self.directory, '%d.input' % i), 'wb') as outfile: pickle.du...
A class to write the input files
InputWriter
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InputWriter: """A class to write the input files""" def __init__(self, directory, function, iterable): """Save the function and iterable""" <|body_0|> def __call__(self): """Call this to write input files""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_010099
4,398
permissive
[ { "docstring": "Save the function and iterable", "name": "__init__", "signature": "def __init__(self, directory, function, iterable)" }, { "docstring": "Call this to write input files", "name": "__call__", "signature": "def __call__(self)" } ]
2
null
Implement the Python class `InputWriter` described below. Class description: A class to write the input files Method signatures and docstrings: - def __init__(self, directory, function, iterable): Save the function and iterable - def __call__(self): Call this to write input files
Implement the Python class `InputWriter` described below. Class description: A class to write the input files Method signatures and docstrings: - def __init__(self, directory, function, iterable): Save the function and iterable - def __call__(self): Call this to write input files <|skeleton|> class InputWriter: ...
88bf7f7c5ac44defc046ebf0719cde748092cfff
<|skeleton|> class InputWriter: """A class to write the input files""" def __init__(self, directory, function, iterable): """Save the function and iterable""" <|body_0|> def __call__(self): """Call this to write input files""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InputWriter: """A class to write the input files""" def __init__(self, directory, function, iterable): """Save the function and iterable""" self.directory = directory self.function = function self.iterable = iterable def __call__(self): """Call this to write i...
the_stack_v2_python_sparse
src/dials/util/cluster_map.py
dials/dials
train
71