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 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e66c8f45a34c77e8c6473086cf955d51b621db6a | [
"super(PickingResult, self).__init__(item, indices)\nself._objectPositions = numpy.array(positions, copy=False, dtype=numpy.float64)\nprimitive = item._getScenePrimitive()\nself._objectToSceneTransform = primitive.objectToSceneTransform\nself._objectToNDCTransform = primitive.objectToNDCTransform\nself._scenePositi... | <|body_start_0|>
super(PickingResult, self).__init__(item, indices)
self._objectPositions = numpy.array(positions, copy=False, dtype=numpy.float64)
primitive = item._getScenePrimitive()
self._objectToSceneTransform = primitive.objectToSceneTransform
self._objectToNDCTransform = p... | Class to access picking information in a 3D scene. | PickingResult | [
"MIT",
"LicenseRef-scancode-public-domain-disclaimer",
"CC0-1.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PickingResult:
"""Class to access picking information in a 3D scene."""
def __init__(self, item, positions, indices=None, fetchdata=None):
"""Init :param ~silx.gui.plot3d.items.Item3D item: The picked item :param numpy.ndarray positions: Nx3 array-like of picked positions (x, y, z) i... | stack_v2_sparse_classes_10k_train_004000 | 9,112 | permissive | [
{
"docstring": "Init :param ~silx.gui.plot3d.items.Item3D item: The picked item :param numpy.ndarray positions: Nx3 array-like of picked positions (x, y, z) in item coordinates. :param numpy.ndarray indices: Array-like of indices of picked data. Either 1D or 2D with dim0: data dimension and dim1: indices. No co... | 3 | stack_v2_sparse_classes_30k_train_004973 | Implement the Python class `PickingResult` described below.
Class description:
Class to access picking information in a 3D scene.
Method signatures and docstrings:
- def __init__(self, item, positions, indices=None, fetchdata=None): Init :param ~silx.gui.plot3d.items.Item3D item: The picked item :param numpy.ndarray ... | Implement the Python class `PickingResult` described below.
Class description:
Class to access picking information in a 3D scene.
Method signatures and docstrings:
- def __init__(self, item, positions, indices=None, fetchdata=None): Init :param ~silx.gui.plot3d.items.Item3D item: The picked item :param numpy.ndarray ... | 5e33cb69afd2a8b1cfe3183282acdd8b34c1a74f | <|skeleton|>
class PickingResult:
"""Class to access picking information in a 3D scene."""
def __init__(self, item, positions, indices=None, fetchdata=None):
"""Init :param ~silx.gui.plot3d.items.Item3D item: The picked item :param numpy.ndarray positions: Nx3 array-like of picked positions (x, y, z) i... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PickingResult:
"""Class to access picking information in a 3D scene."""
def __init__(self, item, positions, indices=None, fetchdata=None):
"""Init :param ~silx.gui.plot3d.items.Item3D item: The picked item :param numpy.ndarray positions: Nx3 array-like of picked positions (x, y, z) in item coordi... | the_stack_v2_python_sparse | src/silx/gui/plot3d/items/_pick.py | silx-kit/silx | train | 120 |
09c15b34fc1ebb4dee9252980e9fb49bcfc335f4 | [
"PygameScreen.__init__(self)\nself.menuView = MenuWithBackgroundWidget(menu, self.width * 0.4, self.height)\nself.lastScreen = lastScreen",
"screenSurface = self.lastScreen.draw()\nself.drawOnSurface(screenSurface, left=0, top=0)\nmenuSurface = self.menuView.draw()\nself.drawOnSurface(menuSurface, right=1, top=0)... | <|body_start_0|>
PygameScreen.__init__(self)
self.menuView = MenuWithBackgroundWidget(menu, self.width * 0.4, self.height)
self.lastScreen = lastScreen
<|end_body_0|>
<|body_start_1|>
screenSurface = self.lastScreen.draw()
self.drawOnSurface(screenSurface, left=0, top=0)
... | Represents the screen for the Zone Menu | ZoneMenuScreen | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZoneMenuScreen:
"""Represents the screen for the Zone Menu"""
def __init__(self, menu, lastScreen):
"""Initialize the screen"""
<|body_0|>
def drawSurface(self):
"""Draws the screen"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
PygameScreen.__... | stack_v2_sparse_classes_10k_train_004001 | 768 | no_license | [
{
"docstring": "Initialize the screen",
"name": "__init__",
"signature": "def __init__(self, menu, lastScreen)"
},
{
"docstring": "Draws the screen",
"name": "drawSurface",
"signature": "def drawSurface(self)"
}
] | 2 | null | Implement the Python class `ZoneMenuScreen` described below.
Class description:
Represents the screen for the Zone Menu
Method signatures and docstrings:
- def __init__(self, menu, lastScreen): Initialize the screen
- def drawSurface(self): Draws the screen | Implement the Python class `ZoneMenuScreen` described below.
Class description:
Represents the screen for the Zone Menu
Method signatures and docstrings:
- def __init__(self, menu, lastScreen): Initialize the screen
- def drawSurface(self): Draws the screen
<|skeleton|>
class ZoneMenuScreen:
"""Represents the sc... | 3931eee5fd04e18bb1738a0b27a4c6979dc4db01 | <|skeleton|>
class ZoneMenuScreen:
"""Represents the screen for the Zone Menu"""
def __init__(self, menu, lastScreen):
"""Initialize the screen"""
<|body_0|>
def drawSurface(self):
"""Draws the screen"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ZoneMenuScreen:
"""Represents the screen for the Zone Menu"""
def __init__(self, menu, lastScreen):
"""Initialize the screen"""
PygameScreen.__init__(self)
self.menuView = MenuWithBackgroundWidget(menu, self.width * 0.4, self.height)
self.lastScreen = lastScreen
def d... | the_stack_v2_python_sparse | src/Screen/Pygame/Menu/ZoneMenu/zone_menu_screen.py | sgtnourry/Pokemon-Project | train | 0 |
99dc51bae9e2b0277dbbee2388f3429992ad23fe | [
"if not height:\n return 0\ncount = 0\nfor i in range(max(height)):\n start = False\n tmp = 0\n for h in height:\n if h > i:\n if tmp:\n count += tmp\n tmp = 0\n start = True\n elif start:\n tmp += 1\nreturn count",
"count = ... | <|body_start_0|>
if not height:
return 0
count = 0
for i in range(max(height)):
start = False
tmp = 0
for h in height:
if h > i:
if tmp:
count += tmp
tmp = 0
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _trap(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def __trap(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
def ___trap(self, height):
""":type height: List[int] :rtype: int"""
<|... | stack_v2_sparse_classes_10k_train_004002 | 5,487 | permissive | [
{
"docstring": ":type height: List[int] :rtype: int",
"name": "_trap",
"signature": "def _trap(self, height)"
},
{
"docstring": ":type height: List[int] :rtype: int",
"name": "__trap",
"signature": "def __trap(self, height)"
},
{
"docstring": ":type height: List[int] :rtype: int"... | 6 | stack_v2_sparse_classes_30k_train_003973 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _trap(self, height): :type height: List[int] :rtype: int
- def __trap(self, height): :type height: List[int] :rtype: int
- def ___trap(self, height): :type height: List[int] ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _trap(self, height): :type height: List[int] :rtype: int
- def __trap(self, height): :type height: List[int] :rtype: int
- def ___trap(self, height): :type height: List[int] ... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _trap(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def __trap(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
def ___trap(self, height):
""":type height: List[int] :rtype: int"""
<|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def _trap(self, height):
""":type height: List[int] :rtype: int"""
if not height:
return 0
count = 0
for i in range(max(height)):
start = False
tmp = 0
for h in height:
if h > i:
if tm... | the_stack_v2_python_sparse | 42.trapping-rain-water.py | windard/leeeeee | train | 0 | |
f4390148ca2a74b34541e1e09af395c607b3f6ef | [
"self._tub = tub\nself._num_records = num_records\nself._active_loop = False",
"if is_delete:\n if not self._active_loop:\n self._tub.delete_last_n_records(self._num_records)\n self._active_loop = True\nelse:\n self._active_loop = False"
] | <|body_start_0|>
self._tub = tub
self._num_records = num_records
self._active_loop = False
<|end_body_0|>
<|body_start_1|>
if is_delete:
if not self._active_loop:
self._tub.delete_last_n_records(self._num_records)
self._active_loop = True
... | Donkey part which deletes a bunch of records from the end of tub. This allows to remove bad data already during recording. As this gets called in the vehicle loop the deletion runs only once in each continuous activation. A new execution requires to release of the input trigger. The action could result in a multiple nu... | TubWiper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TubWiper:
"""Donkey part which deletes a bunch of records from the end of tub. This allows to remove bad data already during recording. As this gets called in the vehicle loop the deletion runs only once in each continuous activation. A new execution requires to release of the input trigger. The ... | stack_v2_sparse_classes_10k_train_004003 | 6,381 | permissive | [
{
"docstring": ":param tub: tub to operate on :param num_records: number or records to delete",
"name": "__init__",
"signature": "def __init__(self, tub, num_records=20)"
},
{
"docstring": "Method in the vehicle loop. Delete records when trigger switches from False to True only. :param is_delete... | 2 | stack_v2_sparse_classes_30k_train_002367 | Implement the Python class `TubWiper` described below.
Class description:
Donkey part which deletes a bunch of records from the end of tub. This allows to remove bad data already during recording. As this gets called in the vehicle loop the deletion runs only once in each continuous activation. A new execution require... | Implement the Python class `TubWiper` described below.
Class description:
Donkey part which deletes a bunch of records from the end of tub. This allows to remove bad data already during recording. As this gets called in the vehicle loop the deletion runs only once in each continuous activation. A new execution require... | 9f91ad1aaff054522b24c2c1e727d1a111e266f4 | <|skeleton|>
class TubWiper:
"""Donkey part which deletes a bunch of records from the end of tub. This allows to remove bad data already during recording. As this gets called in the vehicle loop the deletion runs only once in each continuous activation. A new execution requires to release of the input trigger. The ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TubWiper:
"""Donkey part which deletes a bunch of records from the end of tub. This allows to remove bad data already during recording. As this gets called in the vehicle loop the deletion runs only once in each continuous activation. A new execution requires to release of the input trigger. The action could ... | the_stack_v2_python_sparse | donkeycar/parts/tub_v2.py | autorope/donkeycar | train | 1,861 |
9996591799edd24e8b51773c0c8d8345e7891da7 | [
"agent = request.user.userinfo.agent\ncompany = request.user.userinfo.company\ndata = models.SSARuleManage.tree(agent, company)\nreturn Response({'data': data, 'status': 200, 'msg': '获取成功'})",
"obj_serializer = serializers.RuleManageSerializers(data=request.data, context={'request': request})\nif obj_serializer.i... | <|body_start_0|>
agent = request.user.userinfo.agent
company = request.user.userinfo.company
data = models.SSARuleManage.tree(agent, company)
return Response({'data': data, 'status': 200, 'msg': '获取成功'})
<|end_body_0|>
<|body_start_1|>
obj_serializer = serializers.RuleManageSeri... | 专家分析系统 | RuleManageList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RuleManageList:
"""专家分析系统"""
def get(self, request):
"""获取规则目录树"""
<|body_0|>
def post(self, request):
"""添加规则"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
agent = request.user.userinfo.agent
company = request.user.userinfo.company
... | stack_v2_sparse_classes_10k_train_004004 | 4,124 | no_license | [
{
"docstring": "获取规则目录树",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "添加规则",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005201 | Implement the Python class `RuleManageList` described below.
Class description:
专家分析系统
Method signatures and docstrings:
- def get(self, request): 获取规则目录树
- def post(self, request): 添加规则 | Implement the Python class `RuleManageList` described below.
Class description:
专家分析系统
Method signatures and docstrings:
- def get(self, request): 获取规则目录树
- def post(self, request): 添加规则
<|skeleton|>
class RuleManageList:
"""专家分析系统"""
def get(self, request):
"""获取规则目录树"""
<|body_0|>
def... | d6e025d7e9d9e3aecfd399c77f376130edd8a2df | <|skeleton|>
class RuleManageList:
"""专家分析系统"""
def get(self, request):
"""获取规则目录树"""
<|body_0|>
def post(self, request):
"""添加规则"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RuleManageList:
"""专家分析系统"""
def get(self, request):
"""获取规则目录树"""
agent = request.user.userinfo.agent
company = request.user.userinfo.company
data = models.SSARuleManage.tree(agent, company)
return Response({'data': data, 'status': 200, 'msg': '获取成功'})
def po... | the_stack_v2_python_sparse | soc_ssa/views/experts_analysis.py | sundw2015/841 | train | 4 |
5b2de20438b8f1835ceb6d563893c1643416b2d6 | [
"test = '4 5\\n75 5\\n0 100\\n150 20\\n75 1'\nd = Company(test)\nself.assertEqual(d.n, 4)\nself.assertEqual(d.d, 5)\nself.assertEqual(d.numa, [75, 0, 150, 75])\nself.assertEqual(d.numb, [5, 100, 20, 1])\nself.assertEqual(Company(test).calculate(), '100')\ntest = '5 100\\n0 7\\n11 32\\n99 10\\n46 8\\n87 54'\nself.as... | <|body_start_0|>
test = '4 5\n75 5\n0 100\n150 20\n75 1'
d = Company(test)
self.assertEqual(d.n, 4)
self.assertEqual(d.d, 5)
self.assertEqual(d.numa, [75, 0, 150, 75])
self.assertEqual(d.numb, [5, 100, 20, 1])
self.assertEqual(Company(test).calculate(), '100')
... | unitTests | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class unitTests:
def test_single_test(self):
"""Company class testing"""
<|body_0|>
def time_limit_test(self, nmax):
"""Timelimit testing"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
test = '4 5\n75 5\n0 100\n150 20\n75 1'
d = Company(test)
... | stack_v2_sparse_classes_10k_train_004005 | 3,763 | permissive | [
{
"docstring": "Company class testing",
"name": "test_single_test",
"signature": "def test_single_test(self)"
},
{
"docstring": "Timelimit testing",
"name": "time_limit_test",
"signature": "def time_limit_test(self, nmax)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000249 | Implement the Python class `unitTests` described below.
Class description:
Implement the unitTests class.
Method signatures and docstrings:
- def test_single_test(self): Company class testing
- def time_limit_test(self, nmax): Timelimit testing | Implement the Python class `unitTests` described below.
Class description:
Implement the unitTests class.
Method signatures and docstrings:
- def test_single_test(self): Company class testing
- def time_limit_test(self, nmax): Timelimit testing
<|skeleton|>
class unitTests:
def test_single_test(self):
"... | ae02ea872ca91ef98630cc172a844b82cc56f621 | <|skeleton|>
class unitTests:
def test_single_test(self):
"""Company class testing"""
<|body_0|>
def time_limit_test(self, nmax):
"""Timelimit testing"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class unitTests:
def test_single_test(self):
"""Company class testing"""
test = '4 5\n75 5\n0 100\n150 20\n75 1'
d = Company(test)
self.assertEqual(d.n, 4)
self.assertEqual(d.d, 5)
self.assertEqual(d.numa, [75, 0, 150, 75])
self.assertEqual(d.numb, [5, 100, 20... | the_stack_v2_python_sparse | codeforces/580B_company.py | snsokolov/contests | train | 1 | |
185752dc8c9f2c2df4ff599f4e0f22b79474a0ae | [
"super().__init__()\nself.max_area_only = max_area_only\nself.use_rotated_box = use_rotated_box",
"mask_expand = mask.copy()\ncontours, _ = cv2.findContours(mask_expand, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\napprox_curve = []\nif self.max_area_only:\n contour_areas = [cv2.contourArea(contour) for contour ... | <|body_start_0|>
super().__init__()
self.max_area_only = max_area_only
self.use_rotated_box = use_rotated_box
<|end_body_0|>
<|body_start_1|>
mask_expand = mask.copy()
contours, _ = cv2.findContours(mask_expand, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
approx_curve = []... | Get the contour of the mask area and format output. | PostMaskRCNNSpot | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostMaskRCNNSpot:
"""Get the contour of the mask area and format output."""
def __init__(self, max_area_only=True, use_rotated_box=False):
"""Args: max_area_only (boolean): whether to consider only one (maximum) region in each proposal regions. use_rotated_box (boolean): whether to u... | stack_v2_sparse_classes_10k_train_004006 | 4,785 | permissive | [
{
"docstring": "Args: max_area_only (boolean): whether to consider only one (maximum) region in each proposal regions. use_rotated_box (boolean): whether to use minAreaRect to represent text regions (or use contour polygon)",
"name": "__init__",
"signature": "def __init__(self, max_area_only=True, use_r... | 3 | stack_v2_sparse_classes_30k_test_000280 | Implement the Python class `PostMaskRCNNSpot` described below.
Class description:
Get the contour of the mask area and format output.
Method signatures and docstrings:
- def __init__(self, max_area_only=True, use_rotated_box=False): Args: max_area_only (boolean): whether to consider only one (maximum) region in each ... | Implement the Python class `PostMaskRCNNSpot` described below.
Class description:
Get the contour of the mask area and format output.
Method signatures and docstrings:
- def __init__(self, max_area_only=True, use_rotated_box=False): Args: max_area_only (boolean): whether to consider only one (maximum) region in each ... | fb47a96d1a38f5ce634c6f12d710ed5300cc89fc | <|skeleton|>
class PostMaskRCNNSpot:
"""Get the contour of the mask area and format output."""
def __init__(self, max_area_only=True, use_rotated_box=False):
"""Args: max_area_only (boolean): whether to consider only one (maximum) region in each proposal regions. use_rotated_box (boolean): whether to u... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PostMaskRCNNSpot:
"""Get the contour of the mask area and format output."""
def __init__(self, max_area_only=True, use_rotated_box=False):
"""Args: max_area_only (boolean): whether to consider only one (maximum) region in each proposal regions. use_rotated_box (boolean): whether to use minAreaRec... | the_stack_v2_python_sparse | davarocr/davarocr/davar_spotting/core/post_processing/post_mask_rcnn_spot.py | OCRWorld/DAVAR-Lab-OCR | train | 0 |
01a4e851b177f90ba5a321a0e77a5195ec456767 | [
"_LOGGER.debug('async_step_ssdp: started')\nif not _is_complete_discovery(discovery_info):\n _LOGGER.debug('async_step_ssdp: Incomplete discovery, ignoring')\n return self.async_abort(reason='incomplete_discovery')\n_LOGGER.debug('async_step_ssdp: setting unique id %s', discovery_info.upnp[ATTR_UPNP_UDN])\naw... | <|body_start_0|>
_LOGGER.debug('async_step_ssdp: started')
if not _is_complete_discovery(discovery_info):
_LOGGER.debug('async_step_ssdp: Incomplete discovery, ignoring')
return self.async_abort(reason='incomplete_discovery')
_LOGGER.debug('async_step_ssdp: setting unique... | Handle an Openhome config flow. | OpenhomeConfigFlow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpenhomeConfigFlow:
"""Handle an Openhome config flow."""
async def async_step_ssdp(self, discovery_info: SsdpServiceInfo) -> FlowResult:
"""Handle a flow initialized by discovery."""
<|body_0|>
async def async_step_confirm(self, user_input: dict[str, Any] | None=None) -... | stack_v2_sparse_classes_10k_train_004007 | 2,231 | permissive | [
{
"docstring": "Handle a flow initialized by discovery.",
"name": "async_step_ssdp",
"signature": "async def async_step_ssdp(self, discovery_info: SsdpServiceInfo) -> FlowResult"
},
{
"docstring": "Handle user-confirmation of discovered node.",
"name": "async_step_confirm",
"signature": ... | 2 | null | Implement the Python class `OpenhomeConfigFlow` described below.
Class description:
Handle an Openhome config flow.
Method signatures and docstrings:
- async def async_step_ssdp(self, discovery_info: SsdpServiceInfo) -> FlowResult: Handle a flow initialized by discovery.
- async def async_step_confirm(self, user_inpu... | Implement the Python class `OpenhomeConfigFlow` described below.
Class description:
Handle an Openhome config flow.
Method signatures and docstrings:
- async def async_step_ssdp(self, discovery_info: SsdpServiceInfo) -> FlowResult: Handle a flow initialized by discovery.
- async def async_step_confirm(self, user_inpu... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class OpenhomeConfigFlow:
"""Handle an Openhome config flow."""
async def async_step_ssdp(self, discovery_info: SsdpServiceInfo) -> FlowResult:
"""Handle a flow initialized by discovery."""
<|body_0|>
async def async_step_confirm(self, user_input: dict[str, Any] | None=None) -... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OpenhomeConfigFlow:
"""Handle an Openhome config flow."""
async def async_step_ssdp(self, discovery_info: SsdpServiceInfo) -> FlowResult:
"""Handle a flow initialized by discovery."""
_LOGGER.debug('async_step_ssdp: started')
if not _is_complete_discovery(discovery_info):
... | the_stack_v2_python_sparse | homeassistant/components/openhome/config_flow.py | home-assistant/core | train | 35,501 |
610f415dd3004c76f98c52a0069c0ad72d7389a4 | [
"self.stopwords = self.get_stopwords(stopword_filepath)\nself.raker = r.Rake(self.stopwords)\nself.counter = w.WordCounter(self.stopwords)",
"rake_keys = self.extract_rake(text, False)\ntop_keys = self.extract_top(text, True)\nkey_list = {}\nfor rake_key in rake_keys:\n key_list[rake_key[0]] = 0\n key_score... | <|body_start_0|>
self.stopwords = self.get_stopwords(stopword_filepath)
self.raker = r.Rake(self.stopwords)
self.counter = w.WordCounter(self.stopwords)
<|end_body_0|>
<|body_start_1|>
rake_keys = self.extract_rake(text, False)
top_keys = self.extract_top(text, True)
key... | keywords class | KeyWords | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeyWords:
"""keywords class"""
def __init__(self, stopword_filepath='SmartStoplist.txt'):
"""Init @param stopword_filepath Filepath for stopwordlist, can be modified"""
<|body_0|>
def extract(self, text, return_amount=10):
"""Does a combined rake and relevant wor... | stack_v2_sparse_classes_10k_train_004008 | 3,760 | no_license | [
{
"docstring": "Init @param stopword_filepath Filepath for stopwordlist, can be modified",
"name": "__init__",
"signature": "def __init__(self, stopword_filepath='SmartStoplist.txt')"
},
{
"docstring": "Does a combined rake and relevant word count of the given string in order to give some releva... | 5 | stack_v2_sparse_classes_30k_train_002613 | Implement the Python class `KeyWords` described below.
Class description:
keywords class
Method signatures and docstrings:
- def __init__(self, stopword_filepath='SmartStoplist.txt'): Init @param stopword_filepath Filepath for stopwordlist, can be modified
- def extract(self, text, return_amount=10): Does a combined ... | Implement the Python class `KeyWords` described below.
Class description:
keywords class
Method signatures and docstrings:
- def __init__(self, stopword_filepath='SmartStoplist.txt'): Init @param stopword_filepath Filepath for stopwordlist, can be modified
- def extract(self, text, return_amount=10): Does a combined ... | 5e67a73cb08165bce415131555f21c4713321b0c | <|skeleton|>
class KeyWords:
"""keywords class"""
def __init__(self, stopword_filepath='SmartStoplist.txt'):
"""Init @param stopword_filepath Filepath for stopwordlist, can be modified"""
<|body_0|>
def extract(self, text, return_amount=10):
"""Does a combined rake and relevant wor... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class KeyWords:
"""keywords class"""
def __init__(self, stopword_filepath='SmartStoplist.txt'):
"""Init @param stopword_filepath Filepath for stopwordlist, can be modified"""
self.stopwords = self.get_stopwords(stopword_filepath)
self.raker = r.Rake(self.stopwords)
self.counter ... | the_stack_v2_python_sparse | media_conversation/keywords.py | linriedi/UvA-Home | train | 0 |
a1cfb63f53c3ca948a0e9ee2d737b3392e2a9129 | [
"url = f'{self.code_cloud_api.branch_api}/{repo_name}/pull-requests/{pull_request_id}/comments'\nresponse = self.code_cloud_api.post(url=url, json_data={'text': comment}, cred_hash=cred_hash)\nresponse['data']['repo_name'] = repo_name\nreturn response",
"url = f'{self.code_cloud_api.branch_api}/{repo_name}/pull-r... | <|body_start_0|>
url = f'{self.code_cloud_api.branch_api}/{repo_name}/pull-requests/{pull_request_id}/comments'
response = self.code_cloud_api.post(url=url, json_data={'text': comment}, cred_hash=cred_hash)
response['data']['repo_name'] = repo_name
return response
<|end_body_0|>
<|body_... | Handles all comment actions for code cloud. | Comments | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Comments:
"""Handles all comment actions for code cloud."""
def add_comment_to_pull_request(self, repo_name, pull_request_id, comment, cred_hash):
"""Add a comment to a pull request."""
<|body_0|>
def get_activities(self, repo_name, pull_request_id, cred_hash):
"... | stack_v2_sparse_classes_10k_train_004009 | 853 | no_license | [
{
"docstring": "Add a comment to a pull request.",
"name": "add_comment_to_pull_request",
"signature": "def add_comment_to_pull_request(self, repo_name, pull_request_id, comment, cred_hash)"
},
{
"docstring": "Get the activity details for a pull request.",
"name": "get_activities",
"sign... | 2 | stack_v2_sparse_classes_30k_train_003254 | Implement the Python class `Comments` described below.
Class description:
Handles all comment actions for code cloud.
Method signatures and docstrings:
- def add_comment_to_pull_request(self, repo_name, pull_request_id, comment, cred_hash): Add a comment to a pull request.
- def get_activities(self, repo_name, pull_r... | Implement the Python class `Comments` described below.
Class description:
Handles all comment actions for code cloud.
Method signatures and docstrings:
- def add_comment_to_pull_request(self, repo_name, pull_request_id, comment, cred_hash): Add a comment to a pull request.
- def get_activities(self, repo_name, pull_r... | 52ba4eecd727c200f8ad82652434d171655c5f0a | <|skeleton|>
class Comments:
"""Handles all comment actions for code cloud."""
def add_comment_to_pull_request(self, repo_name, pull_request_id, comment, cred_hash):
"""Add a comment to a pull request."""
<|body_0|>
def get_activities(self, repo_name, pull_request_id, cred_hash):
"... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Comments:
"""Handles all comment actions for code cloud."""
def add_comment_to_pull_request(self, repo_name, pull_request_id, comment, cred_hash):
"""Add a comment to a pull request."""
url = f'{self.code_cloud_api.branch_api}/{repo_name}/pull-requests/{pull_request_id}/comments'
... | the_stack_v2_python_sparse | devcenter/codecloud/comments.py | ljmerza/devCenter | train | 0 |
652a1e2e8b6505c8509e78e302d308bdd1f23802 | [
"max_texture_size = pyglet.image.get_max_texture_size()\nwidth = min(width, max_texture_size)\nheight = min(height, max_texture_size)\nself.texture = pyglet.image.Texture.create(width, height)\nself.allocator = Allocator(width, height)",
"x, y = self.allocator.alloc(img.width + border * 2, img.height + border * 2... | <|body_start_0|>
max_texture_size = pyglet.image.get_max_texture_size()
width = min(width, max_texture_size)
height = min(height, max_texture_size)
self.texture = pyglet.image.Texture.create(width, height)
self.allocator = Allocator(width, height)
<|end_body_0|>
<|body_start_1|>... | Collection of images within a texture. | TextureAtlas | [
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextureAtlas:
"""Collection of images within a texture."""
def __init__(self, width: int=2048, height: int=2048) -> None:
"""Create a texture atlas of the given size. :Parameters: `width` : int Width of the underlying texture. `height` : int Height of the underlying texture."""
... | stack_v2_sparse_classes_10k_train_004010 | 10,284 | permissive | [
{
"docstring": "Create a texture atlas of the given size. :Parameters: `width` : int Width of the underlying texture. `height` : int Height of the underlying texture.",
"name": "__init__",
"signature": "def __init__(self, width: int=2048, height: int=2048) -> None"
},
{
"docstring": "Add an imag... | 2 | stack_v2_sparse_classes_30k_train_006159 | Implement the Python class `TextureAtlas` described below.
Class description:
Collection of images within a texture.
Method signatures and docstrings:
- def __init__(self, width: int=2048, height: int=2048) -> None: Create a texture atlas of the given size. :Parameters: `width` : int Width of the underlying texture. ... | Implement the Python class `TextureAtlas` described below.
Class description:
Collection of images within a texture.
Method signatures and docstrings:
- def __init__(self, width: int=2048, height: int=2048) -> None: Create a texture atlas of the given size. :Parameters: `width` : int Width of the underlying texture. ... | 094c638f0529fecab4e74556487b92453a78753c | <|skeleton|>
class TextureAtlas:
"""Collection of images within a texture."""
def __init__(self, width: int=2048, height: int=2048) -> None:
"""Create a texture atlas of the given size. :Parameters: `width` : int Width of the underlying texture. `height` : int Height of the underlying texture."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TextureAtlas:
"""Collection of images within a texture."""
def __init__(self, width: int=2048, height: int=2048) -> None:
"""Create a texture atlas of the given size. :Parameters: `width` : int Width of the underlying texture. `height` : int Height of the underlying texture."""
max_textur... | the_stack_v2_python_sparse | pyglet/image/atlas.py | pyglet/pyglet | train | 1,687 |
e311bd10e2c0c89fdde8f8a392a818c288b97475 | [
"ans = []\nfactor = [1]\nfor i in range(2, n):\n factor.append(factor[-1] * i)\ncandi = [i for i in range(1, n + 1)]\ni = n - 2\nwhile candi:\n index, k = divmod(k, factor[i])\n if factor[i] == 1 or k == 0:\n index -= 1\n ans.append(str(candi[index]))\n candi.remove(candi[index])\n i -= 1\n... | <|body_start_0|>
ans = []
factor = [1]
for i in range(2, n):
factor.append(factor[-1] * i)
candi = [i for i in range(1, n + 1)]
i = n - 2
while candi:
index, k = divmod(k, factor[i])
if factor[i] == 1 or k == 0:
index -=... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getPermutation_1(self, n, k):
""":type n: int :type k: int :rtype: str"""
<|body_0|>
def getPermutation_k_subtract_one_first(self, n, k):
""":type n: int :type k: int :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ans = []... | stack_v2_sparse_classes_10k_train_004011 | 1,478 | no_license | [
{
"docstring": ":type n: int :type k: int :rtype: str",
"name": "getPermutation_1",
"signature": "def getPermutation_1(self, n, k)"
},
{
"docstring": ":type n: int :type k: int :rtype: str",
"name": "getPermutation_k_subtract_one_first",
"signature": "def getPermutation_k_subtract_one_fi... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getPermutation_1(self, n, k): :type n: int :type k: int :rtype: str
- def getPermutation_k_subtract_one_first(self, n, k): :type n: int :type k: int :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getPermutation_1(self, n, k): :type n: int :type k: int :rtype: str
- def getPermutation_k_subtract_one_first(self, n, k): :type n: int :type k: int :rtype: str
<|skeleton|>... | 0e99f9a5226507706b3ee66fd04bae813755ef40 | <|skeleton|>
class Solution:
def getPermutation_1(self, n, k):
""":type n: int :type k: int :rtype: str"""
<|body_0|>
def getPermutation_k_subtract_one_first(self, n, k):
""":type n: int :type k: int :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def getPermutation_1(self, n, k):
""":type n: int :type k: int :rtype: str"""
ans = []
factor = [1]
for i in range(2, n):
factor.append(factor[-1] * i)
candi = [i for i in range(1, n + 1)]
i = n - 2
while candi:
index, k... | the_stack_v2_python_sparse | medium/math/test_60_Permutation_Sequence.py | wuxu1019/leetcode_sophia | train | 1 | |
e3f1e91a022165a526299378047d7249c65a6eaa | [
"username = request.GET.get('username', None)\nif username is not None:\n teacher = get_object_or_404(Teacher, user__username=username)\n serializer = TeacherSerializer(teacher)\n return JsonResponse({'teachers': [serializer.data]}, safe=False)\nelse:\n teachers = Teacher.objects.all()\n serializer =... | <|body_start_0|>
username = request.GET.get('username', None)
if username is not None:
teacher = get_object_or_404(Teacher, user__username=username)
serializer = TeacherSerializer(teacher)
return JsonResponse({'teachers': [serializer.data]}, safe=False)
else:
... | 教师view | Teachers | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Teachers:
"""教师view"""
def get(self, request):
"""查询教师"""
<|body_0|>
def post(self, request):
"""增加教师"""
<|body_1|>
def delete(self, request):
"""删除教师"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
username = request.GET.ge... | stack_v2_sparse_classes_10k_train_004012 | 16,053 | permissive | [
{
"docstring": "查询教师",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "增加教师",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "删除教师",
"name": "delete",
"signature": "def delete(self, request)"
}
] | 3 | stack_v2_sparse_classes_30k_train_005603 | Implement the Python class `Teachers` described below.
Class description:
教师view
Method signatures and docstrings:
- def get(self, request): 查询教师
- def post(self, request): 增加教师
- def delete(self, request): 删除教师 | Implement the Python class `Teachers` described below.
Class description:
教师view
Method signatures and docstrings:
- def get(self, request): 查询教师
- def post(self, request): 增加教师
- def delete(self, request): 删除教师
<|skeleton|>
class Teachers:
"""教师view"""
def get(self, request):
"""查询教师"""
<|b... | 7aaa1be773718de1beb3ce0080edca7c4114b7ad | <|skeleton|>
class Teachers:
"""教师view"""
def get(self, request):
"""查询教师"""
<|body_0|>
def post(self, request):
"""增加教师"""
<|body_1|>
def delete(self, request):
"""删除教师"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Teachers:
"""教师view"""
def get(self, request):
"""查询教师"""
username = request.GET.get('username', None)
if username is not None:
teacher = get_object_or_404(Teacher, user__username=username)
serializer = TeacherSerializer(teacher)
return JsonResp... | the_stack_v2_python_sparse | user/views.py | MIXISAMA/MIS-backend | train | 0 |
f3cd108c4ee31b5498859b931cd6bc67e4d4b418 | [
"assert isinstance(p1, Point), 'p1=%r is not a point' % p1\nassert isinstance(p2, Point), 'p2=%r is not a point' % p2\nself.p1 = p1\nself.p2 = p2\nself.x_min = min(p1.x, p2.x)\nself.y_min = min(p1.y, p2.x)\nself.x_max = max(p1.x, p2.x)\nself.y_max = max(p1.y, p2.x)",
"assert isinstance(p, Point), 'p=%r is not a p... | <|body_start_0|>
assert isinstance(p1, Point), 'p1=%r is not a point' % p1
assert isinstance(p2, Point), 'p2=%r is not a point' % p2
self.p1 = p1
self.p2 = p2
self.x_min = min(p1.x, p2.x)
self.y_min = min(p1.y, p2.x)
self.x_max = max(p1.x, p2.x)
self.y_max... | A rectangle identified by two points. | Rectangle | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rectangle:
"""A rectangle identified by two points."""
def __init__(self, p1, p2):
"""Constructor for a rectangle. Parameters ---------- p1 : Point p2 : Point"""
<|body_0|>
def get_outcode(self, p):
"""Get the outcode for a point p. The values are (left, right, b... | stack_v2_sparse_classes_10k_train_004013 | 5,195 | permissive | [
{
"docstring": "Constructor for a rectangle. Parameters ---------- p1 : Point p2 : Point",
"name": "__init__",
"signature": "def __init__(self, p1, p2)"
},
{
"docstring": "Get the outcode for a point p. The values are (left, right, bottom, top). Parameters ---------- p : Point Returns ------- li... | 3 | null | Implement the Python class `Rectangle` described below.
Class description:
A rectangle identified by two points.
Method signatures and docstrings:
- def __init__(self, p1, p2): Constructor for a rectangle. Parameters ---------- p1 : Point p2 : Point
- def get_outcode(self, p): Get the outcode for a point p. The value... | Implement the Python class `Rectangle` described below.
Class description:
A rectangle identified by two points.
Method signatures and docstrings:
- def __init__(self, p1, p2): Constructor for a rectangle. Parameters ---------- p1 : Point p2 : Point
- def get_outcode(self, p): Get the outcode for a point p. The value... | 1c20f57185e6324aa840ccff98e69764b4213131 | <|skeleton|>
class Rectangle:
"""A rectangle identified by two points."""
def __init__(self, p1, p2):
"""Constructor for a rectangle. Parameters ---------- p1 : Point p2 : Point"""
<|body_0|>
def get_outcode(self, p):
"""Get the outcode for a point p. The values are (left, right, b... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Rectangle:
"""A rectangle identified by two points."""
def __init__(self, p1, p2):
"""Constructor for a rectangle. Parameters ---------- p1 : Point p2 : Point"""
assert isinstance(p1, Point), 'p1=%r is not a point' % p1
assert isinstance(p2, Point), 'p2=%r is not a point' % p2
... | the_stack_v2_python_sparse | alpha-clipping/main.py | PepSalehi/algorithms | train | 0 |
d1396d8f37d16491d769f52d25607550baa12aad | [
"i = max_profit = 0\nwhile i < len(prices) - 1:\n while i < len(prices) - 1 and prices[i] >= prices[i + 1]:\n i += 1\n valley = prices[i]\n while i < len(prices) - 1 and prices[i] <= prices[i + 1]:\n i += 1\n peak = prices[i]\n max_profit += peak - valley\nreturn max_profit",
"max_pro... | <|body_start_0|>
i = max_profit = 0
while i < len(prices) - 1:
while i < len(prices) - 1 and prices[i] >= prices[i + 1]:
i += 1
valley = prices[i]
while i < len(prices) - 1 and prices[i] <= prices[i + 1]:
i += 1
peak = price... | Stock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Stock:
def get_max_profit_for_multiple_transactions_(self, prices: List[int]) -> int:
"""Approach: Peak Valley Time Complexity: O(N) Space Complexity: O(1) :param prices: :return:"""
<|body_0|>
def get_max_profit_for_multiple_transaction(self, prices: List[int]) -> int:
... | stack_v2_sparse_classes_10k_train_004014 | 1,758 | no_license | [
{
"docstring": "Approach: Peak Valley Time Complexity: O(N) Space Complexity: O(1) :param prices: :return:",
"name": "get_max_profit_for_multiple_transactions_",
"signature": "def get_max_profit_for_multiple_transactions_(self, prices: List[int]) -> int"
},
{
"docstring": "Approach: One Pass Tim... | 3 | null | Implement the Python class `Stock` described below.
Class description:
Implement the Stock class.
Method signatures and docstrings:
- def get_max_profit_for_multiple_transactions_(self, prices: List[int]) -> int: Approach: Peak Valley Time Complexity: O(N) Space Complexity: O(1) :param prices: :return:
- def get_max_... | Implement the Python class `Stock` described below.
Class description:
Implement the Stock class.
Method signatures and docstrings:
- def get_max_profit_for_multiple_transactions_(self, prices: List[int]) -> int: Approach: Peak Valley Time Complexity: O(N) Space Complexity: O(1) :param prices: :return:
- def get_max_... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Stock:
def get_max_profit_for_multiple_transactions_(self, prices: List[int]) -> int:
"""Approach: Peak Valley Time Complexity: O(N) Space Complexity: O(1) :param prices: :return:"""
<|body_0|>
def get_max_profit_for_multiple_transaction(self, prices: List[int]) -> int:
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Stock:
def get_max_profit_for_multiple_transactions_(self, prices: List[int]) -> int:
"""Approach: Peak Valley Time Complexity: O(N) Space Complexity: O(1) :param prices: :return:"""
i = max_profit = 0
while i < len(prices) - 1:
while i < len(prices) - 1 and prices[i] >= pr... | the_stack_v2_python_sparse | revisited/greedy/best_time_to_buy_stock.py | Shiv2157k/leet_code | train | 1 | |
90f2ae134d6af0ec71b0def9c901600c34b92e5c | [
"study_id = filter_params.pop('study_id', None)\nbiospecimen_id = filter_params.pop('biospecimen_id', None)\nq = Diagnosis.query.filter_by(**filter_params)\nfrom dataservice.api.participant.models import Participant\nfrom dataservice.api.biospecimen.models import BiospecimenDiagnosis\nif study_id:\n q = q.join(P... | <|body_start_0|>
study_id = filter_params.pop('study_id', None)
biospecimen_id = filter_params.pop('biospecimen_id', None)
q = Diagnosis.query.filter_by(**filter_params)
from dataservice.api.participant.models import Participant
from dataservice.api.biospecimen.models import Bios... | Diagnosis REST API | DiagnosisListAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiagnosisListAPI:
"""Diagnosis REST API"""
def get(self, filter_params, after, limit):
"""Get all diagnoses --- description: Get all diagnoses template: path: get_list.yml properties: resource: Diagnosis"""
<|body_0|>
def post(self):
"""Create a new diagnosis ---... | stack_v2_sparse_classes_10k_train_004015 | 5,021 | permissive | [
{
"docstring": "Get all diagnoses --- description: Get all diagnoses template: path: get_list.yml properties: resource: Diagnosis",
"name": "get",
"signature": "def get(self, filter_params, after, limit)"
},
{
"docstring": "Create a new diagnosis --- template: path: new_resource.yml properties: ... | 2 | stack_v2_sparse_classes_30k_train_000900 | Implement the Python class `DiagnosisListAPI` described below.
Class description:
Diagnosis REST API
Method signatures and docstrings:
- def get(self, filter_params, after, limit): Get all diagnoses --- description: Get all diagnoses template: path: get_list.yml properties: resource: Diagnosis
- def post(self): Creat... | Implement the Python class `DiagnosisListAPI` described below.
Class description:
Diagnosis REST API
Method signatures and docstrings:
- def get(self, filter_params, after, limit): Get all diagnoses --- description: Get all diagnoses template: path: get_list.yml properties: resource: Diagnosis
- def post(self): Creat... | 36ee3fc3d1ba9d1a177274d051fb175c56dd898e | <|skeleton|>
class DiagnosisListAPI:
"""Diagnosis REST API"""
def get(self, filter_params, after, limit):
"""Get all diagnoses --- description: Get all diagnoses template: path: get_list.yml properties: resource: Diagnosis"""
<|body_0|>
def post(self):
"""Create a new diagnosis ---... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DiagnosisListAPI:
"""Diagnosis REST API"""
def get(self, filter_params, after, limit):
"""Get all diagnoses --- description: Get all diagnoses template: path: get_list.yml properties: resource: Diagnosis"""
study_id = filter_params.pop('study_id', None)
biospecimen_id = filter_par... | the_stack_v2_python_sparse | dataservice/api/diagnosis/resources.py | kids-first/kf-api-dataservice | train | 9 |
6d38d7fb28e65289892b5df40553884525e3d46f | [
"n = len(nums)\nj = 0\nfor i in range(n):\n if nums[i] != 0:\n nums[j] = nums[i]\n j += 1\nfor i in range(j, n):\n nums[i] = 0",
"n = len(nums)\nj = 0\nfor i in range(n):\n if nums[i] != 0:\n nums[i], nums[j] = (nums[j], nums[i])\n j += 1",
"n = len(nums)\nleft, right = (0, ... | <|body_start_0|>
n = len(nums)
j = 0
for i in range(n):
if nums[i] != 0:
nums[j] = nums[i]
j += 1
for i in range(j, n):
nums[i] = 0
<|end_body_0|>
<|body_start_1|>
n = len(nums)
j = 0
for i in range(n):
... | OfficialSolution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OfficialSolution:
def move_zeroes(self, nums: List[int]) -> None:
"""两次遍历(双指针)。"""
<|body_0|>
def move_zeroes_2(self, nums: List[int]) -> None:
"""一次遍历(快排思想,交换元素)。"""
<|body_1|>
def move_zeroes_3(self, nums: List[int]) -> None:
"""双指针。"""
... | stack_v2_sparse_classes_10k_train_004016 | 3,743 | no_license | [
{
"docstring": "两次遍历(双指针)。",
"name": "move_zeroes",
"signature": "def move_zeroes(self, nums: List[int]) -> None"
},
{
"docstring": "一次遍历(快排思想,交换元素)。",
"name": "move_zeroes_2",
"signature": "def move_zeroes_2(self, nums: List[int]) -> None"
},
{
"docstring": "双指针。",
"name": "... | 3 | stack_v2_sparse_classes_30k_train_001407 | Implement the Python class `OfficialSolution` described below.
Class description:
Implement the OfficialSolution class.
Method signatures and docstrings:
- def move_zeroes(self, nums: List[int]) -> None: 两次遍历(双指针)。
- def move_zeroes_2(self, nums: List[int]) -> None: 一次遍历(快排思想,交换元素)。
- def move_zeroes_3(self, nums: Li... | Implement the Python class `OfficialSolution` described below.
Class description:
Implement the OfficialSolution class.
Method signatures and docstrings:
- def move_zeroes(self, nums: List[int]) -> None: 两次遍历(双指针)。
- def move_zeroes_2(self, nums: List[int]) -> None: 一次遍历(快排思想,交换元素)。
- def move_zeroes_3(self, nums: Li... | 6932d69353b94ec824dd0ddc86a92453f6673232 | <|skeleton|>
class OfficialSolution:
def move_zeroes(self, nums: List[int]) -> None:
"""两次遍历(双指针)。"""
<|body_0|>
def move_zeroes_2(self, nums: List[int]) -> None:
"""一次遍历(快排思想,交换元素)。"""
<|body_1|>
def move_zeroes_3(self, nums: List[int]) -> None:
"""双指针。"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OfficialSolution:
def move_zeroes(self, nums: List[int]) -> None:
"""两次遍历(双指针)。"""
n = len(nums)
j = 0
for i in range(n):
if nums[i] != 0:
nums[j] = nums[i]
j += 1
for i in range(j, n):
nums[i] = 0
def move_ze... | the_stack_v2_python_sparse | 0283_move-zeroes.py | Nigirimeshi/leetcode | train | 0 | |
f8956b944efd1fa0f32cde7e248ea4a1a5f22f95 | [
"n = len(data)\ndp = [1] * (n + 1)\nfor i in range(2, n + 1):\n for j in range(i - 1):\n if data[i - 1] == data[j] + 1:\n dp[i] = max(dp[j + 1] + 1, dp[i])\nreturn n - max(dp)",
"if not data:\n return 0\nAList_map = []\nfor num in data:\n flag = 0\n if AList_map:\n for map_old... | <|body_start_0|>
n = len(data)
dp = [1] * (n + 1)
for i in range(2, n + 1):
for j in range(i - 1):
if data[i - 1] == data[j] + 1:
dp[i] = max(dp[j + 1] + 1, dp[i])
return n - max(dp)
<|end_body_0|>
<|body_start_1|>
if not data:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def moveStoneMinNum(self, data):
"""分析:保持原来数组中最长递增子序列不变,移动其他石子,再用序列长度减去最长子序列个数即得答案。 dp[i] 是以 A[i-1_最短回文串.py]为尾的最长序列数长度。 dp[i] = max(dp[j-1_最短回文串.py] + 1_最短回文串.py) if data[i-1_最短回文串.py]==data[j]+1_最短回文串.py j=0,1_最短回文串.py,...,i-2 dp[0] = 0 dp[1_最短回文串.py] = 1_最短回文串.py res = max(dp... | stack_v2_sparse_classes_10k_train_004017 | 1,613 | no_license | [
{
"docstring": "分析:保持原来数组中最长递增子序列不变,移动其他石子,再用序列长度减去最长子序列个数即得答案。 dp[i] 是以 A[i-1_最短回文串.py]为尾的最长序列数长度。 dp[i] = max(dp[j-1_最短回文串.py] + 1_最短回文串.py) if data[i-1_最短回文串.py]==data[j]+1_最短回文串.py j=0,1_最短回文串.py,...,i-2 dp[0] = 0 dp[1_最短回文串.py] = 1_最短回文串.py res = max(dp) T:O(n^2) M:O(n)",
"name": "moveStoneMinNum",
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def moveStoneMinNum(self, data): 分析:保持原来数组中最长递增子序列不变,移动其他石子,再用序列长度减去最长子序列个数即得答案。 dp[i] 是以 A[i-1_最短回文串.py]为尾的最长序列数长度。 dp[i] = max(dp[j-1_最短回文串.py] + 1_最短回文串.py) if data[i-1_最短回文串.... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def moveStoneMinNum(self, data): 分析:保持原来数组中最长递增子序列不变,移动其他石子,再用序列长度减去最长子序列个数即得答案。 dp[i] 是以 A[i-1_最短回文串.py]为尾的最长序列数长度。 dp[i] = max(dp[j-1_最短回文串.py] + 1_最短回文串.py) if data[i-1_最短回文串.... | 57f303aa6e76f7c5292fa60bffdfddcb4ff9ddfb | <|skeleton|>
class Solution:
def moveStoneMinNum(self, data):
"""分析:保持原来数组中最长递增子序列不变,移动其他石子,再用序列长度减去最长子序列个数即得答案。 dp[i] 是以 A[i-1_最短回文串.py]为尾的最长序列数长度。 dp[i] = max(dp[j-1_最短回文串.py] + 1_最短回文串.py) if data[i-1_最短回文串.py]==data[j]+1_最短回文串.py j=0,1_最短回文串.py,...,i-2 dp[0] = 0 dp[1_最短回文串.py] = 1_最短回文串.py res = max(dp... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def moveStoneMinNum(self, data):
"""分析:保持原来数组中最长递增子序列不变,移动其他石子,再用序列长度减去最长子序列个数即得答案。 dp[i] 是以 A[i-1_最短回文串.py]为尾的最长序列数长度。 dp[i] = max(dp[j-1_最短回文串.py] + 1_最短回文串.py) if data[i-1_最短回文串.py]==data[j]+1_最短回文串.py j=0,1_最短回文串.py,...,i-2 dp[0] = 0 dp[1_最短回文串.py] = 1_最短回文串.py res = max(dp) T:O(n^2) M:O... | the_stack_v2_python_sparse | 4_LEETCODE/11_Interview/浪潮/石头排序.py | fzingithub/SwordRefers2Offer | train | 1 | |
89583538a29b38c97ca5d769ef8b17902833fb79 | [
"self.verify_mco_parameters(params)\ntfunc = partial(self.translated_function, func=func, params=params)\nx0, bounds = self.get_initial_and_bounds(params)\noptimization_result = scipy_optimize.minimize(tfunc, x0, method=self.algorithms, bounds=bounds)\noptimal_point = self.translate_array_to_mco(optimization_result... | <|body_start_0|>
self.verify_mco_parameters(params)
tfunc = partial(self.translated_function, func=func, params=params)
x0, bounds = self.get_initial_and_bounds(params)
optimization_result = scipy_optimize.minimize(tfunc, x0, method=self.algorithms, bounds=bounds)
optimal_point =... | Optimization of an objective function using scipy. | ScipyOptimizer | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScipyOptimizer:
"""Optimization of an objective function using scipy."""
def optimize_function(self, func, params):
"""Minimize the passed function. Parameters ---------- func: Callable The MCO function to optimize Takes a list of MCO parameter values. Should return a scalar (i.e. a ... | stack_v2_sparse_classes_10k_train_004018 | 9,020 | permissive | [
{
"docstring": "Minimize the passed function. Parameters ---------- func: Callable The MCO function to optimize Takes a list of MCO parameter values. Should return a scalar (i.e. a single-objective). If not the return (objectives) will be summed. params: list of MCOParameter The MCO parameter objects correspond... | 6 | stack_v2_sparse_classes_30k_train_000701 | Implement the Python class `ScipyOptimizer` described below.
Class description:
Optimization of an objective function using scipy.
Method signatures and docstrings:
- def optimize_function(self, func, params): Minimize the passed function. Parameters ---------- func: Callable The MCO function to optimize Takes a list... | Implement the Python class `ScipyOptimizer` described below.
Class description:
Optimization of an objective function using scipy.
Method signatures and docstrings:
- def optimize_function(self, func, params): Minimize the passed function. Parameters ---------- func: Callable The MCO function to optimize Takes a list... | 6106bec35d6ad2383138a35205cea44fe529a229 | <|skeleton|>
class ScipyOptimizer:
"""Optimization of an objective function using scipy."""
def optimize_function(self, func, params):
"""Minimize the passed function. Parameters ---------- func: Callable The MCO function to optimize Takes a list of MCO parameter values. Should return a scalar (i.e. a ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ScipyOptimizer:
"""Optimization of an objective function using scipy."""
def optimize_function(self, func, params):
"""Minimize the passed function. Parameters ---------- func: Callable The MCO function to optimize Takes a list of MCO parameter values. Should return a scalar (i.e. a single-object... | the_stack_v2_python_sparse | force_bdss/mco/optimizers/scipy_optimizer.py | force-h2020/force-bdss | train | 2 |
dbb04c94750c152755d66a5a56a1f3fb7dc714bb | [
"super()._define_vars()\nself._transformer: Transformer = Transformer()\n'\\n Our lark->veredi tree transformer.\\n '\nself._variables: MutableMapping[lark.Token, tree.Node] = {}\n'\\n A collection to hold the name & value of any variables declared in the\\n tree.\\n '\nself._mili... | <|body_start_0|>
super()._define_vars()
self._transformer: Transformer = Transformer()
'\n Our lark->veredi tree transformer.\n '
self._variables: MutableMapping[lark.Token, tree.Node] = {}
'\n A collection to hold the name & value of any variables declared i... | MathParser interface implementation. Wraps up the lark parsing and tranformation operations for getting from a string to some valid d20 math tree. | D20Parser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class D20Parser:
"""MathParser interface implementation. Wraps up the lark parsing and tranformation operations for getting from a string to some valid d20 math tree."""
def _define_vars(self) -> None:
"""Instance variable definitions, type hinting, doc strings, etc."""
<|body_0|>
... | stack_v2_sparse_classes_10k_train_004019 | 11,922 | no_license | [
{
"docstring": "Instance variable definitions, type hinting, doc strings, etc.",
"name": "_define_vars",
"signature": "def _define_vars(self) -> None"
},
{
"docstring": "Initialize/reset/clear/whatever our instance variables in prep for next parse & transform.",
"name": "_set_up",
"signa... | 3 | null | Implement the Python class `D20Parser` described below.
Class description:
MathParser interface implementation. Wraps up the lark parsing and tranformation operations for getting from a string to some valid d20 math tree.
Method signatures and docstrings:
- def _define_vars(self) -> None: Instance variable definition... | Implement the Python class `D20Parser` described below.
Class description:
MathParser interface implementation. Wraps up the lark parsing and tranformation operations for getting from a string to some valid d20 math tree.
Method signatures and docstrings:
- def _define_vars(self) -> None: Instance variable definition... | 8c9fc1170ceac335985686571568eebf08b0db7a | <|skeleton|>
class D20Parser:
"""MathParser interface implementation. Wraps up the lark parsing and tranformation operations for getting from a string to some valid d20 math tree."""
def _define_vars(self) -> None:
"""Instance variable definitions, type hinting, doc strings, etc."""
<|body_0|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class D20Parser:
"""MathParser interface implementation. Wraps up the lark parsing and tranformation operations for getting from a string to some valid d20 math tree."""
def _define_vars(self) -> None:
"""Instance variable definitions, type hinting, doc strings, etc."""
super()._define_vars()
... | the_stack_v2_python_sparse | math/d20/parser.py | cole-brown/veredi-code | train | 1 |
a6f8effbb72cbea1226d1c5b87cb71ab79e3bea4 | [
"inputs, outputs = equation.split('->')\ninput_dims, output_dims = (inputs.split(','), outputs.split(','))\nassert len(input_dims) <= 2, 'Only support at most two inputs'\nassert len(output_dims) == 1, 'Only support single output'\noutput_dim = output_dims[0]\nreturn (input_dims, output_dim)",
"dim_char_set = set... | <|body_start_0|>
inputs, outputs = equation.split('->')
input_dims, output_dims = (inputs.split(','), outputs.split(','))
assert len(input_dims) <= 2, 'Only support at most two inputs'
assert len(output_dims) == 1, 'Only support single output'
output_dim = output_dims[0]
... | EinsumDims | [
"BSD-3-Clause",
"BSD-2-Clause",
"LicenseRef-scancode-secret-labs-2011",
"LicenseRef-scancode-generic-cla",
"BSL-1.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EinsumDims:
def parse_equation(cls, equation: str) -> Tuple[List[str], str]:
"""Parse the einsum equation str to input dim chars and output dim char"""
<|body_0|>
def parse_dims(cls, input_dims: List[str], output_dim: str) -> 'EinsumDims':
"""Parse the dims and extra... | stack_v2_sparse_classes_10k_train_004020 | 6,665 | permissive | [
{
"docstring": "Parse the einsum equation str to input dim chars and output dim char",
"name": "parse_equation",
"signature": "def parse_equation(cls, equation: str) -> Tuple[List[str], str]"
},
{
"docstring": "Parse the dims and extract the contracting, batch, and free dimensions for the left a... | 2 | stack_v2_sparse_classes_30k_train_005677 | Implement the Python class `EinsumDims` described below.
Class description:
Implement the EinsumDims class.
Method signatures and docstrings:
- def parse_equation(cls, equation: str) -> Tuple[List[str], str]: Parse the einsum equation str to input dim chars and output dim char
- def parse_dims(cls, input_dims: List[s... | Implement the Python class `EinsumDims` described below.
Class description:
Implement the EinsumDims class.
Method signatures and docstrings:
- def parse_equation(cls, equation: str) -> Tuple[List[str], str]: Parse the einsum equation str to input dim chars and output dim char
- def parse_dims(cls, input_dims: List[s... | a6f7dd4707ac116c0f5fb5f44f42429f38d23ab4 | <|skeleton|>
class EinsumDims:
def parse_equation(cls, equation: str) -> Tuple[List[str], str]:
"""Parse the einsum equation str to input dim chars and output dim char"""
<|body_0|>
def parse_dims(cls, input_dims: List[str], output_dim: str) -> 'EinsumDims':
"""Parse the dims and extra... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EinsumDims:
def parse_equation(cls, equation: str) -> Tuple[List[str], str]:
"""Parse the einsum equation str to input dim chars and output dim char"""
inputs, outputs = equation.split('->')
input_dims, output_dims = (inputs.split(','), outputs.split(','))
assert len(input_dims... | the_stack_v2_python_sparse | torch/distributed/_tensor/ops/basic_strategy.py | pytorch/pytorch | train | 77,092 | |
79018f99c43d9acb3717d20a86edbd2675c4c362 | [
"super(SubGraph, self).__init__()\nself.layers_number = layersNumber\nself.layers = nn.ModuleList([SubGraphLayer(feature_length * 2 ** i) for i in range(self.layers_number)])",
"for layer in self.layers:\n x = layer(x)\nx = x.permute(0, 2, 1)\nx = F.max_pool1d(x, kernel_size=x.shape[2])\nx = x.permute(0, 2, 1)... | <|body_start_0|>
super(SubGraph, self).__init__()
self.layers_number = layersNumber
self.layers = nn.ModuleList([SubGraphLayer(feature_length * 2 ** i) for i in range(self.layers_number)])
<|end_body_0|>
<|body_start_1|>
for layer in self.layers:
x = layer(x)
x = x.p... | Subgraph of VectorNet. This network accept a number of initiated vectors belong to the same polyline, flow three layers of network, then output this polyline's feature vector. | SubGraph | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubGraph:
"""Subgraph of VectorNet. This network accept a number of initiated vectors belong to the same polyline, flow three layers of network, then output this polyline's feature vector."""
def __init__(self, feature_length, layersNumber):
"""Given all vectors of this polyline, we ... | stack_v2_sparse_classes_10k_train_004021 | 3,612 | no_license | [
{
"docstring": "Given all vectors of this polyline, we should build a 3-layers subgraph network, get the output which is the polyline's feature vector. :param feature_length: the length of vector. :param layersNumber: the number of subgraph network.",
"name": "__init__",
"signature": "def __init__(self,... | 2 | stack_v2_sparse_classes_30k_train_006837 | Implement the Python class `SubGraph` described below.
Class description:
Subgraph of VectorNet. This network accept a number of initiated vectors belong to the same polyline, flow three layers of network, then output this polyline's feature vector.
Method signatures and docstrings:
- def __init__(self, feature_lengt... | Implement the Python class `SubGraph` described below.
Class description:
Subgraph of VectorNet. This network accept a number of initiated vectors belong to the same polyline, flow three layers of network, then output this polyline's feature vector.
Method signatures and docstrings:
- def __init__(self, feature_lengt... | 0a314f7bdfc6db0247c92bc2c5c3806fdd18b885 | <|skeleton|>
class SubGraph:
"""Subgraph of VectorNet. This network accept a number of initiated vectors belong to the same polyline, flow three layers of network, then output this polyline's feature vector."""
def __init__(self, feature_length, layersNumber):
"""Given all vectors of this polyline, we ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SubGraph:
"""Subgraph of VectorNet. This network accept a number of initiated vectors belong to the same polyline, flow three layers of network, then output this polyline's feature vector."""
def __init__(self, feature_length, layersNumber):
"""Given all vectors of this polyline, we should build ... | the_stack_v2_python_sparse | sub_graph.py | JieFeng-cse/dynamic_driving | train | 1 |
f2f9bb9410af21e09d3f5c0e4b95e135fda2980e | [
"if out_frames not in self.VALID_OUT_FRAMES:\n raise ValueError('Invalid number of frames in desired output: %d' % out_frames)\nsuper(Generator, self).__init__()\nself.gen_name = gen_name\nself.out_frames = out_frames\nlayer_out_channels = {'conv_1a': 256, 'conv_1b': 256, 'conv_2a': 256, 'conv_2b': 256, 'rdn_blo... | <|body_start_0|>
if out_frames not in self.VALID_OUT_FRAMES:
raise ValueError('Invalid number of frames in desired output: %d' % out_frames)
super(Generator, self).__init__()
self.gen_name = gen_name
self.out_frames = out_frames
layer_out_channels = {'conv_1a': 256, '... | Class representing the Generator network to be used. | Generator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Generator:
"""Class representing the Generator network to be used."""
def __init__(self, in_channels, out_frames, gen_name='Video Generator'):
"""Initializes the Generator network. :param in_channels: (int) The number of channels in the input tensor. :param out_frames: (int) The numb... | stack_v2_sparse_classes_10k_train_004022 | 14,041 | no_license | [
{
"docstring": "Initializes the Generator network. :param in_channels: (int) The number of channels in the input tensor. :param out_frames: (int) The number of frames desired in the generated output video. Legal values: 8, 16 :param gen_name: (str, optional) The name of the network (default 'Video Generator'). ... | 2 | stack_v2_sparse_classes_30k_train_003488 | Implement the Python class `Generator` described below.
Class description:
Class representing the Generator network to be used.
Method signatures and docstrings:
- def __init__(self, in_channels, out_frames, gen_name='Video Generator'): Initializes the Generator network. :param in_channels: (int) The number of channe... | Implement the Python class `Generator` described below.
Class description:
Class representing the Generator network to be used.
Method signatures and docstrings:
- def __init__(self, in_channels, out_frames, gen_name='Video Generator'): Initializes the Generator network. :param in_channels: (int) The number of channe... | 6de28b5a8992f6122f2e9813de8b92d9e97ccbf3 | <|skeleton|>
class Generator:
"""Class representing the Generator network to be used."""
def __init__(self, in_channels, out_frames, gen_name='Video Generator'):
"""Initializes the Generator network. :param in_channels: (int) The number of channels in the input tensor. :param out_frames: (int) The numb... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Generator:
"""Class representing the Generator network to be used."""
def __init__(self, in_channels, out_frames, gen_name='Video Generator'):
"""Initializes the Generator network. :param in_channels: (int) The number of channels in the input tensor. :param out_frames: (int) The number of frames ... | the_stack_v2_python_sparse | 1recon/generator.py | schatzkara/REU2019 | train | 0 |
138eb3ab5e261f8bc5ec13406a1c5a1a472aa0a6 | [
"self.application_id_local = kwargs.pop('id')\nself.child = kwargs.pop('child')\nsuper(OtherPeopleChildrenDetailsForm, self).__init__(*args, **kwargs)\nfull_stop_stripper(self)\nif ChildInHome.objects.filter(application_id=self.application_id_local, child=self.child).count() > 0:\n child_record = ChildInHome.obj... | <|body_start_0|>
self.application_id_local = kwargs.pop('id')
self.child = kwargs.pop('child')
super(OtherPeopleChildrenDetailsForm, self).__init__(*args, **kwargs)
full_stop_stripper(self)
if ChildInHome.objects.filter(application_id=self.application_id_local, child=self.child).... | GOV.UK form for the People in your home: children details page | OtherPeopleChildrenDetailsForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OtherPeopleChildrenDetailsForm:
"""GOV.UK form for the People in your home: children details page"""
def __init__(self, *args, **kwargs):
"""Method to configure the initialisation of the People in your home: children details form :param args: arguments passed to the form :param kwarg... | stack_v2_sparse_classes_10k_train_004023 | 20,631 | no_license | [
{
"docstring": "Method to configure the initialisation of the People in your home: children details form :param args: arguments passed to the form :param kwargs: keyword arguments passed to the form, e.g. application ID",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
... | 5 | stack_v2_sparse_classes_30k_train_000455 | Implement the Python class `OtherPeopleChildrenDetailsForm` described below.
Class description:
GOV.UK form for the People in your home: children details page
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Method to configure the initialisation of the People in your home: children details fo... | Implement the Python class `OtherPeopleChildrenDetailsForm` described below.
Class description:
GOV.UK form for the People in your home: children details page
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Method to configure the initialisation of the People in your home: children details fo... | fa6ca6a8164763e1dfe1581702ca5d36e44859de | <|skeleton|>
class OtherPeopleChildrenDetailsForm:
"""GOV.UK form for the People in your home: children details page"""
def __init__(self, *args, **kwargs):
"""Method to configure the initialisation of the People in your home: children details form :param args: arguments passed to the form :param kwarg... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OtherPeopleChildrenDetailsForm:
"""GOV.UK form for the People in your home: children details page"""
def __init__(self, *args, **kwargs):
"""Method to configure the initialisation of the People in your home: children details form :param args: arguments passed to the form :param kwargs: keyword ar... | the_stack_v2_python_sparse | application/forms/other_people.py | IS-JAQU-CAZ/OFS-MORE-Childminder-Website | train | 0 |
86db4818ef9479e48d34659300a17cd3707f2705 | [
"super().__init__()\nself._pad = (kernel_size - 1) * dilation\nself.causal_conv1d = torch.nn.Conv1d(idim, odim, kernel_size=kernel_size, stride=stride, padding=self._pad, dilation=dilation, groups=groups, bias=bias)",
"x = x.permute(0, 2, 1)\nx = self.causal_conv1d(x)\nif self._pad != 0:\n x = x[:, :, :-self._... | <|body_start_0|>
super().__init__()
self._pad = (kernel_size - 1) * dilation
self.causal_conv1d = torch.nn.Conv1d(idim, odim, kernel_size=kernel_size, stride=stride, padding=self._pad, dilation=dilation, groups=groups, bias=bias)
<|end_body_0|>
<|body_start_1|>
x = x.permute(0, 2, 1)
... | CausalConv1d module for transformer decoder. Args: idim (int): dimension of inputs odim (int): dimension of outputs kernel_size (int): size of convolving kernel stride (int): stride of the convolution dilation (int): spacing between the kernel points groups (int): number of blocked connections from ichannels to ochanne... | CausalConv1d | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CausalConv1d:
"""CausalConv1d module for transformer decoder. Args: idim (int): dimension of inputs odim (int): dimension of outputs kernel_size (int): size of convolving kernel stride (int): stride of the convolution dilation (int): spacing between the kernel points groups (int): number of block... | stack_v2_sparse_classes_10k_train_004024 | 1,614 | permissive | [
{
"docstring": "Construct a CausalConv1d object.",
"name": "__init__",
"signature": "def __init__(self, idim, odim, kernel_size, stride=1, dilation=1, groups=1, bias=True)"
},
{
"docstring": "CausalConv1d forward for x. Args: x (torch.Tensor): input torch (B, U, idim) x_mask (torch.Tensor): (B, ... | 2 | stack_v2_sparse_classes_30k_train_000559 | Implement the Python class `CausalConv1d` described below.
Class description:
CausalConv1d module for transformer decoder. Args: idim (int): dimension of inputs odim (int): dimension of outputs kernel_size (int): size of convolving kernel stride (int): stride of the convolution dilation (int): spacing between the kern... | Implement the Python class `CausalConv1d` described below.
Class description:
CausalConv1d module for transformer decoder. Args: idim (int): dimension of inputs odim (int): dimension of outputs kernel_size (int): size of convolving kernel stride (int): stride of the convolution dilation (int): spacing between the kern... | 6ecde88045e1b706b2390f98eb1950ce4075a07d | <|skeleton|>
class CausalConv1d:
"""CausalConv1d module for transformer decoder. Args: idim (int): dimension of inputs odim (int): dimension of outputs kernel_size (int): size of convolving kernel stride (int): stride of the convolution dilation (int): spacing between the kernel points groups (int): number of block... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CausalConv1d:
"""CausalConv1d module for transformer decoder. Args: idim (int): dimension of inputs odim (int): dimension of outputs kernel_size (int): size of convolving kernel stride (int): stride of the convolution dilation (int): spacing between the kernel points groups (int): number of blocked connection... | the_stack_v2_python_sparse | espnet/nets/pytorch_backend/transducer/causal_conv1d.py | sw005320/espnet-1 | train | 4 |
368805339ecb374d96d348d36e86426af6571248 | [
"format_file = DataSaver.FORMAT_CSV\nkwargs = locals()\n_apply_datasaver(format_file, kwargs, last_uuid)\nreturn None",
"format_file = DataSaver.FORMAT_JSON\nkwargs = locals()\n_apply_datasaver(format_file, kwargs, last_uuid)\nreturn None",
"format_file = DataSaver.FORMAT_PARQUET\nkwargs = locals()\n_apply_data... | <|body_start_0|>
format_file = DataSaver.FORMAT_CSV
kwargs = locals()
_apply_datasaver(format_file, kwargs, last_uuid)
return None
<|end_body_0|>
<|body_start_1|>
format_file = DataSaver.FORMAT_JSON
kwargs = locals()
_apply_datasaver(format_file, kwargs, last_uui... | Save | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Save:
def csv(filepath, header=True, mode=DataSaver.MODE_OVERWRITE, sep=',', na_rep='', float_format=None, columns=None, encoding=None, quoting=None, quotechar='"', date_format=None, doublequote=True, escapechar=None, decimal='.'):
"""Saves a csv file. :param filepath: :param header: :pa... | stack_v2_sparse_classes_10k_train_004025 | 3,936 | permissive | [
{
"docstring": "Saves a csv file. :param filepath: :param header: :param mode: :param sep: :param na_rep: :param float_format: :param columns: :param encoding: :param quoting: :param quotechar: :param date_format: :param doublequote: :param escapechar: :param decimal: :return:",
"name": "csv",
"signatur... | 4 | stack_v2_sparse_classes_30k_train_006315 | Implement the Python class `Save` described below.
Class description:
Implement the Save class.
Method signatures and docstrings:
- def csv(filepath, header=True, mode=DataSaver.MODE_OVERWRITE, sep=',', na_rep='', float_format=None, columns=None, encoding=None, quoting=None, quotechar='"', date_format=None, doublequo... | Implement the Python class `Save` described below.
Class description:
Implement the Save class.
Method signatures and docstrings:
- def csv(filepath, header=True, mode=DataSaver.MODE_OVERWRITE, sep=',', na_rep='', float_format=None, columns=None, encoding=None, quoting=None, quotechar='"', date_format=None, doublequo... | 09ab7c474c8badc9932de3e1148f62ffba16b0b2 | <|skeleton|>
class Save:
def csv(filepath, header=True, mode=DataSaver.MODE_OVERWRITE, sep=',', na_rep='', float_format=None, columns=None, encoding=None, quoting=None, quotechar='"', date_format=None, doublequote=True, escapechar=None, decimal='.'):
"""Saves a csv file. :param filepath: :param header: :pa... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Save:
def csv(filepath, header=True, mode=DataSaver.MODE_OVERWRITE, sep=',', na_rep='', float_format=None, columns=None, encoding=None, quoting=None, quotechar='"', date_format=None, doublequote=True, escapechar=None, decimal='.'):
"""Saves a csv file. :param filepath: :param header: :param mode: :par... | the_stack_v2_python_sparse | ddf_library/bases/data_saver.py | eubr-bigsea/Compss-Python | train | 3 | |
2d1f1f1067da6e69c84ea8f6a9c9fb338d2247d9 | [
"self.setup = setup\nself.merge_fields = merge_fields\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\nsetup = idfy_rest_client.models.setup.Setup.from_dictionary(dictionary.get('setup')) if dictionary.get('setup') else None\nmerge_fields = dictionary.get('mergeField... | <|body_start_0|>
self.setup = setup
self.merge_fields = merge_fields
self.additional_properties = additional_properties
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
setup = idfy_rest_client.models.setup.Setup.from_dictionary(dictionary.get('setu... | Implementation of the 'Notifications' model. TODO: type model description here. Attributes: setup (Setup): Setup what kind of notifications this signer should get. Defaults to off merge_fields (dict<object, string>): If you create your own notifications texts (See the root object -> Notification), you can create you... | Notifications | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Notifications:
"""Implementation of the 'Notifications' model. TODO: type model description here. Attributes: setup (Setup): Setup what kind of notifications this signer should get. Defaults to off merge_fields (dict<object, string>): If you create your own notifications texts (See the root objec... | stack_v2_sparse_classes_10k_train_004026 | 2,680 | permissive | [
{
"docstring": "Constructor for the Notifications class",
"name": "__init__",
"signature": "def __init__(self, setup=None, merge_fields=None, additional_properties={})"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representati... | 2 | stack_v2_sparse_classes_30k_train_000244 | Implement the Python class `Notifications` described below.
Class description:
Implementation of the 'Notifications' model. TODO: type model description here. Attributes: setup (Setup): Setup what kind of notifications this signer should get. Defaults to off merge_fields (dict<object, string>): If you create your own ... | Implement the Python class `Notifications` described below.
Class description:
Implementation of the 'Notifications' model. TODO: type model description here. Attributes: setup (Setup): Setup what kind of notifications this signer should get. Defaults to off merge_fields (dict<object, string>): If you create your own ... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class Notifications:
"""Implementation of the 'Notifications' model. TODO: type model description here. Attributes: setup (Setup): Setup what kind of notifications this signer should get. Defaults to off merge_fields (dict<object, string>): If you create your own notifications texts (See the root objec... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Notifications:
"""Implementation of the 'Notifications' model. TODO: type model description here. Attributes: setup (Setup): Setup what kind of notifications this signer should get. Defaults to off merge_fields (dict<object, string>): If you create your own notifications texts (See the root object -> Notif... | the_stack_v2_python_sparse | idfy_rest_client/models/notifications.py | dealflowteam/Idfy | train | 0 |
fdfb16032d63dccfe736757871f28ac55b96b3da | [
"self.label = label\nwith h5py.File(filename, 'r') as f:\n data = f[self.label]\n self.distance = data['D'].value\n self.N = len(self.distance)\n glon = data['glon'].value\n glat = data['glat'].value\n self.coord = get_coordinates(glon, glat)\nself.unit_vector = coord_to_uv(self.coord)",
"write_... | <|body_start_0|>
self.label = label
with h5py.File(filename, 'r') as f:
data = f[self.label]
self.distance = data['D'].value
self.N = len(self.distance)
glon = data['glon'].value
glat = data['glat'].value
self.coord = get_coordinate... | Stores the data and parameters for sources. | Source | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Source:
"""Stores the data and parameters for sources."""
def __init__(self, filename, label):
"""Stores the data and parameters for sources. :param filename: file ocntaining source data :param label: identifier"""
<|body_0|>
def plot(self, style, skymap):
"""Plo... | stack_v2_sparse_classes_10k_train_004027 | 15,467 | no_license | [
{
"docstring": "Stores the data and parameters for sources. :param filename: file ocntaining source data :param label: identifier",
"name": "__init__",
"signature": "def __init__(self, filename, label)"
},
{
"docstring": "Plot the sources on a map of the sky. Called by Data.show() :param style: ... | 4 | stack_v2_sparse_classes_30k_train_004841 | Implement the Python class `Source` described below.
Class description:
Stores the data and parameters for sources.
Method signatures and docstrings:
- def __init__(self, filename, label): Stores the data and parameters for sources. :param filename: file ocntaining source data :param label: identifier
- def plot(self... | Implement the Python class `Source` described below.
Class description:
Stores the data and parameters for sources.
Method signatures and docstrings:
- def __init__(self, filename, label): Stores the data and parameters for sources. :param filename: file ocntaining source data :param label: identifier
- def plot(self... | 0c1894ce8d9f5daed539240d3ac86e645d6de44c | <|skeleton|>
class Source:
"""Stores the data and parameters for sources."""
def __init__(self, filename, label):
"""Stores the data and parameters for sources. :param filename: file ocntaining source data :param label: identifier"""
<|body_0|>
def plot(self, style, skymap):
"""Plo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Source:
"""Stores the data and parameters for sources."""
def __init__(self, filename, label):
"""Stores the data and parameters for sources. :param filename: file ocntaining source data :param label: identifier"""
self.label = label
with h5py.File(filename, 'r') as f:
... | the_stack_v2_python_sparse | stan_implementation/analysis_interface/interfaces/data.py | cescalara/soiaporn_model | train | 1 |
565ee0808c7de8bfc0c3aeecc8894f18786e1944 | [
"test_data = recipe_test_api.TestData()\ntest_data.expect_exception(EXC.__name__)\nself.assertFalse(test_data.consumed)\nwith test_data.should_raise_exception(EXC()) as should_raise:\n self.assertFalse(should_raise)\nwith test_data.should_raise_exception(ValueError()) as should_raise:\n self.assertTrue(should... | <|body_start_0|>
test_data = recipe_test_api.TestData()
test_data.expect_exception(EXC.__name__)
self.assertFalse(test_data.consumed)
with test_data.should_raise_exception(EXC()) as should_raise:
self.assertFalse(should_raise)
with test_data.should_raise_exception(Val... | TestExpectedException | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestExpectedException:
def testRecognizeException(self):
"""An expected exception is correctly recognized."""
<|body_0|>
def testNewException(self):
"""An unexpected exception results in being told to re-raise ."""
<|body_1|>
def testDisabledTestData(sel... | stack_v2_sparse_classes_10k_train_004028 | 1,452 | permissive | [
{
"docstring": "An expected exception is correctly recognized.",
"name": "testRecognizeException",
"signature": "def testRecognizeException(self)"
},
{
"docstring": "An unexpected exception results in being told to re-raise .",
"name": "testNewException",
"signature": "def testNewExcepti... | 3 | stack_v2_sparse_classes_30k_train_002835 | Implement the Python class `TestExpectedException` described below.
Class description:
Implement the TestExpectedException class.
Method signatures and docstrings:
- def testRecognizeException(self): An expected exception is correctly recognized.
- def testNewException(self): An unexpected exception results in being ... | Implement the Python class `TestExpectedException` described below.
Class description:
Implement the TestExpectedException class.
Method signatures and docstrings:
- def testRecognizeException(self): An expected exception is correctly recognized.
- def testNewException(self): An unexpected exception results in being ... | 91c13923c1d136dc688527fa39583ef61a3277f7 | <|skeleton|>
class TestExpectedException:
def testRecognizeException(self):
"""An expected exception is correctly recognized."""
<|body_0|>
def testNewException(self):
"""An unexpected exception results in being told to re-raise ."""
<|body_1|>
def testDisabledTestData(sel... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestExpectedException:
def testRecognizeException(self):
"""An expected exception is correctly recognized."""
test_data = recipe_test_api.TestData()
test_data.expect_exception(EXC.__name__)
self.assertFalse(test_data.consumed)
with test_data.should_raise_exception(EXC()... | the_stack_v2_python_sparse | recipe_engine/unittests/recipe_test_api_test.py | DalavanCloud/recipes-py | train | 1 | |
ce62854d93d713c3085b9ea2038b607f067d7e81 | [
"self._parameters = parameters\nif not hasattr(self, '_mapper'):\n self._mapper = AWSProviderMap(provider=self.provider, report_type=parameters.report_type, cost_type=parameters.parameters.get('cost_type', KOKU_DEFAULT_COST_TYPE))\nif parameters.get_filter('enabled') is None:\n parameters.set_filter(**{'enabl... | <|body_start_0|>
self._parameters = parameters
if not hasattr(self, '_mapper'):
self._mapper = AWSProviderMap(provider=self.provider, report_type=parameters.report_type, cost_type=parameters.parameters.get('cost_type', KOKU_DEFAULT_COST_TYPE))
if parameters.get_filter('enabled') is N... | Handles tag queries and responses for AWS. | AWSTagQueryHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AWSTagQueryHandler:
"""Handles tag queries and responses for AWS."""
def __init__(self, parameters):
"""Establish AWS report query handler. Args: parameters (QueryParameters): parameter object for query"""
<|body_0|>
def filter_map(self):
"""Establish which filte... | stack_v2_sparse_classes_10k_train_004029 | 3,275 | permissive | [
{
"docstring": "Establish AWS report query handler. Args: parameters (QueryParameters): parameter object for query",
"name": "__init__",
"signature": "def __init__(self, parameters)"
},
{
"docstring": "Establish which filter map to use based on tag API.",
"name": "filter_map",
"signature... | 2 | stack_v2_sparse_classes_30k_train_000131 | Implement the Python class `AWSTagQueryHandler` described below.
Class description:
Handles tag queries and responses for AWS.
Method signatures and docstrings:
- def __init__(self, parameters): Establish AWS report query handler. Args: parameters (QueryParameters): parameter object for query
- def filter_map(self): ... | Implement the Python class `AWSTagQueryHandler` described below.
Class description:
Handles tag queries and responses for AWS.
Method signatures and docstrings:
- def __init__(self, parameters): Establish AWS report query handler. Args: parameters (QueryParameters): parameter object for query
- def filter_map(self): ... | 0416e5216eb1ec4b41c8dd4999adde218b1ab2e1 | <|skeleton|>
class AWSTagQueryHandler:
"""Handles tag queries and responses for AWS."""
def __init__(self, parameters):
"""Establish AWS report query handler. Args: parameters (QueryParameters): parameter object for query"""
<|body_0|>
def filter_map(self):
"""Establish which filte... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AWSTagQueryHandler:
"""Handles tag queries and responses for AWS."""
def __init__(self, parameters):
"""Establish AWS report query handler. Args: parameters (QueryParameters): parameter object for query"""
self._parameters = parameters
if not hasattr(self, '_mapper'):
... | the_stack_v2_python_sparse | koku/api/tags/aws/queries.py | project-koku/koku | train | 225 |
8322793999b2280abe1ac321caf63c915a658c36 | [
"defaults = super(ResConfigSettings, self).default_get(fields)\ndefaults['commission_based_on'] = self.env['ir.config_parameter'].sudo().get_param('sales_commission_ept.commission_based_on')\ndefaults['manager_commission_calculation'] = self.env['ir.config_parameter'].sudo().get_param('sales_commission_ept.manager_... | <|body_start_0|>
defaults = super(ResConfigSettings, self).default_get(fields)
defaults['commission_based_on'] = self.env['ir.config_parameter'].sudo().get_param('sales_commission_ept.commission_based_on')
defaults['manager_commission_calculation'] = self.env['ir.config_parameter'].sudo().get_pa... | ResConfigSettings | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResConfigSettings:
def default_get(self, fields):
"""Fetches the value from the ir.config_parameter model and sets in the field :param fields: fields of the res.config.settings model :return: - dictionary of fields along with its value"""
<|body_0|>
def set_values(self):
... | stack_v2_sparse_classes_10k_train_004030 | 3,656 | no_license | [
{
"docstring": "Fetches the value from the ir.config_parameter model and sets in the field :param fields: fields of the res.config.settings model :return: - dictionary of fields along with its value",
"name": "default_get",
"signature": "def default_get(self, fields)"
},
{
"docstring": "To set t... | 2 | stack_v2_sparse_classes_30k_train_000521 | Implement the Python class `ResConfigSettings` described below.
Class description:
Implement the ResConfigSettings class.
Method signatures and docstrings:
- def default_get(self, fields): Fetches the value from the ir.config_parameter model and sets in the field :param fields: fields of the res.config.settings model... | Implement the Python class `ResConfigSettings` described below.
Class description:
Implement the ResConfigSettings class.
Method signatures and docstrings:
- def default_get(self, fields): Fetches the value from the ir.config_parameter model and sets in the field :param fields: fields of the res.config.settings model... | 0ac91c708e0225bc335326fd2bdb0213ac29eb95 | <|skeleton|>
class ResConfigSettings:
def default_get(self, fields):
"""Fetches the value from the ir.config_parameter model and sets in the field :param fields: fields of the res.config.settings model :return: - dictionary of fields along with its value"""
<|body_0|>
def set_values(self):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ResConfigSettings:
def default_get(self, fields):
"""Fetches the value from the ir.config_parameter model and sets in the field :param fields: fields of the res.config.settings model :return: - dictionary of fields along with its value"""
defaults = super(ResConfigSettings, self).default_get(f... | the_stack_v2_python_sparse | sales_commission_ept/models/res_config_settings.py | shankarp-emipro/odoo_practicals_2_170683 | train | 0 | |
6b04bb6d719f32a86b1bc83ce357179226385ced | [
"self.num_hypotheses = num_hypotheses\nself.__name__ = 'mhp_loss'\nif avg_weight > 0.25 or avg_weight < 0.0:\n raise RuntimeError('avg_weight must be in [0,0.25]')\nself.avg_weight = avg_weight\nself.min_weight = 1.0 - self.avg_weight\nself.kl_weight = 0.001\nself.loss = keras.losses.get(loss)",
"xsum = tf.zer... | <|body_start_0|>
self.num_hypotheses = num_hypotheses
self.__name__ = 'mhp_loss'
if avg_weight > 0.25 or avg_weight < 0.0:
raise RuntimeError('avg_weight must be in [0,0.25]')
self.avg_weight = avg_weight
self.min_weight = 1.0 - self.avg_weight
self.kl_weight ... | Defines Christian Rupprecht's multiple-hypothesis loss function. This one operates on multiple hypothesis samples. This version is designed for use with data of one type of output (e.g. an image). ArXiv: https://arxiv.org/pdf/1612.00197.pdf BibTex: @article{rupprecht2016learning, title={Learning in an Uncertain World: ... | MhpLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MhpLoss:
"""Defines Christian Rupprecht's multiple-hypothesis loss function. This one operates on multiple hypothesis samples. This version is designed for use with data of one type of output (e.g. an image). ArXiv: https://arxiv.org/pdf/1612.00197.pdf BibTex: @article{rupprecht2016learning, titl... | stack_v2_sparse_classes_10k_train_004031 | 7,780 | permissive | [
{
"docstring": "Set up the MHP loss function. Parameters: ----------- num_hypotheses: number of targets to generate (e.g., predict 8 possible future images). num_outputs: number of output variables per hypothesis (e.g., 64x64x3 for a 64x64 RGB image). Currently deprecated, but may be necessary later on.",
"... | 2 | null | Implement the Python class `MhpLoss` described below.
Class description:
Defines Christian Rupprecht's multiple-hypothesis loss function. This one operates on multiple hypothesis samples. This version is designed for use with data of one type of output (e.g. an image). ArXiv: https://arxiv.org/pdf/1612.00197.pdf BibTe... | Implement the Python class `MhpLoss` described below.
Class description:
Defines Christian Rupprecht's multiple-hypothesis loss function. This one operates on multiple hypothesis samples. This version is designed for use with data of one type of output (e.g. an image). ArXiv: https://arxiv.org/pdf/1612.00197.pdf BibTe... | be5c12f9d0e9d7078e6a5c283d3be059e7f3d040 | <|skeleton|>
class MhpLoss:
"""Defines Christian Rupprecht's multiple-hypothesis loss function. This one operates on multiple hypothesis samples. This version is designed for use with data of one type of output (e.g. an image). ArXiv: https://arxiv.org/pdf/1612.00197.pdf BibTex: @article{rupprecht2016learning, titl... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MhpLoss:
"""Defines Christian Rupprecht's multiple-hypothesis loss function. This one operates on multiple hypothesis samples. This version is designed for use with data of one type of output (e.g. an image). ArXiv: https://arxiv.org/pdf/1612.00197.pdf BibTex: @article{rupprecht2016learning, title={Learning i... | the_stack_v2_python_sparse | costar_models/python/costar_models/mhp_loss.py | lk-greenbird/costar_plan | train | 0 |
4dd71521fc9f541fa996d6d0e45f2b1f4d3ca673 | [
"if not root:\n return ''\nreturn str(root.val) + ',' + self.serialize(root.left) + ',' + self.serialize(root.right)",
"def dfs(data):\n if not data:\n return\n val = data.popleft()\n if not val:\n return\n root = TreeNode(int(val))\n root.left = dfs(data)\n root.right = dfs(dat... | <|body_start_0|>
if not root:
return ''
return str(root.val) + ',' + self.serialize(root.left) + ',' + self.serialize(root.right)
<|end_body_0|>
<|body_start_1|>
def dfs(data):
if not data:
return
val = data.popleft()
if not val:
... | 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_10k_train_004032 | 6,040 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 0324d247a5567745cc1a48b215066d4aa796abd8 | <|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_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
return str(root.val) + ',' + self.serialize(root.left) + ',' + self.serialize(root.right)
def deserialize(self, data):
"""Decodes ... | the_stack_v2_python_sparse | Tree/Codec.py | BruceHi/leetcode | train | 1 | |
1594a09317edb4bc228dbb1cfb1cf4998336d3d8 | [
"try:\n respone = super().post(request, *args, **kwargs)\n complaint = request.data['complaint']\n comp = ComplaintModel.objects.get(id=complaint)\n comp.like_count += 1\n comp.save()\nexcept Exception as e:\n raise e\nelse:\n return respone",
"complaint_like = self.queryset.filter(complaint=... | <|body_start_0|>
try:
respone = super().post(request, *args, **kwargs)
complaint = request.data['complaint']
comp = ComplaintModel.objects.get(id=complaint)
comp.like_count += 1
comp.save()
except Exception as e:
raise e
els... | 吐槽点赞 | ComplaintLikeView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComplaintLikeView:
"""吐槽点赞"""
def post(self, request, *args, **kwargs):
"""点赞"""
<|body_0|>
def destroy(self, request, complaint, *args, **kwargs):
"""取消点赞"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
respone = super().post(r... | stack_v2_sparse_classes_10k_train_004033 | 9,460 | no_license | [
{
"docstring": "点赞",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
},
{
"docstring": "取消点赞",
"name": "destroy",
"signature": "def destroy(self, request, complaint, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007329 | Implement the Python class `ComplaintLikeView` described below.
Class description:
吐槽点赞
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): 点赞
- def destroy(self, request, complaint, *args, **kwargs): 取消点赞 | Implement the Python class `ComplaintLikeView` described below.
Class description:
吐槽点赞
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): 点赞
- def destroy(self, request, complaint, *args, **kwargs): 取消点赞
<|skeleton|>
class ComplaintLikeView:
"""吐槽点赞"""
def post(self, request, *ar... | c0df44858d0951e345de245505ae8f71f8b5e1b6 | <|skeleton|>
class ComplaintLikeView:
"""吐槽点赞"""
def post(self, request, *args, **kwargs):
"""点赞"""
<|body_0|>
def destroy(self, request, complaint, *args, **kwargs):
"""取消点赞"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ComplaintLikeView:
"""吐槽点赞"""
def post(self, request, *args, **kwargs):
"""点赞"""
try:
respone = super().post(request, *args, **kwargs)
complaint = request.data['complaint']
comp = ComplaintModel.objects.get(id=complaint)
comp.like_count += 1... | the_stack_v2_python_sparse | mlh/apps/complaints/views.py | AmirHuang/mlh | train | 0 |
cf2abb2da66eb777a9103819f2f2ec2a871a5453 | [
"self._validator = None\nself.logger = logger\nif api_spec_path is not None:\n try:\n api_spec_dict = read_yaml_file(api_spec_path)\n if server is not None:\n api_spec_dict['servers'] = [{'url': server}]\n api_spec = create_spec(api_spec_dict)\n self._validator = RequestVal... | <|body_start_0|>
self._validator = None
self.logger = logger
if api_spec_path is not None:
try:
api_spec_dict = read_yaml_file(api_spec_path)
if server is not None:
api_spec_dict['servers'] = [{'url': server}]
api_sp... | API Spec class to verify a request against an OpenAPI/Swagger spec. | APISpec | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class APISpec:
"""API Spec class to verify a request against an OpenAPI/Swagger spec."""
def __init__(self, api_spec_path: Optional[str]=None, server: Optional[str]=None, logger: logging.Logger=_default_logger):
"""Initialize the API spec. :param api_spec_path: Directory API path and filen... | stack_v2_sparse_classes_10k_train_004034 | 21,668 | permissive | [
{
"docstring": "Initialize the API spec. :param api_spec_path: Directory API path and filename of the API spec YAML source file. :param server: the server url :param logger: the logger",
"name": "__init__",
"signature": "def __init__(self, api_spec_path: Optional[str]=None, server: Optional[str]=None, l... | 2 | null | Implement the Python class `APISpec` described below.
Class description:
API Spec class to verify a request against an OpenAPI/Swagger spec.
Method signatures and docstrings:
- def __init__(self, api_spec_path: Optional[str]=None, server: Optional[str]=None, logger: logging.Logger=_default_logger): Initialize the API... | Implement the Python class `APISpec` described below.
Class description:
API Spec class to verify a request against an OpenAPI/Swagger spec.
Method signatures and docstrings:
- def __init__(self, api_spec_path: Optional[str]=None, server: Optional[str]=None, logger: logging.Logger=_default_logger): Initialize the API... | bec49adaeba661d8d0f03ac9935dc89f39d95a0d | <|skeleton|>
class APISpec:
"""API Spec class to verify a request against an OpenAPI/Swagger spec."""
def __init__(self, api_spec_path: Optional[str]=None, server: Optional[str]=None, logger: logging.Logger=_default_logger):
"""Initialize the API spec. :param api_spec_path: Directory API path and filen... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class APISpec:
"""API Spec class to verify a request against an OpenAPI/Swagger spec."""
def __init__(self, api_spec_path: Optional[str]=None, server: Optional[str]=None, logger: logging.Logger=_default_logger):
"""Initialize the API spec. :param api_spec_path: Directory API path and filename of the AP... | the_stack_v2_python_sparse | packages/fetchai/connections/http_server/connection.py | fetchai/agents-aea | train | 192 |
e42a16a8d6f07839c8f8ddb707d52e4da6449ebf | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ArchivedPrintJob()",
"from .print_job_processing_state import PrintJobProcessingState\nfrom .user_identity import UserIdentity\nfrom .print_job_processing_state import PrintJobProcessingState\nfrom .user_identity import UserIdentity\nf... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ArchivedPrintJob()
<|end_body_0|>
<|body_start_1|>
from .print_job_processing_state import PrintJobProcessingState
from .user_identity import UserIdentity
from .print_job_process... | ArchivedPrintJob | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArchivedPrintJob:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ArchivedPrintJob:
"""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_10k_train_004035 | 5,408 | 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: ArchivedPrintJob",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_va... | 3 | null | Implement the Python class `ArchivedPrintJob` described below.
Class description:
Implement the ArchivedPrintJob class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ArchivedPrintJob: Creates a new instance of the appropriate class based on discrimina... | Implement the Python class `ArchivedPrintJob` described below.
Class description:
Implement the ArchivedPrintJob class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ArchivedPrintJob: Creates a new instance of the appropriate class based on discrimina... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ArchivedPrintJob:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ArchivedPrintJob:
"""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_10k | data/stack_v2_sparse_classes_30k | class ArchivedPrintJob:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ArchivedPrintJob:
"""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: Archiv... | the_stack_v2_python_sparse | msgraph/generated/models/archived_print_job.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
3eb37672c5c2aaecd1414adafbd63b921e597b4f | [
"self.radius = radius\nself.x_center = x_center\nself.y_center = y_center",
"radius = self.radius * sqrt(random())\ntheta = 2 * pi * random()\nreturn (self.x_center + radius * cos(theta), self.y_center + radius * sin(theta))"
] | <|body_start_0|>
self.radius = radius
self.x_center = x_center
self.y_center = y_center
<|end_body_0|>
<|body_start_1|>
radius = self.radius * sqrt(random())
theta = 2 * pi * random()
return (self.x_center + radius * cos(theta), self.y_center + radius * sin(theta))
<|end... | Solution | [
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, radius: float, x_center: float, y_center: float):
"""self.r, self.x, self.y = radius, x_center, y_center"""
<|body_0|>
def randPoint(self) -> List[float]:
"""theta = uniform(0, 2 * pi) R = self.r * sqrt(uniform(0, 1)) return [self.x + R *... | stack_v2_sparse_classes_10k_train_004036 | 2,229 | permissive | [
{
"docstring": "self.r, self.x, self.y = radius, x_center, y_center",
"name": "__init__",
"signature": "def __init__(self, radius: float, x_center: float, y_center: float)"
},
{
"docstring": "theta = uniform(0, 2 * pi) R = self.r * sqrt(uniform(0, 1)) return [self.x + R * cos(theta), self.y + R ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, radius: float, x_center: float, y_center: float): self.r, self.x, self.y = radius, x_center, y_center
- def randPoint(self) -> List[float]: theta = uniform(0, ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, radius: float, x_center: float, y_center: float): self.r, self.x, self.y = radius, x_center, y_center
- def randPoint(self) -> List[float]: theta = uniform(0, ... | 4ea4c1579c28308455be4dfa02bd45ebd88b2d0a | <|skeleton|>
class Solution:
def __init__(self, radius: float, x_center: float, y_center: float):
"""self.r, self.x, self.y = radius, x_center, y_center"""
<|body_0|>
def randPoint(self) -> List[float]:
"""theta = uniform(0, 2 * pi) R = self.r * sqrt(uniform(0, 1)) return [self.x + R *... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, radius: float, x_center: float, y_center: float):
"""self.r, self.x, self.y = radius, x_center, y_center"""
self.radius = radius
self.x_center = x_center
self.y_center = y_center
def randPoint(self) -> List[float]:
"""theta = uniform(0,... | the_stack_v2_python_sparse | src/arrays/randPoint.py | way2arun/datastructures_algorithms | train | 1 | |
66b0d04f9ff8ff6a25a73968d0081278f7593e60 | [
"entity = get_entity(self.request.session.get('token', False), self.kwargs['aiid'], self.kwargs['entity_name'])\nentity['entity_values'] = settings.TOKENFIELD_DELIMITER.join(entity['entity_values'])\nself.initial = entity\nreturn super(EntitiesUpdateView, self).get_initial(**kwargs)",
"context = super(EntitiesUpd... | <|body_start_0|>
entity = get_entity(self.request.session.get('token', False), self.kwargs['aiid'], self.kwargs['entity_name'])
entity['entity_values'] = settings.TOKENFIELD_DELIMITER.join(entity['entity_values'])
self.initial = entity
return super(EntitiesUpdateView, self).get_initial(*... | Single Entity view | EntitiesUpdateView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EntitiesUpdateView:
"""Single Entity view"""
def get_initial(self, **kwargs):
"""Get and prepare Entity data"""
<|body_0|>
def get_context_data(self, **kwargs):
"""Provide entity name for the template"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_004037 | 39,842 | permissive | [
{
"docstring": "Get and prepare Entity data",
"name": "get_initial",
"signature": "def get_initial(self, **kwargs)"
},
{
"docstring": "Provide entity name for the template",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005351 | Implement the Python class `EntitiesUpdateView` described below.
Class description:
Single Entity view
Method signatures and docstrings:
- def get_initial(self, **kwargs): Get and prepare Entity data
- def get_context_data(self, **kwargs): Provide entity name for the template | Implement the Python class `EntitiesUpdateView` described below.
Class description:
Single Entity view
Method signatures and docstrings:
- def get_initial(self, **kwargs): Get and prepare Entity data
- def get_context_data(self, **kwargs): Provide entity name for the template
<|skeleton|>
class EntitiesUpdateView:
... | d632d00f9a22a7a826bba4896a7102b2ac8690ff | <|skeleton|>
class EntitiesUpdateView:
"""Single Entity view"""
def get_initial(self, **kwargs):
"""Get and prepare Entity data"""
<|body_0|>
def get_context_data(self, **kwargs):
"""Provide entity name for the template"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EntitiesUpdateView:
"""Single Entity view"""
def get_initial(self, **kwargs):
"""Get and prepare Entity data"""
entity = get_entity(self.request.session.get('token', False), self.kwargs['aiid'], self.kwargs['entity_name'])
entity['entity_values'] = settings.TOKENFIELD_DELIMITER.jo... | the_stack_v2_python_sparse | src/studio/views.py | hutomadotAI/web-console | train | 6 |
453df5d56509724e346bede1f95801d911a90861 | [
"if not root:\n return\nl = self.invertTree(root.left)\nr = self.invertTree(root.right)\nroot.left = r\nroot.right = l\nreturn root",
"if root:\n self.invertTree(root.left)\n self.invertTree(root.right)\n root.left, root.right = (root.right, root.left)\nreturn root"
] | <|body_start_0|>
if not root:
return
l = self.invertTree(root.left)
r = self.invertTree(root.right)
root.left = r
root.right = l
return root
<|end_body_0|>
<|body_start_1|>
if root:
self.invertTree(root.left)
self.invertTree(ro... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
"""Nov 05, 2021 13:16"""
<|body_0|>
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
"""Mar 20, 2023 23:41"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_004038 | 1,710 | no_license | [
{
"docstring": "Nov 05, 2021 13:16",
"name": "invertTree",
"signature": "def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]"
},
{
"docstring": "Mar 20, 2023 23:41",
"name": "invertTree",
"signature": "def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: Nov 05, 2021 13:16
- def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: Mar 20, 2023 23:4... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: Nov 05, 2021 13:16
- def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: Mar 20, 2023 23:4... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
"""Nov 05, 2021 13:16"""
<|body_0|>
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
"""Mar 20, 2023 23:41"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
"""Nov 05, 2021 13:16"""
if not root:
return
l = self.invertTree(root.left)
r = self.invertTree(root.right)
root.left = r
root.right = l
return root
def inve... | the_stack_v2_python_sparse | leetcode/solved/226_Invert_Binary_Tree/solution.py | sungminoh/algorithms | train | 0 | |
c77345d5ba511683f93e85e494bf18806faf1002 | [
"C = self.COEFFS[imt]\nmag = rup.mag - 6\nd = np.sqrt(dists.rjb ** 2 + C['c7'] ** 2)\nmean = np.zeros_like(d)\nmean += C['c1'] + C['c2'] * mag + C['c3'] * mag ** 2 + C['c6']\nidx = d <= 100.0\nmean[idx] = mean[idx] + C['c5'] * np.log10(d[idx])\nidx = d > 100.0\nmean[idx] = mean[idx] + C['c5'] * np.log10(100.0) - np... | <|body_start_0|>
C = self.COEFFS[imt]
mag = rup.mag - 6
d = np.sqrt(dists.rjb ** 2 + C['c7'] ** 2)
mean = np.zeros_like(d)
mean += C['c1'] + C['c2'] * mag + C['c3'] * mag ** 2 + C['c6']
idx = d <= 100.0
mean[idx] = mean[idx] + C['c5'] * np.log10(d[idx])
id... | Implement equation used by the Geological Survey of Canada (GSC) for the 2010 Western Canada National Seismic Hazard Model. The class implements the model of David M. Boore, William B. Joyner, and Thomas E. Fumal ("Estimation of Response Spectra and Peak Accelerations from Western North American Earthquakes: An Interim... | BooreEtAl1993GSCBest | [
"BSD-3-Clause",
"AGPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BooreEtAl1993GSCBest:
"""Implement equation used by the Geological Survey of Canada (GSC) for the 2010 Western Canada National Seismic Hazard Model. The class implements the model of David M. Boore, William B. Joyner, and Thomas E. Fumal ("Estimation of Response Spectra and Peak Accelerations fro... | stack_v2_sparse_classes_10k_train_004039 | 7,227 | permissive | [
{
"docstring": "See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.",
"name": "get_mean_and_stddevs",
"signature": "def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types)"
},
{
"docstring": "Return total standa... | 2 | null | Implement the Python class `BooreEtAl1993GSCBest` described below.
Class description:
Implement equation used by the Geological Survey of Canada (GSC) for the 2010 Western Canada National Seismic Hazard Model. The class implements the model of David M. Boore, William B. Joyner, and Thomas E. Fumal ("Estimation of Resp... | Implement the Python class `BooreEtAl1993GSCBest` described below.
Class description:
Implement equation used by the Geological Survey of Canada (GSC) for the 2010 Western Canada National Seismic Hazard Model. The class implements the model of David M. Boore, William B. Joyner, and Thomas E. Fumal ("Estimation of Resp... | 0da9ba5a575360081715e8b90c71d4b16c6687c8 | <|skeleton|>
class BooreEtAl1993GSCBest:
"""Implement equation used by the Geological Survey of Canada (GSC) for the 2010 Western Canada National Seismic Hazard Model. The class implements the model of David M. Boore, William B. Joyner, and Thomas E. Fumal ("Estimation of Response Spectra and Peak Accelerations fro... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BooreEtAl1993GSCBest:
"""Implement equation used by the Geological Survey of Canada (GSC) for the 2010 Western Canada National Seismic Hazard Model. The class implements the model of David M. Boore, William B. Joyner, and Thomas E. Fumal ("Estimation of Response Spectra and Peak Accelerations from Western Nor... | the_stack_v2_python_sparse | openquake/hazardlib/gsim/boore_1993.py | GFZ-Centre-for-Early-Warning/shakyground | train | 1 |
ac37e5b443e7c473a0176322bc7df017a0c61f54 | [
"attr_map = {'node_uuid': 'uuid', 'bfd_admin_down_count': 'admin_down_count', 'bfd_init_count': 'init_count', 'bfd_up_count': 'up_count', 'bfd_down_count': 'down_count'}\nclient_class_obj = listtransportnodestatus.ListTransportNodeStatus(connection_object=client_obj.connection)\nstatus_schema_object = client_class_... | <|body_start_0|>
attr_map = {'node_uuid': 'uuid', 'bfd_admin_down_count': 'admin_down_count', 'bfd_init_count': 'init_count', 'bfd_up_count': 'up_count', 'bfd_down_count': 'down_count'}
client_class_obj = listtransportnodestatus.ListTransportNodeStatus(connection_object=client_obj.connection)
st... | NSX70AggregationImpl | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NSX70AggregationImpl:
def get_aggregation_transportnode_status(cls, client_obj, **kwargs):
"""Get status summary of all transport nodes under MP. @type client_object: ManagerAPIClient @param client_object: Client object @rtype: dict @return: Dict having status details of all TNs. Endpoin... | stack_v2_sparse_classes_10k_train_004040 | 4,454 | no_license | [
{
"docstring": "Get status summary of all transport nodes under MP. @type client_object: ManagerAPIClient @param client_object: Client object @rtype: dict @return: Dict having status details of all TNs. Endpoint: /aggregations/transport-node-status",
"name": "get_aggregation_transportnode_status",
"sign... | 3 | stack_v2_sparse_classes_30k_train_006630 | Implement the Python class `NSX70AggregationImpl` described below.
Class description:
Implement the NSX70AggregationImpl class.
Method signatures and docstrings:
- def get_aggregation_transportnode_status(cls, client_obj, **kwargs): Get status summary of all transport nodes under MP. @type client_object: ManagerAPICl... | Implement the Python class `NSX70AggregationImpl` described below.
Class description:
Implement the NSX70AggregationImpl class.
Method signatures and docstrings:
- def get_aggregation_transportnode_status(cls, client_obj, **kwargs): Get status summary of all transport nodes under MP. @type client_object: ManagerAPICl... | 5b55817c050b637e2747084290f6206d2e622938 | <|skeleton|>
class NSX70AggregationImpl:
def get_aggregation_transportnode_status(cls, client_obj, **kwargs):
"""Get status summary of all transport nodes under MP. @type client_object: ManagerAPIClient @param client_object: Client object @rtype: dict @return: Dict having status details of all TNs. Endpoin... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NSX70AggregationImpl:
def get_aggregation_transportnode_status(cls, client_obj, **kwargs):
"""Get status summary of all transport nodes under MP. @type client_object: ManagerAPIClient @param client_object: Client object @rtype: dict @return: Dict having status details of all TNs. Endpoint: /aggregatio... | the_stack_v2_python_sparse | SystemTesting/pylib/vmware/nsx/manager/api/nsx70_aggregation_impl.py | Cloudxtreme/MyProject | train | 0 | |
720d2a07ca675ad86e8903581955833b08d1330f | [
"edgeList.sort(key=lambda x: x[2])\nself.__uf = UnionFind(n)\nself.__adj = [[] for _ in xrange(n)]\nfor index, (i, j, weight) in enumerate(edgeList):\n if not self.__uf.union_set(i, j):\n continue\n self.__adj[i].append((j, weight))\n self.__adj[j].append((i, weight))\nself.__tree_infos = TreeInfos(... | <|body_start_0|>
edgeList.sort(key=lambda x: x[2])
self.__uf = UnionFind(n)
self.__adj = [[] for _ in xrange(n)]
for index, (i, j, weight) in enumerate(edgeList):
if not self.__uf.union_set(i, j):
continue
self.__adj[i].append((j, weight))
... | DistanceLimitedPathsExist | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DistanceLimitedPathsExist:
def __init__(self, n, edgeList):
""":type n: int :type edgeList: List[List[int]]"""
<|body_0|>
def query(self, p, q, limit):
""":type p: int :type q: int :type limit: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_10k_train_004041 | 7,205 | permissive | [
{
"docstring": ":type n: int :type edgeList: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, n, edgeList)"
},
{
"docstring": ":type p: int :type q: int :type limit: int :rtype: bool",
"name": "query",
"signature": "def query(self, p, q, limit)"
}
] | 2 | null | Implement the Python class `DistanceLimitedPathsExist` described below.
Class description:
Implement the DistanceLimitedPathsExist class.
Method signatures and docstrings:
- def __init__(self, n, edgeList): :type n: int :type edgeList: List[List[int]]
- def query(self, p, q, limit): :type p: int :type q: int :type li... | Implement the Python class `DistanceLimitedPathsExist` described below.
Class description:
Implement the DistanceLimitedPathsExist class.
Method signatures and docstrings:
- def __init__(self, n, edgeList): :type n: int :type edgeList: List[List[int]]
- def query(self, p, q, limit): :type p: int :type q: int :type li... | 4dc4e6642dc92f1983c13564cc0fd99917cab358 | <|skeleton|>
class DistanceLimitedPathsExist:
def __init__(self, n, edgeList):
""":type n: int :type edgeList: List[List[int]]"""
<|body_0|>
def query(self, p, q, limit):
""":type p: int :type q: int :type limit: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DistanceLimitedPathsExist:
def __init__(self, n, edgeList):
""":type n: int :type edgeList: List[List[int]]"""
edgeList.sort(key=lambda x: x[2])
self.__uf = UnionFind(n)
self.__adj = [[] for _ in xrange(n)]
for index, (i, j, weight) in enumerate(edgeList):
i... | the_stack_v2_python_sparse | Python/checking-existence-of-edge-length-limited-paths-ii.py | kamyu104/LeetCode-Solutions | train | 4,549 | |
aa959fe90a3bc4b2a533c0a62fce8a4d3619db6b | [
"self.component = component\nself.description = description\nself.id = id\nself.ip = ip\nself.netmask_bits = netmask_bits\nself.netmask_ip_4 = netmask_ip_4\nself.nfs_access = nfs_access\nself.nfs_all_squash = nfs_all_squash\nself.nfs_root_squash = nfs_root_squash\nself.s3_access = s3_access\nself.smb_access = smb_a... | <|body_start_0|>
self.component = component
self.description = description
self.id = id
self.ip = ip
self.netmask_bits = netmask_bits
self.netmask_ip_4 = netmask_ip_4
self.nfs_access = nfs_access
self.nfs_all_squash = nfs_all_squash
self.nfs_root_s... | Implementation of the 'Subnet' model. Defines a Subnet (Subnetwork). The netmask can be specified by setting netmaskBits or netmaskIp4. The netmask can only be set using netmaskIp4 if the IP address is an IPv4 address. Attributes: component (string): Component that has reserved the subnet. description (string): Descrip... | Subnet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Subnet:
"""Implementation of the 'Subnet' model. Defines a Subnet (Subnetwork). The netmask can be specified by setting netmaskBits or netmaskIp4. The netmask can only be set using netmaskIp4 if the IP address is an IPv4 address. Attributes: component (string): Component that has reserved the sub... | stack_v2_sparse_classes_10k_train_004042 | 5,189 | permissive | [
{
"docstring": "Constructor for the Subnet class",
"name": "__init__",
"signature": "def __init__(self, component=None, description=None, id=None, ip=None, netmask_bits=None, netmask_ip_4=None, nfs_access=None, nfs_all_squash=None, nfs_root_squash=None, s3_access=None, smb_access=None, tenant_id=None)"
... | 2 | stack_v2_sparse_classes_30k_train_004112 | Implement the Python class `Subnet` described below.
Class description:
Implementation of the 'Subnet' model. Defines a Subnet (Subnetwork). The netmask can be specified by setting netmaskBits or netmaskIp4. The netmask can only be set using netmaskIp4 if the IP address is an IPv4 address. Attributes: component (strin... | Implement the Python class `Subnet` described below.
Class description:
Implementation of the 'Subnet' model. Defines a Subnet (Subnetwork). The netmask can be specified by setting netmaskBits or netmaskIp4. The netmask can only be set using netmaskIp4 if the IP address is an IPv4 address. Attributes: component (strin... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class Subnet:
"""Implementation of the 'Subnet' model. Defines a Subnet (Subnetwork). The netmask can be specified by setting netmaskBits or netmaskIp4. The netmask can only be set using netmaskIp4 if the IP address is an IPv4 address. Attributes: component (string): Component that has reserved the sub... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Subnet:
"""Implementation of the 'Subnet' model. Defines a Subnet (Subnetwork). The netmask can be specified by setting netmaskBits or netmaskIp4. The netmask can only be set using netmaskIp4 if the IP address is an IPv4 address. Attributes: component (string): Component that has reserved the subnet. descript... | the_stack_v2_python_sparse | cohesity_management_sdk/models/subnet.py | cohesity/management-sdk-python | train | 24 |
2201e31140c9e94ce7f3e49d1f38c0e6fdda19f3 | [
"eva = board.evaluate()\nif eva != 999 and eva != 998:\n return eva\nif board.isEnded():\n return 0\nif beta <= alpha:\n return 0\nif isMax:\n for i in range(board.sizeofX):\n for j in range(board.sizeofY):\n if board.get(i, j) == 0:\n board.move(i, j, 'X')\n ... | <|body_start_0|>
eva = board.evaluate()
if eva != 999 and eva != 998:
return eva
if board.isEnded():
return 0
if beta <= alpha:
return 0
if isMax:
for i in range(board.sizeofX):
for j in range(board.sizeofY):
... | Computer for hard difficulty | SmartestComputer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SmartestComputer:
"""Computer for hard difficulty"""
def minmax(self, board, depth, isMax, alpha, beta):
"""minmax Function that finds the best value of a move Arguments: board {Board} -- Game board depth {int} -- depth of the tree isMax {bool} -- check if is max or min alpha {int} -... | stack_v2_sparse_classes_10k_train_004043 | 3,019 | no_license | [
{
"docstring": "minmax Function that finds the best value of a move Arguments: board {Board} -- Game board depth {int} -- depth of the tree isMax {bool} -- check if is max or min alpha {int} -- value of max function beta {int} -- value of min function Returns: int -- value of moveset",
"name": "minmax",
... | 2 | stack_v2_sparse_classes_30k_train_007117 | Implement the Python class `SmartestComputer` described below.
Class description:
Computer for hard difficulty
Method signatures and docstrings:
- def minmax(self, board, depth, isMax, alpha, beta): minmax Function that finds the best value of a move Arguments: board {Board} -- Game board depth {int} -- depth of the ... | Implement the Python class `SmartestComputer` described below.
Class description:
Computer for hard difficulty
Method signatures and docstrings:
- def minmax(self, board, depth, isMax, alpha, beta): minmax Function that finds the best value of a move Arguments: board {Board} -- Game board depth {int} -- depth of the ... | 9fbbb20a63813073ca1abcb73f0c1639bd9f5a76 | <|skeleton|>
class SmartestComputer:
"""Computer for hard difficulty"""
def minmax(self, board, depth, isMax, alpha, beta):
"""minmax Function that finds the best value of a move Arguments: board {Board} -- Game board depth {int} -- depth of the tree isMax {bool} -- check if is max or min alpha {int} -... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SmartestComputer:
"""Computer for hard difficulty"""
def minmax(self, board, depth, isMax, alpha, beta):
"""minmax Function that finds the best value of a move Arguments: board {Board} -- Game board depth {int} -- depth of the tree isMax {bool} -- check if is max or min alpha {int} -- value of ma... | the_stack_v2_python_sparse | Assignment 10/Computer.py | Taveeh/Fundamentals-of-Programming | train | 2 |
21703d416a3d715ae2205e74a456ac197f1b2f17 | [
"my_stack = []\nlength = len(nums)\nres = [-1] * length\nfor i in range(length):\n while my_stack and nums[my_stack[-1]] < nums[i]:\n res[my_stack.pop()] = nums[i]\n my_stack.append(i)\nfor i in range(length):\n while my_stack and nums[my_stack[-1]] < nums[i]:\n res[my_stack.pop()] = nums[i]\... | <|body_start_0|>
my_stack = []
length = len(nums)
res = [-1] * length
for i in range(length):
while my_stack and nums[my_stack[-1]] < nums[i]:
res[my_stack.pop()] = nums[i]
my_stack.append(i)
for i in range(length):
while my_sta... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nextGreaterElements(self, nums):
"""Stack solution O(n) :type nums: List[int] :rtype: List[int]"""
<|body_0|>
def nextGreaterElements2(self, nums):
"""Naive solution O(n^2) :type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_10k_train_004044 | 1,122 | no_license | [
{
"docstring": "Stack solution O(n) :type nums: List[int] :rtype: List[int]",
"name": "nextGreaterElements",
"signature": "def nextGreaterElements(self, nums)"
},
{
"docstring": "Naive solution O(n^2) :type nums: List[int] :rtype: List[int]",
"name": "nextGreaterElements2",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_005059 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextGreaterElements(self, nums): Stack solution O(n) :type nums: List[int] :rtype: List[int]
- def nextGreaterElements2(self, nums): Naive solution O(n^2) :type nums: List[in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextGreaterElements(self, nums): Stack solution O(n) :type nums: List[int] :rtype: List[int]
- def nextGreaterElements2(self, nums): Naive solution O(n^2) :type nums: List[in... | c14d8829c95f61ff6691816e8c0de76b9319f389 | <|skeleton|>
class Solution:
def nextGreaterElements(self, nums):
"""Stack solution O(n) :type nums: List[int] :rtype: List[int]"""
<|body_0|>
def nextGreaterElements2(self, nums):
"""Naive solution O(n^2) :type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def nextGreaterElements(self, nums):
"""Stack solution O(n) :type nums: List[int] :rtype: List[int]"""
my_stack = []
length = len(nums)
res = [-1] * length
for i in range(length):
while my_stack and nums[my_stack[-1]] < nums[i]:
res... | the_stack_v2_python_sparse | medium/next-greater-element-ii/solution.py | hsuanhauliu/leetcode-solutions | train | 0 | |
db2bdd7c70f8e62d120d5a90e91f0fc749c33cac | [
"if name == 'ALLOW_CHANGE':\n raise AttributeError(\"attribute name 'ALLOW_CHANGE' has been occupied, please use another name\")\nif getattr(self, 'ALLOW_CHANGE', None):\n self.__dict__[name] = value\nelse:\n raise AttributeReadOnlyError(self, name)",
"try:\n self.__dict__['ALLOW_CHANGE'] = True\n ... | <|body_start_0|>
if name == 'ALLOW_CHANGE':
raise AttributeError("attribute name 'ALLOW_CHANGE' has been occupied, please use another name")
if getattr(self, 'ALLOW_CHANGE', None):
self.__dict__[name] = value
else:
raise AttributeReadOnlyError(self, name)
<|en... | a base class whose attributes are read-only, unless use the context _context_allow_change to change attributes | ReadOnlySpace | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReadOnlySpace:
"""a base class whose attributes are read-only, unless use the context _context_allow_change to change attributes"""
def __setattr__(self, name, value):
"""attributes could not be change, unless in context _context_allow_change"""
<|body_0|>
def _context_a... | stack_v2_sparse_classes_10k_train_004045 | 1,524 | permissive | [
{
"docstring": "attributes could not be change, unless in context _context_allow_change",
"name": "__setattr__",
"signature": "def __setattr__(self, name, value)"
},
{
"docstring": "the context in which attributes could be change for example: 1.wrong way: would raise AttributeReadOnlyError self.... | 2 | stack_v2_sparse_classes_30k_train_005233 | Implement the Python class `ReadOnlySpace` described below.
Class description:
a base class whose attributes are read-only, unless use the context _context_allow_change to change attributes
Method signatures and docstrings:
- def __setattr__(self, name, value): attributes could not be change, unless in context _conte... | Implement the Python class `ReadOnlySpace` described below.
Class description:
a base class whose attributes are read-only, unless use the context _context_allow_change to change attributes
Method signatures and docstrings:
- def __setattr__(self, name, value): attributes could not be change, unless in context _conte... | f4abc48fff907a0785372b941afcd67e62eec825 | <|skeleton|>
class ReadOnlySpace:
"""a base class whose attributes are read-only, unless use the context _context_allow_change to change attributes"""
def __setattr__(self, name, value):
"""attributes could not be change, unless in context _context_allow_change"""
<|body_0|>
def _context_a... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ReadOnlySpace:
"""a base class whose attributes are read-only, unless use the context _context_allow_change to change attributes"""
def __setattr__(self, name, value):
"""attributes could not be change, unless in context _context_allow_change"""
if name == 'ALLOW_CHANGE':
rais... | the_stack_v2_python_sparse | api/BackendAPI/ReadOnlySpace.py | AutoCoinDCF/NEW_API | train | 0 |
7637949418c337cf32e16a3daf0a35fccb0357a7 | [
"try:\n surface = partial_lexeme.random_kanji_surface\nexcept ObjectDoesNotExist:\n raise plugin_api.UnsupportedItem(partial_lexeme)\nanswer = partial_lexeme.reading_set.all().order_by('?')[0].reading\nquestion = self.build_question(pivot=surface, pivot_type='w', pivot_id=partial_lexeme.id, stimulus=surface, ... | <|body_start_0|>
try:
surface = partial_lexeme.random_kanji_surface
except ObjectDoesNotExist:
raise plugin_api.UnsupportedItem(partial_lexeme)
answer = partial_lexeme.reading_set.all().order_by('?')[0].reading
question = self.build_question(pivot=surface, pivot_t... | Generates questions based on identifying the correct reading for a word or kanji amongst distractors. For each kanji which needs a reading, we use the candidates provided from a user's (reading | kanji) error distribution. | ReadingQuestionFactory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReadingQuestionFactory:
"""Generates questions based on identifying the correct reading for a word or kanji amongst distractors. For each kanji which needs a reading, we use the candidates provided from a user's (reading | kanji) error distribution."""
def get_word_question(self, partial_lex... | stack_v2_sparse_classes_10k_train_004046 | 7,501 | no_license | [
{
"docstring": "See parent.",
"name": "get_word_question",
"signature": "def get_word_question(self, partial_lexeme, user)"
},
{
"docstring": "See parent.",
"name": "get_kanji_question",
"signature": "def get_kanji_question(self, partial_kanji, user)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003800 | Implement the Python class `ReadingQuestionFactory` described below.
Class description:
Generates questions based on identifying the correct reading for a word or kanji amongst distractors. For each kanji which needs a reading, we use the candidates provided from a user's (reading | kanji) error distribution.
Method ... | Implement the Python class `ReadingQuestionFactory` described below.
Class description:
Generates questions based on identifying the correct reading for a word or kanji amongst distractors. For each kanji which needs a reading, we use the candidates provided from a user's (reading | kanji) error distribution.
Method ... | 8ffde158e8b863d6ee725fb689be163b1365f258 | <|skeleton|>
class ReadingQuestionFactory:
"""Generates questions based on identifying the correct reading for a word or kanji amongst distractors. For each kanji which needs a reading, we use the candidates provided from a user's (reading | kanji) error distribution."""
def get_word_question(self, partial_lex... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ReadingQuestionFactory:
"""Generates questions based on identifying the correct reading for a word or kanji amongst distractors. For each kanji which needs a reading, we use the candidates provided from a user's (reading | kanji) error distribution."""
def get_word_question(self, partial_lexeme, user):
... | the_stack_v2_python_sparse | kanji_test/plugins/basic_drills.py | tryforceful/kanjitester | train | 0 |
00a8f678151ee50bb3eea4ad0eaa7ce7959a874d | [
"query_args = {'user': user, 'stock': stock, 'brokerage_account': brokerage_account, 'budget_account': budget_account}\nfinal_query_args = {k: v for k, v in query_args.items() if v is not None}\nreturn super().get_queryset().filter(**final_query_args)",
"query_args = {'user': user, 'stock': stock, 'brokerage_acco... | <|body_start_0|>
query_args = {'user': user, 'stock': stock, 'brokerage_account': brokerage_account, 'budget_account': budget_account}
final_query_args = {k: v for k, v in query_args.items() if v is not None}
return super().get_queryset().filter(**final_query_args)
<|end_body_0|>
<|body_start_1... | StockSharesManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StockSharesManager:
def find_all_shares(self, user, stock=None, brokerage_account=None, budget_account=None):
"""find all shares in all accounts for a ticker"""
<|body_0|>
def investment_sum(self, user=None, stock=None, brokerage_account=None, budget_account=None):
"... | stack_v2_sparse_classes_10k_train_004047 | 2,721 | permissive | [
{
"docstring": "find all shares in all accounts for a ticker",
"name": "find_all_shares",
"signature": "def find_all_shares(self, user, stock=None, brokerage_account=None, budget_account=None)"
},
{
"docstring": "find sum of shares in accounts",
"name": "investment_sum",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_007185 | Implement the Python class `StockSharesManager` described below.
Class description:
Implement the StockSharesManager class.
Method signatures and docstrings:
- def find_all_shares(self, user, stock=None, brokerage_account=None, budget_account=None): find all shares in all accounts for a ticker
- def investment_sum(se... | Implement the Python class `StockSharesManager` described below.
Class description:
Implement the StockSharesManager class.
Method signatures and docstrings:
- def find_all_shares(self, user, stock=None, brokerage_account=None, budget_account=None): find all shares in all accounts for a ticker
- def investment_sum(se... | 585b036b1a2a1c356a366b94676042e4628f6773 | <|skeleton|>
class StockSharesManager:
def find_all_shares(self, user, stock=None, brokerage_account=None, budget_account=None):
"""find all shares in all accounts for a ticker"""
<|body_0|>
def investment_sum(self, user=None, stock=None, brokerage_account=None, budget_account=None):
"... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class StockSharesManager:
def find_all_shares(self, user, stock=None, brokerage_account=None, budget_account=None):
"""find all shares in all accounts for a ticker"""
query_args = {'user': user, 'stock': stock, 'brokerage_account': brokerage_account, 'budget_account': budget_account}
final_q... | the_stack_v2_python_sparse | budgetbuddy/stocks/managers.py | michaelqknguyen/Budget-Buddy | train | 0 | |
63d22c51c4672aa3a749280c75c1df311d6ab1c3 | [
"if User.objects.filter(email__iexact=value).exists():\n raise serializers.ValidationError(_('EMAIL.IN_USE'))\nreturn value.lower()",
"user = User(**data)\npassword = data.get('password')\nerrors = dict()\ntry:\n validators.validate_password(password=password, user=User)\nexcept exceptions.ValidationError a... | <|body_start_0|>
if User.objects.filter(email__iexact=value).exists():
raise serializers.ValidationError(_('EMAIL.IN_USE'))
return value.lower()
<|end_body_0|>
<|body_start_1|>
user = User(**data)
password = data.get('password')
errors = dict()
try:
... | Profile serializer for creating a user instance | ProfileCreateSerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileCreateSerializer:
"""Profile serializer for creating a user instance"""
def validate_email(self, value):
"""Check if email is already in use"""
<|body_0|>
def validate(self, data):
"""Validate Password"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_10k_train_004048 | 6,076 | permissive | [
{
"docstring": "Check if email is already in use",
"name": "validate_email",
"signature": "def validate_email(self, value)"
},
{
"docstring": "Validate Password",
"name": "validate",
"signature": "def validate(self, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000593 | Implement the Python class `ProfileCreateSerializer` described below.
Class description:
Profile serializer for creating a user instance
Method signatures and docstrings:
- def validate_email(self, value): Check if email is already in use
- def validate(self, data): Validate Password | Implement the Python class `ProfileCreateSerializer` described below.
Class description:
Profile serializer for creating a user instance
Method signatures and docstrings:
- def validate_email(self, value): Check if email is already in use
- def validate(self, data): Validate Password
<|skeleton|>
class ProfileCreate... | 5e1a2b51aee87eb79443e0489d13f976b0e6bae8 | <|skeleton|>
class ProfileCreateSerializer:
"""Profile serializer for creating a user instance"""
def validate_email(self, value):
"""Check if email is already in use"""
<|body_0|>
def validate(self, data):
"""Validate Password"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ProfileCreateSerializer:
"""Profile serializer for creating a user instance"""
def validate_email(self, value):
"""Check if email is already in use"""
if User.objects.filter(email__iexact=value).exists():
raise serializers.ValidationError(_('EMAIL.IN_USE'))
return valu... | the_stack_v2_python_sparse | api/api_v1/profiles/serializers.py | ehsanghaffar/djangoware | train | 1 |
850f6b637d7e61d3ff78db91a8d5399b0597c28b | [
"self._resource = resource\nself._pin = pin\nself.data = {}\nself.available = True",
"try:\n if self._pin is None:\n response = requests.get(self._resource, timeout=10)\n self.data = response.json()['variables']\n else:\n try:\n if str(self._pin[0]) == 'A':\n r... | <|body_start_0|>
self._resource = resource
self._pin = pin
self.data = {}
self.available = True
<|end_body_0|>
<|body_start_1|>
try:
if self._pin is None:
response = requests.get(self._resource, timeout=10)
self.data = response.json()[... | The Class for handling the data retrieval for variables. | ArestData | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArestData:
"""The Class for handling the data retrieval for variables."""
def __init__(self, resource, pin=None):
"""Initialize the data object."""
<|body_0|>
def update(self):
"""Get the latest data from aREST device."""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_10k_train_004049 | 6,651 | permissive | [
{
"docstring": "Initialize the data object.",
"name": "__init__",
"signature": "def __init__(self, resource, pin=None)"
},
{
"docstring": "Get the latest data from aREST device.",
"name": "update",
"signature": "def update(self)"
}
] | 2 | null | Implement the Python class `ArestData` described below.
Class description:
The Class for handling the data retrieval for variables.
Method signatures and docstrings:
- def __init__(self, resource, pin=None): Initialize the data object.
- def update(self): Get the latest data from aREST device. | Implement the Python class `ArestData` described below.
Class description:
The Class for handling the data retrieval for variables.
Method signatures and docstrings:
- def __init__(self, resource, pin=None): Initialize the data object.
- def update(self): Get the latest data from aREST device.
<|skeleton|>
class Are... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ArestData:
"""The Class for handling the data retrieval for variables."""
def __init__(self, resource, pin=None):
"""Initialize the data object."""
<|body_0|>
def update(self):
"""Get the latest data from aREST device."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ArestData:
"""The Class for handling the data retrieval for variables."""
def __init__(self, resource, pin=None):
"""Initialize the data object."""
self._resource = resource
self._pin = pin
self.data = {}
self.available = True
def update(self):
"""Get ... | the_stack_v2_python_sparse | homeassistant/components/arest/sensor.py | home-assistant/core | train | 35,501 |
9c7c397f52781a5a52376e4a904672c7c1647aaa | [
"if not settings.NEW_ACCOUNT_REGISTRATION_ENABLED:\n self.msg('Registration is currently disabled.')\n return True\nreturn super().at_pre_cmd()",
"session = self.caller\nargs = self.args.strip()\naddress = session.address\nAccount = class_from_module(settings.BASE_ACCOUNT_TYPECLASS)\nparts = [part.strip() f... | <|body_start_0|>
if not settings.NEW_ACCOUNT_REGISTRATION_ENABLED:
self.msg('Registration is currently disabled.')
return True
return super().at_pre_cmd()
<|end_body_0|>
<|body_start_1|>
session = self.caller
args = self.args.strip()
address = session.add... | create a new account account Usage (at login screen): create <accountname> <password> create "account name" "pass word" This creates a new account account. If you have spaces in your name, enclose it in double quotes. | CmdUnconnectedCreate | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CmdUnconnectedCreate:
"""create a new account account Usage (at login screen): create <accountname> <password> create "account name" "pass word" This creates a new account account. If you have spaces in your name, enclose it in double quotes."""
def at_pre_cmd(self):
"""Verify that a... | stack_v2_sparse_classes_10k_train_004050 | 15,057 | permissive | [
{
"docstring": "Verify that account creation is enabled.",
"name": "at_pre_cmd",
"signature": "def at_pre_cmd(self)"
},
{
"docstring": "Do checks and create account",
"name": "func",
"signature": "def func(self)"
}
] | 2 | null | Implement the Python class `CmdUnconnectedCreate` described below.
Class description:
create a new account account Usage (at login screen): create <accountname> <password> create "account name" "pass word" This creates a new account account. If you have spaces in your name, enclose it in double quotes.
Method signatu... | Implement the Python class `CmdUnconnectedCreate` described below.
Class description:
create a new account account Usage (at login screen): create <accountname> <password> create "account name" "pass word" This creates a new account account. If you have spaces in your name, enclose it in double quotes.
Method signatu... | b3ca58b5c1325a3bf57051dfe23560a08d2947b7 | <|skeleton|>
class CmdUnconnectedCreate:
"""create a new account account Usage (at login screen): create <accountname> <password> create "account name" "pass word" This creates a new account account. If you have spaces in your name, enclose it in double quotes."""
def at_pre_cmd(self):
"""Verify that a... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CmdUnconnectedCreate:
"""create a new account account Usage (at login screen): create <accountname> <password> create "account name" "pass word" This creates a new account account. If you have spaces in your name, enclose it in double quotes."""
def at_pre_cmd(self):
"""Verify that account creati... | the_stack_v2_python_sparse | evennia/commands/default/unloggedin.py | evennia/evennia | train | 1,781 |
50b07e7c84fc46f0900893e3ea4044fc0dc5cac5 | [
"n = len(nums)\ndp = [0] * n\nans = nums[0]\ndp[0] = nums[0]\nfor i in range(1, n):\n dp[i] = max(dp[i - 1] + nums[i], nums[i])\n ans = max(ans, dp[i])\nreturn ans",
"n = len(nums)\nprev = nums[0]\nans = nums[0]\nfor i in range(1, n):\n prev = max(prev + nums[i], nums[i])\n ans = max(ans, prev)\nretur... | <|body_start_0|>
n = len(nums)
dp = [0] * n
ans = nums[0]
dp[0] = nums[0]
for i in range(1, n):
dp[i] = max(dp[i - 1] + nums[i], nums[i])
ans = max(ans, dp[i])
return ans
<|end_body_0|>
<|body_start_1|>
n = len(nums)
prev = nums[0]... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(nums)
dp = [0] * n
an... | stack_v2_sparse_classes_10k_train_004051 | 1,137 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "maxSubArray",
"signature": "def maxSubArray(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "maxSubArray",
"signature": "def maxSubArray(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000222 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray(self, nums): :type nums: List[int] :rtype: int
- def maxSubArray(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray(self, nums): :type nums: List[int] :rtype: int
- def maxSubArray(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def maxSubArray... | b5c25f976866eefec33b96c638a4c5e127319e74 | <|skeleton|>
class Solution:
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
n = len(nums)
dp = [0] * n
ans = nums[0]
dp[0] = nums[0]
for i in range(1, n):
dp[i] = max(dp[i - 1] + nums[i], nums[i])
ans = max(ans, dp[i])
return a... | the_stack_v2_python_sparse | Python/053_Maximum Subarray.py | Eddie02582/Leetcode | train | 1 | |
13b1c91c9b480b9b8a34acfead9d359617857920 | [
"if self == Format.finalfusion:\n embeddings.write(path)\nelif self == Format.word2vec:\n write_word2vec(path, embeddings)\nelif self == Format.text:\n write_text(path, embeddings)\nelif self == Format.textdims:\n write_text_dims(path, embeddings)\nelif self == Format.fasttext:\n write_fasttext(path,... | <|body_start_0|>
if self == Format.finalfusion:
embeddings.write(path)
elif self == Format.word2vec:
write_word2vec(path, embeddings)
elif self == Format.text:
write_text(path, embeddings)
elif self == Format.textdims:
write_text_dims(path,... | Supported embedding formats. | Format | [
"BlueOak-1.0.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Format:
"""Supported embedding formats."""
def write(self, path: str, embeddings: Embeddings):
"""Helper to write different Formats"""
<|body_0|>
def load(self, path: str, lossy: bool, mmap: bool) -> Embeddings:
"""Helper to load different Formats"""
<|bo... | stack_v2_sparse_classes_10k_train_004052 | 3,054 | permissive | [
{
"docstring": "Helper to write different Formats",
"name": "write",
"signature": "def write(self, path: str, embeddings: Embeddings)"
},
{
"docstring": "Helper to load different Formats",
"name": "load",
"signature": "def load(self, path: str, lossy: bool, mmap: bool) -> Embeddings"
}... | 2 | stack_v2_sparse_classes_30k_train_001984 | Implement the Python class `Format` described below.
Class description:
Supported embedding formats.
Method signatures and docstrings:
- def write(self, path: str, embeddings: Embeddings): Helper to write different Formats
- def load(self, path: str, lossy: bool, mmap: bool) -> Embeddings: Helper to load different Fo... | Implement the Python class `Format` described below.
Class description:
Supported embedding formats.
Method signatures and docstrings:
- def write(self, path: str, embeddings: Embeddings): Helper to write different Formats
- def load(self, path: str, lossy: bool, mmap: bool) -> Embeddings: Helper to load different Fo... | f7ab0174a66731d0f71635c45d172f7711f6aec8 | <|skeleton|>
class Format:
"""Supported embedding formats."""
def write(self, path: str, embeddings: Embeddings):
"""Helper to write different Formats"""
<|body_0|>
def load(self, path: str, lossy: bool, mmap: bool) -> Embeddings:
"""Helper to load different Formats"""
<|bo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Format:
"""Supported embedding formats."""
def write(self, path: str, embeddings: Embeddings):
"""Helper to write different Formats"""
if self == Format.finalfusion:
embeddings.write(path)
elif self == Format.word2vec:
write_word2vec(path, embeddings)
... | the_stack_v2_python_sparse | src/finalfusion/scripts/util.py | finalfusion/finalfusion-python | train | 5 |
ebba3d383ed20c3a9cf4020f63018afbac565da2 | [
"if not root:\n return ''\nqueue = [root]\nans = []\nwhile queue:\n cur_node = queue.pop(0)\n if cur_node:\n queue.append(cur_node.left)\n queue.append(cur_node.right)\n ans.append(str(cur_node.val) if cur_node else '#')\nreturn ','.join(ans)",
"if not data:\n return None\ndata = data... | <|body_start_0|>
if not root:
return ''
queue = [root]
ans = []
while queue:
cur_node = queue.pop(0)
if cur_node:
queue.append(cur_node.left)
queue.append(cur_node.right)
ans.append(str(cur_node.val) if cur_n... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
... | stack_v2_sparse_classes_10k_train_004053 | 1,550 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class Co... | 3a83c0b0bcc43f458f7fc54764f60e1104fcc12e | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
if not root:
return ''
queue = [root]
ans = []
while queue:
cur_node = queue.pop(0)
if cur_node:
queue.append(cur_node.left)
... | the_stack_v2_python_sparse | 200111/Serialize_Deserialize_BST.py | Jsonghh/leetcode | train | 0 | |
3fb888b4254b0087c5b8a3ef0656a9349a554e9b | [
"if data is None:\n data = {}\ndata['reference_id'] = reference_id\nurl = f'{self.session.root_url}/study/api/study/'\nreturn self.session.post(url, data).json()",
"url = f'{self.session.root_url}/study/api/study/?assessment_id={assessment_id}'\nresponse_json = self.session.get(url).json()\nreturn pd.DataFrame... | <|body_start_0|>
if data is None:
data = {}
data['reference_id'] = reference_id
url = f'{self.session.root_url}/study/api/study/'
return self.session.post(url, data).json()
<|end_body_0|>
<|body_start_1|>
url = f'{self.session.root_url}/study/api/study/?assessment_id... | Client class for study requests. | StudyClient | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StudyClient:
"""Client class for study requests."""
def create(self, reference_id: int, data: dict | None=None) -> dict:
"""Creates a study using a given reference ID. Args: reference_id (int): Reference ID to create study from. data (dict, optional): Dict containing any additional f... | stack_v2_sparse_classes_10k_train_004054 | 3,384 | permissive | [
{
"docstring": "Creates a study using a given reference ID. Args: reference_id (int): Reference ID to create study from. data (dict, optional): Dict containing any additional field/value pairings for the study. Possible pairings are: short_citation (str): Short study citation, can be used as identifier. full_ci... | 3 | null | Implement the Python class `StudyClient` described below.
Class description:
Client class for study requests.
Method signatures and docstrings:
- def create(self, reference_id: int, data: dict | None=None) -> dict: Creates a study using a given reference ID. Args: reference_id (int): Reference ID to create study from... | Implement the Python class `StudyClient` described below.
Class description:
Client class for study requests.
Method signatures and docstrings:
- def create(self, reference_id: int, data: dict | None=None) -> dict: Creates a study using a given reference ID. Args: reference_id (int): Reference ID to create study from... | 51177c6fb9354cd028f7099fc10d83b1051fd50d | <|skeleton|>
class StudyClient:
"""Client class for study requests."""
def create(self, reference_id: int, data: dict | None=None) -> dict:
"""Creates a study using a given reference ID. Args: reference_id (int): Reference ID to create study from. data (dict, optional): Dict containing any additional f... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class StudyClient:
"""Client class for study requests."""
def create(self, reference_id: int, data: dict | None=None) -> dict:
"""Creates a study using a given reference ID. Args: reference_id (int): Reference ID to create study from. data (dict, optional): Dict containing any additional field/value pa... | the_stack_v2_python_sparse | client/hawc_client/study.py | shapiromatron/hawc | train | 25 |
e9084fd4389f61fc0a3efa6bbec6de19d3d46f7b | [
"self.radius = radius\nself.x_center = x_center\nself.y_center = y_center",
"while 1:\n x = random.uniform(self.x_center - self.radius, self.x_center + self.radius)\n y = random.uniform(self.y_center - self.radius, self.y_center + self.radius)\n if (x - self.x_center) ** 2 + (y - self.y_center) ** 2 <= s... | <|body_start_0|>
self.radius = radius
self.x_center = x_center
self.y_center = y_center
<|end_body_0|>
<|body_start_1|>
while 1:
x = random.uniform(self.x_center - self.radius, self.x_center + self.radius)
y = random.uniform(self.y_center - self.radius, self.y_ce... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, radius, x_center, y_center):
""":type radius: float :type x_center: float :type y_center: float"""
<|body_0|>
def randPoint(self):
""":rtype: List[float]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.radius = radi... | stack_v2_sparse_classes_10k_train_004055 | 759 | no_license | [
{
"docstring": ":type radius: float :type x_center: float :type y_center: float",
"name": "__init__",
"signature": "def __init__(self, radius, x_center, y_center)"
},
{
"docstring": ":rtype: List[float]",
"name": "randPoint",
"signature": "def randPoint(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000301 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, radius, x_center, y_center): :type radius: float :type x_center: float :type y_center: float
- def randPoint(self): :rtype: List[float] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, radius, x_center, y_center): :type radius: float :type x_center: float :type y_center: float
- def randPoint(self): :rtype: List[float]
<|skeleton|>
class Sol... | baa50a759218809f5e92b54e134ad77a43a0da3b | <|skeleton|>
class Solution:
def __init__(self, radius, x_center, y_center):
""":type radius: float :type x_center: float :type y_center: float"""
<|body_0|>
def randPoint(self):
""":rtype: List[float]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, radius, x_center, y_center):
""":type radius: float :type x_center: float :type y_center: float"""
self.radius = radius
self.x_center = x_center
self.y_center = y_center
def randPoint(self):
""":rtype: List[float]"""
while 1:
... | the_stack_v2_python_sparse | GenerateRandomPointinaCircle478.py | wyf19901121/LeetCodeForPython | train | 0 | |
1fb9d33b2b19d3d33c28edd7f09727cf938467c3 | [
"if not head or not head.next:\n return head\nret = head.next\nhead.next = self.swapPairs(head.next.next)\nret.next = head\nreturn ret",
"dummy, dummy.next = (self, head)\nwhile dummy.next and dummy.next.next:\n node1 = dummy.next\n node2 = dummy.next.next\n dummy.next, node1.next, node2.next = (node2... | <|body_start_0|>
if not head or not head.next:
return head
ret = head.next
head.next = self.swapPairs(head.next.next)
ret.next = head
return ret
<|end_body_0|>
<|body_start_1|>
dummy, dummy.next = (self, head)
while dummy.next and dummy.next.next:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
"""递归实现"""
<|body_0|>
def swapPairs_1(self, head: ListNode) -> ListNode:
"""迭代实现"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not head or not head.next:
return head
... | stack_v2_sparse_classes_10k_train_004056 | 844 | no_license | [
{
"docstring": "递归实现",
"name": "swapPairs",
"signature": "def swapPairs(self, head: ListNode) -> ListNode"
},
{
"docstring": "迭代实现",
"name": "swapPairs_1",
"signature": "def swapPairs_1(self, head: ListNode) -> ListNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_000903 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swapPairs(self, head: ListNode) -> ListNode: 递归实现
- def swapPairs_1(self, head: ListNode) -> ListNode: 迭代实现 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swapPairs(self, head: ListNode) -> ListNode: 递归实现
- def swapPairs_1(self, head: ListNode) -> ListNode: 迭代实现
<|skeleton|>
class Solution:
def swapPairs(self, head: ListN... | 41d6d4c748a6543d1c4027badb17ffbb64b43f2d | <|skeleton|>
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
"""递归实现"""
<|body_0|>
def swapPairs_1(self, head: ListNode) -> ListNode:
"""迭代实现"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
"""递归实现"""
if not head or not head.next:
return head
ret = head.next
head.next = self.swapPairs(head.next.next)
ret.next = head
return ret
def swapPairs_1(self, head: ListNode) -> ListNo... | the_stack_v2_python_sparse | learn/24.py | xiaoqiangjava/python-algorithm | train | 0 | |
9923f29d3cc88b68ee931e8f9406b423c8e0f587 | [
"try:\n article = Articles.objects.get(slug=slug)\n comments = Comment.objects.all().filter(article_id=article.id, parent=request.query_params.get('parent', None))\n serializer = self.serializer_class(comments, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\nexcept Articles.Doe... | <|body_start_0|>
try:
article = Articles.objects.get(slug=slug)
comments = Comment.objects.all().filter(article_id=article.id, parent=request.query_params.get('parent', None))
serializer = self.serializer_class(comments, many=True)
return Response(serializer.data,... | Handles viewing of comments if not authenticated and Handles creating comments on an article if authenticated | RetrieveCommentAPIView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RetrieveCommentAPIView:
"""Handles viewing of comments if not authenticated and Handles creating comments on an article if authenticated"""
def get(self, request, slug):
"""Handles listing all comments on an article :param slug: :return: [comments]"""
<|body_0|>
def post... | stack_v2_sparse_classes_10k_train_004057 | 7,543 | permissive | [
{
"docstring": "Handles listing all comments on an article :param slug: :return: [comments]",
"name": "get",
"signature": "def get(self, request, slug)"
},
{
"docstring": "Handles creating a new comment on an article :param request: :param slug: :return: comment",
"name": "post",
"signat... | 2 | stack_v2_sparse_classes_30k_val_000389 | Implement the Python class `RetrieveCommentAPIView` described below.
Class description:
Handles viewing of comments if not authenticated and Handles creating comments on an article if authenticated
Method signatures and docstrings:
- def get(self, request, slug): Handles listing all comments on an article :param slug... | Implement the Python class `RetrieveCommentAPIView` described below.
Class description:
Handles viewing of comments if not authenticated and Handles creating comments on an article if authenticated
Method signatures and docstrings:
- def get(self, request, slug): Handles listing all comments on an article :param slug... | 5a31840856de4b361fe2594dfa7a33d7774d3fe2 | <|skeleton|>
class RetrieveCommentAPIView:
"""Handles viewing of comments if not authenticated and Handles creating comments on an article if authenticated"""
def get(self, request, slug):
"""Handles listing all comments on an article :param slug: :return: [comments]"""
<|body_0|>
def post... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RetrieveCommentAPIView:
"""Handles viewing of comments if not authenticated and Handles creating comments on an article if authenticated"""
def get(self, request, slug):
"""Handles listing all comments on an article :param slug: :return: [comments]"""
try:
article = Articles.o... | the_stack_v2_python_sparse | authors/apps/comments/views.py | bl4ck4ndbr0wn/ah-centauri-backend | train | 0 |
a5428b1a799611dac61e81dbc7ee2f8a16a80f57 | [
"try:\n params = self.request.query_params\n for key in ['part_detail', 'location_detail', 'stock_detail', 'build_detail']:\n if key in params:\n kwargs[key] = str2bool(params.get(key, False))\nexcept AttributeError:\n pass\nreturn self.serializer_class(*args, **kwargs)",
"queryset = Bu... | <|body_start_0|>
try:
params = self.request.query_params
for key in ['part_detail', 'location_detail', 'stock_detail', 'build_detail']:
if key in params:
kwargs[key] = str2bool(params.get(key, False))
except AttributeError:
pass
... | API endpoint for accessing a list of BuildItem objects. - GET: Return list of objects - POST: Create a new BuildItem object | BuildItemList | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BuildItemList:
"""API endpoint for accessing a list of BuildItem objects. - GET: Return list of objects - POST: Create a new BuildItem object"""
def get_serializer(self, *args, **kwargs):
"""Returns a BuildItemSerializer instance based on the request."""
<|body_0|>
def g... | stack_v2_sparse_classes_10k_train_004058 | 20,912 | permissive | [
{
"docstring": "Returns a BuildItemSerializer instance based on the request.",
"name": "get_serializer",
"signature": "def get_serializer(self, *args, **kwargs)"
},
{
"docstring": "Override the queryset method, to allow filtering by stock_item.part.",
"name": "get_queryset",
"signature":... | 3 | null | Implement the Python class `BuildItemList` described below.
Class description:
API endpoint for accessing a list of BuildItem objects. - GET: Return list of objects - POST: Create a new BuildItem object
Method signatures and docstrings:
- def get_serializer(self, *args, **kwargs): Returns a BuildItemSerializer instan... | Implement the Python class `BuildItemList` described below.
Class description:
API endpoint for accessing a list of BuildItem objects. - GET: Return list of objects - POST: Create a new BuildItem object
Method signatures and docstrings:
- def get_serializer(self, *args, **kwargs): Returns a BuildItemSerializer instan... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class BuildItemList:
"""API endpoint for accessing a list of BuildItem objects. - GET: Return list of objects - POST: Create a new BuildItem object"""
def get_serializer(self, *args, **kwargs):
"""Returns a BuildItemSerializer instance based on the request."""
<|body_0|>
def g... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BuildItemList:
"""API endpoint for accessing a list of BuildItem objects. - GET: Return list of objects - POST: Create a new BuildItem object"""
def get_serializer(self, *args, **kwargs):
"""Returns a BuildItemSerializer instance based on the request."""
try:
params = self.req... | the_stack_v2_python_sparse | InvenTree/build/api.py | inventree/InvenTree | train | 3,077 |
4bd8031530ef92e6cfb6cad5044d2de77d57b3aa | [
"if isinstance(context, basestring):\n self.response.write(context)\nelse:\n context = json.dumps(context)\n self.response.write(context)\nself.response.headers['Content-Type'] = 'application/json'",
"error_report = {'method': self.request.method, 'url': self.request.path_url, 'query_string': self.reques... | <|body_start_0|>
if isinstance(context, basestring):
self.response.write(context)
else:
context = json.dumps(context)
self.response.write(context)
self.response.headers['Content-Type'] = 'application/json'
<|end_body_0|>
<|body_start_1|>
error_report ... | Simple webapp2 base handler to return JSON data from API endpoints | JsonHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JsonHandler:
"""Simple webapp2 base handler to return JSON data from API endpoints"""
def render_response(self, context):
"""Accepts a JSON encoded string or object which can be serialised to JSON and outputs it to the response as a JSON encoded string."""
<|body_0|>
def... | stack_v2_sparse_classes_10k_train_004059 | 2,742 | no_license | [
{
"docstring": "Accepts a JSON encoded string or object which can be serialised to JSON and outputs it to the response as a JSON encoded string.",
"name": "render_response",
"signature": "def render_response(self, context)"
},
{
"docstring": "Override handle_exception() to send errors to our sen... | 2 | stack_v2_sparse_classes_30k_train_006414 | Implement the Python class `JsonHandler` described below.
Class description:
Simple webapp2 base handler to return JSON data from API endpoints
Method signatures and docstrings:
- def render_response(self, context): Accepts a JSON encoded string or object which can be serialised to JSON and outputs it to the response... | Implement the Python class `JsonHandler` described below.
Class description:
Simple webapp2 base handler to return JSON data from API endpoints
Method signatures and docstrings:
- def render_response(self, context): Accepts a JSON encoded string or object which can be serialised to JSON and outputs it to the response... | 6e2a4854eac540968ebc8f0893834dcd24cef74e | <|skeleton|>
class JsonHandler:
"""Simple webapp2 base handler to return JSON data from API endpoints"""
def render_response(self, context):
"""Accepts a JSON encoded string or object which can be serialised to JSON and outputs it to the response as a JSON encoded string."""
<|body_0|>
def... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class JsonHandler:
"""Simple webapp2 base handler to return JSON data from API endpoints"""
def render_response(self, context):
"""Accepts a JSON encoded string or object which can be serialised to JSON and outputs it to the response as a JSON encoded string."""
if isinstance(context, basestrin... | the_stack_v2_python_sparse | handlers/api/base.py | paddycarey/taskr | train | 0 |
9a238eecc6a435a2df9e7d85a2e37fc6b7a677d1 | [
"self._len = capacity\nself._caches = {}\nself._priority = []",
"if key in self._caches.keys():\n self._priority.remove(key)\n self._priority.append(key)\ntry:\n return self._caches[key]\nexcept:\n return -1",
"if len(self._caches) < self._len:\n self._caches[key] = value\nelse:\n self._caches... | <|body_start_0|>
self._len = capacity
self._caches = {}
self._priority = []
<|end_body_0|>
<|body_start_1|>
if key in self._caches.keys():
self._priority.remove(key)
self._priority.append(key)
try:
return self._caches[key]
except:
... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_10k_train_004060 | 989 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_005648 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | a6d0e392134afe19d1aed2dfe7914b674e05ecc6 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self._len = capacity
self._caches = {}
self._priority = []
def get(self, key):
""":type key: int :rtype: int"""
if key in self._caches.keys():
self._priority.remove(key)
... | the_stack_v2_python_sparse | 146LRUCache.py | Ting007/leetcodePractice | train | 0 | |
592a65d6e96d8480efcd3f112dbb47bc1b0dd152 | [
"all_dep_paths = rule_details[su.ALL_DEP_PATHS_KEY][:]\nfor rule_symbol in rule_details[su.PACKAGE_MODULES_KEY]:\n all_dep_paths.append(_check_and_get_outfile(details_map[rule_symbol]))\nrule_details[su.ALL_DEP_PATHS_KEY] = sorted(list(set(all_dep_paths)))",
"test_commands = []\nfor rule_symbol in rule_details... | <|body_start_0|>
all_dep_paths = rule_details[su.ALL_DEP_PATHS_KEY][:]
for rule_symbol in rule_details[su.PACKAGE_MODULES_KEY]:
all_dep_paths.append(_check_and_get_outfile(details_map[rule_symbol]))
rule_details[su.ALL_DEP_PATHS_KEY] = sorted(list(set(all_dep_paths)))
<|end_body_0|>
... | Pre-release test and packaging module. | ReleasePackage | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReleasePackage:
"""Pre-release test and packaging module."""
def _setup_deps(cls, rule_details, details_map):
"""Setup all dependencies."""
<|body_0|>
def _setup_tests(cls, rule_details, details_map):
"""Setup all tests."""
<|body_1|>
def _setup_link... | stack_v2_sparse_classes_10k_train_004061 | 3,935 | permissive | [
{
"docstring": "Setup all dependencies.",
"name": "_setup_deps",
"signature": "def _setup_deps(cls, rule_details, details_map)"
},
{
"docstring": "Setup all tests.",
"name": "_setup_tests",
"signature": "def _setup_tests(cls, rule_details, details_map)"
},
{
"docstring": "Setup l... | 5 | stack_v2_sparse_classes_30k_train_001689 | Implement the Python class `ReleasePackage` described below.
Class description:
Pre-release test and packaging module.
Method signatures and docstrings:
- def _setup_deps(cls, rule_details, details_map): Setup all dependencies.
- def _setup_tests(cls, rule_details, details_map): Setup all tests.
- def _setup_linking(... | Implement the Python class `ReleasePackage` described below.
Class description:
Pre-release test and packaging module.
Method signatures and docstrings:
- def _setup_deps(cls, rule_details, details_map): Setup all dependencies.
- def _setup_tests(cls, rule_details, details_map): Setup all tests.
- def _setup_linking(... | af028dd413dd2595cb8338a5a2c2d61a95adf7c6 | <|skeleton|>
class ReleasePackage:
"""Pre-release test and packaging module."""
def _setup_deps(cls, rule_details, details_map):
"""Setup all dependencies."""
<|body_0|>
def _setup_tests(cls, rule_details, details_map):
"""Setup all tests."""
<|body_1|>
def _setup_link... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ReleasePackage:
"""Pre-release test and packaging module."""
def _setup_deps(cls, rule_details, details_map):
"""Setup all dependencies."""
all_dep_paths = rule_details[su.ALL_DEP_PATHS_KEY][:]
for rule_symbol in rule_details[su.PACKAGE_MODULES_KEY]:
all_dep_paths.appe... | the_stack_v2_python_sparse | build_tool/bu.scripts/mool/release_package.py | rocketfuel/mool | train | 3 |
c418ec166e1284e0d99225df099e1d7cc6ed9c54 | [
"prefix_function = [0] * len(pattern)\nborder = 0\nfor i in range(1, len(pattern)):\n while border > 0 and pattern[i] != pattern[border]:\n border = prefix_function[border - 1]\n if pattern[i] == pattern[border]:\n border += 1\n else:\n border = 0\n prefix_function[i] = border\nretu... | <|body_start_0|>
prefix_function = [0] * len(pattern)
border = 0
for i in range(1, len(pattern)):
while border > 0 and pattern[i] != pattern[border]:
border = prefix_function[border - 1]
if pattern[i] == pattern[border]:
border += 1
... | Util | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Util:
def _compute_prefix_function(pattern):
"""Computes the prefix function on the pattern. Definition: The border of string S is a prefix, which is equal to a suffix of S, but not equal to the whole S. Examples: 'a' is a border of 'arba' 'ab' is a border of 'abcdab' 'abab' is a border ... | stack_v2_sparse_classes_10k_train_004062 | 3,748 | no_license | [
{
"docstring": "Computes the prefix function on the pattern. Definition: The border of string S is a prefix, which is equal to a suffix of S, but not equal to the whole S. Examples: 'a' is a border of 'arba' 'ab' is a border of 'abcdab' 'abab' is a border of 'ababab' 'ab' is not a border of 'ab' Definition: The... | 3 | stack_v2_sparse_classes_30k_train_003021 | Implement the Python class `Util` described below.
Class description:
Implement the Util class.
Method signatures and docstrings:
- def _compute_prefix_function(pattern): Computes the prefix function on the pattern. Definition: The border of string S is a prefix, which is equal to a suffix of S, but not equal to the ... | Implement the Python class `Util` described below.
Class description:
Implement the Util class.
Method signatures and docstrings:
- def _compute_prefix_function(pattern): Computes the prefix function on the pattern. Definition: The border of string S is a prefix, which is equal to a suffix of S, but not equal to the ... | 01dd6f0dadf62a520bcafafddf7bf2b79e8e2603 | <|skeleton|>
class Util:
def _compute_prefix_function(pattern):
"""Computes the prefix function on the pattern. Definition: The border of string S is a prefix, which is equal to a suffix of S, but not equal to the whole S. Examples: 'a' is a border of 'arba' 'ab' is a border of 'abcdab' 'abab' is a border ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Util:
def _compute_prefix_function(pattern):
"""Computes the prefix function on the pattern. Definition: The border of string S is a prefix, which is equal to a suffix of S, but not equal to the whole S. Examples: 'a' is a border of 'arba' 'ab' is a border of 'abcdab' 'abab' is a border of 'ababab' 'a... | the_stack_v2_python_sparse | course4-strings/assignments/assignment_003_suffix_array_matching/suffix_array_matching_with_kmp.py | dmitri-mamrukov/coursera-data-structures-and-algorithms | train | 1 | |
e13624cc2eee1469c6aa2cc5c36be371f5a09bbe | [
"self.Wh = np.random.normal(size=(h + i, h))\nself.Wy = np.random.normal(size=(h, o))\nself.bh = np.zeros(shape=(1, h))\nself.by = np.zeros(shape=(1, o))",
"x = np.concatenate((h_prev, x_t), axis=1)\nh_t = np.tanh(np.dot(x, self.Wh) + self.bh)\nŷ = np.dot(h_t, self.Wy) + self.by\ny = np.exp(ŷ) / np.sum(np.exp(ŷ),... | <|body_start_0|>
self.Wh = np.random.normal(size=(h + i, h))
self.Wy = np.random.normal(size=(h, o))
self.bh = np.zeros(shape=(1, h))
self.by = np.zeros(shape=(1, o))
<|end_body_0|>
<|body_start_1|>
x = np.concatenate((h_prev, x_t), axis=1)
h_t = np.tanh(np.dot(x, self.W... | class RNNCell that represents a cell of a simple RNN | RNNCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNCell:
"""class RNNCell that represents a cell of a simple RNN"""
def __init__(self, i, h, o):
"""Constructor Args: i: i is the dimensionality of the data h: is the dimensionality of the hidden state o: is the dimensionality of the outputs Attributes that represent the weights and ... | stack_v2_sparse_classes_10k_train_004063 | 2,615 | no_license | [
{
"docstring": "Constructor Args: i: i is the dimensionality of the data h: is the dimensionality of the hidden state o: is the dimensionality of the outputs Attributes that represent the weights and biases of the cell: Wh: weights for the concatenated hidden state and input data Wy: weights for the output bh: ... | 2 | null | Implement the Python class `RNNCell` described below.
Class description:
class RNNCell that represents a cell of a simple RNN
Method signatures and docstrings:
- def __init__(self, i, h, o): Constructor Args: i: i is the dimensionality of the data h: is the dimensionality of the hidden state o: is the dimensionality ... | Implement the Python class `RNNCell` described below.
Class description:
class RNNCell that represents a cell of a simple RNN
Method signatures and docstrings:
- def __init__(self, i, h, o): Constructor Args: i: i is the dimensionality of the data h: is the dimensionality of the hidden state o: is the dimensionality ... | eb47cd4d12e2f0627bb5e5af28cc0802ff13d0d9 | <|skeleton|>
class RNNCell:
"""class RNNCell that represents a cell of a simple RNN"""
def __init__(self, i, h, o):
"""Constructor Args: i: i is the dimensionality of the data h: is the dimensionality of the hidden state o: is the dimensionality of the outputs Attributes that represent the weights and ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RNNCell:
"""class RNNCell that represents a cell of a simple RNN"""
def __init__(self, i, h, o):
"""Constructor Args: i: i is the dimensionality of the data h: is the dimensionality of the hidden state o: is the dimensionality of the outputs Attributes that represent the weights and biases of the... | the_stack_v2_python_sparse | supervised_learning/0x0D-RNNs/0-rnn_cell.py | rodrigocruz13/holbertonschool-machine_learning | train | 4 |
771d0a7fd546cd8ae30a47c296fc62c68c4566ea | [
"categories = Category.objects.all()\ncates = []\nnav_cates = []\nfor category in categories:\n if category.is_nav:\n nav_cates.append(category)\n else:\n cates.append(category)\nreturn {'nav_cates': nav_cates, 'cates': cates}",
"sidebars = SideBar.objects.filter(status=1)\nrecently_posts = Po... | <|body_start_0|>
categories = Category.objects.all()
cates = []
nav_cates = []
for category in categories:
if category.is_nav:
nav_cates.append(category)
else:
cates.append(category)
return {'nav_cates': nav_cates, 'cates': ... | CommonMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommonMixin:
def get_category_context(self):
"""分类 1、nav_cates = categoryies.filter(is_nav=True) 导航分类 2、cates = categories.filter(is_nav=False) 普通分类 3、Category.objects.all()返回一个queryset对象复制给categories"""
<|body_0|>
def get_context_data(self, **kwargs):
"""侧边栏"""
... | stack_v2_sparse_classes_10k_train_004064 | 5,314 | permissive | [
{
"docstring": "分类 1、nav_cates = categoryies.filter(is_nav=True) 导航分类 2、cates = categories.filter(is_nav=False) 普通分类 3、Category.objects.all()返回一个queryset对象复制给categories",
"name": "get_category_context",
"signature": "def get_category_context(self)"
},
{
"docstring": "侧边栏",
"name": "get_conte... | 2 | stack_v2_sparse_classes_30k_test_000267 | Implement the Python class `CommonMixin` described below.
Class description:
Implement the CommonMixin class.
Method signatures and docstrings:
- def get_category_context(self): 分类 1、nav_cates = categoryies.filter(is_nav=True) 导航分类 2、cates = categories.filter(is_nav=False) 普通分类 3、Category.objects.all()返回一个queryset对象复... | Implement the Python class `CommonMixin` described below.
Class description:
Implement the CommonMixin class.
Method signatures and docstrings:
- def get_category_context(self): 分类 1、nav_cates = categoryies.filter(is_nav=True) 导航分类 2、cates = categories.filter(is_nav=False) 普通分类 3、Category.objects.all()返回一个queryset对象复... | 52e74f18d37abc6e937d7cb5c752bc9dfd6ed662 | <|skeleton|>
class CommonMixin:
def get_category_context(self):
"""分类 1、nav_cates = categoryies.filter(is_nav=True) 导航分类 2、cates = categories.filter(is_nav=False) 普通分类 3、Category.objects.all()返回一个queryset对象复制给categories"""
<|body_0|>
def get_context_data(self, **kwargs):
"""侧边栏"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CommonMixin:
def get_category_context(self):
"""分类 1、nav_cates = categoryies.filter(is_nav=True) 导航分类 2、cates = categories.filter(is_nav=False) 普通分类 3、Category.objects.all()返回一个queryset对象复制给categories"""
categories = Category.objects.all()
cates = []
nav_cates = []
for ... | the_stack_v2_python_sparse | Myblog/blog/views.py | Family-TreeSY/Myblog | train | 5 | |
d1eeeef9328629e21653fd9f3130ad41dd8fc7d6 | [
"self._use_polld = use_polld\nself._server = None\nif use_polld:\n remote = 'http://%s:%s' % (host, tcp_port)\n self._server = net_utils.TimeoutXMLRPCServerProxy(remote, timeout=timeout, verbose=verbose)",
"if edge not in self.GPIO_EDGE_LIST:\n raise GpioManagerError('Invalid edge %r. Valid values: %r' %... | <|body_start_0|>
self._use_polld = use_polld
self._server = None
if use_polld:
remote = 'http://%s:%s' % (host, tcp_port)
self._server = net_utils.TimeoutXMLRPCServerProxy(remote, timeout=timeout, verbose=verbose)
<|end_body_0|>
<|body_start_1|>
if edge not in se... | GPIO monitor and control manager. | GpioManager | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GpioManager:
"""GPIO monitor and control manager."""
def __init__(self, use_polld, host=None, tcp_port=None, timeout=10, verbose=False):
"""Constructor. Args: use_polld: True to use polld to manage GPIO on remote server, or False to manage local GPIO port directly. host: Name or IP a... | stack_v2_sparse_classes_10k_train_004065 | 11,503 | permissive | [
{
"docstring": "Constructor. Args: use_polld: True to use polld to manage GPIO on remote server, or False to manage local GPIO port directly. host: Name or IP address of servo server host. tcp_port: TCP port on which servod is listening on. timeout: Timeout for HTTP connection. verbose: Enables verbose messagin... | 4 | stack_v2_sparse_classes_30k_train_006352 | Implement the Python class `GpioManager` described below.
Class description:
GPIO monitor and control manager.
Method signatures and docstrings:
- def __init__(self, use_polld, host=None, tcp_port=None, timeout=10, verbose=False): Constructor. Args: use_polld: True to use polld to manage GPIO on remote server, or Fal... | Implement the Python class `GpioManager` described below.
Class description:
GPIO monitor and control manager.
Method signatures and docstrings:
- def __init__(self, use_polld, host=None, tcp_port=None, timeout=10, verbose=False): Constructor. Args: use_polld: True to use polld to manage GPIO on remote server, or Fal... | a1b0fccd68987d8cd9c89710adc3c04b868347ec | <|skeleton|>
class GpioManager:
"""GPIO monitor and control manager."""
def __init__(self, use_polld, host=None, tcp_port=None, timeout=10, verbose=False):
"""Constructor. Args: use_polld: True to use polld to manage GPIO on remote server, or False to manage local GPIO port directly. host: Name or IP a... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GpioManager:
"""GPIO monitor and control manager."""
def __init__(self, use_polld, host=None, tcp_port=None, timeout=10, verbose=False):
"""Constructor. Args: use_polld: True to use polld to manage GPIO on remote server, or False to manage local GPIO port directly. host: Name or IP address of ser... | the_stack_v2_python_sparse | py/utils/gpio_utils.py | bridder/factory | train | 0 |
fffcfa947cfa1bbd7db1966c11c4435ba9860d05 | [
"try:\n search = SavedSearch.objects.get(project=project, id=search_id)\nexcept SavedSearch.DoesNotExist:\n raise ResourceDoesNotExist\nreturn Response(serialize(search, request.user))",
"try:\n search = SavedSearch.objects.get(project=project, id=search_id)\nexcept SavedSearch.DoesNotExist:\n raise R... | <|body_start_0|>
try:
search = SavedSearch.objects.get(project=project, id=search_id)
except SavedSearch.DoesNotExist:
raise ResourceDoesNotExist
return Response(serialize(search, request.user))
<|end_body_0|>
<|body_start_1|>
try:
search = SavedSearc... | ProjectSearchDetailsEndpoint | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectSearchDetailsEndpoint:
def get(self, request, project, search_id):
"""Retrieve a saved search Return details on an individual saved search. {method} {path}"""
<|body_0|>
def put(self, request, project, search_id):
"""Update a saved search Update a saved search... | stack_v2_sparse_classes_10k_train_004066 | 3,530 | permissive | [
{
"docstring": "Retrieve a saved search Return details on an individual saved search. {method} {path}",
"name": "get",
"signature": "def get(self, request, project, search_id)"
},
{
"docstring": "Update a saved search Update a saved search. {method} {path} {{ \"name: \"Unresolved\", \"query\": \... | 3 | null | Implement the Python class `ProjectSearchDetailsEndpoint` described below.
Class description:
Implement the ProjectSearchDetailsEndpoint class.
Method signatures and docstrings:
- def get(self, request, project, search_id): Retrieve a saved search Return details on an individual saved search. {method} {path}
- def pu... | Implement the Python class `ProjectSearchDetailsEndpoint` described below.
Class description:
Implement the ProjectSearchDetailsEndpoint class.
Method signatures and docstrings:
- def get(self, request, project, search_id): Retrieve a saved search Return details on an individual saved search. {method} {path}
- def pu... | b937615079d7b24dc225a83b99b1b65da932fc66 | <|skeleton|>
class ProjectSearchDetailsEndpoint:
def get(self, request, project, search_id):
"""Retrieve a saved search Return details on an individual saved search. {method} {path}"""
<|body_0|>
def put(self, request, project, search_id):
"""Update a saved search Update a saved search... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ProjectSearchDetailsEndpoint:
def get(self, request, project, search_id):
"""Retrieve a saved search Return details on an individual saved search. {method} {path}"""
try:
search = SavedSearch.objects.get(project=project, id=search_id)
except SavedSearch.DoesNotExist:
... | the_stack_v2_python_sparse | src/sentry/api/endpoints/project_search_details.py | atlassian/sentry | train | 1 | |
c592dde74f81df459ca629172241f383b399ac34 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Provides text analysis operations such as sentiment analysis and entity recognition. | LanguageServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LanguageServiceServicer:
"""Provides text analysis operations such as sentiment analysis and entity recognition."""
def AnalyzeSentiment(self, request, context):
"""Analyzes the sentiment of the provided text."""
<|body_0|>
def AnalyzeEntities(self, request, context):
... | stack_v2_sparse_classes_10k_train_004067 | 8,150 | permissive | [
{
"docstring": "Analyzes the sentiment of the provided text.",
"name": "AnalyzeSentiment",
"signature": "def AnalyzeSentiment(self, request, context)"
},
{
"docstring": "Finds named entities (currently proper names and common nouns) in the text along with entity types, salience, mentions for eac... | 6 | stack_v2_sparse_classes_30k_train_004855 | Implement the Python class `LanguageServiceServicer` described below.
Class description:
Provides text analysis operations such as sentiment analysis and entity recognition.
Method signatures and docstrings:
- def AnalyzeSentiment(self, request, context): Analyzes the sentiment of the provided text.
- def AnalyzeEnti... | Implement the Python class `LanguageServiceServicer` described below.
Class description:
Provides text analysis operations such as sentiment analysis and entity recognition.
Method signatures and docstrings:
- def AnalyzeSentiment(self, request, context): Analyzes the sentiment of the provided text.
- def AnalyzeEnti... | 253e419666f5dacf4566135faf5d451600020374 | <|skeleton|>
class LanguageServiceServicer:
"""Provides text analysis operations such as sentiment analysis and entity recognition."""
def AnalyzeSentiment(self, request, context):
"""Analyzes the sentiment of the provided text."""
<|body_0|>
def AnalyzeEntities(self, request, context):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LanguageServiceServicer:
"""Provides text analysis operations such as sentiment analysis and entity recognition."""
def AnalyzeSentiment(self, request, context):
"""Analyzes the sentiment of the provided text."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details(... | the_stack_v2_python_sparse | venv/lib/python3.7/site-packages/google/cloud/language_v1beta2/proto/language_service_pb2_grpc.py | nicholasadamou/stockmine | train | 2 |
f12695213c7e209d254cd8ae1da70e4ed61bc69a | [
"self.N_start = N_start\nself.ROI = ROI\nself.N_files = N_finish - N_start\nself.im_shape = (ROI[3] - ROI[1], ROI[2] - ROI[0])\nself.Npad = init_Npad(ROI, compression=compNpad)",
"data_names, ff_names = init_names(data_name, N_distances, first_distance=first_distance)\nimlist = var.im_folder(path)\nimages = np.ze... | <|body_start_0|>
self.N_start = N_start
self.ROI = ROI
self.N_files = N_finish - N_start
self.im_shape = (ROI[3] - ROI[1], ROI[2] - ROI[0])
self.Npad = init_Npad(ROI, compression=compNpad)
<|end_body_0|>
<|body_start_1|>
data_names, ff_names = init_names(data_name, N_dis... | Processor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Processor:
def __init__(self, ROI, folder, N_start, N_finish, compNpad=8):
"""Initialize parameters. Normally should contain ROI, N_distances, etc"""
<|body_0|>
def init_paths(self, data_name, path, N_distances, first_distance=1):
"""Generate paths images & flatfield... | stack_v2_sparse_classes_10k_train_004068 | 8,317 | permissive | [
{
"docstring": "Initialize parameters. Normally should contain ROI, N_distances, etc",
"name": "__init__",
"signature": "def __init__(self, ROI, folder, N_start, N_finish, compNpad=8)"
},
{
"docstring": "Generate paths images & flatfields",
"name": "init_paths",
"signature": "def init_pa... | 2 | stack_v2_sparse_classes_30k_train_006517 | Implement the Python class `Processor` described below.
Class description:
Implement the Processor class.
Method signatures and docstrings:
- def __init__(self, ROI, folder, N_start, N_finish, compNpad=8): Initialize parameters. Normally should contain ROI, N_distances, etc
- def init_paths(self, data_name, path, N_d... | Implement the Python class `Processor` described below.
Class description:
Implement the Processor class.
Method signatures and docstrings:
- def __init__(self, ROI, folder, N_start, N_finish, compNpad=8): Initialize parameters. Normally should contain ROI, N_distances, etc
- def init_paths(self, data_name, path, N_d... | 0178822dfbf4b1a249d510030b21fca28d51d2c0 | <|skeleton|>
class Processor:
def __init__(self, ROI, folder, N_start, N_finish, compNpad=8):
"""Initialize parameters. Normally should contain ROI, N_distances, etc"""
<|body_0|>
def init_paths(self, data_name, path, N_distances, first_distance=1):
"""Generate paths images & flatfield... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Processor:
def __init__(self, ROI, folder, N_start, N_finish, compNpad=8):
"""Initialize parameters. Normally should contain ROI, N_distances, etc"""
self.N_start = N_start
self.ROI = ROI
self.N_files = N_finish - N_start
self.im_shape = (ROI[3] - ROI[1], ROI[2] - ROI[0... | the_stack_v2_python_sparse | maximus48/deprecated/tomo_proc2.py | maximka48/XIMG-EMBL | train | 2 | |
18ce7032bfad47c2578f59cb438859d9c6120add | [
"n = len(nums)\nfor i in range(n + 1):\n if i not in nums:\n return i",
"n = len(nums)\nsetNums = set(nums)\nfor i in range(n + 1):\n if i not in setNums:\n return i",
"expectSum = len(nums) * (len(nums) + 1) // 2\nrealSum = sum(nums)\nreturn expectSum - realSum",
"missing = len(nums)\nfor... | <|body_start_0|>
n = len(nums)
for i in range(n + 1):
if i not in nums:
return i
<|end_body_0|>
<|body_start_1|>
n = len(nums)
setNums = set(nums)
for i in range(n + 1):
if i not in setNums:
return i
<|end_body_1|>
<|body_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def missingNumberBruteforce(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def missingNumberHashSet(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def missingNumberSum(self, nums):
""":type nums: List[i... | stack_v2_sparse_classes_10k_train_004069 | 1,405 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "missingNumberBruteforce",
"signature": "def missingNumberBruteforce(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "missingNumberHashSet",
"signature": "def missingNumberHashSet(self, nums)"
},
... | 5 | stack_v2_sparse_classes_30k_train_000942 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def missingNumberBruteforce(self, nums): :type nums: List[int] :rtype: int
- def missingNumberHashSet(self, nums): :type nums: List[int] :rtype: int
- def missingNumberSum(self, ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def missingNumberBruteforce(self, nums): :type nums: List[int] :rtype: int
- def missingNumberHashSet(self, nums): :type nums: List[int] :rtype: int
- def missingNumberSum(self, ... | a13e7faaf55cd68249267e46a91e93c97e3190c2 | <|skeleton|>
class Solution:
def missingNumberBruteforce(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def missingNumberHashSet(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def missingNumberSum(self, nums):
""":type nums: List[i... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def missingNumberBruteforce(self, nums):
""":type nums: List[int] :rtype: int"""
n = len(nums)
for i in range(n + 1):
if i not in nums:
return i
def missingNumberHashSet(self, nums):
""":type nums: List[int] :rtype: int"""
n = ... | the_stack_v2_python_sparse | LeetCode/Array/268.py | xiaojkql/Algorithm-Data-Structure | train | 1 | |
933bde235606baf6d6bcc568464e99ed3c46cf02 | [
"with self.assertRaises(TypeError):\n get_majorana_operator(1.0)\nwith self.assertRaises(TypeError):\n _fermion_operator_to_majorana_operator([1.0])\nwith self.assertRaises(TypeError):\n _fermion_term_to_majorana_operator(1.0)",
"fermion_op = -2j * (FermionOperator(((0, 0), (1, 0))) - FermionOperator(((0... | <|body_start_0|>
with self.assertRaises(TypeError):
get_majorana_operator(1.0)
with self.assertRaises(TypeError):
_fermion_operator_to_majorana_operator([1.0])
with self.assertRaises(TypeError):
_fermion_term_to_majorana_operator(1.0)
<|end_body_0|>
<|body_st... | Test class get Majorana Operator. | GetMajoranaOperatorTest | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetMajoranaOperatorTest:
"""Test class get Majorana Operator."""
def test_raises(self):
"""Test raises errors."""
<|body_0|>
def test_get_majorana_operator_fermion_operator(self):
"""Test conversion FermionOperator to MajoranaOperator."""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_004070 | 8,235 | permissive | [
{
"docstring": "Test raises errors.",
"name": "test_raises",
"signature": "def test_raises(self)"
},
{
"docstring": "Test conversion FermionOperator to MajoranaOperator.",
"name": "test_get_majorana_operator_fermion_operator",
"signature": "def test_get_majorana_operator_fermion_operator... | 3 | stack_v2_sparse_classes_30k_val_000126 | Implement the Python class `GetMajoranaOperatorTest` described below.
Class description:
Test class get Majorana Operator.
Method signatures and docstrings:
- def test_raises(self): Test raises errors.
- def test_get_majorana_operator_fermion_operator(self): Test conversion FermionOperator to MajoranaOperator.
- def ... | Implement the Python class `GetMajoranaOperatorTest` described below.
Class description:
Test class get Majorana Operator.
Method signatures and docstrings:
- def test_raises(self): Test raises errors.
- def test_get_majorana_operator_fermion_operator(self): Test conversion FermionOperator to MajoranaOperator.
- def ... | 788481753c798a72c5cb3aa9f2aa9da3ce3190b0 | <|skeleton|>
class GetMajoranaOperatorTest:
"""Test class get Majorana Operator."""
def test_raises(self):
"""Test raises errors."""
<|body_0|>
def test_get_majorana_operator_fermion_operator(self):
"""Test conversion FermionOperator to MajoranaOperator."""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GetMajoranaOperatorTest:
"""Test class get Majorana Operator."""
def test_raises(self):
"""Test raises errors."""
with self.assertRaises(TypeError):
get_majorana_operator(1.0)
with self.assertRaises(TypeError):
_fermion_operator_to_majorana_operator([1.0])
... | the_stack_v2_python_sparse | src/openfermion/transforms/opconversions/conversions_test.py | quantumlib/OpenFermion | train | 1,481 |
4f72cec555a029b91bec5f9dda2a949d4f739222 | [
"voucher = get_current_voucher(self.request.user)\nif voucher is None:\n return redirect('voucher:upload')\nelif voucher.is_redeemed():\n return redirect('voucher:redeemed')\neligible_choices = get_eligible_coupon_choices(voucher)\nif not eligible_choices:\n return redirect('voucher:resubmit')\nelse:\n ... | <|body_start_0|>
voucher = get_current_voucher(self.request.user)
if voucher is None:
return redirect('voucher:upload')
elif voucher.is_redeemed():
return redirect('voucher:redeemed')
eligible_choices = get_eligible_coupon_choices(voucher)
if not eligible_... | EnrollView checks the status of the voucher and looks for valid course runs to redeem it for On a POST, it redirects to the enrollment URL based on the submitted CouponEligibility object's product and coupon_code | EnrollView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnrollView:
"""EnrollView checks the status of the voucher and looks for valid course runs to redeem it for On a POST, it redirects to the enrollment URL based on the submitted CouponEligibility object's product and coupon_code"""
def get(self, request):
"""If voucher is not redeemed... | stack_v2_sparse_classes_10k_train_004071 | 5,982 | permissive | [
{
"docstring": "If voucher is not redeemed and valid coupons exist for course runs matching the input strings, render the enroll form with CouponEligibility objects as choices.",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Submit a CouponVersion object and redirect to... | 2 | null | Implement the Python class `EnrollView` described below.
Class description:
EnrollView checks the status of the voucher and looks for valid course runs to redeem it for On a POST, it redirects to the enrollment URL based on the submitted CouponEligibility object's product and coupon_code
Method signatures and docstri... | Implement the Python class `EnrollView` described below.
Class description:
EnrollView checks the status of the voucher and looks for valid course runs to redeem it for On a POST, it redirects to the enrollment URL based on the submitted CouponEligibility object's product and coupon_code
Method signatures and docstri... | c5d9cda4e1ed87463da74d7956f1e1f9258f365c | <|skeleton|>
class EnrollView:
"""EnrollView checks the status of the voucher and looks for valid course runs to redeem it for On a POST, it redirects to the enrollment URL based on the submitted CouponEligibility object's product and coupon_code"""
def get(self, request):
"""If voucher is not redeemed... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EnrollView:
"""EnrollView checks the status of the voucher and looks for valid course runs to redeem it for On a POST, it redirects to the enrollment URL based on the submitted CouponEligibility object's product and coupon_code"""
def get(self, request):
"""If voucher is not redeemed and valid co... | the_stack_v2_python_sparse | voucher/views.py | mitodl/mitxpro | train | 12 |
f456eaa20902f31cd22475449f7fb2bdb936920c | [
"if not head or not k or (not head.next):\n return head\ndummy = ListNode(0)\ndummy.next = head\nlth = 0\nwhile head:\n lth += 1\n head = head.next\nk = k % lth\nif not k:\n return dummy.next\na, b = (dummy, dummy)\nwhile k:\n b = b.next\n k -= 1\nwhile b.next:\n a, b = (a.next, b.next)\ndummy.... | <|body_start_0|>
if not head or not k or (not head.next):
return head
dummy = ListNode(0)
dummy.next = head
lth = 0
while head:
lth += 1
head = head.next
k = k % lth
if not k:
return dummy.next
a, b = (dummy,... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotateRight_twopoint1(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_0|>
def rotateRight_twopoint2(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
def rotateRight_connect_... | stack_v2_sparse_classes_10k_train_004072 | 2,536 | no_license | [
{
"docstring": ":type head: ListNode :type k: int :rtype: ListNode",
"name": "rotateRight_twopoint1",
"signature": "def rotateRight_twopoint1(self, head, k)"
},
{
"docstring": ":type head: ListNode :type k: int :rtype: ListNode",
"name": "rotateRight_twopoint2",
"signature": "def rotateR... | 3 | stack_v2_sparse_classes_30k_train_005476 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotateRight_twopoint1(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
- def rotateRight_twopoint2(self, head, k): :type head: ListNode :type k: int :rtype:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotateRight_twopoint1(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
- def rotateRight_twopoint2(self, head, k): :type head: ListNode :type k: int :rtype:... | 0e99f9a5226507706b3ee66fd04bae813755ef40 | <|skeleton|>
class Solution:
def rotateRight_twopoint1(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_0|>
def rotateRight_twopoint2(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
def rotateRight_connect_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def rotateRight_twopoint1(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
if not head or not k or (not head.next):
return head
dummy = ListNode(0)
dummy.next = head
lth = 0
while head:
lth += 1
... | the_stack_v2_python_sparse | medium/twopointer/test_61_Rotate_List.py | wuxu1019/leetcode_sophia | train | 1 | |
884b24c5e40050a245614050332544662d37e0ea | [
"self.rnd_state = np.random.RandomState(seed)\nself.nb_dims = len(mins)\nself.dims_dicts = []\nself.last_raw_task = None\nself.last_interpolated_task = None\nfor i in range(len(mins)):\n current_min = mins[i]\n current_max = maxs[i]\n region_size = abs(current_max - current_min) / cuttings\n current_dim... | <|body_start_0|>
self.rnd_state = np.random.RandomState(seed)
self.nb_dims = len(mins)
self.dims_dicts = []
self.last_raw_task = None
self.last_interpolated_task = None
for i in range(len(mins)):
current_min = mins[i]
current_max = maxs[i]
... | DimensionsShuffler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DimensionsShuffler:
def __init__(self, mins, maxs, cuttings=4, seed=21):
"""Object evenly cutting a task space into hypercubes and shuffling them. Args: mins: Lower bounds of task space max: Upper bounds of task space cuttings: How many cuttings should be done on each dimension seed: See... | stack_v2_sparse_classes_10k_train_004073 | 2,996 | permissive | [
{
"docstring": "Object evenly cutting a task space into hypercubes and shuffling them. Args: mins: Lower bounds of task space max: Upper bounds of task space cuttings: How many cuttings should be done on each dimension seed: Seed of the random shuffler",
"name": "__init__",
"signature": "def __init__(se... | 3 | stack_v2_sparse_classes_30k_train_005611 | Implement the Python class `DimensionsShuffler` described below.
Class description:
Implement the DimensionsShuffler class.
Method signatures and docstrings:
- def __init__(self, mins, maxs, cuttings=4, seed=21): Object evenly cutting a task space into hypercubes and shuffling them. Args: mins: Lower bounds of task s... | Implement the Python class `DimensionsShuffler` described below.
Class description:
Implement the DimensionsShuffler class.
Method signatures and docstrings:
- def __init__(self, mins, maxs, cuttings=4, seed=21): Object evenly cutting a task space into hypercubes and shuffling them. Args: mins: Lower bounds of task s... | 6c157511a609e84596c4f8aad99e7576a015ee15 | <|skeleton|>
class DimensionsShuffler:
def __init__(self, mins, maxs, cuttings=4, seed=21):
"""Object evenly cutting a task space into hypercubes and shuffling them. Args: mins: Lower bounds of task space max: Upper bounds of task space cuttings: How many cuttings should be done on each dimension seed: See... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DimensionsShuffler:
def __init__(self, mins, maxs, cuttings=4, seed=21):
"""Object evenly cutting a task space into hypercubes and shuffling them. Args: mins: Lower bounds of task space max: Upper bounds of task space cuttings: How many cuttings should be done on each dimension seed: Seed of the rando... | the_stack_v2_python_sparse | TeachMyAgent/teachers/utils/dimensions_shuffler.py | flowersteam/TeachMyAgent | train | 70 | |
0c7a1a5b96126d09e5945b798b8f16a5c95957cd | [
"super().__init__(parent)\nself.input_q = command_queue\nself.sphere_args = sphere_args\nself.fname = fname\nself.file_lock = file_lock\nself.signal_q = mp.Queue()\nself.command_q = mp.Queue()",
"process = wranglerProcess(self.command_q, self.signal_q, self.sphere_args, self.fname, self.file_lock)\nprocess.start(... | <|body_start_0|>
super().__init__(parent)
self.input_q = command_queue
self.sphere_args = sphere_args
self.fname = fname
self.file_lock = file_lock
self.signal_q = mp.Queue()
self.command_q = mp.Queue()
<|end_body_0|>
<|body_start_1|>
process = wranglerPr... | Base class for wranglerThreads. Used to manage processes including data and command queues. Subclasses should override the run method. attributes: command_q: mp.Queue, queue to send commands to process file_lock: mp.Condition, process safe lock for file access fname: str, path to data file. input_q: mp.Queue, queue for... | wranglerThread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class wranglerThread:
"""Base class for wranglerThreads. Used to manage processes including data and command queues. Subclasses should override the run method. attributes: command_q: mp.Queue, queue to send commands to process file_lock: mp.Condition, process safe lock for file access fname: str, path ... | stack_v2_sparse_classes_10k_train_004074 | 8,377 | no_license | [
{
"docstring": "command_queue: mp.Queue, queue for commands sent from parent sphere_args: dict, used as **kwargs in sphere initialization. see EwaldSphere. fname: str, path to data file. file_lock: mp.Condition, process safe lock for file access",
"name": "__init__",
"signature": "def __init__(self, com... | 2 | stack_v2_sparse_classes_30k_train_000814 | Implement the Python class `wranglerThread` described below.
Class description:
Base class for wranglerThreads. Used to manage processes including data and command queues. Subclasses should override the run method. attributes: command_q: mp.Queue, queue to send commands to process file_lock: mp.Condition, process safe... | Implement the Python class `wranglerThread` described below.
Class description:
Base class for wranglerThreads. Used to manage processes including data and command queues. Subclasses should override the run method. attributes: command_q: mp.Queue, queue to send commands to process file_lock: mp.Condition, process safe... | f145e757d092d85b5a21dc4c36d99f82d55f7037 | <|skeleton|>
class wranglerThread:
"""Base class for wranglerThreads. Used to manage processes including data and command queues. Subclasses should override the run method. attributes: command_q: mp.Queue, queue to send commands to process file_lock: mp.Condition, process safe lock for file access fname: str, path ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class wranglerThread:
"""Base class for wranglerThreads. Used to manage processes including data and command queues. Subclasses should override the run method. attributes: command_q: mp.Queue, queue to send commands to process file_lock: mp.Condition, process safe lock for file access fname: str, path to data file.... | the_stack_v2_python_sparse | xdart/gui/tabs/static_scan/wranglers/wrangler_widget.py | rwalroth/xdart | train | 2 |
e0adebad64b655dbb5e2c6cebbc8b311010540da | [
"if 'default' in kwargs:\n if version is not None:\n kwargs['default'] = version\n super().__init__(title=title, advanced=advanced, **kwargs)\nelse:\n super().__init__(title=title, advanced=advanced, default=version, **kwargs)",
"if not is_version_valid(value):\n raise InvalidVersionFormat('Ver... | <|body_start_0|>
if 'default' in kwargs:
if version is not None:
kwargs['default'] = version
super().__init__(title=title, advanced=advanced, **kwargs)
else:
super().__init__(title=title, advanced=advanced, default=version, **kwargs)
<|end_body_0|>
<|... | Defines a Version property. Version property permits saving version information with (major.minor.build) format | VersionProperty | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VersionProperty:
"""Defines a Version property. Version property permits saving version information with (major.minor.build) format"""
def __init__(self, version=None, title='Version', advanced=True, **kwargs):
"""Initializes a version property. Keyword Args: Property definitions"""
... | stack_v2_sparse_classes_10k_train_004075 | 1,220 | no_license | [
{
"docstring": "Initializes a version property. Keyword Args: Property definitions",
"name": "__init__",
"signature": "def __init__(self, version=None, title='Version', advanced=True, **kwargs)"
},
{
"docstring": "Override default set to make sure it's a valid version",
"name": "__set__",
... | 2 | stack_v2_sparse_classes_30k_train_004932 | Implement the Python class `VersionProperty` described below.
Class description:
Defines a Version property. Version property permits saving version information with (major.minor.build) format
Method signatures and docstrings:
- def __init__(self, version=None, title='Version', advanced=True, **kwargs): Initializes a... | Implement the Python class `VersionProperty` described below.
Class description:
Defines a Version property. Version property permits saving version information with (major.minor.build) format
Method signatures and docstrings:
- def __init__(self, version=None, title='Version', advanced=True, **kwargs): Initializes a... | e2ef4c7b56c4e7e06964fe6f64ae6c497ac31727 | <|skeleton|>
class VersionProperty:
"""Defines a Version property. Version property permits saving version information with (major.minor.build) format"""
def __init__(self, version=None, title='Version', advanced=True, **kwargs):
"""Initializes a version property. Keyword Args: Property definitions"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VersionProperty:
"""Defines a Version property. Version property permits saving version information with (major.minor.build) format"""
def __init__(self, version=None, title='Version', advanced=True, **kwargs):
"""Initializes a version property. Keyword Args: Property definitions"""
if 'd... | the_stack_v2_python_sparse | nio/properties/version.py | niolabs/nio | train | 5 |
b2a45618b02c9babe1661231eefdf1d309e6fe6d | [
"assert isinstance(response, scrapy.http.response.html.HtmlResponse)\ncurboard = response.selector.xpath('//div[contains(@class, \"titleBar\")]/h1/text()').extract()\nlast_page = MAX_PAGE[curboard[0].lower()]\n'try:\\n last_page = int(response.selector.xpath(\\'//nav/a[@class=\"PageNavNext\"]/following::... | <|body_start_0|>
assert isinstance(response, scrapy.http.response.html.HtmlResponse)
curboard = response.selector.xpath('//div[contains(@class, "titleBar")]/h1/text()').extract()
last_page = MAX_PAGE[curboard[0].lower()]
'try:\n last_page = int(response.selector.xpath(\'//nav/... | scrape reports from angling addicts forum | worldseafishingAfloatSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class worldseafishingAfloatSpider:
"""scrape reports from angling addicts forum"""
def parse(self, response):
"""generate links to pages in a board yields: https://www.worldseafishing.com/forums/forums/south-east-catch-reports.39/, ..."""
<|body_0|>
def crawl_board_threads(sel... | stack_v2_sparse_classes_10k_train_004076 | 9,045 | no_license | [
{
"docstring": "generate links to pages in a board yields: https://www.worldseafishing.com/forums/forums/south-east-catch-reports.39/, ...",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "crawl",
"name": "crawl_board_threads",
"signature": "def crawl_board_t... | 3 | null | Implement the Python class `worldseafishingAfloatSpider` described below.
Class description:
scrape reports from angling addicts forum
Method signatures and docstrings:
- def parse(self, response): generate links to pages in a board yields: https://www.worldseafishing.com/forums/forums/south-east-catch-reports.39/, .... | Implement the Python class `worldseafishingAfloatSpider` described below.
Class description:
scrape reports from angling addicts forum
Method signatures and docstrings:
- def parse(self, response): generate links to pages in a board yields: https://www.worldseafishing.com/forums/forums/south-east-catch-reports.39/, .... | 9123aa6baf538b662143b9098d963d55165e8409 | <|skeleton|>
class worldseafishingAfloatSpider:
"""scrape reports from angling addicts forum"""
def parse(self, response):
"""generate links to pages in a board yields: https://www.worldseafishing.com/forums/forums/south-east-catch-reports.39/, ..."""
<|body_0|>
def crawl_board_threads(sel... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class worldseafishingAfloatSpider:
"""scrape reports from angling addicts forum"""
def parse(self, response):
"""generate links to pages in a board yields: https://www.worldseafishing.com/forums/forums/south-east-catch-reports.39/, ..."""
assert isinstance(response, scrapy.http.response.html.Ht... | the_stack_v2_python_sparse | imgscrape/spiders/worldseafishing_reports.py | gmonkman/python | train | 0 |
984e51093a614278403bb7ef16f537131e2d68c2 | [
"self.exception_type = exception_type\n'The type of exception that should be raised.'\nself.text = text\n'The snippet or regex that the exception message must match.'\nself.exception = None\n'The exception that was caught.'\nself.assert_exact_type = assert_exact_type\n'\\n Flag saying whether we require an e... | <|body_start_0|>
self.exception_type = exception_type
'The type of exception that should be raised.'
self.text = text
'The snippet or regex that the exception message must match.'
self.exception = None
'The exception that was caught.'
self.assert_exact_type = asse... | Asserts that a certain exception was raised in the suite. You may use a snippet of text that must appear in the exception message or a regex that the exception message must match. Example: with RaiseAssertor(ZeroDivisionError, 'modulo by zero'): 1/0 | RaiseAssertor | [
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RaiseAssertor:
"""Asserts that a certain exception was raised in the suite. You may use a snippet of text that must appear in the exception message or a regex that the exception message must match. Example: with RaiseAssertor(ZeroDivisionError, 'modulo by zero'): 1/0"""
def __init__(self, ex... | stack_v2_sparse_classes_10k_train_004077 | 6,069 | permissive | [
{
"docstring": "Construct the `RaiseAssertor`. `exception_type` is an exception type that the exception must be of; `text` may be either a snippet of text that must appear in the exception's message, or a regex pattern that the exception message must match. Specify `assert_exact_type=False` if you want to asser... | 2 | null | Implement the Python class `RaiseAssertor` described below.
Class description:
Asserts that a certain exception was raised in the suite. You may use a snippet of text that must appear in the exception message or a regex that the exception message must match. Example: with RaiseAssertor(ZeroDivisionError, 'modulo by ze... | Implement the Python class `RaiseAssertor` described below.
Class description:
Asserts that a certain exception was raised in the suite. You may use a snippet of text that must appear in the exception message or a regex that the exception message must match. Example: with RaiseAssertor(ZeroDivisionError, 'modulo by ze... | cb9ef64b48f1d03275484d707dc5079b6701ad0c | <|skeleton|>
class RaiseAssertor:
"""Asserts that a certain exception was raised in the suite. You may use a snippet of text that must appear in the exception message or a regex that the exception message must match. Example: with RaiseAssertor(ZeroDivisionError, 'modulo by zero'): 1/0"""
def __init__(self, ex... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RaiseAssertor:
"""Asserts that a certain exception was raised in the suite. You may use a snippet of text that must appear in the exception message or a regex that the exception message must match. Example: with RaiseAssertor(ZeroDivisionError, 'modulo by zero'): 1/0"""
def __init__(self, exception_type=... | the_stack_v2_python_sparse | python_toolbox/cute_testing.py | cool-RR/python_toolbox | train | 130 |
2ec8540eac3048cc7295d9923e719fc08970a3b2 | [
"cnt = {}\nn = len(nums)\nfor i in nums:\n if cnt.get(i, 0) == 0:\n cnt[i] = 1\n else:\n cnt[i] += 1\n if cnt[i] > n // 2:\n return i\nif n == 1:\n return nums[0]",
"count = 0\ncandidate = None\nfor i in nums:\n if count == 0:\n candidate = i\n count += 1 if i... | <|body_start_0|>
cnt = {}
n = len(nums)
for i in nums:
if cnt.get(i, 0) == 0:
cnt[i] = 1
else:
cnt[i] += 1
if cnt[i] > n // 2:
return i
if n == 1:
return nums[0]
<|end_body_0|>
<|body... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def majorityElement(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def majorityElement(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cnt = {}
n = len(nums)
... | stack_v2_sparse_classes_10k_train_004078 | 776 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "majorityElement",
"signature": "def majorityElement(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "majorityElement",
"signature": "def majorityElement(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002427 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def majorityElement(self, nums): :type nums: List[int] :rtype: int
- def majorityElement(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def majorityElement(self, nums): :type nums: List[int] :rtype: int
- def majorityElement(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def maj... | b7d9238d692b1b2f5ab8f73a76d02228a71a4d15 | <|skeleton|>
class Solution:
def majorityElement(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def majorityElement(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def majorityElement(self, nums):
""":type nums: List[int] :rtype: int"""
cnt = {}
n = len(nums)
for i in nums:
if cnt.get(i, 0) == 0:
cnt[i] = 1
else:
cnt[i] += 1
if cnt[i] > n // 2:
... | the_stack_v2_python_sparse | 169-Majority-Element.py | liuspencersjtu/MyLeetCode | train | 0 | |
f52957f572073650cf122021c25752587457ff7c | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn FilterOperatorSchema()",
"from .attribute_type import AttributeType\nfrom .entity import Entity\nfrom .scope_operator_multi_valued_comparison_type import ScopeOperatorMultiValuedComparisonType\nfrom .scope_operator_type import ScopeOpe... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return FilterOperatorSchema()
<|end_body_0|>
<|body_start_1|>
from .attribute_type import AttributeType
from .entity import Entity
from .scope_operator_multi_valued_comparison_type impo... | FilterOperatorSchema | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilterOperatorSchema:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FilterOperatorSchema:
"""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 ... | stack_v2_sparse_classes_10k_train_004079 | 3,425 | 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: FilterOperatorSchema",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminato... | 3 | null | Implement the Python class `FilterOperatorSchema` described below.
Class description:
Implement the FilterOperatorSchema class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FilterOperatorSchema: Creates a new instance of the appropriate class based o... | Implement the Python class `FilterOperatorSchema` described below.
Class description:
Implement the FilterOperatorSchema class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FilterOperatorSchema: Creates a new instance of the appropriate class based o... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class FilterOperatorSchema:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FilterOperatorSchema:
"""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 ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FilterOperatorSchema:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FilterOperatorSchema:
"""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... | the_stack_v2_python_sparse | msgraph/generated/models/filter_operator_schema.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
e9e36d86ba5386da6568bc453d6f7cf6dac307b0 | [
"if len(chs) < 2:\n return chs\narrs = list(chs)\ni = 0\nj = len(chs) - 1\nwhile i < j:\n if str(arrs[i]).isalpha() and str(arrs[j]).isalpha():\n self.swap(arrs, i, j)\n i += 1\n j -= 1\n elif str(arrs[i]).isalpha():\n j -= 1\n elif str(arrs[j]).isalpha():\n i += 1\n ... | <|body_start_0|>
if len(chs) < 2:
return chs
arrs = list(chs)
i = 0
j = len(chs) - 1
while i < j:
if str(arrs[i]).isalpha() and str(arrs[j]).isalpha():
self.swap(arrs, i, j)
i += 1
j -= 1
elif str... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverse_only_letters(self, chs: str) -> str:
"""反转字符串 Args: chs: 字符串数组 Returns: 反转后字符串"""
<|body_0|>
def swap(self, chs: List[str], i: int, j: int) -> None:
"""交换数组位置 Args: chs: 数组 i: 位置i j: 位置j Returns: 交换位置后的数组"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_10k_train_004080 | 2,439 | permissive | [
{
"docstring": "反转字符串 Args: chs: 字符串数组 Returns: 反转后字符串",
"name": "reverse_only_letters",
"signature": "def reverse_only_letters(self, chs: str) -> str"
},
{
"docstring": "交换数组位置 Args: chs: 数组 i: 位置i j: 位置j Returns: 交换位置后的数组",
"name": "swap",
"signature": "def swap(self, chs: List[str], i... | 2 | stack_v2_sparse_classes_30k_train_002954 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse_only_letters(self, chs: str) -> str: 反转字符串 Args: chs: 字符串数组 Returns: 反转后字符串
- def swap(self, chs: List[str], i: int, j: int) -> None: 交换数组位置 Args: chs: 数组 i: 位置i j: 位... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse_only_letters(self, chs: str) -> str: 反转字符串 Args: chs: 字符串数组 Returns: 反转后字符串
- def swap(self, chs: List[str], i: int, j: int) -> None: 交换数组位置 Args: chs: 数组 i: 位置i j: 位... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def reverse_only_letters(self, chs: str) -> str:
"""反转字符串 Args: chs: 字符串数组 Returns: 反转后字符串"""
<|body_0|>
def swap(self, chs: List[str], i: int, j: int) -> None:
"""交换数组位置 Args: chs: 数组 i: 位置i j: 位置j Returns: 交换位置后的数组"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def reverse_only_letters(self, chs: str) -> str:
"""反转字符串 Args: chs: 字符串数组 Returns: 反转后字符串"""
if len(chs) < 2:
return chs
arrs = list(chs)
i = 0
j = len(chs) - 1
while i < j:
if str(arrs[i]).isalpha() and str(arrs[j]).isalpha():... | the_stack_v2_python_sparse | src/leetcodepython/string/reverse_only_letters_917.py | zhangyu345293721/leetcode | train | 101 | |
273688249d65e0fda0d79cd1e4ae8498e429899e | [
"context = super().get_context_data(**kwargs)\ncontext['url_stap_2'] = reverse('Account:otp-koppelen-stap2')\ncontext['url_controleer'] = reverse('Account:otp-koppelen-stap3')\ncontext['site_name'] = settings.OTP_ISSUER_NAME\ncontext['form'] = OTPControleForm()\ncontext['now'] = timezone.now()\nmenu_dynamics(self.r... | <|body_start_0|>
context = super().get_context_data(**kwargs)
context['url_stap_2'] = reverse('Account:otp-koppelen-stap2')
context['url_controleer'] = reverse('Account:otp-koppelen-stap3')
context['site_name'] = settings.OTP_ISSUER_NAME
context['form'] = OTPControleForm()
... | OTPKoppelenStap3View | [
"BSD-3-Clause-Clear"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OTPKoppelenStap3View:
def get_context_data(self, **kwargs):
"""called by the template system to get the context data for the template"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""deze functie wordt aangeroepen als een POST request ontvangen is. dit is g... | stack_v2_sparse_classes_10k_train_004081 | 5,630 | permissive | [
{
"docstring": "called by the template system to get the context data for the template",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
},
{
"docstring": "deze functie wordt aangeroepen als een POST request ontvangen is. dit is gekoppeld aan het drukken op de Con... | 2 | stack_v2_sparse_classes_30k_val_000177 | Implement the Python class `OTPKoppelenStap3View` described below.
Class description:
Implement the OTPKoppelenStap3View class.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): called by the template system to get the context data for the template
- def post(self, request, *args, **kwargs): d... | Implement the Python class `OTPKoppelenStap3View` described below.
Class description:
Implement the OTPKoppelenStap3View class.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): called by the template system to get the context data for the template
- def post(self, request, *args, **kwargs): d... | 5ed38165a231f0caa56f67e8faf2dd074916e500 | <|skeleton|>
class OTPKoppelenStap3View:
def get_context_data(self, **kwargs):
"""called by the template system to get the context data for the template"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""deze functie wordt aangeroepen als een POST request ontvangen is. dit is g... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OTPKoppelenStap3View:
def get_context_data(self, **kwargs):
"""called by the template system to get the context data for the template"""
context = super().get_context_data(**kwargs)
context['url_stap_2'] = reverse('Account:otp-koppelen-stap2')
context['url_controleer'] = revers... | the_stack_v2_python_sparse | Account/view_otp_koppelen.py | RamonvdW/nhb-apps | train | 2 | |
59ed3e63410910f4775c503f287f03115e2938db | [
"super(ListInterestCategoryInterest, self).__init__(*args, **kwargs)\nself.endpoint = 'lists'\nself.list_id = None\nself.category_id = None\nself.interest_id = None",
"self.list_id = list_id\nself.category_id = category_id\nif 'name' not in data:\n raise KeyError('The list interest category interest must have ... | <|body_start_0|>
super(ListInterestCategoryInterest, self).__init__(*args, **kwargs)
self.endpoint = 'lists'
self.list_id = None
self.category_id = None
self.interest_id = None
<|end_body_0|>
<|body_start_1|>
self.list_id = list_id
self.category_id = category_id
... | Manage interests for a specific MailChimp list. Assign subscribers to interests to group them together. Interests are referred to as ‘group names’ in the MailChimp application. | ListInterestCategoryInterest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListInterestCategoryInterest:
"""Manage interests for a specific MailChimp list. Assign subscribers to interests to group them together. Interests are referred to as ‘group names’ in the MailChimp application."""
def __init__(self, *args, **kwargs):
"""Initialize the endpoint"""
... | stack_v2_sparse_classes_10k_train_004082 | 5,847 | permissive | [
{
"docstring": "Initialize the endpoint",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Create a new interest or ‘group name’ for a specific category. The documentation lists only the name request body parameter so it is being documented and error-chec... | 6 | stack_v2_sparse_classes_30k_train_003666 | Implement the Python class `ListInterestCategoryInterest` described below.
Class description:
Manage interests for a specific MailChimp list. Assign subscribers to interests to group them together. Interests are referred to as ‘group names’ in the MailChimp application.
Method signatures and docstrings:
- def __init_... | Implement the Python class `ListInterestCategoryInterest` described below.
Class description:
Manage interests for a specific MailChimp list. Assign subscribers to interests to group them together. Interests are referred to as ‘group names’ in the MailChimp application.
Method signatures and docstrings:
- def __init_... | bf61cd602dc44cbff32fbf6f6dcdd33cf6f782e8 | <|skeleton|>
class ListInterestCategoryInterest:
"""Manage interests for a specific MailChimp list. Assign subscribers to interests to group them together. Interests are referred to as ‘group names’ in the MailChimp application."""
def __init__(self, *args, **kwargs):
"""Initialize the endpoint"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ListInterestCategoryInterest:
"""Manage interests for a specific MailChimp list. Assign subscribers to interests to group them together. Interests are referred to as ‘group names’ in the MailChimp application."""
def __init__(self, *args, **kwargs):
"""Initialize the endpoint"""
super(Lis... | the_stack_v2_python_sparse | mailchimp3/entities/listinterestcategoryinterest.py | VingtCinq/python-mailchimp | train | 190 |
c0f0133a3e0145e891086ec9b63bfa05c8c66bfd | [
"super(ChassisCharmOperationTest, cls).setUpClass()\ncls.services = ['ovn-controller']\nif cls.application_name == 'ovn-chassis':\n principal_app_name = 'magpie'\nelse:\n principal_app_name = cls.application_name\nsource = zaza.model.get_application_config(principal_app_name)['source']['value']\nlogging.info(... | <|body_start_0|>
super(ChassisCharmOperationTest, cls).setUpClass()
cls.services = ['ovn-controller']
if cls.application_name == 'ovn-chassis':
principal_app_name = 'magpie'
else:
principal_app_name = cls.application_name
source = zaza.model.get_applicatio... | OVN Chassis Charm operation tests. | ChassisCharmOperationTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChassisCharmOperationTest:
"""OVN Chassis Charm operation tests."""
def setUpClass(cls):
"""Run class setup for OVN Chassis charm operation tests."""
<|body_0|>
def test_prefer_chassis_as_gw(self):
"""Confirm effect of prefer-chassis-as-gw configuration option.""... | stack_v2_sparse_classes_10k_train_004083 | 37,617 | permissive | [
{
"docstring": "Run class setup for OVN Chassis charm operation tests.",
"name": "setUpClass",
"signature": "def setUpClass(cls)"
},
{
"docstring": "Confirm effect of prefer-chassis-as-gw configuration option.",
"name": "test_prefer_chassis_as_gw",
"signature": "def test_prefer_chassis_a... | 3 | stack_v2_sparse_classes_30k_train_000290 | Implement the Python class `ChassisCharmOperationTest` described below.
Class description:
OVN Chassis Charm operation tests.
Method signatures and docstrings:
- def setUpClass(cls): Run class setup for OVN Chassis charm operation tests.
- def test_prefer_chassis_as_gw(self): Confirm effect of prefer-chassis-as-gw co... | Implement the Python class `ChassisCharmOperationTest` described below.
Class description:
OVN Chassis Charm operation tests.
Method signatures and docstrings:
- def setUpClass(cls): Run class setup for OVN Chassis charm operation tests.
- def test_prefer_chassis_as_gw(self): Confirm effect of prefer-chassis-as-gw co... | 3b17ad9d97c57b6e62797d4e3333e4b83e43a447 | <|skeleton|>
class ChassisCharmOperationTest:
"""OVN Chassis Charm operation tests."""
def setUpClass(cls):
"""Run class setup for OVN Chassis charm operation tests."""
<|body_0|>
def test_prefer_chassis_as_gw(self):
"""Confirm effect of prefer-chassis-as-gw configuration option.""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ChassisCharmOperationTest:
"""OVN Chassis Charm operation tests."""
def setUpClass(cls):
"""Run class setup for OVN Chassis charm operation tests."""
super(ChassisCharmOperationTest, cls).setUpClass()
cls.services = ['ovn-controller']
if cls.application_name == 'ovn-chassi... | the_stack_v2_python_sparse | zaza/openstack/charm_tests/ovn/tests.py | openstack-charmers/zaza-openstack-tests | train | 7 |
c97bdc9758500115d00dd12e74d8b9f2a1772596 | [
"self.groups: set[LcnAddr] = set()\nself.groups_known = asyncio.Event()\nsuper().__init__(addr_conn, num_tries, timeout_msec)",
"if isinstance(inp, inputs.ModStatusGroups):\n if inp.dynamic:\n self.groups.update(inp.groups)\n self.groups_known.set()\n await self.cancel()",
"if not failed... | <|body_start_0|>
self.groups: set[LcnAddr] = set()
self.groups_known = asyncio.Event()
super().__init__(addr_conn, num_tries, timeout_msec)
<|end_body_0|>
<|body_start_1|>
if isinstance(inp, inputs.ModStatusGroups):
if inp.dynamic:
self.groups.update(inp.grou... | Request handler to request static group membership of a module. | GroupMembershipDynamicRequestHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupMembershipDynamicRequestHandler:
"""Request handler to request static group membership of a module."""
def __init__(self, addr_conn: ModuleConnection, num_tries: int=3, timeout_msec: int=1500):
"""Initialize class instance."""
<|body_0|>
async def async_process_inpu... | stack_v2_sparse_classes_10k_train_004084 | 24,302 | permissive | [
{
"docstring": "Initialize class instance.",
"name": "__init__",
"signature": "def __init__(self, addr_conn: ModuleConnection, num_tries: int=3, timeout_msec: int=1500)"
},
{
"docstring": "Process incoming input object. Method to handle incoming commands for this specific request handler.",
... | 4 | stack_v2_sparse_classes_30k_train_007290 | Implement the Python class `GroupMembershipDynamicRequestHandler` described below.
Class description:
Request handler to request static group membership of a module.
Method signatures and docstrings:
- def __init__(self, addr_conn: ModuleConnection, num_tries: int=3, timeout_msec: int=1500): Initialize class instance... | Implement the Python class `GroupMembershipDynamicRequestHandler` described below.
Class description:
Request handler to request static group membership of a module.
Method signatures and docstrings:
- def __init__(self, addr_conn: ModuleConnection, num_tries: int=3, timeout_msec: int=1500): Initialize class instance... | 00b45d5dcec8fccd4b13d218ac56194f44959e68 | <|skeleton|>
class GroupMembershipDynamicRequestHandler:
"""Request handler to request static group membership of a module."""
def __init__(self, addr_conn: ModuleConnection, num_tries: int=3, timeout_msec: int=1500):
"""Initialize class instance."""
<|body_0|>
async def async_process_inpu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GroupMembershipDynamicRequestHandler:
"""Request handler to request static group membership of a module."""
def __init__(self, addr_conn: ModuleConnection, num_tries: int=3, timeout_msec: int=1500):
"""Initialize class instance."""
self.groups: set[LcnAddr] = set()
self.groups_kno... | the_stack_v2_python_sparse | pypck/request_handlers.py | alengwenus/pypck | train | 6 |
b5f32f84124af5ab1349b23a8d6ccc05ade5e833 | [
"super().__init__()\nself.out_dim = out_dim\nself.num_heads = num_heads\nself.d_k = out_dim // num_heads\nself.k_linear = k_linear\nself.q_linear = q_linear\nself.v_linear = v_linear\nself.w_att = w_att\nself.w_msg = w_msg\nself.mu = mu",
"with g.local_scope():\n feat_src, feat_dst = expand_as_pair(feat, g)\n ... | <|body_start_0|>
super().__init__()
self.out_dim = out_dim
self.num_heads = num_heads
self.d_k = out_dim // num_heads
self.k_linear = k_linear
self.q_linear = q_linear
self.v_linear = v_linear
self.w_att = w_att
self.w_msg = w_msg
self.mu =... | HGTAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HGTAttention:
def __init__(self, out_dim, num_heads, k_linear, q_linear, v_linear, w_att, w_msg, mu):
"""HGT注意力模块 :param out_dim: int 输出特征维数 :param num_heads: int 注意力头数K :param k_linear: nn.Linear(d_in, d_out) :param q_linear: nn.Linear(d_in, d_out) :param v_linear: nn.Linear(d_in, d_out... | stack_v2_sparse_classes_10k_train_004085 | 8,548 | no_license | [
{
"docstring": "HGT注意力模块 :param out_dim: int 输出特征维数 :param num_heads: int 注意力头数K :param k_linear: nn.Linear(d_in, d_out) :param q_linear: nn.Linear(d_in, d_out) :param v_linear: nn.Linear(d_in, d_out) :param w_att: tensor(K, d_out/K, d_out/K) :param w_msg: tensor(K, d_out/K, d_out/K) :param mu: tensor(1)",
... | 2 | stack_v2_sparse_classes_30k_train_002109 | Implement the Python class `HGTAttention` described below.
Class description:
Implement the HGTAttention class.
Method signatures and docstrings:
- def __init__(self, out_dim, num_heads, k_linear, q_linear, v_linear, w_att, w_msg, mu): HGT注意力模块 :param out_dim: int 输出特征维数 :param num_heads: int 注意力头数K :param k_linear: ... | Implement the Python class `HGTAttention` described below.
Class description:
Implement the HGTAttention class.
Method signatures and docstrings:
- def __init__(self, out_dim, num_heads, k_linear, q_linear, v_linear, w_att, w_msg, mu): HGT注意力模块 :param out_dim: int 输出特征维数 :param num_heads: int 注意力头数K :param k_linear: ... | b40071dc9f9fb20f081f4ed4944a7b65de919c18 | <|skeleton|>
class HGTAttention:
def __init__(self, out_dim, num_heads, k_linear, q_linear, v_linear, w_att, w_msg, mu):
"""HGT注意力模块 :param out_dim: int 输出特征维数 :param num_heads: int 注意力头数K :param k_linear: nn.Linear(d_in, d_out) :param q_linear: nn.Linear(d_in, d_out) :param v_linear: nn.Linear(d_in, d_out... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HGTAttention:
def __init__(self, out_dim, num_heads, k_linear, q_linear, v_linear, w_att, w_msg, mu):
"""HGT注意力模块 :param out_dim: int 输出特征维数 :param num_heads: int 注意力头数K :param k_linear: nn.Linear(d_in, d_out) :param q_linear: nn.Linear(d_in, d_out) :param v_linear: nn.Linear(d_in, d_out) :param w_att... | the_stack_v2_python_sparse | gnn/hgt/model.py | deepdumbo/pytorch-tutorial-1 | train | 0 | |
6d749a4f82084b210b4a0b90d11a59ca99d1e67e | [
"if ssh_config['identity'] and ssh_config['identity'].get('ssh_key'):\n return ssh_config['identity']['ssh_key']['label']\nreturn None",
"if 'identityfile' not in config:\n return None\nidentityfile = self.choose_ssh_key(config['identityfile'], config)\nif not identityfile:\n return None\ncontent = ident... | <|body_start_0|>
if ssh_config['identity'] and ssh_config['identity'].get('ssh_key'):
return ssh_config['identity']['ssh_key']['label']
return None
<|end_body_0|>
<|body_start_1|>
if 'identityfile' not in config:
return None
identityfile = self.choose_ssh_key(con... | Class for adapting app host and ssh config hosts. | SSHConfigHostAdapter | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SSHConfigHostAdapter:
"""Class for adapting app host and ssh config hosts."""
def get_instance_ssh_key_label(self, ssh_config):
"""Retrieve the ssh_key lable."""
<|body_0|>
def create_key(self, config):
"""Construct new application ssh key instance."""
<|... | stack_v2_sparse_classes_10k_train_004086 | 2,943 | permissive | [
{
"docstring": "Retrieve the ssh_key lable.",
"name": "get_instance_ssh_key_label",
"signature": "def get_instance_ssh_key_label(self, ssh_config)"
},
{
"docstring": "Construct new application ssh key instance.",
"name": "create_key",
"signature": "def create_key(self, config)"
},
{
... | 5 | stack_v2_sparse_classes_30k_train_001986 | Implement the Python class `SSHConfigHostAdapter` described below.
Class description:
Class for adapting app host and ssh config hosts.
Method signatures and docstrings:
- def get_instance_ssh_key_label(self, ssh_config): Retrieve the ssh_key lable.
- def create_key(self, config): Construct new application ssh key in... | Implement the Python class `SSHConfigHostAdapter` described below.
Class description:
Class for adapting app host and ssh config hosts.
Method signatures and docstrings:
- def get_instance_ssh_key_label(self, ssh_config): Retrieve the ssh_key lable.
- def create_key(self, config): Construct new application ssh key in... | 2664d0c70d3d682ad931b885b4965447b156c280 | <|skeleton|>
class SSHConfigHostAdapter:
"""Class for adapting app host and ssh config hosts."""
def get_instance_ssh_key_label(self, ssh_config):
"""Retrieve the ssh_key lable."""
<|body_0|>
def create_key(self, config):
"""Construct new application ssh key instance."""
<|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SSHConfigHostAdapter:
"""Class for adapting app host and ssh config hosts."""
def get_instance_ssh_key_label(self, ssh_config):
"""Retrieve the ssh_key lable."""
if ssh_config['identity'] and ssh_config['identity'].get('ssh_key'):
return ssh_config['identity']['ssh_key']['labe... | the_stack_v2_python_sparse | termius/porting/providers/ssh/adapter.py | termius/termius-cli | train | 262 |
8bac80a1cfd9c92ac028478771b477e8275f9ef9 | [
"super().__init__(max_id, poisson_lam, zipf_param, id_shift)\nself.__shuffle_window = shuffle_window\nself.__next_shuffle = shuffle_window\nself.__shuffle_map = np.arange(id_shift + 1, id_shift + max_id + 1)\nif start_shuffled:\n np.random.shuffle(self.__shuffle_map)",
"vals = list(super().get_distribution_map... | <|body_start_0|>
super().__init__(max_id, poisson_lam, zipf_param, id_shift)
self.__shuffle_window = shuffle_window
self.__next_shuffle = shuffle_window
self.__shuffle_map = np.arange(id_shift + 1, id_shift + max_id + 1)
if start_shuffled:
np.random.shuffle(self.__shu... | PoissonShuffleZipfGenerator implements generator with poisson arrivals and Zipf popularity distribution, but every time window item popularity is randomly shuffled. Inherits AbstractTimedGenerator. | PoissonShuffleZipfGenerator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PoissonShuffleZipfGenerator:
"""PoissonShuffleZipfGenerator implements generator with poisson arrivals and Zipf popularity distribution, but every time window item popularity is randomly shuffled. Inherits AbstractTimedGenerator."""
def __init__(self, max_id: int=1000, poisson_lam: float=10,... | stack_v2_sparse_classes_10k_train_004087 | 8,929 | no_license | [
{
"docstring": "Construct a new PoissonShuffleZipfGenerator object. :param max_id: Maximum ID of the object. :param poisson_lam: Poisson distribution parameter. :param zipf_param: Zipf distribution parameter. :param id_shift: Shift of the starting item ID. :param shuffle_window: Time window after which populari... | 3 | stack_v2_sparse_classes_30k_train_000119 | Implement the Python class `PoissonShuffleZipfGenerator` described below.
Class description:
PoissonShuffleZipfGenerator implements generator with poisson arrivals and Zipf popularity distribution, but every time window item popularity is randomly shuffled. Inherits AbstractTimedGenerator.
Method signatures and docst... | Implement the Python class `PoissonShuffleZipfGenerator` described below.
Class description:
PoissonShuffleZipfGenerator implements generator with poisson arrivals and Zipf popularity distribution, but every time window item popularity is randomly shuffled. Inherits AbstractTimedGenerator.
Method signatures and docst... | eb3bd7d966f75827026e255caaced052ecec9236 | <|skeleton|>
class PoissonShuffleZipfGenerator:
"""PoissonShuffleZipfGenerator implements generator with poisson arrivals and Zipf popularity distribution, but every time window item popularity is randomly shuffled. Inherits AbstractTimedGenerator."""
def __init__(self, max_id: int=1000, poisson_lam: float=10,... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PoissonShuffleZipfGenerator:
"""PoissonShuffleZipfGenerator implements generator with poisson arrivals and Zipf popularity distribution, but every time window item popularity is randomly shuffled. Inherits AbstractTimedGenerator."""
def __init__(self, max_id: int=1000, poisson_lam: float=10, zipf_param: ... | the_stack_v2_python_sparse | src/data/generation/poisson_zipf_trace_generator.py | vladfedchenko/NeuralCaching | train | 1 |
58aa135f37a9b90f70fb2d90d898f2be8fc419fd | [
"self.count = k\nself.myhq = hq()\nfor i in range(len(nums)):\n self.myhq.push(nums[i])\nfor i in range(k, len(nums)):\n self.myhq.pop()",
"self.myhq.push(val)\nif len(self.myhq.heap) > self.count:\n self.myhq.pop()\nreturn self.myhq.heap[0]"
] | <|body_start_0|>
self.count = k
self.myhq = hq()
for i in range(len(nums)):
self.myhq.push(nums[i])
for i in range(k, len(nums)):
self.myhq.pop()
<|end_body_0|>
<|body_start_1|>
self.myhq.push(val)
if len(self.myhq.heap) > self.count:
... | 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.count = k
self.myhq = hq()
for i in r... | stack_v2_sparse_classes_10k_train_004088 | 1,895 | 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_003217 | 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... | a9ad5b5bc912a4ce5613000fbc47905510cde5ea | <|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_10k | data/stack_v2_sparse_classes_30k | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
self.count = k
self.myhq = hq()
for i in range(len(nums)):
self.myhq.push(nums[i])
for i in range(k, len(nums)):
self.myhq.pop()
def add(self, val):
""... | the_stack_v2_python_sparse | 2.11 KthLargest.py | ANh0r/LeetCode-Daily | train | 2 | |
07574c495be2a9acf06160ee7bd0cc81992cd2ae | [
"if len(nums) == 0:\n return 0\nmax_length = 0\ncur = 1\nfor i in range(len(nums) - 1):\n if nums[i] < nums[i + 1]:\n cur += 1\n else:\n max_length = cur if cur > max_length else max_length\n cur = 1\nreturn max_length if cur < max_length else cur",
"if len(nums) == 0:\n return 0\... | <|body_start_0|>
if len(nums) == 0:
return 0
max_length = 0
cur = 1
for i in range(len(nums) - 1):
if nums[i] < nums[i + 1]:
cur += 1
else:
max_length = cur if cur > max_length else max_length
cur = 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findLengthOfLCIS1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findLengthOfLCIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(nums) == 0:
ret... | stack_v2_sparse_classes_10k_train_004089 | 1,034 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findLengthOfLCIS1",
"signature": "def findLengthOfLCIS1(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findLengthOfLCIS",
"signature": "def findLengthOfLCIS(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLengthOfLCIS1(self, nums): :type nums: List[int] :rtype: int
- def findLengthOfLCIS(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLengthOfLCIS1(self, nums): :type nums: List[int] :rtype: int
- def findLengthOfLCIS(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def ... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def findLengthOfLCIS1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findLengthOfLCIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findLengthOfLCIS1(self, nums):
""":type nums: List[int] :rtype: int"""
if len(nums) == 0:
return 0
max_length = 0
cur = 1
for i in range(len(nums) - 1):
if nums[i] < nums[i + 1]:
cur += 1
else:
... | the_stack_v2_python_sparse | python/leetcode_bak/674_Longest_Continuous_Increasing_Subsequence.py | bobcaoge/my-code | train | 0 | |
65e2e0901eafab88627c231cb157938f52ea5472 | [
"category_id = None\nif 'category_id' in self.request.data:\n category_id = self.request.data['category_id']\ncategory_instance = get_object_or_404(Category, id=category_id)\nserializer.save(user=self.request.user, category=category_instance)",
"queryset = self.queryset.filter(user=self.request.user)\ncategory... | <|body_start_0|>
category_id = None
if 'category_id' in self.request.data:
category_id = self.request.data['category_id']
category_instance = get_object_or_404(Category, id=category_id)
serializer.save(user=self.request.user, category=category_instance)
<|end_body_0|>
<|body... | detail: pk -- category id e.g. api/study/hanzi_study_count/1" login required, so by default, filtering against the current user | HanziStudyCountViewSet | [
"Artistic-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HanziStudyCountViewSet:
"""detail: pk -- category id e.g. api/study/hanzi_study_count/1" login required, so by default, filtering against the current user"""
def perform_create(self, serializer):
"""required 'category_id' is part of POST body"""
<|body_0|>
def get_querys... | stack_v2_sparse_classes_10k_train_004090 | 10,903 | permissive | [
{
"docstring": "required 'category_id' is part of POST body",
"name": "perform_create",
"signature": "def perform_create(self, serializer)"
},
{
"docstring": "filter by user, and category if asked",
"name": "get_queryset",
"signature": "def get_queryset(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000720 | Implement the Python class `HanziStudyCountViewSet` described below.
Class description:
detail: pk -- category id e.g. api/study/hanzi_study_count/1" login required, so by default, filtering against the current user
Method signatures and docstrings:
- def perform_create(self, serializer): required 'category_id' is pa... | Implement the Python class `HanziStudyCountViewSet` described below.
Class description:
detail: pk -- category id e.g. api/study/hanzi_study_count/1" login required, so by default, filtering against the current user
Method signatures and docstrings:
- def perform_create(self, serializer): required 'category_id' is pa... | eff8dd71474e64ed6acb7a2eaaa90cff72daef1f | <|skeleton|>
class HanziStudyCountViewSet:
"""detail: pk -- category id e.g. api/study/hanzi_study_count/1" login required, so by default, filtering against the current user"""
def perform_create(self, serializer):
"""required 'category_id' is part of POST body"""
<|body_0|>
def get_querys... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HanziStudyCountViewSet:
"""detail: pk -- category id e.g. api/study/hanzi_study_count/1" login required, so by default, filtering against the current user"""
def perform_create(self, serializer):
"""required 'category_id' is part of POST body"""
category_id = None
if 'category_id'... | the_stack_v2_python_sparse | wsgi/hornbook/study/views.py | pz325/hornbook | train | 0 |
e8e82ed44fe0b6deecfdbed962d7491ff233da95 | [
"super().__init__(question, test_dict)\nself.preamble = compile(test_dict.get('preamble', ''), '%s.preamble' % self.path, 'exec')\nself.test = compile(test_dict['test'], '%s.test' % self.path, 'eval')\nself.success = test_dict['success']\nself.failure = test_dict['failure']",
"bindings = dict(module_dict)\nexec(s... | <|body_start_0|>
super().__init__(question, test_dict)
self.preamble = compile(test_dict.get('preamble', ''), '%s.preamble' % self.path, 'exec')
self.test = compile(test_dict['test'], '%s.test' % self.path, 'eval')
self.success = test_dict['success']
self.failure = test_dict['fai... | Simple test case which evals an arbitrary piece of python code. The test is correct if the output of the code given the student's solution matches that of the instructor's. | EvalTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EvalTest:
"""Simple test case which evals an arbitrary piece of python code. The test is correct if the output of the code given the student's solution matches that of the instructor's."""
def __init__(self, question, test_dict):
"""Create test from question and test dictionary."""
... | stack_v2_sparse_classes_10k_train_004091 | 6,372 | no_license | [
{
"docstring": "Create test from question and test dictionary.",
"name": "__init__",
"signature": "def __init__(self, question, test_dict)"
},
{
"docstring": "Evaluate the code.",
"name": "eval_code",
"signature": "def eval_code(self, module_dict)"
},
{
"docstring": "Run the test... | 4 | stack_v2_sparse_classes_30k_train_002201 | Implement the Python class `EvalTest` described below.
Class description:
Simple test case which evals an arbitrary piece of python code. The test is correct if the output of the code given the student's solution matches that of the instructor's.
Method signatures and docstrings:
- def __init__(self, question, test_d... | Implement the Python class `EvalTest` described below.
Class description:
Simple test case which evals an arbitrary piece of python code. The test is correct if the output of the code given the student's solution matches that of the instructor's.
Method signatures and docstrings:
- def __init__(self, question, test_d... | 9612a1ff8748d9d58cc929a937a6001e8f0a2494 | <|skeleton|>
class EvalTest:
"""Simple test case which evals an arbitrary piece of python code. The test is correct if the output of the code given the student's solution matches that of the instructor's."""
def __init__(self, question, test_dict):
"""Create test from question and test dictionary."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EvalTest:
"""Simple test case which evals an arbitrary piece of python code. The test is correct if the output of the code given the student's solution matches that of the instructor's."""
def __init__(self, question, test_dict):
"""Create test from question and test dictionary."""
super(... | the_stack_v2_python_sparse | Lab_2/test_classes.py | liamcannon/CSI-275 | train | 0 |
1659677e11407eea66c0f0703d0d9fefb94c8795 | [
"context = util.DotDict()\ncontext.elasticSearchHostname = ''\ncontext.elasticSearchPort = 9200\ncontext.platforms = ({'id': 'windows', 'name': 'Windows NT'}, {'id': 'linux', 'name': 'Linux'})\nreturn context",
"context = self.get_dummy_context()\nfacets = {'signatures': {'terms': [{'term': 'hang', 'count': 145},... | <|body_start_0|>
context = util.DotDict()
context.elasticSearchHostname = ''
context.elasticSearchPort = 9200
context.platforms = ({'id': 'windows', 'name': 'Windows NT'}, {'id': 'linux', 'name': 'Linux'})
return context
<|end_body_0|>
<|body_start_1|>
context = self.get... | Test Search class implemented with ElasticSearch. | TestElasticSearchSearch | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestElasticSearchSearch:
"""Test Search class implemented with ElasticSearch."""
def get_dummy_context(self):
"""Create a dummy config object to use when testing."""
<|body_0|>
def test_get_signatures_list(self):
"""Test Search.get_signatures()"""
<|body_... | stack_v2_sparse_classes_10k_train_004092 | 20,362 | no_license | [
{
"docstring": "Create a dummy config object to use when testing.",
"name": "get_dummy_context",
"signature": "def get_dummy_context(self)"
},
{
"docstring": "Test Search.get_signatures()",
"name": "test_get_signatures_list",
"signature": "def test_get_signatures_list(self)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_004747 | Implement the Python class `TestElasticSearchSearch` described below.
Class description:
Test Search class implemented with ElasticSearch.
Method signatures and docstrings:
- def get_dummy_context(self): Create a dummy config object to use when testing.
- def test_get_signatures_list(self): Test Search.get_signatures... | Implement the Python class `TestElasticSearchSearch` described below.
Class description:
Test Search class implemented with ElasticSearch.
Method signatures and docstrings:
- def get_dummy_context(self): Create a dummy config object to use when testing.
- def test_get_signatures_list(self): Test Search.get_signatures... | 9c9b7701d7ddf9f3cbba1a4d0aa65758e8b49528 | <|skeleton|>
class TestElasticSearchSearch:
"""Test Search class implemented with ElasticSearch."""
def get_dummy_context(self):
"""Create a dummy config object to use when testing."""
<|body_0|>
def test_get_signatures_list(self):
"""Test Search.get_signatures()"""
<|body_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestElasticSearchSearch:
"""Test Search class implemented with ElasticSearch."""
def get_dummy_context(self):
"""Create a dummy config object to use when testing."""
context = util.DotDict()
context.elasticSearchHostname = ''
context.elasticSearchPort = 9200
contex... | the_stack_v2_python_sparse | socorro/unittest/external/elasticsearch/test_search.py | v1ka5/socorro | train | 0 |
34001651f4c638af91830bc6d4e6c92a7c4e1fe6 | [
"self.lists = [v1, v2]\nself.num_lists = 2\nself.cur_row = None\nself.cur_col = None",
"if self.cur_row is None:\n for row in range(self.num_lists):\n if self.lists[row]:\n self.cur_row = row\n self.cur_col = 0\n break\n return self.lists[self.cur_row][0]\nfor row in ... | <|body_start_0|>
self.lists = [v1, v2]
self.num_lists = 2
self.cur_row = None
self.cur_col = None
<|end_body_0|>
<|body_start_1|>
if self.cur_row is None:
for row in range(self.num_lists):
if self.lists[row]:
self.cur_row = row
... | ZigzagIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end... | stack_v2_sparse_classes_10k_train_004093 | 1,967 | no_license | [
{
"docstring": "Initialize your data structure here. :type v1: List[int] :type v2: List[int]",
"name": "__init__",
"signature": "def __init__(self, v1, v2)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"name"... | 3 | stack_v2_sparse_classes_30k_train_005014 | Implement the Python class `ZigzagIterator` described below.
Class description:
Implement the ZigzagIterator class.
Method signatures and docstrings:
- def __init__(self, v1, v2): Initialize your data structure here. :type v1: List[int] :type v2: List[int]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bo... | Implement the Python class `ZigzagIterator` described below.
Class description:
Implement the ZigzagIterator class.
Method signatures and docstrings:
- def __init__(self, v1, v2): Initialize your data structure here. :type v1: List[int] :type v2: List[int]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bo... | 16468a4397430b24b685cab02570ff3f5849e86f | <|skeleton|>
class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
self.lists = [v1, v2]
self.num_lists = 2
self.cur_row = None
self.cur_col = None
def next(self):
""":rtype: int"""
if self... | the_stack_v2_python_sparse | zig-zag-iterator/s1.py | fingerroll/wip | train | 0 | |
25bef5ffaa3f22181dd0a148508b3d2c329959c8 | [
"char_indexes = collections.defaultdict(list)\nfor idx, char in enumerate(S):\n char_indexes[char].append(idx)\nans = 0\nN = len(S)\nfor word in words:\n flag = 1\n idx_prev = -1\n for char in word:\n i = bisect.bisect_right(char_indexes[char], idx_prev)\n if i == len(char_indexes[char]):\... | <|body_start_0|>
char_indexes = collections.defaultdict(list)
for idx, char in enumerate(S):
char_indexes[char].append(idx)
ans = 0
N = len(S)
for word in words:
flag = 1
idx_prev = -1
for char in word:
i = bisect.bi... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numMatchingSubseq(self, S: str, words: List[str]) -> int:
"""1. store the indexes of all chars in ascending order 2. given a query word "...xy...", the index that y appears in S should be larger than the index appears in S 3. scan the word char by char, and for the current ... | stack_v2_sparse_classes_10k_train_004094 | 2,382 | no_license | [
{
"docstring": "1. store the indexes of all chars in ascending order 2. given a query word \"...xy...\", the index that y appears in S should be larger than the index appears in S 3. scan the word char by char, and for the current char x record the smallest index it appears in S called i_x, for the next char y,... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numMatchingSubseq(self, S: str, words: List[str]) -> int: 1. store the indexes of all chars in ascending order 2. given a query word "...xy...", the index that y appears in S... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numMatchingSubseq(self, S: str, words: List[str]) -> int: 1. store the indexes of all chars in ascending order 2. given a query word "...xy...", the index that y appears in S... | 6ff1941ff213a843013100ac7033e2d4f90fbd6a | <|skeleton|>
class Solution:
def numMatchingSubseq(self, S: str, words: List[str]) -> int:
"""1. store the indexes of all chars in ascending order 2. given a query word "...xy...", the index that y appears in S should be larger than the index appears in S 3. scan the word char by char, and for the current ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def numMatchingSubseq(self, S: str, words: List[str]) -> int:
"""1. store the indexes of all chars in ascending order 2. given a query word "...xy...", the index that y appears in S should be larger than the index appears in S 3. scan the word char by char, and for the current char x record ... | the_stack_v2_python_sparse | Leetcode 0792. Number of Matching Subsequences.py | Chaoran-sjsu/leetcode | train | 0 | |
e92308341c7fdc1374457ec4b6a619072cdcf45d | [
"self.log = log\nif e is not None or operation is not None:\n self.handle_exception(e, operation)\nreturn",
"result = {'error': None}\nexc_type, exc_obj, exc_tb = exc_info()\nfname = path_split(exc_tb.tb_frame.f_code.co_filename)[frame]\nresult['error'] = '%s, %s, %s' % (str(exc_type), str(fname), str(exc_tb.t... | <|body_start_0|>
self.log = log
if e is not None or operation is not None:
self.handle_exception(e, operation)
return
<|end_body_0|>
<|body_start_1|>
result = {'error': None}
exc_type, exc_obj, exc_tb = exc_info()
fname = path_split(exc_tb.tb_frame.f_code.co_... | Object for exception handling. | ExceptionHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExceptionHandler:
"""Object for exception handling."""
def __init__(self, log, e=None, operation=None):
"""Initialize the exception handler object. @param log: an initialized logger object. @param e: the exception (from BaseException, e). @param operation: the action being attempted ... | stack_v2_sparse_classes_10k_train_004095 | 3,299 | no_license | [
{
"docstring": "Initialize the exception handler object. @param log: an initialized logger object. @param e: the exception (from BaseException, e). @param operation: the action being attempted (that failed). @return: None.",
"name": "__init__",
"signature": "def __init__(self, log, e=None, operation=Non... | 3 | stack_v2_sparse_classes_30k_train_000855 | Implement the Python class `ExceptionHandler` described below.
Class description:
Object for exception handling.
Method signatures and docstrings:
- def __init__(self, log, e=None, operation=None): Initialize the exception handler object. @param log: an initialized logger object. @param e: the exception (from BaseExc... | Implement the Python class `ExceptionHandler` described below.
Class description:
Object for exception handling.
Method signatures and docstrings:
- def __init__(self, log, e=None, operation=None): Initialize the exception handler object. @param log: an initialized logger object. @param e: the exception (from BaseExc... | cc14053da99f6671b12e03ef5dc1717c3d9e4aa5 | <|skeleton|>
class ExceptionHandler:
"""Object for exception handling."""
def __init__(self, log, e=None, operation=None):
"""Initialize the exception handler object. @param log: an initialized logger object. @param e: the exception (from BaseException, e). @param operation: the action being attempted ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ExceptionHandler:
"""Object for exception handling."""
def __init__(self, log, e=None, operation=None):
"""Initialize the exception handler object. @param log: an initialized logger object. @param e: the exception (from BaseException, e). @param operation: the action being attempted (that failed)... | the_stack_v2_python_sparse | exceptionhandler.py | jslatte/tartaros | train | 1 |
3a44b3761413c880fe481fb0de764ba1ff5b3464 | [
"user = serializer.context.get('request').user\nusername = getattr(user, 'username', 'guest')\nserializer.save(creator=username, updated_by=username)\nservice_type = serializer.data.get('service_type')\nTicketStatusConfig.update_config(service_type, user)",
"user = serializer.context.get('request').user\nusername... | <|body_start_0|>
user = serializer.context.get('request').user
username = getattr(user, 'username', 'guest')
serializer.save(creator=username, updated_by=username)
service_type = serializer.data.get('service_type')
TicketStatusConfig.update_config(service_type, user)
<|end_body_0... | 按需改造DRF默认的ModelViewSet类 | ModelViewSet | [
"MIT",
"LGPL-2.1-or-later",
"LGPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelViewSet:
"""按需改造DRF默认的ModelViewSet类"""
def perform_create(self, serializer):
"""创建时补充基础Model中的字段"""
<|body_0|>
def perform_update(self, serializer):
"""更新时补充基础Model中的字段"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
user = serializer.conte... | stack_v2_sparse_classes_10k_train_004096 | 11,791 | permissive | [
{
"docstring": "创建时补充基础Model中的字段",
"name": "perform_create",
"signature": "def perform_create(self, serializer)"
},
{
"docstring": "更新时补充基础Model中的字段",
"name": "perform_update",
"signature": "def perform_update(self, serializer)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000354 | Implement the Python class `ModelViewSet` described below.
Class description:
按需改造DRF默认的ModelViewSet类
Method signatures and docstrings:
- def perform_create(self, serializer): 创建时补充基础Model中的字段
- def perform_update(self, serializer): 更新时补充基础Model中的字段 | Implement the Python class `ModelViewSet` described below.
Class description:
按需改造DRF默认的ModelViewSet类
Method signatures and docstrings:
- def perform_create(self, serializer): 创建时补充基础Model中的字段
- def perform_update(self, serializer): 更新时补充基础Model中的字段
<|skeleton|>
class ModelViewSet:
"""按需改造DRF默认的ModelViewSet类"""
... | 2d708bd0d869d391456e0fb8d644af3b9f031acf | <|skeleton|>
class ModelViewSet:
"""按需改造DRF默认的ModelViewSet类"""
def perform_create(self, serializer):
"""创建时补充基础Model中的字段"""
<|body_0|>
def perform_update(self, serializer):
"""更新时补充基础Model中的字段"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ModelViewSet:
"""按需改造DRF默认的ModelViewSet类"""
def perform_create(self, serializer):
"""创建时补充基础Model中的字段"""
user = serializer.context.get('request').user
username = getattr(user, 'username', 'guest')
serializer.save(creator=username, updated_by=username)
service_type ... | the_stack_v2_python_sparse | itsm/ticket_status/views.py | TencentBlueKing/bk-itsm | train | 100 |
de1b565ab92f8b99e1e726f62cb4d87d2a621710 | [
"storage = get_storage()\nroles = storage.list_roles()\nreturn jsonify(RoleSchema(many=True).dump(roles))",
"data = request.get_json()\ntry:\n role = RolePostSchema().load(data)\nexcept ValidationError as err:\n raise BadAPIRequest(err.messages)\nstorage = get_storage()\nrole_id = storage.store_role(role)\n... | <|body_start_0|>
storage = get_storage()
roles = storage.list_roles()
return jsonify(RoleSchema(many=True).dump(roles))
<|end_body_0|>
<|body_start_1|>
data = request.get_json()
try:
role = RolePostSchema().load(data)
except ValidationError as err:
... | AllRolesView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AllRolesView:
def get(self):
"""--- summary: List Roles. description: List all Roles that the user has access to. tags: - Roles responses: 200: description: Retrieved roles successfully. content: applicaiton/json: schema: type: array items: $ref: '#/components/schemas/RoleSchema' 401: $r... | stack_v2_sparse_classes_10k_train_004097 | 5,492 | permissive | [
{
"docstring": "--- summary: List Roles. description: List all Roles that the user has access to. tags: - Roles responses: 200: description: Retrieved roles successfully. content: applicaiton/json: schema: type: array items: $ref: '#/components/schemas/RoleSchema' 401: $ref: '#/components/responses/401-Unauthor... | 2 | stack_v2_sparse_classes_30k_train_003712 | Implement the Python class `AllRolesView` described below.
Class description:
Implement the AllRolesView class.
Method signatures and docstrings:
- def get(self): --- summary: List Roles. description: List all Roles that the user has access to. tags: - Roles responses: 200: description: Retrieved roles successfully. ... | Implement the Python class `AllRolesView` described below.
Class description:
Implement the AllRolesView class.
Method signatures and docstrings:
- def get(self): --- summary: List Roles. description: List all Roles that the user has access to. tags: - Roles responses: 200: description: Retrieved roles successfully. ... | 280800c73eb7cfd49029462b352887e78f1ff91b | <|skeleton|>
class AllRolesView:
def get(self):
"""--- summary: List Roles. description: List all Roles that the user has access to. tags: - Roles responses: 200: description: Retrieved roles successfully. content: applicaiton/json: schema: type: array items: $ref: '#/components/schemas/RoleSchema' 401: $r... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AllRolesView:
def get(self):
"""--- summary: List Roles. description: List all Roles that the user has access to. tags: - Roles responses: 200: description: Retrieved roles successfully. content: applicaiton/json: schema: type: array items: $ref: '#/components/schemas/RoleSchema' 401: $ref: '#/compone... | the_stack_v2_python_sparse | sfa_api/roles.py | SolarArbiter/solarforecastarbiter-api | train | 9 | |
5adf9955f31264db3543ee2bfb31382d184bbb69 | [
"try:\n ilp.solve(pulp.GLPK())\n assert round(pulp.value(ilp.objective), 0) == 5\nexcept pulp.solvers.PulpSolverError:\n pytest.fail(f'Solver not installed')",
"try:\n ilp.solve(pulp.COIN())\n assert round(pulp.value(ilp.objective), 0) == 5\nexcept pulp.solvers.PulpSolverError:\n pytest.fail(f'S... | <|body_start_0|>
try:
ilp.solve(pulp.GLPK())
assert round(pulp.value(ilp.objective), 0) == 5
except pulp.solvers.PulpSolverError:
pytest.fail(f'Solver not installed')
<|end_body_0|>
<|body_start_1|>
try:
ilp.solve(pulp.COIN())
assert r... | Test Installed Solvers. | TestSolver | [
"LicenseRef-scancode-proprietary-license",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSolver:
"""Test Installed Solvers."""
def test_glpk(self, ilp):
"""Test method for GLPK."""
<|body_0|>
def test_cbc(self, ilp):
"""Test method for CBC."""
<|body_1|>
def test_cplex(self, ilp):
"""Test method for CPLEX."""
<|body_2... | stack_v2_sparse_classes_10k_train_004098 | 1,770 | permissive | [
{
"docstring": "Test method for GLPK.",
"name": "test_glpk",
"signature": "def test_glpk(self, ilp)"
},
{
"docstring": "Test method for CBC.",
"name": "test_cbc",
"signature": "def test_cbc(self, ilp)"
},
{
"docstring": "Test method for CPLEX.",
"name": "test_cplex",
"sig... | 5 | stack_v2_sparse_classes_30k_train_002738 | Implement the Python class `TestSolver` described below.
Class description:
Test Installed Solvers.
Method signatures and docstrings:
- def test_glpk(self, ilp): Test method for GLPK.
- def test_cbc(self, ilp): Test method for CBC.
- def test_cplex(self, ilp): Test method for CPLEX.
- def test_gurobi(self, ilp): Test... | Implement the Python class `TestSolver` described below.
Class description:
Test Installed Solvers.
Method signatures and docstrings:
- def test_glpk(self, ilp): Test method for GLPK.
- def test_cbc(self, ilp): Test method for CBC.
- def test_cplex(self, ilp): Test method for CPLEX.
- def test_gurobi(self, ilp): Test... | 12f696633743825b34556180eed171649a26f05d | <|skeleton|>
class TestSolver:
"""Test Installed Solvers."""
def test_glpk(self, ilp):
"""Test method for GLPK."""
<|body_0|>
def test_cbc(self, ilp):
"""Test method for CBC."""
<|body_1|>
def test_cplex(self, ilp):
"""Test method for CPLEX."""
<|body_2... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestSolver:
"""Test Installed Solvers."""
def test_glpk(self, ilp):
"""Test method for GLPK."""
try:
ilp.solve(pulp.GLPK())
assert round(pulp.value(ilp.objective), 0) == 5
except pulp.solvers.PulpSolverError:
pytest.fail(f'Solver not installed')... | the_stack_v2_python_sparse | check_installed_solvers.py | atomassi/mapping_distrinet | train | 2 |
0d62d5e599c354881dec58608c9f0396c62d545f | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Proto file describing the Ad Group Ad service. Service to manage ads in an ad group. | AdGroupAdServiceServicer | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdGroupAdServiceServicer:
"""Proto file describing the Ad Group Ad service. Service to manage ads in an ad group."""
def GetAdGroupAd(self, request, context):
"""Returns the requested ad in full detail."""
<|body_0|>
def MutateAdGroupAds(self, request, context):
... | stack_v2_sparse_classes_10k_train_004099 | 3,304 | permissive | [
{
"docstring": "Returns the requested ad in full detail.",
"name": "GetAdGroupAd",
"signature": "def GetAdGroupAd(self, request, context)"
},
{
"docstring": "Creates, updates, or removes ads. Operation statuses are returned.",
"name": "MutateAdGroupAds",
"signature": "def MutateAdGroupAd... | 2 | stack_v2_sparse_classes_30k_train_002059 | Implement the Python class `AdGroupAdServiceServicer` described below.
Class description:
Proto file describing the Ad Group Ad service. Service to manage ads in an ad group.
Method signatures and docstrings:
- def GetAdGroupAd(self, request, context): Returns the requested ad in full detail.
- def MutateAdGroupAds(s... | Implement the Python class `AdGroupAdServiceServicer` described below.
Class description:
Proto file describing the Ad Group Ad service. Service to manage ads in an ad group.
Method signatures and docstrings:
- def GetAdGroupAd(self, request, context): Returns the requested ad in full detail.
- def MutateAdGroupAds(s... | 0fc8a7dbf31d9e8e2a4364df93bec5f6b7edd50a | <|skeleton|>
class AdGroupAdServiceServicer:
"""Proto file describing the Ad Group Ad service. Service to manage ads in an ad group."""
def GetAdGroupAd(self, request, context):
"""Returns the requested ad in full detail."""
<|body_0|>
def MutateAdGroupAds(self, request, context):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AdGroupAdServiceServicer:
"""Proto file describing the Ad Group Ad service. Service to manage ads in an ad group."""
def GetAdGroupAd(self, request, context):
"""Returns the requested ad in full detail."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method... | the_stack_v2_python_sparse | google/ads/google_ads/v1/proto/services/ad_group_ad_service_pb2_grpc.py | juanmacugat/google-ads-python | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.