blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
24eda61b4eb9bf82940f548487f7ff09425ca867 | [
"if minfo is None:\n minfo = {}\nsuper(DumpJournalBlocksMessage, self).__init__(minfo)\nself.IsSystemMessage = False\nself.IsForward = True\nself.IsReliable = True\nself.Count = minfo.get('Count', 0)",
"result = super(DumpJournalBlocksMessage, self).dump()\nresult['Count'] = self.Count\nreturn result"
] | <|body_start_0|>
if minfo is None:
minfo = {}
super(DumpJournalBlocksMessage, self).__init__(minfo)
self.IsSystemMessage = False
self.IsForward = True
self.IsReliable = True
self.Count = minfo.get('Count', 0)
<|end_body_0|>
<|body_start_1|>
result = s... | Dump journal blocks messages represent the message format for exchanging dump journal blocks messages. Attributes: DumpJournalBlocksMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this message is a system message. IsForward (bool): Whether or not this message is forwarde... | DumpJournalBlocksMessage | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DumpJournalBlocksMessage:
"""Dump journal blocks messages represent the message format for exchanging dump journal blocks messages. Attributes: DumpJournalBlocksMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this message is a system message. IsFor... | stack_v2_sparse_classes_75kplus_train_004200 | 5,835 | permissive | [
{
"docstring": "Constructor for DumpJournalBlocksMessage class. Args: minfo (dict): A dict containing intialization values for a DumpJournalBlocksMessage.",
"name": "__init__",
"signature": "def __init__(self, minfo=None)"
},
{
"docstring": "Returns a dict containing information about the DumpJo... | 2 | stack_v2_sparse_classes_30k_train_011693 | Implement the Python class `DumpJournalBlocksMessage` described below.
Class description:
Dump journal blocks messages represent the message format for exchanging dump journal blocks messages. Attributes: DumpJournalBlocksMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not ... | Implement the Python class `DumpJournalBlocksMessage` described below.
Class description:
Dump journal blocks messages represent the message format for exchanging dump journal blocks messages. Attributes: DumpJournalBlocksMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not ... | 8f4ca1aab54ef420a0db10c8ca822ec8686cd423 | <|skeleton|>
class DumpJournalBlocksMessage:
"""Dump journal blocks messages represent the message format for exchanging dump journal blocks messages. Attributes: DumpJournalBlocksMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this message is a system message. IsFor... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DumpJournalBlocksMessage:
"""Dump journal blocks messages represent the message format for exchanging dump journal blocks messages. Attributes: DumpJournalBlocksMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this message is a system message. IsForward (bool): ... | the_stack_v2_python_sparse | validator/journal/messages/journal_debug.py | aludvik/sawtooth-core | train | 0 |
03502115034121b423ee3d439135b66d65952c93 | [
"self.cities = cities\nself.gas_stations = gas_stations\nself.min_sleep_time = min_sleep_time\nself.max_sleep_time = max_sleep_time\nself.parser = Parser()\nself.params = ['address', 'brand', 'lat', 'lon', 'price_1', 'price_2', 'price_3']\nself.storage = storage",
"for city in self.cities:\n try:\n data... | <|body_start_0|>
self.cities = cities
self.gas_stations = gas_stations
self.min_sleep_time = min_sleep_time
self.max_sleep_time = max_sleep_time
self.parser = Parser()
self.params = ['address', 'brand', 'lat', 'lon', 'price_1', 'price_2', 'price_3']
self.storage =... | A Crawler class for crawling GoogleMaps gas station prices. | Crawler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Crawler:
"""A Crawler class for crawling GoogleMaps gas station prices."""
def __init__(self, cities, gas_stations, storage, min_sleep_time=15, max_sleep_time=60):
"""Initializes a crawler. Args: cities: a list of "city, state" gas_stations: a list of gas stations sleep_time: number ... | stack_v2_sparse_classes_75kplus_train_004201 | 3,279 | no_license | [
{
"docstring": "Initializes a crawler. Args: cities: a list of \"city, state\" gas_stations: a list of gas stations sleep_time: number of seconds to sleep after web request",
"name": "__init__",
"signature": "def __init__(self, cities, gas_stations, storage, min_sleep_time=15, max_sleep_time=60)"
},
... | 3 | stack_v2_sparse_classes_30k_train_009375 | Implement the Python class `Crawler` described below.
Class description:
A Crawler class for crawling GoogleMaps gas station prices.
Method signatures and docstrings:
- def __init__(self, cities, gas_stations, storage, min_sleep_time=15, max_sleep_time=60): Initializes a crawler. Args: cities: a list of "city, state"... | Implement the Python class `Crawler` described below.
Class description:
A Crawler class for crawling GoogleMaps gas station prices.
Method signatures and docstrings:
- def __init__(self, cities, gas_stations, storage, min_sleep_time=15, max_sleep_time=60): Initializes a crawler. Args: cities: a list of "city, state"... | 32d02a7893f0645a1ba18fa463fc3dd02e1a6e26 | <|skeleton|>
class Crawler:
"""A Crawler class for crawling GoogleMaps gas station prices."""
def __init__(self, cities, gas_stations, storage, min_sleep_time=15, max_sleep_time=60):
"""Initializes a crawler. Args: cities: a list of "city, state" gas_stations: a list of gas stations sleep_time: number ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Crawler:
"""A Crawler class for crawling GoogleMaps gas station prices."""
def __init__(self, cities, gas_stations, storage, min_sleep_time=15, max_sleep_time=60):
"""Initializes a crawler. Args: cities: a list of "city, state" gas_stations: a list of gas stations sleep_time: number of seconds to... | the_stack_v2_python_sparse | crawler/crawler.py | WSJ-2018SE-CPP/gasme | train | 1 |
a858422fbafaa654b19f6b98fe425d75745320aa | [
"index_map = {num: index for index, num in enumerate(row)}\n\ndef arrange(a: int) -> int:\n count = 0\n while True:\n a = a >> 1 << 1\n if row[a] == row[a + 1] + 1 and row[a] % 2 == 1 or (row[a + 1] == row[a] + 1 and row[a] % 2 == 0):\n break\n if row[a] % 2 == 0:\n ... | <|body_start_0|>
index_map = {num: index for index, num in enumerate(row)}
def arrange(a: int) -> int:
count = 0
while True:
a = a >> 1 << 1
if row[a] == row[a + 1] + 1 and row[a] % 2 == 1 or (row[a + 1] == row[a] + 1 and row[a] % 2 == 0):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minSwapsCouples(self, row: List[int]) -> int:
"""直接按照目标的座位执行交换"""
<|body_0|>
def minSwapsCouples_uf(self, row: List[int]) -> int:
"""faster 也可使用并交集的思路,以(2i, 2i + 1)为单元,对不符合座位条件的组合进行并交集运算 合并的条件是两个组合内均有属于一对夫妻的其中一个编号 最终的交换次数是 sum{ 并集元素数量 - 1 }"""
<... | stack_v2_sparse_classes_75kplus_train_004202 | 2,039 | no_license | [
{
"docstring": "直接按照目标的座位执行交换",
"name": "minSwapsCouples",
"signature": "def minSwapsCouples(self, row: List[int]) -> int"
},
{
"docstring": "faster 也可使用并交集的思路,以(2i, 2i + 1)为单元,对不符合座位条件的组合进行并交集运算 合并的条件是两个组合内均有属于一对夫妻的其中一个编号 最终的交换次数是 sum{ 并集元素数量 - 1 }",
"name": "minSwapsCouples_uf",
"signa... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minSwapsCouples(self, row: List[int]) -> int: 直接按照目标的座位执行交换
- def minSwapsCouples_uf(self, row: List[int]) -> int: faster 也可使用并交集的思路,以(2i, 2i + 1)为单元,对不符合座位条件的组合进行并交集运算 合并的条件... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minSwapsCouples(self, row: List[int]) -> int: 直接按照目标的座位执行交换
- def minSwapsCouples_uf(self, row: List[int]) -> int: faster 也可使用并交集的思路,以(2i, 2i + 1)为单元,对不符合座位条件的组合进行并交集运算 合并的条件... | ba428d2183b916b39b50783c95f909993b04c1f0 | <|skeleton|>
class Solution:
def minSwapsCouples(self, row: List[int]) -> int:
"""直接按照目标的座位执行交换"""
<|body_0|>
def minSwapsCouples_uf(self, row: List[int]) -> int:
"""faster 也可使用并交集的思路,以(2i, 2i + 1)为单元,对不符合座位条件的组合进行并交集运算 合并的条件是两个组合内均有属于一对夫妻的其中一个编号 最终的交换次数是 sum{ 并集元素数量 - 1 }"""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minSwapsCouples(self, row: List[int]) -> int:
"""直接按照目标的座位执行交换"""
index_map = {num: index for index, num in enumerate(row)}
def arrange(a: int) -> int:
count = 0
while True:
a = a >> 1 << 1
if row[a] == row[a + 1] +... | the_stack_v2_python_sparse | src/main/LeetCode/python/couples-holding-hands.py | chengqhuster/xishuashua | train | 0 | |
893d6ef10b4d14255d8476558e092627443298cf | [
"q = deque([root])\noutput = []\nwhile q:\n node = q.popleft()\n if isinstance(node, TreeNode):\n output.append(str(node.val))\n q.append(node.left)\n q.append(node.right)\n else:\n output.append('x')\nreturn ','.join(output)",
"data = data.split(',')\nq = deque([])\nif data[0... | <|body_start_0|>
q = deque([root])
output = []
while q:
node = q.popleft()
if isinstance(node, TreeNode):
output.append(str(node.val))
q.append(node.left)
q.append(node.right)
else:
output.append(... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_004203 | 1,622 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_029354 | 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:... | 97533d53c8892b6519e99f344489fa4fd4c9ab93 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
q = deque([root])
output = []
while q:
node = q.popleft()
if isinstance(node, TreeNode):
output.append(str(node.val))
... | the_stack_v2_python_sparse | 8. Tree/297.py | proTao/leetcode | train | 0 | |
48fc8d2094aca0fb68753a3f46488d3f72a486d2 | [
"res = []\nsetNums = set(nums)\nfor i in range(1, len(nums) + 1):\n if i not in setNums:\n res.append(i)\nreturn res",
"for i in xrange(len(nums)):\n index = abs(nums[i]) - 1\n nums[index] = -abs(nums[index])\nres = [i + 1 for i, x in enumerate(nums) if x > 0]\nreturn res",
"ret = []\nnums = [0]... | <|body_start_0|>
res = []
setNums = set(nums)
for i in range(1, len(nums) + 1):
if i not in setNums:
res.append(i)
return res
<|end_body_0|>
<|body_start_1|>
for i in xrange(len(nums)):
index = abs(nums[i]) - 1
nums[index] = -a... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDisappearedNumbers(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def findDisappearedNumbers2(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
def findDisappearedNumbers3(self, nums):
... | stack_v2_sparse_classes_75kplus_train_004204 | 1,369 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "findDisappearedNumbers",
"signature": "def findDisappearedNumbers(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "findDisappearedNumbers2",
"signature": "def findDisappearedNumbers2(self... | 3 | stack_v2_sparse_classes_30k_train_011040 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDisappearedNumbers(self, nums): :type nums: List[int] :rtype: List[int]
- def findDisappearedNumbers2(self, nums): :type nums: List[int] :rtype: List[int]
- def findDisap... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDisappearedNumbers(self, nums): :type nums: List[int] :rtype: List[int]
- def findDisappearedNumbers2(self, nums): :type nums: List[int] :rtype: List[int]
- def findDisap... | b925bb22d1daa4a56c5a238a5758a926905559b4 | <|skeleton|>
class Solution:
def findDisappearedNumbers(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def findDisappearedNumbers2(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
def findDisappearedNumbers3(self, nums):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findDisappearedNumbers(self, nums):
""":type nums: List[int] :rtype: List[int]"""
res = []
setNums = set(nums)
for i in range(1, len(nums) + 1):
if i not in setNums:
res.append(i)
return res
def findDisappearedNumbers2(self... | the_stack_v2_python_sparse | 448. Find All Numbers Disappeared in an Array.py | beninghton/notGivenUpToG | train | 0 | |
7eaba6bd8242c467d2422136ebc2ec5b4dcd7bf8 | [
"super().__init__()\nself.N = neighbor_graph\nself.stylesheet = stylesheet\nself.style = next(self.stylesheet[style])\nself._ball()\nself._hull()\nself._edges()\nself._points()\nself._vertices()",
"point_style = self.style.get('graph_point')\nif point_style is not None:\n point_style_dict = next(self.styleshee... | <|body_start_0|>
super().__init__()
self.N = neighbor_graph
self.stylesheet = stylesheet
self.style = next(self.stylesheet[style])
self._ball()
self._hull()
self._edges()
self._points()
self._vertices()
<|end_body_0|>
<|body_start_1|>
poin... | A utility class used to draw visualizations of NeighborGraph objects as a series of points, edges, as well as convex hulls. Attributes ---------- neighbor_graph: NeighborGraph a NeighborGraph object to draw to a canvas. style: str The object style used to draw a NeighborGraph as an str. (default 'neighbor_graph') style... | VizNeighborGraph | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VizNeighborGraph:
"""A utility class used to draw visualizations of NeighborGraph objects as a series of points, edges, as well as convex hulls. Attributes ---------- neighbor_graph: NeighborGraph a NeighborGraph object to draw to a canvas. style: str The object style used to draw a NeighborGraph... | stack_v2_sparse_classes_75kplus_train_004205 | 4,615 | permissive | [
{
"docstring": "Parameters ---------- neighbor_graph: NeighborGraph a NeighborGraph object to draw to a canvas. style: str, optional The object style used to draw a NeighborGraph as an str. (default 'neighbor_graph') stylesheet: StyleSheet, optional The stylesheet used to describe which elements to draw an how ... | 6 | stack_v2_sparse_classes_30k_train_023893 | Implement the Python class `VizNeighborGraph` described below.
Class description:
A utility class used to draw visualizations of NeighborGraph objects as a series of points, edges, as well as convex hulls. Attributes ---------- neighbor_graph: NeighborGraph a NeighborGraph object to draw to a canvas. style: str The ob... | Implement the Python class `VizNeighborGraph` described below.
Class description:
A utility class used to draw visualizations of NeighborGraph objects as a series of points, edges, as well as convex hulls. Attributes ---------- neighbor_graph: NeighborGraph a NeighborGraph object to draw to a canvas. style: str The ob... | 1383b7b005ce59d35b4e012524382c08675594c6 | <|skeleton|>
class VizNeighborGraph:
"""A utility class used to draw visualizations of NeighborGraph objects as a series of points, edges, as well as convex hulls. Attributes ---------- neighbor_graph: NeighborGraph a NeighborGraph object to draw to a canvas. style: str The object style used to draw a NeighborGraph... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VizNeighborGraph:
"""A utility class used to draw visualizations of NeighborGraph objects as a series of points, edges, as well as convex hulls. Attributes ---------- neighbor_graph: NeighborGraph a NeighborGraph object to draw to a canvas. style: str The object style used to draw a NeighborGraph as an str. (... | the_stack_v2_python_sparse | greedypermutation/vizneighborgraph.py | donsheehy/greedypermutation | train | 6 |
b70107750ea4f3ab20af32ca645e2787d0d43152 | [
"ingredient = Ingredient()\ningredient.label = request.data['label']\ntry:\n ingredient.save()\n serializer = IngredientSerializer(ingredient, context={'request': request})\n return Response(serializer.data)\nexcept ValidationError as ex:\n return Response({'reason': ex.message}, status=status.HTTP_400_... | <|body_start_0|>
ingredient = Ingredient()
ingredient.label = request.data['label']
try:
ingredient.save()
serializer = IngredientSerializer(ingredient, context={'request': request})
return Response(serializer.data)
except ValidationError as ex:
... | Ingredients | IngredientsViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IngredientsViewSet:
"""Ingredients"""
def create(self, request):
"""Handle POST operations Returns: Response -- JSON serialized tag instance"""
<|body_0|>
def destroy(self, request, pk=None):
"""Handle DELETE requests for a single ingredient Returns: Response -- ... | stack_v2_sparse_classes_75kplus_train_004206 | 3,086 | no_license | [
{
"docstring": "Handle POST operations Returns: Response -- JSON serialized tag instance",
"name": "create",
"signature": "def create(self, request)"
},
{
"docstring": "Handle DELETE requests for a single ingredient Returns: Response -- 200, 404, or 500 status code",
"name": "destroy",
"... | 5 | stack_v2_sparse_classes_30k_train_053276 | Implement the Python class `IngredientsViewSet` described below.
Class description:
Ingredients
Method signatures and docstrings:
- def create(self, request): Handle POST operations Returns: Response -- JSON serialized tag instance
- def destroy(self, request, pk=None): Handle DELETE requests for a single ingredient ... | Implement the Python class `IngredientsViewSet` described below.
Class description:
Ingredients
Method signatures and docstrings:
- def create(self, request): Handle POST operations Returns: Response -- JSON serialized tag instance
- def destroy(self, request, pk=None): Handle DELETE requests for a single ingredient ... | 70c5943b250ae7f81faf8a45a8941abf385f327c | <|skeleton|>
class IngredientsViewSet:
"""Ingredients"""
def create(self, request):
"""Handle POST operations Returns: Response -- JSON serialized tag instance"""
<|body_0|>
def destroy(self, request, pk=None):
"""Handle DELETE requests for a single ingredient Returns: Response -- ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IngredientsViewSet:
"""Ingredients"""
def create(self, request):
"""Handle POST operations Returns: Response -- JSON serialized tag instance"""
ingredient = Ingredient()
ingredient.label = request.data['label']
try:
ingredient.save()
serializer = In... | the_stack_v2_python_sparse | my_neighbors_api/views/ingredient.py | Kamiran79/my_neighbors_server | train | 0 |
0d6703e01217127940a866539fe74fe98a37e0d1 | [
"self.stream_cache = {}\nself.filename = filename\nfilename = '{0}/{1}'.format(settings.LOG_BASE_PATH, filename)\nsuper(CustomFileHandler, self).__init__(filename, mode=mode, encoding=encoding, delay=delay)",
"brand = settings.BRAND\nif brand is None:\n brand = getattr(record, _BRAND)\nkey = brand + self.baseF... | <|body_start_0|>
self.stream_cache = {}
self.filename = filename
filename = '{0}/{1}'.format(settings.LOG_BASE_PATH, filename)
super(CustomFileHandler, self).__init__(filename, mode=mode, encoding=encoding, delay=delay)
<|end_body_0|>
<|body_start_1|>
brand = settings.BRAND
... | A handler class which writes formatted logging records to disk files. | CustomFileHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomFileHandler:
"""A handler class which writes formatted logging records to disk files."""
def __init__(self, filename, mode='a', encoding=None, delay=0):
"""Open the specified file and use it as the stream for logging."""
<|body_0|>
def emit(self, record):
"... | stack_v2_sparse_classes_75kplus_train_004207 | 2,424 | no_license | [
{
"docstring": "Open the specified file and use it as the stream for logging.",
"name": "__init__",
"signature": "def __init__(self, filename, mode='a', encoding=None, delay=0)"
},
{
"docstring": "Emit a record. If the stream was not opened because 'delay' was specified in the constructor, open ... | 3 | stack_v2_sparse_classes_30k_train_050990 | Implement the Python class `CustomFileHandler` described below.
Class description:
A handler class which writes formatted logging records to disk files.
Method signatures and docstrings:
- def __init__(self, filename, mode='a', encoding=None, delay=0): Open the specified file and use it as the stream for logging.
- d... | Implement the Python class `CustomFileHandler` described below.
Class description:
A handler class which writes formatted logging records to disk files.
Method signatures and docstrings:
- def __init__(self, filename, mode='a', encoding=None, delay=0): Open the specified file and use it as the stream for logging.
- d... | ec9e7896f0b005002111cdf26a375813a388cf53 | <|skeleton|>
class CustomFileHandler:
"""A handler class which writes formatted logging records to disk files."""
def __init__(self, filename, mode='a', encoding=None, delay=0):
"""Open the specified file and use it as the stream for logging."""
<|body_0|>
def emit(self, record):
"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomFileHandler:
"""A handler class which writes formatted logging records to disk files."""
def __init__(self, filename, mode='a', encoding=None, delay=0):
"""Open the specified file and use it as the stream for logging."""
self.stream_cache = {}
self.filename = filename
... | the_stack_v2_python_sparse | src/gladminds/core/loaders/custom_logging.py | ashish-srivastava92/GladmindsAshish | train | 0 |
1f253857a7da706aa6ef79334ea3cf5457783677 | [
"searchMin = self.config.searchMin\nsearchMax = self.config.searchMax\nsearchStep = self.config.searchStep\nsearchNum = 1 + int(math.ceil((searchMax - searchMin) / searchStep))\nsearchVelocity = np.linspace(searchMin, searchMax, num=searchNum, endpoint=True)\nbeta = searchVelocity / const.c.to('km/s').value\ndopple... | <|body_start_0|>
searchMin = self.config.searchMin
searchMax = self.config.searchMax
searchStep = self.config.searchStep
searchNum = 1 + int(math.ceil((searchMax - searchMin) / searchStep))
searchVelocity = np.linspace(searchMin, searchMax, num=searchNum, endpoint=True)
b... | Estimate the radial velocity. | EstimateRadialVelocityTask | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EstimateRadialVelocityTask:
"""Estimate the radial velocity."""
def run(self, spectrum: PfsFiberArray, modelSpectrum: PfsSimpleSpectrum) -> Struct:
"""Get the radial velocity of ``spectrum`` in comparison with ``modelSpectrum``. Parameters ---------- spectrum : `pfs.datamodel.pfsFibe... | stack_v2_sparse_classes_75kplus_train_004208 | 13,859 | no_license | [
{
"docstring": "Get the radial velocity of ``spectrum`` in comparison with ``modelSpectrum``. Parameters ---------- spectrum : `pfs.datamodel.pfsFiberArray.PfsFiberArray` Observed spectrum. It must be whitened (Continuum is 1.0 everywhere.) modelSpectrum : `pfs.datamodel.pfsSimpleSpectrum.PfsSimpleSpectrum` Mod... | 2 | stack_v2_sparse_classes_30k_train_013101 | Implement the Python class `EstimateRadialVelocityTask` described below.
Class description:
Estimate the radial velocity.
Method signatures and docstrings:
- def run(self, spectrum: PfsFiberArray, modelSpectrum: PfsSimpleSpectrum) -> Struct: Get the radial velocity of ``spectrum`` in comparison with ``modelSpectrum``... | Implement the Python class `EstimateRadialVelocityTask` described below.
Class description:
Estimate the radial velocity.
Method signatures and docstrings:
- def run(self, spectrum: PfsFiberArray, modelSpectrum: PfsSimpleSpectrum) -> Struct: Get the radial velocity of ``spectrum`` in comparison with ``modelSpectrum``... | 85602eea2485ac24e0831046dc74f1b2d1a3d89f | <|skeleton|>
class EstimateRadialVelocityTask:
"""Estimate the radial velocity."""
def run(self, spectrum: PfsFiberArray, modelSpectrum: PfsSimpleSpectrum) -> Struct:
"""Get the radial velocity of ``spectrum`` in comparison with ``modelSpectrum``. Parameters ---------- spectrum : `pfs.datamodel.pfsFibe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EstimateRadialVelocityTask:
"""Estimate the radial velocity."""
def run(self, spectrum: PfsFiberArray, modelSpectrum: PfsSimpleSpectrum) -> Struct:
"""Get the radial velocity of ``spectrum`` in comparison with ``modelSpectrum``. Parameters ---------- spectrum : `pfs.datamodel.pfsFiberArray.PfsFib... | the_stack_v2_python_sparse | python/pfs/drp/stella/estimateRadialVelocity.py | Subaru-PFS/drp_stella | train | 3 |
10e8f8883cd78de109537884913911e9f3c9d758 | [
"self.followers = defaultdict(set)\nself.user_tweets = defaultdict(list)\nself.tweet_count = 0",
"if userId not in self.user_tweets:\n self.user_tweets[userId] = [(tweetId, self.tweet_count)]\nelif tweetId in self.user_tweets[userId]:\n return\nelse:\n self.user_tweets[userId].append((tweetId, self.tweet... | <|body_start_0|>
self.followers = defaultdict(set)
self.user_tweets = defaultdict(list)
self.tweet_count = 0
<|end_body_0|>
<|body_start_1|>
if userId not in self.user_tweets:
self.user_tweets[userId] = [(tweetId, self.tweet_count)]
elif tweetId in self.user_tweets[u... | Twitter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Twitter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def postTweet(self, userId: int, tweetId: int) -> None:
"""Compose a new tweet."""
<|body_1|>
def getNewsFeed(self, userId: int) -> List[int]:
"""Retrieve the 10 m... | stack_v2_sparse_classes_75kplus_train_004209 | 3,059 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Compose a new tweet.",
"name": "postTweet",
"signature": "def postTweet(self, userId: int, tweetId: int) -> None"
},
{
"docstring": "Retrieve the 10 mos... | 5 | stack_v2_sparse_classes_30k_test_000945 | Implement the Python class `Twitter` described below.
Class description:
Implement the Twitter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def postTweet(self, userId: int, tweetId: int) -> None: Compose a new tweet.
- def getNewsFeed(self, userId: int) -> List... | Implement the Python class `Twitter` described below.
Class description:
Implement the Twitter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def postTweet(self, userId: int, tweetId: int) -> None: Compose a new tweet.
- def getNewsFeed(self, userId: int) -> List... | ecdc7f8f2ddca0d49ae043c877c184da2112497e | <|skeleton|>
class Twitter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def postTweet(self, userId: int, tweetId: int) -> None:
"""Compose a new tweet."""
<|body_1|>
def getNewsFeed(self, userId: int) -> List[int]:
"""Retrieve the 10 m... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Twitter:
def __init__(self):
"""Initialize your data structure here."""
self.followers = defaultdict(set)
self.user_tweets = defaultdict(list)
self.tweet_count = 0
def postTweet(self, userId: int, tweetId: int) -> None:
"""Compose a new tweet."""
if userId ... | the_stack_v2_python_sparse | leetcode/355-design-twitter.py | Knln/online-coding-judge | train | 0 | |
9945cbe9e9332cb34751b9839bbc9156ebcaee5c | [
"postkey = db.Key.from_path('Post', int(post_id), parent=blog_key())\npost = db.get(postkey)\nif post is not None:\n if self.user and self.user.key().id() == int(post.user_id):\n self.render('editpost.html', subject=post.subject, content=post.content, post_id=post_id)\n elif not self.user:\n ret... | <|body_start_0|>
postkey = db.Key.from_path('Post', int(post_id), parent=blog_key())
post = db.get(postkey)
if post is not None:
if self.user and self.user.key().id() == int(post.user_id):
self.render('editpost.html', subject=post.subject, content=post.content, post_i... | EditPost | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EditPost:
def get(self, post_id):
"""If the user is signed in and authored the post - render the edit-post.html template. Users that are not signed in are redirected to the login page. Otherwise the user does not have permission to edit the post."""
<|body_0|>
def post(self,... | stack_v2_sparse_classes_75kplus_train_004210 | 2,217 | no_license | [
{
"docstring": "If the user is signed in and authored the post - render the edit-post.html template. Users that are not signed in are redirected to the login page. Otherwise the user does not have permission to edit the post.",
"name": "get",
"signature": "def get(self, post_id)"
},
{
"docstring... | 2 | stack_v2_sparse_classes_30k_train_012047 | Implement the Python class `EditPost` described below.
Class description:
Implement the EditPost class.
Method signatures and docstrings:
- def get(self, post_id): If the user is signed in and authored the post - render the edit-post.html template. Users that are not signed in are redirected to the login page. Otherw... | Implement the Python class `EditPost` described below.
Class description:
Implement the EditPost class.
Method signatures and docstrings:
- def get(self, post_id): If the user is signed in and authored the post - render the edit-post.html template. Users that are not signed in are redirected to the login page. Otherw... | 1f5b6141e19f673dfb6b06f738c5a49a7d229244 | <|skeleton|>
class EditPost:
def get(self, post_id):
"""If the user is signed in and authored the post - render the edit-post.html template. Users that are not signed in are redirected to the login page. Otherwise the user does not have permission to edit the post."""
<|body_0|>
def post(self,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EditPost:
def get(self, post_id):
"""If the user is signed in and authored the post - render the edit-post.html template. Users that are not signed in are redirected to the login page. Otherwise the user does not have permission to edit the post."""
postkey = db.Key.from_path('Post', int(post_... | the_stack_v2_python_sparse | handlers/editpost.py | StephenOrgan/multi-user-blog | train | 0 | |
0f16180380a3db7b38c0021d48378878cc953f43 | [
"course_id = request.data.get('course_id')\nuser_id = request.user.id\nexpire = 0\ntry:\n course = Course.objects.get(is_show=True, is_delete=False, pk=course_id)\nexcept Course.DoesNotExist:\n return Response({'message': '参数有误,课程不存在'}, status=status.HTTP_400_BAD_REQUEST)\ntry:\n redis_connection = get_red... | <|body_start_0|>
course_id = request.data.get('course_id')
user_id = request.user.id
expire = 0
try:
course = Course.objects.get(is_show=True, is_delete=False, pk=course_id)
except Course.DoesNotExist:
return Response({'message': '参数有误,课程不存在'}, status=stat... | 购物车视图 | CartView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CartView:
"""购物车视图"""
def add_cart(self, request):
"""将课程添加至购物车的相关操作 :param request: 用户id 课程id 勾选状态 有效期选项 :return:"""
<|body_0|>
def list_cart(self, request):
"""返回购物车列表所需的数据 :param request: :return:"""
<|body_1|>
def car_course_select(self, request)... | stack_v2_sparse_classes_75kplus_train_004211 | 8,717 | no_license | [
{
"docstring": "将课程添加至购物车的相关操作 :param request: 用户id 课程id 勾选状态 有效期选项 :return:",
"name": "add_cart",
"signature": "def add_cart(self, request)"
},
{
"docstring": "返回购物车列表所需的数据 :param request: :return:",
"name": "list_cart",
"signature": "def list_cart(self, request)"
},
{
"docstrin... | 6 | stack_v2_sparse_classes_30k_train_051401 | Implement the Python class `CartView` described below.
Class description:
购物车视图
Method signatures and docstrings:
- def add_cart(self, request): 将课程添加至购物车的相关操作 :param request: 用户id 课程id 勾选状态 有效期选项 :return:
- def list_cart(self, request): 返回购物车列表所需的数据 :param request: :return:
- def car_course_select(self, request): 修改... | Implement the Python class `CartView` described below.
Class description:
购物车视图
Method signatures and docstrings:
- def add_cart(self, request): 将课程添加至购物车的相关操作 :param request: 用户id 课程id 勾选状态 有效期选项 :return:
- def list_cart(self, request): 返回购物车列表所需的数据 :param request: :return:
- def car_course_select(self, request): 修改... | 48fec523ebc9376fdbefb0e27de20a49dacacf3e | <|skeleton|>
class CartView:
"""购物车视图"""
def add_cart(self, request):
"""将课程添加至购物车的相关操作 :param request: 用户id 课程id 勾选状态 有效期选项 :return:"""
<|body_0|>
def list_cart(self, request):
"""返回购物车列表所需的数据 :param request: :return:"""
<|body_1|>
def car_course_select(self, request)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CartView:
"""购物车视图"""
def add_cart(self, request):
"""将课程添加至购物车的相关操作 :param request: 用户id 课程id 勾选状态 有效期选项 :return:"""
course_id = request.data.get('course_id')
user_id = request.user.id
expire = 0
try:
course = Course.objects.get(is_show=True, is_delete... | the_stack_v2_python_sparse | djangoProject/apps/cart/views.py | LH667371/django02_20210412 | train | 0 |
15cdf70b16a4f317c991ec38d5470c40c73d15c3 | [
"fl = MyFloat('-', 12345, 17)\nfl1 = MyFloat('', 54321, 17)\nfl2 = MyFloat('-', 12345, 5)\nfl3 = MyFloat('-', 765432, 45)\nfl4 = MyFloat('-', 765432, 1000)\nfl5 = MyFloat('-', 0, 5)\nres1 = fl - fl1\nres2 = fl2 - fl\nres3 = fl3 - fl1\nres4 = fl4 - fl5\nself.assertEqual(str(res1), '-0.66666E+17')\nself.assertEqual(s... | <|body_start_0|>
fl = MyFloat('-', 12345, 17)
fl1 = MyFloat('', 54321, 17)
fl2 = MyFloat('-', 12345, 5)
fl3 = MyFloat('-', 765432, 45)
fl4 = MyFloat('-', 765432, 1000)
fl5 = MyFloat('-', 0, 5)
res1 = fl - fl1
res2 = fl2 - fl
res3 = fl3 - fl1
... | TestEx5 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestEx5:
def test_sub(self):
"""проверка операции вычитания, и сохранения атрибутов после операции"""
<|body_0|>
def test_ne(self):
"""проверка операции 'не равен'"""
<|body_1|>
def test_ge(self):
"""проверка операции 'больше или равно'"""
... | stack_v2_sparse_classes_75kplus_train_004212 | 2,058 | no_license | [
{
"docstring": "проверка операции вычитания, и сохранения атрибутов после операции",
"name": "test_sub",
"signature": "def test_sub(self)"
},
{
"docstring": "проверка операции 'не равен'",
"name": "test_ne",
"signature": "def test_ne(self)"
},
{
"docstring": "проверка операции 'б... | 4 | stack_v2_sparse_classes_30k_val_000005 | Implement the Python class `TestEx5` described below.
Class description:
Implement the TestEx5 class.
Method signatures and docstrings:
- def test_sub(self): проверка операции вычитания, и сохранения атрибутов после операции
- def test_ne(self): проверка операции 'не равен'
- def test_ge(self): проверка операции 'бол... | Implement the Python class `TestEx5` described below.
Class description:
Implement the TestEx5 class.
Method signatures and docstrings:
- def test_sub(self): проверка операции вычитания, и сохранения атрибутов после операции
- def test_ne(self): проверка операции 'не равен'
- def test_ge(self): проверка операции 'бол... | e3e355b86936a057d9efd27beefc25d34515a4db | <|skeleton|>
class TestEx5:
def test_sub(self):
"""проверка операции вычитания, и сохранения атрибутов после операции"""
<|body_0|>
def test_ne(self):
"""проверка операции 'не равен'"""
<|body_1|>
def test_ge(self):
"""проверка операции 'больше или равно'"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestEx5:
def test_sub(self):
"""проверка операции вычитания, и сохранения атрибутов после операции"""
fl = MyFloat('-', 12345, 17)
fl1 = MyFloat('', 54321, 17)
fl2 = MyFloat('-', 12345, 5)
fl3 = MyFloat('-', 765432, 45)
fl4 = MyFloat('-', 765432, 1000)
f... | the_stack_v2_python_sparse | lab_1/ex5_test.py | ZegsZub/Python_sql_corse_labs | train | 2 | |
dea7b5885ac65ffb89d924b6b4bfd65219e40e22 | [
"super().__init__()\nself.conv1 = Conv2d(in_channels=n_in_channels, out_channels=n_out_channels, kernel_size=(1, 1), stride=(1, 1), bias=False)\nself.bn1 = BatchNorm2d(num_features=n_out_channels)\nself.conv2 = Conv2d(in_channels=n_out_channels, out_channels=n_out_channels, kernel_size=(3, 3), stride=(1, 1), paddin... | <|body_start_0|>
super().__init__()
self.conv1 = Conv2d(in_channels=n_in_channels, out_channels=n_out_channels, kernel_size=(1, 1), stride=(1, 1), bias=False)
self.bn1 = BatchNorm2d(num_features=n_out_channels)
self.conv2 = Conv2d(in_channels=n_out_channels, out_channels=n_out_channels, ... | Bottleneck Residual Block As implemented in 'Deep Learning for Image Recognition', the original ResNet paper (https://arxiv.org/abs/1512.03385). | BottleneckBlockV1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BottleneckBlockV1:
"""Bottleneck Residual Block As implemented in 'Deep Learning for Image Recognition', the original ResNet paper (https://arxiv.org/abs/1512.03385)."""
def __init__(self, n_in_channels, n_out_channels):
"""Init :param n_in_channels: number of channels in the inputs ... | stack_v2_sparse_classes_75kplus_train_004213 | 18,521 | no_license | [
{
"docstring": "Init :param n_in_channels: number of channels in the inputs passed to the `forward` method :type n_in_channels: int :param n_out_channels: number of output channels (convolutional filters) to use in the convolutions applied to the inputs passed to the `forward` method :type n_out_channels: int",... | 2 | stack_v2_sparse_classes_30k_val_001531 | Implement the Python class `BottleneckBlockV1` described below.
Class description:
Bottleneck Residual Block As implemented in 'Deep Learning for Image Recognition', the original ResNet paper (https://arxiv.org/abs/1512.03385).
Method signatures and docstrings:
- def __init__(self, n_in_channels, n_out_channels): Ini... | Implement the Python class `BottleneckBlockV1` described below.
Class description:
Bottleneck Residual Block As implemented in 'Deep Learning for Image Recognition', the original ResNet paper (https://arxiv.org/abs/1512.03385).
Method signatures and docstrings:
- def __init__(self, n_in_channels, n_out_channels): Ini... | e05b2a15dd2925fca5206c2509e1da29c1806834 | <|skeleton|>
class BottleneckBlockV1:
"""Bottleneck Residual Block As implemented in 'Deep Learning for Image Recognition', the original ResNet paper (https://arxiv.org/abs/1512.03385)."""
def __init__(self, n_in_channels, n_out_channels):
"""Init :param n_in_channels: number of channels in the inputs ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BottleneckBlockV1:
"""Bottleneck Residual Block As implemented in 'Deep Learning for Image Recognition', the original ResNet paper (https://arxiv.org/abs/1512.03385)."""
def __init__(self, n_in_channels, n_out_channels):
"""Init :param n_in_channels: number of channels in the inputs passed to the... | the_stack_v2_python_sparse | dl_playground/networks/pytorch/object_classification/resnet.py | sallamander/dl-playground | train | 5 |
9b14e47a390889c730650dd6d0add5f2803d3c8d | [
"super(TokenAuthenticator, self).__init__(rpc, response_handler, **kwargs)\nself.basic_token_handler = BasicTokenHandler(self._rpc)\nself.oidc_token_handler = OidcTokenHandler(self._rpc)",
"def token_decorator(*args: Any, **kwargs: Any) -> Union[Callable, Response]:\n \"\"\"Validate a token and execute the pro... | <|body_start_0|>
super(TokenAuthenticator, self).__init__(rpc, response_handler, **kwargs)
self.basic_token_handler = BasicTokenHandler(self._rpc)
self.oidc_token_handler = OidcTokenHandler(self._rpc)
<|end_body_0|>
<|body_start_1|>
def token_decorator(*args: Any, **kwargs: Any) -> Unio... | Authenticate a user by validating a token. Attributes: rpc: Connection to RPC functions - used to connect to the user service. response_handler: The ResponseParser to parse an exception if the authentication fails. **kwargs: Auxiliary arguments to be used by child classes - not needed here. | TokenAuthenticator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TokenAuthenticator:
"""Authenticate a user by validating a token. Attributes: rpc: Connection to RPC functions - used to connect to the user service. response_handler: The ResponseParser to parse an exception if the authentication fails. **kwargs: Auxiliary arguments to be used by child classes -... | stack_v2_sparse_classes_75kplus_train_004214 | 13,445 | permissive | [
{
"docstring": "Initialize TokenAuthenticator.",
"name": "__init__",
"signature": "def __init__(self, rpc: FlaskPooledClusterRpcProxy, response_handler: ResponseParser, **kwargs: Any) -> None"
},
{
"docstring": "Decorator to authenticate a user by validating its token. Args: func: The wrapped fu... | 4 | stack_v2_sparse_classes_30k_train_002880 | Implement the Python class `TokenAuthenticator` described below.
Class description:
Authenticate a user by validating a token. Attributes: rpc: Connection to RPC functions - used to connect to the user service. response_handler: The ResponseParser to parse an exception if the authentication fails. **kwargs: Auxiliary ... | Implement the Python class `TokenAuthenticator` described below.
Class description:
Authenticate a user by validating a token. Attributes: rpc: Connection to RPC functions - used to connect to the user service. response_handler: The ResponseParser to parse an exception if the authentication fails. **kwargs: Auxiliary ... | 822dbd3ccee25180cc48efd2f891504b6b5edc14 | <|skeleton|>
class TokenAuthenticator:
"""Authenticate a user by validating a token. Attributes: rpc: Connection to RPC functions - used to connect to the user service. response_handler: The ResponseParser to parse an exception if the authentication fails. **kwargs: Auxiliary arguments to be used by child classes -... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TokenAuthenticator:
"""Authenticate a user by validating a token. Attributes: rpc: Connection to RPC functions - used to connect to the user service. response_handler: The ResponseParser to parse an exception if the authentication fails. **kwargs: Auxiliary arguments to be used by child classes - not needed h... | the_stack_v2_python_sparse | gateway/gateway/dependencies/auth.py | Open-EO/openeo-eodc-driver | train | 3 |
c80b7956fa0bf97525d3d975235fba44712a339e | [
"ans = ''\ni = 0\ndominoes = list(dominoes)\nwhile i < len(dominoes):\n if dominoes[i] == '.':\n if i + 1 < len(dominoes) and dominoes[i + 1] == 'L':\n ans += 'L'\n else:\n ans += '.'\n i += 1\n elif dominoes[i] == 'L':\n ans += 'L'\n i += 1\n elif i... | <|body_start_0|>
ans = ''
i = 0
dominoes = list(dominoes)
while i < len(dominoes):
if dominoes[i] == '.':
if i + 1 < len(dominoes) and dominoes[i + 1] == 'L':
ans += 'L'
else:
ans += '.'
i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def pushDominoes(self, dominoes):
""":type dominoes: str :rtype: str"""
<|body_0|>
def pushDominoes2(self, dominoes):
""":type dominoes: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ans = ''
i = 0
dominoe... | stack_v2_sparse_classes_75kplus_train_004215 | 1,783 | no_license | [
{
"docstring": ":type dominoes: str :rtype: str",
"name": "pushDominoes",
"signature": "def pushDominoes(self, dominoes)"
},
{
"docstring": ":type dominoes: str :rtype: str",
"name": "pushDominoes2",
"signature": "def pushDominoes2(self, dominoes)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020479 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pushDominoes(self, dominoes): :type dominoes: str :rtype: str
- def pushDominoes2(self, dominoes): :type dominoes: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pushDominoes(self, dominoes): :type dominoes: str :rtype: str
- def pushDominoes2(self, dominoes): :type dominoes: str :rtype: str
<|skeleton|>
class Solution:
def push... | 143aa25f92f3827aa379f29c67a9b7ec3757fef9 | <|skeleton|>
class Solution:
def pushDominoes(self, dominoes):
""":type dominoes: str :rtype: str"""
<|body_0|>
def pushDominoes2(self, dominoes):
""":type dominoes: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def pushDominoes(self, dominoes):
""":type dominoes: str :rtype: str"""
ans = ''
i = 0
dominoes = list(dominoes)
while i < len(dominoes):
if dominoes[i] == '.':
if i + 1 < len(dominoes) and dominoes[i + 1] == 'L':
... | the_stack_v2_python_sparse | py/leetcode_py/contest/85/838.py | imsure/tech-interview-prep | train | 0 | |
9e844c7b35c315aa85140cdf66f94e03bba4704c | [
"self.id = id\nself.provider_id = provider_id\nself.server_time = server_time\nself.event_start = event_start\nself.event_end = event_end\nself.vehicle_id = vehicle_id\nself.event_comment = event_comment\nself.trigger = trigger\nself.gps_speed = gps_speed\nself.gps_heading = gps_heading\nself.gps_quality = gps_qual... | <|body_start_0|>
self.id = id
self.provider_id = provider_id
self.server_time = server_time
self.event_start = event_start
self.event_end = event_end
self.vehicle_id = vehicle_id
self.event_comment = event_comment
self.trigger = trigger
self.gps_sp... | Implementation of the 'Vehicle Flagged Event' model. TODO: type model description here. Attributes: id (string): The unique identifier for the specific Entity object in the system. provider_id (string): The unique 'Provider ID' of the TSP server_time (string): Date and time when this object was received at the TSP even... | VehicleFlaggedEvent | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VehicleFlaggedEvent:
"""Implementation of the 'Vehicle Flagged Event' model. TODO: type model description here. Attributes: id (string): The unique identifier for the specific Entity object in the system. provider_id (string): The unique 'Provider ID' of the TSP server_time (string): Date and tim... | stack_v2_sparse_classes_75kplus_train_004216 | 7,889 | permissive | [
{
"docstring": "Constructor for the VehicleFlaggedEvent class",
"name": "__init__",
"signature": "def __init__(self, id=None, provider_id=None, server_time=None, event_start=None, event_end=None, vehicle_id=None, trigger=None, ecm_speed=None, engine_rpm=None, acceleration_percent=None, ignition_status=N... | 2 | stack_v2_sparse_classes_30k_train_001083 | Implement the Python class `VehicleFlaggedEvent` described below.
Class description:
Implementation of the 'Vehicle Flagged Event' model. TODO: type model description here. Attributes: id (string): The unique identifier for the specific Entity object in the system. provider_id (string): The unique 'Provider ID' of the... | Implement the Python class `VehicleFlaggedEvent` described below.
Class description:
Implementation of the 'Vehicle Flagged Event' model. TODO: type model description here. Attributes: id (string): The unique identifier for the specific Entity object in the system. provider_id (string): The unique 'Provider ID' of the... | 729e9391879e273545a4818558677b2e47261f08 | <|skeleton|>
class VehicleFlaggedEvent:
"""Implementation of the 'Vehicle Flagged Event' model. TODO: type model description here. Attributes: id (string): The unique identifier for the specific Entity object in the system. provider_id (string): The unique 'Provider ID' of the TSP server_time (string): Date and tim... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VehicleFlaggedEvent:
"""Implementation of the 'Vehicle Flagged Event' model. TODO: type model description here. Attributes: id (string): The unique identifier for the specific Entity object in the system. provider_id (string): The unique 'Provider ID' of the TSP server_time (string): Date and time when this o... | the_stack_v2_python_sparse | sdk/python/v0.1-rc.4/opentelematicsapi/models/vehicle_flagged_event.py | nmfta-repo/nmfta-opentelematics-prototype | train | 2 |
9fb0ad4056fe4a027572ba5765a31132a27a9875 | [
"super(Embedding_Encoder, self).__init__()\nself.num_blocks = num_blocks\nself.num_conv = num_conv\nself.kernel_size = kernel_size\nself.hidden_size = hidden_size\nself.num_heads = num_heads\nself.survival_prob = survival_prob\nself.total_depth = num_blocks * (num_conv + 2) - 1\nself.enc = nn.ModuleList([Encoder_Bl... | <|body_start_0|>
super(Embedding_Encoder, self).__init__()
self.num_blocks = num_blocks
self.num_conv = num_conv
self.kernel_size = kernel_size
self.hidden_size = hidden_size
self.num_heads = num_heads
self.survival_prob = survival_prob
self.total_depth = ... | Embedding_Encoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Embedding_Encoder:
def __init__(self, num_blocks, num_conv, kernel_size, hidden_size, num_heads, survival_prob):
"""QAnet embedding encoder https://arxiv.org/pdf/1804.09541.pdf Args: @param num_blocks: number of encoder blocks @param num_conv: number of convolutional layers per encoder b... | stack_v2_sparse_classes_75kplus_train_004217 | 22,434 | permissive | [
{
"docstring": "QAnet embedding encoder https://arxiv.org/pdf/1804.09541.pdf Args: @param num_blocks: number of encoder blocks @param num_conv: number of convolutional layers per encoder block @param kernel_size: kernel size of depthwise seperable convolution @param hidden_size: hidden dimension of QAnet model ... | 2 | null | Implement the Python class `Embedding_Encoder` described below.
Class description:
Implement the Embedding_Encoder class.
Method signatures and docstrings:
- def __init__(self, num_blocks, num_conv, kernel_size, hidden_size, num_heads, survival_prob): QAnet embedding encoder https://arxiv.org/pdf/1804.09541.pdf Args:... | Implement the Python class `Embedding_Encoder` described below.
Class description:
Implement the Embedding_Encoder class.
Method signatures and docstrings:
- def __init__(self, num_blocks, num_conv, kernel_size, hidden_size, num_heads, survival_prob): QAnet embedding encoder https://arxiv.org/pdf/1804.09541.pdf Args:... | da653de190a733b51428737dee8508d8768dfcc9 | <|skeleton|>
class Embedding_Encoder:
def __init__(self, num_blocks, num_conv, kernel_size, hidden_size, num_heads, survival_prob):
"""QAnet embedding encoder https://arxiv.org/pdf/1804.09541.pdf Args: @param num_blocks: number of encoder blocks @param num_conv: number of convolutional layers per encoder b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Embedding_Encoder:
def __init__(self, num_blocks, num_conv, kernel_size, hidden_size, num_heads, survival_prob):
"""QAnet embedding encoder https://arxiv.org/pdf/1804.09541.pdf Args: @param num_blocks: number of encoder blocks @param num_conv: number of convolutional layers per encoder block @param ke... | the_stack_v2_python_sparse | FinalProject/QANet/QANet_Example/QANet_layers_temp.py | hy2632/cs224n | train | 1 | |
7eacdd182db16839f034150616ef9af018bcf79f | [
"self.duration = duration\nself.color = RESOURCE_COLORS[target] if action == 'mine' else RESOURCE_COLORS[action]\nself.dark_color = self.color.mix(Color.dark, 0.7)\ntarget_str = f'*{target}*' if action == 'mine' else target\nself.action = _format_str(f'{VERBS[action]} {target_str}'.capitalize())\nself.elapsed = 0.0... | <|body_start_0|>
self.duration = duration
self.color = RESOURCE_COLORS[target] if action == 'mine' else RESOURCE_COLORS[action]
self.dark_color = self.color.mix(Color.dark, 0.7)
target_str = f'*{target}*' if action == 'mine' else target
self.action = _format_str(f'{VERBS[action]}... | Represent an action that takes some time to complete. | Action | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Action:
"""Represent an action that takes some time to complete."""
def __init__(self, action, target, duration):
"""Set up the new action. Args: action (str): name of the action duration (float): duration of the action in seconds color (str): color representing the action if progres... | stack_v2_sparse_classes_75kplus_train_004218 | 8,484 | permissive | [
{
"docstring": "Set up the new action. Args: action (str): name of the action duration (float): duration of the action in seconds color (str): color representing the action if progress bar is used.",
"name": "__init__",
"signature": "def __init__(self, action, target, duration)"
},
{
"docstring"... | 4 | stack_v2_sparse_classes_30k_test_001784 | Implement the Python class `Action` described below.
Class description:
Represent an action that takes some time to complete.
Method signatures and docstrings:
- def __init__(self, action, target, duration): Set up the new action. Args: action (str): name of the action duration (float): duration of the action in seco... | Implement the Python class `Action` described below.
Class description:
Represent an action that takes some time to complete.
Method signatures and docstrings:
- def __init__(self, action, target, duration): Set up the new action. Args: action (str): name of the action duration (float): duration of the action in seco... | bab16de366073d18327f6bf92294f42c5728cd25 | <|skeleton|>
class Action:
"""Represent an action that takes some time to complete."""
def __init__(self, action, target, duration):
"""Set up the new action. Args: action (str): name of the action duration (float): duration of the action in seconds color (str): color representing the action if progres... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Action:
"""Represent an action that takes some time to complete."""
def __init__(self, action, target, duration):
"""Set up the new action. Args: action (str): name of the action duration (float): duration of the action in seconds color (str): color representing the action if progress bar is used... | the_stack_v2_python_sparse | src/shellcraft/_cli_impl.py | maebert/shellcraft | train | 14 |
d22cc28a5835a2111c7646ab5cf33c708abc3e5f | [
"if not root:\n return False\nif not root.left and (not root.right):\n return root.val == targetSum\nleft = self.hasPathSum(root.left, targetSum - root.val)\nright = self.hasPathSum(root.right, targetSum - root.val)\nreturn left or right",
"if not root:\n return False\n\ndef traverse(root, count):\n i... | <|body_start_0|>
if not root:
return False
if not root.left and (not root.right):
return root.val == targetSum
left = self.hasPathSum(root.left, targetSum - root.val)
right = self.hasPathSum(root.right, targetSum - root.val)
return left or right
<|end_body... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hasPathSum1(self, root, targetSum):
""":type root: TreeNode :type targetSum: int :rtype: bool 递归,如果需要搜索整颗二叉树,那么递归函数就不要返回值, 如果要搜索其中一条符合条件的路径,递归函数就需要返回值, 因为遇到符合条件的路径了就要及时返回。"""
<|body_0|>
def hasPathSum(self, root, targetSum):
""":type root: TreeNode :typ... | stack_v2_sparse_classes_75kplus_train_004219 | 2,781 | no_license | [
{
"docstring": ":type root: TreeNode :type targetSum: int :rtype: bool 递归,如果需要搜索整颗二叉树,那么递归函数就不要返回值, 如果要搜索其中一条符合条件的路径,递归函数就需要返回值, 因为遇到符合条件的路径了就要及时返回。",
"name": "hasPathSum1",
"signature": "def hasPathSum1(self, root, targetSum)"
},
{
"docstring": ":type root: TreeNode :type targetSum: int :rtype:... | 3 | stack_v2_sparse_classes_30k_train_040715 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasPathSum1(self, root, targetSum): :type root: TreeNode :type targetSum: int :rtype: bool 递归,如果需要搜索整颗二叉树,那么递归函数就不要返回值, 如果要搜索其中一条符合条件的路径,递归函数就需要返回值, 因为遇到符合条件的路径了就要及时返回。
- def... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasPathSum1(self, root, targetSum): :type root: TreeNode :type targetSum: int :rtype: bool 递归,如果需要搜索整颗二叉树,那么递归函数就不要返回值, 如果要搜索其中一条符合条件的路径,递归函数就需要返回值, 因为遇到符合条件的路径了就要及时返回。
- def... | 6e18c5d257840489cc3fb1079ae3804c743982a4 | <|skeleton|>
class Solution:
def hasPathSum1(self, root, targetSum):
""":type root: TreeNode :type targetSum: int :rtype: bool 递归,如果需要搜索整颗二叉树,那么递归函数就不要返回值, 如果要搜索其中一条符合条件的路径,递归函数就需要返回值, 因为遇到符合条件的路径了就要及时返回。"""
<|body_0|>
def hasPathSum(self, root, targetSum):
""":type root: TreeNode :typ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def hasPathSum1(self, root, targetSum):
""":type root: TreeNode :type targetSum: int :rtype: bool 递归,如果需要搜索整颗二叉树,那么递归函数就不要返回值, 如果要搜索其中一条符合条件的路径,递归函数就需要返回值, 因为遇到符合条件的路径了就要及时返回。"""
if not root:
return False
if not root.left and (not root.right):
return r... | the_stack_v2_python_sparse | 112.路径总和.py | yangyuxiang1996/leetcode | train | 0 | |
976c5d8bec3c6f60507b912eb8e52bd9f796b2fa | [
"self.k = k\nself.heap = []\nfor n in nums:\n self.add(n)",
"if len(self.heap) < self.k or val > self.heap[0]:\n heapq.heappush(self.heap, val)\nif len(self.heap) > self.k:\n heapq.heappop(self.heap)\nreturn self.heap[0]"
] | <|body_start_0|>
self.k = k
self.heap = []
for n in nums:
self.add(n)
<|end_body_0|>
<|body_start_1|>
if len(self.heap) < self.k or val > self.heap[0]:
heapq.heappush(self.heap, val)
if len(self.heap) > self.k:
heapq.heappop(self.heap)
... | KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.k = k
self.heap = []
for n in nums:
... | stack_v2_sparse_classes_75kplus_train_004220 | 1,279 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008947 | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, nu... | b5a9cf15b9178deb22a6d373f1669c6990378ae2 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
self.k = k
self.heap = []
for n in nums:
self.add(n)
def add(self, val):
""":type val: int :rtype: int"""
if len(self.heap) < self.k or val > self.heap[0]:
... | the_stack_v2_python_sparse | 0700-0799/0703-kth-largest-element-in-a-stream/0703-kth-largest-element-in-a-stream.py | vicch/leetcode | train | 0 | |
57487a29e85277f7229d36ac6ff63518adcea0bf | [
"result = empty_result()\nresult['data'] = {'devices': []}\nwith sqla_session() as session:\n instance = session.query(Device).filter(Device.id == device_id).one_or_none()\n if instance:\n result['data']['devices'] = device_data_postprocess([instance])\n else:\n return (empty_result('error', ... | <|body_start_0|>
result = empty_result()
result['data'] = {'devices': []}
with sqla_session() as session:
instance = session.query(Device).filter(Device.id == device_id).one_or_none()
if instance:
result['data']['devices'] = device_data_postprocess([instan... | DeviceByIdApi | [
"BSD-2-Clause-Views",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeviceByIdApi:
def get(self, device_id):
"""Get a device from ID"""
<|body_0|>
def delete(self, device_id):
"""Delete device from ID"""
<|body_1|>
def put(self, device_id):
"""Modify device from ID"""
<|body_2|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_004221 | 46,972 | permissive | [
{
"docstring": "Get a device from ID",
"name": "get",
"signature": "def get(self, device_id)"
},
{
"docstring": "Delete device from ID",
"name": "delete",
"signature": "def delete(self, device_id)"
},
{
"docstring": "Modify device from ID",
"name": "put",
"signature": "de... | 3 | stack_v2_sparse_classes_30k_train_030836 | Implement the Python class `DeviceByIdApi` described below.
Class description:
Implement the DeviceByIdApi class.
Method signatures and docstrings:
- def get(self, device_id): Get a device from ID
- def delete(self, device_id): Delete device from ID
- def put(self, device_id): Modify device from ID | Implement the Python class `DeviceByIdApi` described below.
Class description:
Implement the DeviceByIdApi class.
Method signatures and docstrings:
- def get(self, device_id): Get a device from ID
- def delete(self, device_id): Delete device from ID
- def put(self, device_id): Modify device from ID
<|skeleton|>
clas... | d755dfed69bebe0c7bea66ad1802cba2cd89fec8 | <|skeleton|>
class DeviceByIdApi:
def get(self, device_id):
"""Get a device from ID"""
<|body_0|>
def delete(self, device_id):
"""Delete device from ID"""
<|body_1|>
def put(self, device_id):
"""Modify device from ID"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeviceByIdApi:
def get(self, device_id):
"""Get a device from ID"""
result = empty_result()
result['data'] = {'devices': []}
with sqla_session() as session:
instance = session.query(Device).filter(Device.id == device_id).one_or_none()
if instance:
... | the_stack_v2_python_sparse | src/cnaas_nms/api/device.py | SUNET/cnaas-nms | train | 67 | |
bae5ecaefb052a019e2d0887c5521078371df5b5 | [
"trie = {}\nend = []\nwords = list(set(words))\nfor w in words:\n t = trie\n for c in w[::-1]:\n if c not in t:\n t[c] = {}\n t = t[c]\n end.append(t)\nreturn sum((len(word) + 1 for i, word in enumerate(words) if len(end[i]) == 0))",
"good = set(words)\nfor word in words:\n fo... | <|body_start_0|>
trie = {}
end = []
words = list(set(words))
for w in words:
t = trie
for c in w[::-1]:
if c not in t:
t[c] = {}
t = t[c]
end.append(t)
return sum((len(word) + 1 for i, word in... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minimumLengthEncoding(self, words):
""":type words: List[str] :rtype: int"""
<|body_0|>
def minimumLengthEncodingSet(self, words):
""":type words: List[str] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
trie = {}
... | stack_v2_sparse_classes_75kplus_train_004222 | 1,089 | no_license | [
{
"docstring": ":type words: List[str] :rtype: int",
"name": "minimumLengthEncoding",
"signature": "def minimumLengthEncoding(self, words)"
},
{
"docstring": ":type words: List[str] :rtype: int",
"name": "minimumLengthEncodingSet",
"signature": "def minimumLengthEncodingSet(self, words)"... | 2 | stack_v2_sparse_classes_30k_train_022758 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumLengthEncoding(self, words): :type words: List[str] :rtype: int
- def minimumLengthEncodingSet(self, words): :type words: List[str] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumLengthEncoding(self, words): :type words: List[str] :rtype: int
- def minimumLengthEncodingSet(self, words): :type words: List[str] :rtype: int
<|skeleton|>
class Sol... | ac53dd9bf2c4c9d17c9dc5f7fdda32e386658fdd | <|skeleton|>
class Solution:
def minimumLengthEncoding(self, words):
""":type words: List[str] :rtype: int"""
<|body_0|>
def minimumLengthEncodingSet(self, words):
""":type words: List[str] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minimumLengthEncoding(self, words):
""":type words: List[str] :rtype: int"""
trie = {}
end = []
words = list(set(words))
for w in words:
t = trie
for c in w[::-1]:
if c not in t:
t[c] = {}
... | the_stack_v2_python_sparse | words/short_encoding_of_words.py | hwc1824/LeetCodeSolution | train | 0 | |
afbc1ccabfb95936f9168a77bde4b0c32a1b2ce1 | [
"n = self.L = 0 if not matrix else len(matrix[0])\nm = len(matrix)\ntrees = self.trees = []\nfor i in xrange(m):\n tree = [0] * n + matrix[i]\n for i in xrange(n - 1, 0, -1):\n tree[i] = tree[i << 1] + tree[i << 1 | 1]\n trees += (tree,)",
"col += self.L\ntree = self.trees[row]\ntree[col] = val\nw... | <|body_start_0|>
n = self.L = 0 if not matrix else len(matrix[0])
m = len(matrix)
trees = self.trees = []
for i in xrange(m):
tree = [0] * n + matrix[i]
for i in xrange(n - 1, 0, -1):
tree[i] = tree[i << 1] + tree[i << 1 | 1]
trees += (... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]] n dimensional segment tree"""
<|body_0|>
def update(self, row, col, val):
""":type row: int :type col: int :type val: int :rtype: None"""
<|body_1|>
def sumRegion(self, row1, col1, r... | stack_v2_sparse_classes_75kplus_train_004223 | 1,548 | no_license | [
{
"docstring": ":type matrix: List[List[int]] n dimensional segment tree",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row: int :type col: int :type val: int :rtype: None",
"name": "update",
"signature": "def update(self, row, col, val)"
},
... | 3 | stack_v2_sparse_classes_30k_train_042613 | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]] n dimensional segment tree
- def update(self, row, col, val): :type row: int :type col: int :type val: int :rtype: Non... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]] n dimensional segment tree
- def update(self, row, col, val): :type row: int :type col: int :type val: int :rtype: Non... | edff905f63ab95cdd40447b27a9c449c9cefec37 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]] n dimensional segment tree"""
<|body_0|>
def update(self, row, col, val):
""":type row: int :type col: int :type val: int :rtype: None"""
<|body_1|>
def sumRegion(self, row1, col1, r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]] n dimensional segment tree"""
n = self.L = 0 if not matrix else len(matrix[0])
m = len(matrix)
trees = self.trees = []
for i in xrange(m):
tree = [0] * n + matrix[i]
for i in... | the_stack_v2_python_sparse | _0308_Range_Sum_Query_2D_Mutable.py | mingweihe/leetcode | train | 3 | |
8b085fff21261152e2cd43b3d0704ed56eb23550 | [
"visitorTypeDict = self.getDictBykey(self.__getVisitorConfigList().json(), 'name', visitorType)\nself.url = '/mgr/park/parkVisitorlist/save.do'\ndata = {'specialCarTypeConfigId': visitorTypeDict['id'], 'carLicenseNumber': carNum, 'owner': 'apipytest', 'ownerPhone': '135' + SA().create_randomNum(val=8), 'visitReason... | <|body_start_0|>
visitorTypeDict = self.getDictBykey(self.__getVisitorConfigList().json(), 'name', visitorType)
self.url = '/mgr/park/parkVisitorlist/save.do'
data = {'specialCarTypeConfigId': visitorTypeDict['id'], 'carLicenseNumber': carNum, 'owner': 'apipytest', 'ownerPhone': '135' + SA().cre... | 访客车录入 | ParkVisitor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParkVisitor:
"""访客车录入"""
def addVisitor(self, visitorType, carNum):
"""新建访客车辆"""
<|body_0|>
def delVisitor(self, parkName, carNum):
"""删除访客车辆"""
<|body_1|>
def __getVisitorConfigList(self):
"""查看访客配置列表"""
<|body_2|>
def getParkVi... | stack_v2_sparse_classes_75kplus_train_004224 | 13,467 | no_license | [
{
"docstring": "新建访客车辆",
"name": "addVisitor",
"signature": "def addVisitor(self, visitorType, carNum)"
},
{
"docstring": "删除访客车辆",
"name": "delVisitor",
"signature": "def delVisitor(self, parkName, carNum)"
},
{
"docstring": "查看访客配置列表",
"name": "__getVisitorConfigList",
... | 4 | stack_v2_sparse_classes_30k_train_045495 | Implement the Python class `ParkVisitor` described below.
Class description:
访客车录入
Method signatures and docstrings:
- def addVisitor(self, visitorType, carNum): 新建访客车辆
- def delVisitor(self, parkName, carNum): 删除访客车辆
- def __getVisitorConfigList(self): 查看访客配置列表
- def getParkVisitorList(self, parkName): 获取访客录入车辆 | Implement the Python class `ParkVisitor` described below.
Class description:
访客车录入
Method signatures and docstrings:
- def addVisitor(self, visitorType, carNum): 新建访客车辆
- def delVisitor(self, parkName, carNum): 删除访客车辆
- def __getVisitorConfigList(self): 查看访客配置列表
- def getParkVisitorList(self, parkName): 获取访客录入车辆
<|s... | 34c368c109867da26d9256bca85f872b0fac2ea7 | <|skeleton|>
class ParkVisitor:
"""访客车录入"""
def addVisitor(self, visitorType, carNum):
"""新建访客车辆"""
<|body_0|>
def delVisitor(self, parkName, carNum):
"""删除访客车辆"""
<|body_1|>
def __getVisitorConfigList(self):
"""查看访客配置列表"""
<|body_2|>
def getParkVi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ParkVisitor:
"""访客车录入"""
def addVisitor(self, visitorType, carNum):
"""新建访客车辆"""
visitorTypeDict = self.getDictBykey(self.__getVisitorConfigList().json(), 'name', visitorType)
self.url = '/mgr/park/parkVisitorlist/save.do'
data = {'specialCarTypeConfigId': visitorTypeDict[... | the_stack_v2_python_sparse | Api/parkingManage_service/carTypeManage_service/carTypeConfig.py | oyebino/pomp_api | train | 1 |
574aa4ad9432a5ba3f479b88018588f277190b81 | [
"d = dict(zip(nums, [1] * len(nums)))\nres = 0\nwhile len(nums) > 0:\n stack = [nums.pop()]\n if d[stack[0]] == 0:\n continue\n length = 0\n while len(stack) > 0:\n tmp = stack.pop()\n length += 1\n d[tmp] = 0\n if d.get(tmp + 1, 0):\n stack.append(tmp + 1)\... | <|body_start_0|>
d = dict(zip(nums, [1] * len(nums)))
res = 0
while len(nums) > 0:
stack = [nums.pop()]
if d[stack[0]] == 0:
continue
length = 0
while len(stack) > 0:
tmp = stack.pop()
length += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestConsecutive(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def longestConsecutive2(self, nums):
"""using set :type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
d = dict(zip(nums, [... | stack_v2_sparse_classes_75kplus_train_004225 | 1,360 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "longestConsecutive",
"signature": "def longestConsecutive(self, nums)"
},
{
"docstring": "using set :type nums: List[int] :rtype: int",
"name": "longestConsecutive2",
"signature": "def longestConsecutive2(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestConsecutive(self, nums): :type nums: List[int] :rtype: int
- def longestConsecutive2(self, nums): using set :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestConsecutive(self, nums): :type nums: List[int] :rtype: int
- def longestConsecutive2(self, nums): using set :type nums: List[int] :rtype: int
<|skeleton|>
class Solut... | 3d82e6c402711057a95a6435fc29fbfcf2ee9c8f | <|skeleton|>
class Solution:
def longestConsecutive(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def longestConsecutive2(self, nums):
"""using set :type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def longestConsecutive(self, nums):
""":type nums: List[int] :rtype: int"""
d = dict(zip(nums, [1] * len(nums)))
res = 0
while len(nums) > 0:
stack = [nums.pop()]
if d[stack[0]] == 0:
continue
length = 0
... | the_stack_v2_python_sparse | Facebook/LongestConsecutiveSequence.py | KeleiAzz/LeetCode | train | 0 | |
bab2c601921c7124627b494155f5a8893b475487 | [
"mean = 0\nstd = 1\nself.w = np.random.normal(0, np.sqrt(2.0 / np.sum(w_shape)), w_shape)\nself.activation = activation\nself.reg = reg",
"result = np.matmul(x, self.w)\nif self.activation == 'sigmoid':\n result = sigmoid(result)\nelif self.activation == 'relu':\n result = reLU(result)\nelif self.activation... | <|body_start_0|>
mean = 0
std = 1
self.w = np.random.normal(0, np.sqrt(2.0 / np.sum(w_shape)), w_shape)
self.activation = activation
self.reg = reg
<|end_body_0|>
<|body_start_1|>
result = np.matmul(x, self.w)
if self.activation == 'sigmoid':
result =... | Layer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Layer:
def __init__(self, w_shape, activation, reg=1e-05):
"""__init__ :param w_shape: create w with shape w_shape using normal distribution :param activation: string, indicating which activation function to be used"""
<|body_0|>
def forward(self, x):
"""forward This... | stack_v2_sparse_classes_75kplus_train_004226 | 15,107 | no_license | [
{
"docstring": "__init__ :param w_shape: create w with shape w_shape using normal distribution :param activation: string, indicating which activation function to be used",
"name": "__init__",
"signature": "def __init__(self, w_shape, activation, reg=1e-05)"
},
{
"docstring": "forward This functi... | 3 | null | Implement the Python class `Layer` described below.
Class description:
Implement the Layer class.
Method signatures and docstrings:
- def __init__(self, w_shape, activation, reg=1e-05): __init__ :param w_shape: create w with shape w_shape using normal distribution :param activation: string, indicating which activatio... | Implement the Python class `Layer` described below.
Class description:
Implement the Layer class.
Method signatures and docstrings:
- def __init__(self, w_shape, activation, reg=1e-05): __init__ :param w_shape: create w with shape w_shape using normal distribution :param activation: string, indicating which activatio... | 3cc56d2d25c7b0832bd6e01154112bfd88d0ec52 | <|skeleton|>
class Layer:
def __init__(self, w_shape, activation, reg=1e-05):
"""__init__ :param w_shape: create w with shape w_shape using normal distribution :param activation: string, indicating which activation function to be used"""
<|body_0|>
def forward(self, x):
"""forward This... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Layer:
def __init__(self, w_shape, activation, reg=1e-05):
"""__init__ :param w_shape: create w with shape w_shape using normal distribution :param activation: string, indicating which activation function to be used"""
mean = 0
std = 1
self.w = np.random.normal(0, np.sqrt(2.0 /... | the_stack_v2_python_sparse | vietai/Assignment2/dnn_np.py | vuamitom/Code-Exercises | train | 13 | |
f70fd974c27e27efe546ebcb21fbaff8e3ff9664 | [
"path = super().save(dirpath, data, image, extension, **kwargs)\nif self.model is not None:\n with open(join(path, 'model.pkl'), 'wb') as file:\n pickle.dump(self.model, file)\nreturn path",
"io = IO()\nvalues_path = join(path, 'values.npy')\nif exists(values_path):\n values = io.read_npy(values_path... | <|body_start_0|>
path = super().save(dirpath, data, image, extension, **kwargs)
if self.model is not None:
with open(join(path, 'model.pkl'), 'wb') as file:
pickle.dump(self.model, file)
return path
<|end_body_0|>
<|body_start_1|>
io = IO()
values_pat... | Methods for saving and loading classifier objects. | MixtureModelIO | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MixtureModelIO:
"""Methods for saving and loading classifier objects."""
def save(self, dirpath, data=False, image=True, extension=None, **kwargs):
"""Save classifier to specified path. Args: dirpath (str) - directory in which classifier is to be saved data (bool) - if True, save tra... | stack_v2_sparse_classes_75kplus_train_004227 | 9,152 | permissive | [
{
"docstring": "Save classifier to specified path. Args: dirpath (str) - directory in which classifier is to be saved data (bool) - if True, save training data image (bool) - if True, save labeled histogram image extension (str) - directory name extension kwargs: keyword arguments for image rendering",
"nam... | 2 | stack_v2_sparse_classes_30k_train_047583 | Implement the Python class `MixtureModelIO` described below.
Class description:
Methods for saving and loading classifier objects.
Method signatures and docstrings:
- def save(self, dirpath, data=False, image=True, extension=None, **kwargs): Save classifier to specified path. Args: dirpath (str) - directory in which ... | Implement the Python class `MixtureModelIO` described below.
Class description:
Methods for saving and loading classifier objects.
Method signatures and docstrings:
- def save(self, dirpath, data=False, image=True, extension=None, **kwargs): Save classifier to specified path. Args: dirpath (str) - directory in which ... | 4a622c3f5fed4456c3b9240f5a96428789fde9bd | <|skeleton|>
class MixtureModelIO:
"""Methods for saving and loading classifier objects."""
def save(self, dirpath, data=False, image=True, extension=None, **kwargs):
"""Save classifier to specified path. Args: dirpath (str) - directory in which classifier is to be saved data (bool) - if True, save tra... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MixtureModelIO:
"""Methods for saving and loading classifier objects."""
def save(self, dirpath, data=False, image=True, extension=None, **kwargs):
"""Save classifier to specified path. Args: dirpath (str) - directory in which classifier is to be saved data (bool) - if True, save training data im... | the_stack_v2_python_sparse | flyqma/annotation/classification/mixtures.py | sbernasek/flyqma | train | 1 |
6595236c44c4057a806bd33297495d727865a14e | [
"p = head\ndummy = ListNode(0)\npre = dummy\npre.next = p\nwhile pre.next and p and p.next:\n if p.val == p.next.val:\n t = p\n while t.next and t.val == t.next.val:\n t = t.next\n if t.next:\n p.val = t.next.val\n p.next = t.next.next\n else:\n ... | <|body_start_0|>
p = head
dummy = ListNode(0)
pre = dummy
pre.next = p
while pre.next and p and p.next:
if p.val == p.next.val:
t = p
while t.next and t.val == t.next.val:
t = t.next
if t.next:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def deleteDuplicates(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def deleteDuplicates2(self, head):
"""记录下是否需要删除最右一个节点 :type head: ListNode :rtype: ListNode"""
<|body_1|>
def deleteDuplicates3(self, head):
"""看大佬... | stack_v2_sparse_classes_75kplus_train_004228 | 3,703 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "deleteDuplicates",
"signature": "def deleteDuplicates(self, head)"
},
{
"docstring": "记录下是否需要删除最右一个节点 :type head: ListNode :rtype: ListNode",
"name": "deleteDuplicates2",
"signature": "def deleteDuplicates2(self, head)"
}... | 4 | stack_v2_sparse_classes_30k_train_032179 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteDuplicates(self, head): :type head: ListNode :rtype: ListNode
- def deleteDuplicates2(self, head): 记录下是否需要删除最右一个节点 :type head: ListNode :rtype: ListNode
- def deleteDup... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteDuplicates(self, head): :type head: ListNode :rtype: ListNode
- def deleteDuplicates2(self, head): 记录下是否需要删除最右一个节点 :type head: ListNode :rtype: ListNode
- def deleteDup... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def deleteDuplicates(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def deleteDuplicates2(self, head):
"""记录下是否需要删除最右一个节点 :type head: ListNode :rtype: ListNode"""
<|body_1|>
def deleteDuplicates3(self, head):
"""看大佬... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def deleteDuplicates(self, head):
""":type head: ListNode :rtype: ListNode"""
p = head
dummy = ListNode(0)
pre = dummy
pre.next = p
while pre.next and p and p.next:
if p.val == p.next.val:
t = p
while t.next ... | the_stack_v2_python_sparse | 82_删除排序链表中的重复元素 II.py | lovehhf/LeetCode | train | 0 | |
fb8196e51a27b80fb927ad178418c565d67a3172 | [
"self.data_path = data_path\nself.model_path = './model'\nself.pretrained_word2vec = './nlpword2vecembeddingspretrained/glove.6B.300d.txt'\nself.sc_model = None\nself.sd_model = None\nself.load_model()\nself.glove_path = './nlpword2vecembeddingspretrained/glove.6B.100d.txt'",
"try:\n with open('./model/stance_... | <|body_start_0|>
self.data_path = data_path
self.model_path = './model'
self.pretrained_word2vec = './nlpword2vecembeddingspretrained/glove.6B.300d.txt'
self.sc_model = None
self.sd_model = None
self.load_model()
self.glove_path = './nlpword2vecembeddingspretraine... | Stance Detection and Stance Classification By: Xiaodan Chen(Stance Detection), Xiaochi Li(Stance Classification) github.com/XC-Li Mar 2019 - May 2019 @ FiscalNote Methods: __init__(self, data_path: str = '../opinion_mining/') retrain_stance_detection(self) retrain_stance_classification(self) stance_detection(self, spee... | StanceDetectionAndClassification | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StanceDetectionAndClassification:
"""Stance Detection and Stance Classification By: Xiaodan Chen(Stance Detection), Xiaochi Li(Stance Classification) github.com/XC-Li Mar 2019 - May 2019 @ FiscalNote Methods: __init__(self, data_path: str = '../opinion_mining/') retrain_stance_detection(self) ret... | stack_v2_sparse_classes_75kplus_train_004229 | 6,418 | permissive | [
{
"docstring": "Define the paths of data to retrain and trained model :param data_path: optional, the path to the data to retrain the models.",
"name": "__init__",
"signature": "def __init__(self, data_path: str='../opinion_mining/')"
},
{
"docstring": "Load the trained stance detection model an... | 6 | null | Implement the Python class `StanceDetectionAndClassification` described below.
Class description:
Stance Detection and Stance Classification By: Xiaodan Chen(Stance Detection), Xiaochi Li(Stance Classification) github.com/XC-Li Mar 2019 - May 2019 @ FiscalNote Methods: __init__(self, data_path: str = '../opinion_minin... | Implement the Python class `StanceDetectionAndClassification` described below.
Class description:
Stance Detection and Stance Classification By: Xiaodan Chen(Stance Detection), Xiaochi Li(Stance Classification) github.com/XC-Li Mar 2019 - May 2019 @ FiscalNote Methods: __init__(self, data_path: str = '../opinion_minin... | a8343f22156f619f2c8fe9102e6df684d1b4c97f | <|skeleton|>
class StanceDetectionAndClassification:
"""Stance Detection and Stance Classification By: Xiaodan Chen(Stance Detection), Xiaochi Li(Stance Classification) github.com/XC-Li Mar 2019 - May 2019 @ FiscalNote Methods: __init__(self, data_path: str = '../opinion_mining/') retrain_stance_detection(self) ret... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StanceDetectionAndClassification:
"""Stance Detection and Stance Classification By: Xiaodan Chen(Stance Detection), Xiaochi Li(Stance Classification) github.com/XC-Li Mar 2019 - May 2019 @ FiscalNote Methods: __init__(self, data_path: str = '../opinion_mining/') retrain_stance_detection(self) retrain_stance_c... | the_stack_v2_python_sparse | deployment/stance_detection_classification.py | XC-Li/FiscalNote_Project | train | 2 |
1e2ff366708c8c237cdd1846b30815e9c89f0dc6 | [
"if not s or not words:\n return []\nword_len = len(words[0])\nstr_len = word_len * len(words)\nres = []\ntimes = {}\nfor i in words:\n if i not in times:\n times[i] = 0\n times[i] += 1\nfor i in range(word_len):\n self.findSubstring_core(i, s, res, word_len, str_len, times)\nreturn res",
"word... | <|body_start_0|>
if not s or not words:
return []
word_len = len(words[0])
str_len = word_len * len(words)
res = []
times = {}
for i in words:
if i not in times:
times[i] = 0
times[i] += 1
for i in range(word_len... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findSubstring(self, s, words):
""":type s: str :type words: List[str] 其中每个word长度相同!!! :rtype: List[int]"""
<|body_0|>
def findSubstring_core(self, str_start, s, res, word_len, str_len, times):
"""依照分布相同寻找与单词相关联的子串 :param str_start: :param s: :param res:... | stack_v2_sparse_classes_75kplus_train_004230 | 2,309 | no_license | [
{
"docstring": ":type s: str :type words: List[str] 其中每个word长度相同!!! :rtype: List[int]",
"name": "findSubstring",
"signature": "def findSubstring(self, s, words)"
},
{
"docstring": "依照分布相同寻找与单词相关联的子串 :param str_start: :param s: :param res: :param word_len: :param str_len: :param times: :return:",... | 2 | stack_v2_sparse_classes_30k_train_000454 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findSubstring(self, s, words): :type s: str :type words: List[str] 其中每个word长度相同!!! :rtype: List[int]
- def findSubstring_core(self, str_start, s, res, word_len, str_len, time... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findSubstring(self, s, words): :type s: str :type words: List[str] 其中每个word长度相同!!! :rtype: List[int]
- def findSubstring_core(self, str_start, s, res, word_len, str_len, time... | 328fdd303af1c8cde5bc9bb4c4f039e777de20e5 | <|skeleton|>
class Solution:
def findSubstring(self, s, words):
""":type s: str :type words: List[str] 其中每个word长度相同!!! :rtype: List[int]"""
<|body_0|>
def findSubstring_core(self, str_start, s, res, word_len, str_len, times):
"""依照分布相同寻找与单词相关联的子串 :param str_start: :param s: :param res:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findSubstring(self, s, words):
""":type s: str :type words: List[str] 其中每个word长度相同!!! :rtype: List[int]"""
if not s or not words:
return []
word_len = len(words[0])
str_len = word_len * len(words)
res = []
times = {}
for i in wo... | the_stack_v2_python_sparse | leetcode/x30. 与所有单词相关联的字串.py | zhangzeyang0/code | train | 0 | |
85310979df1a365a755a504e544a2a1f779fd344 | [
"self.particles = particles\nself.time = 0.0\nself.boundary = boundary\nself.g = g",
"self.time += dt\nself.particles.state[:, :2] += self.particles.state[:, 2:] * dt\ndist = squareform(pdist(self.particles.state[:, :2]))\ni, j = np.where(dist < 2 * self.particles.size)\ncollided = i < j\ni = i[collided]\nj = j[c... | <|body_start_0|>
self.particles = particles
self.time = 0.0
self.boundary = boundary
self.g = g
<|end_body_0|>
<|body_start_1|>
self.time += dt
self.particles.state[:, :2] += self.particles.state[:, 2:] * dt
dist = squareform(pdist(self.particles.state[:, :2]))
... | class that implements the basic fiels that contain particles and its properties and how it evolves in time. | Arena | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Arena:
"""class that implements the basic fiels that contain particles and its properties and how it evolves in time."""
def __init__(self, particles, boundary, g=9.8):
"""particles : instance of Particles class boundary : boundary of Arena"""
<|body_0|>
def proceed(self... | stack_v2_sparse_classes_75kplus_train_004231 | 7,012 | permissive | [
{
"docstring": "particles : instance of Particles class boundary : boundary of Arena",
"name": "__init__",
"signature": "def __init__(self, particles, boundary, g=9.8)"
},
{
"docstring": "Proceed the Arena from time t to t + dt seconds Change the state of the particles in the arena accouding to ... | 2 | stack_v2_sparse_classes_30k_train_005433 | Implement the Python class `Arena` described below.
Class description:
class that implements the basic fiels that contain particles and its properties and how it evolves in time.
Method signatures and docstrings:
- def __init__(self, particles, boundary, g=9.8): particles : instance of Particles class boundary : boun... | Implement the Python class `Arena` described below.
Class description:
class that implements the basic fiels that contain particles and its properties and how it evolves in time.
Method signatures and docstrings:
- def __init__(self, particles, boundary, g=9.8): particles : instance of Particles class boundary : boun... | 46818eb405c283c563231d1816eab1f60f39b898 | <|skeleton|>
class Arena:
"""class that implements the basic fiels that contain particles and its properties and how it evolves in time."""
def __init__(self, particles, boundary, g=9.8):
"""particles : instance of Particles class boundary : boundary of Arena"""
<|body_0|>
def proceed(self... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Arena:
"""class that implements the basic fiels that contain particles and its properties and how it evolves in time."""
def __init__(self, particles, boundary, g=9.8):
"""particles : instance of Particles class boundary : boundary of Arena"""
self.particles = particles
self.time ... | the_stack_v2_python_sparse | StatisticalMechanics/brownian_motion.py | phy6boy/pyphy6 | train | 0 |
dd811b1b26d95c3097d589c43773a4b0fbb54725 | [
"if letter.islower():\n if letter == 'z':\n letter = 'A'\n else:\n letter = chr(ord(letter) + 1).upper()\nelif letter == 'Z':\n letter = 'a'\nelse:\n letter = chr(ord(letter) + 1).lower()\nreturn letter",
"if letter.islower():\n if letter == 'a':\n letter = 'Z'\n else:\n ... | <|body_start_0|>
if letter.islower():
if letter == 'z':
letter = 'A'
else:
letter = chr(ord(letter) + 1).upper()
elif letter == 'Z':
letter = 'a'
else:
letter = chr(ord(letter) + 1).lower()
return letter
<|en... | Encrytion_decryption | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encrytion_decryption:
def letter_encryption(self, letter):
"""对字母的加密"""
<|body_0|>
def letter_decryption(self, letter):
"""对字母的解密方法"""
<|body_1|>
def digit_encryption(self, num):
"""对数字的加密方法"""
<|body_2|>
def digit_decryption(self, n... | stack_v2_sparse_classes_75kplus_train_004232 | 1,285 | no_license | [
{
"docstring": "对字母的加密",
"name": "letter_encryption",
"signature": "def letter_encryption(self, letter)"
},
{
"docstring": "对字母的解密方法",
"name": "letter_decryption",
"signature": "def letter_decryption(self, letter)"
},
{
"docstring": "对数字的加密方法",
"name": "digit_encryption",
... | 4 | stack_v2_sparse_classes_30k_train_053979 | Implement the Python class `Encrytion_decryption` described below.
Class description:
Implement the Encrytion_decryption class.
Method signatures and docstrings:
- def letter_encryption(self, letter): 对字母的加密
- def letter_decryption(self, letter): 对字母的解密方法
- def digit_encryption(self, num): 对数字的加密方法
- def digit_decryp... | Implement the Python class `Encrytion_decryption` described below.
Class description:
Implement the Encrytion_decryption class.
Method signatures and docstrings:
- def letter_encryption(self, letter): 对字母的加密
- def letter_decryption(self, letter): 对字母的解密方法
- def digit_encryption(self, num): 对数字的加密方法
- def digit_decryp... | 1d37ef796e2f01b29a8b9a3924b0db5dd8f312cc | <|skeleton|>
class Encrytion_decryption:
def letter_encryption(self, letter):
"""对字母的加密"""
<|body_0|>
def letter_decryption(self, letter):
"""对字母的解密方法"""
<|body_1|>
def digit_encryption(self, num):
"""对数字的加密方法"""
<|body_2|>
def digit_decryption(self, n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Encrytion_decryption:
def letter_encryption(self, letter):
"""对字母的加密"""
if letter.islower():
if letter == 'z':
letter = 'A'
else:
letter = chr(ord(letter) + 1).upper()
elif letter == 'Z':
letter = 'a'
else:
... | the_stack_v2_python_sparse | huaweiTest/encryption_decryption.py | moguoyi/httpApi | train | 0 | |
6fe53ab2e6d986e08e1d6215410aa090ba05c46b | [
"self.L = nestedList\nself.idx = 0\nself.iter = None",
"if self.hasNext():\n if self.L[self.idx].isInteger():\n self.idx += 1\n self.iter = None\n return self.L[self.idx - 1].getInteger()\n else:\n return self.iter.next()\nelse:\n return None",
"try:\n if self.L[self.idx]... | <|body_start_0|>
self.L = nestedList
self.idx = 0
self.iter = None
<|end_body_0|>
<|body_start_1|>
if self.hasNext():
if self.L[self.idx].isInteger():
self.idx += 1
self.iter = None
return self.L[self.idx - 1].getInteger()
... | NestedIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NestedIterator:
def __init__(self, nestedList):
"""Initialize your data structure here. :type nestedList: List[NestedInteger]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|e... | stack_v2_sparse_classes_75kplus_train_004233 | 3,014 | no_license | [
{
"docstring": "Initialize your data structure here. :type nestedList: List[NestedInteger]",
"name": "__init__",
"signature": "def __init__(self, nestedList)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"nam... | 3 | stack_v2_sparse_classes_30k_train_038371 | Implement the Python class `NestedIterator` described below.
Class description:
Implement the NestedIterator class.
Method signatures and docstrings:
- def __init__(self, nestedList): Initialize your data structure here. :type nestedList: List[NestedInteger]
- def next(self): :rtype: int
- def hasNext(self): :rtype: ... | Implement the Python class `NestedIterator` described below.
Class description:
Implement the NestedIterator class.
Method signatures and docstrings:
- def __init__(self, nestedList): Initialize your data structure here. :type nestedList: List[NestedInteger]
- def next(self): :rtype: int
- def hasNext(self): :rtype: ... | 85415872711c7c4b646f71ba44b5ef9200c03f5e | <|skeleton|>
class NestedIterator:
def __init__(self, nestedList):
"""Initialize your data structure here. :type nestedList: List[NestedInteger]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NestedIterator:
def __init__(self, nestedList):
"""Initialize your data structure here. :type nestedList: List[NestedInteger]"""
self.L = nestedList
self.idx = 0
self.iter = None
def next(self):
""":rtype: int"""
if self.hasNext():
if self.L[sel... | the_stack_v2_python_sparse | 341.py | ninini976/yf_leetcode_problems | train | 0 | |
092ec24d96a916b92a96ee0b82d40d4d169574e4 | [
"super(AdaIN, self).__init__()\nself.net_type = net_type\nself.norm_type = norm_type\nself.resize_type = resize_type\nif self.norm_type == 'batch':\n self.norm_layer = nn.BatchNorm2d(n_hin_channles, affine=False)\nelif self.norm_type == 'instance':\n self.norm_layer = nn.InstanceNorm2d(n_hin_channles, affine=... | <|body_start_0|>
super(AdaIN, self).__init__()
self.net_type = net_type
self.norm_type = norm_type
self.resize_type = resize_type
if self.norm_type == 'batch':
self.norm_layer = nn.BatchNorm2d(n_hin_channles, affine=False)
elif self.norm_type == 'instance':
... | AdaIN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdaIN:
def __init__(self, n_hin_channles, n_in_channles, net_type='conv', norm_type='batch', resize_type='nearest'):
"""[args] resize_type : ネットワーク外部から入力するデータ(セグメンテーション画像など)のサイズを、前段のネットワークからの活性化入力のサイズにリサイズして合わせるときのリサイズ手法 'nearest' | 'linear' | 'bilinear' | 'bicubic' | 'trilinear' | 'area... | stack_v2_sparse_classes_75kplus_train_004234 | 5,381 | no_license | [
{
"docstring": "[args] resize_type : ネットワーク外部から入力するデータ(セグメンテーション画像など)のサイズを、前段のネットワークからの活性化入力のサイズにリサイズして合わせるときのリサイズ手法 'nearest' | 'linear' | 'bilinear' | 'bicubic' | 'trilinear' | 'area'",
"name": "__init__",
"signature": "def __init__(self, n_hin_channles, n_in_channles, net_type='conv', norm_type='batc... | 2 | stack_v2_sparse_classes_30k_train_000762 | Implement the Python class `AdaIN` described below.
Class description:
Implement the AdaIN class.
Method signatures and docstrings:
- def __init__(self, n_hin_channles, n_in_channles, net_type='conv', norm_type='batch', resize_type='nearest'): [args] resize_type : ネットワーク外部から入力するデータ(セグメンテーション画像など)のサイズを、前段のネットワークからの活性化... | Implement the Python class `AdaIN` described below.
Class description:
Implement the AdaIN class.
Method signatures and docstrings:
- def __init__(self, n_hin_channles, n_in_channles, net_type='conv', norm_type='batch', resize_type='nearest'): [args] resize_type : ネットワーク外部から入力するデータ(セグメンテーション画像など)のサイズを、前段のネットワークからの活性化... | 97e1bd1eebc528d8c682a41031c750fa2066a713 | <|skeleton|>
class AdaIN:
def __init__(self, n_hin_channles, n_in_channles, net_type='conv', norm_type='batch', resize_type='nearest'):
"""[args] resize_type : ネットワーク外部から入力するデータ(セグメンテーション画像など)のサイズを、前段のネットワークからの活性化入力のサイズにリサイズして合わせるときのリサイズ手法 'nearest' | 'linear' | 'bilinear' | 'bicubic' | 'trilinear' | 'area... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AdaIN:
def __init__(self, n_hin_channles, n_in_channles, net_type='conv', norm_type='batch', resize_type='nearest'):
"""[args] resize_type : ネットワーク外部から入力するデータ(セグメンテーション画像など)のサイズを、前段のネットワークからの活性化入力のサイズにリサイズして合わせるときのリサイズ手法 'nearest' | 'linear' | 'bilinear' | 'bicubic' | 'trilinear' | 'area'"""
s... | the_stack_v2_python_sparse | _in_progress/GAN_Pix2PixStyleGAN/models/adain.py | Yagami360/MachineLearning_Exercises_Python_PyTorch | train | 18 | |
0a91946433d464744d81b68e3e92c9d8efe9102d | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AttributeMapping()",
"from .attribute_flow_behavior import AttributeFlowBehavior\nfrom .attribute_flow_type import AttributeFlowType\nfrom .attribute_mapping_source import AttributeMappingSource\nfrom .attribute_flow_behavior import At... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AttributeMapping()
<|end_body_0|>
<|body_start_1|>
from .attribute_flow_behavior import AttributeFlowBehavior
from .attribute_flow_type import AttributeFlowType
from .attribute_m... | AttributeMapping | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttributeMapping:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AttributeMapping:
"""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 R... | stack_v2_sparse_classes_75kplus_train_004235 | 5,238 | 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: AttributeMapping",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_va... | 3 | stack_v2_sparse_classes_30k_train_045131 | Implement the Python class `AttributeMapping` described below.
Class description:
Implement the AttributeMapping class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AttributeMapping: Creates a new instance of the appropriate class based on discrimina... | Implement the Python class `AttributeMapping` described below.
Class description:
Implement the AttributeMapping class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AttributeMapping: Creates a new instance of the appropriate class based on discrimina... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AttributeMapping:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AttributeMapping:
"""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 R... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AttributeMapping:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AttributeMapping:
"""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: Attrib... | the_stack_v2_python_sparse | msgraph/generated/models/attribute_mapping.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
00259784bf0e573bfb11ff3cc92768e8dd6ec020 | [
"assert isinstance(proxyCall, ProxyCall), 'Invalid proxy call %s' % proxyCall\nassert isinstance(handlers, deque), 'Invalid handlers queue %s' % handlers\nassert handlers, 'Invalid handlers %s, expected at least one handler' % handlers\nif isinstance(args, tuple):\n args = list(args)\nassert isinstance(args, lis... | <|body_start_0|>
assert isinstance(proxyCall, ProxyCall), 'Invalid proxy call %s' % proxyCall
assert isinstance(handlers, deque), 'Invalid handlers queue %s' % handlers
assert handlers, 'Invalid handlers %s, expected at least one handler' % handlers
if isinstance(args, tuple):
... | Provides the container for the execution of the proxied method. | Execution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Execution:
"""Provides the container for the execution of the proxied method."""
def __init__(self, proxyCall, handlers, args, keyargs):
"""Construct the execution chain. @param proxyCall: ProxyCall The proxy call of the execution. @param handlers: deque[IProxyHandler] The proxy hand... | stack_v2_sparse_classes_75kplus_train_004236 | 13,156 | no_license | [
{
"docstring": "Construct the execution chain. @param proxyCall: ProxyCall The proxy call of the execution. @param handlers: deque[IProxyHandler] The proxy handlers to use in the execution. @param args: list[object] The arguments used in the proxied method call. @param keyargs: dictionary{string, object} The ke... | 2 | null | Implement the Python class `Execution` described below.
Class description:
Provides the container for the execution of the proxied method.
Method signatures and docstrings:
- def __init__(self, proxyCall, handlers, args, keyargs): Construct the execution chain. @param proxyCall: ProxyCall The proxy call of the execut... | Implement the Python class `Execution` described below.
Class description:
Provides the container for the execution of the proxied method.
Method signatures and docstrings:
- def __init__(self, proxyCall, handlers, args, keyargs): Construct the execution chain. @param proxyCall: ProxyCall The proxy call of the execut... | a10cb774c8cbc5010950eed9342413846734fea7 | <|skeleton|>
class Execution:
"""Provides the container for the execution of the proxied method."""
def __init__(self, proxyCall, handlers, args, keyargs):
"""Construct the execution chain. @param proxyCall: ProxyCall The proxy call of the execution. @param handlers: deque[IProxyHandler] The proxy hand... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Execution:
"""Provides the container for the execution of the proxied method."""
def __init__(self, proxyCall, handlers, args, keyargs):
"""Construct the execution chain. @param proxyCall: ProxyCall The proxy call of the execution. @param handlers: deque[IProxyHandler] The proxy handlers to use i... | the_stack_v2_python_sparse | components/ally/ally/container/impl/proxy.py | bonomali/Ally-Py | train | 0 |
900f1ade5ca7d4173ffcd286665905fd7d2cf5f4 | [
"self.domid = domid\nself.mbid = domid\nself.atwd = [None, None, None, None]\nif buf is not None:\n self.decode(buf)",
"io = StringIO(buf)\ndecotup = struct.unpack('>2H6B6s', io.read(16))\nself.domclk = struct.unpack('>q', '\\x00\\x00' + decotup[8])[0]\nself.atwd_chip = decotup[2] & 1\nself.evt_trig_flag = dec... | <|body_start_0|>
self.domid = domid
self.mbid = domid
self.atwd = [None, None, None, None]
if buf is not None:
self.decode(buf)
<|end_body_0|>
<|body_start_1|>
io = StringIO(buf)
decotup = struct.unpack('>2H6B6s', io.read(16))
self.domclk = struct.unp... | DOM hit data structure - data members domhit.domid domhit.domclk domhit.atwd[i][j] - jth sample of atwd channel i (0..3) domhit.atwd_chip - 0 if atwd-a, 1 if atwd-b domhit.fadc[i] - ith FADC sample | domhit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class domhit:
"""DOM hit data structure - data members domhit.domid domhit.domclk domhit.atwd[i][j] - jth sample of atwd channel i (0..3) domhit.atwd_chip - 0 if atwd-a, 1 if atwd-b domhit.fadc[i] - ith FADC sample"""
def __init__(self, domid, buf=None):
"""Init the d/s - fill in fields /w... | stack_v2_sparse_classes_75kplus_train_004237 | 2,212 | no_license | [
{
"docstring": "Init the d/s - fill in fields /w/ blanks.",
"name": "__init__",
"signature": "def __init__(self, domid, buf=None)"
},
{
"docstring": "Decode the domhit data structure from engineering record.",
"name": "decode",
"signature": "def decode(self, buf)"
}
] | 2 | stack_v2_sparse_classes_30k_train_024624 | Implement the Python class `domhit` described below.
Class description:
DOM hit data structure - data members domhit.domid domhit.domclk domhit.atwd[i][j] - jth sample of atwd channel i (0..3) domhit.atwd_chip - 0 if atwd-a, 1 if atwd-b domhit.fadc[i] - ith FADC sample
Method signatures and docstrings:
- def __init__... | Implement the Python class `domhit` described below.
Class description:
DOM hit data structure - data members domhit.domid domhit.domclk domhit.atwd[i][j] - jth sample of atwd channel i (0..3) domhit.atwd_chip - 0 if atwd-a, 1 if atwd-b domhit.fadc[i] - ith FADC sample
Method signatures and docstrings:
- def __init__... | 13cb63ba2390bbd49facb2d9093da528ae52cd91 | <|skeleton|>
class domhit:
"""DOM hit data structure - data members domhit.domid domhit.domclk domhit.atwd[i][j] - jth sample of atwd channel i (0..3) domhit.atwd_chip - 0 if atwd-a, 1 if atwd-b domhit.fadc[i] - ith FADC sample"""
def __init__(self, domid, buf=None):
"""Init the d/s - fill in fields /w... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class domhit:
"""DOM hit data structure - data members domhit.domid domhit.domclk domhit.atwd[i][j] - jth sample of atwd channel i (0..3) domhit.atwd_chip - 0 if atwd-a, 1 if atwd-b domhit.fadc[i] - ith FADC sample"""
def __init__(self, domid, buf=None):
"""Init the d/s - fill in fields /w/ blanks."""
... | the_stack_v2_python_sparse | icecube/daq/hits.py | dglo/PyDOM | train | 0 |
5b76167ef5c170e06020ac3eefaafa4e2a4f12db | [
"if len(items) < 2:\n return items[:]\nmid = len(items) // 2\nleft = self.merge_sort(items[:mid], comp)\nright = self.merge_sort(items[mid:], comp)\nreturn self.merge(left, right, comp)",
"items = []\nindex1, index2 = (0, 0)\nwhile index1 < len(items1) and index2 < len(items2):\n if comp(items1[index1], ite... | <|body_start_0|>
if len(items) < 2:
return items[:]
mid = len(items) // 2
left = self.merge_sort(items[:mid], comp)
right = self.merge_sort(items[mid:], comp)
return self.merge(left, right, comp)
<|end_body_0|>
<|body_start_1|>
items = []
index1, inde... | MergeSort_2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MergeSort_2:
def merge_sort(self, items, comp=lambda x, y: x <= y):
"""归并排序(分治法)"""
<|body_0|>
def merge(self, items1, items2, comp):
"""合并(将两个有序的列表合并成一个有序的列表)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(items) < 2:
return ite... | stack_v2_sparse_classes_75kplus_train_004238 | 4,093 | no_license | [
{
"docstring": "归并排序(分治法)",
"name": "merge_sort",
"signature": "def merge_sort(self, items, comp=lambda x, y: x <= y)"
},
{
"docstring": "合并(将两个有序的列表合并成一个有序的列表)",
"name": "merge",
"signature": "def merge(self, items1, items2, comp)"
}
] | 2 | stack_v2_sparse_classes_30k_train_024013 | Implement the Python class `MergeSort_2` described below.
Class description:
Implement the MergeSort_2 class.
Method signatures and docstrings:
- def merge_sort(self, items, comp=lambda x, y: x <= y): 归并排序(分治法)
- def merge(self, items1, items2, comp): 合并(将两个有序的列表合并成一个有序的列表) | Implement the Python class `MergeSort_2` described below.
Class description:
Implement the MergeSort_2 class.
Method signatures and docstrings:
- def merge_sort(self, items, comp=lambda x, y: x <= y): 归并排序(分治法)
- def merge(self, items1, items2, comp): 合并(将两个有序的列表合并成一个有序的列表)
<|skeleton|>
class MergeSort_2:
def m... | a5ea407cec27e44d35f607c4a828bf893f503538 | <|skeleton|>
class MergeSort_2:
def merge_sort(self, items, comp=lambda x, y: x <= y):
"""归并排序(分治法)"""
<|body_0|>
def merge(self, items1, items2, comp):
"""合并(将两个有序的列表合并成一个有序的列表)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MergeSort_2:
def merge_sort(self, items, comp=lambda x, y: x <= y):
"""归并排序(分治法)"""
if len(items) < 2:
return items[:]
mid = len(items) // 2
left = self.merge_sort(items[:mid], comp)
right = self.merge_sort(items[mid:], comp)
return self.merge(left, ... | the_stack_v2_python_sparse | leetcode/Sort_method.py | YLyeliang/miscellaneous | train | 1 | |
162f5ee60161cd0028357fbb3134a4243be62758 | [
"game_loop = True\nstore = Store.get_instance()\nwhile game_loop:\n state = store.get_state()\n if state.reboot or state.next_state:\n if state.reboot:\n store.set_initial()\n elif state.next_state:\n store.set_next_state()\n elif state.quit:\n game_loop = False\n... | <|body_start_0|>
game_loop = True
store = Store.get_instance()
while game_loop:
state = store.get_state()
if state.reboot or state.next_state:
if state.reboot:
store.set_initial()
elif state.next_state:
... | this class deals with the smooth running of the states | GameManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GameManager:
"""this class deals with the smooth running of the states"""
def start():
"""this method start the game with the main loop"""
<|body_0|>
def collect_item(object_name):
"""recover the item that the character wants to pick up"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_004239 | 5,555 | no_license | [
{
"docstring": "this method start the game with the main loop",
"name": "start",
"signature": "def start()"
},
{
"docstring": "recover the item that the character wants to pick up",
"name": "collect_item",
"signature": "def collect_item(object_name)"
},
{
"docstring": "determines... | 3 | stack_v2_sparse_classes_30k_train_025667 | Implement the Python class `GameManager` described below.
Class description:
this class deals with the smooth running of the states
Method signatures and docstrings:
- def start(): this method start the game with the main loop
- def collect_item(object_name): recover the item that the character wants to pick up
- def... | Implement the Python class `GameManager` described below.
Class description:
this class deals with the smooth running of the states
Method signatures and docstrings:
- def start(): this method start the game with the main loop
- def collect_item(object_name): recover the item that the character wants to pick up
- def... | 475ed7dd9ecf972909c84b58d926745bc8687ba1 | <|skeleton|>
class GameManager:
"""this class deals with the smooth running of the states"""
def start():
"""this method start the game with the main loop"""
<|body_0|>
def collect_item(object_name):
"""recover the item that the character wants to pick up"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GameManager:
"""this class deals with the smooth running of the states"""
def start():
"""this method start the game with the main loop"""
game_loop = True
store = Store.get_instance()
while game_loop:
state = store.get_state()
if state.reboot or st... | the_stack_v2_python_sparse | managers.py | ivan-fr/oc_projet_3 | train | 0 |
6896717402fddf38a9dbd01d27d34f00bf909ec2 | [
"from sagas.nlu.inspectors import query_duckling\nresp = query_duckling(text, lang)\nprint(pretty_json(resp))\nif resp['result'] == 'success':\n print('-' * 25)\n print([d['dim'] for d in resp['data']])",
"from dateparser.search import search_dates\nfrom dateparser import parse\nsearch_r = search_dates(text... | <|body_start_0|>
from sagas.nlu.inspectors import query_duckling
resp = query_duckling(text, lang)
print(pretty_json(resp))
if resp['result'] == 'success':
print('-' * 25)
print([d['dim'] for d in resp['data']])
<|end_body_0|>
<|body_start_1|>
from datepa... | ExtractorCli | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExtractorCli:
def duckling(self, text, lang='en'):
"""$ python -m sagas.nlu.extractor_cli duckling 'tomorrow at eight' en $ python -m sagas.nlu.extractor_cli duckling "3 mins" en $ python -m sagas.nlu.extractor_cli duckling "last week" en $ python -m sagas.nlu.extractor_cli duckling "明天是... | stack_v2_sparse_classes_75kplus_train_004240 | 4,289 | permissive | [
{
"docstring": "$ python -m sagas.nlu.extractor_cli duckling 'tomorrow at eight' en $ python -m sagas.nlu.extractor_cli duckling \"3 mins\" en $ python -m sagas.nlu.extractor_cli duckling \"last week\" en $ python -m sagas.nlu.extractor_cli duckling \"明天是九月九日\" zh $ python -m sagas.nlu.extractor_cli duckling 'あ... | 4 | stack_v2_sparse_classes_30k_train_020610 | Implement the Python class `ExtractorCli` described below.
Class description:
Implement the ExtractorCli class.
Method signatures and docstrings:
- def duckling(self, text, lang='en'): $ python -m sagas.nlu.extractor_cli duckling 'tomorrow at eight' en $ python -m sagas.nlu.extractor_cli duckling "3 mins" en $ python... | Implement the Python class `ExtractorCli` described below.
Class description:
Implement the ExtractorCli class.
Method signatures and docstrings:
- def duckling(self, text, lang='en'): $ python -m sagas.nlu.extractor_cli duckling 'tomorrow at eight' en $ python -m sagas.nlu.extractor_cli duckling "3 mins" en $ python... | 9958d18ee5e75cf9794f546c904097dc1ff4f3a0 | <|skeleton|>
class ExtractorCli:
def duckling(self, text, lang='en'):
"""$ python -m sagas.nlu.extractor_cli duckling 'tomorrow at eight' en $ python -m sagas.nlu.extractor_cli duckling "3 mins" en $ python -m sagas.nlu.extractor_cli duckling "last week" en $ python -m sagas.nlu.extractor_cli duckling "明天是... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExtractorCli:
def duckling(self, text, lang='en'):
"""$ python -m sagas.nlu.extractor_cli duckling 'tomorrow at eight' en $ python -m sagas.nlu.extractor_cli duckling "3 mins" en $ python -m sagas.nlu.extractor_cli duckling "last week" en $ python -m sagas.nlu.extractor_cli duckling "明天是九月九日" zh $ pyt... | the_stack_v2_python_sparse | sagas/nlu/extractor_cli.py | samlet/stack | train | 3 | |
344ea88cc170fbaeab1a9ad74946e3e6d4c3036b | [
"if values.get('send_user_email'):\n record = super(Ticket, self).create(values)\n self.env['flspautoemails.bpmemails'].send_email(record, 'TKT0001')\nelse:\n record = super(Ticket, self).create(values)\nreturn record",
"view_id = self.env.ref('flspticketsystem.assign_from_view').id\nname = 'Assign respo... | <|body_start_0|>
if values.get('send_user_email'):
record = super(Ticket, self).create(values)
self.env['flspautoemails.bpmemails'].send_email(record, 'TKT0001')
else:
record = super(Ticket, self).create(values)
return record
<|end_body_0|>
<|body_start_1|>
... | Class_Name: Ticket Model_Name: flspticketsystem.ticket Purpose: To help in the creation of the tickets Date: sept/4th/friday/2020 Updated: Oct/6th/Tuesday/2020 Author: Sami Byaruhanga | Ticket | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ticket:
"""Class_Name: Ticket Model_Name: flspticketsystem.ticket Purpose: To help in the creation of the tickets Date: sept/4th/friday/2020 Updated: Oct/6th/Tuesday/2020 Author: Sami Byaruhanga"""
def create(self, values):
"""Purpose: Override create method, on creation an email is ... | stack_v2_sparse_classes_75kplus_train_004241 | 6,258 | no_license | [
{
"docstring": "Purpose: Override create method, on creation an email is sent to the user if boolean is true in admin but if not its not sent upon creation",
"name": "create",
"signature": "def create(self, values)"
},
{
"docstring": "Purpose: To call assign responsible wizard with context for t... | 5 | null | Implement the Python class `Ticket` described below.
Class description:
Class_Name: Ticket Model_Name: flspticketsystem.ticket Purpose: To help in the creation of the tickets Date: sept/4th/friday/2020 Updated: Oct/6th/Tuesday/2020 Author: Sami Byaruhanga
Method signatures and docstrings:
- def create(self, values): ... | Implement the Python class `Ticket` described below.
Class description:
Class_Name: Ticket Model_Name: flspticketsystem.ticket Purpose: To help in the creation of the tickets Date: sept/4th/friday/2020 Updated: Oct/6th/Tuesday/2020 Author: Sami Byaruhanga
Method signatures and docstrings:
- def create(self, values): ... | 4a82cd5cfd1898c6da860cb68dff3a14e037bbad | <|skeleton|>
class Ticket:
"""Class_Name: Ticket Model_Name: flspticketsystem.ticket Purpose: To help in the creation of the tickets Date: sept/4th/friday/2020 Updated: Oct/6th/Tuesday/2020 Author: Sami Byaruhanga"""
def create(self, values):
"""Purpose: Override create method, on creation an email is ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Ticket:
"""Class_Name: Ticket Model_Name: flspticketsystem.ticket Purpose: To help in the creation of the tickets Date: sept/4th/friday/2020 Updated: Oct/6th/Tuesday/2020 Author: Sami Byaruhanga"""
def create(self, values):
"""Purpose: Override create method, on creation an email is sent to the u... | the_stack_v2_python_sparse | flspticketsystem/models/ticket.py | odoo-smg/firstlight | train | 3 |
f468e6e2b9abec36c07460a047d90952da8789c3 | [
"with mute_signals(post_save):\n profile = ProfileFactory()\nassert profile.student_id is not None\nassert profile.student_id == profile.id",
"with mute_signals(post_save):\n profile_one = ProfileFactory()\n profile_two = ProfileFactory()\nassert profile_two.student_id > profile_one.student_id",
"with ... | <|body_start_0|>
with mute_signals(post_save):
profile = ProfileFactory()
assert profile.student_id is not None
assert profile.student_id == profile.id
<|end_body_0|>
<|body_start_1|>
with mute_signals(post_save):
profile_one = ProfileFactory()
profil... | tests for the profile model | ProfileTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileTests:
"""tests for the profile model"""
def test_student_id_on_save(self):
"""test that a student id is set on save"""
<|body_0|>
def test_student_id_increments(self):
"""test that a student id increments correctly"""
<|body_1|>
def test_stud... | stack_v2_sparse_classes_75kplus_train_004242 | 1,912 | no_license | [
{
"docstring": "test that a student id is set on save",
"name": "test_student_id_on_save",
"signature": "def test_student_id_on_save(self)"
},
{
"docstring": "test that a student id increments correctly",
"name": "test_student_id_increments",
"signature": "def test_student_id_increments(... | 5 | null | Implement the Python class `ProfileTests` described below.
Class description:
tests for the profile model
Method signatures and docstrings:
- def test_student_id_on_save(self): test that a student id is set on save
- def test_student_id_increments(self): test that a student id increments correctly
- def test_student_... | Implement the Python class `ProfileTests` described below.
Class description:
tests for the profile model
Method signatures and docstrings:
- def test_student_id_on_save(self): test that a student id is set on save
- def test_student_id_increments(self): test that a student id increments correctly
- def test_student_... | 3c166bc52dfe8d7aa04f922134f4f6deeff49eb6 | <|skeleton|>
class ProfileTests:
"""tests for the profile model"""
def test_student_id_on_save(self):
"""test that a student id is set on save"""
<|body_0|>
def test_student_id_increments(self):
"""test that a student id increments correctly"""
<|body_1|>
def test_stud... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProfileTests:
"""tests for the profile model"""
def test_student_id_on_save(self):
"""test that a student id is set on save"""
with mute_signals(post_save):
profile = ProfileFactory()
assert profile.student_id is not None
assert profile.student_id == profile.id... | the_stack_v2_python_sparse | profiles/models_test.py | avontd2868/micromasters | train | 0 |
5c1d653df2380e03c42735136d5d98ac4410a5c3 | [
"if operation == 'update' and self.request.authenticated_role != self.context.author:\n self.request.errors.add('url', 'role', 'Can update document only author')\n self.request.errors.status = 403\n raise error_handler(self.request)\nif self.request.validated['tender_status'] not in ['active.qualification'... | <|body_start_0|>
if operation == 'update' and self.request.authenticated_role != self.context.author:
self.request.errors.add('url', 'role', 'Can update document only author')
self.request.errors.status = 403
raise error_handler(self.request)
if self.request.validated... | TenderUaAwardComplaintDocumentResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TenderUaAwardComplaintDocumentResource:
def validate_complaint_document(self, operation):
"""TODO move validators This class is inherited in limited and openeu (qualification complaint) package, but validate_complaint_document function has different validators. For now, we have no way to... | stack_v2_sparse_classes_75kplus_train_004243 | 3,624 | permissive | [
{
"docstring": "TODO move validators This class is inherited in limited and openeu (qualification complaint) package, but validate_complaint_document function has different validators. For now, we have no way to use different validators on methods according to procedure type.",
"name": "validate_complaint_d... | 4 | stack_v2_sparse_classes_30k_train_041617 | Implement the Python class `TenderUaAwardComplaintDocumentResource` described below.
Class description:
Implement the TenderUaAwardComplaintDocumentResource class.
Method signatures and docstrings:
- def validate_complaint_document(self, operation): TODO move validators This class is inherited in limited and openeu (... | Implement the Python class `TenderUaAwardComplaintDocumentResource` described below.
Class description:
Implement the TenderUaAwardComplaintDocumentResource class.
Method signatures and docstrings:
- def validate_complaint_document(self, operation): TODO move validators This class is inherited in limited and openeu (... | f901e1d8913cb10fee044dc267ef7c0f42c6a947 | <|skeleton|>
class TenderUaAwardComplaintDocumentResource:
def validate_complaint_document(self, operation):
"""TODO move validators This class is inherited in limited and openeu (qualification complaint) package, but validate_complaint_document function has different validators. For now, we have no way to... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TenderUaAwardComplaintDocumentResource:
def validate_complaint_document(self, operation):
"""TODO move validators This class is inherited in limited and openeu (qualification complaint) package, but validate_complaint_document function has different validators. For now, we have no way to use different... | the_stack_v2_python_sparse | src/openprocurement/tender/openua/views/award_complaint_document.py | ProzorroUKR/openprocurement.api | train | 14 | |
db9fe8b81beb54a31cd720913b4e27eb1c01e8d4 | [
"node_type = request.query_params.get('type')\nif node_type == 'parent':\n needed = ['parent']\nelif node_type == 'children':\n needed = ['children']\nelse:\n needed = ['children', 'parent']\nparent_dict = {}\nchildren_list = []\nif 'parent' in needed:\n parent = models.Node.objects.filter(agent=request... | <|body_start_0|>
node_type = request.query_params.get('type')
if node_type == 'parent':
needed = ['parent']
elif node_type == 'children':
needed = ['children']
else:
needed = ['children', 'parent']
parent_dict = {}
children_list = []
... | 系统中心 | SystemNodeList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SystemNodeList:
"""系统中心"""
def get(self, request):
"""获取当前中心的上下级数据 :param request: :param type: 中心类型 :return:"""
<|body_0|>
def post(self, request):
"""添加 :param request: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
node_type = reque... | stack_v2_sparse_classes_75kplus_train_004244 | 29,724 | no_license | [
{
"docstring": "获取当前中心的上下级数据 :param request: :param type: 中心类型 :return:",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "添加 :param request: :return:",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014910 | Implement the Python class `SystemNodeList` described below.
Class description:
系统中心
Method signatures and docstrings:
- def get(self, request): 获取当前中心的上下级数据 :param request: :param type: 中心类型 :return:
- def post(self, request): 添加 :param request: :return: | Implement the Python class `SystemNodeList` described below.
Class description:
系统中心
Method signatures and docstrings:
- def get(self, request): 获取当前中心的上下级数据 :param request: :param type: 中心类型 :return:
- def post(self, request): 添加 :param request: :return:
<|skeleton|>
class SystemNodeList:
"""系统中心"""
def ge... | d6e025d7e9d9e3aecfd399c77f376130edd8a2df | <|skeleton|>
class SystemNodeList:
"""系统中心"""
def get(self, request):
"""获取当前中心的上下级数据 :param request: :param type: 中心类型 :return:"""
<|body_0|>
def post(self, request):
"""添加 :param request: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SystemNodeList:
"""系统中心"""
def get(self, request):
"""获取当前中心的上下级数据 :param request: :param type: 中心类型 :return:"""
node_type = request.query_params.get('type')
if node_type == 'parent':
needed = ['parent']
elif node_type == 'children':
needed = ['chil... | the_stack_v2_python_sparse | soc_system/views/node_views.py | sundw2015/841 | train | 4 |
9da8c1a84e763dcbec5560dfd9bb3f6830db2c81 | [
"if sys.argv == ['manage.py', 'runserver', '--noreload']:\n return True\nreturn False",
"if self._socket_server_should_start():\n socket_thread = SocketConnection()\n socket_thread.start()"
] | <|body_start_0|>
if sys.argv == ['manage.py', 'runserver', '--noreload']:
return True
return False
<|end_body_0|>
<|body_start_1|>
if self._socket_server_should_start():
socket_thread = SocketConnection()
socket_thread.start()
<|end_body_1|>
| ControlBoardConfig | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ControlBoardConfig:
def _socket_server_should_start():
"""Return whether the thread should start when server is launched."""
<|body_0|>
def ready(self):
"""Starts socket thread on launch."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if sys.argv =... | stack_v2_sparse_classes_75kplus_train_004245 | 677 | no_license | [
{
"docstring": "Return whether the thread should start when server is launched.",
"name": "_socket_server_should_start",
"signature": "def _socket_server_should_start()"
},
{
"docstring": "Starts socket thread on launch.",
"name": "ready",
"signature": "def ready(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007413 | Implement the Python class `ControlBoardConfig` described below.
Class description:
Implement the ControlBoardConfig class.
Method signatures and docstrings:
- def _socket_server_should_start(): Return whether the thread should start when server is launched.
- def ready(self): Starts socket thread on launch. | Implement the Python class `ControlBoardConfig` described below.
Class description:
Implement the ControlBoardConfig class.
Method signatures and docstrings:
- def _socket_server_should_start(): Return whether the thread should start when server is launched.
- def ready(self): Starts socket thread on launch.
<|skele... | 58d149b8fb461f9b1f8ed162bb7e80dbf333b71b | <|skeleton|>
class ControlBoardConfig:
def _socket_server_should_start():
"""Return whether the thread should start when server is launched."""
<|body_0|>
def ready(self):
"""Starts socket thread on launch."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ControlBoardConfig:
def _socket_server_should_start():
"""Return whether the thread should start when server is launched."""
if sys.argv == ['manage.py', 'runserver', '--noreload']:
return True
return False
def ready(self):
"""Starts socket thread on launch."""... | the_stack_v2_python_sparse | remote_robot_web/control_board/apps.py | AB036/remote_robot | train | 2 | |
2b895cf4392273b689ddafc6f26c5ab11f737a5a | [
"super(CustomSmoothL1Loss, self).__init__()\nself.beta = beta\nself.reduction = reduction\nself.loss_weight = loss_weight",
"reduction = reduction_override if reduction_override else self.reduction\nif target.numel() > 0:\n loss_bbox = self.loss_weight * smooth_l1_loss(pred, target, weight, beta=self.beta, red... | <|body_start_0|>
super(CustomSmoothL1Loss, self).__init__()
self.beta = beta
self.reduction = reduction
self.loss_weight = loss_weight
<|end_body_0|>
<|body_start_1|>
reduction = reduction_override if reduction_override else self.reduction
if target.numel() > 0:
... | Smooth L1 Loss. | CustomSmoothL1Loss | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomSmoothL1Loss:
"""Smooth L1 Loss."""
def __init__(self, beta=1.0, reduction='mean', loss_weight=1.0):
"""Init smooth l1 loss."""
<|body_0|>
def forward(self, pred, target, weight=None, avg_factor=None, reduction_override=None, **kwargs):
"""Forward compute. ... | stack_v2_sparse_classes_75kplus_train_004246 | 13,829 | permissive | [
{
"docstring": "Init smooth l1 loss.",
"name": "__init__",
"signature": "def __init__(self, beta=1.0, reduction='mean', loss_weight=1.0)"
},
{
"docstring": "Forward compute. :param pred: predict :param target: target :param weight: weight :param avg_factor: avg factor :param reduction_override: ... | 2 | stack_v2_sparse_classes_30k_train_017237 | Implement the Python class `CustomSmoothL1Loss` described below.
Class description:
Smooth L1 Loss.
Method signatures and docstrings:
- def __init__(self, beta=1.0, reduction='mean', loss_weight=1.0): Init smooth l1 loss.
- def forward(self, pred, target, weight=None, avg_factor=None, reduction_override=None, **kwarg... | Implement the Python class `CustomSmoothL1Loss` described below.
Class description:
Smooth L1 Loss.
Method signatures and docstrings:
- def __init__(self, beta=1.0, reduction='mean', loss_weight=1.0): Init smooth l1 loss.
- def forward(self, pred, target, weight=None, avg_factor=None, reduction_override=None, **kwarg... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class CustomSmoothL1Loss:
"""Smooth L1 Loss."""
def __init__(self, beta=1.0, reduction='mean', loss_weight=1.0):
"""Init smooth l1 loss."""
<|body_0|>
def forward(self, pred, target, weight=None, avg_factor=None, reduction_override=None, **kwargs):
"""Forward compute. ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomSmoothL1Loss:
"""Smooth L1 Loss."""
def __init__(self, beta=1.0, reduction='mean', loss_weight=1.0):
"""Init smooth l1 loss."""
super(CustomSmoothL1Loss, self).__init__()
self.beta = beta
self.reduction = reduction
self.loss_weight = loss_weight
def forw... | the_stack_v2_python_sparse | built-in/TensorFlow/Research/cv/image_classification/Darts_for_TensorFlow/automl/vega/search_space/networks/pytorch/operator/rpn.py | Huawei-Ascend/modelzoo | train | 1 |
09fee9b0000bb00c14c0c3747ea4e910cc2f87f1 | [
"pta = self.pt_alphabet\ncta = self.ct_alphabet\ntry:\n pt_key_symbol, ct_symbol = key.split('-')\n assert pt_key_symbol in pta\n assert ct_key_symbol in cta\n height, width = (int(h), int(w))\nexcept:\n raise ValueError(\"Illegal key of of '{}' for Monoalphabetic cipher\".format(key))\npt_key_positi... | <|body_start_0|>
pta = self.pt_alphabet
cta = self.ct_alphabet
try:
pt_key_symbol, ct_symbol = key.split('-')
assert pt_key_symbol in pta
assert ct_key_symbol in cta
height, width = (int(h), int(w))
except:
raise ValueError("Ill... | A simple monoalphabetic substitution cipher. Base class used for decoder badges. | Monoalphabetic_Cipher | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Monoalphabetic_Cipher:
"""A simple monoalphabetic substitution cipher. Base class used for decoder badges."""
def __init__(self, key):
"""This cipher is keyed by providing a string indicating the alignment between a symbol in the plaintext alphabet with a symbol in the cipher text al... | stack_v2_sparse_classes_75kplus_train_004247 | 14,483 | permissive | [
{
"docstring": "This cipher is keyed by providing a string indicating the alignment between a symbol in the plaintext alphabet with a symbol in the cipher text alphabet of the form 'C-G'. The cipher text alphabet is then shifted by this alignment.",
"name": "__init__",
"signature": "def __init__(self, k... | 3 | stack_v2_sparse_classes_30k_train_049574 | Implement the Python class `Monoalphabetic_Cipher` described below.
Class description:
A simple monoalphabetic substitution cipher. Base class used for decoder badges.
Method signatures and docstrings:
- def __init__(self, key): This cipher is keyed by providing a string indicating the alignment between a symbol in t... | Implement the Python class `Monoalphabetic_Cipher` described below.
Class description:
A simple monoalphabetic substitution cipher. Base class used for decoder badges.
Method signatures and docstrings:
- def __init__(self, key): This cipher is keyed by providing a string indicating the alignment between a symbol in t... | 33557ee2400790d2b1296a5913d587e6f5183533 | <|skeleton|>
class Monoalphabetic_Cipher:
"""A simple monoalphabetic substitution cipher. Base class used for decoder badges."""
def __init__(self, key):
"""This cipher is keyed by providing a string indicating the alignment between a symbol in the plaintext alphabet with a symbol in the cipher text al... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Monoalphabetic_Cipher:
"""A simple monoalphabetic substitution cipher. Base class used for decoder badges."""
def __init__(self, key):
"""This cipher is keyed by providing a string indicating the alignment between a symbol in the plaintext alphabet with a symbol in the cipher text alphabet of the... | the_stack_v2_python_sparse | code/cipher.py | CryptoUSF/Course-Material | train | 5 |
824b9af86e785f438d84ab5113c842200ff98820 | [
"super(G_MAPPING, self).__init__()\nself.num_layers = cfg.M.LAYERS\nself.c_dim = cfg.C_DIM\nself.z_dim = cfg.Z_DIM\nself.w_dim = cfg.W_DIM\nself.concat_dim = self.c_dim + self.z_dim\nself.normalize = cfg.M.USE_NORM\nif self.normalize:\n self.pixel_norm = Pixel_Norm()\nelse:\n self.pixel_norm = None\nself.mapp... | <|body_start_0|>
super(G_MAPPING, self).__init__()
self.num_layers = cfg.M.LAYERS
self.c_dim = cfg.C_DIM
self.z_dim = cfg.Z_DIM
self.w_dim = cfg.W_DIM
self.concat_dim = self.c_dim + self.z_dim
self.normalize = cfg.M.USE_NORM
if self.normalize:
... | G_MAPPING | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class G_MAPPING:
def __init__(self):
"""Mapping layers"""
<|body_0|>
def forward(self, c_code, z_code):
"""Inputs: c_code: [batch_size, cfg.C_DIM], text after augmentation z_code: [batch_size, cfg.W_DIM], noise(Z) generated from some distribution Outputs: w_code: [batch_si... | stack_v2_sparse_classes_75kplus_train_004248 | 20,736 | no_license | [
{
"docstring": "Mapping layers",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inputs: c_code: [batch_size, cfg.C_DIM], text after augmentation z_code: [batch_size, cfg.W_DIM], noise(Z) generated from some distribution Outputs: w_code: [batch_size, cfg.W_DIM], latent(W... | 2 | stack_v2_sparse_classes_30k_train_007868 | Implement the Python class `G_MAPPING` described below.
Class description:
Implement the G_MAPPING class.
Method signatures and docstrings:
- def __init__(self): Mapping layers
- def forward(self, c_code, z_code): Inputs: c_code: [batch_size, cfg.C_DIM], text after augmentation z_code: [batch_size, cfg.W_DIM], noise(... | Implement the Python class `G_MAPPING` described below.
Class description:
Implement the G_MAPPING class.
Method signatures and docstrings:
- def __init__(self): Mapping layers
- def forward(self, c_code, z_code): Inputs: c_code: [batch_size, cfg.C_DIM], text after augmentation z_code: [batch_size, cfg.W_DIM], noise(... | 581d0ced59b0b00900ad68cc927d9ba39cd58671 | <|skeleton|>
class G_MAPPING:
def __init__(self):
"""Mapping layers"""
<|body_0|>
def forward(self, c_code, z_code):
"""Inputs: c_code: [batch_size, cfg.C_DIM], text after augmentation z_code: [batch_size, cfg.W_DIM], noise(Z) generated from some distribution Outputs: w_code: [batch_si... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class G_MAPPING:
def __init__(self):
"""Mapping layers"""
super(G_MAPPING, self).__init__()
self.num_layers = cfg.M.LAYERS
self.c_dim = cfg.C_DIM
self.z_dim = cfg.Z_DIM
self.w_dim = cfg.W_DIM
self.concat_dim = self.c_dim + self.z_dim
self.normalize = c... | the_stack_v2_python_sparse | Old_Code/code/model.py | Trccc/SBA-GAN | train | 2 | |
0c146d5a26cc0cb941453e2d4ed1b86257ced4d2 | [
"R_0 = pyEpiabm.core.Parameters.instance().basic_reproduction_num\ninfect_profile = pyEpiabm.core.Parameters.instance().infectiousness_prof\ntotal_infectiousness = np.sum(infect_profile)\nsummed_infectiousness = sum([person.infectiousness for person in inf_cell.persons])\naverage_number_to_infect = R_0 * (summed_in... | <|body_start_0|>
R_0 = pyEpiabm.core.Parameters.instance().basic_reproduction_num
infect_profile = pyEpiabm.core.Parameters.instance().infectiousness_prof
total_infectiousness = np.sum(infect_profile)
summed_infectiousness = sum([person.infectiousness for person in inf_cell.persons])
... | Class to calculate the infectiousness and susceptibility parameters for the force of infection parameter, between cells. | SpatialInfection | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpatialInfection:
"""Class to calculate the infectiousness and susceptibility parameters for the force of infection parameter, between cells."""
def cell_inf(inf_cell, time: float):
"""Calculate the infectiousness of one cell towards its nearby cells. Does not include interventions s... | stack_v2_sparse_classes_75kplus_train_004249 | 7,809 | permissive | [
{
"docstring": "Calculate the infectiousness of one cell towards its nearby cells. Does not include interventions such as isolation, or whether individual is a carehome resident. Returns the expected number of infections for a given timestep. Parameters ---------- inf_cell : Cell Cell causing the infection time... | 4 | stack_v2_sparse_classes_30k_train_047627 | Implement the Python class `SpatialInfection` described below.
Class description:
Class to calculate the infectiousness and susceptibility parameters for the force of infection parameter, between cells.
Method signatures and docstrings:
- def cell_inf(inf_cell, time: float): Calculate the infectiousness of one cell t... | Implement the Python class `SpatialInfection` described below.
Class description:
Class to calculate the infectiousness and susceptibility parameters for the force of infection parameter, between cells.
Method signatures and docstrings:
- def cell_inf(inf_cell, time: float): Calculate the infectiousness of one cell t... | c11de122c6bfdf9103162e4045758808da5df322 | <|skeleton|>
class SpatialInfection:
"""Class to calculate the infectiousness and susceptibility parameters for the force of infection parameter, between cells."""
def cell_inf(inf_cell, time: float):
"""Calculate the infectiousness of one cell towards its nearby cells. Does not include interventions s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpatialInfection:
"""Class to calculate the infectiousness and susceptibility parameters for the force of infection parameter, between cells."""
def cell_inf(inf_cell, time: float):
"""Calculate the infectiousness of one cell towards its nearby cells. Does not include interventions such as isolat... | the_stack_v2_python_sparse | pyEpiabm/pyEpiabm/property/spatial_foi.py | SABS-R3-Epidemiology/epiabm | train | 21 |
51c540312df3685e1af04074a8b27b90d1b82440 | [
"Form.setObjectName('Form')\nForm.resize(491, 280)\nqr = Form.frameGeometry()\ncp = QDesktopWidget().availableGeometry().center()\nqr.moveCenter(cp)\nForm.move(qr.topLeft())\nForm.setAutoFillBackground(True)\np = Form.palette()\np.setColor(Form.backgroundRole(), Qt.white)\nForm.setPalette(p)\nForm.setWindowFlags(Qt... | <|body_start_0|>
Form.setObjectName('Form')
Form.resize(491, 280)
qr = Form.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
Form.move(qr.topLeft())
Form.setAutoFillBackground(True)
p = Form.palette()
p.setColor(... | Ui_Form | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ui_Form:
def setupUi(self, Form):
"""Setup for Connection Screen 491x280 px Frameless window with Label on it The LAble shows GIF on successful connection to Socket Server conn() function is called to check connection"""
<|body_0|>
def conn(self):
"""Establishing ini... | stack_v2_sparse_classes_75kplus_train_004250 | 3,830 | no_license | [
{
"docstring": "Setup for Connection Screen 491x280 px Frameless window with Label on it The LAble shows GIF on successful connection to Socket Server conn() function is called to check connection",
"name": "setupUi",
"signature": "def setupUi(self, Form)"
},
{
"docstring": "Establishing initial... | 4 | stack_v2_sparse_classes_30k_train_047513 | Implement the Python class `Ui_Form` described below.
Class description:
Implement the Ui_Form class.
Method signatures and docstrings:
- def setupUi(self, Form): Setup for Connection Screen 491x280 px Frameless window with Label on it The LAble shows GIF on successful connection to Socket Server conn() function is c... | Implement the Python class `Ui_Form` described below.
Class description:
Implement the Ui_Form class.
Method signatures and docstrings:
- def setupUi(self, Form): Setup for Connection Screen 491x280 px Frameless window with Label on it The LAble shows GIF on successful connection to Socket Server conn() function is c... | 5860edaf8e4a3bf8ae1c0593c5e65779a6643a71 | <|skeleton|>
class Ui_Form:
def setupUi(self, Form):
"""Setup for Connection Screen 491x280 px Frameless window with Label on it The LAble shows GIF on successful connection to Socket Server conn() function is called to check connection"""
<|body_0|>
def conn(self):
"""Establishing ini... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Ui_Form:
def setupUi(self, Form):
"""Setup for Connection Screen 491x280 px Frameless window with Label on it The LAble shows GIF on successful connection to Socket Server conn() function is called to check connection"""
Form.setObjectName('Form')
Form.resize(491, 280)
qr = For... | the_stack_v2_python_sparse | FinalGui/botgui.py | Prabhanshu76/Open-Pit-Mine-Autonomous-Bot | train | 0 | |
36734cf3c512acf2f182a9646fa3739df805df66 | [
"super().__init__(mt_constant)\nself.mt_namespace = get_namespace(mt_constant, command=True)\nself.mt_endpoint = get_command(mt_constant)\nself.channel = get_channel_from_connection(self.connection)\nself.publish_schema_types = get_schema_types_from_file(mt_constant['command_json_file'])\nself.event_consumer = self... | <|body_start_0|>
super().__init__(mt_constant)
self.mt_namespace = get_namespace(mt_constant, command=True)
self.mt_endpoint = get_command(mt_constant)
self.channel = get_channel_from_connection(self.connection)
self.publish_schema_types = get_schema_types_from_file(mt_constant['... | Class for simplifying publish message from Python to MassTransit (MT) and consuming for events messages | MTPublisher | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MTPublisher:
"""Class for simplifying publish message from Python to MassTransit (MT) and consuming for events messages"""
def __init__(self, mt_constant):
"""Method for define all needed for publishing variables. :param mt_constant: dict with emulation of MT interfaces"""
<|... | stack_v2_sparse_classes_75kplus_train_004251 | 14,450 | permissive | [
{
"docstring": "Method for define all needed for publishing variables. :param mt_constant: dict with emulation of MT interfaces",
"name": "__init__",
"signature": "def __init__(self, mt_constant)"
},
{
"docstring": "Method for publish message to MT listener exchange. Declare needed exchange, the... | 2 | stack_v2_sparse_classes_30k_train_049861 | Implement the Python class `MTPublisher` described below.
Class description:
Class for simplifying publish message from Python to MassTransit (MT) and consuming for events messages
Method signatures and docstrings:
- def __init__(self, mt_constant): Method for define all needed for publishing variables. :param mt_con... | Implement the Python class `MTPublisher` described below.
Class description:
Class for simplifying publish message from Python to MassTransit (MT) and consuming for events messages
Method signatures and docstrings:
- def __init__(self, mt_constant): Method for define all needed for publishing variables. :param mt_con... | 0c9beacc4a98c3f55ed56969a8b7eb84c4209c21 | <|skeleton|>
class MTPublisher:
"""Class for simplifying publish message from Python to MassTransit (MT) and consuming for events messages"""
def __init__(self, mt_constant):
"""Method for define all needed for publishing variables. :param mt_constant: dict with emulation of MT interfaces"""
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MTPublisher:
"""Class for simplifying publish message from Python to MassTransit (MT) and consuming for events messages"""
def __init__(self, mt_constant):
"""Method for define all needed for publishing variables. :param mt_constant: dict with emulation of MT interfaces"""
super().__init_... | the_stack_v2_python_sparse | Source/sds_tools/mass_transit/MTMessageProcessor.py | ArqiSoft/ml-services | train | 0 |
eebff158880d87447d878ba85ef43c059fd947b0 | [
"y_pred_placeholder = keras.KerasPlaceholder(lambda y_true, y_pred: y_pred)\ny_true_placeholder = keras.KerasPlaceholder(lambda y_true, y_pred: y_true)\ny_pred_placeholder.assign(-2.0, -1.0)\ny_true_placeholder.assign(1.0, 2.0)\nself.assertEqual(-1.0, y_pred_placeholder())\nself.assertEqual(1.0, y_true_placeholder(... | <|body_start_0|>
y_pred_placeholder = keras.KerasPlaceholder(lambda y_true, y_pred: y_pred)
y_true_placeholder = keras.KerasPlaceholder(lambda y_true, y_pred: y_true)
y_pred_placeholder.assign(-2.0, -1.0)
y_true_placeholder.assign(1.0, 2.0)
self.assertEqual(-1.0, y_pred_placehold... | Tests for classes in keras.py. | KerasTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KerasTest:
"""Tests for classes in keras.py."""
def test_keras_placeholder(self):
"""Tests the `KerasPlaceholder` class."""
<|body_0|>
def test_keras_layer(self):
"""Tests the `KerasLayer` class."""
<|body_1|>
def test_keras_wrapped_metric(self):
... | stack_v2_sparse_classes_75kplus_train_004252 | 6,701 | permissive | [
{
"docstring": "Tests the `KerasPlaceholder` class.",
"name": "test_keras_placeholder",
"signature": "def test_keras_placeholder(self)"
},
{
"docstring": "Tests the `KerasLayer` class.",
"name": "test_keras_layer",
"signature": "def test_keras_layer(self)"
},
{
"docstring": "Test... | 3 | null | Implement the Python class `KerasTest` described below.
Class description:
Tests for classes in keras.py.
Method signatures and docstrings:
- def test_keras_placeholder(self): Tests the `KerasPlaceholder` class.
- def test_keras_layer(self): Tests the `KerasLayer` class.
- def test_keras_wrapped_metric(self): Tests t... | Implement the Python class `KerasTest` described below.
Class description:
Tests for classes in keras.py.
Method signatures and docstrings:
- def test_keras_placeholder(self): Tests the `KerasPlaceholder` class.
- def test_keras_layer(self): Tests the `KerasLayer` class.
- def test_keras_wrapped_metric(self): Tests t... | 723d63f8567aaa988c4ce4761152beee2b462e1d | <|skeleton|>
class KerasTest:
"""Tests for classes in keras.py."""
def test_keras_placeholder(self):
"""Tests the `KerasPlaceholder` class."""
<|body_0|>
def test_keras_layer(self):
"""Tests the `KerasLayer` class."""
<|body_1|>
def test_keras_wrapped_metric(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KerasTest:
"""Tests for classes in keras.py."""
def test_keras_placeholder(self):
"""Tests the `KerasPlaceholder` class."""
y_pred_placeholder = keras.KerasPlaceholder(lambda y_true, y_pred: y_pred)
y_true_placeholder = keras.KerasPlaceholder(lambda y_true, y_pred: y_true)
... | the_stack_v2_python_sparse | tensorflow_constrained_optimization/python/rates/keras_test.py | thomasbhard/tensorflow_constrained_optimization | train | 0 |
6deccbe5fe0ff30cf3551dd40a27ed470687f296 | [
"in_board = board.HiTechBoard(in_board)\nin_box = box.Box(in_box)\nboxpiecenum = len(in_box.piecelist)\nbox_index = None\nwhile box_index is None:\n in_str = [int(i) for i in input('choice >>').split()]\n if not (0 <= in_str[0] and in_str[0] < boxpiecenum):\n continue\n box_index = in_str[0]\nres_ca... | <|body_start_0|>
in_board = board.HiTechBoard(in_board)
in_box = box.Box(in_box)
boxpiecenum = len(in_box.piecelist)
box_index = None
while box_index is None:
in_str = [int(i) for i in input('choice >>').split()]
if not (0 <= in_str[0] and in_str[0] < boxp... | ManualAiクラス 手入力をサポートする | ManualAi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ManualAi:
"""ManualAiクラス 手入力をサポートする"""
def choice(self, in_board, in_box):
"""in_boxリストにある最初の1つを返す"""
<|body_0|>
def put(self, in_board, in_piece):
"""in_boardからまだピースが置かれていない座標を返す"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
in_board = board.... | stack_v2_sparse_classes_75kplus_train_004253 | 2,640 | no_license | [
{
"docstring": "in_boxリストにある最初の1つを返す",
"name": "choice",
"signature": "def choice(self, in_board, in_box)"
},
{
"docstring": "in_boardからまだピースが置かれていない座標を返す",
"name": "put",
"signature": "def put(self, in_board, in_piece)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009727 | Implement the Python class `ManualAi` described below.
Class description:
ManualAiクラス 手入力をサポートする
Method signatures and docstrings:
- def choice(self, in_board, in_box): in_boxリストにある最初の1つを返す
- def put(self, in_board, in_piece): in_boardからまだピースが置かれていない座標を返す | Implement the Python class `ManualAi` described below.
Class description:
ManualAiクラス 手入力をサポートする
Method signatures and docstrings:
- def choice(self, in_board, in_box): in_boxリストにある最初の1つを返す
- def put(self, in_board, in_piece): in_boardからまだピースが置かれていない座標を返す
<|skeleton|>
class ManualAi:
"""ManualAiクラス 手入力をサポートする"""... | a833c5ed30972131d257a9a716f35a8dc961012d | <|skeleton|>
class ManualAi:
"""ManualAiクラス 手入力をサポートする"""
def choice(self, in_board, in_box):
"""in_boxリストにある最初の1つを返す"""
<|body_0|>
def put(self, in_board, in_piece):
"""in_boardからまだピースが置かれていない座標を返す"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ManualAi:
"""ManualAiクラス 手入力をサポートする"""
def choice(self, in_board, in_box):
"""in_boxリストにある最初の1つを返す"""
in_board = board.HiTechBoard(in_board)
in_box = box.Box(in_box)
boxpiecenum = len(in_box.piecelist)
box_index = None
while box_index is None:
i... | the_stack_v2_python_sparse | python/quarto/gamesys/gameplayer.py | keisukekimura-sv/Ktuarto | train | 0 |
165c40b542bf6703c0aaea8b83ea06f2920ddb81 | [
"self.best = GA.best\nself.elite = GA.elite\nself.noise_prob = GA.noise_prob\nsuper(GeneticAlgorithm, self).__init__()",
"agents = population.agents_weights[generation]\nrewards = population.scores[generation]\nscaled_rewards = np.interp(rewards, (rewards.min(), rewards.max()), (0, 1))\nordered_indexes = np.argso... | <|body_start_0|>
self.best = GA.best
self.elite = GA.elite
self.noise_prob = GA.noise_prob
super(GeneticAlgorithm, self).__init__()
<|end_body_0|>
<|body_start_1|>
agents = population.agents_weights[generation]
rewards = population.scores[generation]
scaled_rewar... | GeneticAlgorithm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeneticAlgorithm:
def __init__(self):
""":param best: number of best agents to be picked from previous generation as parents for the next one :type best: int :param elite: number of best agents to keep in the next generation from the previous one :type elite: int :param noise_prob: proba... | stack_v2_sparse_classes_75kplus_train_004254 | 2,496 | no_license | [
{
"docstring": ":param best: number of best agents to be picked from previous generation as parents for the next one :type best: int :param elite: number of best agents to keep in the next generation from the previous one :type elite: int :param noise_prob: probability of sample uniform noise in range [0,0.1] f... | 2 | stack_v2_sparse_classes_30k_train_012641 | Implement the Python class `GeneticAlgorithm` described below.
Class description:
Implement the GeneticAlgorithm class.
Method signatures and docstrings:
- def __init__(self): :param best: number of best agents to be picked from previous generation as parents for the next one :type best: int :param elite: number of b... | Implement the Python class `GeneticAlgorithm` described below.
Class description:
Implement the GeneticAlgorithm class.
Method signatures and docstrings:
- def __init__(self): :param best: number of best agents to be picked from previous generation as parents for the next one :type best: int :param elite: number of b... | 691707f418192e02896fb73088c9f5df95ab1068 | <|skeleton|>
class GeneticAlgorithm:
def __init__(self):
""":param best: number of best agents to be picked from previous generation as parents for the next one :type best: int :param elite: number of best agents to keep in the next generation from the previous one :type elite: int :param noise_prob: proba... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GeneticAlgorithm:
def __init__(self):
""":param best: number of best agents to be picked from previous generation as parents for the next one :type best: int :param elite: number of best agents to keep in the next generation from the previous one :type elite: int :param noise_prob: probability of samp... | the_stack_v2_python_sparse | src/GA/genetic_algorithm.py | mfouda/drl-optimization | train | 0 | |
a6fcdc81e14c9b1e6070988ffd9a23cbb1a0a0ec | [
"h, w = (len(matrix), len(matrix[0]))\nrows, cols = (set(), set())\nfor i in range(h):\n for j in range(w):\n if matrix[i][j] == 0:\n rows.add(i)\n cols.add(j)\nfor i in range(h):\n for j in range(w):\n if i in rows or j in cols:\n matrix[i][j] = 0",
"h, w = (l... | <|body_start_0|>
h, w = (len(matrix), len(matrix[0]))
rows, cols = (set(), set())
for i in range(h):
for j in range(w):
if matrix[i][j] == 0:
rows.add(i)
cols.add(j)
for i in range(h):
for j in range(w):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def setZeroes(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def setZeroes_v0(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify mat... | stack_v2_sparse_classes_75kplus_train_004255 | 2,395 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.",
"name": "setZeroes",
"signature": "def setZeroes(self, matrix)"
},
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instea... | 2 | stack_v2_sparse_classes_30k_train_020496 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def setZeroes_v0(self, matrix): :type matrix: Li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def setZeroes_v0(self, matrix): :type matrix: Li... | b5e09f24e8e96454dc99e20281e853fb9fcc85ed | <|skeleton|>
class Solution:
def setZeroes(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def setZeroes_v0(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify mat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def setZeroes(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
h, w = (len(matrix), len(matrix[0]))
rows, cols = (set(), set())
for i in range(h):
for j in range(w):
if ... | the_stack_v2_python_sparse | python/73_Set_Matrix_Zeroes.py | Moby5/myleetcode | train | 2 | |
bb0a0edc82b3387f1d7c7aac57e8e127f676dc9e | [
"global tensorflow\nimport tensorflow\ntensorflow.random.set_seed(base.random_state_.random())\nself.model_class = tensorflow.keras.Model\nself.optim_class = tensorflow.keras.optimizers.Optimizer\nsuper(TensorflowEngine, self).__init__(base, X, Y, A)",
"Y_pred = self.predictor_model(X, training=False)\nY_pred = Y... | <|body_start_0|>
global tensorflow
import tensorflow
tensorflow.random.set_seed(base.random_state_.random())
self.model_class = tensorflow.keras.Model
self.optim_class = tensorflow.keras.optimizers.Optimizer
super(TensorflowEngine, self).__init__(base, X, Y, A)
<|end_body... | Adds TensorFlow specific functions. | TensorflowEngine | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TensorflowEngine:
"""Adds TensorFlow specific functions."""
def __init__(self, base, X, Y, A):
"""Initialize the (Tensorflow specific parts) of the backend engine. There are not really tensorflow specifics besides the import, but don't forget to set up the optimizers after the init!"... | stack_v2_sparse_classes_75kplus_train_004256 | 6,175 | permissive | [
{
"docstring": "Initialize the (Tensorflow specific parts) of the backend engine. There are not really tensorflow specifics besides the import, but don't forget to set up the optimizers after the init!",
"name": "__init__",
"signature": "def __init__(self, base, X, Y, A)"
},
{
"docstring": "Eval... | 6 | stack_v2_sparse_classes_30k_train_037575 | Implement the Python class `TensorflowEngine` described below.
Class description:
Adds TensorFlow specific functions.
Method signatures and docstrings:
- def __init__(self, base, X, Y, A): Initialize the (Tensorflow specific parts) of the backend engine. There are not really tensorflow specifics besides the import, b... | Implement the Python class `TensorflowEngine` described below.
Class description:
Adds TensorFlow specific functions.
Method signatures and docstrings:
- def __init__(self, base, X, Y, A): Initialize the (Tensorflow specific parts) of the backend engine. There are not really tensorflow specifics besides the import, b... | bc75fc8ad1a98125c73bdc24a4d934b2f930c249 | <|skeleton|>
class TensorflowEngine:
"""Adds TensorFlow specific functions."""
def __init__(self, base, X, Y, A):
"""Initialize the (Tensorflow specific parts) of the backend engine. There are not really tensorflow specifics besides the import, but don't forget to set up the optimizers after the init!"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TensorflowEngine:
"""Adds TensorFlow specific functions."""
def __init__(self, base, X, Y, A):
"""Initialize the (Tensorflow specific parts) of the backend engine. There are not really tensorflow specifics besides the import, but don't forget to set up the optimizers after the init!"""
gl... | the_stack_v2_python_sparse | fairlearn/adversarial/_tensorflow_engine.py | fairlearn/fairlearn | train | 1,551 |
324c32dbd0feaf6df90e4eea5a3b994a3912f845 | [
"root_div = html_tags.div(cls='content-block', style='margin-bottom:40px;')\n\ndef get_th(heading_name):\n return html_tags.th(heading_name, cls='text-muted')\nwith root_div:\n html_tags.legend('Geometry Information')\n with html_tags.table(cls='custom-table'):\n with html_tags.tbody():\n ... | <|body_start_0|>
root_div = html_tags.div(cls='content-block', style='margin-bottom:40px;')
def get_th(heading_name):
return html_tags.th(heading_name, cls='text-muted')
with root_div:
html_tags.legend('Geometry Information')
with html_tags.table(cls='custom-... | GeometryInformation | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeometryInformation:
def get_html(self, pretty=True):
"""Generates html code for displaying data for this metadata element"""
<|body_0|>
def get_html_form(cls, resource, element=None, allow_edit=True, file_type=False):
"""Generates html form code for an instance of t... | stack_v2_sparse_classes_75kplus_train_004257 | 48,694 | permissive | [
{
"docstring": "Generates html code for displaying data for this metadata element",
"name": "get_html",
"signature": "def get_html(self, pretty=True)"
},
{
"docstring": "Generates html form code for an instance of this metadata element so that this element can be edited",
"name": "get_html_f... | 2 | stack_v2_sparse_classes_30k_train_048407 | Implement the Python class `GeometryInformation` described below.
Class description:
Implement the GeometryInformation class.
Method signatures and docstrings:
- def get_html(self, pretty=True): Generates html code for displaying data for this metadata element
- def get_html_form(cls, resource, element=None, allow_ed... | Implement the Python class `GeometryInformation` described below.
Class description:
Implement the GeometryInformation class.
Method signatures and docstrings:
- def get_html(self, pretty=True): Generates html code for displaying data for this metadata element
- def get_html_form(cls, resource, element=None, allow_ed... | 69855813052243c702c9b0108d2eac3f4f1a768f | <|skeleton|>
class GeometryInformation:
def get_html(self, pretty=True):
"""Generates html code for displaying data for this metadata element"""
<|body_0|>
def get_html_form(cls, resource, element=None, allow_edit=True, file_type=False):
"""Generates html form code for an instance of t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GeometryInformation:
def get_html(self, pretty=True):
"""Generates html code for displaying data for this metadata element"""
root_div = html_tags.div(cls='content-block', style='margin-bottom:40px;')
def get_th(heading_name):
return html_tags.th(heading_name, cls='text-mu... | the_stack_v2_python_sparse | hs_file_types/models/geofeature.py | hydroshare/hydroshare | train | 207 | |
730cceb8463c917a34f8f3e22f5d4cf39a0666ea | [
"super(Snat, self).__init__(snat_s)\nself._meta_data['required_json_kind'] = 'tm:ltm:snat:snatstate'\nself._meta_data['required_creation_parameters'].update(('partition', 'origins'))",
"required_one_of = ['automap', 'snatpool', 'translation']\nhas_any = [x for x in iterkeys(kwargs) if x in required_one_of]\nif le... | <|body_start_0|>
super(Snat, self).__init__(snat_s)
self._meta_data['required_json_kind'] = 'tm:ltm:snat:snatstate'
self._meta_data['required_creation_parameters'].update(('partition', 'origins'))
<|end_body_0|>
<|body_start_1|>
required_one_of = ['automap', 'snatpool', 'translation']
... | BIG-IP® LTM Snat resource | Snat | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Snat:
"""BIG-IP® LTM Snat resource"""
def __init__(self, snat_s):
"""This represents a Snat. "origins" is our first example of a dict attribute, it appears to behave as expected."""
<|body_0|>
def create(self, **kwargs):
"""Call this to create a new snat on the B... | stack_v2_sparse_classes_75kplus_train_004258 | 3,520 | permissive | [
{
"docstring": "This represents a Snat. \"origins\" is our first example of a dict attribute, it appears to behave as expected.",
"name": "__init__",
"signature": "def __init__(self, snat_s)"
},
{
"docstring": "Call this to create a new snat on the BIG-IP®. Uses HTTP POST to 'containing' URI to ... | 2 | stack_v2_sparse_classes_30k_train_028395 | Implement the Python class `Snat` described below.
Class description:
BIG-IP® LTM Snat resource
Method signatures and docstrings:
- def __init__(self, snat_s): This represents a Snat. "origins" is our first example of a dict attribute, it appears to behave as expected.
- def create(self, **kwargs): Call this to creat... | Implement the Python class `Snat` described below.
Class description:
BIG-IP® LTM Snat resource
Method signatures and docstrings:
- def __init__(self, snat_s): This represents a Snat. "origins" is our first example of a dict attribute, it appears to behave as expected.
- def create(self, **kwargs): Call this to creat... | 3050df0079c2426af99b9a1b8f93d0b512468ff4 | <|skeleton|>
class Snat:
"""BIG-IP® LTM Snat resource"""
def __init__(self, snat_s):
"""This represents a Snat. "origins" is our first example of a dict attribute, it appears to behave as expected."""
<|body_0|>
def create(self, **kwargs):
"""Call this to create a new snat on the B... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Snat:
"""BIG-IP® LTM Snat resource"""
def __init__(self, snat_s):
"""This represents a Snat. "origins" is our first example of a dict attribute, it appears to behave as expected."""
super(Snat, self).__init__(snat_s)
self._meta_data['required_json_kind'] = 'tm:ltm:snat:snatstate'
... | the_stack_v2_python_sparse | f5/bigip/tm/ltm/snat.py | F5Networks/f5-common-python | train | 286 |
156d0ef95d585b74975a6d0822c3636faf6e7a03 | [
"super().__init__()\nself.conv_name = conv_name\nif conv_name in self.conv_dict:\n self.conv_layer = self.conv_dict[conv_name]\nelse:\n raise KeyError(f'Unknown model name \"{conv_name}\".Available models are: {str(self.conv_dict.keys())}')\nself.conv_layers = torch.nn.ModuleList()\ndefault_conv_hparams = sel... | <|body_start_0|>
super().__init__()
self.conv_name = conv_name
if conv_name in self.conv_dict:
self.conv_layer = self.conv_dict[conv_name]
else:
raise KeyError(f'Unknown model name "{conv_name}".Available models are: {str(self.conv_dict.keys())}')
self.con... | GNN Regressor model | GNNRegressor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GNNRegressor:
"""GNN Regressor model"""
def __init__(self, in_channels, out_channels, conv_name, conv_hparams, num_layers, hidden_channels, num_layers_fc, hidden_channels_fc, hidden_channels_flows, num_transforms):
"""Arguments: - in_channels: [int] number of input channels - out_cha... | stack_v2_sparse_classes_75kplus_train_004259 | 3,796 | permissive | [
{
"docstring": "Arguments: - in_channels: [int] number of input channels - out_channels: [int] number of output channels - conv_name [str]: name of the GNN layer - conv_hparams: [dict] dictionary with extra kargs for GNN layer - num_layers: [int] number of GNN hidden layers - hidden_channels: [int] number of GN... | 2 | stack_v2_sparse_classes_30k_train_049132 | Implement the Python class `GNNRegressor` described below.
Class description:
GNN Regressor model
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, conv_name, conv_hparams, num_layers, hidden_channels, num_layers_fc, hidden_channels_fc, hidden_channels_flows, num_transforms): Arguments... | Implement the Python class `GNNRegressor` described below.
Class description:
GNN Regressor model
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, conv_name, conv_hparams, num_layers, hidden_channels, num_layers_fc, hidden_channels_fc, hidden_channels_flows, num_transforms): Arguments... | bfafeff3354cc760f35f34aca19bdd50e5998054 | <|skeleton|>
class GNNRegressor:
"""GNN Regressor model"""
def __init__(self, in_channels, out_channels, conv_name, conv_hparams, num_layers, hidden_channels, num_layers_fc, hidden_channels_fc, hidden_channels_flows, num_transforms):
"""Arguments: - in_channels: [int] number of input channels - out_cha... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GNNRegressor:
"""GNN Regressor model"""
def __init__(self, in_channels, out_channels, conv_name, conv_hparams, num_layers, hidden_channels, num_layers_fc, hidden_channels_fc, hidden_channels_flows, num_transforms):
"""Arguments: - in_channels: [int] number of input channels - out_channels: [int] ... | the_stack_v2_python_sparse | src/dsphs_gnn/gnn.py | trivnguyen/dsphs_gnn | train | 2 |
3cfe2d7a46b8caa771c9a6559338b8fdab7c328e | [
"if args.count(' ') >= 1:\n [muc, text] = args.split(' ', 1)\nelse:\n return 'Insufficient parameters'\nself.bot.sendMessage(muc, text, mtype='groupchat')\nreturn 'Sent.'",
"if args.count(' ') >= 1:\n [jid, text] = args.split(' ', 1)\nelse:\n return 'Insufficient parameters'\nself.bot.sendMessage(jid,... | <|body_start_0|>
if args.count(' ') >= 1:
[muc, text] = args.split(' ', 1)
else:
return 'Insufficient parameters'
self.bot.sendMessage(muc, text, mtype='groupchat')
return 'Sent.'
<|end_body_0|>
<|body_start_1|>
if args.count(' ') >= 1:
[jid, ... | A plugin to interact with and obtain information about other users. | Others | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Others:
"""A plugin to interact with and obtain information about other users."""
def say(self, command, args, msg):
"""Have the bot parrot some text in a channel."""
<|body_0|>
def tell(self, command, args, msg):
"""Have the bot parrot some text to a JID."""
... | stack_v2_sparse_classes_75kplus_train_004260 | 1,570 | permissive | [
{
"docstring": "Have the bot parrot some text in a channel.",
"name": "say",
"signature": "def say(self, command, args, msg)"
},
{
"docstring": "Have the bot parrot some text to a JID.",
"name": "tell",
"signature": "def tell(self, command, args, msg)"
},
{
"docstring": "Discover... | 3 | stack_v2_sparse_classes_30k_test_001839 | Implement the Python class `Others` described below.
Class description:
A plugin to interact with and obtain information about other users.
Method signatures and docstrings:
- def say(self, command, args, msg): Have the bot parrot some text in a channel.
- def tell(self, command, args, msg): Have the bot parrot some ... | Implement the Python class `Others` described below.
Class description:
A plugin to interact with and obtain information about other users.
Method signatures and docstrings:
- def say(self, command, args, msg): Have the bot parrot some text in a channel.
- def tell(self, command, args, msg): Have the bot parrot some ... | 6690cc9f644d5b0c9f8eb6e3540eea336ed61847 | <|skeleton|>
class Others:
"""A plugin to interact with and obtain information about other users."""
def say(self, command, args, msg):
"""Have the bot parrot some text in a channel."""
<|body_0|>
def tell(self, command, args, msg):
"""Have the bot parrot some text to a JID."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Others:
"""A plugin to interact with and obtain information about other users."""
def say(self, command, args, msg):
"""Have the bot parrot some text in a channel."""
if args.count(' ') >= 1:
[muc, text] = args.split(' ', 1)
else:
return 'Insufficient param... | the_stack_v2_python_sparse | sleekbot/plugins/others.py | hgrecco/SleekBot | train | 2 |
62d144f1105d376ee4c32ec28637f3be77f146bf | [
"super(RestDataCollection, self).__init__()\nself.Database = kwargs['Database']\nself.dbTable = kwargs['Table']\nself.CollectionTitle = kwargs['CollectionTitle']\nself.SingleElementTitle = kwargs['SingleElementTitle']\nself.DisplayFormat = kwargs['DisplayFormat']\nself.PostParser = kwargs['PostParser']\nself.has_pa... | <|body_start_0|>
super(RestDataCollection, self).__init__()
self.Database = kwargs['Database']
self.dbTable = kwargs['Table']
self.CollectionTitle = kwargs['CollectionTitle']
self.SingleElementTitle = kwargs['SingleElementTitle']
self.DisplayFormat = kwargs['DisplayFormat... | RestDataCollection: Manage with REST a collection of elements : - POST : is allowing to add an element to the collection - GET : is allowing to display all elements of the collection | RestDataCollection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestDataCollection:
"""RestDataCollection: Manage with REST a collection of elements : - POST : is allowing to add an element to the collection - GET : is allowing to display all elements of the collection"""
def __init__(self, **kwargs):
"""RestDataCollection constructor: - Database... | stack_v2_sparse_classes_75kplus_train_004261 | 3,788 | no_license | [
{
"docstring": "RestDataCollection constructor: - Database : SQL database which is containing table - Table : data persistence table - Collection Title : JSON title to display for the whole collection display - SingleElementTitle : JSON title to display for a single element display - DisplayFormat : JSON list o... | 3 | stack_v2_sparse_classes_30k_train_035263 | Implement the Python class `RestDataCollection` described below.
Class description:
RestDataCollection: Manage with REST a collection of elements : - POST : is allowing to add an element to the collection - GET : is allowing to display all elements of the collection
Method signatures and docstrings:
- def __init__(se... | Implement the Python class `RestDataCollection` described below.
Class description:
RestDataCollection: Manage with REST a collection of elements : - POST : is allowing to add an element to the collection - GET : is allowing to display all elements of the collection
Method signatures and docstrings:
- def __init__(se... | 8f107644a74fe46827ec5ed53d0457022bd1608b | <|skeleton|>
class RestDataCollection:
"""RestDataCollection: Manage with REST a collection of elements : - POST : is allowing to add an element to the collection - GET : is allowing to display all elements of the collection"""
def __init__(self, **kwargs):
"""RestDataCollection constructor: - Database... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RestDataCollection:
"""RestDataCollection: Manage with REST a collection of elements : - POST : is allowing to add an element to the collection - GET : is allowing to display all elements of the collection"""
def __init__(self, **kwargs):
"""RestDataCollection constructor: - Database : SQL databa... | the_stack_v2_python_sparse | restapp/view_RestDataCollection.py | ldurandadomia/Flask-Restful | train | 0 |
2097bc5c81179f9667a9a53a3530837eca0cac9d | [
"if len(nums) < 3:\n return []\nif nums[0] * nums[-1] > 0:\n return []\nj, k = (1, len(nums) - 1)\nx = nums[0]\ntarget = x * -1\nresult = []\nalready_calculate = []\nwhile j < k:\n y = nums[j]\n z = nums[k]\n sum = y + z\n if sum > target:\n k -= 1\n elif sum < target:\n j += 1\n ... | <|body_start_0|>
if len(nums) < 3:
return []
if nums[0] * nums[-1] > 0:
return []
j, k = (1, len(nums) - 1)
x = nums[0]
target = x * -1
result = []
already_calculate = []
while j < k:
y = nums[j]
z = nums[k]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def pairs(self, nums):
""":param nums: :return: >>> s = Solution() >>> s.pairs([-5, -4, -1, 0, 1, 3, 7]) [] >>> s.pairs([-4, -1, 0, 1, 3, 7]) [(-4, 1, 3)] >>> s.pairs([-1, 0, 1, 3, 7]) [(-1, 0, 1)] >>> s.pairs([0, 1, 3, 7]) []"""
<|body_0|>
def threeSum(self, nums)... | stack_v2_sparse_classes_75kplus_train_004262 | 2,009 | no_license | [
{
"docstring": ":param nums: :return: >>> s = Solution() >>> s.pairs([-5, -4, -1, 0, 1, 3, 7]) [] >>> s.pairs([-4, -1, 0, 1, 3, 7]) [(-4, 1, 3)] >>> s.pairs([-1, 0, 1, 3, 7]) [(-1, 0, 1)] >>> s.pairs([0, 1, 3, 7]) []",
"name": "pairs",
"signature": "def pairs(self, nums)"
},
{
"docstring": ":typ... | 2 | stack_v2_sparse_classes_30k_train_032969 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pairs(self, nums): :param nums: :return: >>> s = Solution() >>> s.pairs([-5, -4, -1, 0, 1, 3, 7]) [] >>> s.pairs([-4, -1, 0, 1, 3, 7]) [(-4, 1, 3)] >>> s.pairs([-1, 0, 1, 3, ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def pairs(self, nums): :param nums: :return: >>> s = Solution() >>> s.pairs([-5, -4, -1, 0, 1, 3, 7]) [] >>> s.pairs([-4, -1, 0, 1, 3, 7]) [(-4, 1, 3)] >>> s.pairs([-1, 0, 1, 3, ... | 3b13a02f9c8273f9794a57b948d2655792707f37 | <|skeleton|>
class Solution:
def pairs(self, nums):
""":param nums: :return: >>> s = Solution() >>> s.pairs([-5, -4, -1, 0, 1, 3, 7]) [] >>> s.pairs([-4, -1, 0, 1, 3, 7]) [(-4, 1, 3)] >>> s.pairs([-1, 0, 1, 3, 7]) [(-1, 0, 1)] >>> s.pairs([0, 1, 3, 7]) []"""
<|body_0|>
def threeSum(self, nums)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def pairs(self, nums):
""":param nums: :return: >>> s = Solution() >>> s.pairs([-5, -4, -1, 0, 1, 3, 7]) [] >>> s.pairs([-4, -1, 0, 1, 3, 7]) [(-4, 1, 3)] >>> s.pairs([-1, 0, 1, 3, 7]) [(-1, 0, 1)] >>> s.pairs([0, 1, 3, 7]) []"""
if len(nums) < 3:
return []
if num... | the_stack_v2_python_sparse | 3sum.py | gsy/leetcode | train | 1 | |
bbbdf35b930f8652c9bb060ce3e02576701d6b99 | [
"is_file(image_path)\ntry:\n return cv2.imread(image_path)\nexcept IOError as io:\n print(io)",
"try:\n cv2.imshow(win_name, image)\n cv2.waitKey(wait_val)\n cv2.destroyAllWindows()\nexcept IOError as io:\n print(io)",
"try:\n cv2.imwrite(filename, image)\nexcept IOError as io:\n print(i... | <|body_start_0|>
is_file(image_path)
try:
return cv2.imread(image_path)
except IOError as io:
print(io)
<|end_body_0|>
<|body_start_1|>
try:
cv2.imshow(win_name, image)
cv2.waitKey(wait_val)
cv2.destroyAllWindows()
exce... | ImageHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageHandler:
def load_img(image_path: str) -> np.ndarray:
"""[Opencv read function] Args: image_path (str): [description] Returns: np.ndarray: [description]"""
<|body_0|>
def show_img(image: np.ndarray, win_name: str='Preview', wait_val: int=500) -> None:
"""[image ... | stack_v2_sparse_classes_75kplus_train_004263 | 4,044 | permissive | [
{
"docstring": "[Opencv read function] Args: image_path (str): [description] Returns: np.ndarray: [description]",
"name": "load_img",
"signature": "def load_img(image_path: str) -> np.ndarray"
},
{
"docstring": "[image preview] Args: image (np.ndarray): [description] win_name (str, optional): [d... | 4 | stack_v2_sparse_classes_30k_train_043938 | Implement the Python class `ImageHandler` described below.
Class description:
Implement the ImageHandler class.
Method signatures and docstrings:
- def load_img(image_path: str) -> np.ndarray: [Opencv read function] Args: image_path (str): [description] Returns: np.ndarray: [description]
- def show_img(image: np.ndar... | Implement the Python class `ImageHandler` described below.
Class description:
Implement the ImageHandler class.
Method signatures and docstrings:
- def load_img(image_path: str) -> np.ndarray: [Opencv read function] Args: image_path (str): [description] Returns: np.ndarray: [description]
- def show_img(image: np.ndar... | bf50ae22918d3ca343dc9d7b1e1de89ea80f1273 | <|skeleton|>
class ImageHandler:
def load_img(image_path: str) -> np.ndarray:
"""[Opencv read function] Args: image_path (str): [description] Returns: np.ndarray: [description]"""
<|body_0|>
def show_img(image: np.ndarray, win_name: str='Preview', wait_val: int=500) -> None:
"""[image ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImageHandler:
def load_img(image_path: str) -> np.ndarray:
"""[Opencv read function] Args: image_path (str): [description] Returns: np.ndarray: [description]"""
is_file(image_path)
try:
return cv2.imread(image_path)
except IOError as io:
print(io)
d... | the_stack_v2_python_sparse | ram_utils/opencv_image/imagehandler.py | shreeramsigdel77/ram_utils | train | 3 | |
1bebf5d0ceac2ebb9379f272ee52d5b9dac018d6 | [
"key = LibraryLocatorV2.from_string(lib_key_str)\napi.require_permission_for_library_key(key, request.user, permissions.CAN_VIEW_THIS_CONTENT_LIBRARY)\nresult = api.get_library(key)\nreturn Response(ContentLibraryMetadataSerializer(result).data)",
"key = LibraryLocatorV2.from_string(lib_key_str)\napi.require_perm... | <|body_start_0|>
key = LibraryLocatorV2.from_string(lib_key_str)
api.require_permission_for_library_key(key, request.user, permissions.CAN_VIEW_THIS_CONTENT_LIBRARY)
result = api.get_library(key)
return Response(ContentLibraryMetadataSerializer(result).data)
<|end_body_0|>
<|body_start_... | Views to work with a specific content library | LibraryDetailsView | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LibraryDetailsView:
"""Views to work with a specific content library"""
def get(self, request, lib_key_str):
"""Get a specific content library"""
<|body_0|>
def patch(self, request, lib_key_str):
"""Update a content library"""
<|body_1|>
def delete(s... | stack_v2_sparse_classes_75kplus_train_004264 | 42,120 | permissive | [
{
"docstring": "Get a specific content library",
"name": "get",
"signature": "def get(self, request, lib_key_str)"
},
{
"docstring": "Update a content library",
"name": "patch",
"signature": "def patch(self, request, lib_key_str)"
},
{
"docstring": "Delete a content library",
... | 3 | stack_v2_sparse_classes_30k_train_015148 | Implement the Python class `LibraryDetailsView` described below.
Class description:
Views to work with a specific content library
Method signatures and docstrings:
- def get(self, request, lib_key_str): Get a specific content library
- def patch(self, request, lib_key_str): Update a content library
- def delete(self,... | Implement the Python class `LibraryDetailsView` described below.
Class description:
Views to work with a specific content library
Method signatures and docstrings:
- def get(self, request, lib_key_str): Get a specific content library
- def patch(self, request, lib_key_str): Update a content library
- def delete(self,... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class LibraryDetailsView:
"""Views to work with a specific content library"""
def get(self, request, lib_key_str):
"""Get a specific content library"""
<|body_0|>
def patch(self, request, lib_key_str):
"""Update a content library"""
<|body_1|>
def delete(s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LibraryDetailsView:
"""Views to work with a specific content library"""
def get(self, request, lib_key_str):
"""Get a specific content library"""
key = LibraryLocatorV2.from_string(lib_key_str)
api.require_permission_for_library_key(key, request.user, permissions.CAN_VIEW_THIS_CON... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/content_libraries/views.py | luque/better-ways-of-thinking-about-software | train | 3 |
2f23210c9a3e2c82a7fb73e2641bf9b90ac9a64c | [
"self.pybullet_client = pybullet\nself.pybullet_client.connect(self.pybullet_client.GUI)\nself.pybullet_client.setAdditionalSearchPath(pybullet_data.getDataPath())\nself.motor_id_list = [0, 1, 2, 4, 5, 6, 8, 9, 10, 12, 13, 14]\nself.pybullet_client.setGravity(0, 0, -9.8)\nself.pybullet_client.resetDebugVisualizerCa... | <|body_start_0|>
self.pybullet_client = pybullet
self.pybullet_client.connect(self.pybullet_client.GUI)
self.pybullet_client.setAdditionalSearchPath(pybullet_data.getDataPath())
self.motor_id_list = [0, 1, 2, 4, 5, 6, 8, 9, 10, 12, 13, 14]
self.pybullet_client.setGravity(0, 0, -9... | Cheetah | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cheetah:
def __init__(self):
"""初始化参数 pybullet客户端:pybullet的使用标准 motor_id:用于设置电机角度,需要区分各个关节类型,这里为了方便直接给出了对应的编号。 设置重力 设置参数:addUserDebugParameter这个api提供用户自定义的参数,我这里设置成 髋关节角度 设置视角:resetDebugVisualizerCamera这个api可以设置相机姿态 当我们的类初始化的时候需要调用一次reset()函数来设置mini cheetah的姿态"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_004265 | 4,557 | no_license | [
{
"docstring": "初始化参数 pybullet客户端:pybullet的使用标准 motor_id:用于设置电机角度,需要区分各个关节类型,这里为了方便直接给出了对应的编号。 设置重力 设置参数:addUserDebugParameter这个api提供用户自定义的参数,我这里设置成 髋关节角度 设置视角:resetDebugVisualizerCamera这个api可以设置相机姿态 当我们的类初始化的时候需要调用一次reset()函数来设置mini cheetah的姿态",
"name": "__init__",
"signature": "def __init__(self)"
}... | 4 | stack_v2_sparse_classes_30k_train_027969 | Implement the Python class `Cheetah` described below.
Class description:
Implement the Cheetah class.
Method signatures and docstrings:
- def __init__(self): 初始化参数 pybullet客户端:pybullet的使用标准 motor_id:用于设置电机角度,需要区分各个关节类型,这里为了方便直接给出了对应的编号。 设置重力 设置参数:addUserDebugParameter这个api提供用户自定义的参数,我这里设置成 髋关节角度 设置视角:resetDebugVisual... | Implement the Python class `Cheetah` described below.
Class description:
Implement the Cheetah class.
Method signatures and docstrings:
- def __init__(self): 初始化参数 pybullet客户端:pybullet的使用标准 motor_id:用于设置电机角度,需要区分各个关节类型,这里为了方便直接给出了对应的编号。 设置重力 设置参数:addUserDebugParameter这个api提供用户自定义的参数,我这里设置成 髋关节角度 设置视角:resetDebugVisual... | 54e6f8df26cf12e776f7fe06c4757ab361b02c9a | <|skeleton|>
class Cheetah:
def __init__(self):
"""初始化参数 pybullet客户端:pybullet的使用标准 motor_id:用于设置电机角度,需要区分各个关节类型,这里为了方便直接给出了对应的编号。 设置重力 设置参数:addUserDebugParameter这个api提供用户自定义的参数,我这里设置成 髋关节角度 设置视角:resetDebugVisualizerCamera这个api可以设置相机姿态 当我们的类初始化的时候需要调用一次reset()函数来设置mini cheetah的姿态"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Cheetah:
def __init__(self):
"""初始化参数 pybullet客户端:pybullet的使用标准 motor_id:用于设置电机角度,需要区分各个关节类型,这里为了方便直接给出了对应的编号。 设置重力 设置参数:addUserDebugParameter这个api提供用户自定义的参数,我这里设置成 髋关节角度 设置视角:resetDebugVisualizerCamera这个api可以设置相机姿态 当我们的类初始化的时候需要调用一次reset()函数来设置mini cheetah的姿态"""
self.pybullet_client = pybulle... | the_stack_v2_python_sparse | MiniCheetah仿真环境/build_env.py | suiup/pybullet | train | 1 | |
31a3b9f86fb60a700fc89d40bfb62fc5621ccaf4 | [
"self.full_prefix = '{}_{}'.format(self.__class__._PREFIX, prefix)\nself.progress = prometheus_client.Gauge('{}_attempt_inprogress'.format(self.full_prefix), 'In progress attempts to {}'.format(description), labels, registry=REGISTRY, multiprocess_mode='livesum')\nself.attempt_total = prometheus_client.Counter('{}_... | <|body_start_0|>
self.full_prefix = '{}_{}'.format(self.__class__._PREFIX, prefix)
self.progress = prometheus_client.Gauge('{}_attempt_inprogress'.format(self.full_prefix), 'In progress attempts to {}'.format(description), labels, registry=REGISTRY, multiprocess_mode='livesum')
self.attempt_tota... | Support for defining and observing metrics for an action, including tracking attempts, failures, and timing. | ActionMetrics | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActionMetrics:
"""Support for defining and observing metrics for an action, including tracking attempts, failures, and timing."""
def __init__(self, prefix, description, labels):
""":param prefix: prefix to use for each metric name :param description: description of action to use in ... | stack_v2_sparse_classes_75kplus_train_004266 | 6,480 | permissive | [
{
"docstring": ":param prefix: prefix to use for each metric name :param description: description of action to use in metric description :param labels: label names to define for each metric",
"name": "__init__",
"signature": "def __init__(self, prefix, description, labels)"
},
{
"docstring": "An... | 2 | stack_v2_sparse_classes_30k_train_012406 | Implement the Python class `ActionMetrics` described below.
Class description:
Support for defining and observing metrics for an action, including tracking attempts, failures, and timing.
Method signatures and docstrings:
- def __init__(self, prefix, description, labels): :param prefix: prefix to use for each metric ... | Implement the Python class `ActionMetrics` described below.
Class description:
Support for defining and observing metrics for an action, including tracking attempts, failures, and timing.
Method signatures and docstrings:
- def __init__(self, prefix, description, labels): :param prefix: prefix to use for each metric ... | 6595dd83ea65324196c89cf6fb83f168818822de | <|skeleton|>
class ActionMetrics:
"""Support for defining and observing metrics for an action, including tracking attempts, failures, and timing."""
def __init__(self, prefix, description, labels):
""":param prefix: prefix to use for each metric name :param description: description of action to use in ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ActionMetrics:
"""Support for defining and observing metrics for an action, including tracking attempts, failures, and timing."""
def __init__(self, prefix, description, labels):
""":param prefix: prefix to use for each metric name :param description: description of action to use in metric descri... | the_stack_v2_python_sparse | armada/handlers/metrics.py | airshipit/armada | train | 20 |
5fbc926a0fe35648d3c8eae69e02aed5486f6e76 | [
"m = Mapper({'DISCARD': ['foo', ('bar', ['barbar', 'barfoo'])]})\nr = m({'foo': 'buzz', 'bar': {'barfoo': 'bf', 'barbar': 'bb', 'barbuzz': 'bz'}, 'baz': 1})\nself.assertEqual(r, {'baz': 1, 'bar': {'barbuzz': 'bz'}})",
"data = {'foo': 'F', 'bar': {'bar2': 'B', 'zip': 'Z'}}\nm = Mapper({'REMAP': {'F': 'foo', 'B': (... | <|body_start_0|>
m = Mapper({'DISCARD': ['foo', ('bar', ['barbar', 'barfoo'])]})
r = m({'foo': 'buzz', 'bar': {'barfoo': 'bf', 'barbar': 'bb', 'barbuzz': 'bz'}, 'baz': 1})
self.assertEqual(r, {'baz': 1, 'bar': {'barbuzz': 'bz'}})
<|end_body_0|>
<|body_start_1|>
data = {'foo': 'F', 'bar'... | testMapper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class testMapper:
def test_discard(self):
"""see if mapper properly discards and remaps"""
<|body_0|>
def test_eval(self):
"""see if mapper properly uses fields"""
<|body_1|>
def test_remap(self):
"""see if mapper properly discards and remaps"""
... | stack_v2_sparse_classes_75kplus_train_004267 | 7,033 | permissive | [
{
"docstring": "see if mapper properly discards and remaps",
"name": "test_discard",
"signature": "def test_discard(self)"
},
{
"docstring": "see if mapper properly uses fields",
"name": "test_eval",
"signature": "def test_eval(self)"
},
{
"docstring": "see if mapper properly dis... | 3 | stack_v2_sparse_classes_30k_train_024608 | Implement the Python class `testMapper` described below.
Class description:
Implement the testMapper class.
Method signatures and docstrings:
- def test_discard(self): see if mapper properly discards and remaps
- def test_eval(self): see if mapper properly uses fields
- def test_remap(self): see if mapper properly di... | Implement the Python class `testMapper` described below.
Class description:
Implement the testMapper class.
Method signatures and docstrings:
- def test_discard(self): see if mapper properly discards and remaps
- def test_eval(self): see if mapper properly uses fields
- def test_remap(self): see if mapper properly di... | 3e406009f123dcc52565ad1fc6b7d3ef94990cb3 | <|skeleton|>
class testMapper:
def test_discard(self):
"""see if mapper properly discards and remaps"""
<|body_0|>
def test_eval(self):
"""see if mapper properly uses fields"""
<|body_1|>
def test_remap(self):
"""see if mapper properly discards and remaps"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class testMapper:
def test_discard(self):
"""see if mapper properly discards and remaps"""
m = Mapper({'DISCARD': ['foo', ('bar', ['barbar', 'barfoo'])]})
r = m({'foo': 'buzz', 'bar': {'barfoo': 'bf', 'barbar': 'bb', 'barbuzz': 'bz'}, 'baz': 1})
self.assertEqual(r, {'baz': 1, 'bar': ... | the_stack_v2_python_sparse | src/tests.py | JeffKwasha/hachit | train | 2 | |
fcd0455b4f24449edfe52e07cc065d4c2efa7aae | [
"StochasticGradientDescent.__init__(self, loss)\nself.beta_m = beta_m\nself.beta_v = beta_v\nself.epsilon = epsilon\nself.alpha = alpha\nself.beta_m_ac = beta_m\nself.beta_v_ac = beta_v\nself.mE = [0 for _ in self.Q.model.w]\nself.vE = [0 for _ in self.Q.model.w]",
"self.Q.randomDataPoint()\nself.beta_m_ac *= sel... | <|body_start_0|>
StochasticGradientDescent.__init__(self, loss)
self.beta_m = beta_m
self.beta_v = beta_v
self.epsilon = epsilon
self.alpha = alpha
self.beta_m_ac = beta_m
self.beta_v_ac = beta_v
self.mE = [0 for _ in self.Q.model.w]
self.vE = [0 f... | Implementation of Adam. | AdamSGD | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdamSGD:
"""Implementation of Adam."""
def __init__(self, loss, beta_m=1 - 0.1, beta_v=1 - 0.001, epsilon=1e-08, alpha=0.01):
"""loss: the loss function beta_m: decay parameter for the average m beta_v: decay parameter for the average v epsilon: safety parameter (to avoid division by... | stack_v2_sparse_classes_75kplus_train_004268 | 2,172 | permissive | [
{
"docstring": "loss: the loss function beta_m: decay parameter for the average m beta_v: decay parameter for the average v epsilon: safety parameter (to avoid division by 0) alpha: a learning rate that multiplies the rate.",
"name": "__init__",
"signature": "def __init__(self, loss, beta_m=1 - 0.1, bet... | 2 | stack_v2_sparse_classes_30k_train_036700 | Implement the Python class `AdamSGD` described below.
Class description:
Implementation of Adam.
Method signatures and docstrings:
- def __init__(self, loss, beta_m=1 - 0.1, beta_v=1 - 0.001, epsilon=1e-08, alpha=0.01): loss: the loss function beta_m: decay parameter for the average m beta_v: decay parameter for the ... | Implement the Python class `AdamSGD` described below.
Class description:
Implementation of Adam.
Method signatures and docstrings:
- def __init__(self, loss, beta_m=1 - 0.1, beta_v=1 - 0.001, epsilon=1e-08, alpha=0.01): loss: the loss function beta_m: decay parameter for the average m beta_v: decay parameter for the ... | e12ea464e7845793c88adfff6da4c8454099c03b | <|skeleton|>
class AdamSGD:
"""Implementation of Adam."""
def __init__(self, loss, beta_m=1 - 0.1, beta_v=1 - 0.001, epsilon=1e-08, alpha=0.01):
"""loss: the loss function beta_m: decay parameter for the average m beta_v: decay parameter for the average v epsilon: safety parameter (to avoid division by... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AdamSGD:
"""Implementation of Adam."""
def __init__(self, loss, beta_m=1 - 0.1, beta_v=1 - 0.001, epsilon=1e-08, alpha=0.01):
"""loss: the loss function beta_m: decay parameter for the average m beta_v: decay parameter for the average v epsilon: safety parameter (to avoid division by 0) alpha: a ... | the_stack_v2_python_sparse | Optimization/FitData/Stochastic-Gradient-Descent/python/SGD/AdamSGD.py | dkaramit/ASAP | train | 2 |
b912b6c10818fd94deaf560322ffe25073772f4b | [
"super(ConfigurationContext, self).__init__(**kw)\nself.hash = OPTION_CONTEXT.hash\nself.files = OPTION_CONTEXT.files[:]",
"super(ConfigurationContext, self).execute()\nself.store_options()\nif Options.options.tidy == 'force' or (Options.options.tidy == 'auto' and Options.options.compilers == [] and (Options.opti... | <|body_start_0|>
super(ConfigurationContext, self).__init__(**kw)
self.hash = OPTION_CONTEXT.hash
self.files = OPTION_CONTEXT.files[:]
<|end_body_0|>
<|body_start_1|>
super(ConfigurationContext, self).execute()
self.store_options()
if Options.options.tidy == 'force' or (... | ConfigurationContext subclass, which allows to store the current environment used for configure so it can be restored during a reconfigure. | ConfigurationContext | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigurationContext:
"""ConfigurationContext subclass, which allows to store the current environment used for configure so it can be restored during a reconfigure."""
def __init__(self, **kw):
"""main init"""
<|body_0|>
def execute(self):
"""Executes the configu... | stack_v2_sparse_classes_75kplus_train_004269 | 16,259 | permissive | [
{
"docstring": "main init",
"name": "__init__",
"signature": "def __init__(self, **kw)"
},
{
"docstring": "Executes the configuration, then stores the current status that can be checked during the reconfiguration step",
"name": "execute",
"signature": "def execute(self)"
},
{
"do... | 4 | stack_v2_sparse_classes_30k_train_037341 | Implement the Python class `ConfigurationContext` described below.
Class description:
ConfigurationContext subclass, which allows to store the current environment used for configure so it can be restored during a reconfigure.
Method signatures and docstrings:
- def __init__(self, **kw): main init
- def execute(self):... | Implement the Python class `ConfigurationContext` described below.
Class description:
ConfigurationContext subclass, which allows to store the current environment used for configure so it can be restored during a reconfigure.
Method signatures and docstrings:
- def __init__(self, **kw): main init
- def execute(self):... | 1b3831d494ee06b0bd74a8227c939dd774b91226 | <|skeleton|>
class ConfigurationContext:
"""ConfigurationContext subclass, which allows to store the current environment used for configure so it can be restored during a reconfigure."""
def __init__(self, **kw):
"""main init"""
<|body_0|>
def execute(self):
"""Executes the configu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConfigurationContext:
"""ConfigurationContext subclass, which allows to store the current environment used for configure so it can be restored during a reconfigure."""
def __init__(self, **kw):
"""main init"""
super(ConfigurationContext, self).__init__(**kw)
self.hash = OPTION_CON... | the_stack_v2_python_sparse | mak/build_framework/options/commands.py | bugengine/BugEngine | train | 4 |
23e834dd89476a82d85fc627a3f293183c72d566 | [
"assert self.user_id is not None\nuser_settings = user_services.get_user_settings(self.user_id)\nuser_email_preferences = user_services.get_email_preferences(self.user_id)\ncreators_subscribed_to = subscription_services.get_all_creators_subscribed_to(self.user_id)\ncreators_settings = user_services.get_users_settin... | <|body_start_0|>
assert self.user_id is not None
user_settings = user_services.get_user_settings(self.user_id)
user_email_preferences = user_services.get_email_preferences(self.user_id)
creators_subscribed_to = subscription_services.get_all_creators_subscribed_to(self.user_id)
cr... | Provides data for the preferences page. | PreferencesHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PreferencesHandler:
"""Provides data for the preferences page."""
def get(self) -> None:
"""Handles GET requests."""
<|body_0|>
def put(self) -> None:
"""Handles PUT requests."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
assert self.user_id i... | stack_v2_sparse_classes_75kplus_train_004270 | 29,572 | permissive | [
{
"docstring": "Handles GET requests.",
"name": "get",
"signature": "def get(self) -> None"
},
{
"docstring": "Handles PUT requests.",
"name": "put",
"signature": "def put(self) -> None"
}
] | 2 | stack_v2_sparse_classes_30k_val_000898 | Implement the Python class `PreferencesHandler` described below.
Class description:
Provides data for the preferences page.
Method signatures and docstrings:
- def get(self) -> None: Handles GET requests.
- def put(self) -> None: Handles PUT requests. | Implement the Python class `PreferencesHandler` described below.
Class description:
Provides data for the preferences page.
Method signatures and docstrings:
- def get(self) -> None: Handles GET requests.
- def put(self) -> None: Handles PUT requests.
<|skeleton|>
class PreferencesHandler:
"""Provides data for t... | d16fdf23d790eafd63812bd7239532256e30a21d | <|skeleton|>
class PreferencesHandler:
"""Provides data for the preferences page."""
def get(self) -> None:
"""Handles GET requests."""
<|body_0|>
def put(self) -> None:
"""Handles PUT requests."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PreferencesHandler:
"""Provides data for the preferences page."""
def get(self) -> None:
"""Handles GET requests."""
assert self.user_id is not None
user_settings = user_services.get_user_settings(self.user_id)
user_email_preferences = user_services.get_email_preferences(s... | the_stack_v2_python_sparse | core/controllers/profile.py | oppia/oppia | train | 6,172 |
1b78c7d9d8a926db4786577ea8ebd650eecd1d3c | [
"super(LandmarkGeneratorMultipleHeatmap, self).__init__(dim, output_size, landmark_indizes, landmark_flip_pairs, data_format, pre_transformation, post_transformation)\nself.output_size_np = list(reversed(self.output_size))\nself.sigma = sigma\nself.scale_factor = scale_factor\nself.normalize_center = normalize_cent... | <|body_start_0|>
super(LandmarkGeneratorMultipleHeatmap, self).__init__(dim, output_size, landmark_indizes, landmark_flip_pairs, data_format, pre_transformation, post_transformation)
self.output_size_np = list(reversed(self.output_size))
self.sigma = sigma
self.scale_factor = scale_facto... | Generates heatmap images with multiple Gaussian peaks | LandmarkGeneratorMultipleHeatmap | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LandmarkGeneratorMultipleHeatmap:
"""Generates heatmap images with multiple Gaussian peaks"""
def __init__(self, dim, output_size, sigma, scale_factor, normalize_center, landmark_indizes=None, landmark_flip_pairs=None, data_format='channels_first', pre_transformation=None, post_transformatio... | stack_v2_sparse_classes_75kplus_train_004271 | 16,690 | no_license | [
{
"docstring": "Initializer :param output_size: output image size :param sigma: Gaussian sigma :param scale_factor: heatmap scale factor, each value of the Gaussian will be multiplied with this value :param normalize_center: if True, the value on the center is set to scale_factor otherwise, the default gaussian... | 2 | stack_v2_sparse_classes_30k_train_009465 | Implement the Python class `LandmarkGeneratorMultipleHeatmap` described below.
Class description:
Generates heatmap images with multiple Gaussian peaks
Method signatures and docstrings:
- def __init__(self, dim, output_size, sigma, scale_factor, normalize_center, landmark_indizes=None, landmark_flip_pairs=None, data_... | Implement the Python class `LandmarkGeneratorMultipleHeatmap` described below.
Class description:
Generates heatmap images with multiple Gaussian peaks
Method signatures and docstrings:
- def __init__(self, dim, output_size, sigma, scale_factor, normalize_center, landmark_indizes=None, landmark_flip_pairs=None, data_... | ef6cee91264ba1fe6b40d9823a07647b95bcc2c4 | <|skeleton|>
class LandmarkGeneratorMultipleHeatmap:
"""Generates heatmap images with multiple Gaussian peaks"""
def __init__(self, dim, output_size, sigma, scale_factor, normalize_center, landmark_indizes=None, landmark_flip_pairs=None, data_format='channels_first', pre_transformation=None, post_transformatio... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LandmarkGeneratorMultipleHeatmap:
"""Generates heatmap images with multiple Gaussian peaks"""
def __init__(self, dim, output_size, sigma, scale_factor, normalize_center, landmark_indizes=None, landmark_flip_pairs=None, data_format='channels_first', pre_transformation=None, post_transformation=None):
... | the_stack_v2_python_sparse | generators/landmark_generator.py | XiaoweiXu/MedicalDataAugmentationTool | train | 1 |
d147be66a46875d93ef743b65b1917f1fec7292a | [
"try:\n games = {}\n query = 'search *\"{}\"*;fields id, name, genres.name, first_release_date,platforms.name, summary, dlcs.name,expansions.name,total_rating, keywords.name, age_ratings.synopsis, similar_games.name,similar_games.cover.url, cover.url, screenshots.url,videos.video_id, websites.url;limit 20;'.f... | <|body_start_0|>
try:
games = {}
query = 'search *"{}"*;fields id, name, genres.name, first_release_date,platforms.name, summary, dlcs.name,expansions.name,total_rating, keywords.name, age_ratings.synopsis, similar_games.name,similar_games.cover.url, cover.url, screenshots.url,videos.vid... | Utilities for the service of games. | UtilsGames | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UtilsGames:
"""Utilities for the service of games."""
def search_all(self, data):
"""Search by all items."""
<|body_0|>
def search_date(self, data):
"""Search by date."""
<|body_1|>
def search_uuid(self, data):
"""Search by uuid."""
<... | stack_v2_sparse_classes_75kplus_train_004272 | 11,622 | no_license | [
{
"docstring": "Search by all items.",
"name": "search_all",
"signature": "def search_all(self, data)"
},
{
"docstring": "Search by date.",
"name": "search_date",
"signature": "def search_date(self, data)"
},
{
"docstring": "Search by uuid.",
"name": "search_uuid",
"signa... | 4 | stack_v2_sparse_classes_30k_train_011337 | Implement the Python class `UtilsGames` described below.
Class description:
Utilities for the service of games.
Method signatures and docstrings:
- def search_all(self, data): Search by all items.
- def search_date(self, data): Search by date.
- def search_uuid(self, data): Search by uuid.
- def search_coming_soon(se... | Implement the Python class `UtilsGames` described below.
Class description:
Utilities for the service of games.
Method signatures and docstrings:
- def search_all(self, data): Search by all items.
- def search_date(self, data): Search by date.
- def search_uuid(self, data): Search by uuid.
- def search_coming_soon(se... | cd8767b5eeaef3a09d77c936781b4126fd8591de | <|skeleton|>
class UtilsGames:
"""Utilities for the service of games."""
def search_all(self, data):
"""Search by all items."""
<|body_0|>
def search_date(self, data):
"""Search by date."""
<|body_1|>
def search_uuid(self, data):
"""Search by uuid."""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UtilsGames:
"""Utilities for the service of games."""
def search_all(self, data):
"""Search by all items."""
try:
games = {}
query = 'search *"{}"*;fields id, name, genres.name, first_release_date,platforms.name, summary, dlcs.name,expansions.name,total_rating, key... | the_stack_v2_python_sparse | api/services/utils.py | ignite7/backproject | train | 0 |
936843fd1a1c8006bdcbb87d5a3f1cdc7137f77d | [
"self.input_json_path = input_json_path\nself.template_pattern = template_pattern\nself.templates = []\nself.debug = debug\nif self.debug:\n print('TemplateDiscovery - __init__' + lineno())",
"if self.debug:\n print('\\n\\n#######################################')\n print('discover templates' + lineno())... | <|body_start_0|>
self.input_json_path = input_json_path
self.template_pattern = template_pattern
self.templates = []
self.debug = debug
if self.debug:
print('TemplateDiscovery - __init__' + lineno())
<|end_body_0|>
<|body_start_1|>
if self.debug:
... | Template discover | TemplateDiscovery | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TemplateDiscovery:
"""Template discover"""
def __init__(self, input_json_path=str(os.path.dirname(__file__) + '/test_templates/json'), template_pattern='json', debug=False):
"""Initialize TemplateDiscovery :param input_json_path: :param template_pattern: :param debug:"""
<|bo... | stack_v2_sparse_classes_75kplus_train_004273 | 2,635 | permissive | [
{
"docstring": "Initialize TemplateDiscovery :param input_json_path: :param template_pattern: :param debug:",
"name": "__init__",
"signature": "def __init__(self, input_json_path=str(os.path.dirname(__file__) + '/test_templates/json'), template_pattern='json', debug=False)"
},
{
"docstring": "Di... | 4 | stack_v2_sparse_classes_30k_train_040595 | Implement the Python class `TemplateDiscovery` described below.
Class description:
Template discover
Method signatures and docstrings:
- def __init__(self, input_json_path=str(os.path.dirname(__file__) + '/test_templates/json'), template_pattern='json', debug=False): Initialize TemplateDiscovery :param input_json_pat... | Implement the Python class `TemplateDiscovery` described below.
Class description:
Template discover
Method signatures and docstrings:
- def __init__(self, input_json_path=str(os.path.dirname(__file__) + '/test_templates/json'), template_pattern='json', debug=False): Initialize TemplateDiscovery :param input_json_pat... | a9d0335a532acdb4070e5537155b03b34915b73e | <|skeleton|>
class TemplateDiscovery:
"""Template discover"""
def __init__(self, input_json_path=str(os.path.dirname(__file__) + '/test_templates/json'), template_pattern='json', debug=False):
"""Initialize TemplateDiscovery :param input_json_path: :param template_pattern: :param debug:"""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TemplateDiscovery:
"""Template discover"""
def __init__(self, input_json_path=str(os.path.dirname(__file__) + '/test_templates/json'), template_pattern='json', debug=False):
"""Initialize TemplateDiscovery :param input_json_path: :param template_pattern: :param debug:"""
self.input_json_p... | the_stack_v2_python_sparse | terraform_validator/TemplateDiscovery.py | rubelw/terraform-validator | train | 7 |
2288c7e93069d369f7693626a7994bf25ef0a459 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn HostCookie()",
"from .artifact import Artifact\nfrom .host import Host\nfrom .artifact import Artifact\nfrom .host import Host\nfields: Dict[str, Callable[[Any], None]] = {'domain': lambda n: setattr(self, 'domain', n.get_str_value()),... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return HostCookie()
<|end_body_0|>
<|body_start_1|>
from .artifact import Artifact
from .host import Host
from .artifact import Artifact
from .host import Host
fields: D... | HostCookie | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HostCookie:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> HostCookie:
"""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: Host... | stack_v2_sparse_classes_75kplus_train_004274 | 3,561 | 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: HostCookie",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(pa... | 3 | stack_v2_sparse_classes_30k_train_052312 | Implement the Python class `HostCookie` described below.
Class description:
Implement the HostCookie class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> HostCookie: Creates a new instance of the appropriate class based on discriminator value Args: pa... | Implement the Python class `HostCookie` described below.
Class description:
Implement the HostCookie class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> HostCookie: Creates a new instance of the appropriate class based on discriminator value Args: pa... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class HostCookie:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> HostCookie:
"""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: Host... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HostCookie:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> HostCookie:
"""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: HostCookie"""
... | the_stack_v2_python_sparse | msgraph/generated/models/security/host_cookie.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
34cef8b96047866cb54a7651d926dd3b0ec89221 | [
"mce_attrs = {}\nif obj:\n link_list_url = self.get_link_list_url(request, field, obj)\n image_list_url = self.get_image_list_url(request, field, obj)\nelse:\n link_list_url = self.get_link_list_url(request, field)\n image_list_url = self.get_image_list_url(request, field)\nif link_list_url:\n mce_at... | <|body_start_0|>
mce_attrs = {}
if obj:
link_list_url = self.get_link_list_url(request, field, obj)
image_list_url = self.get_image_list_url(request, field, obj)
else:
link_list_url = self.get_link_list_url(request, field)
image_list_url = self.get... | Example usage:: class BrandTranslationInline(TinyMCEAdminListMixin, TranslationInline): model = BrandTranslation tinymce_fields = ('description', ) def get_image_list_url(self, request, field, obj=None): if obj: return reverse('admin:basic_webshop_brand_image_list', args=(obj.pk, )) else: return None | TinyMCEAdminListMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TinyMCEAdminListMixin:
"""Example usage:: class BrandTranslationInline(TinyMCEAdminListMixin, TranslationInline): model = BrandTranslation tinymce_fields = ('description', ) def get_image_list_url(self, request, field, obj=None): if obj: return reverse('admin:basic_webshop_brand_image_list', args... | stack_v2_sparse_classes_75kplus_train_004275 | 5,965 | no_license | [
{
"docstring": "Return the appropriate TinyMCE widget.",
"name": "get_tinymce_widget",
"signature": "def get_tinymce_widget(self, request, field, obj)"
},
{
"docstring": "Override the form widget for the content field with a TinyMCE field which uses a dynamically assigned image list.",
"name... | 2 | stack_v2_sparse_classes_30k_train_013960 | Implement the Python class `TinyMCEAdminListMixin` described below.
Class description:
Example usage:: class BrandTranslationInline(TinyMCEAdminListMixin, TranslationInline): model = BrandTranslation tinymce_fields = ('description', ) def get_image_list_url(self, request, field, obj=None): if obj: return reverse('admi... | Implement the Python class `TinyMCEAdminListMixin` described below.
Class description:
Example usage:: class BrandTranslationInline(TinyMCEAdminListMixin, TranslationInline): model = BrandTranslation tinymce_fields = ('description', ) def get_image_list_url(self, request, field, obj=None): if obj: return reverse('admi... | 618dee93539ecc4d1ff20aafb138ee85b4d6173b | <|skeleton|>
class TinyMCEAdminListMixin:
"""Example usage:: class BrandTranslationInline(TinyMCEAdminListMixin, TranslationInline): model = BrandTranslation tinymce_fields = ('description', ) def get_image_list_url(self, request, field, obj=None): if obj: return reverse('admin:basic_webshop_brand_image_list', args... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TinyMCEAdminListMixin:
"""Example usage:: class BrandTranslationInline(TinyMCEAdminListMixin, TranslationInline): model = BrandTranslation tinymce_fields = ('description', ) def get_image_list_url(self, request, field, obj=None): if obj: return reverse('admin:basic_webshop_brand_image_list', args=(obj.pk, )) ... | the_stack_v2_python_sparse | basic_webshop/baseadmin.py | dokterbob/basic-webshop | train | 1 |
7ae4418b5d3d9bda061bdaa770389304788001e0 | [
"if stop_list == None:\n __location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))\n stop_list = set((line.strip() for line in open(os.path.join(__location__, 'stop_words.txt'))))\nif config is None:\n config = {'dimensionality': dimensionality, 'num_indices': num_indices, 'wind... | <|body_start_0|>
if stop_list == None:
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
stop_list = set((line.strip() for line in open(os.path.join(__location__, 'stop_words.txt'))))
if config is None:
config = {'dimensionality': d... | RandomIndexing | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomIndexing:
def __init__(self, matrix=None, corpus=None, config=None, window_size=(2, 2), vocabulary=None, dimensionality=2000, num_indices=8, stop_list=None, **kwargs):
"""Builds a Random Indexing DSM from text-iterator [1]. :param matrix: Instantiate DSM with already created matrix... | stack_v2_sparse_classes_75kplus_train_004276 | 18,587 | permissive | [
{
"docstring": "Builds a Random Indexing DSM from text-iterator [1]. :param matrix: Instantiate DSM with already created matrix. :param corpus: File path string or iterable to read. :param config: Additional configuration options. Obligatory: window_size: 2-tuple of size of the context. dimensionality: Number o... | 3 | stack_v2_sparse_classes_30k_val_001161 | Implement the Python class `RandomIndexing` described below.
Class description:
Implement the RandomIndexing class.
Method signatures and docstrings:
- def __init__(self, matrix=None, corpus=None, config=None, window_size=(2, 2), vocabulary=None, dimensionality=2000, num_indices=8, stop_list=None, **kwargs): Builds a... | Implement the Python class `RandomIndexing` described below.
Class description:
Implement the RandomIndexing class.
Method signatures and docstrings:
- def __init__(self, matrix=None, corpus=None, config=None, window_size=(2, 2), vocabulary=None, dimensionality=2000, num_indices=8, stop_list=None, **kwargs): Builds a... | 272558cf41a0c3bca4d5659027bc6b546d5e9b7d | <|skeleton|>
class RandomIndexing:
def __init__(self, matrix=None, corpus=None, config=None, window_size=(2, 2), vocabulary=None, dimensionality=2000, num_indices=8, stop_list=None, **kwargs):
"""Builds a Random Indexing DSM from text-iterator [1]. :param matrix: Instantiate DSM with already created matrix... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomIndexing:
def __init__(self, matrix=None, corpus=None, config=None, window_size=(2, 2), vocabulary=None, dimensionality=2000, num_indices=8, stop_list=None, **kwargs):
"""Builds a Random Indexing DSM from text-iterator [1]. :param matrix: Instantiate DSM with already created matrix. :param corpu... | the_stack_v2_python_sparse | pydsm/model.py | hugoflug/pydsm | train | 0 | |
b8e6aaeb20d50a4216913d6592c3b612ef703f91 | [
"params = base.get_params(('event', 'type', 'unit', 'interval'), locals(), serialize_param)\nrequest = http.Request('GET', 'events/', params)\nreturn (request, parsers.parse_json)",
"params = base.get_params(('type', 'limit'), locals(), serialize_param)\nrequest = http.Request('GET', 'events/top/', params)\nretur... | <|body_start_0|>
params = base.get_params(('event', 'type', 'unit', 'interval'), locals(), serialize_param)
request = http.Request('GET', 'events/', params)
return (request, parsers.parse_json)
<|end_body_0|>
<|body_start_1|>
params = base.get_params(('type', 'limit'), locals(), seriali... | Events | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Events:
def get(self, event, type, unit, interval):
"""Fetch event data."""
<|body_0|>
def top(self, type, limit=None):
"""Fetch the top events for today."""
<|body_1|>
def names(self, type, limit=None):
"""Fetch the most common events over the l... | stack_v2_sparse_classes_75kplus_train_004277 | 7,208 | permissive | [
{
"docstring": "Fetch event data.",
"name": "get",
"signature": "def get(self, event, type, unit, interval)"
},
{
"docstring": "Fetch the top events for today.",
"name": "top",
"signature": "def top(self, type, limit=None)"
},
{
"docstring": "Fetch the most common events over the... | 3 | stack_v2_sparse_classes_30k_train_037814 | Implement the Python class `Events` described below.
Class description:
Implement the Events class.
Method signatures and docstrings:
- def get(self, event, type, unit, interval): Fetch event data.
- def top(self, type, limit=None): Fetch the top events for today.
- def names(self, type, limit=None): Fetch the most c... | Implement the Python class `Events` described below.
Class description:
Implement the Events class.
Method signatures and docstrings:
- def get(self, event, type, unit, interval): Fetch event data.
- def top(self, type, limit=None): Fetch the top events for today.
- def names(self, type, limit=None): Fetch the most c... | 25caa745a104c8dc209584fa359294c65dbf88bb | <|skeleton|>
class Events:
def get(self, event, type, unit, interval):
"""Fetch event data."""
<|body_0|>
def top(self, type, limit=None):
"""Fetch the top events for today."""
<|body_1|>
def names(self, type, limit=None):
"""Fetch the most common events over the l... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Events:
def get(self, event, type, unit, interval):
"""Fetch event data."""
params = base.get_params(('event', 'type', 'unit', 'interval'), locals(), serialize_param)
request = http.Request('GET', 'events/', params)
return (request, parsers.parse_json)
def top(self, type, ... | the_stack_v2_python_sparse | libsaas/services/mixpanel/resources.py | piplcom/libsaas | train | 1 | |
a706247e5979fa7a63f8e16f7059b995cc979899 | [
"new_head = None\nwhile head:\n curr = ListNode(head.val)\n curr.next, new_head = (new_head, curr)\n head = head.next\nreturn new_head",
"if not head or not head.next:\n return head\nnew = Solution().reverseList2(head.next)\nhead.next.next = head\nhead.next = None\nreturn new"
] | <|body_start_0|>
new_head = None
while head:
curr = ListNode(head.val)
curr.next, new_head = (new_head, curr)
head = head.next
return new_head
<|end_body_0|>
<|body_start_1|>
if not head or not head.next:
return head
new = Solution... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList(self, head):
"""Iterative solution"""
<|body_0|>
def reverseList2(self, head):
"""Recursive solution"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
new_head = None
while head:
curr = ListNode(head.val)
... | stack_v2_sparse_classes_75kplus_train_004278 | 613 | no_license | [
{
"docstring": "Iterative solution",
"name": "reverseList",
"signature": "def reverseList(self, head)"
},
{
"docstring": "Recursive solution",
"name": "reverseList2",
"signature": "def reverseList2(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021834 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): Iterative solution
- def reverseList2(self, head): Recursive solution | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): Iterative solution
- def reverseList2(self, head): Recursive solution
<|skeleton|>
class Solution:
def reverseList(self, head):
"""Iter... | f33d004d7629d46fbc5670f5b384f8a604d7f1e7 | <|skeleton|>
class Solution:
def reverseList(self, head):
"""Iterative solution"""
<|body_0|>
def reverseList2(self, head):
"""Recursive solution"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverseList(self, head):
"""Iterative solution"""
new_head = None
while head:
curr = ListNode(head.val)
curr.next, new_head = (new_head, curr)
head = head.next
return new_head
def reverseList2(self, head):
"""Recurs... | the_stack_v2_python_sparse | Reverse Linked List.py | aulee888/LeetCode | train | 0 | |
dc83002818180a7301698d0cdf59d8b35b05bd48 | [
"try:\n return super().emit(record)\nexcept FileNotFoundError:\n return self._emit_safely(record)\nexcept OSError as exception:\n if exception.errno == errno.ESTALE:\n return self._emit_safely(record)\n else:\n raise",
"ATTEMPTS_MAX = 8\nSLEEP_INTERVAL = 0.1\nfor attempt_index in range(A... | <|body_start_0|>
try:
return super().emit(record)
except FileNotFoundError:
return self._emit_safely(record)
except OSError as exception:
if exception.errno == errno.ESTALE:
return self._emit_safely(record)
else:
rai... | Process-safe rotating file handler. The standard :class:`RotatingFileHandler` class is thread- but *not* process-safe. Concurrent attempts to log to the same physical file from multiple processes can and typically will produce fatal race conditions producing raised exceptions from one or more of these processes. On log... | LogHandlerFileRotateSafe | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogHandlerFileRotateSafe:
"""Process-safe rotating file handler. The standard :class:`RotatingFileHandler` class is thread- but *not* process-safe. Concurrent attempts to log to the same physical file from multiple processes can and typically will produce fatal race conditions producing raised ex... | stack_v2_sparse_classes_75kplus_train_004279 | 17,464 | no_license | [
{
"docstring": "Log the passed logging record in a thread- *and* process-safe manner. Parameters ---------- record : LogRecord Logging record to be logged. Raises ---------- BetseLogRaceException If this method detects but fails to automatically resolve a logging race condition between multiple processes concur... | 2 | stack_v2_sparse_classes_30k_val_002325 | Implement the Python class `LogHandlerFileRotateSafe` described below.
Class description:
Process-safe rotating file handler. The standard :class:`RotatingFileHandler` class is thread- but *not* process-safe. Concurrent attempts to log to the same physical file from multiple processes can and typically will produce fa... | Implement the Python class `LogHandlerFileRotateSafe` described below.
Class description:
Process-safe rotating file handler. The standard :class:`RotatingFileHandler` class is thread- but *not* process-safe. Concurrent attempts to log to the same physical file from multiple processes can and typically will produce fa... | dd03ff5e3df3ef48d887a6566a6286fcd168880b | <|skeleton|>
class LogHandlerFileRotateSafe:
"""Process-safe rotating file handler. The standard :class:`RotatingFileHandler` class is thread- but *not* process-safe. Concurrent attempts to log to the same physical file from multiple processes can and typically will produce fatal race conditions producing raised ex... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LogHandlerFileRotateSafe:
"""Process-safe rotating file handler. The standard :class:`RotatingFileHandler` class is thread- but *not* process-safe. Concurrent attempts to log to the same physical file from multiple processes can and typically will produce fatal race conditions producing raised exceptions from... | the_stack_v2_python_sparse | betse/util/io/log/conf/logconfhandle.py | R-Stefano/betse-ml | train | 0 |
3f8e53009ab8311f53c1ccba9ed00800535a2dd7 | [
"if not nums:\n return 0\nlis = [1] * len(nums)\nfor i, n in enumerate(nums):\n for j, m in enumerate(nums[:i]):\n if m < n:\n lis[i] = max(lis[i], lis[j] + 1)\nprint(lis)\nreturn max(lis)",
"if not nums:\n return 0\n\ndef bisearch(arr, n):\n left, right = (0, len(arr) - 1)\n whil... | <|body_start_0|>
if not nums:
return 0
lis = [1] * len(nums)
for i, n in enumerate(nums):
for j, m in enumerate(nums[:i]):
if m < n:
lis[i] = max(lis[i], lis[j] + 1)
print(lis)
return max(lis)
<|end_body_0|>
<|body_star... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
"""11/05/2019 01:36"""
<|body_0|>
def lengthOfLIS(self, nums: List[int]) -> int:
"""11/05/2019 02:28"""
<|body_1|>
def lengthOfLIS(self, nums: List[int]) -> int:
"""DP Time complexity: O(n^... | stack_v2_sparse_classes_75kplus_train_004280 | 3,572 | no_license | [
{
"docstring": "11/05/2019 01:36",
"name": "lengthOfLIS",
"signature": "def lengthOfLIS(self, nums: List[int]) -> int"
},
{
"docstring": "11/05/2019 02:28",
"name": "lengthOfLIS",
"signature": "def lengthOfLIS(self, nums: List[int]) -> int"
},
{
"docstring": "DP Time complexity: ... | 5 | stack_v2_sparse_classes_30k_train_035108 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS(self, nums: List[int]) -> int: 11/05/2019 01:36
- def lengthOfLIS(self, nums: List[int]) -> int: 11/05/2019 02:28
- def lengthOfLIS(self, nums: List[int]) -> int:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS(self, nums: List[int]) -> int: 11/05/2019 01:36
- def lengthOfLIS(self, nums: List[int]) -> int: 11/05/2019 02:28
- def lengthOfLIS(self, nums: List[int]) -> int:... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
"""11/05/2019 01:36"""
<|body_0|>
def lengthOfLIS(self, nums: List[int]) -> int:
"""11/05/2019 02:28"""
<|body_1|>
def lengthOfLIS(self, nums: List[int]) -> int:
"""DP Time complexity: O(n^... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
"""11/05/2019 01:36"""
if not nums:
return 0
lis = [1] * len(nums)
for i, n in enumerate(nums):
for j, m in enumerate(nums[:i]):
if m < n:
lis[i] = max(lis[i], l... | the_stack_v2_python_sparse | leetcode/solved/300_Longest_Increasing_Subsequence/solution.py | sungminoh/algorithms | train | 0 | |
a75ffba7539aade134637c0e1cbc29885554dd6a | [
"super().__init__(json=json, **kwargs)\nif max_size is not None:\n if isinstance(max_size, (int, float)):\n self._config['maxSize'] = int(max_size) * 1024 ** 2\n else:\n raise ValueError('`max_size` should be a number.')\nself.max_size = self._config.get('maxSize', float('inf'))",
"if value is... | <|body_start_0|>
super().__init__(json=json, **kwargs)
if max_size is not None:
if isinstance(max_size, (int, float)):
self._config['maxSize'] = int(max_size) * 1024 ** 2
else:
raise ValueError('`max_size` should be a number.')
self.max_siz... | A file size Validator. The actual size of the file cannot be checked in pykechain without downloading this from the server, hence when the validator is used inside an attachment property, the validator returns always being valid. :ivar max_size: maximum size to check, in MB :type max_size: Union[int,float] Example ----... | FileSizeValidator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileSizeValidator:
"""A file size Validator. The actual size of the file cannot be checked in pykechain without downloading this from the server, hence when the validator is used inside an attachment property, the validator returns always being valid. :ivar max_size: maximum size to check, in MB ... | stack_v2_sparse_classes_75kplus_train_004281 | 20,653 | permissive | [
{
"docstring": "Construct a file size validator. :param json: (optional) dict (json) object to construct the object from :type json: Optional[Dict] :param max_size: (optional) number that counts as maximum size of the file, in MB :type accept: Optional[Union[int,float]] :param kwargs: (optional) additional kwar... | 2 | null | Implement the Python class `FileSizeValidator` described below.
Class description:
A file size Validator. The actual size of the file cannot be checked in pykechain without downloading this from the server, hence when the validator is used inside an attachment property, the validator returns always being valid. :ivar ... | Implement the Python class `FileSizeValidator` described below.
Class description:
A file size Validator. The actual size of the file cannot be checked in pykechain without downloading this from the server, hence when the validator is used inside an attachment property, the validator returns always being valid. :ivar ... | e8352e4d434bd5d0a5d76f7351f100d0b63f6fa8 | <|skeleton|>
class FileSizeValidator:
"""A file size Validator. The actual size of the file cannot be checked in pykechain without downloading this from the server, hence when the validator is used inside an attachment property, the validator returns always being valid. :ivar max_size: maximum size to check, in MB ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FileSizeValidator:
"""A file size Validator. The actual size of the file cannot be checked in pykechain without downloading this from the server, hence when the validator is used inside an attachment property, the validator returns always being valid. :ivar max_size: maximum size to check, in MB :type max_siz... | the_stack_v2_python_sparse | pykechain/models/validators/validators.py | KE-works/pykechain | train | 7 |
70895d393258b47f3d8da573e86c45916b21fa4c | [
"self.age_adjustment_functions = {}\naffected_age_indices = [i for i in AGE_INDICES if f'age_{i}' in mixing_age_adjust]\nfor age_idx in affected_age_indices:\n key = f'age_{age_idx}'\n mixing_age_adjust[key]['times'] = [(time_date - BASE_DATE).days for time_date in mixing_age_adjust[key]['times']]\n age_ti... | <|body_start_0|>
self.age_adjustment_functions = {}
affected_age_indices = [i for i in AGE_INDICES if f'age_{i}' in mixing_age_adjust]
for age_idx in affected_age_indices:
key = f'age_{age_idx}'
mixing_age_adjust[key]['times'] = [(time_date - BASE_DATE).days for time_date... | AgeMixingAdjustment | [
"BSD-2-Clause-Views"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AgeMixingAdjustment:
def __init__(self, mixing_age_adjust: dict):
"""Build the time variant age adjustment functions"""
<|body_0|>
def get_adjustment(self, time: float, mixing_matrix: np.ndarray) -> np.ndarray:
"""Apply time-varying age adjustments. Returns a new mix... | stack_v2_sparse_classes_75kplus_train_004282 | 1,827 | permissive | [
{
"docstring": "Build the time variant age adjustment functions",
"name": "__init__",
"signature": "def __init__(self, mixing_age_adjust: dict)"
},
{
"docstring": "Apply time-varying age adjustments. Returns a new mixing matrix, modified to adjust for dynamic mixing changes for a given point in ... | 2 | stack_v2_sparse_classes_30k_train_037991 | Implement the Python class `AgeMixingAdjustment` described below.
Class description:
Implement the AgeMixingAdjustment class.
Method signatures and docstrings:
- def __init__(self, mixing_age_adjust: dict): Build the time variant age adjustment functions
- def get_adjustment(self, time: float, mixing_matrix: np.ndarr... | Implement the Python class `AgeMixingAdjustment` described below.
Class description:
Implement the AgeMixingAdjustment class.
Method signatures and docstrings:
- def __init__(self, mixing_age_adjust: dict): Build the time variant age adjustment functions
- def get_adjustment(self, time: float, mixing_matrix: np.ndarr... | 0cbd006d1f15da414d02eed44e48bb5c06f0802e | <|skeleton|>
class AgeMixingAdjustment:
def __init__(self, mixing_age_adjust: dict):
"""Build the time variant age adjustment functions"""
<|body_0|>
def get_adjustment(self, time: float, mixing_matrix: np.ndarray) -> np.ndarray:
"""Apply time-varying age adjustments. Returns a new mix... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AgeMixingAdjustment:
def __init__(self, mixing_age_adjust: dict):
"""Build the time variant age adjustment functions"""
self.age_adjustment_functions = {}
affected_age_indices = [i for i in AGE_INDICES if f'age_{i}' in mixing_age_adjust]
for age_idx in affected_age_indices:
... | the_stack_v2_python_sparse | apps/covid_19/preprocess/mixing_matrix/adjust_age.py | malanchak/AuTuMN | train | 0 | |
f6ecf85b696c7659d758374912794512142bac86 | [
"check_classification_targets(y)\nlab_enc = LabelEncoder()\nenc_y = lab_enc.fit_transform(y).astype(np.float64, copy=False)\nself.classes_ = lab_enc.classes_\nif self.classes_.shape[0] != self.num_classes:\n raise ValueError('Number of classes defined in configuration file and the classes derived from the data d... | <|body_start_0|>
check_classification_targets(y)
lab_enc = LabelEncoder()
enc_y = lab_enc.fit_transform(y).astype(np.float64, copy=False)
self.classes_ = lab_enc.classes_
if self.classes_.shape[0] != self.num_classes:
raise ValueError('Number of classes defined in con... | XGBClassifierLocalTrainingHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XGBClassifierLocalTrainingHandler:
def encode_target(self, y):
"""Converts the input y to the expected dtype and performs a label encoding. Here, we assume that each party has at least one sample of the corresponding class label type for each different classes. :param y: The correspondin... | stack_v2_sparse_classes_75kplus_train_004283 | 18,049 | no_license | [
{
"docstring": "Converts the input y to the expected dtype and performs a label encoding. Here, we assume that each party has at least one sample of the corresponding class label type for each different classes. :param y: The corresponding target data from the dataset to encode. :type y: `np.array` :return: Ret... | 2 | null | Implement the Python class `XGBClassifierLocalTrainingHandler` described below.
Class description:
Implement the XGBClassifierLocalTrainingHandler class.
Method signatures and docstrings:
- def encode_target(self, y): Converts the input y to the expected dtype and performs a label encoding. Here, we assume that each ... | Implement the Python class `XGBClassifierLocalTrainingHandler` described below.
Class description:
Implement the XGBClassifierLocalTrainingHandler class.
Method signatures and docstrings:
- def encode_target(self, y): Converts the input y to the expected dtype and performs a label encoding. Here, we assume that each ... | a4cd429484e857b849df08d93688d35e632b3e29 | <|skeleton|>
class XGBClassifierLocalTrainingHandler:
def encode_target(self, y):
"""Converts the input y to the expected dtype and performs a label encoding. Here, we assume that each party has at least one sample of the corresponding class label type for each different classes. :param y: The correspondin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class XGBClassifierLocalTrainingHandler:
def encode_target(self, y):
"""Converts the input y to the expected dtype and performs a label encoding. Here, we assume that each party has at least one sample of the corresponding class label type for each different classes. :param y: The corresponding target data ... | the_stack_v2_python_sparse | venv/Lib/site-packages/ibmfl/party/training/xgboost_local_training_handler.py | yusufcet/healty-hearts | train | 0 | |
3ca8010b9cf717717269783e8b32624020611c2c | [
"if 'username' in request.query_params:\n if pk is None:\n user = User.objects.get(username=request.query_params['username'])\n todo_items = Todo.objects.filter(user=user)\n serializer = TodoSerializer(todo_items, many=True)\n serialized_data = serializer.data\n return Response... | <|body_start_0|>
if 'username' in request.query_params:
if pk is None:
user = User.objects.get(username=request.query_params['username'])
todo_items = Todo.objects.filter(user=user)
serializer = TodoSerializer(todo_items, many=True)
ser... | TodoView used to handle the incoming requests relating to `todo` items | TodoView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TodoView:
"""TodoView used to handle the incoming requests relating to `todo` items"""
def get(self, request, pk=None):
"""Handle the GET request for the `/todo/` endpoint. Gets `username` from the `query_params` in order to retrieve the `todo` items belonging to that user, then chec... | stack_v2_sparse_classes_75kplus_train_004284 | 5,337 | permissive | [
{
"docstring": "Handle the GET request for the `/todo/` endpoint. Gets `username` from the `query_params` in order to retrieve the `todo` items belonging to that user, then checks to see if a primary key has been provided by the URL. If not, a full list of `todo` will be retrieved. If a primary key has been pro... | 4 | null | Implement the Python class `TodoView` described below.
Class description:
TodoView used to handle the incoming requests relating to `todo` items
Method signatures and docstrings:
- def get(self, request, pk=None): Handle the GET request for the `/todo/` endpoint. Gets `username` from the `query_params` in order to re... | Implement the Python class `TodoView` described below.
Class description:
TodoView used to handle the incoming requests relating to `todo` items
Method signatures and docstrings:
- def get(self, request, pk=None): Handle the GET request for the `/todo/` endpoint. Gets `username` from the `query_params` in order to re... | efba0984a3dc71558eef97724c85e274a712798c | <|skeleton|>
class TodoView:
"""TodoView used to handle the incoming requests relating to `todo` items"""
def get(self, request, pk=None):
"""Handle the GET request for the `/todo/` endpoint. Gets `username` from the `query_params` in order to retrieve the `todo` items belonging to that user, then chec... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TodoView:
"""TodoView used to handle the incoming requests relating to `todo` items"""
def get(self, request, pk=None):
"""Handle the GET request for the `/todo/` endpoint. Gets `username` from the `query_params` in order to retrieve the `todo` items belonging to that user, then checks to see if ... | the_stack_v2_python_sparse | Stream-3/Full-Stack-Development/21.Django REST Framework/4.User-Authentication/django_todo/todo/views.py | GunnerJnr/_CodeInstitute | train | 8 |
887b14d91de848a55fea2efdd13470d357e289d5 | [
"self.x = x\nself.y = y\nself.z = z",
"x = self.x\ny = self.y\nz = self.z\nreturn math.sqrt((new_point.x - x) ** 2 + (new_point.y - y) ** 2 + (new_point.z - z) ** 2)"
] | <|body_start_0|>
self.x = x
self.y = y
self.z = z
<|end_body_0|>
<|body_start_1|>
x = self.x
y = self.y
z = self.z
return math.sqrt((new_point.x - x) ** 2 + (new_point.y - y) ** 2 + (new_point.z - z) ** 2)
<|end_body_1|>
| Creates Point Objects that have three coordinates: x, y, z. | Point | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Point:
"""Creates Point Objects that have three coordinates: x, y, z."""
def __init__(self, x, y, z):
"""Initializes x, y, z."""
<|body_0|>
def distanceTo(self, new_point):
"""Returns distance between two points."""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_75kplus_train_004285 | 3,603 | no_license | [
{
"docstring": "Initializes x, y, z.",
"name": "__init__",
"signature": "def __init__(self, x, y, z)"
},
{
"docstring": "Returns distance between two points.",
"name": "distanceTo",
"signature": "def distanceTo(self, new_point)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018115 | Implement the Python class `Point` described below.
Class description:
Creates Point Objects that have three coordinates: x, y, z.
Method signatures and docstrings:
- def __init__(self, x, y, z): Initializes x, y, z.
- def distanceTo(self, new_point): Returns distance between two points. | Implement the Python class `Point` described below.
Class description:
Creates Point Objects that have three coordinates: x, y, z.
Method signatures and docstrings:
- def __init__(self, x, y, z): Initializes x, y, z.
- def distanceTo(self, new_point): Returns distance between two points.
<|skeleton|>
class Point:
... | 6b247ddca2718e5c6b39021733c2cd554a990597 | <|skeleton|>
class Point:
"""Creates Point Objects that have three coordinates: x, y, z."""
def __init__(self, x, y, z):
"""Initializes x, y, z."""
<|body_0|>
def distanceTo(self, new_point):
"""Returns distance between two points."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Point:
"""Creates Point Objects that have three coordinates: x, y, z."""
def __init__(self, x, y, z):
"""Initializes x, y, z."""
self.x = x
self.y = y
self.z = z
def distanceTo(self, new_point):
"""Returns distance between two points."""
x = self.x
... | the_stack_v2_python_sparse | lab5_ab.py | mnuzen/cs1 | train | 0 |
3f011496a21801fdc6d9da6cdfdcff8843f4af66 | [
"super().__init__(env)\nself.get_robot_act = get_robot_act\nassert 0 <= beta <= 1\nself.beta = beta\nself.traj_accum = None\nself.save_dir = save_dir\nself._last_obs = None\nself._done_before = True\nself._is_reset = False",
"self.traj_accum = rollout.TrajectoryAccumulator()\nobs = self.env.reset()\nself._last_ob... | <|body_start_0|>
super().__init__(env)
self.get_robot_act = get_robot_act
assert 0 <= beta <= 1
self.beta = beta
self.traj_accum = None
self.save_dir = save_dir
self._last_obs = None
self._done_before = True
self._is_reset = False
<|end_body_0|>
<... | Wrapper around the `.step()` and `.reset()` of an env that allows DAgger to inject a "robot" action (i.e. an action from the imitation policy) that overrides the action given to `.step()` when necessary. Will also automatically save trajectories. | InteractiveTrajectoryCollector | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InteractiveTrajectoryCollector:
"""Wrapper around the `.step()` and `.reset()` of an env that allows DAgger to inject a "robot" action (i.e. an action from the imitation policy) that overrides the action given to `.step()` when necessary. Will also automatically save trajectories."""
def __i... | stack_v2_sparse_classes_75kplus_train_004286 | 15,535 | permissive | [
{
"docstring": "Trajectory collector constructor. Args: env: environment to sample trajectories from. get_robot_act: get a single robot action that can be substituted for human action. Takes a single observation as input & returns a single action. beta: fraction of the time to use action given to .step() instea... | 3 | null | Implement the Python class `InteractiveTrajectoryCollector` described below.
Class description:
Wrapper around the `.step()` and `.reset()` of an env that allows DAgger to inject a "robot" action (i.e. an action from the imitation policy) that overrides the action given to `.step()` when necessary. Will also automatic... | Implement the Python class `InteractiveTrajectoryCollector` described below.
Class description:
Wrapper around the `.step()` and `.reset()` of an env that allows DAgger to inject a "robot" action (i.e. an action from the imitation policy) that overrides the action given to `.step()` when necessary. Will also automatic... | abe23cf28c62d875774469e431858977631b5550 | <|skeleton|>
class InteractiveTrajectoryCollector:
"""Wrapper around the `.step()` and `.reset()` of an env that allows DAgger to inject a "robot" action (i.e. an action from the imitation policy) that overrides the action given to `.step()` when necessary. Will also automatically save trajectories."""
def __i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InteractiveTrajectoryCollector:
"""Wrapper around the `.step()` and `.reset()` of an env that allows DAgger to inject a "robot" action (i.e. an action from the imitation policy) that overrides the action given to `.step()` when necessary. Will also automatically save trajectories."""
def __init__(self, e... | the_stack_v2_python_sparse | libraries/imitation/src/imitation/algorithms/dagger.py | sen-pai/Not-GAIL | train | 0 |
db81a34fea7d975f6789b013737d7250bb5eba8c | [
"super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=timedelta(seconds=DEFAULT_SCAN_INTERVAL))\nself._api = HERERoutingApi(api_key)\nself.config = config",
"origin, destination, arrival, departure = prepare_parameters(self.hass, self.config)\nroute_mode = RoutingMode.FAST if self.config.route_mode == ROU... | <|body_start_0|>
super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=timedelta(seconds=DEFAULT_SCAN_INTERVAL))
self._api = HERERoutingApi(api_key)
self.config = config
<|end_body_0|>
<|body_start_1|>
origin, destination, arrival, departure = prepare_parameters(self.hass, self.c... | here_routing DataUpdateCoordinator. | HERERoutingDataUpdateCoordinator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HERERoutingDataUpdateCoordinator:
"""here_routing DataUpdateCoordinator."""
def __init__(self, hass: HomeAssistant, api_key: str, config: HERETravelTimeConfig) -> None:
"""Initialize."""
<|body_0|>
async def _async_update_data(self) -> HERETravelTimeData:
"""Get ... | stack_v2_sparse_classes_75kplus_train_004287 | 12,892 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, api_key: str, config: HERETravelTimeConfig) -> None"
},
{
"docstring": "Get the latest data from the HERE Routing API.",
"name": "_async_update_data",
"signature": "async def _async_up... | 3 | null | Implement the Python class `HERERoutingDataUpdateCoordinator` described below.
Class description:
here_routing DataUpdateCoordinator.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, api_key: str, config: HERETravelTimeConfig) -> None: Initialize.
- async def _async_update_data(self) -> HER... | Implement the Python class `HERERoutingDataUpdateCoordinator` described below.
Class description:
here_routing DataUpdateCoordinator.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, api_key: str, config: HERETravelTimeConfig) -> None: Initialize.
- async def _async_update_data(self) -> HER... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class HERERoutingDataUpdateCoordinator:
"""here_routing DataUpdateCoordinator."""
def __init__(self, hass: HomeAssistant, api_key: str, config: HERETravelTimeConfig) -> None:
"""Initialize."""
<|body_0|>
async def _async_update_data(self) -> HERETravelTimeData:
"""Get ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HERERoutingDataUpdateCoordinator:
"""here_routing DataUpdateCoordinator."""
def __init__(self, hass: HomeAssistant, api_key: str, config: HERETravelTimeConfig) -> None:
"""Initialize."""
super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=timedelta(seconds=DEFAULT_SCAN_INTERVAL))... | the_stack_v2_python_sparse | homeassistant/components/here_travel_time/coordinator.py | home-assistant/core | train | 35,501 |
92e681dc31b1f699c166c3367b7e34f444b8d761 | [
"self.snake = collections.deque([(0, 0)])\nself.food = collections.deque(food)\nself.width = width\nself.height = height\nself.d = {'U': (-1, 0), 'L': (0, -1), 'R': (0, 1), 'D': (1, 0)}",
"\"\"\"\n 1. check out of boundary\n 2. deque to store snake, add to the top and delete the last one in the dequ... | <|body_start_0|>
self.snake = collections.deque([(0, 0)])
self.food = collections.deque(food)
self.width = width
self.height = height
self.d = {'U': (-1, 0), 'L': (0, -1), 'R': (0, 1), 'D': (1, 0)}
<|end_body_0|>
<|body_start_1|>
"""
1. check out of bound... | SnakeGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t... | stack_v2_sparse_classes_75kplus_train_004288 | 2,091 | no_license | [
{
"docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].",
"name": "__init__",
"signature": "def __init__(self, widt... | 2 | stack_v2_sparse_classes_30k_train_043117 | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -... | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -... | e431ff831ddd5f26891e6ee4506a20d7972b4f02 | <|skeleton|>
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is a... | the_stack_v2_python_sparse | leetcode_python/353.Design_Snake_Game.py | zihuaweng/leetcode-solutions | train | 4 | |
2a64914a782066498ca488e831698892cbece572 | [
"super().__init__()\nlogging_levels = {val: val for val in LEVELS.values()}\nlogging_levels.update(LEVELS)\nself._ignore_exceptions = []\nfor exc_name, exc_level in ignore_exceptions:\n try:\n self._ignore_exceptions.append((logging_levels[exc_level], exc_name))\n except KeyError as err:\n raise... | <|body_start_0|>
super().__init__()
logging_levels = {val: val for val in LEVELS.values()}
logging_levels.update(LEVELS)
self._ignore_exceptions = []
for exc_name, exc_level in ignore_exceptions:
try:
self._ignore_exceptions.append((logging_levels[exc_... | Filter out the specified exceptions with specified logging level. | ExceptionFilter | [
"BSD-2-Clause",
"BSD-3-Clause",
"BSD-2-Clause-Views"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExceptionFilter:
"""Filter out the specified exceptions with specified logging level."""
def __init__(self, ignore_exceptions):
"""Configure filtering out of the specified exceptions with specified logging level. Note if there are multiple exceptions that have the same name this will... | stack_v2_sparse_classes_75kplus_train_004289 | 1,804 | permissive | [
{
"docstring": "Configure filtering out of the specified exceptions with specified logging level. Note if there are multiple exceptions that have the same name this will filter out all exceptions with that name. ignore_exceptions: a tuple of tuples ((exception name, loglevel)) example: ((\"ReadTimeout\", \"WARN... | 2 | stack_v2_sparse_classes_30k_train_004028 | Implement the Python class `ExceptionFilter` described below.
Class description:
Filter out the specified exceptions with specified logging level.
Method signatures and docstrings:
- def __init__(self, ignore_exceptions): Configure filtering out of the specified exceptions with specified logging level. Note if there ... | Implement the Python class `ExceptionFilter` described below.
Class description:
Filter out the specified exceptions with specified logging level.
Method signatures and docstrings:
- def __init__(self, ignore_exceptions): Configure filtering out of the specified exceptions with specified logging level. Note if there ... | 232446d776fdb906d2fb253cf0a409c6813a08d6 | <|skeleton|>
class ExceptionFilter:
"""Filter out the specified exceptions with specified logging level."""
def __init__(self, ignore_exceptions):
"""Configure filtering out of the specified exceptions with specified logging level. Note if there are multiple exceptions that have the same name this will... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExceptionFilter:
"""Filter out the specified exceptions with specified logging level."""
def __init__(self, ignore_exceptions):
"""Configure filtering out of the specified exceptions with specified logging level. Note if there are multiple exceptions that have the same name this will filter out a... | the_stack_v2_python_sparse | h/util/logging_filters.py | hypothesis/h | train | 2,558 |
881d57eadf9dcb97da5282035cd9ef88ba6679b2 | [
"red = randint(0, 255)\ngreen = randint(0, 255)\nblue = randint(0, 255)\np1 = Point(position.getX() - 40, position.getY() - 20)\np2 = Point(position.getX() + 40, position.getY() + 20)\nself.body = Oval(p1, p2)\nself.body.setFill(color_rgb(red, green, blue))\np1 = Point(position.getX() + 30, position.getY() - 30)\np... | <|body_start_0|>
red = randint(0, 255)
green = randint(0, 255)
blue = randint(0, 255)
p1 = Point(position.getX() - 40, position.getY() - 20)
p2 = Point(position.getX() + 40, position.getY() + 20)
self.body = Oval(p1, p2)
self.body.setFill(color_rgb(red, green, blu... | Definition for a fish with a body, eye, and tail | Fish | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fish:
"""Definition for a fish with a body, eye, and tail"""
def __init__(self, win, position):
"""constructs a fish made of 1 oval centered at `position`, a second oval for the tail, and a circle for the eye"""
<|body_0|>
def draw(self, win):
"""draw the fish to... | stack_v2_sparse_classes_75kplus_train_004290 | 6,450 | no_license | [
{
"docstring": "constructs a fish made of 1 oval centered at `position`, a second oval for the tail, and a circle for the eye",
"name": "__init__",
"signature": "def __init__(self, win, position)"
},
{
"docstring": "draw the fish to the window",
"name": "draw",
"signature": "def draw(sel... | 3 | stack_v2_sparse_classes_30k_test_001447 | Implement the Python class `Fish` described below.
Class description:
Definition for a fish with a body, eye, and tail
Method signatures and docstrings:
- def __init__(self, win, position): constructs a fish made of 1 oval centered at `position`, a second oval for the tail, and a circle for the eye
- def draw(self, w... | Implement the Python class `Fish` described below.
Class description:
Definition for a fish with a body, eye, and tail
Method signatures and docstrings:
- def __init__(self, win, position): constructs a fish made of 1 oval centered at `position`, a second oval for the tail, and a circle for the eye
- def draw(self, w... | 7ba30d731917fccaa1f81e984fc6ac2c07df2494 | <|skeleton|>
class Fish:
"""Definition for a fish with a body, eye, and tail"""
def __init__(self, win, position):
"""constructs a fish made of 1 oval centered at `position`, a second oval for the tail, and a circle for the eye"""
<|body_0|>
def draw(self, win):
"""draw the fish to... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Fish:
"""Definition for a fish with a body, eye, and tail"""
def __init__(self, win, position):
"""constructs a fish made of 1 oval centered at `position`, a second oval for the tail, and a circle for the eye"""
red = randint(0, 255)
green = randint(0, 255)
blue = randint(... | the_stack_v2_python_sparse | aquarium.py | jossshhuaa/scs-noonan-labs-2019 | train | 0 |
098e9c483b1d043e0920697eab1885c3b8f972eb | [
"self.logger = logging.getLogger(__name__)\nself.Name = name\nself.Drawing_type = drawing_type\nself.Text_presentation = {}\nself.Underlays = set()\nself.Shape_presentation = {}\nself.Closed_shape_fill = {}\nself.Corner_spec = {}\nself.logger.info(f'Loading assets for Presentation [{self.Name}]')\nself.load_text_pr... | <|body_start_0|>
self.logger = logging.getLogger(__name__)
self.Name = name
self.Drawing_type = drawing_type
self.Text_presentation = {}
self.Underlays = set()
self.Shape_presentation = {}
self.Closed_shape_fill = {}
self.Corner_spec = {}
self.logg... | A set of compatible visual styles including fonts, colors, border widths and so forth as appropriate to a given Drawing Type form a selectable Presentation. For example, an `Executable UML State Machine Diagram` might be drawn using certain fonts for state names and possibly different colors for transient and non-trans... | Presentation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Presentation:
"""A set of compatible visual styles including fonts, colors, border widths and so forth as appropriate to a given Drawing Type form a selectable Presentation. For example, an `Executable UML State Machine Diagram` might be drawn using certain fonts for state names and possibly diff... | stack_v2_sparse_classes_75kplus_train_004291 | 3,484 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, name: str, drawing_type: str)"
},
{
"docstring": "For each text Asset in this Presentation, load its Text Presentation",
"name": "load_text_presentations",
"signature": "def load_text_presentations(self)"
... | 3 | stack_v2_sparse_classes_30k_train_020122 | Implement the Python class `Presentation` described below.
Class description:
A set of compatible visual styles including fonts, colors, border widths and so forth as appropriate to a given Drawing Type form a selectable Presentation. For example, an `Executable UML State Machine Diagram` might be drawn using certain ... | Implement the Python class `Presentation` described below.
Class description:
A set of compatible visual styles including fonts, colors, border widths and so forth as appropriate to a given Drawing Type form a selectable Presentation. For example, an `Executable UML State Machine Diagram` might be drawn using certain ... | 088e27cded9eca2cacba2c6168c03caf4b43ef72 | <|skeleton|>
class Presentation:
"""A set of compatible visual styles including fonts, colors, border widths and so forth as appropriate to a given Drawing Type form a selectable Presentation. For example, an `Executable UML State Machine Diagram` might be drawn using certain fonts for state names and possibly diff... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Presentation:
"""A set of compatible visual styles including fonts, colors, border widths and so forth as appropriate to a given Drawing Type form a selectable Presentation. For example, an `Executable UML State Machine Diagram` might be drawn using certain fonts for state names and possibly different colors ... | the_stack_v2_python_sparse | flatland/drawing_domain/presentation.py | Laurelinex/flatland-model-diagram-editor | train | 0 |
b00baeeea21f8769456e03bacbb89fed027f136c | [
"threading.Thread.__init__(self, name='output')\nself.queues = queue\nself.date_time = date_time\nself.out_func = out_func\nself.out_frequency = out_frequency\nself.nx = nx\nself.ny = ny\nlname = '{}.{}'.format(__name__, 'output')\nself._logger = logging.getLogger(lname)\nself._logger.debug('Initialized output thre... | <|body_start_0|>
threading.Thread.__init__(self, name='output')
self.queues = queue
self.date_time = date_time
self.out_func = out_func
self.out_frequency = out_frequency
self.nx = nx
self.ny = ny
lname = '{}.{}'.format(__name__, 'output')
self._lo... | Takes values from the queue and outputs using 'out_func' | QueueOutput | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain",
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QueueOutput:
"""Takes values from the queue and outputs using 'out_func'"""
def __init__(self, queue, date_time, out_func, out_frequency, nx, ny):
"""Args: date_time: array of date_time queue: dict of the queue"""
<|body_0|>
def run(self):
"""Output the desired v... | stack_v2_sparse_classes_75kplus_train_004292 | 9,600 | permissive | [
{
"docstring": "Args: date_time: array of date_time queue: dict of the queue",
"name": "__init__",
"signature": "def __init__(self, queue, date_time, out_func, out_frequency, nx, ny)"
},
{
"docstring": "Output the desired variables to a file. Go through the date times and look for when all the q... | 2 | stack_v2_sparse_classes_30k_train_006234 | Implement the Python class `QueueOutput` described below.
Class description:
Takes values from the queue and outputs using 'out_func'
Method signatures and docstrings:
- def __init__(self, queue, date_time, out_func, out_frequency, nx, ny): Args: date_time: array of date_time queue: dict of the queue
- def run(self):... | Implement the Python class `QueueOutput` described below.
Class description:
Takes values from the queue and outputs using 'out_func'
Method signatures and docstrings:
- def __init__(self, queue, date_time, out_func, out_frequency, nx, ny): Args: date_time: array of date_time queue: dict of the queue
- def run(self):... | 465d42cca85820e76a50bc311d101c7dc506df8c | <|skeleton|>
class QueueOutput:
"""Takes values from the queue and outputs using 'out_func'"""
def __init__(self, queue, date_time, out_func, out_frequency, nx, ny):
"""Args: date_time: array of date_time queue: dict of the queue"""
<|body_0|>
def run(self):
"""Output the desired v... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QueueOutput:
"""Takes values from the queue and outputs using 'out_func'"""
def __init__(self, queue, date_time, out_func, out_frequency, nx, ny):
"""Args: date_time: array of date_time queue: dict of the queue"""
threading.Thread.__init__(self, name='output')
self.queues = queue
... | the_stack_v2_python_sparse | smrf/utils/queue.py | USDA-ARS-NWRC/smrf | train | 9 |
dd9c6a80e3cdb9dad37839d2c6d98e65e3e248d4 | [
"if type(FocalPlaneInfo) == type(None):\n self.FocalPlaneInfo = [{'xpos': 0.0, 'ypos': 0.0, 'Pf': 0, 'Px': 0, 'Py': 0, 'Pc': 0, 'Pn': 0, 'Pa': 0, 'Pb': 0}]\nelse:\n self.FocalPlaneInfo = FocalPlaneInfo\nif type(ReceiverInfo) == type(None):\n self.ReceiverInfo = [{'sigma': 1.0, 'fknee': 1.0, 'SampRate': 100... | <|body_start_0|>
if type(FocalPlaneInfo) == type(None):
self.FocalPlaneInfo = [{'xpos': 0.0, 'ypos': 0.0, 'Pf': 0, 'Px': 0, 'Py': 0, 'Pc': 0, 'Pn': 0, 'Pa': 0, 'Pb': 0}]
else:
self.FocalPlaneInfo = FocalPlaneInfo
if type(ReceiverInfo) == type(None):
self.Recei... | Telescope | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Telescope:
def __init__(self, FocalPlaneInfo=None, ReceiverInfo=None, SkyMap=None, Healpix=False):
"""Simulated Telescope Arguments ObsInfo-- List of user defined observations KeyWord Arguments FocalPlaneInfo -- Information on focal positions of horns and TPoint values ReceiverInfo -- In... | stack_v2_sparse_classes_75kplus_train_004293 | 2,432 | no_license | [
{
"docstring": "Simulated Telescope Arguments ObsInfo-- List of user defined observations KeyWord Arguments FocalPlaneInfo -- Information on focal positions of horns and TPoint values ReceiverInfo -- Information of receiver noise and 1/f characteristics SkyMap -- Fits file containing image to be sampled",
"... | 2 | stack_v2_sparse_classes_30k_train_037455 | Implement the Python class `Telescope` described below.
Class description:
Implement the Telescope class.
Method signatures and docstrings:
- def __init__(self, FocalPlaneInfo=None, ReceiverInfo=None, SkyMap=None, Healpix=False): Simulated Telescope Arguments ObsInfo-- List of user defined observations KeyWord Argume... | Implement the Python class `Telescope` described below.
Class description:
Implement the Telescope class.
Method signatures and docstrings:
- def __init__(self, FocalPlaneInfo=None, ReceiverInfo=None, SkyMap=None, Healpix=False): Simulated Telescope Arguments ObsInfo-- List of user defined observations KeyWord Argume... | ef7caf1b05880a4a2f4c1c12ca439014f82dfe6b | <|skeleton|>
class Telescope:
def __init__(self, FocalPlaneInfo=None, ReceiverInfo=None, SkyMap=None, Healpix=False):
"""Simulated Telescope Arguments ObsInfo-- List of user defined observations KeyWord Arguments FocalPlaneInfo -- Information on focal positions of horns and TPoint values ReceiverInfo -- In... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Telescope:
def __init__(self, FocalPlaneInfo=None, ReceiverInfo=None, SkyMap=None, Healpix=False):
"""Simulated Telescope Arguments ObsInfo-- List of user defined observations KeyWord Arguments FocalPlaneInfo -- Information on focal positions of horns and TPoint values ReceiverInfo -- Information of r... | the_stack_v2_python_sparse | SIMTELE/Telescope.py | SharperJBCA/MFI-Pipeline | train | 0 | |
23721ffe77c1012c5535614b99606f88b78dbb7d | [
"assert False, logger.error('Joint generator not functional')\nself.config = config\nself.is_sub_model = is_sub_model\nself.step = 0\nself.stage = stage\nself.train = self.stage == 'train'\nself.teacher_forcing = teacher_forcing\nself.word_embedding = word_embedding\nassert self.stage in ['train', 'test', 'val', 'i... | <|body_start_0|>
assert False, logger.error('Joint generator not functional')
self.config = config
self.is_sub_model = is_sub_model
self.step = 0
self.stage = stage
self.train = self.stage == 'train'
self.teacher_forcing = teacher_forcing
self.word_embeddi... | @NOT FUNCTIONAL! @brief: The conditional generator. In the first edition, let's assume the image embedding vector is conditioned to generate the text, and the text vector is conditioned to generate the image (we have more options though) @components: def __init__ def build_models | joint_generator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class joint_generator:
"""@NOT FUNCTIONAL! @brief: The conditional generator. In the first edition, let's assume the image embedding vector is conditioned to generate the text, and the text vector is conditioned to generate the image (we have more options though) @components: def __init__ def build_mod... | stack_v2_sparse_classes_75kplus_train_004294 | 15,550 | no_license | [
{
"docstring": "@brief: The initialization of the model. we use a config file to store the information of configuration",
"name": "__init__",
"signature": "def __init__(self, config, stage='train', is_sub_model=True, teacher_forcing=True, word_embedding=None)"
},
{
"docstring": "@brief: build th... | 2 | stack_v2_sparse_classes_30k_train_021499 | Implement the Python class `joint_generator` described below.
Class description:
@NOT FUNCTIONAL! @brief: The conditional generator. In the first edition, let's assume the image embedding vector is conditioned to generate the text, and the text vector is conditioned to generate the image (we have more options though) ... | Implement the Python class `joint_generator` described below.
Class description:
@NOT FUNCTIONAL! @brief: The conditional generator. In the first edition, let's assume the image embedding vector is conditioned to generate the text, and the text vector is conditioned to generate the image (we have more options though) ... | 71bf42b89308b56113c12096d2280c02abad9e84 | <|skeleton|>
class joint_generator:
"""@NOT FUNCTIONAL! @brief: The conditional generator. In the first edition, let's assume the image embedding vector is conditioned to generate the text, and the text vector is conditioned to generate the image (we have more options though) @components: def __init__ def build_mod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class joint_generator:
"""@NOT FUNCTIONAL! @brief: The conditional generator. In the first edition, let's assume the image embedding vector is conditioned to generate the text, and the text vector is conditioned to generate the image (we have more options though) @components: def __init__ def build_models"""
d... | the_stack_v2_python_sparse | model/network.py | WilsonWangTHU/gan_playground | train | 0 |
f9704242a4cf79534323fa8c824f8e11e5ec28b3 | [
"len_a = len(arr)\nif len_a <= 1:\n return len_a\ndp = [[1, 1] for i in range(len_a)]\nres = 1\nfor i in range(1, len_a):\n if arr[i] < arr[i - 1]:\n dp[i][0] = dp[i - 1][1] + 1\n res = max(res, dp[i][0])\n elif arr[i - 1] < arr[i]:\n dp[i][1] = dp[i - 1][0] + 1\n res = max(res,... | <|body_start_0|>
len_a = len(arr)
if len_a <= 1:
return len_a
dp = [[1, 1] for i in range(len_a)]
res = 1
for i in range(1, len_a):
if arr[i] < arr[i - 1]:
dp[i][0] = dp[i - 1][1] + 1
res = max(res, dp[i][0])
eli... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxTurbulenceSize(self, arr: List[int]) -> int:
"""执行用时: 312 ms , 在所有 Python3 提交中击败了 5.02% 的用户 内存消耗: 19.6 MB , 在所有 Python3 提交中击败了 8.85% 的用户"""
<|body_0|>
def maxTurbulenceSize1(self, arr: List[int]) -> int:
"""执行用时: 140 ms , 在所有 Python3 提交中击败了 84.72% 的用... | stack_v2_sparse_classes_75kplus_train_004295 | 2,439 | no_license | [
{
"docstring": "执行用时: 312 ms , 在所有 Python3 提交中击败了 5.02% 的用户 内存消耗: 19.6 MB , 在所有 Python3 提交中击败了 8.85% 的用户",
"name": "maxTurbulenceSize",
"signature": "def maxTurbulenceSize(self, arr: List[int]) -> int"
},
{
"docstring": "执行用时: 140 ms , 在所有 Python3 提交中击败了 84.72% 的用户 内存消耗: 18 MB , 在所有 Python3 提交中击... | 2 | stack_v2_sparse_classes_30k_train_052197 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxTurbulenceSize(self, arr: List[int]) -> int: 执行用时: 312 ms , 在所有 Python3 提交中击败了 5.02% 的用户 内存消耗: 19.6 MB , 在所有 Python3 提交中击败了 8.85% 的用户
- def maxTurbulenceSize1(self, arr: L... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxTurbulenceSize(self, arr: List[int]) -> int: 执行用时: 312 ms , 在所有 Python3 提交中击败了 5.02% 的用户 内存消耗: 19.6 MB , 在所有 Python3 提交中击败了 8.85% 的用户
- def maxTurbulenceSize1(self, arr: L... | d613ed8a5a2c15ace7d513965b372d128845d66a | <|skeleton|>
class Solution:
def maxTurbulenceSize(self, arr: List[int]) -> int:
"""执行用时: 312 ms , 在所有 Python3 提交中击败了 5.02% 的用户 内存消耗: 19.6 MB , 在所有 Python3 提交中击败了 8.85% 的用户"""
<|body_0|>
def maxTurbulenceSize1(self, arr: List[int]) -> int:
"""执行用时: 140 ms , 在所有 Python3 提交中击败了 84.72% 的用... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxTurbulenceSize(self, arr: List[int]) -> int:
"""执行用时: 312 ms , 在所有 Python3 提交中击败了 5.02% 的用户 内存消耗: 19.6 MB , 在所有 Python3 提交中击败了 8.85% 的用户"""
len_a = len(arr)
if len_a <= 1:
return len_a
dp = [[1, 1] for i in range(len_a)]
res = 1
for ... | the_stack_v2_python_sparse | 最长湍流子数组.py | nomboy/leetcode | train | 0 | |
465ed60760e6bb8e6b95f85300273aca358d4610 | [
"dit.pageclasses.DITPage.AssertBasePermission(self, req_info)\nif not req_info.demetrius_perms.Check(permissions.EDIT_PROJECT):\n raise permissions.PermissionException('You are not allowed to administer this project')",
"page_data = {'admin_tab_mode': demetrius.constants.ADMIN_TAB_ISSUES}\nconfig = dit.helpers... | <|body_start_0|>
dit.pageclasses.DITPage.AssertBasePermission(self, req_info)
if not req_info.demetrius_perms.Check(permissions.EDIT_PROJECT):
raise permissions.PermissionException('You are not allowed to administer this project')
<|end_body_0|>
<|body_start_1|>
page_data = {'admin_... | A page and form allowing project owners to configure the issue tracker. | ProjectAdminIssues | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectAdminIssues:
"""A page and form allowing project owners to configure the issue tracker."""
def AssertBasePermission(self, req_info):
"""Check whether the user has any permission to visit this page. Args: req_info: commonly used info parsed from the request."""
<|body_0... | stack_v2_sparse_classes_75kplus_train_004296 | 6,058 | permissive | [
{
"docstring": "Check whether the user has any permission to visit this page. Args: req_info: commonly used info parsed from the request.",
"name": "AssertBasePermission",
"signature": "def AssertBasePermission(self, req_info)"
},
{
"docstring": "Build up a dictionary of data values to use when ... | 4 | null | Implement the Python class `ProjectAdminIssues` described below.
Class description:
A page and form allowing project owners to configure the issue tracker.
Method signatures and docstrings:
- def AssertBasePermission(self, req_info): Check whether the user has any permission to visit this page. Args: req_info: common... | Implement the Python class `ProjectAdminIssues` described below.
Class description:
A page and form allowing project owners to configure the issue tracker.
Method signatures and docstrings:
- def AssertBasePermission(self, req_info): Check whether the user has any permission to visit this page. Args: req_info: common... | 104069e83c0c6eafc70bd0a8a4d3bf0b57b00e1d | <|skeleton|>
class ProjectAdminIssues:
"""A page and form allowing project owners to configure the issue tracker."""
def AssertBasePermission(self, req_info):
"""Check whether the user has any permission to visit this page. Args: req_info: commonly used info parsed from the request."""
<|body_0... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProjectAdminIssues:
"""A page and form allowing project owners to configure the issue tracker."""
def AssertBasePermission(self, req_info):
"""Check whether the user has any permission to visit this page. Args: req_info: commonly used info parsed from the request."""
dit.pageclasses.DITPa... | the_stack_v2_python_sparse | src/dit/issueadmin.py | scashin133/longhouse | train | 0 |
602861e02c85ec6f0bda94c74be302830841db2e | [
"logger.info('Overriding class: Space -> HyperComplexSpace.')\nlower_bound = np.zeros(n_variables)\nupper_bound = np.ones(n_variables)\nsuper(HyperComplexSpace, self).__init__(n_agents, n_variables, n_dimensions, lower_bound, upper_bound, mapping)\nself.build()\nlogger.info('Class overrided.')",
"for agent in sel... | <|body_start_0|>
logger.info('Overriding class: Space -> HyperComplexSpace.')
lower_bound = np.zeros(n_variables)
upper_bound = np.ones(n_variables)
super(HyperComplexSpace, self).__init__(n_agents, n_variables, n_dimensions, lower_bound, upper_bound, mapping)
self.build()
... | An HyperComplexSpace class that will hold agents, variables and methods related to the hypercomplex search space. | HyperComplexSpace | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HyperComplexSpace:
"""An HyperComplexSpace class that will hold agents, variables and methods related to the hypercomplex search space."""
def __init__(self, n_agents: int, n_variables: int, n_dimensions: int, mapping: Optional[List[str]]=None) -> None:
"""Initialization method. Args... | stack_v2_sparse_classes_75kplus_train_004297 | 1,466 | permissive | [
{
"docstring": "Initialization method. Args: n_agents: Number of agents. n_variables: Number of decision variables. n_dimensions: Number of search space dimensions. mapping: String-based identifiers for mapping variables' names.",
"name": "__init__",
"signature": "def __init__(self, n_agents: int, n_var... | 2 | stack_v2_sparse_classes_30k_train_013160 | Implement the Python class `HyperComplexSpace` described below.
Class description:
An HyperComplexSpace class that will hold agents, variables and methods related to the hypercomplex search space.
Method signatures and docstrings:
- def __init__(self, n_agents: int, n_variables: int, n_dimensions: int, mapping: Optio... | Implement the Python class `HyperComplexSpace` described below.
Class description:
An HyperComplexSpace class that will hold agents, variables and methods related to the hypercomplex search space.
Method signatures and docstrings:
- def __init__(self, n_agents: int, n_variables: int, n_dimensions: int, mapping: Optio... | 7326a887ed8e3858bc99c8815048d56d02edf88c | <|skeleton|>
class HyperComplexSpace:
"""An HyperComplexSpace class that will hold agents, variables and methods related to the hypercomplex search space."""
def __init__(self, n_agents: int, n_variables: int, n_dimensions: int, mapping: Optional[List[str]]=None) -> None:
"""Initialization method. Args... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HyperComplexSpace:
"""An HyperComplexSpace class that will hold agents, variables and methods related to the hypercomplex search space."""
def __init__(self, n_agents: int, n_variables: int, n_dimensions: int, mapping: Optional[List[str]]=None) -> None:
"""Initialization method. Args: n_agents: N... | the_stack_v2_python_sparse | opytimizer/spaces/hyper_complex.py | gugarosa/opytimizer | train | 602 |
79609da4ebb7b41e9546575df82cac770fc8e609 | [
"permissions = [IsAuthenticated]\nif self.action in ['update', 'partial_update', 'destroy']:\n permissions.append(IsRecipeOwner)\nreturn [permission() for permission in permissions]",
"if self.action == 'create':\n return CreateRecipeSerializer\nelse:\n return RecipeModelSerializer",
"fridge_ingredient... | <|body_start_0|>
permissions = [IsAuthenticated]
if self.action in ['update', 'partial_update', 'destroy']:
permissions.append(IsRecipeOwner)
return [permission() for permission in permissions]
<|end_body_0|>
<|body_start_1|>
if self.action == 'create':
return Cr... | Recipes viewset. | RecipesViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecipesViewSet:
"""Recipes viewset."""
def get_permissions(self):
"""Assign permissions based on action."""
<|body_0|>
def get_serializer_class(self):
"""Return serializer class based on action."""
<|body_1|>
def possible_recipes(self, request):
... | stack_v2_sparse_classes_75kplus_train_004298 | 2,893 | no_license | [
{
"docstring": "Assign permissions based on action.",
"name": "get_permissions",
"signature": "def get_permissions(self)"
},
{
"docstring": "Return serializer class based on action.",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": ... | 4 | stack_v2_sparse_classes_30k_train_054288 | Implement the Python class `RecipesViewSet` described below.
Class description:
Recipes viewset.
Method signatures and docstrings:
- def get_permissions(self): Assign permissions based on action.
- def get_serializer_class(self): Return serializer class based on action.
- def possible_recipes(self, request): Returns ... | Implement the Python class `RecipesViewSet` described below.
Class description:
Recipes viewset.
Method signatures and docstrings:
- def get_permissions(self): Assign permissions based on action.
- def get_serializer_class(self): Return serializer class based on action.
- def possible_recipes(self, request): Returns ... | 5cd1b3155c4542d0479948f39701b539497e28f7 | <|skeleton|>
class RecipesViewSet:
"""Recipes viewset."""
def get_permissions(self):
"""Assign permissions based on action."""
<|body_0|>
def get_serializer_class(self):
"""Return serializer class based on action."""
<|body_1|>
def possible_recipes(self, request):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RecipesViewSet:
"""Recipes viewset."""
def get_permissions(self):
"""Assign permissions based on action."""
permissions = [IsAuthenticated]
if self.action in ['update', 'partial_update', 'destroy']:
permissions.append(IsRecipeOwner)
return [permission() for per... | the_stack_v2_python_sparse | apps/recipes/views/recipes.py | NicolasTerroni/MyFridgeAPI | train | 0 |
c39dfa2fa2f23ea740523cf785442a88ab227687 | [
"qs = super().get_queryset(request)\nid_list = request.GET.getlist(BULK_EDIT_VAR_IDS, [])\nif id_list:\n qs = qs.filter(pk__in=id_list)\nreturn qs",
"self.list_editable = []\nif request.GET.get(BULK_EDIT_VAR):\n bulk_list_display = self.bulk_edit_list\n bulk_list_edit = self.bulk_edit_list\n if issubc... | <|body_start_0|>
qs = super().get_queryset(request)
id_list = request.GET.getlist(BULK_EDIT_VAR_IDS, [])
if id_list:
qs = qs.filter(pk__in=id_list)
return qs
<|end_body_0|>
<|body_start_1|>
self.list_editable = []
if request.GET.get(BULK_EDIT_VAR):
... | BulkEditChangeListMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BulkEditChangeListMixin:
def get_queryset(self, request):
"""Override django admin get queryset method."""
<|body_0|>
def get_list_display(self, request):
"""Override django admin get list display method. Set new values for fields list_editable and list_display."""
... | stack_v2_sparse_classes_75kplus_train_004299 | 21,334 | permissive | [
{
"docstring": "Override django admin get queryset method.",
"name": "get_queryset",
"signature": "def get_queryset(self, request)"
},
{
"docstring": "Override django admin get list display method. Set new values for fields list_editable and list_display.",
"name": "get_list_display",
"s... | 3 | stack_v2_sparse_classes_30k_test_001100 | Implement the Python class `BulkEditChangeListMixin` described below.
Class description:
Implement the BulkEditChangeListMixin class.
Method signatures and docstrings:
- def get_queryset(self, request): Override django admin get queryset method.
- def get_list_display(self, request): Override django admin get list di... | Implement the Python class `BulkEditChangeListMixin` described below.
Class description:
Implement the BulkEditChangeListMixin class.
Method signatures and docstrings:
- def get_queryset(self, request): Override django admin get queryset method.
- def get_list_display(self, request): Override django admin get list di... | b4a72356f527b1f12c7babd7465d2d7fa3ffb0d3 | <|skeleton|>
class BulkEditChangeListMixin:
def get_queryset(self, request):
"""Override django admin get queryset method."""
<|body_0|>
def get_list_display(self, request):
"""Override django admin get list display method. Set new values for fields list_editable and list_display."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BulkEditChangeListMixin:
def get_queryset(self, request):
"""Override django admin get queryset method."""
qs = super().get_queryset(request)
id_list = request.GET.getlist(BULK_EDIT_VAR_IDS, [])
if id_list:
qs = qs.filter(pk__in=id_list)
return qs
def g... | the_stack_v2_python_sparse | src/ralph/admin/mixins.py | allegro/ralph | train | 1,970 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.