blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
27ad75972013aecfc59bf9b056d3c372928bac0f | [
"connected = False\ntry:\n logging.info('Connecting to redis')\n self.dataUtil = DataUtil.DataUtil()\n self.redisActuator = redis.Redis(host='localhost', port=6379, db=0)\n self.redisActuator.ping()\n self.redisSensor = redis.Redis(host='localhost', port=6379, db=1)\n self.redisSensor.ping()\n ... | <|body_start_0|>
connected = False
try:
logging.info('Connecting to redis')
self.dataUtil = DataUtil.DataUtil()
self.redisActuator = redis.Redis(host='localhost', port=6379, db=0)
self.redisActuator.ping()
self.redisSensor = redis.Redis(host='l... | Class to read write data to redis and to register threads which listen on redis | PersistenceUtil | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PersistenceUtil:
"""Class to read write data to redis and to register threads which listen on redis"""
def __init__(self):
"""Constructor"""
<|body_0|>
def registerActuatorDataDbmsListener(self) -> bool:
"""Register ActuatorListener to redis"""
<|body_1|>... | stack_v2_sparse_classes_36k_train_026800 | 3,369 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Register ActuatorListener to redis",
"name": "registerActuatorDataDbmsListener",
"signature": "def registerActuatorDataDbmsListener(self) -> bool"
},
{
"docstring": "Register Se... | 5 | null | Implement the Python class `PersistenceUtil` described below.
Class description:
Class to read write data to redis and to register threads which listen on redis
Method signatures and docstrings:
- def __init__(self): Constructor
- def registerActuatorDataDbmsListener(self) -> bool: Register ActuatorListener to redis
... | Implement the Python class `PersistenceUtil` described below.
Class description:
Class to read write data to redis and to register threads which listen on redis
Method signatures and docstrings:
- def __init__(self): Constructor
- def registerActuatorDataDbmsListener(self) -> bool: Register ActuatorListener to redis
... | dfd5fd8c757cae8b1306ae3e4eb2cfc9bf124fee | <|skeleton|>
class PersistenceUtil:
"""Class to read write data to redis and to register threads which listen on redis"""
def __init__(self):
"""Constructor"""
<|body_0|>
def registerActuatorDataDbmsListener(self) -> bool:
"""Register ActuatorListener to redis"""
<|body_1|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PersistenceUtil:
"""Class to read write data to redis and to register threads which listen on redis"""
def __init__(self):
"""Constructor"""
connected = False
try:
logging.info('Connecting to redis')
self.dataUtil = DataUtil.DataUtil()
self.redi... | the_stack_v2_python_sparse | apps/labs/common/PersistenceUtil.py | mnk400/iot-device | train | 0 |
88419b381e84e266ed7b834b99a16df2852fe6fd | [
"if not out:\n return\nprint('[{}]: {}'.format(tag, message))",
"if not debug:\n return\nprint('[{}]: {}'.format(tag, message))"
] | <|body_start_0|>
if not out:
return
print('[{}]: {}'.format(tag, message))
<|end_body_0|>
<|body_start_1|>
if not debug:
return
print('[{}]: {}'.format(tag, message))
<|end_body_1|>
| GeneralLogger | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeneralLogger:
def o(cls, message, tag=None):
"""out message with tag of specified if config 'out' = true, else do nothing"""
<|body_0|>
def d(cls, message, tag=None):
"""out message with tag of specified if config 'debug' = true, else do nothing"""
<|body_1|... | stack_v2_sparse_classes_36k_train_026801 | 2,014 | no_license | [
{
"docstring": "out message with tag of specified if config 'out' = true, else do nothing",
"name": "o",
"signature": "def o(cls, message, tag=None)"
},
{
"docstring": "out message with tag of specified if config 'debug' = true, else do nothing",
"name": "d",
"signature": "def d(cls, mes... | 2 | stack_v2_sparse_classes_30k_train_000761 | Implement the Python class `GeneralLogger` described below.
Class description:
Implement the GeneralLogger class.
Method signatures and docstrings:
- def o(cls, message, tag=None): out message with tag of specified if config 'out' = true, else do nothing
- def d(cls, message, tag=None): out message with tag of specif... | Implement the Python class `GeneralLogger` described below.
Class description:
Implement the GeneralLogger class.
Method signatures and docstrings:
- def o(cls, message, tag=None): out message with tag of specified if config 'out' = true, else do nothing
- def d(cls, message, tag=None): out message with tag of specif... | 13d5ef9100bbc09f1b6d4b57b868833449ea9699 | <|skeleton|>
class GeneralLogger:
def o(cls, message, tag=None):
"""out message with tag of specified if config 'out' = true, else do nothing"""
<|body_0|>
def d(cls, message, tag=None):
"""out message with tag of specified if config 'debug' = true, else do nothing"""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GeneralLogger:
def o(cls, message, tag=None):
"""out message with tag of specified if config 'out' = true, else do nothing"""
if not out:
return
print('[{}]: {}'.format(tag, message))
def d(cls, message, tag=None):
"""out message with tag of specified if config... | the_stack_v2_python_sparse | AppLogger.py | omarsgalal/PlayWithYourHand | train | 4 | |
09c863b1154f1928e4d9a19469bffe5f7456c77e | [
"frames = {}\nself._animation = []\nself._max_frame_count = 0\nself._first_tick = -1\nself._pos = pos\nfor frame_key in frame_list:\n frame = frame_list[frame_key]\n picture = picture_manager.get_picture(frame['picture'])\n rect = pygame.Rect(float(frame['left']), float(frame['top']), float(frame['right'])... | <|body_start_0|>
frames = {}
self._animation = []
self._max_frame_count = 0
self._first_tick = -1
self._pos = pos
for frame_key in frame_list:
frame = frame_list[frame_key]
picture = picture_manager.get_picture(frame['picture'])
rect = ... | The animation class. An object of this class represents an animation. Attributes: _animation: The list of frames and its duration of this animation. _max_frame_count: The overall duration of this animation. _first_tick: The first game tick after the animation was started. _pos: The position of the animation. | Animation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Animation:
"""The animation class. An object of this class represents an animation. Attributes: _animation: The list of frames and its duration of this animation. _max_frame_count: The overall duration of this animation. _first_tick: The first game tick after the animation was started. _pos: The ... | stack_v2_sparse_classes_36k_train_026802 | 2,082 | no_license | [
{
"docstring": "Generates a new instance of this class. Generates a new instance of this class and sets the field information. Args: picture_manager: The picture manager to use. frame_list: The list of frames. animation: The animation dictionary. pos: The position of this animation.",
"name": "__init__",
... | 2 | stack_v2_sparse_classes_30k_train_019233 | Implement the Python class `Animation` described below.
Class description:
The animation class. An object of this class represents an animation. Attributes: _animation: The list of frames and its duration of this animation. _max_frame_count: The overall duration of this animation. _first_tick: The first game tick afte... | Implement the Python class `Animation` described below.
Class description:
The animation class. An object of this class represents an animation. Attributes: _animation: The list of frames and its duration of this animation. _max_frame_count: The overall duration of this animation. _first_tick: The first game tick afte... | 0308785a51bf61d9a4fec2d8370540df502b8178 | <|skeleton|>
class Animation:
"""The animation class. An object of this class represents an animation. Attributes: _animation: The list of frames and its duration of this animation. _max_frame_count: The overall duration of this animation. _first_tick: The first game tick after the animation was started. _pos: The ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Animation:
"""The animation class. An object of this class represents an animation. Attributes: _animation: The list of frames and its duration of this animation. _max_frame_count: The overall duration of this animation. _first_tick: The first game tick after the animation was started. _pos: The position of t... | the_stack_v2_python_sparse | graphics/drawables/animation.py | donhilion/JumpAndRun | train | 0 |
128778697b225808e6e5d76a992d8cbcdcbffb0e | [
"self.kernel = None\nself.batch_size = -1\nself.conv_size = conv_size\nself.c = None\nself.h = None\nself._x = None\nif conv_size == 1:\n self.kernel = QRNNLinear(in_size, size)\nelif conv_size == 2:\n self.kernel = QRNNWithPrevious(in_size, size)\nelse:\n self.kernel = QRNNConvolution(in_size, size, conv_... | <|body_start_0|>
self.kernel = None
self.batch_size = -1
self.conv_size = conv_size
self.c = None
self.h = None
self._x = None
if conv_size == 1:
self.kernel = QRNNLinear(in_size, size)
elif conv_size == 2:
self.kernel = QRNNWithPre... | Quasi-Recurrent Neural Networks. See details in https://arxiv.org/abs/1611.01576. | QRNN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QRNN:
"""Quasi-Recurrent Neural Networks. See details in https://arxiv.org/abs/1611.01576."""
def __init__(self, in_size, size, conv_size=2):
"""Args: in_size: size: conv_size:"""
<|body_0|>
def _step(self, f, z, o):
"""Args: f: z: o: Returns: h:"""
<|bod... | stack_v2_sparse_classes_36k_train_026803 | 5,719 | permissive | [
{
"docstring": "Args: in_size: size: conv_size:",
"name": "__init__",
"signature": "def __init__(self, in_size, size, conv_size=2)"
},
{
"docstring": "Args: f: z: o: Returns: h:",
"name": "_step",
"signature": "def _step(self, f, z, o)"
},
{
"docstring": "Args: x: Returns: h:",
... | 3 | stack_v2_sparse_classes_30k_train_010684 | Implement the Python class `QRNN` described below.
Class description:
Quasi-Recurrent Neural Networks. See details in https://arxiv.org/abs/1611.01576.
Method signatures and docstrings:
- def __init__(self, in_size, size, conv_size=2): Args: in_size: size: conv_size:
- def _step(self, f, z, o): Args: f: z: o: Returns... | Implement the Python class `QRNN` described below.
Class description:
Quasi-Recurrent Neural Networks. See details in https://arxiv.org/abs/1611.01576.
Method signatures and docstrings:
- def __init__(self, in_size, size, conv_size=2): Args: in_size: size: conv_size:
- def _step(self, f, z, o): Args: f: z: o: Returns... | 61e4a65fb5c9f3d9f690d713dcd77a48b1de0a14 | <|skeleton|>
class QRNN:
"""Quasi-Recurrent Neural Networks. See details in https://arxiv.org/abs/1611.01576."""
def __init__(self, in_size, size, conv_size=2):
"""Args: in_size: size: conv_size:"""
<|body_0|>
def _step(self, f, z, o):
"""Args: f: z: o: Returns: h:"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QRNN:
"""Quasi-Recurrent Neural Networks. See details in https://arxiv.org/abs/1611.01576."""
def __init__(self, in_size, size, conv_size=2):
"""Args: in_size: size: conv_size:"""
self.kernel = None
self.batch_size = -1
self.conv_size = conv_size
self.c = None
... | the_stack_v2_python_sparse | models/recurrent/layers/qrnn.py | sundogrd/tensorflow_end2end_speech_recognition | train | 0 |
8e133a51bb04a38a218e6eca754a2c064fb5ffcf | [
"if not super().has_permission(request, view):\n return False\nif is_user_mo_admin_or_owner(request.user):\n return True\nreturn False",
"if isinstance(obj, MemberOrganisation):\n return [obj]\nelif isinstance(obj, User):\n return list(obj.member_organisations_memberorganisation.all())\nelse:\n rai... | <|body_start_0|>
if not super().has_permission(request, view):
return False
if is_user_mo_admin_or_owner(request.user):
return True
return False
<|end_body_0|>
<|body_start_1|>
if isinstance(obj, MemberOrganisation):
return [obj]
elif isinstan... | IsMOAdminOrOwner | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IsMOAdminOrOwner:
def has_permission(self, request, view):
"""If user is admin or an owner of any member organisation"""
<|body_0|>
def get_member_organisations(self, obj):
"""source objects can have various types (MemberOrganisation, User, etc), here member organisa... | stack_v2_sparse_classes_36k_train_026804 | 5,275 | no_license | [
{
"docstring": "If user is admin or an owner of any member organisation",
"name": "has_permission",
"signature": "def has_permission(self, request, view)"
},
{
"docstring": "source objects can have various types (MemberOrganisation, User, etc), here member organisations is retrieved from a sourc... | 3 | null | Implement the Python class `IsMOAdminOrOwner` described below.
Class description:
Implement the IsMOAdminOrOwner class.
Method signatures and docstrings:
- def has_permission(self, request, view): If user is admin or an owner of any member organisation
- def get_member_organisations(self, obj): source objects can hav... | Implement the Python class `IsMOAdminOrOwner` described below.
Class description:
Implement the IsMOAdminOrOwner class.
Method signatures and docstrings:
- def has_permission(self, request, view): If user is admin or an owner of any member organisation
- def get_member_organisations(self, obj): source objects can hav... | 338fd6396dbdce971bc542718fbb9608bdcfc2a7 | <|skeleton|>
class IsMOAdminOrOwner:
def has_permission(self, request, view):
"""If user is admin or an owner of any member organisation"""
<|body_0|>
def get_member_organisations(self, obj):
"""source objects can have various types (MemberOrganisation, User, etc), here member organisa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IsMOAdminOrOwner:
def has_permission(self, request, view):
"""If user is admin or an owner of any member organisation"""
if not super().has_permission(request, view):
return False
if is_user_mo_admin_or_owner(request.user):
return True
return False
... | the_stack_v2_python_sparse | api/permissions.py | sai9912/mypyton | train | 0 | |
f9e7fead436b149db2096f71f4c710d2a1a0881a | [
"self.strings = []\nfor x in range(0, len(document) - 1):\n if x + k < len(document):\n self.strings.append(document[x:x + k])\n else:\n self.strings.append(document[x:len(document)])\ncomp = lambda x, y: 0 if len(x) == len(y) else -1 if len(x) > len(y) else 1\nself.strings = mysort(self.strings... | <|body_start_0|>
self.strings = []
for x in range(0, len(document) - 1):
if x + k < len(document):
self.strings.append(document[x:x + k])
else:
self.strings.append(document[x:len(document)])
comp = lambda x, y: 0 if len(x) == len(y) else -1... | PrefixSearcher | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrefixSearcher:
def __init__(self, document, k):
"""Initializes a prefix searcher using a document and a maximum search string length k."""
<|body_0|>
def search(self, q):
"""Return true if the document contains search string q (of length up to n). If q is longer tha... | stack_v2_sparse_classes_36k_train_026805 | 8,672 | no_license | [
{
"docstring": "Initializes a prefix searcher using a document and a maximum search string length k.",
"name": "__init__",
"signature": "def __init__(self, document, k)"
},
{
"docstring": "Return true if the document contains search string q (of length up to n). If q is longer than n, then raise... | 2 | stack_v2_sparse_classes_30k_train_017616 | Implement the Python class `PrefixSearcher` described below.
Class description:
Implement the PrefixSearcher class.
Method signatures and docstrings:
- def __init__(self, document, k): Initializes a prefix searcher using a document and a maximum search string length k.
- def search(self, q): Return true if the docume... | Implement the Python class `PrefixSearcher` described below.
Class description:
Implement the PrefixSearcher class.
Method signatures and docstrings:
- def __init__(self, document, k): Initializes a prefix searcher using a document and a maximum search string length k.
- def search(self, q): Return true if the docume... | b4edf759b2916ab44f08741a6f19b103a9070203 | <|skeleton|>
class PrefixSearcher:
def __init__(self, document, k):
"""Initializes a prefix searcher using a document and a maximum search string length k."""
<|body_0|>
def search(self, q):
"""Return true if the document contains search string q (of length up to n). If q is longer tha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrefixSearcher:
def __init__(self, document, k):
"""Initializes a prefix searcher using a document and a maximum search string length k."""
self.strings = []
for x in range(0, len(document) - 1):
if x + k < len(document):
self.strings.append(document[x:x + k... | the_stack_v2_python_sparse | lab03/lab03.py | saronson/cs331-s21-jmallett2 | train | 2 | |
4464771e57a25ab137cc5d8f9cb8f55e677d326e | [
"sql = \"\\n SELECT id from tms_functional_block\\n WHERE active = 't'\\n AND id != %s\\n AND LOWER(name) = '%s'\\n \" % (self.id, self.name.lower())\ncr = self._cr\ncr.execute(sql)\nres_ids = [x[0] for x in cr.fetchall()]\nif res_ids:\n list_project_name = []\n functional_b... | <|body_start_0|>
sql = "\n SELECT id from tms_functional_block\n WHERE active = 't'\n AND id != %s\n AND LOWER(name) = '%s'\n " % (self.id, self.name.lower())
cr = self._cr
cr.execute(sql)
res_ids = [x[0] for x in cr.fetchall()]
if res_ids:
... | tms_functional_block | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class tms_functional_block:
def check_unique_name_project(self):
"""Check Functional Block name should be unique"""
<|body_0|>
def check_tpm_access(self):
"""Admin user: full access on functional block TPM user: full access on functional block of his project"""
<|b... | stack_v2_sparse_classes_36k_train_026806 | 3,262 | no_license | [
{
"docstring": "Check Functional Block name should be unique",
"name": "check_unique_name_project",
"signature": "def check_unique_name_project(self)"
},
{
"docstring": "Admin user: full access on functional block TPM user: full access on functional block of his project",
"name": "check_tpm_... | 3 | null | Implement the Python class `tms_functional_block` described below.
Class description:
Implement the tms_functional_block class.
Method signatures and docstrings:
- def check_unique_name_project(self): Check Functional Block name should be unique
- def check_tpm_access(self): Admin user: full access on functional bloc... | Implement the Python class `tms_functional_block` described below.
Class description:
Implement the tms_functional_block class.
Method signatures and docstrings:
- def check_unique_name_project(self): Check Functional Block name should be unique
- def check_tpm_access(self): Admin user: full access on functional bloc... | 673dd0f2a7c0b69a984342b20f55164a97a00529 | <|skeleton|>
class tms_functional_block:
def check_unique_name_project(self):
"""Check Functional Block name should be unique"""
<|body_0|>
def check_tpm_access(self):
"""Admin user: full access on functional block TPM user: full access on functional block of his project"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class tms_functional_block:
def check_unique_name_project(self):
"""Check Functional Block name should be unique"""
sql = "\n SELECT id from tms_functional_block\n WHERE active = 't'\n AND id != %s\n AND LOWER(name) = '%s'\n " % (self.id, self.name.lower())
... | the_stack_v2_python_sparse | project/tms_modules/model/ticket/tms_functional_block.py | TinPlusIT05/tms | train | 0 | |
ef2664d5130b60abc8390eb8d9694cfe8c11c510 | [
"dd = dictionary\nself.dset = dict()\nfor d in dd:\n if d:\n if len(d) > 1:\n self.dset[d[0] + str(len(d[1:-1]) if len(d[1:-1]) else '') + d[-1]] = d\n else:\n self.dset[d] = d\nprint(self.dset)",
"d = word\nw = None\nif d:\n if len(d) > 1:\n w = d[0] + str(len(d[1... | <|body_start_0|>
dd = dictionary
self.dset = dict()
for d in dd:
if d:
if len(d) > 1:
self.dset[d[0] + str(len(d[1:-1]) if len(d[1:-1]) else '') + d[-1]] = d
else:
self.dset[d] = d
print(self.dset)
<|end_... | ValidWordAbbr | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidWordAbbr:
def __init__(self, dictionary):
""":type dictionary: List[str]"""
<|body_0|>
def isUnique(self, word):
""":type word: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dd = dictionary
self.dset = dict()
... | stack_v2_sparse_classes_36k_train_026807 | 2,410 | no_license | [
{
"docstring": ":type dictionary: List[str]",
"name": "__init__",
"signature": "def __init__(self, dictionary)"
},
{
"docstring": ":type word: str :rtype: bool",
"name": "isUnique",
"signature": "def isUnique(self, word)"
}
] | 2 | null | Implement the Python class `ValidWordAbbr` described below.
Class description:
Implement the ValidWordAbbr class.
Method signatures and docstrings:
- def __init__(self, dictionary): :type dictionary: List[str]
- def isUnique(self, word): :type word: str :rtype: bool | Implement the Python class `ValidWordAbbr` described below.
Class description:
Implement the ValidWordAbbr class.
Method signatures and docstrings:
- def __init__(self, dictionary): :type dictionary: List[str]
- def isUnique(self, word): :type word: str :rtype: bool
<|skeleton|>
class ValidWordAbbr:
def __init_... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class ValidWordAbbr:
def __init__(self, dictionary):
""":type dictionary: List[str]"""
<|body_0|>
def isUnique(self, word):
""":type word: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ValidWordAbbr:
def __init__(self, dictionary):
""":type dictionary: List[str]"""
dd = dictionary
self.dset = dict()
for d in dd:
if d:
if len(d) > 1:
self.dset[d[0] + str(len(d[1:-1]) if len(d[1:-1]) else '') + d[-1]] = d
... | the_stack_v2_python_sparse | hash/288_Unique_Word_Abbreviation.py | vsdrun/lc_public | train | 6 | |
3d53c1aec4a26c471e66d8c60b20d73e7b36de34 | [
"self.SUBJECT = 'MOSJA00299'\nsuper(OASEMailAddBlackList, self).__init__(self.MAILACC, addr_to, self.SUBJECT, '', inquiry_url, login_url, charset)\nself.create_mail_text(ipaddr, url)",
"self.MAILTEXT = get_message('MOSJA00300', self.lang_mode, showMsgId=False, ipaddr=ipaddr, url=url)\nself.add_header()\nself.add_... | <|body_start_0|>
self.SUBJECT = 'MOSJA00299'
super(OASEMailAddBlackList, self).__init__(self.MAILACC, addr_to, self.SUBJECT, '', inquiry_url, login_url, charset)
self.create_mail_text(ipaddr, url)
<|end_body_0|>
<|body_start_1|>
self.MAILTEXT = get_message('MOSJA00300', self.lang_mode, ... | [クラス概要] ブラックリスト登録通知メール | OASEMailAddBlackList | [
"Apache-2.0",
"BSD-3-Clause",
"LGPL-3.0-only",
"MIT",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OASEMailAddBlackList:
"""[クラス概要] ブラックリスト登録通知メール"""
def __init__(self, addr_to, ipaddr, url, inquiry_url, login_url, charset='utf-8'):
"""[メソッド概要] 初期化処理 [引数] addr_to : str 宛先メールアドレス user_name : str 宛先ユーザ名 ipaddr : str ブラックリスト登録されたipアドレス url : url ブラックリスト画面URL charset : str 文字コード"""
... | stack_v2_sparse_classes_36k_train_026808 | 20,173 | permissive | [
{
"docstring": "[メソッド概要] 初期化処理 [引数] addr_to : str 宛先メールアドレス user_name : str 宛先ユーザ名 ipaddr : str ブラックリスト登録されたipアドレス url : url ブラックリスト画面URL charset : str 文字コード",
"name": "__init__",
"signature": "def __init__(self, addr_to, ipaddr, url, inquiry_url, login_url, charset='utf-8')"
},
{
"docstring": "... | 2 | null | Implement the Python class `OASEMailAddBlackList` described below.
Class description:
[クラス概要] ブラックリスト登録通知メール
Method signatures and docstrings:
- def __init__(self, addr_to, ipaddr, url, inquiry_url, login_url, charset='utf-8'): [メソッド概要] 初期化処理 [引数] addr_to : str 宛先メールアドレス user_name : str 宛先ユーザ名 ipaddr : str ブラックリスト登録さ... | Implement the Python class `OASEMailAddBlackList` described below.
Class description:
[クラス概要] ブラックリスト登録通知メール
Method signatures and docstrings:
- def __init__(self, addr_to, ipaddr, url, inquiry_url, login_url, charset='utf-8'): [メソッド概要] 初期化処理 [引数] addr_to : str 宛先メールアドレス user_name : str 宛先ユーザ名 ipaddr : str ブラックリスト登録さ... | c00ea4fe1bf4b4a18d545aabeaaf1d95c7664b94 | <|skeleton|>
class OASEMailAddBlackList:
"""[クラス概要] ブラックリスト登録通知メール"""
def __init__(self, addr_to, ipaddr, url, inquiry_url, login_url, charset='utf-8'):
"""[メソッド概要] 初期化処理 [引数] addr_to : str 宛先メールアドレス user_name : str 宛先ユーザ名 ipaddr : str ブラックリスト登録されたipアドレス url : url ブラックリスト画面URL charset : str 文字コード"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OASEMailAddBlackList:
"""[クラス概要] ブラックリスト登録通知メール"""
def __init__(self, addr_to, ipaddr, url, inquiry_url, login_url, charset='utf-8'):
"""[メソッド概要] 初期化処理 [引数] addr_to : str 宛先メールアドレス user_name : str 宛先ユーザ名 ipaddr : str ブラックリスト登録されたipアドレス url : url ブラックリスト画面URL charset : str 文字コード"""
self.SU... | the_stack_v2_python_sparse | oase-root/libs/webcommonlibs/oase_mail.py | exastro-suite/oase | train | 10 |
cfde457675af576c03951a39725249b17164802d | [
"vel_x = set_up_xy_velocity_cube('advection_velocity_x')\nvel_y = set_up_xy_velocity_cube('advection_velocity_y')\nplugin = AdvectField(vel_x, vel_y)\nself.assertEqual(plugin.x_coord.name(), 'projection_x_coordinate')\nself.assertIsInstance(plugin.vel_y, iris.cube.Cube)",
"vel_x = set_up_xy_velocity_cube('advecti... | <|body_start_0|>
vel_x = set_up_xy_velocity_cube('advection_velocity_x')
vel_y = set_up_xy_velocity_cube('advection_velocity_y')
plugin = AdvectField(vel_x, vel_y)
self.assertEqual(plugin.x_coord.name(), 'projection_x_coordinate')
self.assertIsInstance(plugin.vel_y, iris.cube.Cub... | Test class initialisation | Test__init__ | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test__init__:
"""Test class initialisation"""
def test_basic(self):
"""Test for cubes and coordinates in class instance"""
<|body_0|>
def test_units(self):
"""Test velocity fields are converted to m/s"""
<|body_1|>
def test_raises_grid_mismatch_error... | stack_v2_sparse_classes_36k_train_026809 | 22,262 | permissive | [
{
"docstring": "Test for cubes and coordinates in class instance",
"name": "test_basic",
"signature": "def test_basic(self)"
},
{
"docstring": "Test velocity fields are converted to m/s",
"name": "test_units",
"signature": "def test_units(self)"
},
{
"docstring": "Test error is r... | 3 | stack_v2_sparse_classes_30k_train_013217 | Implement the Python class `Test__init__` described below.
Class description:
Test class initialisation
Method signatures and docstrings:
- def test_basic(self): Test for cubes and coordinates in class instance
- def test_units(self): Test velocity fields are converted to m/s
- def test_raises_grid_mismatch_error(sel... | Implement the Python class `Test__init__` described below.
Class description:
Test class initialisation
Method signatures and docstrings:
- def test_basic(self): Test for cubes and coordinates in class instance
- def test_units(self): Test velocity fields are converted to m/s
- def test_raises_grid_mismatch_error(sel... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test__init__:
"""Test class initialisation"""
def test_basic(self):
"""Test for cubes and coordinates in class instance"""
<|body_0|>
def test_units(self):
"""Test velocity fields are converted to m/s"""
<|body_1|>
def test_raises_grid_mismatch_error... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test__init__:
"""Test class initialisation"""
def test_basic(self):
"""Test for cubes and coordinates in class instance"""
vel_x = set_up_xy_velocity_cube('advection_velocity_x')
vel_y = set_up_xy_velocity_cube('advection_velocity_y')
plugin = AdvectField(vel_x, vel_y)
... | the_stack_v2_python_sparse | improver_tests/nowcasting/forecasting/test_AdvectField.py | metoppv/improver | train | 101 |
345e3f8062c01205fe5dabe7f95fd75b69aaec68 | [
"if not employee_id:\n return {'value': {'mission_amounts': 0, 'amount': 0}}\npayroll_obj = self.pool.get('payroll')\nmission_obj = self.pool.get('hr.mission.category')\nemp_obj = self.pool.get('hr.employee')\nallowance_id = mission_obj.browse(cr, uid, mission_id).allowance_id\nemp = emp_obj.browse(cr, uid, empl... | <|body_start_0|>
if not employee_id:
return {'value': {'mission_amounts': 0, 'amount': 0}}
payroll_obj = self.pool.get('payroll')
mission_obj = self.pool.get('hr.mission.category')
emp_obj = self.pool.get('hr.employee')
allowance_id = mission_obj.browse(cr, uid, missi... | employee_mission_line | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class employee_mission_line:
def onchange_days(self, cr, uid, ids, days, employee_id, mission_id, context=None):
"""Compute missions amount for(Internal/External missions). @param days: integer no of days entered by user @param employee_id: ID of employee @param mission_id: ID of mission @retu... | stack_v2_sparse_classes_36k_train_026810 | 17,962 | no_license | [
{
"docstring": "Compute missions amount for(Internal/External missions). @param days: integer no of days entered by user @param employee_id: ID of employee @param mission_id: ID of mission @return: Dictionary of mission amount to be updated",
"name": "onchange_days",
"signature": "def onchange_days(self... | 2 | null | Implement the Python class `employee_mission_line` described below.
Class description:
Implement the employee_mission_line class.
Method signatures and docstrings:
- def onchange_days(self, cr, uid, ids, days, employee_id, mission_id, context=None): Compute missions amount for(Internal/External missions). @param days... | Implement the Python class `employee_mission_line` described below.
Class description:
Implement the employee_mission_line class.
Method signatures and docstrings:
- def onchange_days(self, cr, uid, ids, days, employee_id, mission_id, context=None): Compute missions amount for(Internal/External missions). @param days... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class employee_mission_line:
def onchange_days(self, cr, uid, ids, days, employee_id, mission_id, context=None):
"""Compute missions amount for(Internal/External missions). @param days: integer no of days entered by user @param employee_id: ID of employee @param mission_id: ID of mission @retu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class employee_mission_line:
def onchange_days(self, cr, uid, ids, days, employee_id, mission_id, context=None):
"""Compute missions amount for(Internal/External missions). @param days: integer no of days entered by user @param employee_id: ID of employee @param mission_id: ID of mission @return: Dictionary... | the_stack_v2_python_sparse | v_7/Dongola/common/hr_mission/hr_mission.py | musabahmed/baba | train | 0 | |
d3dcdffb355ebdccc9baa3e8c28803d559b84cea | [
"self.enter_message()\nes = self.find_elements('message_items', *self.by_message_item_id)\nfor i, e in enumerate(es[0]):\n if '群聊' in e.text:\n self.swipe_to_left_del_item((e, '群聊%d' % i))",
"self.enter_message()\nself.myClick(self.find_element('联系人', *self.by_message_contact_id))\nself.myClick(self.fin... | <|body_start_0|>
self.enter_message()
es = self.find_elements('message_items', *self.by_message_item_id)
for i, e in enumerate(es[0]):
if '群聊' in e.text:
self.swipe_to_left_del_item((e, '群聊%d' % i))
<|end_body_0|>
<|body_start_1|>
self.enter_message()
... | MessageContact | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MessageContact:
def test_message_del_groupchat(self):
"""消息_删除_群聊message"""
<|body_0|>
def test_message_contact_partner(self):
"""消息_通讯录_合伙人"""
<|body_1|>
def test_message_account_contact_cs(self):
"""消息_通讯录_购物号_联系客服"""
<|body_2|>
de... | stack_v2_sparse_classes_36k_train_026811 | 4,093 | no_license | [
{
"docstring": "消息_删除_群聊message",
"name": "test_message_del_groupchat",
"signature": "def test_message_del_groupchat(self)"
},
{
"docstring": "消息_通讯录_合伙人",
"name": "test_message_contact_partner",
"signature": "def test_message_contact_partner(self)"
},
{
"docstring": "消息_通讯录_购物号_... | 4 | null | Implement the Python class `MessageContact` described below.
Class description:
Implement the MessageContact class.
Method signatures and docstrings:
- def test_message_del_groupchat(self): 消息_删除_群聊message
- def test_message_contact_partner(self): 消息_通讯录_合伙人
- def test_message_account_contact_cs(self): 消息_通讯录_购物号_联系客... | Implement the Python class `MessageContact` described below.
Class description:
Implement the MessageContact class.
Method signatures and docstrings:
- def test_message_del_groupchat(self): 消息_删除_群聊message
- def test_message_contact_partner(self): 消息_通讯录_合伙人
- def test_message_account_contact_cs(self): 消息_通讯录_购物号_联系客... | b2066139eb0723eff69d971589b283b4b776c84c | <|skeleton|>
class MessageContact:
def test_message_del_groupchat(self):
"""消息_删除_群聊message"""
<|body_0|>
def test_message_contact_partner(self):
"""消息_通讯录_合伙人"""
<|body_1|>
def test_message_account_contact_cs(self):
"""消息_通讯录_购物号_联系客服"""
<|body_2|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MessageContact:
def test_message_del_groupchat(self):
"""消息_删除_群聊message"""
self.enter_message()
es = self.find_elements('message_items', *self.by_message_item_id)
for i, e in enumerate(es[0]):
if '群聊' in e.text:
self.swipe_to_left_del_item((e, '群聊%d... | the_stack_v2_python_sparse | TestCase/4_5/TC_Message/test_message_contact.py | testerSunshine/auto_md | train | 4 | |
683859b8ebbb5d83222e3e406b7333fa266a277e | [
"indices = 5\nres = fn.take(t, indices)\nassert fn.allclose(res, 1)",
"indices = [0, 2, 3, 6, -2]\nres = fn.take(t, indices)\nassert fn.allclose(res, [1, 3, 4, 5, 2])",
"indices = [[0, 1], [3, 2]]\nres = fn.take(t, indices)\nassert fn.allclose(res, [[1, 2], [4, 3]])",
"indices = [0, 1, -2]\nres = fn.take(t, i... | <|body_start_0|>
indices = 5
res = fn.take(t, indices)
assert fn.allclose(res, 1)
<|end_body_0|>
<|body_start_1|>
indices = [0, 2, 3, 6, -2]
res = fn.take(t, indices)
assert fn.allclose(res, [1, 3, 4, 5, 2])
<|end_body_1|>
<|body_start_2|>
indices = [[0, 1], [3,... | Tests for the qml.take function | TestTake | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestTake:
"""Tests for the qml.take function"""
def test_flattened_indexing(self, t):
"""Test that indexing without the axis argument will flatten the tensor first"""
<|body_0|>
def test_array_indexing(self, t):
"""Test that indexing with a sequence properly extr... | stack_v2_sparse_classes_36k_train_026812 | 47,600 | permissive | [
{
"docstring": "Test that indexing without the axis argument will flatten the tensor first",
"name": "test_flattened_indexing",
"signature": "def test_flattened_indexing(self, t)"
},
{
"docstring": "Test that indexing with a sequence properly extracts the elements from the flattened tensor",
... | 5 | null | Implement the Python class `TestTake` described below.
Class description:
Tests for the qml.take function
Method signatures and docstrings:
- def test_flattened_indexing(self, t): Test that indexing without the axis argument will flatten the tensor first
- def test_array_indexing(self, t): Test that indexing with a s... | Implement the Python class `TestTake` described below.
Class description:
Tests for the qml.take function
Method signatures and docstrings:
- def test_flattened_indexing(self, t): Test that indexing without the axis argument will flatten the tensor first
- def test_array_indexing(self, t): Test that indexing with a s... | 0c1c805fd5dfce465a8955ee3faf81037023a23e | <|skeleton|>
class TestTake:
"""Tests for the qml.take function"""
def test_flattened_indexing(self, t):
"""Test that indexing without the axis argument will flatten the tensor first"""
<|body_0|>
def test_array_indexing(self, t):
"""Test that indexing with a sequence properly extr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestTake:
"""Tests for the qml.take function"""
def test_flattened_indexing(self, t):
"""Test that indexing without the axis argument will flatten the tensor first"""
indices = 5
res = fn.take(t, indices)
assert fn.allclose(res, 1)
def test_array_indexing(self, t):
... | the_stack_v2_python_sparse | artifacts/old_dataset_versions/original_commits_backup/pennylane/pennylane#1081/before/test_functions.py | MattePalte/Bugs-Quantum-Computing-Platforms | train | 4 |
a16bd30e87bfbe53fbdf046a723fe64414623bab | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn TimeOffRequest()",
"from .schedule_change_request import ScheduleChangeRequest\nfrom .schedule_change_request import ScheduleChangeRequest\nfields: Dict[str, Callable[[Any], None]] = {'endDateTime': lambda n: setattr(self, 'end_date_ti... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return TimeOffRequest()
<|end_body_0|>
<|body_start_1|>
from .schedule_change_request import ScheduleChangeRequest
from .schedule_change_request import ScheduleChangeRequest
fields: Dic... | TimeOffRequest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeOffRequest:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TimeOffRequest:
"""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 Retur... | stack_v2_sparse_classes_36k_train_026813 | 2,982 | 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: TimeOffRequest",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_valu... | 3 | stack_v2_sparse_classes_30k_train_013734 | Implement the Python class `TimeOffRequest` described below.
Class description:
Implement the TimeOffRequest class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TimeOffRequest: Creates a new instance of the appropriate class based on discriminator va... | Implement the Python class `TimeOffRequest` described below.
Class description:
Implement the TimeOffRequest class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TimeOffRequest: Creates a new instance of the appropriate class based on discriminator va... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class TimeOffRequest:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TimeOffRequest:
"""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 Retur... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TimeOffRequest:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TimeOffRequest:
"""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: TimeOffReq... | the_stack_v2_python_sparse | msgraph/generated/models/time_off_request.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
9f2f7bdbe644fc84c68066666508221cd7e6e9bc | [
"super().__init__(**kwargs)\nself.fc1 = keras.layers.Dense(hidden_dim)\nself.fcs = [keras.layers.Dense(dim) for dim in output_dims]",
"x = tf.nn.relu(self.fc1(x))\nxs = [fc(x) for fc in self.fcs]\nreturn xs"
] | <|body_start_0|>
super().__init__(**kwargs)
self.fc1 = keras.layers.Dense(hidden_dim)
self.fcs = [keras.layers.Dense(dim) for dim in output_dims]
<|end_body_0|>
<|body_start_1|>
x = tf.nn.relu(self.fc1(x))
xs = [fc(x) for fc in self.fcs]
return xs
<|end_body_1|>
| ADULT decoder used in the Counterfactual with Reinforcement Learning experiments. The model consists of of a fully connected layer with ReLU nonlinearity, and a multiheaded layer, one for each categorical feature and a single head for the rest of numerical features. The hidden dimension used in the paper is 128. | ADULTDecoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ADULTDecoder:
"""ADULT decoder used in the Counterfactual with Reinforcement Learning experiments. The model consists of of a fully connected layer with ReLU nonlinearity, and a multiheaded layer, one for each categorical feature and a single head for the rest of numerical features. The hidden di... | stack_v2_sparse_classes_36k_train_026814 | 8,692 | permissive | [
{
"docstring": "Constructor. Parameters ---------- hidden_dim Hidden dimension. output_dim List of output dimensions.",
"name": "__init__",
"signature": "def __init__(self, hidden_dim: int, output_dims: List[int], **kwargs)"
},
{
"docstring": "Forward pass. Parameters ---------- x Input tensor. ... | 2 | null | Implement the Python class `ADULTDecoder` described below.
Class description:
ADULT decoder used in the Counterfactual with Reinforcement Learning experiments. The model consists of of a fully connected layer with ReLU nonlinearity, and a multiheaded layer, one for each categorical feature and a single head for the re... | Implement the Python class `ADULTDecoder` described below.
Class description:
ADULT decoder used in the Counterfactual with Reinforcement Learning experiments. The model consists of of a fully connected layer with ReLU nonlinearity, and a multiheaded layer, one for each categorical feature and a single head for the re... | 54d0c957fb01c7ebba4e2a0d28fcbde52d9c6718 | <|skeleton|>
class ADULTDecoder:
"""ADULT decoder used in the Counterfactual with Reinforcement Learning experiments. The model consists of of a fully connected layer with ReLU nonlinearity, and a multiheaded layer, one for each categorical feature and a single head for the rest of numerical features. The hidden di... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ADULTDecoder:
"""ADULT decoder used in the Counterfactual with Reinforcement Learning experiments. The model consists of of a fully connected layer with ReLU nonlinearity, and a multiheaded layer, one for each categorical feature and a single head for the rest of numerical features. The hidden dimension used ... | the_stack_v2_python_sparse | alibi/models/tensorflow/cfrl_models.py | SeldonIO/alibi | train | 2,143 |
1e85eb646433c4af8865769fa1232c5dac431876 | [
"rights = access.Checker(params)\nrights['create'] = [('checkHasRoleForScope', host_logic.logic)]\nrights['edit'] = [('checkIsMyActiveRole', host_logic.logic)]\nrights['invite'] = [('checkHasRoleForScope', host_logic.logic)]\nrights['list'] = ['checkIsDeveloper']\nrights['accept_invite'] = [('checkIsMyRequestWithSt... | <|body_start_0|>
rights = access.Checker(params)
rights['create'] = [('checkHasRoleForScope', host_logic.logic)]
rights['edit'] = [('checkIsMyActiveRole', host_logic.logic)]
rights['invite'] = [('checkHasRoleForScope', host_logic.logic)]
rights['list'] = ['checkIsDeveloper']
... | View methods for the Host model. | View | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class View:
"""View methods for the Host model."""
def __init__(self, params=None):
"""Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete views. Params: params: a dict with params for this View"""
<|body_0|... | stack_v2_sparse_classes_36k_train_026815 | 4,637 | permissive | [
{
"docstring": "Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete views. Params: params: a dict with params for this View",
"name": "__init__",
"signature": "def __init__(self, params=None)"
},
{
"docstring": "See base.... | 2 | null | Implement the Python class `View` described below.
Class description:
View methods for the Host model.
Method signatures and docstrings:
- def __init__(self, params=None): Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete views. Params: para... | Implement the Python class `View` described below.
Class description:
View methods for the Host model.
Method signatures and docstrings:
- def __init__(self, params=None): Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete views. Params: para... | 9bd45c168f8ddb5c0e6c04eacdcaeafd61908be7 | <|skeleton|>
class View:
"""View methods for the Host model."""
def __init__(self, params=None):
"""Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete views. Params: params: a dict with params for this View"""
<|body_0|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class View:
"""View methods for the Host model."""
def __init__(self, params=None):
"""Defines the fields and methods required for the base View class to provide the user with list, public, create, edit and delete views. Params: params: a dict with params for this View"""
rights = access.Checke... | the_stack_v2_python_sparse | app/soc/views/models/host.py | pombredanne/Melange-1 | train | 0 |
9e7d845f1105f7a97f8953a3a5b35c74fcf67d06 | [
"self._expression = expression\n\ndef function_wrapper(q, p):\n \"\"\" helper function for sympy differentiation\"\"\"\n return eval(self._expression)\nq, p = sym.symbols('q p', real=True)\ntry:\n self._derivative_q = str(sym.diff(function_wrapper(q, p), q))\n self._derivative_p = str(sym.diff(function_... | <|body_start_0|>
self._expression = expression
def function_wrapper(q, p):
""" helper function for sympy differentiation"""
return eval(self._expression)
q, p = sym.symbols('q p', real=True)
try:
self._derivative_q = str(sym.diff(function_wrapper(q, p... | Interaction base class between particles Common Parameters ----------------- q_state : np.array current state of the position of N X DIM array p_state : np.array current state of the momentum of N X DIM array | Interaction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Interaction:
"""Interaction base class between particles Common Parameters ----------------- q_state : np.array current state of the position of N X DIM array p_state : np.array current state of the momentum of N X DIM array"""
def __init__(self, expression):
"""base interaction clas... | stack_v2_sparse_classes_36k_train_026816 | 4,161 | no_license | [
{
"docstring": "base interaction class that will call the expression Parameters ---------- expression : string the expression of the term for variable q and p which represents position and momentum respectively otherwise, eval would return error",
"name": "__init__",
"signature": "def __init__(self, exp... | 4 | stack_v2_sparse_classes_30k_train_011621 | Implement the Python class `Interaction` described below.
Class description:
Interaction base class between particles Common Parameters ----------------- q_state : np.array current state of the position of N X DIM array p_state : np.array current state of the momentum of N X DIM array
Method signatures and docstrings... | Implement the Python class `Interaction` described below.
Class description:
Interaction base class between particles Common Parameters ----------------- q_state : np.array current state of the position of N X DIM array p_state : np.array current state of the momentum of N X DIM array
Method signatures and docstrings... | fe939de84a8d8f3ad74c0f3172214e0304bff05f | <|skeleton|>
class Interaction:
"""Interaction base class between particles Common Parameters ----------------- q_state : np.array current state of the position of N X DIM array p_state : np.array current state of the momentum of N X DIM array"""
def __init__(self, expression):
"""base interaction clas... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Interaction:
"""Interaction base class between particles Common Parameters ----------------- q_state : np.array current state of the position of N X DIM array p_state : np.array current state of the momentum of N X DIM array"""
def __init__(self, expression):
"""base interaction class that will c... | the_stack_v2_python_sparse | hamiltonian/Interaction.py | simonjulianl/Langevin_Machine_Learning | train | 4 |
091d813a63709ff14d3d61ab33bafface608f74e | [
"self.id = id\nself.account_id = account_id\nself.mtype = mtype\nself.callback_url = callback_url\nself.signing_key = signing_key\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\nid = dictionary.get('id')\naccount_id = dictionary.get('accountId')\nmtype = dictionary.... | <|body_start_0|>
self.id = id
self.account_id = account_id
self.mtype = mtype
self.callback_url = callback_url
self.signing_key = signing_key
self.additional_properties = additional_properties
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
ret... | Implementation of the 'Subscription Record' model. TxPush subscription details Attributes: id (long|int): Unique subscription identifier account_id (long|int): The Finicity account Id for the subscription mtype (string): Event subscription type. account or transaction callback_url (string): The url for the events signi... | SubscriptionRecord | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubscriptionRecord:
"""Implementation of the 'Subscription Record' model. TxPush subscription details Attributes: id (long|int): Unique subscription identifier account_id (long|int): The Finicity account Id for the subscription mtype (string): Event subscription type. account or transaction callb... | stack_v2_sparse_classes_36k_train_026817 | 2,623 | permissive | [
{
"docstring": "Constructor for the SubscriptionRecord class",
"name": "__init__",
"signature": "def __init__(self, id=None, account_id=None, mtype=None, callback_url=None, signing_key=None, additional_properties={})"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: d... | 2 | stack_v2_sparse_classes_30k_train_021589 | Implement the Python class `SubscriptionRecord` described below.
Class description:
Implementation of the 'Subscription Record' model. TxPush subscription details Attributes: id (long|int): Unique subscription identifier account_id (long|int): The Finicity account Id for the subscription mtype (string): Event subscrip... | Implement the Python class `SubscriptionRecord` described below.
Class description:
Implementation of the 'Subscription Record' model. TxPush subscription details Attributes: id (long|int): Unique subscription identifier account_id (long|int): The Finicity account Id for the subscription mtype (string): Event subscrip... | b2ab1ded435db75c78d42261f5e4acd2a3061487 | <|skeleton|>
class SubscriptionRecord:
"""Implementation of the 'Subscription Record' model. TxPush subscription details Attributes: id (long|int): Unique subscription identifier account_id (long|int): The Finicity account Id for the subscription mtype (string): Event subscription type. account or transaction callb... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubscriptionRecord:
"""Implementation of the 'Subscription Record' model. TxPush subscription details Attributes: id (long|int): Unique subscription identifier account_id (long|int): The Finicity account Id for the subscription mtype (string): Event subscription type. account or transaction callback_url (stri... | the_stack_v2_python_sparse | finicityapi/models/subscription_record.py | monarchmoney/finicity-python | train | 0 |
434dc0c4410f3899b9f3bd4b6a016f9850bcf9db | [
"response = self.client.get(reverse('rango:index'))\nself.assertEqual(response.status_code, 200)\nself.assertContains(response, 'There are no categories present.')\nself.assertQuerysetEqual(response.context['categories'], [])",
"add_cat('test', 1, 1)\nadd_cat('temp', 1, 1)\nadd_cat('tmp', 1, 1)\nadd_cat('tmp test... | <|body_start_0|>
response = self.client.get(reverse('rango:index'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'There are no categories present.')
self.assertQuerysetEqual(response.context['categories'], [])
<|end_body_0|>
<|body_start_1|>
add_cat(... | IndexViewTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IndexViewTests:
def test_index_view_with_no_categories(self):
"""If no questions exist,an appropriate message should be displayed."""
<|body_0|>
def test_index_view_with_categories(self):
"""If no questions exist,an appropriate message should be displayed."""
... | stack_v2_sparse_classes_36k_train_026818 | 2,266 | no_license | [
{
"docstring": "If no questions exist,an appropriate message should be displayed.",
"name": "test_index_view_with_no_categories",
"signature": "def test_index_view_with_no_categories(self)"
},
{
"docstring": "If no questions exist,an appropriate message should be displayed.",
"name": "test_i... | 2 | null | Implement the Python class `IndexViewTests` described below.
Class description:
Implement the IndexViewTests class.
Method signatures and docstrings:
- def test_index_view_with_no_categories(self): If no questions exist,an appropriate message should be displayed.
- def test_index_view_with_categories(self): If no que... | Implement the Python class `IndexViewTests` described below.
Class description:
Implement the IndexViewTests class.
Method signatures and docstrings:
- def test_index_view_with_no_categories(self): If no questions exist,an appropriate message should be displayed.
- def test_index_view_with_categories(self): If no que... | 9e3d117d17025b3b587c5a80638cb8b3de754195 | <|skeleton|>
class IndexViewTests:
def test_index_view_with_no_categories(self):
"""If no questions exist,an appropriate message should be displayed."""
<|body_0|>
def test_index_view_with_categories(self):
"""If no questions exist,an appropriate message should be displayed."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IndexViewTests:
def test_index_view_with_no_categories(self):
"""If no questions exist,an appropriate message should be displayed."""
response = self.client.get(reverse('rango:index'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'There are no categ... | the_stack_v2_python_sparse | Django-Projects/tango_with_django_project/rango/tests.py | breezy1812/MyCodes | train | 0 | |
e0af6dfbdec7a38410a949cd965e439bd94e672e | [
"self.logger = Logger('Simulation')\nself.model = model\nself.x0 = model.state0\nself.finished = False\nself.controller = controller",
"self.fps = 30\nself.tf = tf\nself.t = np.linspace(0.0, self.tf, self.tf * self.fps)\n\ndef dxdt(x, t):\n return self.model.rhs(x, t, self.controller.controller(x, t, self.x0),... | <|body_start_0|>
self.logger = Logger('Simulation')
self.model = model
self.x0 = model.state0
self.finished = False
self.controller = controller
<|end_body_0|>
<|body_start_1|>
self.fps = 30
self.tf = tf
self.t = np.linspace(0.0, self.tf, self.tf * self.f... | This class accepts a ArmModel and a Controller class that must define a function control(x, t, x0) and performs a numerical integration. | Simulation | [
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Simulation:
"""This class accepts a ArmModel and a Controller class that must define a function control(x, t, x0) and performs a numerical integration."""
def __init__(self, model, controller):
"""Constructor. Parameters ---------- model: a reference to ToyModel controller: a referen... | stack_v2_sparse_classes_36k_train_026819 | 9,732 | permissive | [
{
"docstring": "Constructor. Parameters ---------- model: a reference to ToyModel controller: a reference to a tracking controller (forcing)",
"name": "__init__",
"signature": "def __init__(self, model, controller)"
},
{
"docstring": "Numerical integration of the model for the given initial stat... | 3 | stack_v2_sparse_classes_30k_train_016377 | Implement the Python class `Simulation` described below.
Class description:
This class accepts a ArmModel and a Controller class that must define a function control(x, t, x0) and performs a numerical integration.
Method signatures and docstrings:
- def __init__(self, model, controller): Constructor. Parameters ------... | Implement the Python class `Simulation` described below.
Class description:
This class accepts a ArmModel and a Controller class that must define a function control(x, t, x0) and performs a numerical integration.
Method signatures and docstrings:
- def __init__(self, model, controller): Constructor. Parameters ------... | 331ae7ab01e768c6a8c20ec8090464eeef547eea | <|skeleton|>
class Simulation:
"""This class accepts a ArmModel and a Controller class that must define a function control(x, t, x0) and performs a numerical integration."""
def __init__(self, model, controller):
"""Constructor. Parameters ---------- model: a reference to ToyModel controller: a referen... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Simulation:
"""This class accepts a ArmModel and a Controller class that must define a function control(x, t, x0) and performs a numerical integration."""
def __init__(self, model, controller):
"""Constructor. Parameters ---------- model: a reference to ToyModel controller: a reference to a track... | the_stack_v2_python_sparse | arm_model/simulation.py | mitkof6/musculoskeletal-redundancy | train | 7 |
94c1c735e48c65dc64ce437f239fd89a7bfe982b | [
"self.X = x\nself.KEEPPRO = keep_pro\nself.CLASSNUM = class_num\nself.MODELPATH = model_path\nself.nn()",
"conv_1 = convLayer(self.X, 11, 11, 4, 4, 96, 'conv1', 'VALID')\npool_1 = tf.nn.max_pool(conv_1, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='VALID', name='pool1')\nlrn_1 = tf.nn.lrn(pool_1, depth_radiu... | <|body_start_0|>
self.X = x
self.KEEPPRO = keep_pro
self.CLASSNUM = class_num
self.MODELPATH = model_path
self.nn()
<|end_body_0|>
<|body_start_1|>
conv_1 = convLayer(self.X, 11, 11, 4, 4, 96, 'conv1', 'VALID')
pool_1 = tf.nn.max_pool(conv_1, ksize=[1, 3, 3, 1], ... | descrption: to set up alexnet network function: _init_ -- set parameters and initialize the network nn -- the cnn architecture load -- to load model | alexnet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class alexnet:
"""descrption: to set up alexnet network function: _init_ -- set parameters and initialize the network nn -- the cnn architecture load -- to load model"""
def __init__(self, x, keep_pro, class_num, model_path='bvlc_alexnet.npy'):
"""descrption: to initialize parameters for a... | stack_v2_sparse_classes_36k_train_026820 | 6,866 | no_license | [
{
"docstring": "descrption: to initialize parameters for alexnet model Args: x: input data[image] keep_pro: keep alive probility of neruial units class_num: numbers of class model_path: the trained model file",
"name": "__init__",
"signature": "def __init__(self, x, keep_pro, class_num, model_path='bvlc... | 3 | stack_v2_sparse_classes_30k_train_000317 | Implement the Python class `alexnet` described below.
Class description:
descrption: to set up alexnet network function: _init_ -- set parameters and initialize the network nn -- the cnn architecture load -- to load model
Method signatures and docstrings:
- def __init__(self, x, keep_pro, class_num, model_path='bvlc_... | Implement the Python class `alexnet` described below.
Class description:
descrption: to set up alexnet network function: _init_ -- set parameters and initialize the network nn -- the cnn architecture load -- to load model
Method signatures and docstrings:
- def __init__(self, x, keep_pro, class_num, model_path='bvlc_... | 4b44860d8849155fc91134faf1f4beb45c8c5df8 | <|skeleton|>
class alexnet:
"""descrption: to set up alexnet network function: _init_ -- set parameters and initialize the network nn -- the cnn architecture load -- to load model"""
def __init__(self, x, keep_pro, class_num, model_path='bvlc_alexnet.npy'):
"""descrption: to initialize parameters for a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class alexnet:
"""descrption: to set up alexnet network function: _init_ -- set parameters and initialize the network nn -- the cnn architecture load -- to load model"""
def __init__(self, x, keep_pro, class_num, model_path='bvlc_alexnet.npy'):
"""descrption: to initialize parameters for alexnet model ... | the_stack_v2_python_sparse | alexnet/main.py | GinkgoX/tensorfolw_cnn | train | 0 |
cd43ea9ebf98f1622082426ca6e3cf5863856fa2 | [
"assert interrupt_handle or parent_handle\nsuper().__init__()\nif ctypes is None:\n msg = 'ParentPollerWindows requires ctypes'\n raise ImportError(msg)\nself.daemon = True\nself.interrupt_handle = interrupt_handle\nself.parent_handle = parent_handle",
"try:\n from _winapi import INFINITE, WAIT_OBJECT_0\... | <|body_start_0|>
assert interrupt_handle or parent_handle
super().__init__()
if ctypes is None:
msg = 'ParentPollerWindows requires ctypes'
raise ImportError(msg)
self.daemon = True
self.interrupt_handle = interrupt_handle
self.parent_handle = pare... | A Windows-specific daemon thread that listens for a special event that signals an interrupt and, optionally, terminates the program immediately when the parent process no longer exists. | ParentPollerWindows | [
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParentPollerWindows:
"""A Windows-specific daemon thread that listens for a special event that signals an interrupt and, optionally, terminates the program immediately when the parent process no longer exists."""
def __init__(self, interrupt_handle=None, parent_handle=None):
"""Creat... | stack_v2_sparse_classes_36k_train_026821 | 4,249 | permissive | [
{
"docstring": "Create the poller. At least one of the optional parameters must be provided. Parameters ---------- interrupt_handle : HANDLE (int), optional If provided, the program will generate a Ctrl+C event when this handle is signaled. parent_handle : HANDLE (int), optional If provided, the program will te... | 2 | null | Implement the Python class `ParentPollerWindows` described below.
Class description:
A Windows-specific daemon thread that listens for a special event that signals an interrupt and, optionally, terminates the program immediately when the parent process no longer exists.
Method signatures and docstrings:
- def __init_... | Implement the Python class `ParentPollerWindows` described below.
Class description:
A Windows-specific daemon thread that listens for a special event that signals an interrupt and, optionally, terminates the program immediately when the parent process no longer exists.
Method signatures and docstrings:
- def __init_... | f5042e35b945aded77b23470ead62d7eacefde92 | <|skeleton|>
class ParentPollerWindows:
"""A Windows-specific daemon thread that listens for a special event that signals an interrupt and, optionally, terminates the program immediately when the parent process no longer exists."""
def __init__(self, interrupt_handle=None, parent_handle=None):
"""Creat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParentPollerWindows:
"""A Windows-specific daemon thread that listens for a special event that signals an interrupt and, optionally, terminates the program immediately when the parent process no longer exists."""
def __init__(self, interrupt_handle=None, parent_handle=None):
"""Create the poller.... | the_stack_v2_python_sparse | contrib/python/ipykernel/py3/ipykernel/parentpoller.py | catboost/catboost | train | 8,012 |
bbd2951ab410da2d2f34ad4b21a4e0bf1cdb6dd9 | [
"if not self.is_visible(source, overrides):\n return None\nx = self.get_property('x', source, overrides)\ny = self.get_property('y', source, overrides)\nx_offset = self.get_property('x_offset', source, overrides)\ny_offset = self.get_property('y_offset', source, overrides)\ntext = self.get_property('text', sourc... | <|body_start_0|>
if not self.is_visible(source, overrides):
return None
x = self.get_property('x', source, overrides)
y = self.get_property('y', source, overrides)
x_offset = self.get_property('x_offset', source, overrides)
y_offset = self.get_property('y_offset', sou... | Defines a simple text label glyph. Properties: text: str, callable, None or UNDEF Specifies the text to be drawn. text properties: Includes pero.TextProperties to specify the text properties. angle properties: Includes pero.AngleProperties to specify the text angle. | TextLabel | [
"LicenseRef-scancode-philippe-de-muyter",
"LicenseRef-scancode-commercial-license",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextLabel:
"""Defines a simple text label glyph. Properties: text: str, callable, None or UNDEF Specifies the text to be drawn. text properties: Includes pero.TextProperties to specify the text properties. angle properties: Includes pero.AngleProperties to specify the text angle."""
def get_... | stack_v2_sparse_classes_36k_train_026822 | 10,183 | permissive | [
{
"docstring": "Gets glyph bounding box.",
"name": "get_bbox",
"signature": "def get_bbox(self, canvas, source=UNDEF, **overrides)"
},
{
"docstring": "Uses given canvas to draw label.",
"name": "draw",
"signature": "def draw(self, canvas, source=UNDEF, **overrides)"
}
] | 2 | null | Implement the Python class `TextLabel` described below.
Class description:
Defines a simple text label glyph. Properties: text: str, callable, None or UNDEF Specifies the text to be drawn. text properties: Includes pero.TextProperties to specify the text properties. angle properties: Includes pero.AngleProperties to s... | Implement the Python class `TextLabel` described below.
Class description:
Defines a simple text label glyph. Properties: text: str, callable, None or UNDEF Specifies the text to be drawn. text properties: Includes pero.TextProperties to specify the text properties. angle properties: Includes pero.AngleProperties to s... | d59b1bc056f3037b7b7ab635b6deb41120612965 | <|skeleton|>
class TextLabel:
"""Defines a simple text label glyph. Properties: text: str, callable, None or UNDEF Specifies the text to be drawn. text properties: Includes pero.TextProperties to specify the text properties. angle properties: Includes pero.AngleProperties to specify the text angle."""
def get_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TextLabel:
"""Defines a simple text label glyph. Properties: text: str, callable, None or UNDEF Specifies the text to be drawn. text properties: Includes pero.TextProperties to specify the text properties. angle properties: Includes pero.AngleProperties to specify the text angle."""
def get_bbox(self, ca... | the_stack_v2_python_sparse | pero/glyphs/labels.py | xxao/pero | train | 31 |
7695c16a2268e1a0c635dcb9e2d72cad3ce82e00 | [
"cnt = 0\nk = 0\nwhile True:\n k += 1\n x0k = N - k * (k - 1) // 2\n if x0k <= 0:\n break\n if x0k % k == 0:\n cnt += 1\nreturn cnt",
"cnt = 0\nfor k in range(1, int(N ** 0.5)):\n x0k = N - k * (k - 1) // 2\n if x0k % k == 0:\n cnt += 1\nreturn cnt",
"if N == 1:\n retur... | <|body_start_0|>
cnt = 0
k = 0
while True:
k += 1
x0k = N - k * (k - 1) // 2
if x0k <= 0:
break
if x0k % k == 0:
cnt += 1
return cnt
<|end_body_0|>
<|body_start_1|>
cnt = 0
for k in range(1, ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def consecutiveNumbersSum(self, N: int) -> int:
"""Arithmetic Array math (x0 + xn) * (xn - x0 + 1) / 2 = N xn = x0 + k - 1 (2x0 + k - 1) * k / 2 = N 2x0 = 2N / k - k + 1 x0 * k = N - k * (k - 1) / 2 # assure for divisibility"""
<|body_0|>
def consecutiveNumbersSum_... | stack_v2_sparse_classes_36k_train_026823 | 1,863 | no_license | [
{
"docstring": "Arithmetic Array math (x0 + xn) * (xn - x0 + 1) / 2 = N xn = x0 + k - 1 (2x0 + k - 1) * k / 2 = N 2x0 = 2N / k - k + 1 x0 * k = N - k * (k - 1) / 2 # assure for divisibility",
"name": "consecutiveNumbersSum",
"signature": "def consecutiveNumbersSum(self, N: int) -> int"
},
{
"doc... | 3 | stack_v2_sparse_classes_30k_train_004205 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def consecutiveNumbersSum(self, N: int) -> int: Arithmetic Array math (x0 + xn) * (xn - x0 + 1) / 2 = N xn = x0 + k - 1 (2x0 + k - 1) * k / 2 = N 2x0 = 2N / k - k + 1 x0 * k = N ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def consecutiveNumbersSum(self, N: int) -> int: Arithmetic Array math (x0 + xn) * (xn - x0 + 1) / 2 = N xn = x0 + k - 1 (2x0 + k - 1) * k / 2 = N 2x0 = 2N / k - k + 1 x0 * k = N ... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Solution:
def consecutiveNumbersSum(self, N: int) -> int:
"""Arithmetic Array math (x0 + xn) * (xn - x0 + 1) / 2 = N xn = x0 + k - 1 (2x0 + k - 1) * k / 2 = N 2x0 = 2N / k - k + 1 x0 * k = N - k * (k - 1) / 2 # assure for divisibility"""
<|body_0|>
def consecutiveNumbersSum_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def consecutiveNumbersSum(self, N: int) -> int:
"""Arithmetic Array math (x0 + xn) * (xn - x0 + 1) / 2 = N xn = x0 + k - 1 (2x0 + k - 1) * k / 2 = N 2x0 = 2N / k - k + 1 x0 * k = N - k * (k - 1) / 2 # assure for divisibility"""
cnt = 0
k = 0
while True:
k ... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetCode/829 Consecutive Numbers Sum.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
ea6e11dac26b8478ad5a12bb1ec2e510980403fa | [
"assert 0 <= beta <= 1, 'beta must be in [0, 1]'\nself.beta = beta\nself.sample_mean = None\nself.precision = None\nsuper(Proposal, self).__init__()",
"rand = np.random.RandomState() if random is None else random\nbeta = kwargs.get('beta', self.beta)\nB, _ = walkers_to_move.shape\nNc, dim = ensemble.shape\nself.s... | <|body_start_0|>
assert 0 <= beta <= 1, 'beta must be in [0, 1]'
self.beta = beta
self.sample_mean = None
self.precision = None
super(Proposal, self).__init__()
<|end_body_0|>
<|body_start_1|>
rand = np.random.RandomState() if random is None else random
beta = kw... | Walk | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Walk:
def __init__(self, beta=0.4, **kwargs):
"""Generate a Gaussian r.v. W_t ~ N(0, C), where C = cov(ensemble) Make a proposal using the strategy: X_{t+1} = mu + sqrt(1 - beta ** 2) (X_t - mu) + beta * W_t, where mu = sample mean"""
<|body_0|>
def propose(self, walkers_to_... | stack_v2_sparse_classes_36k_train_026824 | 1,267 | no_license | [
{
"docstring": "Generate a Gaussian r.v. W_t ~ N(0, C), where C = cov(ensemble) Make a proposal using the strategy: X_{t+1} = mu + sqrt(1 - beta ** 2) (X_t - mu) + beta * W_t, where mu = sample mean",
"name": "__init__",
"signature": "def __init__(self, beta=0.4, **kwargs)"
},
{
"docstring": "wa... | 2 | stack_v2_sparse_classes_30k_train_018923 | Implement the Python class `Walk` described below.
Class description:
Implement the Walk class.
Method signatures and docstrings:
- def __init__(self, beta=0.4, **kwargs): Generate a Gaussian r.v. W_t ~ N(0, C), where C = cov(ensemble) Make a proposal using the strategy: X_{t+1} = mu + sqrt(1 - beta ** 2) (X_t - mu) ... | Implement the Python class `Walk` described below.
Class description:
Implement the Walk class.
Method signatures and docstrings:
- def __init__(self, beta=0.4, **kwargs): Generate a Gaussian r.v. W_t ~ N(0, C), where C = cov(ensemble) Make a proposal using the strategy: X_{t+1} = mu + sqrt(1 - beta ** 2) (X_t - mu) ... | 446023c838ea90df68ddee8108258193e0292bee | <|skeleton|>
class Walk:
def __init__(self, beta=0.4, **kwargs):
"""Generate a Gaussian r.v. W_t ~ N(0, C), where C = cov(ensemble) Make a proposal using the strategy: X_{t+1} = mu + sqrt(1 - beta ** 2) (X_t - mu) + beta * W_t, where mu = sample mean"""
<|body_0|>
def propose(self, walkers_to_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Walk:
def __init__(self, beta=0.4, **kwargs):
"""Generate a Gaussian r.v. W_t ~ N(0, C), where C = cov(ensemble) Make a proposal using the strategy: X_{t+1} = mu + sqrt(1 - beta ** 2) (X_t - mu) + beta * W_t, where mu = sample mean"""
assert 0 <= beta <= 1, 'beta must be in [0, 1]'
sel... | the_stack_v2_python_sparse | ensemble_sampler/proposal/walk.py | JialinMao/pcnemsemble | train | 0 | |
f96ce189551e8151de2b718711e8cdbff120b997 | [
"self.points = points\nxyz_min = numpy.min(points, axis=0) - 0.001\nxyz_max = numpy.max(points, axis=0) + 0.001\nif bb_cuboid:\n diff = max(xyz_max - xyz_min) - (xyz_max - xyz_min)\n xyz_min = xyz_min - diff / 2\n xyz_max = xyz_max + diff / 2\nself.xyz_min = xyz_min\nself.xyz_max = xyz_max\nsegments = []\n... | <|body_start_0|>
self.points = points
xyz_min = numpy.min(points, axis=0) - 0.001
xyz_max = numpy.max(points, axis=0) + 0.001
if bb_cuboid:
diff = max(xyz_max - xyz_min) - (xyz_max - xyz_min)
xyz_min = xyz_min - diff / 2
xyz_max = xyz_max + diff / 2
... | description | VoxelGrid | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VoxelGrid:
"""description"""
def __init__(self, points, x_y_z=(1, 1, 1), bb_cuboid=True, build=True):
"""Parameters ---------- points: (N,3) ndarray The point cloud from wich we want to construct the VoxelGrid. Where N is the number of points in the point cloud and the second dimensi... | stack_v2_sparse_classes_36k_train_026825 | 4,119 | permissive | [
{
"docstring": "Parameters ---------- points: (N,3) ndarray The point cloud from wich we want to construct the VoxelGrid. Where N is the number of points in the point cloud and the second dimension represents the x, y and z coordinates of each point. x_y_z: list The segments in wich each axis will be divided. x... | 3 | stack_v2_sparse_classes_30k_train_004553 | Implement the Python class `VoxelGrid` described below.
Class description:
description
Method signatures and docstrings:
- def __init__(self, points, x_y_z=(1, 1, 1), bb_cuboid=True, build=True): Parameters ---------- points: (N,3) ndarray The point cloud from wich we want to construct the VoxelGrid. Where N is the n... | Implement the Python class `VoxelGrid` described below.
Class description:
description
Method signatures and docstrings:
- def __init__(self, points, x_y_z=(1, 1, 1), bb_cuboid=True, build=True): Parameters ---------- points: (N,3) ndarray The point cloud from wich we want to construct the VoxelGrid. Where N is the n... | 06839b08d8e8f274c02a6bcd31bf1b32d3dc04e4 | <|skeleton|>
class VoxelGrid:
"""description"""
def __init__(self, points, x_y_z=(1, 1, 1), bb_cuboid=True, build=True):
"""Parameters ---------- points: (N,3) ndarray The point cloud from wich we want to construct the VoxelGrid. Where N is the number of points in the point cloud and the second dimensi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VoxelGrid:
"""description"""
def __init__(self, points, x_y_z=(1, 1, 1), bb_cuboid=True, build=True):
"""Parameters ---------- points: (N,3) ndarray The point cloud from wich we want to construct the VoxelGrid. Where N is the number of points in the point cloud and the second dimension represents... | the_stack_v2_python_sparse | neodroidvision/data/synthesis/conversion/mnist/threed/voxel_grid.py | aivclab/vision | train | 1 |
c35db9b2607694455932feda2181ed287fcb476e | [
"def inner_wrapper(wrapped_class: Taskmodel) -> Callable:\n assert task_type not in cls.registry\n cls.registry[task_type] = wrapped_class\n return wrapped_class\nreturn inner_wrapper",
"taskmodel_class = cls.registry[task.TASK_TYPE]\ntaskmodel = taskmodel_class(task, encoder, head, **kwargs)\nreturn tas... | <|body_start_0|>
def inner_wrapper(wrapped_class: Taskmodel) -> Callable:
assert task_type not in cls.registry
cls.registry[task_type] = wrapped_class
return wrapped_class
return inner_wrapper
<|end_body_0|>
<|body_start_1|>
taskmodel_class = cls.registry[tas... | This factory is used to create task models bundling the task, encoder, and task head within the task model. Attributes: registry (dict): Dynamic registry mapping task types to task models | JiantTaskModelFactory | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JiantTaskModelFactory:
"""This factory is used to create task models bundling the task, encoder, and task head within the task model. Attributes: registry (dict): Dynamic registry mapping task types to task models"""
def register(cls, task_type: TaskTypes) -> Callable:
"""Register ta... | stack_v2_sparse_classes_36k_train_026826 | 15,252 | permissive | [
{
"docstring": "Register task_type as a key mapping to a TaskModel Args: task_type (TaskTypes): TaskType key mapping to a BaseHead task head Returns: Callable: inner_wrapper() wrapping TaskModel constructor",
"name": "register",
"signature": "def register(cls, task_type: TaskTypes) -> Callable"
},
{... | 2 | null | Implement the Python class `JiantTaskModelFactory` described below.
Class description:
This factory is used to create task models bundling the task, encoder, and task head within the task model. Attributes: registry (dict): Dynamic registry mapping task types to task models
Method signatures and docstrings:
- def reg... | Implement the Python class `JiantTaskModelFactory` described below.
Class description:
This factory is used to create task models bundling the task, encoder, and task head within the task model. Attributes: registry (dict): Dynamic registry mapping task types to task models
Method signatures and docstrings:
- def reg... | daa5a258e3af5e7503288de8401429eaf3f58e13 | <|skeleton|>
class JiantTaskModelFactory:
"""This factory is used to create task models bundling the task, encoder, and task head within the task model. Attributes: registry (dict): Dynamic registry mapping task types to task models"""
def register(cls, task_type: TaskTypes) -> Callable:
"""Register ta... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JiantTaskModelFactory:
"""This factory is used to create task models bundling the task, encoder, and task head within the task model. Attributes: registry (dict): Dynamic registry mapping task types to task models"""
def register(cls, task_type: TaskTypes) -> Callable:
"""Register task_type as a ... | the_stack_v2_python_sparse | jiant/proj/main/modeling/taskmodels.py | nyu-mll/jiant | train | 1,289 |
a4b197c0124306bd5b75e2d8855cc8d2e2d867a9 | [
"super(DisparateImpactRemover, self).__init__(repair_level=repair_level)\nfrom BlackBoxAuditing.repairers.GeneralRepairer import Repairer\nself.Repairer = Repairer\nif not 0.0 <= repair_level <= 1.0:\n raise ValueError(\"'repair_level' must be between 0.0 and 1.0.\")\nself.repair_level = repair_level\nself.sensi... | <|body_start_0|>
super(DisparateImpactRemover, self).__init__(repair_level=repair_level)
from BlackBoxAuditing.repairers.GeneralRepairer import Repairer
self.Repairer = Repairer
if not 0.0 <= repair_level <= 1.0:
raise ValueError("'repair_level' must be between 0.0 and 1.0.")... | Disparate impact remover is a preprocessing technique that edits feature values increase group fairness while preserving rank-ordering within groups [1]_. References: .. [1] M. Feldman, S. A. Friedler, J. Moeller, C. Scheidegger, and S. Venkatasubramanian, "Certifying and removing disparate impact." ACM SIGKDD Internat... | DisparateImpactRemover | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DisparateImpactRemover:
"""Disparate impact remover is a preprocessing technique that edits feature values increase group fairness while preserving rank-ordering within groups [1]_. References: .. [1] M. Feldman, S. A. Friedler, J. Moeller, C. Scheidegger, and S. Venkatasubramanian, "Certifying a... | stack_v2_sparse_classes_36k_train_026827 | 2,594 | permissive | [
{
"docstring": "Args: repair_level (float): Repair amount. 0.0 is no repair while 1.0 is full repair. sensitive_attribute (str): Single protected attribute with which to do repair.",
"name": "__init__",
"signature": "def __init__(self, repair_level=1.0, sensitive_attribute='')"
},
{
"docstring":... | 2 | stack_v2_sparse_classes_30k_train_000986 | Implement the Python class `DisparateImpactRemover` described below.
Class description:
Disparate impact remover is a preprocessing technique that edits feature values increase group fairness while preserving rank-ordering within groups [1]_. References: .. [1] M. Feldman, S. A. Friedler, J. Moeller, C. Scheidegger, a... | Implement the Python class `DisparateImpactRemover` described below.
Class description:
Disparate impact remover is a preprocessing technique that edits feature values increase group fairness while preserving rank-ordering within groups [1]_. References: .. [1] M. Feldman, S. A. Friedler, J. Moeller, C. Scheidegger, a... | 6f9972e4a7dbca2402f29b86ea67889143dbeb3e | <|skeleton|>
class DisparateImpactRemover:
"""Disparate impact remover is a preprocessing technique that edits feature values increase group fairness while preserving rank-ordering within groups [1]_. References: .. [1] M. Feldman, S. A. Friedler, J. Moeller, C. Scheidegger, and S. Venkatasubramanian, "Certifying a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DisparateImpactRemover:
"""Disparate impact remover is a preprocessing technique that edits feature values increase group fairness while preserving rank-ordering within groups [1]_. References: .. [1] M. Feldman, S. A. Friedler, J. Moeller, C. Scheidegger, and S. Venkatasubramanian, "Certifying and removing d... | the_stack_v2_python_sparse | aif360/algorithms/preprocessing/disparate_impact_remover.py | Trusted-AI/AIF360 | train | 1,157 |
c5bebccb508d183ba2ea4e78b149087e7ab80620 | [
"self.file_name = file_name\nself.parser = Parser.Parser(self.file_name)\nself.binary_lines = None",
"self.parser.line_sectioning()\nself.binary_lines = self.parser.parse()\nself.output_into_file()",
"name = self.file_name.replace('.asm', '')\nname = name + '.hack'\nwith open(name, 'w') as out_file:\n for li... | <|body_start_0|>
self.file_name = file_name
self.parser = Parser.Parser(self.file_name)
self.binary_lines = None
<|end_body_0|>
<|body_start_1|>
self.parser.line_sectioning()
self.binary_lines = self.parser.parse()
self.output_into_file()
<|end_body_1|>
<|body_start_2|>... | a main class to create the file of the hack language translating create a new file and outputs the file | Assembler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Assembler:
"""a main class to create the file of the hack language translating create a new file and outputs the file"""
def __init__(self, file_name):
"""constructor of Assembler object :param file_name: file name of asm file"""
<|body_0|>
def transpiler(self):
... | stack_v2_sparse_classes_36k_train_026828 | 1,964 | no_license | [
{
"docstring": "constructor of Assembler object :param file_name: file name of asm file",
"name": "__init__",
"signature": "def __init__(self, file_name)"
},
{
"docstring": "method of transpiling from ASM to OPCODE. :return: none",
"name": "transpiler",
"signature": "def transpiler(self)... | 3 | stack_v2_sparse_classes_30k_train_018299 | Implement the Python class `Assembler` described below.
Class description:
a main class to create the file of the hack language translating create a new file and outputs the file
Method signatures and docstrings:
- def __init__(self, file_name): constructor of Assembler object :param file_name: file name of asm file
... | Implement the Python class `Assembler` described below.
Class description:
a main class to create the file of the hack language translating create a new file and outputs the file
Method signatures and docstrings:
- def __init__(self, file_name): constructor of Assembler object :param file_name: file name of asm file
... | 6780e523108dccd211be320305d3dfacef7d035e | <|skeleton|>
class Assembler:
"""a main class to create the file of the hack language translating create a new file and outputs the file"""
def __init__(self, file_name):
"""constructor of Assembler object :param file_name: file name of asm file"""
<|body_0|>
def transpiler(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Assembler:
"""a main class to create the file of the hack language translating create a new file and outputs the file"""
def __init__(self, file_name):
"""constructor of Assembler object :param file_name: file name of asm file"""
self.file_name = file_name
self.parser = Parser.Par... | the_stack_v2_python_sparse | 06/Assembler.py | rina-karnauch/NandToTetris | train | 0 |
d472f5576f911296750003c7773aa2cc14b39898 | [
"self.argmap = {}\nself.required_params = []\nself.repeated_params = []\nself.pattern_params = {}\nself.query_params = []\nself.path_params = set()\nself.param_types = {}\nself.enum_params = {}\nself.set_parameters(method_desc)",
"for arg, desc in six.iteritems(method_desc.get('parameters', {})):\n param = key... | <|body_start_0|>
self.argmap = {}
self.required_params = []
self.repeated_params = []
self.pattern_params = {}
self.query_params = []
self.path_params = set()
self.param_types = {}
self.enum_params = {}
self.set_parameters(method_desc)
<|end_body_0... | Represents the parameters associated with a method. Attributes: argmap: Map from method parameter name (string) to query parameter name (string). required_params: List of required parameters (represented by parameter name as string). repeated_params: List of repeated parameters (represented by parameter name as string)... | ResourceMethodParameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourceMethodParameters:
"""Represents the parameters associated with a method. Attributes: argmap: Map from method parameter name (string) to query parameter name (string). required_params: List of required parameters (represented by parameter name as string). repeated_params: List of repeated ... | stack_v2_sparse_classes_36k_train_026829 | 42,994 | permissive | [
{
"docstring": "Constructor for ResourceMethodParameters. Sets default values and defers to set_parameters to populate. Args: method_desc: Dictionary with metadata describing an API method. Value comes from the dictionary of methods stored in the 'methods' key in the deserialized discovery document.",
"name... | 2 | stack_v2_sparse_classes_30k_train_014744 | Implement the Python class `ResourceMethodParameters` described below.
Class description:
Represents the parameters associated with a method. Attributes: argmap: Map from method parameter name (string) to query parameter name (string). required_params: List of required parameters (represented by parameter name as stri... | Implement the Python class `ResourceMethodParameters` described below.
Class description:
Represents the parameters associated with a method. Attributes: argmap: Map from method parameter name (string) to query parameter name (string). required_params: List of required parameters (represented by parameter name as stri... | 975a95032ce5b7012d1772c7f1f5cfe606eae839 | <|skeleton|>
class ResourceMethodParameters:
"""Represents the parameters associated with a method. Attributes: argmap: Map from method parameter name (string) to query parameter name (string). required_params: List of required parameters (represented by parameter name as string). repeated_params: List of repeated ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResourceMethodParameters:
"""Represents the parameters associated with a method. Attributes: argmap: Map from method parameter name (string) to query parameter name (string). required_params: List of required parameters (represented by parameter name as string). repeated_params: List of repeated parameters (r... | the_stack_v2_python_sparse | courses/machine_learning/deepdive2/structured/solutions/serving/application/lib/googleapiclient/discovery.py | GoogleCloudPlatform/training-data-analyst | train | 7,311 |
f3011cd729ef73e504ea6cc26978c97c26795a35 | [
"try:\n skill = skill_fetchers.get_skill_from_model(skill_model)\n skill.validate()\nexcept Exception as e:\n logging.exception(e)\n return result.Err((skill_id, e))\nreturn result.Ok((skill_id, skill))",
"contents_version = skill_model.skill_contents_schema_version\nif contents_version < feconf.CURRE... | <|body_start_0|>
try:
skill = skill_fetchers.get_skill_from_model(skill_model)
skill.validate()
except Exception as e:
logging.exception(e)
return result.Err((skill_id, e))
return result.Ok((skill_id, skill))
<|end_body_0|>
<|body_start_1|>
... | Transform that gets all Skill models, performs migration and filters any error results. | MigrateSkillModels | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MigrateSkillModels:
"""Transform that gets all Skill models, performs migration and filters any error results."""
def _migrate_skill(skill_id: str, skill_model: skill_models.SkillModel) -> result.Result[Tuple[str, skill_domain.Skill], Tuple[str, Exception]]:
"""Migrates skill and tra... | stack_v2_sparse_classes_36k_train_026830 | 14,669 | permissive | [
{
"docstring": "Migrates skill and transform skill model into skill object. Args: skill_id: str. The id of the skill. skill_model: SkillModel. The skill model to migrate. Returns: Result((str, Skill), (str, Exception)). Result containing tuple that consists of skill ID and either skill object or Exception. Skil... | 3 | null | Implement the Python class `MigrateSkillModels` described below.
Class description:
Transform that gets all Skill models, performs migration and filters any error results.
Method signatures and docstrings:
- def _migrate_skill(skill_id: str, skill_model: skill_models.SkillModel) -> result.Result[Tuple[str, skill_doma... | Implement the Python class `MigrateSkillModels` described below.
Class description:
Transform that gets all Skill models, performs migration and filters any error results.
Method signatures and docstrings:
- def _migrate_skill(skill_id: str, skill_model: skill_models.SkillModel) -> result.Result[Tuple[str, skill_doma... | d16fdf23d790eafd63812bd7239532256e30a21d | <|skeleton|>
class MigrateSkillModels:
"""Transform that gets all Skill models, performs migration and filters any error results."""
def _migrate_skill(skill_id: str, skill_model: skill_models.SkillModel) -> result.Result[Tuple[str, skill_domain.Skill], Tuple[str, Exception]]:
"""Migrates skill and tra... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MigrateSkillModels:
"""Transform that gets all Skill models, performs migration and filters any error results."""
def _migrate_skill(skill_id: str, skill_model: skill_models.SkillModel) -> result.Result[Tuple[str, skill_domain.Skill], Tuple[str, Exception]]:
"""Migrates skill and transform skill ... | the_stack_v2_python_sparse | core/jobs/batch_jobs/skill_migration_jobs.py | oppia/oppia | train | 6,172 |
36c7d4420b19009ae678f6f2dd026f86f3e4220c | [
"self.input = ['yo', 'act', 'flop', 'tac', 'foo', 'cat', 'oy', 'olfp']\nself.output = [['yo', 'oy'], ['flop', 'olfp'], ['act', 'tac', 'cat'], ['foo']]\nreturn (self.input, self.output)",
"input_arr, output_arr = self.setUp()\noutput = groupAnagrams(input_arr)\nself.assertEqual(compare_lists(output, output_arr), T... | <|body_start_0|>
self.input = ['yo', 'act', 'flop', 'tac', 'foo', 'cat', 'oy', 'olfp']
self.output = [['yo', 'oy'], ['flop', 'olfp'], ['act', 'tac', 'cat'], ['foo']]
return (self.input, self.output)
<|end_body_0|>
<|body_start_1|>
input_arr, output_arr = self.setUp()
output = gr... | Class with unittests for GroupAnagrams.py | test_GroupAnagrams | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_GroupAnagrams:
"""Class with unittests for GroupAnagrams.py"""
def setUp(self):
"""Sets up input."""
<|body_0|>
def test_ExpectedOutput(self):
"""Checks if returned output is as expected."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self... | stack_v2_sparse_classes_36k_train_026831 | 970 | no_license | [
{
"docstring": "Sets up input.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Checks if returned output is as expected.",
"name": "test_ExpectedOutput",
"signature": "def test_ExpectedOutput(self)"
}
] | 2 | null | Implement the Python class `test_GroupAnagrams` described below.
Class description:
Class with unittests for GroupAnagrams.py
Method signatures and docstrings:
- def setUp(self): Sets up input.
- def test_ExpectedOutput(self): Checks if returned output is as expected. | Implement the Python class `test_GroupAnagrams` described below.
Class description:
Class with unittests for GroupAnagrams.py
Method signatures and docstrings:
- def setUp(self): Sets up input.
- def test_ExpectedOutput(self): Checks if returned output is as expected.
<|skeleton|>
class test_GroupAnagrams:
"""Cl... | 3aa62ad36c3b06b2a3b05f1f8e2a9e21d68b371f | <|skeleton|>
class test_GroupAnagrams:
"""Class with unittests for GroupAnagrams.py"""
def setUp(self):
"""Sets up input."""
<|body_0|>
def test_ExpectedOutput(self):
"""Checks if returned output is as expected."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class test_GroupAnagrams:
"""Class with unittests for GroupAnagrams.py"""
def setUp(self):
"""Sets up input."""
self.input = ['yo', 'act', 'flop', 'tac', 'foo', 'cat', 'oy', 'olfp']
self.output = [['yo', 'oy'], ['flop', 'olfp'], ['act', 'tac', 'cat'], ['foo']]
return (self.input... | the_stack_v2_python_sparse | AlgoExpert_algorithms/Medium/GroupAnagrams/test_GroupAnagrams.py | JakubKazimierski/PythonPortfolio | train | 9 |
a8904f2c319ee5ca143ec31fb7a53c891df28290 | [
"result = {'result': 'NG'}\nctrl_obj = CtrlGroup()\ncontent = ctrl_obj.get_group_members(group_id)\nif content:\n result['result'] = 'OK'\n result['content'] = content\nreturn result",
"json_data = request.get_json(force=True)\nctrl_obj = CtrlGroup()\nresult = {'result': 'NG', 'error': ''}\ntry:\n ctrl_o... | <|body_start_0|>
result = {'result': 'NG'}
ctrl_obj = CtrlGroup()
content = ctrl_obj.get_group_members(group_id)
if content:
result['result'] = 'OK'
result['content'] = content
return result
<|end_body_0|>
<|body_start_1|>
json_data = request.get_... | ApiGroupMembers | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApiGroupMembers:
def get(self, group_id=None):
"""获取组成员信息 :param group_id: :return:"""
<|body_0|>
def post(self):
"""添加组成员 :return:"""
<|body_1|>
def put(self):
"""编辑组成员角色 :return:"""
<|body_2|>
def delete(self, group_id, user_id):
... | stack_v2_sparse_classes_36k_train_026832 | 5,041 | no_license | [
{
"docstring": "获取组成员信息 :param group_id: :return:",
"name": "get",
"signature": "def get(self, group_id=None)"
},
{
"docstring": "添加组成员 :return:",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "编辑组成员角色 :return:",
"name": "put",
"signature": "def put(self... | 4 | stack_v2_sparse_classes_30k_train_013686 | Implement the Python class `ApiGroupMembers` described below.
Class description:
Implement the ApiGroupMembers class.
Method signatures and docstrings:
- def get(self, group_id=None): 获取组成员信息 :param group_id: :return:
- def post(self): 添加组成员 :return:
- def put(self): 编辑组成员角色 :return:
- def delete(self, group_id, user... | Implement the Python class `ApiGroupMembers` described below.
Class description:
Implement the ApiGroupMembers class.
Method signatures and docstrings:
- def get(self, group_id=None): 获取组成员信息 :param group_id: :return:
- def post(self): 添加组成员 :return:
- def put(self): 编辑组成员角色 :return:
- def delete(self, group_id, user... | 64b31e7bdfcb8a4c95f0a8a607f0bcff576cec11 | <|skeleton|>
class ApiGroupMembers:
def get(self, group_id=None):
"""获取组成员信息 :param group_id: :return:"""
<|body_0|>
def post(self):
"""添加组成员 :return:"""
<|body_1|>
def put(self):
"""编辑组成员角色 :return:"""
<|body_2|>
def delete(self, group_id, user_id):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ApiGroupMembers:
def get(self, group_id=None):
"""获取组成员信息 :param group_id: :return:"""
result = {'result': 'NG'}
ctrl_obj = CtrlGroup()
content = ctrl_obj.get_group_members(group_id)
if content:
result['result'] = 'OK'
result['content'] = content... | the_stack_v2_python_sparse | Source/collaboration_2/app/api_1_0/api_group_members.py | lsn1183/web_project | train | 0 | |
fd899f950f1e50bf1718487203b063fd03573ea8 | [
"self.power_off_vm_before_recovery = power_off_vm_before_recovery\nself.power_on_vm_after_recovery = power_on_vm_after_recovery\nself.target_source = target_source\nself.virtual_disk_mappings = virtual_disk_mappings",
"if dictionary is None:\n return None\npower_off_vm_before_recovery = dictionary.get('powerOf... | <|body_start_0|>
self.power_off_vm_before_recovery = power_off_vm_before_recovery
self.power_on_vm_after_recovery = power_on_vm_after_recovery
self.target_source = target_source
self.virtual_disk_mappings = virtual_disk_mappings
<|end_body_0|>
<|body_start_1|>
if dictionary is N... | Implementation of the 'VirtualDiskRestoreResponse' model. Specifies the parameters to recover virtual disks of a vm with full Protection Source. Attributes: power_off_vm_before_recovery (bool): Specifies whether to power off the VM before recovering virtual disks. power_on_vm_after_recovery (bool): Specifies whether to... | VirtualDiskRestoreResponse | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VirtualDiskRestoreResponse:
"""Implementation of the 'VirtualDiskRestoreResponse' model. Specifies the parameters to recover virtual disks of a vm with full Protection Source. Attributes: power_off_vm_before_recovery (bool): Specifies whether to power off the VM before recovering virtual disks. p... | stack_v2_sparse_classes_36k_train_026833 | 3,302 | permissive | [
{
"docstring": "Constructor for the VirtualDiskRestoreResponse class",
"name": "__init__",
"signature": "def __init__(self, power_off_vm_before_recovery=None, power_on_vm_after_recovery=None, target_source=None, virtual_disk_mappings=None)"
},
{
"docstring": "Creates an instance of this model fr... | 2 | null | Implement the Python class `VirtualDiskRestoreResponse` described below.
Class description:
Implementation of the 'VirtualDiskRestoreResponse' model. Specifies the parameters to recover virtual disks of a vm with full Protection Source. Attributes: power_off_vm_before_recovery (bool): Specifies whether to power off th... | Implement the Python class `VirtualDiskRestoreResponse` described below.
Class description:
Implementation of the 'VirtualDiskRestoreResponse' model. Specifies the parameters to recover virtual disks of a vm with full Protection Source. Attributes: power_off_vm_before_recovery (bool): Specifies whether to power off th... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class VirtualDiskRestoreResponse:
"""Implementation of the 'VirtualDiskRestoreResponse' model. Specifies the parameters to recover virtual disks of a vm with full Protection Source. Attributes: power_off_vm_before_recovery (bool): Specifies whether to power off the VM before recovering virtual disks. p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VirtualDiskRestoreResponse:
"""Implementation of the 'VirtualDiskRestoreResponse' model. Specifies the parameters to recover virtual disks of a vm with full Protection Source. Attributes: power_off_vm_before_recovery (bool): Specifies whether to power off the VM before recovering virtual disks. power_on_vm_af... | the_stack_v2_python_sparse | cohesity_management_sdk/models/virtual_disk_restore_response.py | cohesity/management-sdk-python | train | 24 |
d1c764f2c8ad499ee499f9d5c59b0e95e9a63c8d | [
"self.radius = radius\nself.x_center = x_center\nself.y_center = y_center",
"import random\nub = self.radius * self.radius\nxl, xr = (self.x_center - self.radius, self.x_center + self.radius)\nyl, yr = (self.y_center - self.radius, self.y_center + self.radius)\nwhile True:\n x = random.uniform(xl, xr)\n y =... | <|body_start_0|>
self.radius = radius
self.x_center = x_center
self.y_center = y_center
<|end_body_0|>
<|body_start_1|>
import random
ub = self.radius * self.radius
xl, xr = (self.x_center - self.radius, self.x_center + self.radius)
yl, yr = (self.y_center - self... | 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_36k_train_026834 | 851 | 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 | null | 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... | e00cf94c5b86c8cca27e3bee69ad21e727b7679b | <|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_36k | 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]"""
import rand... | the_stack_v2_python_sparse | statistics/prob478.py | binchen15/leet-python | train | 1 | |
b139fca755fec6f99cec0814e5aeeb77d9430818 | [
"ImageProcessor.__init__(self, **kwargs)\nself.sigma = sigma\nself.order = order\nself.mode = mode\nself.cval = cval\nself.truncate = truncate",
"img = image.copy()\nif img.data is None:\n log.warning('No data found in image.')\n return image\nimg.data = gaussian_filter(img.data, self.sigma, order=self.orde... | <|body_start_0|>
ImageProcessor.__init__(self, **kwargs)
self.sigma = sigma
self.order = order
self.mode = mode
self.cval = cval
self.truncate = truncate
<|end_body_0|>
<|body_start_1|>
img = image.copy()
if img.data is None:
log.warning('No d... | smooth an image. | Smooth | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Smooth:
"""smooth an image."""
def __init__(self, sigma: float, order: int=0, mode: str='reflect', cval: float=0.0, truncate: float=4.0, **kwargs: Any):
"""Init a new smoothing pipeline step. Args: binning: Binning to apply to image."""
<|body_0|>
async def __call__(self... | stack_v2_sparse_classes_36k_train_026835 | 1,406 | permissive | [
{
"docstring": "Init a new smoothing pipeline step. Args: binning: Binning to apply to image.",
"name": "__init__",
"signature": "def __init__(self, sigma: float, order: int=0, mode: str='reflect', cval: float=0.0, truncate: float=4.0, **kwargs: Any)"
},
{
"docstring": "Bin an image. Args: image... | 2 | stack_v2_sparse_classes_30k_train_014050 | Implement the Python class `Smooth` described below.
Class description:
smooth an image.
Method signatures and docstrings:
- def __init__(self, sigma: float, order: int=0, mode: str='reflect', cval: float=0.0, truncate: float=4.0, **kwargs: Any): Init a new smoothing pipeline step. Args: binning: Binning to apply to ... | Implement the Python class `Smooth` described below.
Class description:
smooth an image.
Method signatures and docstrings:
- def __init__(self, sigma: float, order: int=0, mode: str='reflect', cval: float=0.0, truncate: float=4.0, **kwargs: Any): Init a new smoothing pipeline step. Args: binning: Binning to apply to ... | 2d7a06e5485b61b6ca7e51d99b08651ea6021086 | <|skeleton|>
class Smooth:
"""smooth an image."""
def __init__(self, sigma: float, order: int=0, mode: str='reflect', cval: float=0.0, truncate: float=4.0, **kwargs: Any):
"""Init a new smoothing pipeline step. Args: binning: Binning to apply to image."""
<|body_0|>
async def __call__(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Smooth:
"""smooth an image."""
def __init__(self, sigma: float, order: int=0, mode: str='reflect', cval: float=0.0, truncate: float=4.0, **kwargs: Any):
"""Init a new smoothing pipeline step. Args: binning: Binning to apply to image."""
ImageProcessor.__init__(self, **kwargs)
self... | the_stack_v2_python_sparse | pyobs/images/processors/misc/smooth.py | pyobs/pyobs-core | train | 9 |
0fce2b0191799408092d7ff9a62a5fe807552d7a | [
"params = dict(((key, val) for key, val in request.QUERY_PARAMS.iteritems()))\nparams['publication_request_id'] = publication_request_id\nform = SingleGetForm(params)\nif not form.is_valid():\n raise BadRequestException()\nreturn Response(form.submit(request))",
"params = dict(((key, val) for key, val in reque... | <|body_start_0|>
params = dict(((key, val) for key, val in request.QUERY_PARAMS.iteritems()))
params['publication_request_id'] = publication_request_id
form = SingleGetForm(params)
if not form.is_valid():
raise BadRequestException()
return Response(form.submit(request... | Class for rendering the view for getting a PublicationRequest, deleting a PublicationRequest and updating a PublicationRequest. | PublicationRequestSingle | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PublicationRequestSingle:
"""Class for rendering the view for getting a PublicationRequest, deleting a PublicationRequest and updating a PublicationRequest."""
def get(self, request, publication_request_id):
"""Method for getting an PublicationRequest."""
<|body_0|>
def ... | stack_v2_sparse_classes_36k_train_026836 | 3,336 | no_license | [
{
"docstring": "Method for getting an PublicationRequest.",
"name": "get",
"signature": "def get(self, request, publication_request_id)"
},
{
"docstring": "Method for updating a PublicationRequest's information.",
"name": "put",
"signature": "def put(self, request, publication_request_id... | 3 | stack_v2_sparse_classes_30k_train_006155 | Implement the Python class `PublicationRequestSingle` described below.
Class description:
Class for rendering the view for getting a PublicationRequest, deleting a PublicationRequest and updating a PublicationRequest.
Method signatures and docstrings:
- def get(self, request, publication_request_id): Method for getti... | Implement the Python class `PublicationRequestSingle` described below.
Class description:
Class for rendering the view for getting a PublicationRequest, deleting a PublicationRequest and updating a PublicationRequest.
Method signatures and docstrings:
- def get(self, request, publication_request_id): Method for getti... | 22c1ce3c5a8e4ed99c2f014672d60ad3c5a4003c | <|skeleton|>
class PublicationRequestSingle:
"""Class for rendering the view for getting a PublicationRequest, deleting a PublicationRequest and updating a PublicationRequest."""
def get(self, request, publication_request_id):
"""Method for getting an PublicationRequest."""
<|body_0|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PublicationRequestSingle:
"""Class for rendering the view for getting a PublicationRequest, deleting a PublicationRequest and updating a PublicationRequest."""
def get(self, request, publication_request_id):
"""Method for getting an PublicationRequest."""
params = dict(((key, val) for key... | the_stack_v2_python_sparse | biodig/rest/v2/PublicationRequests/views.py | asmariyaz23/BioDIG | train | 0 |
3eb30b96aedebe0c424000bf5c963a1d74096b4b | [
"if verbose:\n print('SQL Database type %s verbose=%s' % (db_dict, verbose))\nsuper(SQLPreviousScansTable, self).__init__(db_dict, dbtype, verbose)\nself.connection = None",
"try:\n print('Database characteristics')\n for key in self.db_dict:\n print('%s: %s' % key, self.db_dict[key])\nexcept Val... | <|body_start_0|>
if verbose:
print('SQL Database type %s verbose=%s' % (db_dict, verbose))
super(SQLPreviousScansTable, self).__init__(db_dict, dbtype, verbose)
self.connection = None
<|end_body_0|>
<|body_start_1|>
try:
print('Database characteristics')
... | " Table representing the PreviousScans database table This table supports a single dictionary that contains the data when the table is intialized. | SQLPreviousScansTable | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SQLPreviousScansTable:
"""" Table representing the PreviousScans database table This table supports a single dictionary that contains the data when the table is intialized."""
def __init__(self, db_dict, dbtype, verbose):
"""Pass through to SQL"""
<|body_0|>
def db_info(... | stack_v2_sparse_classes_36k_train_026837 | 5,186 | permissive | [
{
"docstring": "Pass through to SQL",
"name": "__init__",
"signature": "def __init__(self, db_dict, dbtype, verbose)"
},
{
"docstring": "Display the db info and Return info on the database used as a dictionary.",
"name": "db_info",
"signature": "def db_info(self)"
}
] | 2 | null | Implement the Python class `SQLPreviousScansTable` described below.
Class description:
" Table representing the PreviousScans database table This table supports a single dictionary that contains the data when the table is intialized.
Method signatures and docstrings:
- def __init__(self, db_dict, dbtype, verbose): Pa... | Implement the Python class `SQLPreviousScansTable` described below.
Class description:
" Table representing the PreviousScans database table This table supports a single dictionary that contains the data when the table is intialized.
Method signatures and docstrings:
- def __init__(self, db_dict, dbtype, verbose): Pa... | 9c60b3489f02592bd9099b8719ca23ae43a9eaa5 | <|skeleton|>
class SQLPreviousScansTable:
"""" Table representing the PreviousScans database table This table supports a single dictionary that contains the data when the table is intialized."""
def __init__(self, db_dict, dbtype, verbose):
"""Pass through to SQL"""
<|body_0|>
def db_info(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SQLPreviousScansTable:
"""" Table representing the PreviousScans database table This table supports a single dictionary that contains the data when the table is intialized."""
def __init__(self, db_dict, dbtype, verbose):
"""Pass through to SQL"""
if verbose:
print('SQL Databa... | the_stack_v2_python_sparse | smipyping/_previousscanstable.py | KSchopmeyer/smipyping | train | 0 |
95fc48bc12f5746bb3baae844bac2e6f3b3ceedd | [
"self.root = data.getTreeRoot(globs.ITEMS, 'Items global')\nfor item in self.root.getChildren('item'):\n if item.getAttr('id', data.D_STRING) == itemId:\n self.itemNode = item\n break\nelse:\n raise ValueError\nself.pocketId = self.itemNode.getAttr('pocket', data.D_STRING)\nself.name = self.item... | <|body_start_0|>
self.root = data.getTreeRoot(globs.ITEMS, 'Items global')
for item in self.root.getChildren('item'):
if item.getAttr('id', data.D_STRING) == itemId:
self.itemNode = item
break
else:
raise ValueError
self.pocketId = ... | Represents a single item. Note quantity is dealt with by the bag, not the item. | Item | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Item:
"""Represents a single item. Note quantity is dealt with by the bag, not the item."""
def __init__(self, itemId):
"""Create the item from the id string. itemId - the id of the item."""
<|body_0|>
def getImage(self):
"""Get the item's icon image."""
... | stack_v2_sparse_classes_36k_train_026838 | 6,693 | no_license | [
{
"docstring": "Create the item from the id string. itemId - the id of the item.",
"name": "__init__",
"signature": "def __init__(self, itemId)"
},
{
"docstring": "Get the item's icon image.",
"name": "getImage",
"signature": "def getImage(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002813 | Implement the Python class `Item` described below.
Class description:
Represents a single item. Note quantity is dealt with by the bag, not the item.
Method signatures and docstrings:
- def __init__(self, itemId): Create the item from the id string. itemId - the id of the item.
- def getImage(self): Get the item's ic... | Implement the Python class `Item` described below.
Class description:
Represents a single item. Note quantity is dealt with by the bag, not the item.
Method signatures and docstrings:
- def __init__(self, itemId): Create the item from the id string. itemId - the id of the item.
- def getImage(self): Get the item's ic... | 72841fc503c716ac3b524e42f2311cbd9d18a092 | <|skeleton|>
class Item:
"""Represents a single item. Note quantity is dealt with by the bag, not the item."""
def __init__(self, itemId):
"""Create the item from the id string. itemId - the id of the item."""
<|body_0|>
def getImage(self):
"""Get the item's icon image."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Item:
"""Represents a single item. Note quantity is dealt with by the bag, not the item."""
def __init__(self, itemId):
"""Create the item from the id string. itemId - the id of the item."""
self.root = data.getTreeRoot(globs.ITEMS, 'Items global')
for item in self.root.getChildre... | the_stack_v2_python_sparse | eng/items.py | andrew-turner/Ditto | train | 0 |
1f74424865e12a7a5881a723a18462cd130e6aca | [
"length = len(A)\ndp = [set([index]) for index in range(length)]\nfor ind, val in enumerate(A):\n if ind != 0 and len(dp[ind]) < 2:\n continue\n for i in xrange(ind + 1, ind + val + 1):\n if i >= length:\n break\n for item in dp[ind]:\n dp[i].add(item)\nreturn 0 in d... | <|body_start_0|>
length = len(A)
dp = [set([index]) for index in range(length)]
for ind, val in enumerate(A):
if ind != 0 and len(dp[ind]) < 2:
continue
for i in xrange(ind + 1, ind + val + 1):
if i >= length:
break
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canJump_TLE(self, A):
"""dp with data structure. complicated Time Limit Exceeded :param A: a list of integers :return: a boolean"""
<|body_0|>
def canJump_TLE2(self, A):
"""Simplified forward dp to fill True value if can jump O(N^2) Time Limit Exceeds :... | stack_v2_sparse_classes_36k_train_026839 | 2,848 | permissive | [
{
"docstring": "dp with data structure. complicated Time Limit Exceeded :param A: a list of integers :return: a boolean",
"name": "canJump_TLE",
"signature": "def canJump_TLE(self, A)"
},
{
"docstring": "Simplified forward dp to fill True value if can jump O(N^2) Time Limit Exceeds :param A: :re... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump_TLE(self, A): dp with data structure. complicated Time Limit Exceeded :param A: a list of integers :return: a boolean
- def canJump_TLE2(self, A): Simplified forward ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump_TLE(self, A): dp with data structure. complicated Time Limit Exceeded :param A: a list of integers :return: a boolean
- def canJump_TLE2(self, A): Simplified forward ... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class Solution:
def canJump_TLE(self, A):
"""dp with data structure. complicated Time Limit Exceeded :param A: a list of integers :return: a boolean"""
<|body_0|>
def canJump_TLE2(self, A):
"""Simplified forward dp to fill True value if can jump O(N^2) Time Limit Exceeds :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canJump_TLE(self, A):
"""dp with data structure. complicated Time Limit Exceeded :param A: a list of integers :return: a boolean"""
length = len(A)
dp = [set([index]) for index in range(length)]
for ind, val in enumerate(A):
if ind != 0 and len(dp[ind]... | the_stack_v2_python_sparse | 054 Jump Game.py | Aminaba123/LeetCode | train | 1 | |
631be76e304147dd58947c7b755ab8f3b2b7886f | [
"rights = gci_access.GCIChecker(params)\nrights['any_access'] = ['allow']\nnew_params = {}\nnew_params['logic'] = soc.modules.gci.logic.models.student_ranking.logic\nnew_params['rights'] = rights\nnew_params['name'] = 'Student Ranking'\nnew_params['module_name'] = 'student_ranking'\nnew_params['sidebar_grouping'] =... | <|body_start_0|>
rights = gci_access.GCIChecker(params)
rights['any_access'] = ['allow']
new_params = {}
new_params['logic'] = soc.modules.gci.logic.models.student_ranking.logic
new_params['rights'] = rights
new_params['name'] = 'Student Ranking'
new_params['modul... | View methods for the Tasks. | View | [
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class View:
"""View methods for the Tasks."""
def __init__(self, params=None):
"""Defines the fields and methods required for the task View class to provide the user with the necessary views. Params: params: a dict with params for this View"""
<|body_0|>
def showDetails(self, ... | stack_v2_sparse_classes_36k_train_026840 | 4,859 | permissive | [
{
"docstring": "Defines the fields and methods required for the task View class to provide the user with the necessary views. Params: params: a dict with params for this View",
"name": "__init__",
"signature": "def __init__(self, params=None)"
},
{
"docstring": "Shows ranking details for the ent... | 3 | stack_v2_sparse_classes_30k_train_011162 | Implement the Python class `View` described below.
Class description:
View methods for the Tasks.
Method signatures and docstrings:
- def __init__(self, params=None): Defines the fields and methods required for the task View class to provide the user with the necessary views. Params: params: a dict with params for th... | Implement the Python class `View` described below.
Class description:
View methods for the Tasks.
Method signatures and docstrings:
- def __init__(self, params=None): Defines the fields and methods required for the task View class to provide the user with the necessary views. Params: params: a dict with params for th... | 9bd45c168f8ddb5c0e6c04eacdcaeafd61908be7 | <|skeleton|>
class View:
"""View methods for the Tasks."""
def __init__(self, params=None):
"""Defines the fields and methods required for the task View class to provide the user with the necessary views. Params: params: a dict with params for this View"""
<|body_0|>
def showDetails(self, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class View:
"""View methods for the Tasks."""
def __init__(self, params=None):
"""Defines the fields and methods required for the task View class to provide the user with the necessary views. Params: params: a dict with params for this View"""
rights = gci_access.GCIChecker(params)
righ... | the_stack_v2_python_sparse | app/soc/modules/gci/views/models/student_ranking.py | pombredanne/Melange-1 | train | 0 |
7f9be951db40216dbef352b4d1c8c1487bfcec29 | [
"self.threshold = threshold\nself.sampling_method = sampling_method\nself.func_of_freq = func_of_freq\nself.elements = {}",
"if key in self.elements:\n raise ValueError('Only works for aggregated data: repeated key %s' % key)\nscore = self.sampling_method.sampling_score(self.func_of_freq(freq))\nif score < sel... | <|body_start_0|>
self.threshold = threshold
self.sampling_method = sampling_method
self.func_of_freq = func_of_freq
self.elements = {}
<|end_body_0|>
<|body_start_1|>
if key in self.elements:
raise ValueError('Only works for aggregated data: repeated key %s' % key)
... | Implementation of a threshold sampling sketch (without privacy guarantees). Threshold sampling works by computing a random score for each key, and keeping the keys with score below a given threshold (a parameter). The keys that are kept are the sample. The score is determined by the underlying sampling method, e.g., PP... | ThresholdSample | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThresholdSample:
"""Implementation of a threshold sampling sketch (without privacy guarantees). Threshold sampling works by computing a random score for each key, and keeping the keys with score below a given threshold (a parameter). The keys that are kept are the sample. The score is determined ... | stack_v2_sparse_classes_36k_train_026841 | 32,453 | permissive | [
{
"docstring": "Initializes an empty sample. Args: threshold: The sampling threshold sampling_method: A class that provides functions to compute the score and inclusion probability according to the underlying sampling method (e.g., PPSWOR, which is the default value) func_of_freq: The function applied to the fr... | 3 | stack_v2_sparse_classes_30k_train_015119 | Implement the Python class `ThresholdSample` described below.
Class description:
Implementation of a threshold sampling sketch (without privacy guarantees). Threshold sampling works by computing a random score for each key, and keeping the keys with score below a given threshold (a parameter). The keys that are kept a... | Implement the Python class `ThresholdSample` described below.
Class description:
Implementation of a threshold sampling sketch (without privacy guarantees). Threshold sampling works by computing a random score for each key, and keeping the keys with score below a given threshold (a parameter). The keys that are kept a... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class ThresholdSample:
"""Implementation of a threshold sampling sketch (without privacy guarantees). Threshold sampling works by computing a random score for each key, and keeping the keys with score below a given threshold (a parameter). The keys that are kept are the sample. The score is determined ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThresholdSample:
"""Implementation of a threshold sampling sketch (without privacy guarantees). Threshold sampling works by computing a random score for each key, and keeping the keys with score below a given threshold (a parameter). The keys that are kept are the sample. The score is determined by the underl... | the_stack_v2_python_sparse | private_sampling/private_sampling.py | Jimmy-INL/google-research | train | 1 |
ff496719693c73f3a1a7f813f914a864d1dac34f | [
"if isinstance(value, weakref.ReferenceType):\n value = value()\nif not value:\n if not isinstance(client, type):\n self.fdel(client, notify=notify)\n return None\nvalue = weakref.ref(value)\nvalue = super(WeakField, self).fset(client, value, notify=notify)\nreturn value()",
"value = super(WeakFie... | <|body_start_0|>
if isinstance(value, weakref.ReferenceType):
value = value()
if not value:
if not isinstance(client, type):
self.fdel(client, notify=notify)
return None
value = weakref.ref(value)
value = super(WeakField, self).fset(cli... | A Mix-in for fields which stores weak-references to values | WeakField | [
"LicenseRef-scancode-warranty-disclaimer",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-copyleft",
"LGPL-2.1-or-later",
"GPL-3.0-only",
"LGPL-2.0-or-later",
"GPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WeakField:
"""A Mix-in for fields which stores weak-references to values"""
def fset(self, client, value, notify=1):
"""Set the client's value for this property if notify is true send a notification event."""
<|body_0|>
def fget(self, client):
"""Get the client's... | stack_v2_sparse_classes_36k_train_026842 | 13,856 | permissive | [
{
"docstring": "Set the client's value for this property if notify is true send a notification event.",
"name": "fset",
"signature": "def fset(self, client, value, notify=1)"
},
{
"docstring": "Get the client's value for this property if notify is true send a notification event.",
"name": "f... | 2 | null | Implement the Python class `WeakField` described below.
Class description:
A Mix-in for fields which stores weak-references to values
Method signatures and docstrings:
- def fset(self, client, value, notify=1): Set the client's value for this property if notify is true send a notification event.
- def fget(self, clie... | Implement the Python class `WeakField` described below.
Class description:
A Mix-in for fields which stores weak-references to values
Method signatures and docstrings:
- def fset(self, client, value, notify=1): Set the client's value for this property if notify is true send a notification event.
- def fget(self, clie... | 7f600ad153270feff12aa7aa86d7ed0a49ebc71c | <|skeleton|>
class WeakField:
"""A Mix-in for fields which stores weak-references to values"""
def fset(self, client, value, notify=1):
"""Set the client's value for this property if notify is true send a notification event."""
<|body_0|>
def fget(self, client):
"""Get the client's... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WeakField:
"""A Mix-in for fields which stores weak-references to values"""
def fset(self, client, value, notify=1):
"""Set the client's value for this property if notify is true send a notification event."""
if isinstance(value, weakref.ReferenceType):
value = value()
... | the_stack_v2_python_sparse | pythonAnimations/pyOpenGLChess/engineDirectory/oglc-env/lib/python2.7/site-packages/vrml/field.py | alexus37/AugmentedRealityChess | train | 1 |
10dd98eddf26538ad9569eca5759db08478c9224 | [
"threading.Thread.__init__(self)\nself.name = '{} Delta Sync Thread'.format(name)\nself.function_to_thread = function",
"LOGGER.info('Starting %s', self.name)\nself.function_to_thread()\nLOGGER.info('Exiting %s', self.name)"
] | <|body_start_0|>
threading.Thread.__init__(self)
self.name = '{} Delta Sync Thread'.format(name)
self.function_to_thread = function
<|end_body_0|>
<|body_start_1|>
LOGGER.info('Starting %s', self.name)
self.function_to_thread()
LOGGER.info('Exiting %s', self.name)
<|end_... | Custom class that runs a delta sync listener in its thread. | DeltaSyncThread | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeltaSyncThread:
"""Custom class that runs a delta sync listener in its thread."""
def __init__(self, name, function):
"""Initialize the OutboundSyncThread class"""
<|body_0|>
def run(self):
"""Start the OutboundSyncThread"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_026843 | 1,371 | permissive | [
{
"docstring": "Initialize the OutboundSyncThread class",
"name": "__init__",
"signature": "def __init__(self, name, function)"
},
{
"docstring": "Start the OutboundSyncThread",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000781 | Implement the Python class `DeltaSyncThread` described below.
Class description:
Custom class that runs a delta sync listener in its thread.
Method signatures and docstrings:
- def __init__(self, name, function): Initialize the OutboundSyncThread class
- def run(self): Start the OutboundSyncThread | Implement the Python class `DeltaSyncThread` described below.
Class description:
Custom class that runs a delta sync listener in its thread.
Method signatures and docstrings:
- def __init__(self, name, function): Initialize the OutboundSyncThread class
- def run(self): Start the OutboundSyncThread
<|skeleton|>
class... | debcdeecb29f0b403f3d37d25240952441f7238c | <|skeleton|>
class DeltaSyncThread:
"""Custom class that runs a delta sync listener in its thread."""
def __init__(self, name, function):
"""Initialize the OutboundSyncThread class"""
<|body_0|>
def run(self):
"""Start the OutboundSyncThread"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeltaSyncThread:
"""Custom class that runs a delta sync listener in its thread."""
def __init__(self, name, function):
"""Initialize the OutboundSyncThread class"""
threading.Thread.__init__(self)
self.name = '{} Delta Sync Thread'.format(name)
self.function_to_thread = fu... | the_stack_v2_python_sparse | rbac/providers/common/threading.py | tmobile/sawtooth-next-directory | train | 14 |
4dd257af394c62e6124ed5f29860675572b5d6f7 | [
"self.lambda_mixture = 0.0\nself.num_class = 0\nself.likelihood = [[]]\nself.prior = []\nself.vocab = [[]]",
"self.num_class = max(train_label)\nfrequency = [0] * self.num_class\nfor i in train_label:\n frequency[i - 1] += 1\nself.prior = [x / len(train_set) for x in frequency]\nvocab = [[] for _ in range(self... | <|body_start_0|>
self.lambda_mixture = 0.0
self.num_class = 0
self.likelihood = [[]]
self.prior = []
self.vocab = [[]]
<|end_body_0|>
<|body_start_1|>
self.num_class = max(train_label)
frequency = [0] * self.num_class
for i in train_label:
fre... | TextClassifier | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextClassifier:
def __init__(self):
"""Implementation of Naive Bayes for multiclass classification :param lambda_mixture - (Extra Credit) This param controls the proportion of contribution of Bigram and Unigram model in the mixture model. Hard Code the value you find to be most suitable ... | stack_v2_sparse_classes_36k_train_026844 | 4,696 | no_license | [
{
"docstring": "Implementation of Naive Bayes for multiclass classification :param lambda_mixture - (Extra Credit) This param controls the proportion of contribution of Bigram and Unigram model in the mixture model. Hard Code the value you find to be most suitable for your model",
"name": "__init__",
"s... | 3 | stack_v2_sparse_classes_30k_train_015359 | Implement the Python class `TextClassifier` described below.
Class description:
Implement the TextClassifier class.
Method signatures and docstrings:
- def __init__(self): Implementation of Naive Bayes for multiclass classification :param lambda_mixture - (Extra Credit) This param controls the proportion of contribut... | Implement the Python class `TextClassifier` described below.
Class description:
Implement the TextClassifier class.
Method signatures and docstrings:
- def __init__(self): Implementation of Naive Bayes for multiclass classification :param lambda_mixture - (Extra Credit) This param controls the proportion of contribut... | fb48deaa1a05ba9cc60a242b37c727cadf57c377 | <|skeleton|>
class TextClassifier:
def __init__(self):
"""Implementation of Naive Bayes for multiclass classification :param lambda_mixture - (Extra Credit) This param controls the proportion of contribution of Bigram and Unigram model in the mixture model. Hard Code the value you find to be most suitable ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TextClassifier:
def __init__(self):
"""Implementation of Naive Bayes for multiclass classification :param lambda_mixture - (Extra Credit) This param controls the proportion of contribution of Bigram and Unigram model in the mixture model. Hard Code the value you find to be most suitable for your model... | the_stack_v2_python_sparse | AI_ML/CS440_mp3-code/part2/TextClassifier - Copy.py | yxzhang2/Projects | train | 0 | |
5fffc0e0e0930338df0122fe258f0a65a9ee9db2 | [
"super().__init__()\nroot = root or DEFAULT_ROOT\nif keys is None:\n keys = chain(MANIFEST.keys(), PIDMANIFEST.keys())\n if pids is None:\n pids = (literal_eval(ospath.split(i)[1]) for i in iglob(ospath.join(root, PIDROOT, '[1-9]*')))\nLOGGER.debug('keys are %s', keys)\nLOGGER.debug('pids are %s', pids... | <|body_start_0|>
super().__init__()
root = root or DEFAULT_ROOT
if keys is None:
keys = chain(MANIFEST.keys(), PIDMANIFEST.keys())
if pids is None:
pids = (literal_eval(ospath.split(i)[1]) for i in iglob(ospath.join(root, PIDROOT, '[1-9]*')))
LOGGE... | Handle collection of ReadFile objects | Resources | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Resources:
"""Handle collection of ReadFile objects"""
def __init__(self, keys=None, pids=None, root=None):
"""Instantiate ReadFile object :param keys: list of object keys :param pids: list of optional pids"""
<|body_0|>
def read(self):
"""Read data for all keys"... | stack_v2_sparse_classes_36k_train_026845 | 5,968 | permissive | [
{
"docstring": "Instantiate ReadFile object :param keys: list of object keys :param pids: list of optional pids",
"name": "__init__",
"signature": "def __init__(self, keys=None, pids=None, root=None)"
},
{
"docstring": "Read data for all keys",
"name": "read",
"signature": "def read(self... | 3 | null | Implement the Python class `Resources` described below.
Class description:
Handle collection of ReadFile objects
Method signatures and docstrings:
- def __init__(self, keys=None, pids=None, root=None): Instantiate ReadFile object :param keys: list of object keys :param pids: list of optional pids
- def read(self): Re... | Implement the Python class `Resources` described below.
Class description:
Handle collection of ReadFile objects
Method signatures and docstrings:
- def __init__(self, keys=None, pids=None, root=None): Instantiate ReadFile object :param keys: list of object keys :param pids: list of optional pids
- def read(self): Re... | f9d9a75a0a233d2def76b150784108dc453ad9ad | <|skeleton|>
class Resources:
"""Handle collection of ReadFile objects"""
def __init__(self, keys=None, pids=None, root=None):
"""Instantiate ReadFile object :param keys: list of object keys :param pids: list of optional pids"""
<|body_0|>
def read(self):
"""Read data for all keys"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Resources:
"""Handle collection of ReadFile objects"""
def __init__(self, keys=None, pids=None, root=None):
"""Instantiate ReadFile object :param keys: list of object keys :param pids: list of optional pids"""
super().__init__()
root = root or DEFAULT_ROOT
if keys is None:... | the_stack_v2_python_sparse | lnxproc/resources.py | eccles/lnxproc | train | 1 |
76fd700d06256e785b92b531607be26227564104 | [
"try:\n id = kwargs.get('id')\n Order.objects.get(pk=id).delete()\nexcept:\n return Response({'message': '删除失败!'})\nreturn Response({'message': '删除成功!'})",
"try:\n id = kwargs.get('id')\n print(id)\n order = Order.objects.get(pk=id)\n order.order_status = 2\n order.save()\nexcept:\n ret... | <|body_start_0|>
try:
id = kwargs.get('id')
Order.objects.get(pk=id).delete()
except:
return Response({'message': '删除失败!'})
return Response({'message': '删除成功!'})
<|end_body_0|>
<|body_start_1|>
try:
id = kwargs.get('id')
print(... | 删除订单 | DelOrderAPIView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DelOrderAPIView:
"""删除订单"""
def del_order(self, request, *args, **kwargs):
"""删除商品"""
<|body_0|>
def cha_order(self, request, *args, **kwargs):
"""删除商品"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
id = kwargs.get('id')
... | stack_v2_sparse_classes_36k_train_026846 | 2,517 | no_license | [
{
"docstring": "删除商品",
"name": "del_order",
"signature": "def del_order(self, request, *args, **kwargs)"
},
{
"docstring": "删除商品",
"name": "cha_order",
"signature": "def cha_order(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018108 | Implement the Python class `DelOrderAPIView` described below.
Class description:
删除订单
Method signatures and docstrings:
- def del_order(self, request, *args, **kwargs): 删除商品
- def cha_order(self, request, *args, **kwargs): 删除商品 | Implement the Python class `DelOrderAPIView` described below.
Class description:
删除订单
Method signatures and docstrings:
- def del_order(self, request, *args, **kwargs): 删除商品
- def cha_order(self, request, *args, **kwargs): 删除商品
<|skeleton|>
class DelOrderAPIView:
"""删除订单"""
def del_order(self, request, *arg... | 130917424a4c5bb6f5de3193d4091b8e8e01bbff | <|skeleton|>
class DelOrderAPIView:
"""删除订单"""
def del_order(self, request, *args, **kwargs):
"""删除商品"""
<|body_0|>
def cha_order(self, request, *args, **kwargs):
"""删除商品"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DelOrderAPIView:
"""删除订单"""
def del_order(self, request, *args, **kwargs):
"""删除商品"""
try:
id = kwargs.get('id')
Order.objects.get(pk=id).delete()
except:
return Response({'message': '删除失败!'})
return Response({'message': '删除成功!'})
d... | the_stack_v2_python_sparse | edu_api/apps/order/views.py | c-congcong/web_drf_edu | train | 0 |
43e9af6b709cfd66b581d4870a9b72e51ace1d39 | [
"links = response.xpath('//div[@class=\"lc_right\"]/div[@class=\"lcr_bottom\"]/ul/li/a/@href').extract()\nfor link in links:\n base_url = 'http://yyk.99.com.cn' + link\n yield scrapy.Request(base_url, callback=self.parse_item)",
"link_list = response.xpath('//div[@class=\"tablist\"]/ul/li/a/@href').extract(... | <|body_start_0|>
links = response.xpath('//div[@class="lc_right"]/div[@class="lcr_bottom"]/ul/li/a/@href').extract()
for link in links:
base_url = 'http://yyk.99.com.cn' + link
yield scrapy.Request(base_url, callback=self.parse_item)
<|end_body_0|>
<|body_start_1|>
link_... | A99HealthSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class A99HealthSpider:
def parse(self, response):
"""获取到所有省份的url地址"""
<|body_0|>
def parse_item(self, response):
"""获取省里面的全部医院"""
<|body_1|>
def parse_content(self, response):
"""通过xpath获取数据"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_026847 | 3,714 | no_license | [
{
"docstring": "获取到所有省份的url地址",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "获取省里面的全部医院",
"name": "parse_item",
"signature": "def parse_item(self, response)"
},
{
"docstring": "通过xpath获取数据",
"name": "parse_content",
"signature": "def parse_... | 3 | null | Implement the Python class `A99HealthSpider` described below.
Class description:
Implement the A99HealthSpider class.
Method signatures and docstrings:
- def parse(self, response): 获取到所有省份的url地址
- def parse_item(self, response): 获取省里面的全部医院
- def parse_content(self, response): 通过xpath获取数据 | Implement the Python class `A99HealthSpider` described below.
Class description:
Implement the A99HealthSpider class.
Method signatures and docstrings:
- def parse(self, response): 获取到所有省份的url地址
- def parse_item(self, response): 获取省里面的全部医院
- def parse_content(self, response): 通过xpath获取数据
<|skeleton|>
class A99Health... | 441f309c50d28c1a3917bed19321cd5cbe7c2861 | <|skeleton|>
class A99HealthSpider:
def parse(self, response):
"""获取到所有省份的url地址"""
<|body_0|>
def parse_item(self, response):
"""获取省里面的全部医院"""
<|body_1|>
def parse_content(self, response):
"""通过xpath获取数据"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class A99HealthSpider:
def parse(self, response):
"""获取到所有省份的url地址"""
links = response.xpath('//div[@class="lc_right"]/div[@class="lcr_bottom"]/ul/li/a/@href').extract()
for link in links:
base_url = 'http://yyk.99.com.cn' + link
yield scrapy.Request(base_url, callbac... | the_stack_v2_python_sparse | 146_hospital_project/hospital_project/hospital_project/spiders/a99_health.py | wliustc/SpiderS | train | 0 | |
668082819d5e45b2b64110c840fa0dda10db7796 | [
"model = from_state.apps.get_model(app_label, self.name)\nif self.allow_migrate_model(schema_editor.connection.alias, model):\n schema_editor.delete_partitioned_model(model)",
"model = to_state.apps.get_model(app_label, self.name)\nif self.allow_migrate_model(schema_editor.connection.alias, model):\n schema... | <|body_start_0|>
model = from_state.apps.get_model(app_label, self.name)
if self.allow_migrate_model(schema_editor.connection.alias, model):
schema_editor.delete_partitioned_model(model)
<|end_body_0|>
<|body_start_1|>
model = to_state.apps.get_model(app_label, self.name)
if... | Deletes the specified partitioned model. | PostgresDeletePartitionedModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostgresDeletePartitionedModel:
"""Deletes the specified partitioned model."""
def database_forwards(self, app_label, schema_editor, from_state, to_state):
"""Apply this migration operation forwards."""
<|body_0|>
def database_backwards(self, app_label, schema_editor, fr... | stack_v2_sparse_classes_36k_train_026848 | 1,087 | permissive | [
{
"docstring": "Apply this migration operation forwards.",
"name": "database_forwards",
"signature": "def database_forwards(self, app_label, schema_editor, from_state, to_state)"
},
{
"docstring": "Apply this migration operation backwards.",
"name": "database_backwards",
"signature": "de... | 3 | null | Implement the Python class `PostgresDeletePartitionedModel` described below.
Class description:
Deletes the specified partitioned model.
Method signatures and docstrings:
- def database_forwards(self, app_label, schema_editor, from_state, to_state): Apply this migration operation forwards.
- def database_backwards(se... | Implement the Python class `PostgresDeletePartitionedModel` described below.
Class description:
Deletes the specified partitioned model.
Method signatures and docstrings:
- def database_forwards(self, app_label, schema_editor, from_state, to_state): Apply this migration operation forwards.
- def database_backwards(se... | e5503cb3f3c1b7959bd55253d3a79296f4c8f0ef | <|skeleton|>
class PostgresDeletePartitionedModel:
"""Deletes the specified partitioned model."""
def database_forwards(self, app_label, schema_editor, from_state, to_state):
"""Apply this migration operation forwards."""
<|body_0|>
def database_backwards(self, app_label, schema_editor, fr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PostgresDeletePartitionedModel:
"""Deletes the specified partitioned model."""
def database_forwards(self, app_label, schema_editor, from_state, to_state):
"""Apply this migration operation forwards."""
model = from_state.apps.get_model(app_label, self.name)
if self.allow_migrate_... | the_stack_v2_python_sparse | psqlextra/backend/migrations/operations/delete_partitioned_model.py | SectorLabs/django-postgres-extra | train | 645 |
6ba58ca118a0c3ae62235e19c487cebb8bc0d64e | [
"self.cwd = os.getcwd()\nself.songInfo = GetSongInfo(target_path_list)\nself.songer_pic_folder = os.path.join(self.cwd, 'app\\\\resource\\\\Songer Photos')\nself.url = 'https://www.kugou.com/yy/html/search.html#searchType=song&searchKeyWord='",
"with open('app\\\\data\\\\songerInfo.json', encoding='utf-8') as f:\... | <|body_start_0|>
self.cwd = os.getcwd()
self.songInfo = GetSongInfo(target_path_list)
self.songer_pic_folder = os.path.join(self.cwd, 'app\\resource\\Songer Photos')
self.url = 'https://www.kugou.com/yy/html/search.html#searchType=song&searchKeyWord='
<|end_body_0|>
<|body_start_1|>
... | 定义一个从酷狗爬取歌手信息的类 | SongerInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SongerInfo:
"""定义一个从酷狗爬取歌手信息的类"""
def __init__(self, target_path_list: list):
"""初始化属性"""
<|body_0|>
def getSongerInfo(self):
"""开始爬取歌手信息"""
<|body_1|>
def crawlInfo(self, info_dict, url):
"""打开浏览器爬取信息"""
<|body_2|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_026849 | 4,941 | no_license | [
{
"docstring": "初始化属性",
"name": "__init__",
"signature": "def __init__(self, target_path_list: list)"
},
{
"docstring": "开始爬取歌手信息",
"name": "getSongerInfo",
"signature": "def getSongerInfo(self)"
},
{
"docstring": "打开浏览器爬取信息",
"name": "crawlInfo",
"signature": "def crawlI... | 3 | stack_v2_sparse_classes_30k_train_016902 | Implement the Python class `SongerInfo` described below.
Class description:
定义一个从酷狗爬取歌手信息的类
Method signatures and docstrings:
- def __init__(self, target_path_list: list): 初始化属性
- def getSongerInfo(self): 开始爬取歌手信息
- def crawlInfo(self, info_dict, url): 打开浏览器爬取信息 | Implement the Python class `SongerInfo` described below.
Class description:
定义一个从酷狗爬取歌手信息的类
Method signatures and docstrings:
- def __init__(self, target_path_list: list): 初始化属性
- def getSongerInfo(self): 开始爬取歌手信息
- def crawlInfo(self, info_dict, url): 打开浏览器爬取信息
<|skeleton|>
class SongerInfo:
"""定义一个从酷狗爬取歌手信息的类"... | da78c8bba159c67c7a25ba64dae060a577c816e8 | <|skeleton|>
class SongerInfo:
"""定义一个从酷狗爬取歌手信息的类"""
def __init__(self, target_path_list: list):
"""初始化属性"""
<|body_0|>
def getSongerInfo(self):
"""开始爬取歌手信息"""
<|body_1|>
def crawlInfo(self, info_dict, url):
"""打开浏览器爬取信息"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SongerInfo:
"""定义一个从酷狗爬取歌手信息的类"""
def __init__(self, target_path_list: list):
"""初始化属性"""
self.cwd = os.getcwd()
self.songInfo = GetSongInfo(target_path_list)
self.songer_pic_folder = os.path.join(self.cwd, 'app\\resource\\Songer Photos')
self.url = 'https://www.ku... | the_stack_v2_python_sparse | app/View/setting_interface/crawler/get_songer_pic.py | wlmsoft/Groove | train | 0 |
03af4e46b6013cb433ce40a6d99b3ae1beaec82e | [
"args = {'media_type': url[0] if url else None, 'keyword': params.get_string('keyword', u'').split(), 'file_filter': params.get_int('file_filter', None), 'keyword_filter': params.get_string('keyword_filter', u'').split(), 'ordering': params.get_int('ordering', 0), 'since': params.get_int('since', None), 'limit': pa... | <|body_start_0|>
args = {'media_type': url[0] if url else None, 'keyword': params.get_string('keyword', u'').split(), 'file_filter': params.get_int('file_filter', None), 'keyword_filter': params.get_string('keyword_filter', u'').split(), 'ordering': params.get_int('ordering', 0), 'since': params.get_int('since'... | SearchModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchModel:
def _parse_args(self, url, params):
"""Common arguments hanlder. [Arguments] url[0] : string. Search type. keyword : string. Search keyword. file_filter : int string. File filter. keyword_filter : string. Keyword filter. ordering : int. Ordering rule. since : int string. Res... | stack_v2_sparse_classes_36k_train_026850 | 4,317 | no_license | [
{
"docstring": "Common arguments hanlder. [Arguments] url[0] : string. Search type. keyword : string. Search keyword. file_filter : int string. File filter. keyword_filter : string. Keyword filter. ordering : int. Ordering rule. since : int string. Response data start from. limit : int string. Number of respons... | 4 | stack_v2_sparse_classes_30k_train_007658 | Implement the Python class `SearchModel` described below.
Class description:
Implement the SearchModel class.
Method signatures and docstrings:
- def _parse_args(self, url, params): Common arguments hanlder. [Arguments] url[0] : string. Search type. keyword : string. Search keyword. file_filter : int string. File fil... | Implement the Python class `SearchModel` described below.
Class description:
Implement the SearchModel class.
Method signatures and docstrings:
- def _parse_args(self, url, params): Common arguments hanlder. [Arguments] url[0] : string. Search type. keyword : string. Search keyword. file_filter : int string. File fil... | cde458ff8f51fcd2840292274906b43bab6f197e | <|skeleton|>
class SearchModel:
def _parse_args(self, url, params):
"""Common arguments hanlder. [Arguments] url[0] : string. Search type. keyword : string. Search keyword. file_filter : int string. File filter. keyword_filter : string. Keyword filter. ordering : int. Ordering rule. since : int string. Res... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SearchModel:
def _parse_args(self, url, params):
"""Common arguments hanlder. [Arguments] url[0] : string. Search type. keyword : string. Search keyword. file_filter : int string. File filter. keyword_filter : string. Keyword filter. ordering : int. Ordering rule. since : int string. Response data sta... | the_stack_v2_python_sparse | api/app_src/apps/main_server/resource/search/search_model.py | codeguycool/CEC | train | 0 | |
61ae928ced3e9d8b20fc9a06445095a73dec41f2 | [
"super().__init__(**kwargs)\nself.model = None\nself.path = path\nif path != '':\n self.initialize_model()\nself.config = dict()\nself.dimensions = 100",
"try:\n tf.logging.info('FastText model is loading')\n if self.path.endswith('.pkl'):\n self.model = pickle.load(open(self.path, 'rb'))\n els... | <|body_start_0|>
super().__init__(**kwargs)
self.model = None
self.path = path
if path != '':
self.initialize_model()
self.config = dict()
self.dimensions = 100
<|end_body_0|>
<|body_start_1|>
try:
tf.logging.info('FastText model is loadin... | Class to train and use FastText Models | FastTextWrapper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FastTextWrapper:
"""Class to train and use FastText Models"""
def __init__(self, path: str='', **kwargs) -> None:
"""Class to train and use FastText Models :param path: Path to the .joblib dumped model :type path: str :param kwargs:"""
<|body_0|>
def initialize_model(sel... | stack_v2_sparse_classes_36k_train_026851 | 4,638 | no_license | [
{
"docstring": "Class to train and use FastText Models :param path: Path to the .joblib dumped model :type path: str :param kwargs:",
"name": "__init__",
"signature": "def __init__(self, path: str='', **kwargs) -> None"
},
{
"docstring": "Initializes the model by loading it via joblib.load() :pa... | 5 | stack_v2_sparse_classes_30k_train_015546 | Implement the Python class `FastTextWrapper` described below.
Class description:
Class to train and use FastText Models
Method signatures and docstrings:
- def __init__(self, path: str='', **kwargs) -> None: Class to train and use FastText Models :param path: Path to the .joblib dumped model :type path: str :param kw... | Implement the Python class `FastTextWrapper` described below.
Class description:
Class to train and use FastText Models
Method signatures and docstrings:
- def __init__(self, path: str='', **kwargs) -> None: Class to train and use FastText Models :param path: Path to the .joblib dumped model :type path: str :param kw... | 30a3c7e59f195381527aa39f56659a3185c2c8d1 | <|skeleton|>
class FastTextWrapper:
"""Class to train and use FastText Models"""
def __init__(self, path: str='', **kwargs) -> None:
"""Class to train and use FastText Models :param path: Path to the .joblib dumped model :type path: str :param kwargs:"""
<|body_0|>
def initialize_model(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FastTextWrapper:
"""Class to train and use FastText Models"""
def __init__(self, path: str='', **kwargs) -> None:
"""Class to train and use FastText Models :param path: Path to the .joblib dumped model :type path: str :param kwargs:"""
super().__init__(**kwargs)
self.model = None
... | the_stack_v2_python_sparse | rs_helper/core/distributed_models/FastTextWrapper.py | MonteChristo46/Recommender-System | train | 1 |
865a4ed482eecfb7ccb3f284f7e6bd97bc2a6972 | [
"super().__init__()\nself.requires_grad = False\nself._r = 2",
"batch, in_channel, in_height, in_width = x.size()\nout_channel, out_height, out_width = (int(in_channel / self._r ** 2), self._r * in_height, self._r * in_width)\nx1 = x[:, 0:out_channel, :, :] / 2\nx2 = x[:, out_channel:out_channel * 2, :, :] / 2\nx... | <|body_start_0|>
super().__init__()
self.requires_grad = False
self._r = 2
<|end_body_0|>
<|body_start_1|>
batch, in_channel, in_height, in_width = x.size()
out_channel, out_height, out_width = (int(in_channel / self._r ** 2), self._r * in_height, self._r * in_width)
x1 ... | 2D Inverse Wavelet Transform as implemented in [1]_. References ---------- .. [1] Liu, Pengju, et al. “Multi-Level Wavelet-CNN for Image Restoration.” ArXiv:1805.07071 [Cs], May 2018. arXiv.org, http://arxiv.org/abs/1805.07071. | IWT | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IWT:
"""2D Inverse Wavelet Transform as implemented in [1]_. References ---------- .. [1] Liu, Pengju, et al. “Multi-Level Wavelet-CNN for Image Restoration.” ArXiv:1805.07071 [Cs], May 2018. arXiv.org, http://arxiv.org/abs/1805.07071."""
def __init__(self):
"""Inits :class:`IWT`."""... | stack_v2_sparse_classes_36k_train_026852 | 14,137 | permissive | [
{
"docstring": "Inits :class:`IWT`.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Computes IWT(`x`) given tensor `x`. Parameters ---------- x: torch.Tensor Input tensor. Returns ------- h: torch.Tensor IWT of `x`.",
"name": "forward",
"signature": "def forwar... | 2 | stack_v2_sparse_classes_30k_train_006877 | Implement the Python class `IWT` described below.
Class description:
2D Inverse Wavelet Transform as implemented in [1]_. References ---------- .. [1] Liu, Pengju, et al. “Multi-Level Wavelet-CNN for Image Restoration.” ArXiv:1805.07071 [Cs], May 2018. arXiv.org, http://arxiv.org/abs/1805.07071.
Method signatures and... | Implement the Python class `IWT` described below.
Class description:
2D Inverse Wavelet Transform as implemented in [1]_. References ---------- .. [1] Liu, Pengju, et al. “Multi-Level Wavelet-CNN for Image Restoration.” ArXiv:1805.07071 [Cs], May 2018. arXiv.org, http://arxiv.org/abs/1805.07071.
Method signatures and... | 2a4c29342bc52a404aae097bc2654fb4323e1ac8 | <|skeleton|>
class IWT:
"""2D Inverse Wavelet Transform as implemented in [1]_. References ---------- .. [1] Liu, Pengju, et al. “Multi-Level Wavelet-CNN for Image Restoration.” ArXiv:1805.07071 [Cs], May 2018. arXiv.org, http://arxiv.org/abs/1805.07071."""
def __init__(self):
"""Inits :class:`IWT`."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IWT:
"""2D Inverse Wavelet Transform as implemented in [1]_. References ---------- .. [1] Liu, Pengju, et al. “Multi-Level Wavelet-CNN for Image Restoration.” ArXiv:1805.07071 [Cs], May 2018. arXiv.org, http://arxiv.org/abs/1805.07071."""
def __init__(self):
"""Inits :class:`IWT`."""
supe... | the_stack_v2_python_sparse | direct/nn/mwcnn/mwcnn.py | NKI-AI/direct | train | 151 |
07fdf4b40622247a5a0efcdafdc81429cb091e19 | [
"self.disk_blocks = disk_blocks\nself.disk_format = disk_format\nself.disk_partitions = disk_partitions\nself.partition_table_format = partition_table_format\nself.sector_size_bytes = sector_size_bytes\nself.uuid = uuid\nself.vmdk_file_name = vmdk_file_name\nself.vmdk_size_bytes = vmdk_size_bytes",
"if dictionary... | <|body_start_0|>
self.disk_blocks = disk_blocks
self.disk_format = disk_format
self.disk_partitions = disk_partitions
self.partition_table_format = partition_table_format
self.sector_size_bytes = sector_size_bytes
self.uuid = uuid
self.vmdk_file_name = vmdk_file_n... | Implementation of the 'Disk' model. Specifies information about a disk and partitions in a volume. Attributes: disk_blocks (list of DiskBlock): Array of Disk Blocks. Specifies a set of disk blocks by defining the location and offset of disk blocks in a disk. disk_format (DiskFormatEnum): Specifies the format of the vir... | Disk | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Disk:
"""Implementation of the 'Disk' model. Specifies information about a disk and partitions in a volume. Attributes: disk_blocks (list of DiskBlock): Array of Disk Blocks. Specifies a set of disk blocks by defining the location and offset of disk blocks in a disk. disk_format (DiskFormatEnum):... | stack_v2_sparse_classes_36k_train_026853 | 4,974 | permissive | [
{
"docstring": "Constructor for the Disk class",
"name": "__init__",
"signature": "def __init__(self, disk_blocks=None, disk_format=None, disk_partitions=None, partition_table_format=None, sector_size_bytes=None, uuid=None, vmdk_file_name=None, vmdk_size_bytes=None)"
},
{
"docstring": "Creates a... | 2 | null | Implement the Python class `Disk` described below.
Class description:
Implementation of the 'Disk' model. Specifies information about a disk and partitions in a volume. Attributes: disk_blocks (list of DiskBlock): Array of Disk Blocks. Specifies a set of disk blocks by defining the location and offset of disk blocks i... | Implement the Python class `Disk` described below.
Class description:
Implementation of the 'Disk' model. Specifies information about a disk and partitions in a volume. Attributes: disk_blocks (list of DiskBlock): Array of Disk Blocks. Specifies a set of disk blocks by defining the location and offset of disk blocks i... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class Disk:
"""Implementation of the 'Disk' model. Specifies information about a disk and partitions in a volume. Attributes: disk_blocks (list of DiskBlock): Array of Disk Blocks. Specifies a set of disk blocks by defining the location and offset of disk blocks in a disk. disk_format (DiskFormatEnum):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Disk:
"""Implementation of the 'Disk' model. Specifies information about a disk and partitions in a volume. Attributes: disk_blocks (list of DiskBlock): Array of Disk Blocks. Specifies a set of disk blocks by defining the location and offset of disk blocks in a disk. disk_format (DiskFormatEnum): Specifies th... | the_stack_v2_python_sparse | cohesity_management_sdk/models/disk.py | cohesity/management-sdk-python | train | 24 |
73d639bc2d7ea47fbbc59bffd5942a81f8bc90c5 | [
"queue = deque([root])\nresult = []\nwhile queue:\n node = queue.popleft()\n if node:\n queue.extend([node.left, node.right])\n result.append(str(node.val))\n else:\n result.append('#')\nreturn ' '.join(result)",
"if data == '#':\n return None\nnodes = deque(data.split())\nroot = ... | <|body_start_0|>
queue = deque([root])
result = []
while queue:
node = queue.popleft()
if node:
queue.extend([node.left, node.right])
result.append(str(node.val))
else:
result.append('#')
return ' '.join(... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_026854 | 1,931 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_test_000808 | 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:... | 1ca8298361b6a030d2569c06a34d955cc5e4b1bb | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
queue = deque([root])
result = []
while queue:
node = queue.popleft()
if node:
queue.extend([node.left, node.right])
... | the_stack_v2_python_sparse | ch14/saeyoon/ch14_6_saeyoon.py | hyo-eun-kim/algorithm-study | train | 0 | |
1928c24256a534020d0e2d265695991f2f8d49f7 | [
"self._dataset = dataset\nself._train_set = train_set\nself._model = self.__train()",
"class_indices_dict = util.get_class_indices_dict(self._dataset, self._train_set)\nclass_count_dict = util.get_class_count_dict(class_indices_dict)\nclass_prob_dict = {}\nfor class_name in class_count_dict:\n class_prob_dict[... | <|body_start_0|>
self._dataset = dataset
self._train_set = train_set
self._model = self.__train()
<|end_body_0|>
<|body_start_1|>
class_indices_dict = util.get_class_indices_dict(self._dataset, self._train_set)
class_count_dict = util.get_class_count_dict(class_indices_dict)
... | NaiveBayes | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NaiveBayes:
def __init__(self, dataset, train_set):
"""Constructor for a naive bayes model"""
<|body_0|>
def __train(self):
"""Train a given feature table to classify the given classes using naive bayes algorithm."""
<|body_1|>
def classify(self, point):... | stack_v2_sparse_classes_36k_train_026855 | 3,862 | no_license | [
{
"docstring": "Constructor for a naive bayes model",
"name": "__init__",
"signature": "def __init__(self, dataset, train_set)"
},
{
"docstring": "Train a given feature table to classify the given classes using naive bayes algorithm.",
"name": "__train",
"signature": "def __train(self)"
... | 4 | null | Implement the Python class `NaiveBayes` described below.
Class description:
Implement the NaiveBayes class.
Method signatures and docstrings:
- def __init__(self, dataset, train_set): Constructor for a naive bayes model
- def __train(self): Train a given feature table to classify the given classes using naive bayes a... | Implement the Python class `NaiveBayes` described below.
Class description:
Implement the NaiveBayes class.
Method signatures and docstrings:
- def __init__(self, dataset, train_set): Constructor for a naive bayes model
- def __train(self): Train a given feature table to classify the given classes using naive bayes a... | 9ae339f81fc7134ba9058fe975dec9ac7e3aaba4 | <|skeleton|>
class NaiveBayes:
def __init__(self, dataset, train_set):
"""Constructor for a naive bayes model"""
<|body_0|>
def __train(self):
"""Train a given feature table to classify the given classes using naive bayes algorithm."""
<|body_1|>
def classify(self, point):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NaiveBayes:
def __init__(self, dataset, train_set):
"""Constructor for a naive bayes model"""
self._dataset = dataset
self._train_set = train_set
self._model = self.__train()
def __train(self):
"""Train a given feature table to classify the given classes using naiv... | the_stack_v2_python_sparse | Project5/naive_bayes.py | vincy0320/School_Intro_to_ML | train | 0 | |
69ef8b95244ba262646f9a23e85ee544d12ee7ab | [
"self.grammar = cnf_grammar\nself.matrix = []\nself.i = self.k = self.j = 0",
"self.matrix = [None] * length\nfor x in range(0, length):\n self.matrix[x] = [None] * length\nself.i = self.k = self.j = 0",
"self.j += 1\nself.i = self.j - 1\nself.matrix[self.i][self.j] = {}\npossible_tags = self.grammar.product... | <|body_start_0|>
self.grammar = cnf_grammar
self.matrix = []
self.i = self.k = self.j = 0
<|end_body_0|>
<|body_start_1|>
self.matrix = [None] * length
for x in range(0, length):
self.matrix[x] = [None] * length
self.i = self.k = self.j = 0
<|end_body_1|>
<|... | This class parses a given sentence according the the given CNF grammar using a probabilistic CKY algorithm | PCKY | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PCKY:
"""This class parses a given sentence according the the given CNF grammar using a probabilistic CKY algorithm"""
def __init__(self, cnf_grammar):
"""Initialize the class by loading the grammar :param cnf_grammar: the given CNF grammar"""
<|body_0|>
def setup(self, ... | stack_v2_sparse_classes_36k_train_026856 | 5,674 | no_license | [
{
"docstring": "Initialize the class by loading the grammar :param cnf_grammar: the given CNF grammar",
"name": "__init__",
"signature": "def __init__(self, cnf_grammar)"
},
{
"docstring": "Set up the matrix and indices for a new parse :param length: the length of the sentence to parse :return: ... | 5 | stack_v2_sparse_classes_30k_train_007457 | Implement the Python class `PCKY` described below.
Class description:
This class parses a given sentence according the the given CNF grammar using a probabilistic CKY algorithm
Method signatures and docstrings:
- def __init__(self, cnf_grammar): Initialize the class by loading the grammar :param cnf_grammar: the give... | Implement the Python class `PCKY` described below.
Class description:
This class parses a given sentence according the the given CNF grammar using a probabilistic CKY algorithm
Method signatures and docstrings:
- def __init__(self, cnf_grammar): Initialize the class by loading the grammar :param cnf_grammar: the give... | 7af7b357347ed526de7a3d6f16652843d214dcbf | <|skeleton|>
class PCKY:
"""This class parses a given sentence according the the given CNF grammar using a probabilistic CKY algorithm"""
def __init__(self, cnf_grammar):
"""Initialize the class by loading the grammar :param cnf_grammar: the given CNF grammar"""
<|body_0|>
def setup(self, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PCKY:
"""This class parses a given sentence according the the given CNF grammar using a probabilistic CKY algorithm"""
def __init__(self, cnf_grammar):
"""Initialize the class by loading the grammar :param cnf_grammar: the given CNF grammar"""
self.grammar = cnf_grammar
self.matri... | the_stack_v2_python_sparse | Parser/pcky.py | zoew2/Projects | train | 0 |
59fcb5108d5e142fe1aa1b66a1749dd64766d828 | [
"super().__init__()\nself.in_channels = in_channels\nself.out_channels = out_channels\nself.bias = bias\nself.dropout = dropout\nself.pad_type = pad_type\nself.kernel_size = kernel_size\nself.dilation = dilation\nself.stride = stride\nself.activation_fn = pt.ops.mappings.ACTIVATION_FN_MAP[activation_fn]()\nif norm ... | <|body_start_0|>
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.bias = bias
self.dropout = dropout
self.pad_type = pad_type
self.kernel_size = kernel_size
self.dilation = dilation
self.stride = stride
... | simplified version of padertorch.contrib.je.modules.Conv1d #ToDo: replace with JE version when published | Conv1d | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Conv1d:
"""simplified version of padertorch.contrib.je.modules.Conv1d #ToDo: replace with JE version when published"""
def __init__(self, in_channels, out_channels, kernel_size, dropout=0.0, pad_type='both', groups=1, dilation=1, stride=1, bias=True, norm=None, activation_fn='relu'):
... | stack_v2_sparse_classes_36k_train_026857 | 6,500 | permissive | [
{
"docstring": "Args: in_channels: out_channels: kernel_size: dilation: stride: bias: dropout: norm: activation_fn:",
"name": "__init__",
"signature": "def __init__(self, in_channels, out_channels, kernel_size, dropout=0.0, pad_type='both', groups=1, dilation=1, stride=1, bias=True, norm=None, activatio... | 3 | stack_v2_sparse_classes_30k_train_013025 | Implement the Python class `Conv1d` described below.
Class description:
simplified version of padertorch.contrib.je.modules.Conv1d #ToDo: replace with JE version when published
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, kernel_size, dropout=0.0, pad_type='both', groups=1, dilati... | Implement the Python class `Conv1d` described below.
Class description:
simplified version of padertorch.contrib.je.modules.Conv1d #ToDo: replace with JE version when published
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, kernel_size, dropout=0.0, pad_type='both', groups=1, dilati... | 93e18f41447a6833372bf912d49bc60fc441279a | <|skeleton|>
class Conv1d:
"""simplified version of padertorch.contrib.je.modules.Conv1d #ToDo: replace with JE version when published"""
def __init__(self, in_channels, out_channels, kernel_size, dropout=0.0, pad_type='both', groups=1, dilation=1, stride=1, bias=True, norm=None, activation_fn='relu'):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Conv1d:
"""simplified version of padertorch.contrib.je.modules.Conv1d #ToDo: replace with JE version when published"""
def __init__(self, in_channels, out_channels, kernel_size, dropout=0.0, pad_type='both', groups=1, dilation=1, stride=1, bias=True, norm=None, activation_fn='relu'):
"""Args: in_... | the_stack_v2_python_sparse | padertorch/modules/convnet.py | fgnt/padertorch | train | 82 |
41145683fe5c34069af48a96205796310aa0123c | [
"post_list = []\ntry:\n group = await self.application.objects.get(CommunityGroup, id=int(group_id))\n group_member = await self.application.objects.get(CommunityGroupMember, user=self.current_user, community=group, status='agree')\n posts_query = Post.extend()\n c = self.get_argument('c', None)\n if... | <|body_start_0|>
post_list = []
try:
group = await self.application.objects.get(CommunityGroup, id=int(group_id))
group_member = await self.application.objects.get(CommunityGroupMember, user=self.current_user, community=group, status='agree')
posts_query = Post.extend... | 帖子列表,发表帖子 | PostHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostHandler:
"""帖子列表,发表帖子"""
async def get(self, group_id, *args, **kwargs):
"""获取帖子列表信息 :param args: :param kwargs: :return:"""
<|body_0|>
async def post(self, group_id, *args, **kwargs):
"""发表帖子 :param group_id: 发帖的小组id :param args: :param kwargs: :return:"""
... | stack_v2_sparse_classes_36k_train_026858 | 16,600 | no_license | [
{
"docstring": "获取帖子列表信息 :param args: :param kwargs: :return:",
"name": "get",
"signature": "async def get(self, group_id, *args, **kwargs)"
},
{
"docstring": "发表帖子 :param group_id: 发帖的小组id :param args: :param kwargs: :return:",
"name": "post",
"signature": "async def post(self, group_id... | 2 | stack_v2_sparse_classes_30k_train_004891 | Implement the Python class `PostHandler` described below.
Class description:
帖子列表,发表帖子
Method signatures and docstrings:
- async def get(self, group_id, *args, **kwargs): 获取帖子列表信息 :param args: :param kwargs: :return:
- async def post(self, group_id, *args, **kwargs): 发表帖子 :param group_id: 发帖的小组id :param args: :param ... | Implement the Python class `PostHandler` described below.
Class description:
帖子列表,发表帖子
Method signatures and docstrings:
- async def get(self, group_id, *args, **kwargs): 获取帖子列表信息 :param args: :param kwargs: :return:
- async def post(self, group_id, *args, **kwargs): 发表帖子 :param group_id: 发帖的小组id :param args: :param ... | 7ae3bfaef5bffa366ebe11d7af0111a5988bba64 | <|skeleton|>
class PostHandler:
"""帖子列表,发表帖子"""
async def get(self, group_id, *args, **kwargs):
"""获取帖子列表信息 :param args: :param kwargs: :return:"""
<|body_0|>
async def post(self, group_id, *args, **kwargs):
"""发表帖子 :param group_id: 发帖的小组id :param args: :param kwargs: :return:"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PostHandler:
"""帖子列表,发表帖子"""
async def get(self, group_id, *args, **kwargs):
"""获取帖子列表信息 :param args: :param kwargs: :return:"""
post_list = []
try:
group = await self.application.objects.get(CommunityGroup, id=int(group_id))
group_member = await self.appli... | the_stack_v2_python_sparse | Q&A_site/apps/community/handler.py | miniYYan/tornado_web | train | 0 |
c5f22cc721611f155d77c5edc881d06b53255082 | [
"if len(matrix) == 0:\n return matrix\nrow, col = (len(matrix), len(matrix[0]))\narr_x, arr_y = ([], [])\nfor i in range(row):\n if 0 in matrix[i]:\n arr_x.append(i)\n for j in range(col):\n if matrix[i][j] == 0 and j not in arr_y:\n arr_y.append(j)\nfor i in range(row)... | <|body_start_0|>
if len(matrix) == 0:
return matrix
row, col = (len(matrix), len(matrix[0]))
arr_x, arr_y = ([], [])
for i in range(row):
if 0 in matrix[i]:
arr_x.append(i)
for j in range(col):
if matrix[i][j] ==... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def setZeroes1(self, matrix: List[List[int]]) -> None:
"""执行用时 :84 ms, 在所有 Python3 提交中击败了54.93%的用户 内存消耗 :13.8 MB, 在所有 Python3 提交中击败了5.97%的用户 思路:用两个数组分别存储值为零的x,y 时间复杂度:O(MN) 空间复杂度:O(MN) Do not return anything, modify matrix in-place instead."""
<|body_0|>
def setZer... | stack_v2_sparse_classes_36k_train_026859 | 3,882 | no_license | [
{
"docstring": "执行用时 :84 ms, 在所有 Python3 提交中击败了54.93%的用户 内存消耗 :13.8 MB, 在所有 Python3 提交中击败了5.97%的用户 思路:用两个数组分别存储值为零的x,y 时间复杂度:O(MN) 空间复杂度:O(MN) Do not return anything, modify matrix in-place instead.",
"name": "setZeroes1",
"signature": "def setZeroes1(self, matrix: List[List[int]]) -> None"
},
{
... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes1(self, matrix: List[List[int]]) -> None: 执行用时 :84 ms, 在所有 Python3 提交中击败了54.93%的用户 内存消耗 :13.8 MB, 在所有 Python3 提交中击败了5.97%的用户 思路:用两个数组分别存储值为零的x,y 时间复杂度:O(MN) 空间复杂度:O(... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes1(self, matrix: List[List[int]]) -> None: 执行用时 :84 ms, 在所有 Python3 提交中击败了54.93%的用户 内存消耗 :13.8 MB, 在所有 Python3 提交中击败了5.97%的用户 思路:用两个数组分别存储值为零的x,y 时间复杂度:O(MN) 空间复杂度:O(... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def setZeroes1(self, matrix: List[List[int]]) -> None:
"""执行用时 :84 ms, 在所有 Python3 提交中击败了54.93%的用户 内存消耗 :13.8 MB, 在所有 Python3 提交中击败了5.97%的用户 思路:用两个数组分别存储值为零的x,y 时间复杂度:O(MN) 空间复杂度:O(MN) Do not return anything, modify matrix in-place instead."""
<|body_0|>
def setZer... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def setZeroes1(self, matrix: List[List[int]]) -> None:
"""执行用时 :84 ms, 在所有 Python3 提交中击败了54.93%的用户 内存消耗 :13.8 MB, 在所有 Python3 提交中击败了5.97%的用户 思路:用两个数组分别存储值为零的x,y 时间复杂度:O(MN) 空间复杂度:O(MN) Do not return anything, modify matrix in-place instead."""
if len(matrix) == 0:
return ... | the_stack_v2_python_sparse | LeetCode/数组/73. Set Matrix Zeroes.py | yiming1012/MyLeetCode | train | 2 | |
a538932b3c5cca46a57b1e0ce829a20522252fb4 | [
"pre = None\nwhile head:\n tmp = head.next\n head.next = pre\n pre = head\n head = tmp\nreturn pre",
"if not head or not head.next:\n return head\nnew_head = self.reverseList(head.next)\nhead.next.next = head\nhead.next = None\nreturn new_head"
] | <|body_start_0|>
pre = None
while head:
tmp = head.next
head.next = pre
pre = head
head = tmp
return pre
<|end_body_0|>
<|body_start_1|>
if not head or not head.next:
return head
new_head = self.reverseList(head.next)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList1(self, head: ListNode) -> ListNode:
"""非递归: 从头结点开始反转,头结点的next变成None,最后一次while循环反转尾结点,之后head变成head.next为None,所以返回pre结点。"""
<|body_0|>
def reverseList(self, head: ListNode) -> ListNode:
"""递归: 递归到尾结的前一个结点,每次反转当前结点的next结点,next结点指向head,head指向Non... | stack_v2_sparse_classes_36k_train_026860 | 1,778 | no_license | [
{
"docstring": "非递归: 从头结点开始反转,头结点的next变成None,最后一次while循环反转尾结点,之后head变成head.next为None,所以返回pre结点。",
"name": "reverseList1",
"signature": "def reverseList1(self, head: ListNode) -> ListNode"
},
{
"docstring": "递归: 递归到尾结的前一个结点,每次反转当前结点的next结点,next结点指向head,head指向None。",
"name": "reverseList",
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList1(self, head: ListNode) -> ListNode: 非递归: 从头结点开始反转,头结点的next变成None,最后一次while循环反转尾结点,之后head变成head.next为None,所以返回pre结点。
- def reverseList(self, head: ListNode) -> Lis... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList1(self, head: ListNode) -> ListNode: 非递归: 从头结点开始反转,头结点的next变成None,最后一次while循环反转尾结点,之后head变成head.next为None,所以返回pre结点。
- def reverseList(self, head: ListNode) -> Lis... | 2bbb1640589aab34f2bc42489283033cc11fb885 | <|skeleton|>
class Solution:
def reverseList1(self, head: ListNode) -> ListNode:
"""非递归: 从头结点开始反转,头结点的next变成None,最后一次while循环反转尾结点,之后head变成head.next为None,所以返回pre结点。"""
<|body_0|>
def reverseList(self, head: ListNode) -> ListNode:
"""递归: 递归到尾结的前一个结点,每次反转当前结点的next结点,next结点指向head,head指向Non... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseList1(self, head: ListNode) -> ListNode:
"""非递归: 从头结点开始反转,头结点的next变成None,最后一次while循环反转尾结点,之后head变成head.next为None,所以返回pre结点。"""
pre = None
while head:
tmp = head.next
head.next = pre
pre = head
head = tmp
retur... | the_stack_v2_python_sparse | 206_reverse-linked-list.py | helloocc/algorithm | train | 1 | |
8ef76ee55021915956e251679d57339834e34733 | [
"n1, n2 = (len(nums1), len(nums2))\nleft, right = ((n1 + n2 + 1) // 2, (n1 + n2 + 2) // 2)\nreturn (self.findKthSortedArrays(nums1, 0, nums2, 0, left) + self.findKthSortedArrays(nums1, 0, nums2, 0, right)) / 2",
"if s1 >= len(nums1):\n return nums2[s2 + k - 1]\nif s2 >= len(nums2):\n return nums1[s1 + k - 1... | <|body_start_0|>
n1, n2 = (len(nums1), len(nums2))
left, right = ((n1 + n2 + 1) // 2, (n1 + n2 + 2) // 2)
return (self.findKthSortedArrays(nums1, 0, nums2, 0, left) + self.findKthSortedArrays(nums1, 0, nums2, 0, right)) / 2
<|end_body_0|>
<|body_start_1|>
if s1 >= len(nums1):
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
<|body_0|>
def findKthSortedArrays(self, nums1, s1, nums2, s2, k):
""":type nums1: List[int] :type s1: int :type nums2: List[int] :type s2: int... | stack_v2_sparse_classes_36k_train_026861 | 1,422 | permissive | [
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: float",
"name": "findMedianSortedArrays",
"signature": "def findMedianSortedArrays(self, nums1, nums2)"
},
{
"docstring": ":type nums1: List[int] :type s1: int :type nums2: List[int] :type s2: int :type k: int :rtype: float",
... | 2 | stack_v2_sparse_classes_30k_train_021433 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMedianSortedArrays(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: float
- def findKthSortedArrays(self, nums1, s1, nums2, s2, k): :type nums1:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMedianSortedArrays(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: float
- def findKthSortedArrays(self, nums1, s1, nums2, s2, k): :type nums1:... | cb70ca87aa4604d1aec83d4224b3489eacebba75 | <|skeleton|>
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
<|body_0|>
def findKthSortedArrays(self, nums1, s1, nums2, s2, k):
""":type nums1: List[int] :type s1: int :type nums2: List[int] :type s2: int... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
n1, n2 = (len(nums1), len(nums2))
left, right = ((n1 + n2 + 1) // 2, (n1 + n2 + 2) // 2)
return (self.findKthSortedArrays(nums1, 0, nums2, 0, left) + self... | the_stack_v2_python_sparse | LeetCode/Python3/0004._Median_of_Two_Sorted_Arrays.py | icgw/practice | train | 1 | |
14ae5040f647c5c2727a54de11be143983505526 | [
"if self.signal_type not in ['analog', 'digital']:\n raise ValueError(f'{self.signal_type} is an invalid signal type.')\nself.units = U_(self.units)",
"if self.data is None:\n raise ValueError('This signal has no data that can be plotted.')\nreturn self.data.plot(time=time, axes=axes, data_name=data_name, t... | <|body_start_0|>
if self.signal_type not in ['analog', 'digital']:
raise ValueError(f'{self.signal_type} is an invalid signal type.')
self.units = U_(self.units)
<|end_body_0|>
<|body_start_1|>
if self.data is None:
raise ValueError('This signal has no data that can be p... | Simple dataclass implementation for measurement signals. | Signal | [
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Signal:
"""Simple dataclass implementation for measurement signals."""
def __post_init__(self):
"""Perform some checks after construction."""
<|body_0|>
def plot(self, time: Union[TimedeltaIndex, Quantity]=None, axes: matplotlib.axes.Axes=None, data_name: str='values', t... | stack_v2_sparse_classes_36k_train_026862 | 37,433 | permissive | [
{
"docstring": "Perform some checks after construction.",
"name": "__post_init__",
"signature": "def __post_init__(self)"
},
{
"docstring": "Plot the time dependent data of the `Signal`. Parameters ---------- time : The points in time that should be plotted. This is an optional parameter for dis... | 2 | null | Implement the Python class `Signal` described below.
Class description:
Simple dataclass implementation for measurement signals.
Method signatures and docstrings:
- def __post_init__(self): Perform some checks after construction.
- def plot(self, time: Union[TimedeltaIndex, Quantity]=None, axes: matplotlib.axes.Axes=... | Implement the Python class `Signal` described below.
Class description:
Simple dataclass implementation for measurement signals.
Method signatures and docstrings:
- def __post_init__(self): Perform some checks after construction.
- def plot(self, time: Union[TimedeltaIndex, Quantity]=None, axes: matplotlib.axes.Axes=... | 7bc16a196ee669822f3663f3c7a08f6bbd0c76d5 | <|skeleton|>
class Signal:
"""Simple dataclass implementation for measurement signals."""
def __post_init__(self):
"""Perform some checks after construction."""
<|body_0|>
def plot(self, time: Union[TimedeltaIndex, Quantity]=None, axes: matplotlib.axes.Axes=None, data_name: str='values', t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Signal:
"""Simple dataclass implementation for measurement signals."""
def __post_init__(self):
"""Perform some checks after construction."""
if self.signal_type not in ['analog', 'digital']:
raise ValueError(f'{self.signal_type} is an invalid signal type.')
self.units... | the_stack_v2_python_sparse | weldx/measurement.py | BAMWelDX/weldx | train | 20 |
5b438eb08862e916099a0a789fa411f3c93badb8 | [
"def preorder(root):\n res = []\n if root:\n res += [str(root.val)]\n res += preorder(root.left)\n res += preorder(root.right)\n return res\nreturn ','.join(preorder(root))",
"if not data:\n return None\n\ndef build_tree(pre_o, in_o):\n if not pre_o:\n return None\n m... | <|body_start_0|>
def preorder(root):
res = []
if root:
res += [str(root.val)]
res += preorder(root.left)
res += preorder(root.right)
return res
return ','.join(preorder(root))
<|end_body_0|>
<|body_start_1|>
if ... | 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|>
def preorder(r... | stack_v2_sparse_classes_36k_train_026863 | 1,118 | 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 | stack_v2_sparse_classes_30k_train_000389 | 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... | 33eb204b1c7229ecb42651b17287d39164967e44 | <|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_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
def preorder(root):
res = []
if root:
res += [str(root.val)]
res += preorder(root.left)
res += preorder(root.right)
re... | the_stack_v2_python_sparse | Binary_tree/449. Serialize and Deserialize BST.py | WujiaShi/Leetcode | train | 0 | |
7387d1184e2af209b64de27c7b1ae1e1ed6378bc | [
"for i in range(1, len(w)):\n w[i] += w[i - 1]\nself.w = w",
"rand = random.randint(1, self.w[-1])\ns, e = (0, len(self.w) - 1)\nwhile s + 1 < e:\n m = s + (e - s) // 2\n if self.w[m] > rand:\n e = m\n else:\n s = m\nif self.w[s] >= rand:\n return s\nreturn e"
] | <|body_start_0|>
for i in range(1, len(w)):
w[i] += w[i - 1]
self.w = w
<|end_body_0|>
<|body_start_1|>
rand = random.randint(1, self.w[-1])
s, e = (0, len(self.w) - 1)
while s + 1 < e:
m = s + (e - s) // 2
if self.w[m] > rand:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for i in range(1, len(w)):
w[i] += w[i - 1]
self.w = w
<|end_body_0|>
<|bod... | stack_v2_sparse_classes_36k_train_026864 | 679 | no_license | [
{
"docstring": ":type w: List[int]",
"name": "__init__",
"signature": "def __init__(self, w)"
},
{
"docstring": ":rtype: int",
"name": "pickIndex",
"signature": "def pickIndex(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021473 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int
<|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|... | 542c99e038d21429853515f62af51a77deaa4d9c | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, w):
""":type w: List[int]"""
for i in range(1, len(w)):
w[i] += w[i - 1]
self.w = w
def pickIndex(self):
""":rtype: int"""
rand = random.randint(1, self.w[-1])
s, e = (0, len(self.w) - 1)
while s + 1 < e:
... | the_stack_v2_python_sparse | random-pick-with-weight/random-pick-with-weight.py | niufenjujuexianhua/Leetcode | train | 0 | |
ff13de9afacbd8ff777b7fe3cc68f692e1b77d96 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn MediaStream()",
"from .media_direction import MediaDirection\nfrom .modality import Modality\nfrom .media_direction import MediaDirection\nfrom .modality import Modality\nfields: Dict[str, Callable[[Any], None]] = {'direction': lambda ... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return MediaStream()
<|end_body_0|>
<|body_start_1|>
from .media_direction import MediaDirection
from .modality import Modality
from .media_direction import MediaDirection
from ... | MediaStream | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MediaStream:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MediaStream:
"""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: Me... | stack_v2_sparse_classes_36k_train_026865 | 3,593 | 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: MediaStream",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(p... | 3 | null | Implement the Python class `MediaStream` described below.
Class description:
Implement the MediaStream class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MediaStream: Creates a new instance of the appropriate class based on discriminator value Args:... | Implement the Python class `MediaStream` described below.
Class description:
Implement the MediaStream class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MediaStream: Creates a new instance of the appropriate class based on discriminator value Args:... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class MediaStream:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MediaStream:
"""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: Me... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MediaStream:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> MediaStream:
"""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: MediaStream"""
... | the_stack_v2_python_sparse | msgraph/generated/models/media_stream.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
62f3ee17d2eaf93ceb22cb0f5ff9e4471cbe2acd | [
"group = None\nitem = entry\nif isinstance(entry, collections.Sequence) and (not isinstance(entry, six.string_types)):\n entry_length = len(entry)\n if all((isinstance(el, list) for el in entry)) and entry_length > 1:\n group, item = entry[0:2]\n return ((group, item),)\n elif all((isinstance... | <|body_start_0|>
group = None
item = entry
if isinstance(entry, collections.Sequence) and (not isinstance(entry, six.string_types)):
entry_length = len(entry)
if all((isinstance(el, list) for el in entry)) and entry_length > 1:
group, item = entry[0:2]
... | View mixin for grouped options. | Select2GroupListView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Select2GroupListView:
"""View mixin for grouped options."""
def get_item_as_group(self, entry):
"""Return the item with its group."""
<|body_0|>
def get(self, request, *args, **kwargs):
"""Return option list with children(s) json response."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_026866 | 10,116 | permissive | [
{
"docstring": "Return the item with its group.",
"name": "get_item_as_group",
"signature": "def get_item_as_group(self, entry)"
},
{
"docstring": "Return option list with children(s) json response.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019003 | Implement the Python class `Select2GroupListView` described below.
Class description:
View mixin for grouped options.
Method signatures and docstrings:
- def get_item_as_group(self, entry): Return the item with its group.
- def get(self, request, *args, **kwargs): Return option list with children(s) json response. | Implement the Python class `Select2GroupListView` described below.
Class description:
View mixin for grouped options.
Method signatures and docstrings:
- def get_item_as_group(self, entry): Return the item with its group.
- def get(self, request, *args, **kwargs): Return option list with children(s) json response.
<... | 0ffcc7c52edbab21153de458dbbb7fbcd706c17e | <|skeleton|>
class Select2GroupListView:
"""View mixin for grouped options."""
def get_item_as_group(self, entry):
"""Return the item with its group."""
<|body_0|>
def get(self, request, *args, **kwargs):
"""Return option list with children(s) json response."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Select2GroupListView:
"""View mixin for grouped options."""
def get_item_as_group(self, entry):
"""Return the item with its group."""
group = None
item = entry
if isinstance(entry, collections.Sequence) and (not isinstance(entry, six.string_types)):
entry_lengt... | the_stack_v2_python_sparse | src/dal_select2/views.py | HelloWatt/django-autocomplete-light | train | 0 |
a7bf9580e8f5b8118276c2adea987f196dd59018 | [
"show_uncategorized = request.GET.get('show_uncategorized', False)\nif show_uncategorized is True or show_uncategorized == 'true':\n return True\nreturn False",
"stats_datasets = StatsMakerDataverses(**request.GET.dict())\nif self.is_show_uncategorized(request):\n exclude_uncategorized = False\nelse:\n e... | <|body_start_0|>
show_uncategorized = request.GET.get('show_uncategorized', False)
if show_uncategorized is True or show_uncategorized == 'true':
return True
return False
<|end_body_0|>
<|body_start_1|>
stats_datasets = StatsMakerDataverses(**request.GET.dict())
if s... | DataverseTypeCounts | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataverseTypeCounts:
def is_show_uncategorized(self, request):
"""Return the result of the "?show_uncategorized" query string param"""
<|body_0|>
def get_stats_result(self, request):
"""Return the StatsResult object for this statistic"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k_train_026867 | 6,085 | no_license | [
{
"docstring": "Return the result of the \"?show_uncategorized\" query string param",
"name": "is_show_uncategorized",
"signature": "def is_show_uncategorized(self, request)"
},
{
"docstring": "Return the StatsResult object for this statistic",
"name": "get_stats_result",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_013295 | Implement the Python class `DataverseTypeCounts` described below.
Class description:
Implement the DataverseTypeCounts class.
Method signatures and docstrings:
- def is_show_uncategorized(self, request): Return the result of the "?show_uncategorized" query string param
- def get_stats_result(self, request): Return th... | Implement the Python class `DataverseTypeCounts` described below.
Class description:
Implement the DataverseTypeCounts class.
Method signatures and docstrings:
- def is_show_uncategorized(self, request): Return the result of the "?show_uncategorized" query string param
- def get_stats_result(self, request): Return th... | 2a17e5ba918d6d1c7d38c192e0504e6cd96b32d2 | <|skeleton|>
class DataverseTypeCounts:
def is_show_uncategorized(self, request):
"""Return the result of the "?show_uncategorized" query string param"""
<|body_0|>
def get_stats_result(self, request):
"""Return the StatsResult object for this statistic"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataverseTypeCounts:
def is_show_uncategorized(self, request):
"""Return the result of the "?show_uncategorized" query string param"""
show_uncategorized = request.GET.get('show_uncategorized', False)
if show_uncategorized is True or show_uncategorized == 'true':
return Tru... | the_stack_v2_python_sparse | dv_apps/metrics/stats_views_dataverses.py | IQSS/miniverse | train | 3 | |
c3bf65507e20cdc06384ffb9a8e4fc478664b919 | [
"super(CohorteBoot, self).__init__()\nself._http = None\nself._broker = None\nself._sender = None\nself._timeout = 5.0",
"environment = self.setup_environment(configuration)\nargs = [sys.executable]\ninterpreter_args = configuration.get('boot', {}).get('boot_args')\nif interpreter_args:\n if type(interpreter_a... | <|body_start_0|>
super(CohorteBoot, self).__init__()
self._http = None
self._broker = None
self._sender = None
self._timeout = 5.0
<|end_body_0|>
<|body_start_1|>
environment = self.setup_environment(configuration)
args = [sys.executable]
interpreter_args... | Isolate starter using the Cohorte boot script | CohorteBoot | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CohorteBoot:
"""Isolate starter using the Cohorte boot script"""
def __init__(self):
"""Sets up members"""
<|body_0|>
def _run_boot_script(self, working_directory, configuration, config_broker_url, state_updater_url, looper_name=None, forker_http_port=None):
"""R... | stack_v2_sparse_classes_36k_train_026868 | 9,123 | permissive | [
{
"docstring": "Sets up members",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Runs the boot script in a new process :param working_directory: Isolate working directory (must exist) :param configuration: Isolate configuration dictionary :param config_broker_url: URL t... | 4 | null | Implement the Python class `CohorteBoot` described below.
Class description:
Isolate starter using the Cohorte boot script
Method signatures and docstrings:
- def __init__(self): Sets up members
- def _run_boot_script(self, working_directory, configuration, config_broker_url, state_updater_url, looper_name=None, fork... | Implement the Python class `CohorteBoot` described below.
Class description:
Isolate starter using the Cohorte boot script
Method signatures and docstrings:
- def __init__(self): Sets up members
- def _run_boot_script(self, working_directory, configuration, config_broker_url, state_updater_url, looper_name=None, fork... | 686556cdde20beba77ae202de9969be46feed5e2 | <|skeleton|>
class CohorteBoot:
"""Isolate starter using the Cohorte boot script"""
def __init__(self):
"""Sets up members"""
<|body_0|>
def _run_boot_script(self, working_directory, configuration, config_broker_url, state_updater_url, looper_name=None, forker_http_port=None):
"""R... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CohorteBoot:
"""Isolate starter using the Cohorte boot script"""
def __init__(self):
"""Sets up members"""
super(CohorteBoot, self).__init__()
self._http = None
self._broker = None
self._sender = None
self._timeout = 5.0
def _run_boot_script(self, work... | the_stack_v2_python_sparse | python/cohorte/forker/starters/cohorte_boot.py | cohorte/cohorte-runtime | train | 3 |
cc31aba5b664993468fc4c55dbafdfa022526468 | [
"if not root or not p or (not q):\n return None\nif root == p or root == q:\n return root\nif self.contains(root.left, p) and self.contains(root.left, q):\n return self.lowestCommonAncestor(root.left, p, q)\nif self.contains(root.right, p) and self.contains(root.right, q):\n return self.lowestCommonAnce... | <|body_start_0|>
if not root or not p or (not q):
return None
if root == p or root == q:
return root
if self.contains(root.left, p) and self.contains(root.left, q):
return self.lowestCommonAncestor(root.left, p, q)
if self.contains(root.right, p) and s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode"""
<|body_0|>
def contains(self, root, node):
"""does tree root contains node?"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_026869 | 5,241 | no_license | [
{
"docstring": ":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode",
"name": "lowestCommonAncestor",
"signature": "def lowestCommonAncestor(self, root, p, q)"
},
{
"docstring": "does tree root contains node?",
"name": "contains",
"signature": "def contains(self, ro... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root, p, q): :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode
- def contains(self, root, node): does tree root contains no... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root, p, q): :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode
- def contains(self, root, node): does tree root contains no... | e00cf94c5b86c8cca27e3bee69ad21e727b7679b | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode"""
<|body_0|>
def contains(self, root, node):
"""does tree root contains node?"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode"""
if not root or not p or (not q):
return None
if root == p or root == q:
return root
if self.contains(root.left, p) and s... | the_stack_v2_python_sparse | tree/prob236.py | binchen15/leet-python | train | 1 | |
46d107c6f69a2034c9e4829373205d80ba3843b9 | [
"self.policy_store = PolicyStore()\nself.service_store = {}\nfrom ranger_performance_tool import perf_globals\nenabled_services = perf_globals.CONFIG_READER.get_config_value('secondary', 'enabled_services')\nservice_type_mapping = perf_globals.CONFIG_READER.get_config_value('secondary', 'service_type_mapping')\nfor... | <|body_start_0|>
self.policy_store = PolicyStore()
self.service_store = {}
from ranger_performance_tool import perf_globals
enabled_services = perf_globals.CONFIG_READER.get_config_value('secondary', 'enabled_services')
service_type_mapping = perf_globals.CONFIG_READER.get_config... | Primary class to connect object stores to the Ranger API Attributes ---------- service_store : dict Mapping of service type to service store objects. Add new service names here if required or unsupported. policy_store: PolicyStore object to create objects associated with policy api's. Methods ------- get_service_type_f... | RangerAPIObjectStore | [
"Apache-2.0",
"BSD-3-Clause",
"WTFPL",
"MIT",
"GPL-2.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RangerAPIObjectStore:
"""Primary class to connect object stores to the Ranger API Attributes ---------- service_store : dict Mapping of service type to service store objects. Add new service names here if required or unsupported. policy_store: PolicyStore object to create objects associated with ... | stack_v2_sparse_classes_36k_train_026870 | 10,846 | permissive | [
{
"docstring": "Constructor Modify if new object stores are added",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Returns the service type for the given service name :parameter service_name: Service name for the service type to be returned :return: Service type for the... | 5 | stack_v2_sparse_classes_30k_train_011358 | Implement the Python class `RangerAPIObjectStore` described below.
Class description:
Primary class to connect object stores to the Ranger API Attributes ---------- service_store : dict Mapping of service type to service store objects. Add new service names here if required or unsupported. policy_store: PolicyStore ob... | Implement the Python class `RangerAPIObjectStore` described below.
Class description:
Primary class to connect object stores to the Ranger API Attributes ---------- service_store : dict Mapping of service type to service store objects. Add new service names here if required or unsupported. policy_store: PolicyStore ob... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class RangerAPIObjectStore:
"""Primary class to connect object stores to the Ranger API Attributes ---------- service_store : dict Mapping of service type to service store objects. Add new service names here if required or unsupported. policy_store: PolicyStore object to create objects associated with ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RangerAPIObjectStore:
"""Primary class to connect object stores to the Ranger API Attributes ---------- service_store : dict Mapping of service type to service store objects. Add new service names here if required or unsupported. policy_store: PolicyStore object to create objects associated with policy api's.... | the_stack_v2_python_sparse | govern/data-security/ranger/ranger-tools/src/main/python/ranger_performance_tool/ranger_perf_object_stores/base_object_stores.py | alldatacenter/alldata | train | 774 |
1c3604b96d02fbf96a5450f6d743d10a155b450c | [
"if node.attr == 'display_name_with_default_escaped':\n self.results.violations.append(ExpressionRuleViolation(ruleset.python_deprecated_display_name, self.node_to_expression(node)))\nself.generic_visit(node)",
"if isinstance(node.func, ast.Attribute) and node.func.attr == 'format':\n visitor = FormatInterp... | <|body_start_0|>
if node.attr == 'display_name_with_default_escaped':
self.results.violations.append(ExpressionRuleViolation(ruleset.python_deprecated_display_name, self.node_to_expression(node)))
self.generic_visit(node)
<|end_body_0|>
<|body_start_1|>
if isinstance(node.func, ast.... | Visits all nodes and does not interfere with calls to generic_visit(). This is used in conjunction with other visitors to check for a variety of violations. This visitor is meant to be used once from the root. | AllNodeVisitor | [
"MIT",
"AGPL-3.0-only",
"AGPL-3.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AllNodeVisitor:
"""Visits all nodes and does not interfere with calls to generic_visit(). This is used in conjunction with other visitors to check for a variety of violations. This visitor is meant to be used once from the root."""
def visit_Attribute(self, node):
"""Checks for uses ... | stack_v2_sparse_classes_36k_train_026871 | 12,510 | permissive | [
{
"docstring": "Checks for uses of deprecated `display_name_with_default_escaped`. Arguments: node: An AST node.",
"name": "visit_Attribute",
"signature": "def visit_Attribute(self, node)"
},
{
"docstring": "Checks for a variety of violations: - Checks that format() calls with nested HTML() or T... | 3 | null | Implement the Python class `AllNodeVisitor` described below.
Class description:
Visits all nodes and does not interfere with calls to generic_visit(). This is used in conjunction with other visitors to check for a variety of violations. This visitor is meant to be used once from the root.
Method signatures and docstr... | Implement the Python class `AllNodeVisitor` described below.
Class description:
Visits all nodes and does not interfere with calls to generic_visit(). This is used in conjunction with other visitors to check for a variety of violations. This visitor is meant to be used once from the root.
Method signatures and docstr... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class AllNodeVisitor:
"""Visits all nodes and does not interfere with calls to generic_visit(). This is used in conjunction with other visitors to check for a variety of violations. This visitor is meant to be used once from the root."""
def visit_Attribute(self, node):
"""Checks for uses ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AllNodeVisitor:
"""Visits all nodes and does not interfere with calls to generic_visit(). This is used in conjunction with other visitors to check for a variety of violations. This visitor is meant to be used once from the root."""
def visit_Attribute(self, node):
"""Checks for uses of deprecated... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/scripts/xsslint/xsslint/visitors.py | luque/better-ways-of-thinking-about-software | train | 3 |
46e9bccabda90b55a81ca1b8dae84645425c2c53 | [
"self.entry = entry\nself.id = entry.id\nself.title = entry.title\nself.date = entry.date\nself.time_spent = entry.time_spent\nself.learned = entry.learned\n_resources = self.entry.get_resources()\n_tags = self.entry.get_tags()\nself.resources = [(resource.id, resource.title) for resource in list(_resources)]\nself... | <|body_start_0|>
self.entry = entry
self.id = entry.id
self.title = entry.title
self.date = entry.date
self.time_spent = entry.time_spent
self.learned = entry.learned
_resources = self.entry.get_resources()
_tags = self.entry.get_tags()
self.resour... | helper class that is not stored in the database it is used to update an entry along with its tags and resources | EntryWithResourcesandTags | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EntryWithResourcesandTags:
"""helper class that is not stored in the database it is used to update an entry along with its tags and resources"""
def __init__(self, entry):
"""the combined record is initilized in the way it exists before the update"""
<|body_0|>
def updat... | stack_v2_sparse_classes_36k_train_026872 | 10,083 | no_license | [
{
"docstring": "the combined record is initilized in the way it exists before the update",
"name": "__init__",
"signature": "def __init__(self, entry)"
},
{
"docstring": "the update is performed",
"name": "update",
"signature": "def update(self, form)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009813 | Implement the Python class `EntryWithResourcesandTags` described below.
Class description:
helper class that is not stored in the database it is used to update an entry along with its tags and resources
Method signatures and docstrings:
- def __init__(self, entry): the combined record is initilized in the way it exis... | Implement the Python class `EntryWithResourcesandTags` described below.
Class description:
helper class that is not stored in the database it is used to update an entry along with its tags and resources
Method signatures and docstrings:
- def __init__(self, entry): the combined record is initilized in the way it exis... | 8bfbba09132b405f7c68cbfd9a0e7596223c3a53 | <|skeleton|>
class EntryWithResourcesandTags:
"""helper class that is not stored in the database it is used to update an entry along with its tags and resources"""
def __init__(self, entry):
"""the combined record is initilized in the way it exists before the update"""
<|body_0|>
def updat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EntryWithResourcesandTags:
"""helper class that is not stored in the database it is used to update an entry along with its tags and resources"""
def __init__(self, entry):
"""the combined record is initilized in the way it exists before the update"""
self.entry = entry
self.id = e... | the_stack_v2_python_sparse | project05_flask_learningjournal/learning_journal/models.py | sabinem/treehouse-python-techdegree | train | 3 |
96a8e020a72d791a55bf963cc8fc9d8fe4217538 | [
"max_len = 0\nA_set = set(A)\n\ndef backtrack(cur_seq):\n nonlocal max_len\n next = cur_seq[-1] + cur_seq[-2]\n if next in A_set:\n cur_seq.append(next)\n backtrack(cur_seq)\n else:\n max_len = max(max_len, len(cur_seq))\nfor i in range(len(A) - 1):\n for j in range(i + 1, len(A)... | <|body_start_0|>
max_len = 0
A_set = set(A)
def backtrack(cur_seq):
nonlocal max_len
next = cur_seq[-1] + cur_seq[-2]
if next in A_set:
cur_seq.append(next)
backtrack(cur_seq)
else:
max_len = max(max... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lenLongestFibSubseq(self, A):
""":type A: List[int] :rtype: int"""
<|body_0|>
def lenLongestFibSubseq2(self, A):
""":type A: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
max_len = 0
A_set = set(A)
... | stack_v2_sparse_classes_36k_train_026873 | 1,219 | no_license | [
{
"docstring": ":type A: List[int] :rtype: int",
"name": "lenLongestFibSubseq",
"signature": "def lenLongestFibSubseq(self, A)"
},
{
"docstring": ":type A: List[int] :rtype: int",
"name": "lenLongestFibSubseq2",
"signature": "def lenLongestFibSubseq2(self, A)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lenLongestFibSubseq(self, A): :type A: List[int] :rtype: int
- def lenLongestFibSubseq2(self, A): :type A: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lenLongestFibSubseq(self, A): :type A: List[int] :rtype: int
- def lenLongestFibSubseq2(self, A): :type A: List[int] :rtype: int
<|skeleton|>
class Solution:
def lenLon... | 4a1747b6497305f3821612d9c358a6795b1690da | <|skeleton|>
class Solution:
def lenLongestFibSubseq(self, A):
""":type A: List[int] :rtype: int"""
<|body_0|>
def lenLongestFibSubseq2(self, A):
""":type A: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lenLongestFibSubseq(self, A):
""":type A: List[int] :rtype: int"""
max_len = 0
A_set = set(A)
def backtrack(cur_seq):
nonlocal max_len
next = cur_seq[-1] + cur_seq[-2]
if next in A_set:
cur_seq.append(next)
... | the_stack_v2_python_sparse | DynamicProgramming/q873_length_of_longest_fibonacci_subsequence.py | sevenhe716/LeetCode | train | 0 | |
4fa653fa920695043dc3c04da98d7c7b3e755ec5 | [
"self.mp_array = mp_array\nsuper().__init__()\nreturn",
"while True:\n data = datetime.datetime.utcnow()\n print(' DataCollector: {:s}'.format(data.strftime('%Y-%m-%d %H:%M:%S.%f')))\n datalist = list(data.timetuple())[:6]\n datalist.append(data.microsecond)\n with self.mp_array.get_lock():\n ... | <|body_start_0|>
self.mp_array = mp_array
super().__init__()
return
<|end_body_0|>
<|body_start_1|>
while True:
data = datetime.datetime.utcnow()
print(' DataCollector: {:s}'.format(data.strftime('%Y-%m-%d %H:%M:%S.%f')))
datalist = list(data.timet... | DataCollector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataCollector:
def __init__(self, mp_array):
"""Instance a sample data collector. This sample simply reads the local clock. mp_array: shared data multiprocessing.Array object"""
<|body_0|>
def run(self):
"""Main Receiver Loop. Oveloaded multiprocessing.Process.run()"... | stack_v2_sparse_classes_36k_train_026874 | 3,891 | no_license | [
{
"docstring": "Instance a sample data collector. This sample simply reads the local clock. mp_array: shared data multiprocessing.Array object",
"name": "__init__",
"signature": "def __init__(self, mp_array)"
},
{
"docstring": "Main Receiver Loop. Oveloaded multiprocessing.Process.run()",
"n... | 2 | stack_v2_sparse_classes_30k_train_000279 | Implement the Python class `DataCollector` described below.
Class description:
Implement the DataCollector class.
Method signatures and docstrings:
- def __init__(self, mp_array): Instance a sample data collector. This sample simply reads the local clock. mp_array: shared data multiprocessing.Array object
- def run(s... | Implement the Python class `DataCollector` described below.
Class description:
Implement the DataCollector class.
Method signatures and docstrings:
- def __init__(self, mp_array): Instance a sample data collector. This sample simply reads the local clock. mp_array: shared data multiprocessing.Array object
- def run(s... | f45e3ac1ae4a88de46027f4801f4b46aacb21f5e | <|skeleton|>
class DataCollector:
def __init__(self, mp_array):
"""Instance a sample data collector. This sample simply reads the local clock. mp_array: shared data multiprocessing.Array object"""
<|body_0|>
def run(self):
"""Main Receiver Loop. Oveloaded multiprocessing.Process.run()"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataCollector:
def __init__(self, mp_array):
"""Instance a sample data collector. This sample simply reads the local clock. mp_array: shared data multiprocessing.Array object"""
self.mp_array = mp_array
super().__init__()
return
def run(self):
"""Main Receiver Loop... | the_stack_v2_python_sparse | templates/data_processor_template.py | IslePilot/py3_scripts | train | 1 | |
817b80d24a35cdd638b5959ec124fade0106313f | [
"super(Encoder, self).__init__()\nself.num_layers = num_layers\nself.hidden_size = hidden_size\nself.batch_size = batch_size\nself.LSTM = LSTM(input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, batch_first=True, dropout=dropout)",
"if h_0 is not None and c_0 is not None:\n _, (h_n, _) = sel... | <|body_start_0|>
super(Encoder, self).__init__()
self.num_layers = num_layers
self.hidden_size = hidden_size
self.batch_size = batch_size
self.LSTM = LSTM(input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, batch_first=True, dropout=dropout)
<|end_body_0|>
<|b... | Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
def __init__(self, input_size, batch_size=1, hidden_size=128, num_layers=2, dropout=0.85):
"""Construct a multilayer LSTM that computes the encoding vector"""
<|body_0|>
def forward(self, input, h_0=None, c_0=None):
"""input should have size (batch_size, seq... | stack_v2_sparse_classes_36k_train_026875 | 8,815 | no_license | [
{
"docstring": "Construct a multilayer LSTM that computes the encoding vector",
"name": "__init__",
"signature": "def __init__(self, input_size, batch_size=1, hidden_size=128, num_layers=2, dropout=0.85)"
},
{
"docstring": "input should have size (batch_size, seq_len, input_size)",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_008556 | Implement the Python class `Encoder` described below.
Class description:
Implement the Encoder class.
Method signatures and docstrings:
- def __init__(self, input_size, batch_size=1, hidden_size=128, num_layers=2, dropout=0.85): Construct a multilayer LSTM that computes the encoding vector
- def forward(self, input, ... | Implement the Python class `Encoder` described below.
Class description:
Implement the Encoder class.
Method signatures and docstrings:
- def __init__(self, input_size, batch_size=1, hidden_size=128, num_layers=2, dropout=0.85): Construct a multilayer LSTM that computes the encoding vector
- def forward(self, input, ... | 6fd5b2c1b03528a828b3f5395f6e2fa8659ebbd0 | <|skeleton|>
class Encoder:
def __init__(self, input_size, batch_size=1, hidden_size=128, num_layers=2, dropout=0.85):
"""Construct a multilayer LSTM that computes the encoding vector"""
<|body_0|>
def forward(self, input, h_0=None, c_0=None):
"""input should have size (batch_size, seq... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Encoder:
def __init__(self, input_size, batch_size=1, hidden_size=128, num_layers=2, dropout=0.85):
"""Construct a multilayer LSTM that computes the encoding vector"""
super(Encoder, self).__init__()
self.num_layers = num_layers
self.hidden_size = hidden_size
self.batch... | the_stack_v2_python_sparse | model/model.py | TommyAngelini/rl-finance | train | 0 | |
cc10a6146830a1de30f6f3d90ec2d7c3c2cfe1d0 | [
"super().__init__()\nself.encoder = smp.encoders.get_encoder(encoder_name, in_channels=in_channels, depth=encoder_depth, weights=encoder_weights)\nencoder_out_channels = [c * 2 for c in self.encoder.out_channels[1:]]\nencoder_out_channels.insert(0, self.encoder.out_channels[0])\ntry:\n UnetDecoder = smp.decoders... | <|body_start_0|>
super().__init__()
self.encoder = smp.encoders.get_encoder(encoder_name, in_channels=in_channels, depth=encoder_depth, weights=encoder_weights)
encoder_out_channels = [c * 2 for c in self.encoder.out_channels[1:]]
encoder_out_channels.insert(0, self.encoder.out_channels[... | Fully-convolutional Siamese Concatenation (FC-Siam-conc). If you use this model in your research, please cite the following paper: * https://doi.org/10.1109/ICIP.2018.8451652 | FCSiamConc | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FCSiamConc:
"""Fully-convolutional Siamese Concatenation (FC-Siam-conc). If you use this model in your research, please cite the following paper: * https://doi.org/10.1109/ICIP.2018.8451652"""
def __init__(self, encoder_name: str='resnet34', encoder_depth: int=5, encoder_weights: Optional[st... | stack_v2_sparse_classes_36k_train_026876 | 8,273 | permissive | [
{
"docstring": "Initialize a new FCSiamConc model. Args: encoder_name: Name of the classification model that will be used as an encoder (a.k.a backbone) to extract features of different spatial resolution encoder_depth: A number of stages used in encoder in range [3, 5]. two times smaller in spatial dimensions ... | 2 | stack_v2_sparse_classes_30k_train_017797 | Implement the Python class `FCSiamConc` described below.
Class description:
Fully-convolutional Siamese Concatenation (FC-Siam-conc). If you use this model in your research, please cite the following paper: * https://doi.org/10.1109/ICIP.2018.8451652
Method signatures and docstrings:
- def __init__(self, encoder_name... | Implement the Python class `FCSiamConc` described below.
Class description:
Fully-convolutional Siamese Concatenation (FC-Siam-conc). If you use this model in your research, please cite the following paper: * https://doi.org/10.1109/ICIP.2018.8451652
Method signatures and docstrings:
- def __init__(self, encoder_name... | 29985861614b3b93f9ef5389469ebb98570de7dd | <|skeleton|>
class FCSiamConc:
"""Fully-convolutional Siamese Concatenation (FC-Siam-conc). If you use this model in your research, please cite the following paper: * https://doi.org/10.1109/ICIP.2018.8451652"""
def __init__(self, encoder_name: str='resnet34', encoder_depth: int=5, encoder_weights: Optional[st... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FCSiamConc:
"""Fully-convolutional Siamese Concatenation (FC-Siam-conc). If you use this model in your research, please cite the following paper: * https://doi.org/10.1109/ICIP.2018.8451652"""
def __init__(self, encoder_name: str='resnet34', encoder_depth: int=5, encoder_weights: Optional[str]='imagenet'... | the_stack_v2_python_sparse | torchgeo/models/fcsiam.py | microsoft/torchgeo | train | 1,724 |
8543a199a3945b25dea9db4e2d61a23a1b906f7c | [
"n = len(nextVisit)\ndp = [0] * n\nfor i in range(1, n):\n dp[i] = (dp[i - 1] + 1 + (dp[i - 1] - dp[nextVisit[i - 1]]) + 1) % MOD\nreturn dp[-1]",
"n = len(nextVisit)\ndp = [0] * n\ndpSum = [0] * n\nfor i in range(1, n):\n dp[i] = (dpSum[i - 1] - dpSum[nextVisit[i - 1]] + 2) % MOD\n dpSum[i] = (dpSum[i -... | <|body_start_0|>
n = len(nextVisit)
dp = [0] * n
for i in range(1, n):
dp[i] = (dp[i - 1] + 1 + (dp[i - 1] - dp[nextVisit[i - 1]]) + 1) % MOD
return dp[-1]
<|end_body_0|>
<|body_start_1|>
n = len(nextVisit)
dp = [0] * n
dpSum = [0] * n
for i i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def firstDayBeenInAllRooms(self, nextVisit: List[int]) -> int:
"""dp[i] is number of days to reach cell i `We can only reach cell i from the cell i-1` summary: start => i-1 =>nextVisit[i-1] => i-1 => i"""
<|body_0|>
def firstDayBeenInAllRooms2(self, nextVisit: List... | stack_v2_sparse_classes_36k_train_026877 | 2,151 | no_license | [
{
"docstring": "dp[i] is number of days to reach cell i `We can only reach cell i from the cell i-1` summary: start => i-1 =>nextVisit[i-1] => i-1 => i",
"name": "firstDayBeenInAllRooms",
"signature": "def firstDayBeenInAllRooms(self, nextVisit: List[int]) -> int"
},
{
"docstring": "dp[i]=2+dp[j... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstDayBeenInAllRooms(self, nextVisit: List[int]) -> int: dp[i] is number of days to reach cell i `We can only reach cell i from the cell i-1` summary: start => i-1 =>nextVi... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstDayBeenInAllRooms(self, nextVisit: List[int]) -> int: dp[i] is number of days to reach cell i `We can only reach cell i from the cell i-1` summary: start => i-1 =>nextVi... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def firstDayBeenInAllRooms(self, nextVisit: List[int]) -> int:
"""dp[i] is number of days to reach cell i `We can only reach cell i from the cell i-1` summary: start => i-1 =>nextVisit[i-1] => i-1 => i"""
<|body_0|>
def firstDayBeenInAllRooms2(self, nextVisit: List... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def firstDayBeenInAllRooms(self, nextVisit: List[int]) -> int:
"""dp[i] is number of days to reach cell i `We can only reach cell i from the cell i-1` summary: start => i-1 =>nextVisit[i-1] => i-1 => i"""
n = len(nextVisit)
dp = [0] * n
for i in range(1, n):
... | the_stack_v2_python_sparse | 11_动态规划/dp优化/前缀和优化/1997. 访问完所有房间的第一天-前缀和优化.py | 981377660LMT/algorithm-study | train | 225 | |
259d5c1bb856b2eb9ce05ecefb891adbcd0e2945 | [
"x_headers = 'x-ms-date:' + date\nstring_to_hash = method + '\\n' + str(content_length) + '\\n' + content_type + '\\n' + x_headers + '\\n' + resource\nbytes_to_hash = bytes(string_to_hash, encoding='utf-8')\ndecoded_key = base64.b64decode(shared_key)\nencoded_hash = base64.b64encode(hmac.new(decoded_key, bytes_to_h... | <|body_start_0|>
x_headers = 'x-ms-date:' + date
string_to_hash = method + '\n' + str(content_length) + '\n' + content_type + '\n' + x_headers + '\n' + resource
bytes_to_hash = bytes(string_to_hash, encoding='utf-8')
decoded_key = base64.b64decode(shared_key)
encoded_hash = base6... | AzureSentinel class is used to post data into log Analytics workspace. | AzureSentinel | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AzureSentinel:
"""AzureSentinel class is used to post data into log Analytics workspace."""
def build_signature(self, date, content_length, method, content_type, resource):
"""To build signature which is required in header."""
<|body_0|>
def post_data(self, body, log_typ... | stack_v2_sparse_classes_36k_train_026878 | 3,284 | permissive | [
{
"docstring": "To build signature which is required in header.",
"name": "build_signature",
"signature": "def build_signature(self, date, content_length, method, content_type, resource)"
},
{
"docstring": "Build and send a request to the POST API. Args: body (str): Data to post into Sentinel lo... | 2 | null | Implement the Python class `AzureSentinel` described below.
Class description:
AzureSentinel class is used to post data into log Analytics workspace.
Method signatures and docstrings:
- def build_signature(self, date, content_length, method, content_type, resource): To build signature which is required in header.
- d... | Implement the Python class `AzureSentinel` described below.
Class description:
AzureSentinel class is used to post data into log Analytics workspace.
Method signatures and docstrings:
- def build_signature(self, date, content_length, method, content_type, resource): To build signature which is required in header.
- d... | 4536a3f6b9bdef902312b3d96f9c2e66b8bf52c1 | <|skeleton|>
class AzureSentinel:
"""AzureSentinel class is used to post data into log Analytics workspace."""
def build_signature(self, date, content_length, method, content_type, resource):
"""To build signature which is required in header."""
<|body_0|>
def post_data(self, body, log_typ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AzureSentinel:
"""AzureSentinel class is used to post data into log Analytics workspace."""
def build_signature(self, date, content_length, method, content_type, resource):
"""To build signature which is required in header."""
x_headers = 'x-ms-date:' + date
string_to_hash = metho... | the_stack_v2_python_sparse | Solutions/Vectra XDR/Data Connectors/VectraDataConnector/SharedCode/azure_sentinel.py | Azure/Azure-Sentinel | train | 3,697 |
885433a4563ccf8a3fac7bedf2aedeaa5f8ea3b4 | [
"RDFS_OWLRL_Semantics.__init__(self, graph, axioms, daxioms, rdfs)\nself.rdfs = rdfs\nself.add_new_datatype(OWL.rational, _strToRational, OWL_RL_Datatypes, subsumption_dict=OWL_Datatype_Subsumptions, subsumption_key=XSD.decimal, subsumption_list=[OWL.rational])\nself.restricted_datatypes = extract_faceted_datatypes... | <|body_start_0|>
RDFS_OWLRL_Semantics.__init__(self, graph, axioms, daxioms, rdfs)
self.rdfs = rdfs
self.add_new_datatype(OWL.rational, _strToRational, OWL_RL_Datatypes, subsumption_dict=OWL_Datatype_Subsumptions, subsumption_key=XSD.decimal, subsumption_list=[OWL.rational])
self.restric... | Additional rules to OWL 2 RL. The initialization method also adds the :code:`owl:rational` datatype to the set of allowed datatypes with the :py:func:`._strToRational` function as a conversion between the literal form and a Rational. The :code:`xsd:decimal` datatype is also set to be a subclass of :code:`owl:rational`.... | OWLRL_Extension | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OWLRL_Extension:
"""Additional rules to OWL 2 RL. The initialization method also adds the :code:`owl:rational` datatype to the set of allowed datatypes with the :py:func:`._strToRational` function as a conversion between the literal form and a Rational. The :code:`xsd:decimal` datatype is also se... | stack_v2_sparse_classes_36k_train_026879 | 15,325 | permissive | [
{
"docstring": "@param graph: the RDF graph to be extended @type graph: rdflib.Graph @param axioms: whether (non-datatype) axiomatic triples should be added or not @type axioms: Boolean @param daxioms: whether datatype axiomatic triples should be added or not @type daxioms: Boolean @param rdfs: whether RDFS ext... | 6 | null | Implement the Python class `OWLRL_Extension` described below.
Class description:
Additional rules to OWL 2 RL. The initialization method also adds the :code:`owl:rational` datatype to the set of allowed datatypes with the :py:func:`._strToRational` function as a conversion between the literal form and a Rational. The ... | Implement the Python class `OWLRL_Extension` described below.
Class description:
Additional rules to OWL 2 RL. The initialization method also adds the :code:`owl:rational` datatype to the set of allowed datatypes with the :py:func:`._strToRational` function as a conversion between the literal form and a Rational. The ... | 84f6d3fced521849657d21ae4cb9681f5897b957 | <|skeleton|>
class OWLRL_Extension:
"""Additional rules to OWL 2 RL. The initialization method also adds the :code:`owl:rational` datatype to the set of allowed datatypes with the :py:func:`._strToRational` function as a conversion between the literal form and a Rational. The :code:`xsd:decimal` datatype is also se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OWLRL_Extension:
"""Additional rules to OWL 2 RL. The initialization method also adds the :code:`owl:rational` datatype to the set of allowed datatypes with the :py:func:`._strToRational` function as a conversion between the literal form and a Rational. The :code:`xsd:decimal` datatype is also set to be a sub... | the_stack_v2_python_sparse | venv/lib/python3.9/site-packages/owlrl/OWLRLExtras.py | ClassWizard/PodLockParser | train | 2 |
77232aae9c35123396bc59ca3070fa6f0e4fadfb | [
"if not root:\n return tree_string\ntree_string += str(root.val) + ','\ntree_string = self.serialize(root.left, tree_string)\ntree_string = self.serialize(root.right, tree_string)\nreturn tree_string",
"if not data:\n return []\nvalues = data.split(',')\nvalues.pop()\nvalues = [int(x) for x in values]\nroot... | <|body_start_0|>
if not root:
return tree_string
tree_string += str(root.val) + ','
tree_string = self.serialize(root.left, tree_string)
tree_string = self.serialize(root.right, tree_string)
return tree_string
<|end_body_0|>
<|body_start_1|>
if not data:
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: Optional[TreeNode], tree_string='') -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> Optional[TreeNode]:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_026880 | 1,524 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: Optional[TreeNode], tree_string='') -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> O... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: Optional[TreeNode], tree_string='') -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> Optional[TreeNode]: Decodes your encoded ... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: Optional[TreeNode], tree_string='') -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> Optional[TreeNode]: Decodes your encoded ... | 10db2aab180aece1130b8da19094cf74f158e625 | <|skeleton|>
class Codec:
def serialize(self, root: Optional[TreeNode], tree_string='') -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> Optional[TreeNode]:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: Optional[TreeNode], tree_string='') -> str:
"""Encodes a tree to a single string."""
if not root:
return tree_string
tree_string += str(root.val) + ','
tree_string = self.serialize(root.left, tree_string)
tree_string = self.s... | the_stack_v2_python_sparse | notion/449_serialize_and_deserialize_bst.py | cukejianya/leetcode | train | 0 | |
ba3c984ded47887d4138f67bc8ba372b6dcc271c | [
"max_steps = max_steps or 0\nmax_episodes = max_episodes or 0\nif max_steps < 1 and max_episodes < 1:\n raise ValueError('Either `max_steps` or `max_episodes` should be greater than 0.')\nsuper(PyDriver, self).__init__(env, policy, observers, transition_observers, info_observers)\nself._max_steps = max_steps or ... | <|body_start_0|>
max_steps = max_steps or 0
max_episodes = max_episodes or 0
if max_steps < 1 and max_episodes < 1:
raise ValueError('Either `max_steps` or `max_episodes` should be greater than 0.')
super(PyDriver, self).__init__(env, policy, observers, transition_observers, ... | A driver that runs a python policy in a python environment. | PyDriver | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PyDriver:
"""A driver that runs a python policy in a python environment."""
def __init__(self, env: py_environment.PyEnvironment, policy: py_policy.PyPolicy, observers: Sequence[Callable[[trajectory.Trajectory], Any]], transition_observers: Optional[Sequence[Callable[[trajectory.Transition],... | stack_v2_sparse_classes_36k_train_026881 | 6,250 | permissive | [
{
"docstring": "A driver that runs a python policy in a python environment. **Note** about bias when using batched environments with `max_episodes`: When using `max_episodes != None`, a `run` step \"finishes\" when `max_episodes` have been completely collected (hit a boundary). When used in conjunction with env... | 2 | stack_v2_sparse_classes_30k_train_019792 | Implement the Python class `PyDriver` described below.
Class description:
A driver that runs a python policy in a python environment.
Method signatures and docstrings:
- def __init__(self, env: py_environment.PyEnvironment, policy: py_policy.PyPolicy, observers: Sequence[Callable[[trajectory.Trajectory], Any]], trans... | Implement the Python class `PyDriver` described below.
Class description:
A driver that runs a python policy in a python environment.
Method signatures and docstrings:
- def __init__(self, env: py_environment.PyEnvironment, policy: py_policy.PyPolicy, observers: Sequence[Callable[[trajectory.Trajectory], Any]], trans... | eca1093d3a047e538f17f6ab92ab4d8144284f23 | <|skeleton|>
class PyDriver:
"""A driver that runs a python policy in a python environment."""
def __init__(self, env: py_environment.PyEnvironment, policy: py_policy.PyPolicy, observers: Sequence[Callable[[trajectory.Trajectory], Any]], transition_observers: Optional[Sequence[Callable[[trajectory.Transition],... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PyDriver:
"""A driver that runs a python policy in a python environment."""
def __init__(self, env: py_environment.PyEnvironment, policy: py_policy.PyPolicy, observers: Sequence[Callable[[trajectory.Trajectory], Any]], transition_observers: Optional[Sequence[Callable[[trajectory.Transition], Any]]]=None,... | the_stack_v2_python_sparse | tf_agents/drivers/py_driver.py | tensorflow/agents | train | 2,755 |
b557c2c21d25090ff9b5cb0b083cca9ea34c029a | [
"self.model = model\nself.checkpoints_dir = checkpoints_dir\nself.save_step_frequency = save_step_frequency\nos.makedirs(self.checkpoints_dir, exist_ok=True)",
"global_step = trainer.global_step\nif global_step % self.save_step_frequency == 0:\n checkpoint_path = os.path.join(self.checkpoints_dir, 'step={}.pth... | <|body_start_0|>
self.model = model
self.checkpoints_dir = checkpoints_dir
self.save_step_frequency = save_step_frequency
os.makedirs(self.checkpoints_dir, exist_ok=True)
<|end_body_0|>
<|body_start_1|>
global_step = trainer.global_step
if global_step % self.save_step_fr... | SaveCheckpointsCallback | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SaveCheckpointsCallback:
def __init__(self, model: nn.Module, checkpoints_dir: str, save_step_frequency: int):
"""Callback to save checkpoints every #save_step_frequency steps. Args: model: nn.Module checkpoints_dir: str, directory to save checkpoints save_step_frequency: int"""
... | stack_v2_sparse_classes_36k_train_026882 | 1,324 | permissive | [
{
"docstring": "Callback to save checkpoints every #save_step_frequency steps. Args: model: nn.Module checkpoints_dir: str, directory to save checkpoints save_step_frequency: int",
"name": "__init__",
"signature": "def __init__(self, model: nn.Module, checkpoints_dir: str, save_step_frequency: int)"
}... | 2 | null | Implement the Python class `SaveCheckpointsCallback` described below.
Class description:
Implement the SaveCheckpointsCallback class.
Method signatures and docstrings:
- def __init__(self, model: nn.Module, checkpoints_dir: str, save_step_frequency: int): Callback to save checkpoints every #save_step_frequency steps.... | Implement the Python class `SaveCheckpointsCallback` described below.
Class description:
Implement the SaveCheckpointsCallback class.
Method signatures and docstrings:
- def __init__(self, model: nn.Module, checkpoints_dir: str, save_step_frequency: int): Callback to save checkpoints every #save_step_frequency steps.... | 0a088e1fc852a15d7e558a7e203888de0577dfb1 | <|skeleton|>
class SaveCheckpointsCallback:
def __init__(self, model: nn.Module, checkpoints_dir: str, save_step_frequency: int):
"""Callback to save checkpoints every #save_step_frequency steps. Args: model: nn.Module checkpoints_dir: str, directory to save checkpoints save_step_frequency: int"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SaveCheckpointsCallback:
def __init__(self, model: nn.Module, checkpoints_dir: str, save_step_frequency: int):
"""Callback to save checkpoints every #save_step_frequency steps. Args: model: nn.Module checkpoints_dir: str, directory to save checkpoints save_step_frequency: int"""
self.model = m... | the_stack_v2_python_sparse | bytesep/callbacks/base_callbacks.py | XinyuanLiu2018/music_source_separation | train | 0 | |
6a3d3141ebb96bb6a2cc8f12949015f363be51d2 | [
"queryset = JobApply.objects.filter(job__project__id=pk).order_by('-id')\nqueryset = self.filter_queryset(queryset)\npage = self.paginate_queryset(queryset)\nif page is not None:\n serializer = self.get_serializer(page, many=True)\n return self.get_paginated_response(serializer.data)\nserializer = self.get_se... | <|body_start_0|>
queryset = JobApply.objects.filter(job__project__id=pk).order_by('-id')
queryset = self.filter_queryset(queryset)
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_pagina... | Endpoint for employee job response | EmployeeJobResponseViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmployeeJobResponseViewSet:
"""Endpoint for employee job response"""
def project_job_response(self, request, pk=None):
"""Endpoint for project job responses"""
<|body_0|>
def send_appointment(self, request, pk=None):
"""Endpoint for job applied hire employee"""
... | stack_v2_sparse_classes_36k_train_026883 | 49,113 | no_license | [
{
"docstring": "Endpoint for project job responses",
"name": "project_job_response",
"signature": "def project_job_response(self, request, pk=None)"
},
{
"docstring": "Endpoint for job applied hire employee",
"name": "send_appointment",
"signature": "def send_appointment(self, request, p... | 5 | stack_v2_sparse_classes_30k_train_006246 | Implement the Python class `EmployeeJobResponseViewSet` described below.
Class description:
Endpoint for employee job response
Method signatures and docstrings:
- def project_job_response(self, request, pk=None): Endpoint for project job responses
- def send_appointment(self, request, pk=None): Endpoint for job appli... | Implement the Python class `EmployeeJobResponseViewSet` described below.
Class description:
Endpoint for employee job response
Method signatures and docstrings:
- def project_job_response(self, request, pk=None): Endpoint for project job responses
- def send_appointment(self, request, pk=None): Endpoint for job appli... | cf3481991c9cfaba44d8ecc17f5b205ae5591dd0 | <|skeleton|>
class EmployeeJobResponseViewSet:
"""Endpoint for employee job response"""
def project_job_response(self, request, pk=None):
"""Endpoint for project job responses"""
<|body_0|>
def send_appointment(self, request, pk=None):
"""Endpoint for job applied hire employee"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmployeeJobResponseViewSet:
"""Endpoint for employee job response"""
def project_job_response(self, request, pk=None):
"""Endpoint for project job responses"""
queryset = JobApply.objects.filter(job__project__id=pk).order_by('-id')
queryset = self.filter_queryset(queryset)
... | the_stack_v2_python_sparse | recruitment/api_recruitment.py | miloradradisic12/team-management-tool-backend | train | 0 |
592a2a6de1d9cd9890c6206a82f57498c157fe24 | [
"action_out = zaza_model.run_on_leader(self.application_name, \"dpkg-query --showformat='${Version}' --show python3-tvault-horizon-plugin\")\nif 'no packages found' in action_out['stderr']:\n action_out = zaza_model.run_on_leader(self.application_name, \"dpkg-query --showformat='${Version}' --show tvault-horizon... | <|body_start_0|>
action_out = zaza_model.run_on_leader(self.application_name, "dpkg-query --showformat='${Version}' --show python3-tvault-horizon-plugin")
if 'no packages found' in action_out['stderr']:
action_out = zaza_model.run_on_leader(self.application_name, "dpkg-query --showformat='${... | Tests for Trilio Horizon Plugin charm. | TrilioHorizonPluginTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrilioHorizonPluginTest:
"""Tests for Trilio Horizon Plugin charm."""
def installed_trilio_version(self):
"""Get the Trilio version from the installed package."""
<|body_0|>
def set_openstack_encryption_support(self, os_enc_support):
"""Set the openstack-encrypti... | stack_v2_sparse_classes_36k_train_026884 | 16,781 | permissive | [
{
"docstring": "Get the Trilio version from the installed package.",
"name": "installed_trilio_version",
"signature": "def installed_trilio_version(self)"
},
{
"docstring": "Set the openstack-encryption-support option.",
"name": "set_openstack_encryption_support",
"signature": "def set_o... | 3 | null | Implement the Python class `TrilioHorizonPluginTest` described below.
Class description:
Tests for Trilio Horizon Plugin charm.
Method signatures and docstrings:
- def installed_trilio_version(self): Get the Trilio version from the installed package.
- def set_openstack_encryption_support(self, os_enc_support): Set t... | Implement the Python class `TrilioHorizonPluginTest` described below.
Class description:
Tests for Trilio Horizon Plugin charm.
Method signatures and docstrings:
- def installed_trilio_version(self): Get the Trilio version from the installed package.
- def set_openstack_encryption_support(self, os_enc_support): Set t... | 3b17ad9d97c57b6e62797d4e3333e4b83e43a447 | <|skeleton|>
class TrilioHorizonPluginTest:
"""Tests for Trilio Horizon Plugin charm."""
def installed_trilio_version(self):
"""Get the Trilio version from the installed package."""
<|body_0|>
def set_openstack_encryption_support(self, os_enc_support):
"""Set the openstack-encrypti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TrilioHorizonPluginTest:
"""Tests for Trilio Horizon Plugin charm."""
def installed_trilio_version(self):
"""Get the Trilio version from the installed package."""
action_out = zaza_model.run_on_leader(self.application_name, "dpkg-query --showformat='${Version}' --show python3-tvault-horiz... | the_stack_v2_python_sparse | zaza/openstack/charm_tests/trilio/tests.py | openstack-charmers/zaza-openstack-tests | train | 7 |
fbcfbae620ce813eb04f3941781ccfe51b9a46dd | [
"self.edges = edges\nself.locations = locations\naSet = set()\nfor edge in self.edges:\n distance = math.sqrt((locations.get(edge[0])[0] - locations.get(edge[1])[0]) ** 2 + (locations.get(edge[0])[1] - locations.get(edge[1])[1]) ** 2)\n aSet.add((edge[0], edge[1], distance))\n aSet.add((edge[1], edge[0], d... | <|body_start_0|>
self.edges = edges
self.locations = locations
aSet = set()
for edge in self.edges:
distance = math.sqrt((locations.get(edge[0])[0] - locations.get(edge[1])[0]) ** 2 + (locations.get(edge[0])[1] - locations.get(edge[1])[1]) ** 2)
aSet.add((edge[0],... | This is a concrete subclass of Graph where vertices and edges are explicitly enumerated. Objects of this type are useful for testing graph algorithms. | LocationGraph | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocationGraph:
"""This is a concrete subclass of Graph where vertices and edges are explicitly enumerated. Objects of this type are useful for testing graph algorithms."""
def __init__(self, nodes, edges, starting_nodes, goal_nodes, locations):
"""Initialises an location graph. Keywo... | stack_v2_sparse_classes_36k_train_026885 | 3,139 | no_license | [
{
"docstring": "Initialises an location graph. Keyword arguments: nodes -- a set of nodes edges -- a sequence of tuples in the form (tail, head) or (tail, head, cost) starting_nodes -- the list of starting nodes. We use a list to remind you that the order can influence the search behaviour. goal_node -- the set... | 2 | stack_v2_sparse_classes_30k_val_000709 | Implement the Python class `LocationGraph` described below.
Class description:
This is a concrete subclass of Graph where vertices and edges are explicitly enumerated. Objects of this type are useful for testing graph algorithms.
Method signatures and docstrings:
- def __init__(self, nodes, edges, starting_nodes, goa... | Implement the Python class `LocationGraph` described below.
Class description:
This is a concrete subclass of Graph where vertices and edges are explicitly enumerated. Objects of this type are useful for testing graph algorithms.
Method signatures and docstrings:
- def __init__(self, nodes, edges, starting_nodes, goa... | 99e5a1f6b6e546f44e46a24824b8205528d97825 | <|skeleton|>
class LocationGraph:
"""This is a concrete subclass of Graph where vertices and edges are explicitly enumerated. Objects of this type are useful for testing graph algorithms."""
def __init__(self, nodes, edges, starting_nodes, goal_nodes, locations):
"""Initialises an location graph. Keywo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LocationGraph:
"""This is a concrete subclass of Graph where vertices and edges are explicitly enumerated. Objects of this type are useful for testing graph algorithms."""
def __init__(self, nodes, edges, starting_nodes, goal_nodes, locations):
"""Initialises an location graph. Keyword arguments:... | the_stack_v2_python_sparse | Lab2/Lab2_Q8.py | VongRichard/Artificial-Intelligence | train | 0 |
674da03d4a4804cfa94e21eb5bd1c5f22251afcc | [
"self._output_path = output_path\nself._all_op_exe_time = defaultdict(list)\nself._op_shape_info = defaultdict(list)\nself._op_info = dict()\nself._rank_id = rank_id\nself._op_type_exe_time = defaultdict(list)\nself._exe_time_and_shape_detail = defaultdict(dict)\nself._dynamic_shape_info = defaultdict(list)\nself._... | <|body_start_0|>
self._output_path = output_path
self._all_op_exe_time = defaultdict(list)
self._op_shape_info = defaultdict(list)
self._op_info = dict()
self._rank_id = rank_id
self._op_type_exe_time = defaultdict(list)
self._exe_time_and_shape_detail = defaultdi... | Thr parser for parsing dynamic shape framework files. Args: output_path (str): The profiling path which should contain Ascend profiling data. rank_id (int): The rank ID. | DynamicFrameWorkParser | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license",
"MPL-1.0",
"OpenSSL",
"LGPL-3.0-only",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause-Open-MPI",
"MIT",
"MPL-2.0-no-copyleft-exception",
"NTP",
"BSD-3-Clause",
"GPL-1.0-or-later",
"0BSD",
"MPL-2.0",
"LicenseRef-scancode-f... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DynamicFrameWorkParser:
"""Thr parser for parsing dynamic shape framework files. Args: output_path (str): The profiling path which should contain Ascend profiling data. rank_id (int): The rank ID."""
def __init__(self, output_path, rank_id):
"""Initialization of parsing framework dat... | stack_v2_sparse_classes_36k_train_026886 | 39,984 | permissive | [
{
"docstring": "Initialization of parsing framework data.",
"name": "__init__",
"signature": "def __init__(self, output_path, rank_id)"
},
{
"docstring": "Analyze dynamic shape data and write to dynamic shape file.",
"name": "write_dynamic_shape_data",
"signature": "def write_dynamic_sha... | 5 | null | Implement the Python class `DynamicFrameWorkParser` described below.
Class description:
Thr parser for parsing dynamic shape framework files. Args: output_path (str): The profiling path which should contain Ascend profiling data. rank_id (int): The rank ID.
Method signatures and docstrings:
- def __init__(self, outpu... | Implement the Python class `DynamicFrameWorkParser` described below.
Class description:
Thr parser for parsing dynamic shape framework files. Args: output_path (str): The profiling path which should contain Ascend profiling data. rank_id (int): The rank ID.
Method signatures and docstrings:
- def __init__(self, outpu... | 54acb15d435533c815ee1bd9f6dc0b56b4d4cf83 | <|skeleton|>
class DynamicFrameWorkParser:
"""Thr parser for parsing dynamic shape framework files. Args: output_path (str): The profiling path which should contain Ascend profiling data. rank_id (int): The rank ID."""
def __init__(self, output_path, rank_id):
"""Initialization of parsing framework dat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DynamicFrameWorkParser:
"""Thr parser for parsing dynamic shape framework files. Args: output_path (str): The profiling path which should contain Ascend profiling data. rank_id (int): The rank ID."""
def __init__(self, output_path, rank_id):
"""Initialization of parsing framework data."""
... | the_stack_v2_python_sparse | mindspore/python/mindspore/profiler/parser/framework_parser.py | mindspore-ai/mindspore | train | 4,178 |
df0c3881c586bee9eb8eb1a9d28dad75fb4fe559 | [
"area = 0\nl = len(height)\nj = l - 1\ni = 0\nwhile i < j:\n if height[i] < height[j]:\n a = height[i] * (j - i)\n i += 1\n else:\n a = height[j] * (j - i)\n j -= 1\n if a > area:\n area = a\nreturn area",
"area = 0\nl = len(height)\nj = l - 1\ni = 0\nwhile i < j:\n ... | <|body_start_0|>
area = 0
l = len(height)
j = l - 1
i = 0
while i < j:
if height[i] < height[j]:
a = height[i] * (j - i)
i += 1
else:
a = height[j] * (j - i)
j -= 1
if a > area:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxArea(self, height: 'List[int]') -> int:
"""时间复杂度 : O(n) 执行用时 : 72 ms, 在Container With Most Water的Python3提交中击败了95.49% 的用户 内存消耗 : 14.2 MB, 在Container With Most Water的Python3提交中击败了98.69% 的用户"""
<|body_0|>
def maxArea2(self, height: 'List[int]') -> int:
... | stack_v2_sparse_classes_36k_train_026887 | 3,565 | no_license | [
{
"docstring": "时间复杂度 : O(n) 执行用时 : 72 ms, 在Container With Most Water的Python3提交中击败了95.49% 的用户 内存消耗 : 14.2 MB, 在Container With Most Water的Python3提交中击败了98.69% 的用户",
"name": "maxArea",
"signature": "def maxArea(self, height: 'List[int]') -> int"
},
{
"docstring": "时间复杂度 : O(n) 执行用时 : 100 ms, 在Conta... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxArea(self, height: 'List[int]') -> int: 时间复杂度 : O(n) 执行用时 : 72 ms, 在Container With Most Water的Python3提交中击败了95.49% 的用户 内存消耗 : 14.2 MB, 在Container With Most Water的Python3提交中... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxArea(self, height: 'List[int]') -> int: 时间复杂度 : O(n) 执行用时 : 72 ms, 在Container With Most Water的Python3提交中击败了95.49% 的用户 内存消耗 : 14.2 MB, 在Container With Most Water的Python3提交中... | 7bca9dc8ec211be15c12f89bffbb680d639f87bf | <|skeleton|>
class Solution:
def maxArea(self, height: 'List[int]') -> int:
"""时间复杂度 : O(n) 执行用时 : 72 ms, 在Container With Most Water的Python3提交中击败了95.49% 的用户 内存消耗 : 14.2 MB, 在Container With Most Water的Python3提交中击败了98.69% 的用户"""
<|body_0|>
def maxArea2(self, height: 'List[int]') -> int:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxArea(self, height: 'List[int]') -> int:
"""时间复杂度 : O(n) 执行用时 : 72 ms, 在Container With Most Water的Python3提交中击败了95.49% 的用户 内存消耗 : 14.2 MB, 在Container With Most Water的Python3提交中击败了98.69% 的用户"""
area = 0
l = len(height)
j = l - 1
i = 0
while i < j:
... | the_stack_v2_python_sparse | python/leetcode/11-container-with-most-water.py | wxnacy/study | train | 18 | |
1a532a686b468959ca78ca78562a78a607f868c5 | [
"if batch and batch.state in (self.dataproc.messages.Batch.StateValueValuesEnum.SUCCEEDED, self.dataproc.messages.Batch.StateValueValuesEnum.CANCELLED, self.dataproc.messages.Batch.StateValueValuesEnum.FAILED):\n return True\nreturn False",
"request = self.dataproc.messages.DataprocProjectsLocationsBatchesGetR... | <|body_start_0|>
if batch and batch.state in (self.dataproc.messages.Batch.StateValueValuesEnum.SUCCEEDED, self.dataproc.messages.Batch.StateValueValuesEnum.CANCELLED, self.dataproc.messages.Batch.StateValueValuesEnum.FAILED):
return True
return False
<|end_body_0|>
<|body_start_1|>
... | Poller for batch workload. | BatchPoller | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchPoller:
"""Poller for batch workload."""
def IsDone(self, batch):
"""See base class."""
<|body_0|>
def Poll(self, batch_ref):
"""See base class."""
<|body_1|>
def _GetResult(self, batch):
"""Handles errors. Error handling for batch jobs.... | stack_v2_sparse_classes_36k_train_026888 | 4,021 | permissive | [
{
"docstring": "See base class.",
"name": "IsDone",
"signature": "def IsDone(self, batch)"
},
{
"docstring": "See base class.",
"name": "Poll",
"signature": "def Poll(self, batch_ref)"
},
{
"docstring": "Handles errors. Error handling for batch jobs. This happen after the batch r... | 4 | null | Implement the Python class `BatchPoller` described below.
Class description:
Poller for batch workload.
Method signatures and docstrings:
- def IsDone(self, batch): See base class.
- def Poll(self, batch_ref): See base class.
- def _GetResult(self, batch): Handles errors. Error handling for batch jobs. This happen af... | Implement the Python class `BatchPoller` described below.
Class description:
Poller for batch workload.
Method signatures and docstrings:
- def IsDone(self, batch): See base class.
- def Poll(self, batch_ref): See base class.
- def _GetResult(self, batch): Handles errors. Error handling for batch jobs. This happen af... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class BatchPoller:
"""Poller for batch workload."""
def IsDone(self, batch):
"""See base class."""
<|body_0|>
def Poll(self, batch_ref):
"""See base class."""
<|body_1|>
def _GetResult(self, batch):
"""Handles errors. Error handling for batch jobs.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BatchPoller:
"""Poller for batch workload."""
def IsDone(self, batch):
"""See base class."""
if batch and batch.state in (self.dataproc.messages.Batch.StateValueValuesEnum.SUCCEEDED, self.dataproc.messages.Batch.StateValueValuesEnum.CANCELLED, self.dataproc.messages.Batch.StateValueValues... | the_stack_v2_python_sparse | lib/googlecloudsdk/api_lib/dataproc/poller/batch_poller.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
fbe9dcae7b5627239b0adbd2698a649be399902c | [
"result = []\nqueue = [root]\nwhile any(queue):\n result += [str(node.val) if node else 'null' for node in queue]\n temp = []\n for node in queue:\n if node:\n temp.append(node.left)\n temp.append(node.right)\n queue = temp\ns = '[' + ','.join(result) + ']'\nreturn s",
"no... | <|body_start_0|>
result = []
queue = [root]
while any(queue):
result += [str(node.val) if node else 'null' for node in queue]
temp = []
for node in queue:
if node:
temp.append(node.left)
temp.append(node.... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_026889 | 1,900 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_009919 | 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:... | 237985eea9853a658f811355e8c75d6b141e40b2 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
result = []
queue = [root]
while any(queue):
result += [str(node.val) if node else 'null' for node in queue]
temp = []
for node in que... | the_stack_v2_python_sparse | 297. Serialize and Deserialize Binary Tree.py | Eustaceyi/Leetcode | train | 0 | |
8432376f115d6a985428d21523ab82355e19b0b7 | [
"self.id_to_label = invert_mapping(mapping=self.label_to_id)\nself._vectorized_mapper = np.vectorize(self.label_to_id.get)\nself._vectorized_labeler = np.vectorize(self.id_to_label.get)",
"if isinstance(ids, torch.Tensor):\n ids = ids.cpu().numpy()\nif isinstance(ids, int):\n ids = [ids]\nids = np.asanyarra... | <|body_start_0|>
self.id_to_label = invert_mapping(mapping=self.label_to_id)
self._vectorized_mapper = np.vectorize(self.label_to_id.get)
self._vectorized_labeler = np.vectorize(self.id_to_label.get)
<|end_body_0|>
<|body_start_1|>
if isinstance(ids, torch.Tensor):
ids = ids... | A mapping between labels and IDs. | Labeling | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Labeling:
"""A mapping between labels and IDs."""
def __post_init__(self):
"""Precompute inverse mappings."""
<|body_0|>
def label(self, ids: Union[int, Sequence[int], np.ndarray, torch.LongTensor], unknown_label: str='unknown') -> np.ndarray:
"""Convert IDs to l... | stack_v2_sparse_classes_36k_train_026890 | 40,476 | permissive | [
{
"docstring": "Precompute inverse mappings.",
"name": "__post_init__",
"signature": "def __post_init__(self)"
},
{
"docstring": "Convert IDs to labels.",
"name": "label",
"signature": "def label(self, ids: Union[int, Sequence[int], np.ndarray, torch.LongTensor], unknown_label: str='unkn... | 2 | stack_v2_sparse_classes_30k_train_008192 | Implement the Python class `Labeling` described below.
Class description:
A mapping between labels and IDs.
Method signatures and docstrings:
- def __post_init__(self): Precompute inverse mappings.
- def label(self, ids: Union[int, Sequence[int], np.ndarray, torch.LongTensor], unknown_label: str='unknown') -> np.ndar... | Implement the Python class `Labeling` described below.
Class description:
A mapping between labels and IDs.
Method signatures and docstrings:
- def __post_init__(self): Precompute inverse mappings.
- def label(self, ids: Union[int, Sequence[int], np.ndarray, torch.LongTensor], unknown_label: str='unknown') -> np.ndar... | eeaf1d623aa881c0c897772372988390e1d8302d | <|skeleton|>
class Labeling:
"""A mapping between labels and IDs."""
def __post_init__(self):
"""Precompute inverse mappings."""
<|body_0|>
def label(self, ids: Union[int, Sequence[int], np.ndarray, torch.LongTensor], unknown_label: str='unknown') -> np.ndarray:
"""Convert IDs to l... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Labeling:
"""A mapping between labels and IDs."""
def __post_init__(self):
"""Precompute inverse mappings."""
self.id_to_label = invert_mapping(mapping=self.label_to_id)
self._vectorized_mapper = np.vectorize(self.label_to_id.get)
self._vectorized_labeler = np.vectorize(se... | the_stack_v2_python_sparse | src/pykeen/triples/triples_factory.py | Moon-xm/pykeen | train | 1 |
2afa9a3c3815a8549ef52ff0c6197861958f4da8 | [
"self.res = []\nlst = [x for x in range(1, n + 1)]\n\ndef help(lst, k, r):\n if k == 0:\n self.res.append(r)\n for i, x in enumerate(lst):\n help(lst[i + 1:], k - 1, r + [x])\nhelp(lst, k, [])\nreturn self.res",
"if k == n or k == 0:\n l = [x for x in range(1, k + 1)]\n return [l]\nres =... | <|body_start_0|>
self.res = []
lst = [x for x in range(1, n + 1)]
def help(lst, k, r):
if k == 0:
self.res.append(r)
for i, x in enumerate(lst):
help(lst[i + 1:], k - 1, r + [x])
help(lst, k, [])
return self.res
<|end_body_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def combine1(self, n, k):
""":type n: int :type k: int :rtype: List[List[int]]"""
<|body_0|>
def combine(self, n, k):
""":type n: int :type k: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.res = []
... | stack_v2_sparse_classes_36k_train_026891 | 795 | no_license | [
{
"docstring": ":type n: int :type k: int :rtype: List[List[int]]",
"name": "combine1",
"signature": "def combine1(self, n, k)"
},
{
"docstring": ":type n: int :type k: int :rtype: List[List[int]]",
"name": "combine",
"signature": "def combine(self, n, k)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combine1(self, n, k): :type n: int :type k: int :rtype: List[List[int]]
- def combine(self, n, k): :type n: int :type k: int :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combine1(self, n, k): :type n: int :type k: int :rtype: List[List[int]]
- def combine(self, n, k): :type n: int :type k: int :rtype: List[List[int]]
<|skeleton|>
class Solut... | e5b018493bbd12edcdcd0434f35d9c358106d391 | <|skeleton|>
class Solution:
def combine1(self, n, k):
""":type n: int :type k: int :rtype: List[List[int]]"""
<|body_0|>
def combine(self, n, k):
""":type n: int :type k: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def combine1(self, n, k):
""":type n: int :type k: int :rtype: List[List[int]]"""
self.res = []
lst = [x for x in range(1, n + 1)]
def help(lst, k, r):
if k == 0:
self.res.append(r)
for i, x in enumerate(lst):
h... | the_stack_v2_python_sparse | py/leetcode/77.py | wfeng1991/learnpy | train | 0 | |
9243827fce05a901bda0b6d4c621682a628394b6 | [
"for param in self.params:\n group = self._create_group_given_minentities(self.gc_min_entities_alt)\n self.verify_group_state(group.id, group.groupConfiguration.minEntities)\n delete_group_response = self.autoscale_client.delete_scaling_group(group.id, param)\n self.assertEquals(delete_group_response.st... | <|body_start_0|>
for param in self.params:
group = self._create_group_given_minentities(self.gc_min_entities_alt)
self.verify_group_state(group.id, group.groupConfiguration.minEntities)
delete_group_response = self.autoscale_client.delete_scaling_group(group.id, param)
... | System tests to verify various force delete scaling group scenarios. self.gc_min_entities_alt is set to >0 in the config. | ForceDeleteGroupTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ForceDeleteGroupTest:
"""System tests to verify various force delete scaling group scenarios. self.gc_min_entities_alt is set to >0 in the config."""
def test_minentities_over_zero(self):
"""Force deleting a scaling group with active servers, updates the desired capacity to be 0, by ... | stack_v2_sparse_classes_36k_train_026892 | 4,553 | permissive | [
{
"docstring": "Force deleting a scaling group with active servers, updates the desired capacity to be 0, by deleting all the servers and then deletes the group.",
"name": "test_minentities_over_zero",
"signature": "def test_minentities_over_zero(self)"
},
{
"docstring": "Force deleting a scalin... | 5 | null | Implement the Python class `ForceDeleteGroupTest` described below.
Class description:
System tests to verify various force delete scaling group scenarios. self.gc_min_entities_alt is set to >0 in the config.
Method signatures and docstrings:
- def test_minentities_over_zero(self): Force deleting a scaling group with ... | Implement the Python class `ForceDeleteGroupTest` described below.
Class description:
System tests to verify various force delete scaling group scenarios. self.gc_min_entities_alt is set to >0 in the config.
Method signatures and docstrings:
- def test_minentities_over_zero(self): Force deleting a scaling group with ... | 7199cdd67255fe116dbcbedea660c13453671134 | <|skeleton|>
class ForceDeleteGroupTest:
"""System tests to verify various force delete scaling group scenarios. self.gc_min_entities_alt is set to >0 in the config."""
def test_minentities_over_zero(self):
"""Force deleting a scaling group with active servers, updates the desired capacity to be 0, by ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ForceDeleteGroupTest:
"""System tests to verify various force delete scaling group scenarios. self.gc_min_entities_alt is set to >0 in the config."""
def test_minentities_over_zero(self):
"""Force deleting a scaling group with active servers, updates the desired capacity to be 0, by deleting all ... | the_stack_v2_python_sparse | autoscale_cloudroast/test_repo/autoscale/system/group/test_force_delete_group.py | rackerlabs/otter | train | 20 |
0f375f0f5bc5ff81b28b2302bee2d5b5a5954aac | [
"stack, curr = ([], root)\nres = []\nwhile stack or curr:\n if curr:\n res.append(str(curr.val))\n stack.append(curr)\n curr = curr.left\n else:\n res.append('None')\n curr = stack.pop()\n curr = curr.right\nprint(res)\nreturn ' '.join(res)",
"if not data:\n retu... | <|body_start_0|>
stack, curr = ([], root)
res = []
while stack or curr:
if curr:
res.append(str(curr.val))
stack.append(curr)
curr = curr.left
else:
res.append('None')
curr = stack.pop()
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_026893 | 4,842 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_006443 | 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:... | 63120dbaabd7c3c19633ebe952bcee4cf826b0e0 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
stack, curr = ([], root)
res = []
while stack or curr:
if curr:
res.append(str(curr.val))
stack.append(curr)
c... | the_stack_v2_python_sparse | 297. Serialize and Deserialize Binary Tree _ tee.py | CaizhiXu/LeetCode-Python-Solutions | train | 0 | |
2c014763256e8981c0b1c2f9e0cf1ed6c467728f | [
"if self.shape[0] != self.mask.sub_shape_native[0]:\n return self\narray = array_1d_util.array_1d_slim_from(array_1d_native=self, mask_1d=self.mask, sub_size=self.mask.sub_size)\nreturn array_1d.Array1D(array=array, mask=self.mask)",
"if self.shape[0] == self.mask.sub_shape_native[0]:\n return self\narray =... | <|body_start_0|>
if self.shape[0] != self.mask.sub_shape_native[0]:
return self
array = array_1d_util.array_1d_slim_from(array_1d_native=self, mask_1d=self.mask, sub_size=self.mask.sub_size)
return array_1d.Array1D(array=array, mask=self.mask)
<|end_body_0|>
<|body_start_1|>
... | AbstractArray1D | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbstractArray1D:
def slim(self):
"""Return an `Array1D` where the data is stored its `slim` representation, which is an ndarray of shape [total_unmasked_pixels * sub_size]. If it is already stored in its `slim` representation it is returned as it is. If not, it is mapped from `native` to... | stack_v2_sparse_classes_36k_train_026894 | 1,615 | permissive | [
{
"docstring": "Return an `Array1D` where the data is stored its `slim` representation, which is an ndarray of shape [total_unmasked_pixels * sub_size]. If it is already stored in its `slim` representation it is returned as it is. If not, it is mapped from `native` to `slim` and returned as a new `Array1D`.",
... | 2 | null | Implement the Python class `AbstractArray1D` described below.
Class description:
Implement the AbstractArray1D class.
Method signatures and docstrings:
- def slim(self): Return an `Array1D` where the data is stored its `slim` representation, which is an ndarray of shape [total_unmasked_pixels * sub_size]. If it is al... | Implement the Python class `AbstractArray1D` described below.
Class description:
Implement the AbstractArray1D class.
Method signatures and docstrings:
- def slim(self): Return an `Array1D` where the data is stored its `slim` representation, which is an ndarray of shape [total_unmasked_pixels * sub_size]. If it is al... | c21e8859bdb20737352147b9904797ac99985b73 | <|skeleton|>
class AbstractArray1D:
def slim(self):
"""Return an `Array1D` where the data is stored its `slim` representation, which is an ndarray of shape [total_unmasked_pixels * sub_size]. If it is already stored in its `slim` representation it is returned as it is. If not, it is mapped from `native` to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AbstractArray1D:
def slim(self):
"""Return an `Array1D` where the data is stored its `slim` representation, which is an ndarray of shape [total_unmasked_pixels * sub_size]. If it is already stored in its `slim` representation it is returned as it is. If not, it is mapped from `native` to `slim` and re... | the_stack_v2_python_sparse | autoarray/structures/arrays/one_d/abstract_array_1d.py | jonathanfrawley/PyAutoArray_copy | train | 0 | |
21d1e5a6c4c7bacbf2cf4bbc825f01b7ae49149a | [
"if value not in ['gaussian', 'sp', 'rain']:\n self.fail('invalid_noise')\nreturn value",
"try:\n attrs['image_url'] = get_full_url(attrs['image_url'])\nexcept FileNotFoundError:\n self.fail('img_doesnt_exists')\nreturn attrs"
] | <|body_start_0|>
if value not in ['gaussian', 'sp', 'rain']:
self.fail('invalid_noise')
return value
<|end_body_0|>
<|body_start_1|>
try:
attrs['image_url'] = get_full_url(attrs['image_url'])
except FileNotFoundError:
self.fail('img_doesnt_exists')
... | Serializer validates noise type | NoiseTypeSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoiseTypeSerializer:
"""Serializer validates noise type"""
def validate_noise(self, value):
"""validation of noise type"""
<|body_0|>
def validate(self, attrs):
"""changes image url to full url"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if ... | stack_v2_sparse_classes_36k_train_026895 | 3,334 | no_license | [
{
"docstring": "validation of noise type",
"name": "validate_noise",
"signature": "def validate_noise(self, value)"
},
{
"docstring": "changes image url to full url",
"name": "validate",
"signature": "def validate(self, attrs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006563 | Implement the Python class `NoiseTypeSerializer` described below.
Class description:
Serializer validates noise type
Method signatures and docstrings:
- def validate_noise(self, value): validation of noise type
- def validate(self, attrs): changes image url to full url | Implement the Python class `NoiseTypeSerializer` described below.
Class description:
Serializer validates noise type
Method signatures and docstrings:
- def validate_noise(self, value): validation of noise type
- def validate(self, attrs): changes image url to full url
<|skeleton|>
class NoiseTypeSerializer:
"""... | 525f4ced839fe0176304c3feacd436962bcd8a0e | <|skeleton|>
class NoiseTypeSerializer:
"""Serializer validates noise type"""
def validate_noise(self, value):
"""validation of noise type"""
<|body_0|>
def validate(self, attrs):
"""changes image url to full url"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NoiseTypeSerializer:
"""Serializer validates noise type"""
def validate_noise(self, value):
"""validation of noise type"""
if value not in ['gaussian', 'sp', 'rain']:
self.fail('invalid_noise')
return value
def validate(self, attrs):
"""changes image url t... | the_stack_v2_python_sparse | backend/images/serializers.py | jsz5/denoising_app | train | 0 |
18af1d7efde7b5b07149f6fb68c9c6ff43d78bd5 | [
"printtime('Starting mashsippr analysis pipeline', self.starttime)\nif not self.pipeline:\n objects = Objectprep(self)\n objects.objectprep()\n self.runmetadata = objects.samples\nMash(self, self.analysistype)",
"self.commit = str(pipelinecommit)\nself.starttime = startingtime\nself.homepath = scriptpath... | <|body_start_0|>
printtime('Starting mashsippr analysis pipeline', self.starttime)
if not self.pipeline:
objects = Objectprep(self)
objects.objectprep()
self.runmetadata = objects.samples
Mash(self, self.analysistype)
<|end_body_0|>
<|body_start_1|>
s... | MashSippr | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MashSippr:
def runner(self):
"""Run the necessary methods in the correct order"""
<|body_0|>
def __init__(self, args, pipelinecommit, startingtime, scriptpath):
""":param args: command line arguments :param pipelinecommit: pipeline commit or version :param startingti... | stack_v2_sparse_classes_36k_train_026896 | 6,801 | permissive | [
{
"docstring": "Run the necessary methods in the correct order",
"name": "runner",
"signature": "def runner(self)"
},
{
"docstring": ":param args: command line arguments :param pipelinecommit: pipeline commit or version :param startingtime: time the script was started :param scriptpath: home pat... | 2 | stack_v2_sparse_classes_30k_train_017892 | Implement the Python class `MashSippr` described below.
Class description:
Implement the MashSippr class.
Method signatures and docstrings:
- def runner(self): Run the necessary methods in the correct order
- def __init__(self, args, pipelinecommit, startingtime, scriptpath): :param args: command line arguments :para... | Implement the Python class `MashSippr` described below.
Class description:
Implement the MashSippr class.
Method signatures and docstrings:
- def runner(self): Run the necessary methods in the correct order
- def __init__(self, args, pipelinecommit, startingtime, scriptpath): :param args: command line arguments :para... | b4cc546485bddbbe26de6a80b629350314db6422 | <|skeleton|>
class MashSippr:
def runner(self):
"""Run the necessary methods in the correct order"""
<|body_0|>
def __init__(self, args, pipelinecommit, startingtime, scriptpath):
""":param args: command line arguments :param pipelinecommit: pipeline commit or version :param startingti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MashSippr:
def runner(self):
"""Run the necessary methods in the correct order"""
printtime('Starting mashsippr analysis pipeline', self.starttime)
if not self.pipeline:
objects = Objectprep(self)
objects.objectprep()
self.runmetadata = objects.sampl... | the_stack_v2_python_sparse | genemethods/MASHsippr/mashsippr.py | OLC-LOC-Bioinformatics/genemethods | train | 1 | |
668fc6b8d41dc44d72aea56c92eb0e6c3e297b4c | [
"self.data_frame: Optional[pd.DataFrame] = None\nself.frame_info = None\nself.workflow = kwargs.pop(str('workflow'), None)\nsuper().__init__(*args, **kwargs)",
"try:\n pandas.verify_data_frame(self.data_frame)\nexcept OnTaskDataFrameNoKey as exc:\n self.add_error(None, str(exc))\n return\ntry:\n self.... | <|body_start_0|>
self.data_frame: Optional[pd.DataFrame] = None
self.frame_info = None
self.workflow = kwargs.pop(str('workflow'), None)
super().__init__(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
try:
pandas.verify_data_frame(self.data_frame)
except On... | Basic class to use for inheritance. | UploadBasic | [
"LGPL-2.0-or-later",
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"LGPL-2.1-only",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UploadBasic:
"""Basic class to use for inheritance."""
def __init__(self, *args, **kwargs):
"""Store the workflow for further processing."""
<|body_0|>
def validate_data_frame(self):
"""Check that the dataframe can be properly stored. :return: The cleaned data"""... | stack_v2_sparse_classes_36k_train_026897 | 10,714 | permissive | [
{
"docstring": "Store the workflow for further processing.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Check that the dataframe can be properly stored. :return: The cleaned data",
"name": "validate_data_frame",
"signature": "def validate_da... | 2 | stack_v2_sparse_classes_30k_train_001254 | Implement the Python class `UploadBasic` described below.
Class description:
Basic class to use for inheritance.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Store the workflow for further processing.
- def validate_data_frame(self): Check that the dataframe can be properly stored. :return... | Implement the Python class `UploadBasic` described below.
Class description:
Basic class to use for inheritance.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Store the workflow for further processing.
- def validate_data_frame(self): Check that the dataframe can be properly stored. :return... | c432745dfff932cbe7397100422d49df78f0a882 | <|skeleton|>
class UploadBasic:
"""Basic class to use for inheritance."""
def __init__(self, *args, **kwargs):
"""Store the workflow for further processing."""
<|body_0|>
def validate_data_frame(self):
"""Check that the dataframe can be properly stored. :return: The cleaned data"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UploadBasic:
"""Basic class to use for inheritance."""
def __init__(self, *args, **kwargs):
"""Store the workflow for further processing."""
self.data_frame: Optional[pd.DataFrame] = None
self.frame_info = None
self.workflow = kwargs.pop(str('workflow'), None)
supe... | the_stack_v2_python_sparse | ontask/dataops/forms/upload.py | abelardopardo/ontask_b | train | 43 |
739c3b2989434fdac35edf6948c601c59db85d42 | [
"if not PIL:\n raise ImportError('ImageHash pipeline is not available - install \"pipeline\" extra to enable')\nself.algorithm = algorithm\nself.size = size\nself.strings = strings",
"values = [images] if not isinstance(images, list) else images\nvalues = [Image.open(image) if isinstance(image, str) else image... | <|body_start_0|>
if not PIL:
raise ImportError('ImageHash pipeline is not available - install "pipeline" extra to enable')
self.algorithm = algorithm
self.size = size
self.strings = strings
<|end_body_0|>
<|body_start_1|>
values = [images] if not isinstance(images, l... | Generates perceptual image hashes. These hashes can be used to detect near-duplicate images. This method is not backed by machine learning models and not intended to find conceptually similar images. | ImageHash | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageHash:
"""Generates perceptual image hashes. These hashes can be used to detect near-duplicate images. This method is not backed by machine learning models and not intended to find conceptually similar images."""
def __init__(self, algorithm='average', size=8, strings=True):
"""C... | stack_v2_sparse_classes_36k_train_026898 | 2,546 | permissive | [
{
"docstring": "Creates an ImageHash pipeline. Args: algorithm: image hashing algorithm (average, perceptual, difference, wavelet, color) size: hash size strings: outputs hex strings if True (default), otherwise the pipeline returns numpy arrays",
"name": "__init__",
"signature": "def __init__(self, alg... | 3 | null | Implement the Python class `ImageHash` described below.
Class description:
Generates perceptual image hashes. These hashes can be used to detect near-duplicate images. This method is not backed by machine learning models and not intended to find conceptually similar images.
Method signatures and docstrings:
- def __i... | Implement the Python class `ImageHash` described below.
Class description:
Generates perceptual image hashes. These hashes can be used to detect near-duplicate images. This method is not backed by machine learning models and not intended to find conceptually similar images.
Method signatures and docstrings:
- def __i... | 789a4555cb60ee9cdfa69afae5a5236d197e2b07 | <|skeleton|>
class ImageHash:
"""Generates perceptual image hashes. These hashes can be used to detect near-duplicate images. This method is not backed by machine learning models and not intended to find conceptually similar images."""
def __init__(self, algorithm='average', size=8, strings=True):
"""C... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageHash:
"""Generates perceptual image hashes. These hashes can be used to detect near-duplicate images. This method is not backed by machine learning models and not intended to find conceptually similar images."""
def __init__(self, algorithm='average', size=8, strings=True):
"""Creates an Ima... | the_stack_v2_python_sparse | src/python/txtai/pipeline/image/imagehash.py | neuml/txtai | train | 4,804 |
be9c84ce8c5d55f7b08a5e5d1ddbf2b7373fe49b | [
"FetcherApp.__init__(self, classify, critical_max_repeat=10, critical_sleep_time=60)\ncookie_string = 'PHPSESSID=btqkg9amjrtoeev8coq0m78396; USERINFO=n6nxTHTY%2BJA39z6CpNB4eKN8f0KsYLjAQTwPe%2BhLHLruEbjaeh4ulhWAS5RysUM%2B; Hm_lvt_0bcb16196dddadaf61c121323a9ec0b6=1472528976; Hm_lpvt_0bcb16196dddadaf61c121323a9ec0b6=1... | <|body_start_0|>
FetcherApp.__init__(self, classify, critical_max_repeat=10, critical_sleep_time=60)
cookie_string = 'PHPSESSID=btqkg9amjrtoeev8coq0m78396; USERINFO=n6nxTHTY%2BJA39z6CpNB4eKN8f0KsYLjAQTwPe%2BhLHLruEbjaeh4ulhWAS5RysUM%2B; Hm_lvt_0bcb16196dddadaf61c121323a9ec0b6=1472528976; Hm_lpvt_0bcb161... | class of FetcherASO | FetcherASO | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FetcherASO:
"""class of FetcherASO"""
def __init__(self, classify):
"""constructor"""
<|body_0|>
def url_fetch(self, url, keys, critical, repeat):
"""fetch the content of a url"""
<|body_1|>
def htm_parse(self, url, keys, cur_html):
"""parse ... | stack_v2_sparse_classes_36k_train_026899 | 17,241 | no_license | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self, classify)"
},
{
"docstring": "fetch the content of a url",
"name": "url_fetch",
"signature": "def url_fetch(self, url, keys, critical, repeat)"
},
{
"docstring": "parse the content of a url :return... | 3 | stack_v2_sparse_classes_30k_train_002337 | Implement the Python class `FetcherASO` described below.
Class description:
class of FetcherASO
Method signatures and docstrings:
- def __init__(self, classify): constructor
- def url_fetch(self, url, keys, critical, repeat): fetch the content of a url
- def htm_parse(self, url, keys, cur_html): parse the content of ... | Implement the Python class `FetcherASO` described below.
Class description:
class of FetcherASO
Method signatures and docstrings:
- def __init__(self, classify): constructor
- def url_fetch(self, url, keys, critical, repeat): fetch the content of a url
- def htm_parse(self, url, keys, cur_html): parse the content of ... | 8d40508a568fcdeb091c51c95050bb936621613f | <|skeleton|>
class FetcherASO:
"""class of FetcherASO"""
def __init__(self, classify):
"""constructor"""
<|body_0|>
def url_fetch(self, url, keys, critical, repeat):
"""fetch the content of a url"""
<|body_1|>
def htm_parse(self, url, keys, cur_html):
"""parse ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FetcherASO:
"""class of FetcherASO"""
def __init__(self, classify):
"""constructor"""
FetcherApp.__init__(self, classify, critical_max_repeat=10, critical_sleep_time=60)
cookie_string = 'PHPSESSID=btqkg9amjrtoeev8coq0m78396; USERINFO=n6nxTHTY%2BJA39z6CpNB4eKN8f0KsYLjAQTwPe%2BhLHLr... | the_stack_v2_python_sparse | demos_apps/app_fetcher.py | Java-via/AppSpider | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.