blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b584c2df4b677e43de1b1bfa77e51f7b47fee9b4 | [
"self.name = buffer_name\nself.poligons = []\ncur = con.cursor()\ncur.execute('select id from acumulos.buffers where nome=%s', (self.name,))\nids = cur.fetchall()\nself.id = ids[0][0]",
"cur = con.cursor()\ncur.execute('select id,st_astext(poligono) from acumulos.poligonos where id_buffer=%s', (self.id,))\nrespos... | <|body_start_0|>
self.name = buffer_name
self.poligons = []
cur = con.cursor()
cur.execute('select id from acumulos.buffers where nome=%s', (self.name,))
ids = cur.fetchall()
self.id = ids[0][0]
<|end_body_0|>
<|body_start_1|>
cur = con.cursor()
cur.execu... | Clase Buffer | Buffer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Buffer:
"""Clase Buffer"""
def __init__(self, con, buffer_name):
"""Inicializa o buffer dando un nome :param con: conexión activa :param buffer_name: Nome de buffer na base de datos"""
<|body_0|>
def fill_poligons(self, con):
"""Enche unha lista cos polígonos :pa... | stack_v2_sparse_classes_75kplus_train_074200 | 2,140 | no_license | [
{
"docstring": "Inicializa o buffer dando un nome :param con: conexión activa :param buffer_name: Nome de buffer na base de datos",
"name": "__init__",
"signature": "def __init__(self, con, buffer_name)"
},
{
"docstring": "Enche unha lista cos polígonos :param con: conexión :return:",
"name"... | 3 | stack_v2_sparse_classes_30k_train_031604 | Implement the Python class `Buffer` described below.
Class description:
Clase Buffer
Method signatures and docstrings:
- def __init__(self, con, buffer_name): Inicializa o buffer dando un nome :param con: conexión activa :param buffer_name: Nome de buffer na base de datos
- def fill_poligons(self, con): Enche unha li... | Implement the Python class `Buffer` described below.
Class description:
Clase Buffer
Method signatures and docstrings:
- def __init__(self, con, buffer_name): Inicializa o buffer dando un nome :param con: conexión activa :param buffer_name: Nome de buffer na base de datos
- def fill_poligons(self, con): Enche unha li... | e3c577e6048d546706df0c6191a0d0d10a58d3d8 | <|skeleton|>
class Buffer:
"""Clase Buffer"""
def __init__(self, con, buffer_name):
"""Inicializa o buffer dando un nome :param con: conexión activa :param buffer_name: Nome de buffer na base de datos"""
<|body_0|>
def fill_poligons(self, con):
"""Enche unha lista cos polígonos :pa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Buffer:
"""Clase Buffer"""
def __init__(self, con, buffer_name):
"""Inicializa o buffer dando un nome :param con: conexión activa :param buffer_name: Nome de buffer na base de datos"""
self.name = buffer_name
self.poligons = []
cur = con.cursor()
cur.execute('selec... | the_stack_v2_python_sparse | cleanatlantic/buffer.py | pedromontero/CLEANATLANTIC | train | 1 |
ed7225fd64634e43f6bf3ab700171e4610856faa | [
"self.player = player or ExternalPlayer(0)\nself.coder = coder\nself.coder.encode(handshake)\ntry:\n self.__player_id__ = int(handshake)\nexcept:\n self.__player_id__ = 1",
"try:\n self.wait_for_ok()\n self.update_for_start()\n while True:\n self.wait_for_choice_request()\n self.wait_... | <|body_start_0|>
self.player = player or ExternalPlayer(0)
self.coder = coder
self.coder.encode(handshake)
try:
self.__player_id__ = int(handshake)
except:
self.__player_id__ = 1
<|end_body_0|>
<|body_start_1|>
try:
self.wait_for_ok()
... | Implements a finite state machine of the messages acceptable by the Player, and sends responses from an ExternalPlayer | ProxyDealer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProxyDealer:
"""Implements a finite state machine of the messages acceptable by the Player, and sends responses from an ExternalPlayer"""
def __init__(self, coder, player=None, handshake='Hello'):
"""Creates a ProxyDealer, and sends an initial handshake to it. :param coder: a JSONSoc... | stack_v2_sparse_classes_75kplus_train_074201 | 3,632 | permissive | [
{
"docstring": "Creates a ProxyDealer, and sends an initial handshake to it. :param coder: a JSONSocket connected to a server :param player: Optionally, a class to use as a player agent. If none is found, :param handshake: a String to send as a handshake to the Server",
"name": "__init__",
"signature": ... | 6 | stack_v2_sparse_classes_30k_train_045193 | Implement the Python class `ProxyDealer` described below.
Class description:
Implements a finite state machine of the messages acceptable by the Player, and sends responses from an ExternalPlayer
Method signatures and docstrings:
- def __init__(self, coder, player=None, handshake='Hello'): Creates a ProxyDealer, and ... | Implement the Python class `ProxyDealer` described below.
Class description:
Implements a finite state machine of the messages acceptable by the Player, and sends responses from an ExternalPlayer
Method signatures and docstrings:
- def __init__(self, coder, player=None, handshake='Hello'): Creates a ProxyDealer, and ... | ab0de37f9ed7f9e545067726ec514f73bdeb3b51 | <|skeleton|>
class ProxyDealer:
"""Implements a finite state machine of the messages acceptable by the Player, and sends responses from an ExternalPlayer"""
def __init__(self, coder, player=None, handshake='Hello'):
"""Creates a ProxyDealer, and sends an initial handshake to it. :param coder: a JSONSoc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProxyDealer:
"""Implements a finite state machine of the messages acceptable by the Player, and sends responses from an ExternalPlayer"""
def __init__(self, coder, player=None, handshake='Hello'):
"""Creates a ProxyDealer, and sends an initial handshake to it. :param coder: a JSONSocket connected... | the_stack_v2_python_sparse | evolution/proxy_dealer.py | ctbeiser/Evolution | train | 0 |
8335333d2be629b5817a9b1f3105a8e068d02f4c | [
"if not isinstance(dirloc, pathlib.Path):\n dirloc = pathlib.Path(dirloc)\nif dirloc.is_dir():\n return any((fpath.suffix.lower() in cls.AUDIO_EXTENSIONS for fpath in dirloc.iterdir()))\nreturn False",
"o = []\nfor fname in os.listdir(dir_loc):\n _, fname_ext = os.path.splitext(fname)\n if fname_ext i... | <|body_start_0|>
if not isinstance(dirloc, pathlib.Path):
dirloc = pathlib.Path(dirloc)
if dirloc.is_dir():
return any((fpath.suffix.lower() in cls.AUDIO_EXTENSIONS for fpath in dirloc.iterdir()))
return False
<|end_body_0|>
<|body_start_1|>
o = []
for fn... | This is a more or less static class that can be used to load audiobooks. | AudiobookLoader | [
"LicenseRef-scancode-warranty-disclaimer",
"CC0-1.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AudiobookLoader:
"""This is a more or less static class that can be used to load audiobooks."""
def is_audio(cls, dirloc: PathType) -> bool:
"""Function to determine if a directory contains an audiobook. The assumption is that in this context, any directory containing at least one fi... | stack_v2_sparse_classes_75kplus_train_074202 | 9,402 | permissive | [
{
"docstring": "Function to determine if a directory contains an audiobook. The assumption is that in this context, any directory containing at least one file with the AUDIO_EXTENSIONS is, itself, an audiobook. :param dirloc: The directory to test. :return: Returns boolean value whether or not it's an audiobook... | 5 | stack_v2_sparse_classes_30k_train_008855 | Implement the Python class `AudiobookLoader` described below.
Class description:
This is a more or less static class that can be used to load audiobooks.
Method signatures and docstrings:
- def is_audio(cls, dirloc: PathType) -> bool: Function to determine if a directory contains an audiobook. The assumption is that ... | Implement the Python class `AudiobookLoader` described below.
Class description:
This is a more or less static class that can be used to load audiobooks.
Method signatures and docstrings:
- def is_audio(cls, dirloc: PathType) -> bool: Function to determine if a directory contains an audiobook. The assumption is that ... | 69bd569910f90e2aba9c0032e05b0eef38f3181b | <|skeleton|>
class AudiobookLoader:
"""This is a more or less static class that can be used to load audiobooks."""
def is_audio(cls, dirloc: PathType) -> bool:
"""Function to determine if a directory contains an audiobook. The assumption is that in this context, any directory containing at least one fi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AudiobookLoader:
"""This is a more or less static class that can be used to load audiobooks."""
def is_audio(cls, dirloc: PathType) -> bool:
"""Function to determine if a directory contains an audiobook. The assumption is that in this context, any directory containing at least one file with the A... | the_stack_v2_python_sparse | src/audio_feeder/directory_parser.py | pganssle/audio-feeder | train | 16 |
d5fe262f36fab6d42d649fbc882387158f06b3be | [
"if value.org_unit_type in self.instance.form.org_unit_types.all():\n try:\n return OrgUnit.objects.filter_for_user_and_app_id(self.context['request'].user, None).get(pk=value.pk)\n except OrgUnit.DoesNotExist:\n pass\nraise serializers.ValidationError('Org unit type not assigned to this form or... | <|body_start_0|>
if value.org_unit_type in self.instance.form.org_unit_types.all():
try:
return OrgUnit.objects.filter_for_user_and_app_id(self.context['request'].user, None).get(pk=value.pk)
except OrgUnit.DoesNotExist:
pass
raise serializers.Vali... | InstanceSerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstanceSerializer:
def validate_org_unit(self, value):
"""Check if user has acces to this org_unit."""
<|body_0|>
def validate_period(self, value):
"""Check if period is of self.instance.form.period_type."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_074203 | 16,776 | permissive | [
{
"docstring": "Check if user has acces to this org_unit.",
"name": "validate_org_unit",
"signature": "def validate_org_unit(self, value)"
},
{
"docstring": "Check if period is of self.instance.form.period_type.",
"name": "validate_period",
"signature": "def validate_period(self, value)"... | 2 | stack_v2_sparse_classes_30k_train_046805 | Implement the Python class `InstanceSerializer` described below.
Class description:
Implement the InstanceSerializer class.
Method signatures and docstrings:
- def validate_org_unit(self, value): Check if user has acces to this org_unit.
- def validate_period(self, value): Check if period is of self.instance.form.per... | Implement the Python class `InstanceSerializer` described below.
Class description:
Implement the InstanceSerializer class.
Method signatures and docstrings:
- def validate_org_unit(self, value): Check if user has acces to this org_unit.
- def validate_period(self, value): Check if period is of self.instance.form.per... | 4d3a9d3faa6b3ed3a2e08c728cc4f03e5a0bbcb6 | <|skeleton|>
class InstanceSerializer:
def validate_org_unit(self, value):
"""Check if user has acces to this org_unit."""
<|body_0|>
def validate_period(self, value):
"""Check if period is of self.instance.form.period_type."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InstanceSerializer:
def validate_org_unit(self, value):
"""Check if user has acces to this org_unit."""
if value.org_unit_type in self.instance.form.org_unit_types.all():
try:
return OrgUnit.objects.filter_for_user_and_app_id(self.context['request'].user, None).get(... | the_stack_v2_python_sparse | iaso/api/instances.py | lpontis/iaso | train | 0 | |
4df4d6233462111bf0db60982323ccf08ba48edc | [
"if a * b < 0:\n return -(abs(a) / abs(b))\nelse:\n return a / b",
"if not s:\n return 0\nnumstk = []\nnum = 0\nop = '+'\nfor i in xrange(len(s)):\n if s[i].isdigit():\n num = num * 10 + int(s[i])\n if not s[i].isdigit() and s[i] != ' ' or i == len(s) - 1:\n if op == '+' or op == '-':... | <|body_start_0|>
if a * b < 0:
return -(abs(a) / abs(b))
else:
return a / b
<|end_body_0|>
<|body_start_1|>
if not s:
return 0
numstk = []
num = 0
op = '+'
for i in xrange(len(s)):
if s[i].isdigit():
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def divideNeg(self, a, b):
"""python divide -3/2==-2"""
<|body_0|>
def calculate(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if a * b < 0:
return -(abs(a) / abs(b))
else:
... | stack_v2_sparse_classes_75kplus_train_074204 | 1,319 | permissive | [
{
"docstring": "python divide -3/2==-2",
"name": "divideNeg",
"signature": "def divideNeg(self, a, b)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "calculate",
"signature": "def calculate(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002128 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def divideNeg(self, a, b): python divide -3/2==-2
- def calculate(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def divideNeg(self, a, b): python divide -3/2==-2
- def calculate(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def divideNeg(self, a, b):
"""pyth... | 86f1cb98de801f58c39d9a48ce9de12df7303d20 | <|skeleton|>
class Solution:
def divideNeg(self, a, b):
"""python divide -3/2==-2"""
<|body_0|>
def calculate(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def divideNeg(self, a, b):
"""python divide -3/2==-2"""
if a * b < 0:
return -(abs(a) / abs(b))
else:
return a / b
def calculate(self, s):
""":type s: str :rtype: int"""
if not s:
return 0
numstk = []
nu... | the_stack_v2_python_sparse | 227-Basic-Calculator-II/solution.py | Tanych/CodeTracking | train | 0 | |
13b2b828ed1db2879c251acad926e256ef46f702 | [
"self.timeout = scr_env.param.get('SCR_WATCHDOG_TIMEOUT')\nself.timeout_pfs = scr_env.param.get('SCR_WATCHDOG_TIMEOUT_PFS')\nif self.timeout is not None and self.timeout_pfs is not None:\n self.timeout = int(self.timeout)\n self.timeout_pfs = int(self.timeout_pfs)\n self.launcher = scr_env.launcher\n se... | <|body_start_0|>
self.timeout = scr_env.param.get('SCR_WATCHDOG_TIMEOUT')
self.timeout_pfs = scr_env.param.get('SCR_WATCHDOG_TIMEOUT_PFS')
if self.timeout is not None and self.timeout_pfs is not None:
self.timeout = int(self.timeout)
self.timeout_pfs = int(self.timeout_pf... | This class attempts to detect hanging applications in order to avoid wasting allocations Use of the SCR_Watchdog requires 3 configuration variables to be set: SCR_WATCHDOG=1 The watchdog must be enabled (set to '1') We must also have an expected time (in seconds) to check for existence of checkpoint files. For example:... | SCR_Watchdog | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SCR_Watchdog:
"""This class attempts to detect hanging applications in order to avoid wasting allocations Use of the SCR_Watchdog requires 3 configuration variables to be set: SCR_WATCHDOG=1 The watchdog must be enabled (set to '1') We must also have an expected time (in seconds) to check for exi... | stack_v2_sparse_classes_75kplus_train_074205 | 4,737 | permissive | [
{
"docstring": "The SCR_Watchdog class is instantiated once, before any jobstep is ever launched, if SCR_Watchdog is enabled. Set timeout values from the environment. Copy the reference to the Joblauncher from the SCR_Env class. Instantiate an instance of SCRFlushFile using the provided prefix for later checkin... | 3 | stack_v2_sparse_classes_30k_train_033246 | Implement the Python class `SCR_Watchdog` described below.
Class description:
This class attempts to detect hanging applications in order to avoid wasting allocations Use of the SCR_Watchdog requires 3 configuration variables to be set: SCR_WATCHDOG=1 The watchdog must be enabled (set to '1') We must also have an expe... | Implement the Python class `SCR_Watchdog` described below.
Class description:
This class attempts to detect hanging applications in order to avoid wasting allocations Use of the SCR_Watchdog requires 3 configuration variables to be set: SCR_WATCHDOG=1 The watchdog must be enabled (set to '1') We must also have an expe... | 1d78ff0bccd02a9443ad07844c4ca75129a537a1 | <|skeleton|>
class SCR_Watchdog:
"""This class attempts to detect hanging applications in order to avoid wasting allocations Use of the SCR_Watchdog requires 3 configuration variables to be set: SCR_WATCHDOG=1 The watchdog must be enabled (set to '1') We must also have an expected time (in seconds) to check for exi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SCR_Watchdog:
"""This class attempts to detect hanging applications in order to avoid wasting allocations Use of the SCR_Watchdog requires 3 configuration variables to be set: SCR_WATCHDOG=1 The watchdog must be enabled (set to '1') We must also have an expected time (in seconds) to check for existence of che... | the_stack_v2_python_sparse | scripts/python/scrjob/scr_watchdog.py | LLNL/scr | train | 84 |
f9d898b49d3a88471a106d1c524279be9bf97144 | [
"self.code = _code_\nself.title: Optional[str] = _title_\nself.describe: Optional[str] = _describe_\nself.options: Dict[Code, str] = dict()\npass",
"if _code_ not in self.options:\n self.options[_code_] = _text_\n return True\nreturn False"
] | <|body_start_0|>
self.code = _code_
self.title: Optional[str] = _title_
self.describe: Optional[str] = _describe_
self.options: Dict[Code, str] = dict()
pass
<|end_body_0|>
<|body_start_1|>
if _code_ not in self.options:
self.options[_code_] = _text_
... | Class contains all data use for display scene. | SceneFrame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SceneFrame:
"""Class contains all data use for display scene."""
def __init__(self, _code_: Code, _title_: Optional[str]=None, _describe_: Optional[str]=None):
""":param _title_: Scene title. :type _title_: str :param _describe_: Scene describe. :type _describe_: str :param _img_: Sc... | stack_v2_sparse_classes_75kplus_train_074206 | 2,210 | no_license | [
{
"docstring": ":param _title_: Scene title. :type _title_: str :param _describe_: Scene describe. :type _describe_: str :param _img_: Scene image path. :type _img_: Path",
"name": "__init__",
"signature": "def __init__(self, _code_: Code, _title_: Optional[str]=None, _describe_: Optional[str]=None)"
... | 2 | stack_v2_sparse_classes_30k_train_048929 | Implement the Python class `SceneFrame` described below.
Class description:
Class contains all data use for display scene.
Method signatures and docstrings:
- def __init__(self, _code_: Code, _title_: Optional[str]=None, _describe_: Optional[str]=None): :param _title_: Scene title. :type _title_: str :param _describe... | Implement the Python class `SceneFrame` described below.
Class description:
Class contains all data use for display scene.
Method signatures and docstrings:
- def __init__(self, _code_: Code, _title_: Optional[str]=None, _describe_: Optional[str]=None): :param _title_: Scene title. :type _title_: str :param _describe... | c08887ef940685519c65932c9a955089ec3db5a9 | <|skeleton|>
class SceneFrame:
"""Class contains all data use for display scene."""
def __init__(self, _code_: Code, _title_: Optional[str]=None, _describe_: Optional[str]=None):
""":param _title_: Scene title. :type _title_: str :param _describe_: Scene describe. :type _describe_: str :param _img_: Sc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SceneFrame:
"""Class contains all data use for display scene."""
def __init__(self, _code_: Code, _title_: Optional[str]=None, _describe_: Optional[str]=None):
""":param _title_: Scene title. :type _title_: str :param _describe_: Scene describe. :type _describe_: str :param _img_: Scene image pat... | the_stack_v2_python_sparse | data_frame.py | paladynlowca/py_creator | train | 0 |
f0d0ba5425629ac8e6deb9303324bd8d56b47de2 | [
"self.command = command\nself.left = left if left else ''\nself.right = right if right else ''\nself.aux = kwarg['aux'] if 'aux' in kwarg else None\nself.leftOffset = kwarg['leftOffset'] if 'leftOffset' in kwarg else None\nself.rightOffset = kwarg['rightOffset'] if 'rightOffset' in kwarg else None\nself.leftNeedsRe... | <|body_start_0|>
self.command = command
self.left = left if left else ''
self.right = right if right else ''
self.aux = kwarg['aux'] if 'aux' in kwarg else None
self.leftOffset = kwarg['leftOffset'] if 'leftOffset' in kwarg else None
self.rightOffset = kwarg['rightOffset'... | The class for a node of assembly, essentially each node is a line in assembly | ASMNode | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ASMNode:
"""The class for a node of assembly, essentially each node is a line in assembly"""
def __init__(self, command, left, right, **kwarg):
"""Initializes the ASMNode object Args: command: The operation (mov, add, etc.) left: The left side of the operation (mov x,y), left is x ri... | stack_v2_sparse_classes_75kplus_train_074207 | 4,120 | no_license | [
{
"docstring": "Initializes the ASMNode object Args: command: The operation (mov, add, etc.) left: The left side of the operation (mov x,y), left is x right: The right side of the operation (mov x,y) right is y kwargs: A dictionary of values that give various metadata about the command (will it need a register,... | 2 | stack_v2_sparse_classes_30k_train_050709 | Implement the Python class `ASMNode` described below.
Class description:
The class for a node of assembly, essentially each node is a line in assembly
Method signatures and docstrings:
- def __init__(self, command, left, right, **kwarg): Initializes the ASMNode object Args: command: The operation (mov, add, etc.) lef... | Implement the Python class `ASMNode` described below.
Class description:
The class for a node of assembly, essentially each node is a line in assembly
Method signatures and docstrings:
- def __init__(self, command, left, right, **kwarg): Initializes the ASMNode object Args: command: The operation (mov, add, etc.) lef... | 625308a416638e42d81100b73e054152e8c6620e | <|skeleton|>
class ASMNode:
"""The class for a node of assembly, essentially each node is a line in assembly"""
def __init__(self, command, left, right, **kwarg):
"""Initializes the ASMNode object Args: command: The operation (mov, add, etc.) left: The left side of the operation (mov x,y), left is x ri... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ASMNode:
"""The class for a node of assembly, essentially each node is a line in assembly"""
def __init__(self, command, left, right, **kwarg):
"""Initializes the ASMNode object Args: command: The operation (mov, add, etc.) left: The left side of the operation (mov x,y), left is x right: The righ... | the_stack_v2_python_sparse | src/backend/ASMNode.py | bensonalec/CCBWIPFSR-C-Compiler | train | 0 |
7d48359e5b9532ada9a0bf6ce0859bfacef18e85 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AppliedConditionalAccessPolicy()",
"from .applied_conditional_access_policy_result import AppliedConditionalAccessPolicyResult\nfrom .applied_conditional_access_policy_result import AppliedConditionalAccessPolicyResult\nfields: Dict[st... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AppliedConditionalAccessPolicy()
<|end_body_0|>
<|body_start_1|>
from .applied_conditional_access_policy_result import AppliedConditionalAccessPolicyResult
from .applied_conditional_acce... | AppliedConditionalAccessPolicy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AppliedConditionalAccessPolicy:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AppliedConditionalAccessPolicy:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator v... | stack_v2_sparse_classes_75kplus_train_074208 | 4,450 | 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: AppliedConditionalAccessPolicy",
"name": "create_from_discriminator_value",
"signature": "def create_from_di... | 3 | stack_v2_sparse_classes_30k_train_005706 | Implement the Python class `AppliedConditionalAccessPolicy` described below.
Class description:
Implement the AppliedConditionalAccessPolicy class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AppliedConditionalAccessPolicy: Creates a new instance of... | Implement the Python class `AppliedConditionalAccessPolicy` described below.
Class description:
Implement the AppliedConditionalAccessPolicy class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AppliedConditionalAccessPolicy: Creates a new instance of... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AppliedConditionalAccessPolicy:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AppliedConditionalAccessPolicy:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator v... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AppliedConditionalAccessPolicy:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AppliedConditionalAccessPolicy:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and creat... | the_stack_v2_python_sparse | msgraph/generated/models/applied_conditional_access_policy.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
fb4d6cd3c81c2cfbe254f5da5685f93084a77e34 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn TeamworkApplicationIdentity()",
"from .identity import Identity\nfrom .teamwork_application_identity_type import TeamworkApplicationIdentityType\nfrom .identity import Identity\nfrom .teamwork_application_identity_type import TeamworkA... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return TeamworkApplicationIdentity()
<|end_body_0|>
<|body_start_1|>
from .identity import Identity
from .teamwork_application_identity_type import TeamworkApplicationIdentityType
from ... | TeamworkApplicationIdentity | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeamworkApplicationIdentity:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeamworkApplicationIdentity:
"""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 a... | stack_v2_sparse_classes_75kplus_train_074209 | 2,589 | 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: TeamworkApplicationIdentity",
"name": "create_from_discriminator_value",
"signature": "def create_from_discr... | 3 | null | Implement the Python class `TeamworkApplicationIdentity` described below.
Class description:
Implement the TeamworkApplicationIdentity class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeamworkApplicationIdentity: Creates a new instance of the appr... | Implement the Python class `TeamworkApplicationIdentity` described below.
Class description:
Implement the TeamworkApplicationIdentity class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeamworkApplicationIdentity: Creates a new instance of the appr... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class TeamworkApplicationIdentity:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeamworkApplicationIdentity:
"""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 a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TeamworkApplicationIdentity:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeamworkApplicationIdentity:
"""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 ... | the_stack_v2_python_sparse | msgraph/generated/models/teamwork_application_identity.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
183a03f7f47983f55d47a6675ab8bdf4f518e454 | [
"query_ass_field = TestCaseAssField.query.get(ass_field_id)\nif not query_ass_field:\n return api_result(code=400, message='字段断言id:{}数据不存在'.format(ass_field_id))\nreturn api_result(code=200, message='操作成功', data=query_ass_field.to_json())",
"data = request.get_json()\nassert_description = data.get('assert_desc... | <|body_start_0|>
query_ass_field = TestCaseAssField.query.get(ass_field_id)
if not query_ass_field:
return api_result(code=400, message='字段断言id:{}数据不存在'.format(ass_field_id))
return api_result(code=200, message='操作成功', data=query_ass_field.to_json())
<|end_body_0|>
<|body_start_1|>
... | 字段断言规则Api GET: 断言规则详情 POST: 断言规则新增 PUT: 断言规则编辑 DELETE: 断言规则删除 req_demo = { "assert_description": "A通用字段校验", "remark": "remark", "ass_json": [ { "db_id": 1, "query": "select id FROM exilic_test_case WHERE id=1;", "assert_list": [ { "assert_key": "id", "expect_val": 1, "expect_val_type": "1", "rule": "==" }, { "assert_ke... | FieldAssertionRuleApi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FieldAssertionRuleApi:
"""字段断言规则Api GET: 断言规则详情 POST: 断言规则新增 PUT: 断言规则编辑 DELETE: 断言规则删除 req_demo = { "assert_description": "A通用字段校验", "remark": "remark", "ass_json": [ { "db_id": 1, "query": "select id FROM exilic_test_case WHERE id=1;", "assert_list": [ { "assert_key": "id", "expect_val": 1, "ex... | stack_v2_sparse_classes_75kplus_train_074210 | 17,166 | no_license | [
{
"docstring": "字段断言明细",
"name": "get",
"signature": "def get(self, ass_field_id)"
},
{
"docstring": "字段断言新增",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "字段断言编辑",
"name": "put",
"signature": "def put(self)"
},
{
"docstring": "字段断言规则删除",
"... | 4 | stack_v2_sparse_classes_30k_train_051177 | Implement the Python class `FieldAssertionRuleApi` described below.
Class description:
字段断言规则Api GET: 断言规则详情 POST: 断言规则新增 PUT: 断言规则编辑 DELETE: 断言规则删除 req_demo = { "assert_description": "A通用字段校验", "remark": "remark", "ass_json": [ { "db_id": 1, "query": "select id FROM exilic_test_case WHERE id=1;", "assert_list": [ { "... | Implement the Python class `FieldAssertionRuleApi` described below.
Class description:
字段断言规则Api GET: 断言规则详情 POST: 断言规则新增 PUT: 断言规则编辑 DELETE: 断言规则删除 req_demo = { "assert_description": "A通用字段校验", "remark": "remark", "ass_json": [ { "db_id": 1, "query": "select id FROM exilic_test_case WHERE id=1;", "assert_list": [ { "... | df76812885d7d7f3a5269e3f7c652db6a9f3c3ad | <|skeleton|>
class FieldAssertionRuleApi:
"""字段断言规则Api GET: 断言规则详情 POST: 断言规则新增 PUT: 断言规则编辑 DELETE: 断言规则删除 req_demo = { "assert_description": "A通用字段校验", "remark": "remark", "ass_json": [ { "db_id": 1, "query": "select id FROM exilic_test_case WHERE id=1;", "assert_list": [ { "assert_key": "id", "expect_val": 1, "ex... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FieldAssertionRuleApi:
"""字段断言规则Api GET: 断言规则详情 POST: 断言规则新增 PUT: 断言规则编辑 DELETE: 断言规则删除 req_demo = { "assert_description": "A通用字段校验", "remark": "remark", "ass_json": [ { "db_id": 1, "query": "select id FROM exilic_test_case WHERE id=1;", "assert_list": [ { "assert_key": "id", "expect_val": 1, "expect_val_type... | the_stack_v2_python_sparse | app/api/case_ass_rule_api/case_ass_rule_api.py | chengzizhen/ExileTestPlatformServer | train | 0 |
43f9d5e7b889c6640bdff1cefa90ee85175817ee | [
"prediction = hypothesis.prediction\nmeasurement = hypothesis.measurement\nmeasurement_model = hypothesis.measurement.measurement_model\nmeasurement_model = self._check_measurement_model(measurement_model)\nif hypothesis.measurement_prediction is None:\n hypothesis.measurement_prediction = self.predict_measureme... | <|body_start_0|>
prediction = hypothesis.prediction
measurement = hypothesis.measurement
measurement_model = hypothesis.measurement.measurement_model
measurement_model = self._check_measurement_model(measurement_model)
if hypothesis.measurement_prediction is None:
hyp... | Hidden Markov model updater | HMMUpdater | [
"LicenseRef-scancode-proprietary-license",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"Python-2.0",
"LicenseRef-scancode-secret-labs-2011"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HMMUpdater:
"""Hidden Markov model updater"""
def update(self, hypothesis, **kwargs):
"""The update method. Given a hypothesised association between a predicted state or predicted measurement and an actual measurement, calculate the posterior state. .. math:: \\alpha_t^i = E^{ki}(F\\... | stack_v2_sparse_classes_75kplus_train_074211 | 5,093 | permissive | [
{
"docstring": "The update method. Given a hypothesised association between a predicted state or predicted measurement and an actual measurement, calculate the posterior state. .. math:: \\\\alpha_t^i = E^{ki}(F\\\\alpha_{t-1})^i Measurements are assumed to be discrete categories from a finite set of measuremen... | 3 | stack_v2_sparse_classes_30k_train_002665 | Implement the Python class `HMMUpdater` described below.
Class description:
Hidden Markov model updater
Method signatures and docstrings:
- def update(self, hypothesis, **kwargs): The update method. Given a hypothesised association between a predicted state or predicted measurement and an actual measurement, calculat... | Implement the Python class `HMMUpdater` described below.
Class description:
Hidden Markov model updater
Method signatures and docstrings:
- def update(self, hypothesis, **kwargs): The update method. Given a hypothesised association between a predicted state or predicted measurement and an actual measurement, calculat... | f24090cc919b3b590b84f965a3884ed1293d181d | <|skeleton|>
class HMMUpdater:
"""Hidden Markov model updater"""
def update(self, hypothesis, **kwargs):
"""The update method. Given a hypothesised association between a predicted state or predicted measurement and an actual measurement, calculate the posterior state. .. math:: \\alpha_t^i = E^{ki}(F\\... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HMMUpdater:
"""Hidden Markov model updater"""
def update(self, hypothesis, **kwargs):
"""The update method. Given a hypothesised association between a predicted state or predicted measurement and an actual measurement, calculate the posterior state. .. math:: \\alpha_t^i = E^{ki}(F\\alpha_{t-1})^... | the_stack_v2_python_sparse | stonesoup/updater/categorical.py | dstl/Stone-Soup | train | 315 |
4f4e7e24c88efd35134e5d3fdb0b06c23569571e | [
"self.lora_conn = lora_conn\nself.packet = HandShakePacket()\nself.trans_cnt = 0",
"end_time = time() + self.__MAX_TIME\nwhile time() < end_time:\n if not self.trans_cnt:\n self.lora_conn.send_raw(self.packet.buffer(0, bytes(str(self.__SYN), encoding=CHAR_ENCODING)))\n self.trans_cnt += 1\n el... | <|body_start_0|>
self.lora_conn = lora_conn
self.packet = HandShakePacket()
self.trans_cnt = 0
<|end_body_0|>
<|body_start_1|>
end_time = time() + self.__MAX_TIME
while time() < end_time:
if not self.trans_cnt:
self.lora_conn.send_raw(self.packet.buff... | Class for managing TCP 3-way handshake transmissions Date: 06/03/2020 | ThreeWayHandshake | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreeWayHandshake:
"""Class for managing TCP 3-way handshake transmissions Date: 06/03/2020"""
def __init__(self, lora_conn):
"""Class constructor"""
<|body_0|>
def request_conn(self):
"""Request establishing a LoRa connection for transmitting data using 3-way ha... | stack_v2_sparse_classes_75kplus_train_074212 | 8,192 | no_license | [
{
"docstring": "Class constructor",
"name": "__init__",
"signature": "def __init__(self, lora_conn)"
},
{
"docstring": "Request establishing a LoRa connection for transmitting data using 3-way handshake :return: True if connection established with the server using 3-way handshake, False otherwis... | 3 | null | Implement the Python class `ThreeWayHandshake` described below.
Class description:
Class for managing TCP 3-way handshake transmissions Date: 06/03/2020
Method signatures and docstrings:
- def __init__(self, lora_conn): Class constructor
- def request_conn(self): Request establishing a LoRa connection for transmittin... | Implement the Python class `ThreeWayHandshake` described below.
Class description:
Class for managing TCP 3-way handshake transmissions Date: 06/03/2020
Method signatures and docstrings:
- def __init__(self, lora_conn): Class constructor
- def request_conn(self): Request establishing a LoRa connection for transmittin... | 751c683c33ea61da54d85453f433871f5307408f | <|skeleton|>
class ThreeWayHandshake:
"""Class for managing TCP 3-way handshake transmissions Date: 06/03/2020"""
def __init__(self, lora_conn):
"""Class constructor"""
<|body_0|>
def request_conn(self):
"""Request establishing a LoRa connection for transmitting data using 3-way ha... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ThreeWayHandshake:
"""Class for managing TCP 3-way handshake transmissions Date: 06/03/2020"""
def __init__(self, lora_conn):
"""Class constructor"""
self.lora_conn = lora_conn
self.packet = HandShakePacket()
self.trans_cnt = 0
def request_conn(self):
"""Reque... | the_stack_v2_python_sparse | pi/lora/tcp_handshake.py | EmilStalvinge/LoRa_Communication_Network | train | 0 |
47f4cee3eaadf4035a91dece808110531a7504ee | [
"while self.tcex.service.loop_forever(sleep=30):\n self.tcex.log.debug(f'Server configuration service_input {self.args.service_input}')\n self.tcex.service.fire_event(self.trigger_callback, my_data='data')",
"my_data: str = kwargs.get('my_data')\nself.tcex.log.debug(f'my_data: {my_data}')\nself.tcex.log.deb... | <|body_start_0|>
while self.tcex.service.loop_forever(sleep=30):
self.tcex.log.debug(f'Server configuration service_input {self.args.service_input}')
self.tcex.service.fire_event(self.trigger_callback, my_data='data')
<|end_body_0|>
<|body_start_1|>
my_data: str = kwargs.get('my... | Service App Template. | App | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class App:
"""Service App Template."""
def run(self) -> None:
"""Run the trigger logic."""
<|body_0|>
def trigger_callback(self, playbook: Playbooks, trigger_id: int, config: dict, **kwargs) -> None:
"""Execute trigger callback for all current configs. Args: playbook: ... | stack_v2_sparse_classes_75kplus_train_074213 | 1,924 | permissive | [
{
"docstring": "Run the trigger logic.",
"name": "run",
"signature": "def run(self) -> None"
},
{
"docstring": "Execute trigger callback for all current configs. Args: playbook: An instance of Playbooks used to write output variables to be used in downstream Apps. trigger_id: The ID of the Playb... | 2 | null | Implement the Python class `App` described below.
Class description:
Service App Template.
Method signatures and docstrings:
- def run(self) -> None: Run the trigger logic.
- def trigger_callback(self, playbook: Playbooks, trigger_id: int, config: dict, **kwargs) -> None: Execute trigger callback for all current conf... | Implement the Python class `App` described below.
Class description:
Service App Template.
Method signatures and docstrings:
- def run(self) -> None: Run the trigger logic.
- def trigger_callback(self, playbook: Playbooks, trigger_id: int, config: dict, **kwargs) -> None: Execute trigger callback for all current conf... | 7cf04fec048fadc71ff851970045b8a587269ccf | <|skeleton|>
class App:
"""Service App Template."""
def run(self) -> None:
"""Run the trigger logic."""
<|body_0|>
def trigger_callback(self, playbook: Playbooks, trigger_id: int, config: dict, **kwargs) -> None:
"""Execute trigger callback for all current configs. Args: playbook: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class App:
"""Service App Template."""
def run(self) -> None:
"""Run the trigger logic."""
while self.tcex.service.loop_forever(sleep=30):
self.tcex.log.debug(f'Server configuration service_input {self.args.service_input}')
self.tcex.service.fire_event(self.trigger_callb... | the_stack_v2_python_sparse | app_init/service_trigger/app.py | TpyoKnig/tcex | train | 0 |
f18474b0953ba4ce26057c897179de0c8fb8a674 | [
"if not value:\n return []\nreturn [email.strip() for email in value.split(',')]",
"super().validate(value)\nfor email in value:\n validate_email(email)"
] | <|body_start_0|>
if not value:
return []
return [email.strip() for email in value.split(',')]
<|end_body_0|>
<|body_start_1|>
super().validate(value)
for email in value:
validate_email(email)
<|end_body_1|>
| MultiEmailField | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiEmailField:
def to_python(self, value):
"""Normalize data to a list of strings."""
<|body_0|>
def validate(self, value):
"""Check if value consists only of valid emails."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not value:
... | stack_v2_sparse_classes_75kplus_train_074214 | 19,443 | permissive | [
{
"docstring": "Normalize data to a list of strings.",
"name": "to_python",
"signature": "def to_python(self, value)"
},
{
"docstring": "Check if value consists only of valid emails.",
"name": "validate",
"signature": "def validate(self, value)"
}
] | 2 | null | Implement the Python class `MultiEmailField` described below.
Class description:
Implement the MultiEmailField class.
Method signatures and docstrings:
- def to_python(self, value): Normalize data to a list of strings.
- def validate(self, value): Check if value consists only of valid emails. | Implement the Python class `MultiEmailField` described below.
Class description:
Implement the MultiEmailField class.
Method signatures and docstrings:
- def to_python(self, value): Normalize data to a list of strings.
- def validate(self, value): Check if value consists only of valid emails.
<|skeleton|>
class Mult... | 6708944bbcecb6d3d1467b096b2d72e991583d51 | <|skeleton|>
class MultiEmailField:
def to_python(self, value):
"""Normalize data to a list of strings."""
<|body_0|>
def validate(self, value):
"""Check if value consists only of valid emails."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiEmailField:
def to_python(self, value):
"""Normalize data to a list of strings."""
if not value:
return []
return [email.strip() for email in value.split(',')]
def validate(self, value):
"""Check if value consists only of valid emails."""
super().v... | the_stack_v2_python_sparse | events/forms.py | GetTogetherComm/GetTogether | train | 462 | |
c608285517b43a6ecbc3b93514b56c4e140986da | [
"self._polyline = polyline\nself._distance_threshold = distance_threshold\nself._x_index, self._y_index = position_indices\nsuper(SemiquadraticPolylineCost, self).__init__(name)",
"signed_distance = self._polyline.signed_distance_to(Point(x[self._x_index, 0], x[self._y_index, 0]))\nif abs(signed_distance) > self.... | <|body_start_0|>
self._polyline = polyline
self._distance_threshold = distance_threshold
self._x_index, self._y_index = position_indices
super(SemiquadraticPolylineCost, self).__init__(name)
<|end_body_0|>
<|body_start_1|>
signed_distance = self._polyline.signed_distance_to(Poin... | SemiquadraticPolylineCost | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SemiquadraticPolylineCost:
def __init__(self, polyline, distance_threshold, position_indices, name=''):
"""Initialize with a polyline, a threshold in distance from the polyline. :param polyline: piecewise linear path which defines signed distances :type polyline: Polyline :param distance... | stack_v2_sparse_classes_75kplus_train_074215 | 3,651 | permissive | [
{
"docstring": "Initialize with a polyline, a threshold in distance from the polyline. :param polyline: piecewise linear path which defines signed distances :type polyline: Polyline :param distance_threshold: value above which to penalize :type distance_threshold: float :param position_indices: indices of input... | 3 | null | Implement the Python class `SemiquadraticPolylineCost` described below.
Class description:
Implement the SemiquadraticPolylineCost class.
Method signatures and docstrings:
- def __init__(self, polyline, distance_threshold, position_indices, name=''): Initialize with a polyline, a threshold in distance from the polyli... | Implement the Python class `SemiquadraticPolylineCost` described below.
Class description:
Implement the SemiquadraticPolylineCost class.
Method signatures and docstrings:
- def __init__(self, polyline, distance_threshold, position_indices, name=''): Initialize with a polyline, a threshold in distance from the polyli... | fbe9501a51e33498e0b916e2a870dada7c61df57 | <|skeleton|>
class SemiquadraticPolylineCost:
def __init__(self, polyline, distance_threshold, position_indices, name=''):
"""Initialize with a polyline, a threshold in distance from the polyline. :param polyline: piecewise linear path which defines signed distances :type polyline: Polyline :param distance... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SemiquadraticPolylineCost:
def __init__(self, polyline, distance_threshold, position_indices, name=''):
"""Initialize with a polyline, a threshold in distance from the polyline. :param polyline: piecewise linear path which defines signed distances :type polyline: Polyline :param distance_threshold: va... | the_stack_v2_python_sparse | python/semiquadratic_polyline_cost.py | HJReachability/ilqgames | train | 89 | |
6fa9a101b098c469b59272175fd10f4e92c07226 | [
"ref_path = '/home/yk/Project/keras/dataset/BraTs19DataSet/BraTs19Mixture_N4_HM_Norm/Train/BraTS19_2013_11_1/BraTS19_2013_11_1_flair.nii.gz'\nassert os.path.exists(ref_path), 'The input reference data does not exist or is incorrect.'\nif reference_path is None:\n self.reference_path = ref_path\nelse:\n self.r... | <|body_start_0|>
ref_path = '/home/yk/Project/keras/dataset/BraTs19DataSet/BraTs19Mixture_N4_HM_Norm/Train/BraTS19_2013_11_1/BraTS19_2013_11_1_flair.nii.gz'
assert os.path.exists(ref_path), 'The input reference data does not exist or is incorrect.'
if reference_path is None:
self.ref... | Save2Nii | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Save2Nii:
def __init__(self, reference_path=None, lib_type='nib'):
""":param reference_path: For the first time to define class Save2Nii,you should fill in the reference path. Reference data provides stored parameters. like this: F = Save2Nii(data_path) F(img, filename)"""
<|body... | stack_v2_sparse_classes_75kplus_train_074216 | 18,569 | permissive | [
{
"docstring": ":param reference_path: For the first time to define class Save2Nii,you should fill in the reference path. Reference data provides stored parameters. like this: F = Save2Nii(data_path) F(img, filename)",
"name": "__init__",
"signature": "def __init__(self, reference_path=None, lib_type='n... | 4 | null | Implement the Python class `Save2Nii` described below.
Class description:
Implement the Save2Nii class.
Method signatures and docstrings:
- def __init__(self, reference_path=None, lib_type='nib'): :param reference_path: For the first time to define class Save2Nii,you should fill in the reference path. Reference data ... | Implement the Python class `Save2Nii` described below.
Class description:
Implement the Save2Nii class.
Method signatures and docstrings:
- def __init__(self, reference_path=None, lib_type='nib'): :param reference_path: For the first time to define class Save2Nii,you should fill in the reference path. Reference data ... | 0cd5a72244e0eb572c06d309a66fa2027be60d52 | <|skeleton|>
class Save2Nii:
def __init__(self, reference_path=None, lib_type='nib'):
""":param reference_path: For the first time to define class Save2Nii,you should fill in the reference path. Reference data provides stored parameters. like this: F = Save2Nii(data_path) F(img, filename)"""
<|body... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Save2Nii:
def __init__(self, reference_path=None, lib_type='nib'):
""":param reference_path: For the first time to define class Save2Nii,you should fill in the reference path. Reference data provides stored parameters. like this: F = Save2Nii(data_path) F(img, filename)"""
ref_path = '/home/yk... | the_stack_v2_python_sparse | Test_demo/TestOneCase.py | YKSIAT/Segmentation | train | 3 | |
46188758fbda68dd02400a4c68ab39701895dd56 | [
"self.client = sclient.Client(wsdl_file)\nif is_ssl:\n trans = HttpAuthUsingCert('', '')\n self.client.set_options(transport=trans)\nif endpoint is not None:\n self.client.options.location = endpoint\nif is_ssl and username:\n passman = urllib2.HTTPPasswordMgrWithDefaultRealm()\n passman.add_password... | <|body_start_0|>
self.client = sclient.Client(wsdl_file)
if is_ssl:
trans = HttpAuthUsingCert('', '')
self.client.set_options(transport=trans)
if endpoint is not None:
self.client.options.location = endpoint
if is_ssl and username:
passman ... | This class repsent wraper for SOAP client | SoapInterface | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SoapInterface:
"""This class repsent wraper for SOAP client"""
def __init__(self, wsdl_file, endpoint=None, is_ssl=False, username=None, password=None):
"""Constructor method @wsdl_file - URL representing WSDL file (local or global URL) @endpoint - SOAP endpoint URL @is_ssl - if True... | stack_v2_sparse_classes_75kplus_train_074217 | 5,178 | no_license | [
{
"docstring": "Constructor method @wsdl_file - URL representing WSDL file (local or global URL) @endpoint - SOAP endpoint URL @is_ssl - if True then initiate ssl connection @username - username for HTTP authentication (if None then no HTTP authentication) @password - password for HTTP authentication",
"nam... | 3 | stack_v2_sparse_classes_30k_train_008870 | Implement the Python class `SoapInterface` described below.
Class description:
This class repsent wraper for SOAP client
Method signatures and docstrings:
- def __init__(self, wsdl_file, endpoint=None, is_ssl=False, username=None, password=None): Constructor method @wsdl_file - URL representing WSDL file (local or gl... | Implement the Python class `SoapInterface` described below.
Class description:
This class repsent wraper for SOAP client
Method signatures and docstrings:
- def __init__(self, wsdl_file, endpoint=None, is_ssl=False, username=None, password=None): Constructor method @wsdl_file - URL representing WSDL file (local or gl... | e6bc6eb747e39dcacf5f3fd0738d82f16ed0f76d | <|skeleton|>
class SoapInterface:
"""This class repsent wraper for SOAP client"""
def __init__(self, wsdl_file, endpoint=None, is_ssl=False, username=None, password=None):
"""Constructor method @wsdl_file - URL representing WSDL file (local or global URL) @endpoint - SOAP endpoint URL @is_ssl - if True... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SoapInterface:
"""This class repsent wraper for SOAP client"""
def __init__(self, wsdl_file, endpoint=None, is_ssl=False, username=None, password=None):
"""Constructor method @wsdl_file - URL representing WSDL file (local or global URL) @endpoint - SOAP endpoint URL @is_ssl - if True then initiat... | the_stack_v2_python_sparse | FablikFramework/FablikClient/bin/soapClient.py | fabregas/old_projects | train | 0 |
b41ec46cf9c2113467c51e9c4fb656d9a9f1a320 | [
"data = parsers.parse_key(file_key='icrf2_non_vcs').as_dict()\ndata.update(parsers.parse_key(file_key='icrf2_vcs_only').as_dict())\nreturn data",
"source_info = self.data[source]\nvector = Direction(ra=source_info['ra'], dec=source_info['dec'], time=self.time)\nreturn np.squeeze(vector)"
] | <|body_start_0|>
data = parsers.parse_key(file_key='icrf2_non_vcs').as_dict()
data.update(parsers.parse_key(file_key='icrf2_vcs_only').as_dict())
return data
<|end_body_0|>
<|body_start_1|>
source_info = self.data[source]
vector = Direction(ra=source_info['ra'], dec=source_info[... | A class to provide information from radio sources defined in ICRF2 | Icrf2 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Icrf2:
"""A class to provide information from radio sources defined in ICRF2"""
def _read_data(self):
"""Read data needed by this Celestial Reference Frame for calculating positions of sources Returns: Dict: Dictionary containing data about each source defined in this reference frame... | stack_v2_sparse_classes_75kplus_train_074218 | 1,419 | permissive | [
{
"docstring": "Read data needed by this Celestial Reference Frame for calculating positions of sources Returns: Dict: Dictionary containing data about each source defined in this reference frame.",
"name": "_read_data",
"signature": "def _read_data(self)"
},
{
"docstring": "Calculate position f... | 2 | stack_v2_sparse_classes_30k_train_047265 | Implement the Python class `Icrf2` described below.
Class description:
A class to provide information from radio sources defined in ICRF2
Method signatures and docstrings:
- def _read_data(self): Read data needed by this Celestial Reference Frame for calculating positions of sources Returns: Dict: Dictionary containi... | Implement the Python class `Icrf2` described below.
Class description:
A class to provide information from radio sources defined in ICRF2
Method signatures and docstrings:
- def _read_data(self): Read data needed by this Celestial Reference Frame for calculating positions of sources Returns: Dict: Dictionary containi... | 0c8c5c68adca08f97e22cab1bce10e382a7fbf77 | <|skeleton|>
class Icrf2:
"""A class to provide information from radio sources defined in ICRF2"""
def _read_data(self):
"""Read data needed by this Celestial Reference Frame for calculating positions of sources Returns: Dict: Dictionary containing data about each source defined in this reference frame... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Icrf2:
"""A class to provide information from radio sources defined in ICRF2"""
def _read_data(self):
"""Read data needed by this Celestial Reference Frame for calculating positions of sources Returns: Dict: Dictionary containing data about each source defined in this reference frame."""
... | the_stack_v2_python_sparse | where/apriori/crf/icrf2.py | kartverket/where | train | 21 |
674e672c4d76a1bf9bc85a8b0450549be7095fc2 | [
"t = Tree()\nt.add(100)\nt.add(50)\nt.add(25)\nt.add(75)\nt.add(150)\nt.add(125)\nt.add(175)\nt.add(110)\nreturn t.root",
"t = self.create_sample_tree()\nexpected = [100, 50, 25, 75, 150, 125, 110, 175]\nself.assertEqual(preorder_traversal(t), expected)",
"t = self.create_sample_tree()\nexpected = [25, 50, 75, ... | <|body_start_0|>
t = Tree()
t.add(100)
t.add(50)
t.add(25)
t.add(75)
t.add(150)
t.add(125)
t.add(175)
t.add(110)
return t.root
<|end_body_0|>
<|body_start_1|>
t = self.create_sample_tree()
expected = [100, 50, 25, 75, 150, ... | test_traversal_implementations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_traversal_implementations:
def create_sample_tree(self):
"""create a sample tree to use in the traversal implementations"""
<|body_0|>
def test_preorder_traversal_implementation(self):
"""test that the output is indeed what is expected"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_074219 | 1,654 | no_license | [
{
"docstring": "create a sample tree to use in the traversal implementations",
"name": "create_sample_tree",
"signature": "def create_sample_tree(self)"
},
{
"docstring": "test that the output is indeed what is expected",
"name": "test_preorder_traversal_implementation",
"signature": "de... | 5 | null | Implement the Python class `test_traversal_implementations` described below.
Class description:
Implement the test_traversal_implementations class.
Method signatures and docstrings:
- def create_sample_tree(self): create a sample tree to use in the traversal implementations
- def test_preorder_traversal_implementatio... | Implement the Python class `test_traversal_implementations` described below.
Class description:
Implement the test_traversal_implementations class.
Method signatures and docstrings:
- def create_sample_tree(self): create a sample tree to use in the traversal implementations
- def test_preorder_traversal_implementatio... | 7e884adb19b84a2e5960d1b6e81cd926f0b46705 | <|skeleton|>
class test_traversal_implementations:
def create_sample_tree(self):
"""create a sample tree to use in the traversal implementations"""
<|body_0|>
def test_preorder_traversal_implementation(self):
"""test that the output is indeed what is expected"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class test_traversal_implementations:
def create_sample_tree(self):
"""create a sample tree to use in the traversal implementations"""
t = Tree()
t.add(100)
t.add(50)
t.add(25)
t.add(75)
t.add(150)
t.add(125)
t.add(175)
t.add(110)
... | the_stack_v2_python_sparse | questions/trees_and_graphs/traversal_test.py | qdonnellan/random_questions | train | 0 | |
777cb4b018b56fee1ae26f0573d8e3f24221056b | [
"all_players = Models.Player.get_all_players()\noptions = {'1': [Views.TournamentView.new_tournament, Models.Tournament(), 0], '2': Views.MenuView.load_menu, '3': [Views.PlayerView.add_player_to_db, Models.Player(), 0], '4': [Views.PlayerView.load_player, all_players], '5': Views.MenuView.export_menu, '6': exit}\ni... | <|body_start_0|>
all_players = Models.Player.get_all_players()
options = {'1': [Views.TournamentView.new_tournament, Models.Tournament(), 0], '2': Views.MenuView.load_menu, '3': [Views.PlayerView.add_player_to_db, Models.Player(), 0], '4': [Views.PlayerView.load_player, all_players], '5': Views.MenuView... | MenuController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MenuController:
def main_menu(response):
"""Check the response of the corresponding view Redirect to the chosen view"""
<|body_0|>
def export_menu(response):
"""Check the response of the corresponding view Redirect to the chosen view"""
<|body_1|>
def lo... | stack_v2_sparse_classes_75kplus_train_074220 | 2,180 | permissive | [
{
"docstring": "Check the response of the corresponding view Redirect to the chosen view",
"name": "main_menu",
"signature": "def main_menu(response)"
},
{
"docstring": "Check the response of the corresponding view Redirect to the chosen view",
"name": "export_menu",
"signature": "def ex... | 3 | null | Implement the Python class `MenuController` described below.
Class description:
Implement the MenuController class.
Method signatures and docstrings:
- def main_menu(response): Check the response of the corresponding view Redirect to the chosen view
- def export_menu(response): Check the response of the corresponding... | Implement the Python class `MenuController` described below.
Class description:
Implement the MenuController class.
Method signatures and docstrings:
- def main_menu(response): Check the response of the corresponding view Redirect to the chosen view
- def export_menu(response): Check the response of the corresponding... | 91f3745f56b59b4b02301400df784cbe529d72e1 | <|skeleton|>
class MenuController:
def main_menu(response):
"""Check the response of the corresponding view Redirect to the chosen view"""
<|body_0|>
def export_menu(response):
"""Check the response of the corresponding view Redirect to the chosen view"""
<|body_1|>
def lo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MenuController:
def main_menu(response):
"""Check the response of the corresponding view Redirect to the chosen view"""
all_players = Models.Player.get_all_players()
options = {'1': [Views.TournamentView.new_tournament, Models.Tournament(), 0], '2': Views.MenuView.load_menu, '3': [View... | the_stack_v2_python_sparse | Controllers/menus_controller.py | arbitre125/ChessTournament-1 | train | 0 | |
f218a16813a9351c677fdbc7a6ebe9d0242e2284 | [
"QuestionTextFormRecord._init_map(self)\nQuestionFilesFormRecord._init_map(self)\nsuper(QuestionTextAndFilesMixin, self)._init_map()",
"QuestionTextFormRecord._init_metadata(self)\nQuestionFilesFormRecord._init_metadata(self)\nsuper(QuestionTextAndFilesMixin, self)._init_metadata()"
] | <|body_start_0|>
QuestionTextFormRecord._init_map(self)
QuestionFilesFormRecord._init_map(self)
super(QuestionTextAndFilesMixin, self)._init_map()
<|end_body_0|>
<|body_start_1|>
QuestionTextFormRecord._init_metadata(self)
QuestionFilesFormRecord._init_metadata(self)
sup... | Mixin class to make the two classes compatible with super() for _init_map and _init_metadata | QuestionTextAndFilesMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionTextAndFilesMixin:
"""Mixin class to make the two classes compatible with super() for _init_map and _init_metadata"""
def _init_map(self):
"""stub"""
<|body_0|>
def _init_metadata(self):
"""stub"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_074221 | 22,562 | permissive | [
{
"docstring": "stub",
"name": "_init_map",
"signature": "def _init_map(self)"
},
{
"docstring": "stub",
"name": "_init_metadata",
"signature": "def _init_metadata(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_024551 | Implement the Python class `QuestionTextAndFilesMixin` described below.
Class description:
Mixin class to make the two classes compatible with super() for _init_map and _init_metadata
Method signatures and docstrings:
- def _init_map(self): stub
- def _init_metadata(self): stub | Implement the Python class `QuestionTextAndFilesMixin` described below.
Class description:
Mixin class to make the two classes compatible with super() for _init_map and _init_metadata
Method signatures and docstrings:
- def _init_map(self): stub
- def _init_metadata(self): stub
<|skeleton|>
class QuestionTextAndFile... | 445f968a175d61c8d92c0f617a3c17dc1dc7c584 | <|skeleton|>
class QuestionTextAndFilesMixin:
"""Mixin class to make the two classes compatible with super() for _init_map and _init_metadata"""
def _init_map(self):
"""stub"""
<|body_0|>
def _init_metadata(self):
"""stub"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QuestionTextAndFilesMixin:
"""Mixin class to make the two classes compatible with super() for _init_map and _init_metadata"""
def _init_map(self):
"""stub"""
QuestionTextFormRecord._init_map(self)
QuestionFilesFormRecord._init_map(self)
super(QuestionTextAndFilesMixin, sel... | the_stack_v2_python_sparse | dlkit/records/assessment/basic/simple_records.py | mitsei/dlkit | train | 2 |
58591fd41cb8461036ec678b6053a42152499998 | [
"ports = {}\nif not self._device.link.IsLocal():\n raise DisplayError('Cannot support Freon+DRM remotely.')\nd = None\nfor p in sorted(self._device.Glob('/dev/dri/*')):\n d = drm_utils.DRMFromPath(p)\n if d.resources:\n break\nelse:\n raise DisplayError(\"Can't find suitable DRM devices\")\nfor c... | <|body_start_0|>
ports = {}
if not self._device.link.IsLocal():
raise DisplayError('Cannot support Freon+DRM remotely.')
d = None
for p in sorted(self._device.Glob('/dev/dri/*')):
d = drm_utils.DRMFromPath(p)
if d.resources:
break
... | ChromeOSDisplay | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChromeOSDisplay:
def GetPortInfo(self):
"""Gets the port info of all the display ports. Returns: A dict of port IDs to PortInfo instances of all the display ports."""
<|body_0|>
def CaptureFramebuffer(self, port, box=None, downscale=False):
"""Captures a RGB image of... | stack_v2_sparse_classes_75kplus_train_074222 | 3,830 | permissive | [
{
"docstring": "Gets the port info of all the display ports. Returns: A dict of port IDs to PortInfo instances of all the display ports.",
"name": "GetPortInfo",
"signature": "def GetPortInfo(self)"
},
{
"docstring": "Captures a RGB image of the framebuffer on the given display port. Screenshots... | 2 | stack_v2_sparse_classes_30k_train_054600 | Implement the Python class `ChromeOSDisplay` described below.
Class description:
Implement the ChromeOSDisplay class.
Method signatures and docstrings:
- def GetPortInfo(self): Gets the port info of all the display ports. Returns: A dict of port IDs to PortInfo instances of all the display ports.
- def CaptureFramebu... | Implement the Python class `ChromeOSDisplay` described below.
Class description:
Implement the ChromeOSDisplay class.
Method signatures and docstrings:
- def GetPortInfo(self): Gets the port info of all the display ports. Returns: A dict of port IDs to PortInfo instances of all the display ports.
- def CaptureFramebu... | a1b0fccd68987d8cd9c89710adc3c04b868347ec | <|skeleton|>
class ChromeOSDisplay:
def GetPortInfo(self):
"""Gets the port info of all the display ports. Returns: A dict of port IDs to PortInfo instances of all the display ports."""
<|body_0|>
def CaptureFramebuffer(self, port, box=None, downscale=False):
"""Captures a RGB image of... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChromeOSDisplay:
def GetPortInfo(self):
"""Gets the port info of all the display ports. Returns: A dict of port IDs to PortInfo instances of all the display ports."""
ports = {}
if not self._device.link.IsLocal():
raise DisplayError('Cannot support Freon+DRM remotely.')
... | the_stack_v2_python_sparse | py/device/chromeos/display.py | bridder/factory | train | 0 | |
acfc2ef70e3e94e12d6be37ad16666f33e65e9bf | [
"self.output_root_dir = output_root_dir\nself.jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(TEMPLATE_DIR))\nself.jinja_env.filters['repr'] = repr\nself.jinja_env.filters['pargs_kwargs'] = sort_parg_kwarg\nself.jinja_env.filters.update(dict(repr=repr, sort_parg_kwarg=sort_parg_kwarg, to_snake=to_snak... | <|body_start_0|>
self.output_root_dir = output_root_dir
self.jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(TEMPLATE_DIR))
self.jinja_env.filters['repr'] = repr
self.jinja_env.filters['pargs_kwargs'] = sort_parg_kwarg
self.jinja_env.filters.update(dict(repr=repr, s... | Foundation Interface Template Renderer for jinja2 | TemplateRenderer | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TemplateRenderer:
"""Foundation Interface Template Renderer for jinja2"""
def __init__(self, output_root_dir):
"""Setup the jinja2 environment :param str output_root_dir: Root directory in which to write the Foundation interface."""
<|body_0|>
def render_template(self, t... | stack_v2_sparse_classes_75kplus_train_074223 | 29,296 | permissive | [
{
"docstring": "Setup the jinja2 environment :param str output_root_dir: Root directory in which to write the Foundation interface.",
"name": "__init__",
"signature": "def __init__(self, output_root_dir)"
},
{
"docstring": "Render one or more jinja2 templates. The output filename is relative to ... | 2 | stack_v2_sparse_classes_30k_train_031531 | Implement the Python class `TemplateRenderer` described below.
Class description:
Foundation Interface Template Renderer for jinja2
Method signatures and docstrings:
- def __init__(self, output_root_dir): Setup the jinja2 environment :param str output_root_dir: Root directory in which to write the Foundation interfac... | Implement the Python class `TemplateRenderer` described below.
Class description:
Foundation Interface Template Renderer for jinja2
Method signatures and docstrings:
- def __init__(self, output_root_dir): Setup the jinja2 environment :param str output_root_dir: Root directory in which to write the Foundation interfac... | 76ef009903415f37f69dcc5778be8f5fb14c08fe | <|skeleton|>
class TemplateRenderer:
"""Foundation Interface Template Renderer for jinja2"""
def __init__(self, output_root_dir):
"""Setup the jinja2 environment :param str output_root_dir: Root directory in which to write the Foundation interface."""
<|body_0|>
def render_template(self, t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TemplateRenderer:
"""Foundation Interface Template Renderer for jinja2"""
def __init__(self, output_root_dir):
"""Setup the jinja2 environment :param str output_root_dir: Root directory in which to write the Foundation interface."""
self.output_root_dir = output_root_dir
self.jinj... | the_stack_v2_python_sparse | scripts/foundation/render_sdk.py | GQMai/mbed-cloud-sdk-python | train | 0 |
11a72443dfdce4db6dd71ccd35e37422d9a7c62d | [
"if value is self.field.missing_value:\n return []\nwidget = self.widget\nif widget.terms is None:\n widget.update_terms()\nvalues = []\nfor entry in value:\n try:\n values.append(widget.terms.getTerm(entry).token)\n except LookupError:\n pass\nreturn values",
"widget = self.widget\nif w... | <|body_start_0|>
if value is self.field.missing_value:
return []
widget = self.widget
if widget.terms is None:
widget.update_terms()
values = []
for entry in value:
try:
values.append(widget.terms.getTerm(entry).token)
... | A special converter between collections and sequence widgets. | CollectionSequenceDataConverter | [
"ZPL-2.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CollectionSequenceDataConverter:
"""A special converter between collections and sequence widgets."""
def to_widget_value(self, value):
"""Convert from Python bool to HTML representation."""
<|body_0|>
def to_field_value(self, value):
"""See interfaces.IDataConver... | stack_v2_sparse_classes_75kplus_train_074224 | 16,755 | permissive | [
{
"docstring": "Convert from Python bool to HTML representation.",
"name": "to_widget_value",
"signature": "def to_widget_value(self, value)"
},
{
"docstring": "See interfaces.IDataConverter",
"name": "to_field_value",
"signature": "def to_field_value(self, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_046244 | Implement the Python class `CollectionSequenceDataConverter` described below.
Class description:
A special converter between collections and sequence widgets.
Method signatures and docstrings:
- def to_widget_value(self, value): Convert from Python bool to HTML representation.
- def to_field_value(self, value): See i... | Implement the Python class `CollectionSequenceDataConverter` described below.
Class description:
A special converter between collections and sequence widgets.
Method signatures and docstrings:
- def to_widget_value(self, value): Convert from Python bool to HTML representation.
- def to_field_value(self, value): See i... | e83e2ce314355f98eaf66e90ad6feccbda7934f9 | <|skeleton|>
class CollectionSequenceDataConverter:
"""A special converter between collections and sequence widgets."""
def to_widget_value(self, value):
"""Convert from Python bool to HTML representation."""
<|body_0|>
def to_field_value(self, value):
"""See interfaces.IDataConver... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CollectionSequenceDataConverter:
"""A special converter between collections and sequence widgets."""
def to_widget_value(self, value):
"""Convert from Python bool to HTML representation."""
if value is self.field.missing_value:
return []
widget = self.widget
if... | the_stack_v2_python_sparse | src/pyams_form/converter.py | Py-AMS/pyams-form | train | 0 |
24cfa4537b34d1abc086292a71d163eeb73c6bc5 | [
"record.data = {'time': datetime.now(timezone.utc)}\nrecord.time = record.data['time'].strftime(self.datetime_format)\nrecord.level = record.levelname\nrecord.stack_trace = None\nif record.exc_info:\n record.stack_trace = ''.join(traceback.format_exception(*record.exc_info)) if record.exc_info else ''\nreturn re... | <|body_start_0|>
record.data = {'time': datetime.now(timezone.utc)}
record.time = record.data['time'].strftime(self.datetime_format)
record.level = record.levelname
record.stack_trace = None
if record.exc_info:
record.stack_trace = ''.join(traceback.format_exception(*... | Log event record in JSON format. Subclass this for finer control. | JSONBaseLogFormatter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JSONBaseLogFormatter:
"""Log event record in JSON format. Subclass this for finer control."""
def prep_record(self, record):
"""Prepare event record for logging. :param record: Record of event to be logged :type record: LogRecord :return: Transformed LogRecord object :trype: LogRecor... | stack_v2_sparse_classes_75kplus_train_074225 | 6,498 | permissive | [
{
"docstring": "Prepare event record for logging. :param record: Record of event to be logged :type record: LogRecord :return: Transformed LogRecord object :trype: LogRecord",
"name": "prep_record",
"signature": "def prep_record(self, record)"
},
{
"docstring": "Prepare request for logging. :par... | 4 | stack_v2_sparse_classes_30k_train_000205 | Implement the Python class `JSONBaseLogFormatter` described below.
Class description:
Log event record in JSON format. Subclass this for finer control.
Method signatures and docstrings:
- def prep_record(self, record): Prepare event record for logging. :param record: Record of event to be logged :type record: LogReco... | Implement the Python class `JSONBaseLogFormatter` described below.
Class description:
Log event record in JSON format. Subclass this for finer control.
Method signatures and docstrings:
- def prep_record(self, record): Prepare event record for logging. :param record: Record of event to be logged :type record: LogReco... | fdf6dc02ab73d588919f38d6017788f7822cfd04 | <|skeleton|>
class JSONBaseLogFormatter:
"""Log event record in JSON format. Subclass this for finer control."""
def prep_record(self, record):
"""Prepare event record for logging. :param record: Record of event to be logged :type record: LogRecord :return: Transformed LogRecord object :trype: LogRecor... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JSONBaseLogFormatter:
"""Log event record in JSON format. Subclass this for finer control."""
def prep_record(self, record):
"""Prepare event record for logging. :param record: Record of event to be logged :type record: LogRecord :return: Transformed LogRecord object :trype: LogRecord"""
... | the_stack_v2_python_sparse | application/src/main/python/lib/logger/json_base_log_formatter.py | okebinda/base.api.python | train | 0 |
ab92a54d31ae2efd9626ea684e4c00d5098413e2 | [
"if instrument is None:\n instrument = self._instrument\nself._order_data = OrderData(instrument=instrument, lots=lots, price=price, take_profit=take_profit, stop_loss=stop_loss, trailing_stop=trailing_stop, cur_bar=self._cur_bar, execute_mode=self._execute_mode, order_type=self.order_type)\nself.__set_order_dat... | <|body_start_0|>
if instrument is None:
instrument = self._instrument
self._order_data = OrderData(instrument=instrument, lots=lots, price=price, take_profit=take_profit, stop_loss=stop_loss, trailing_stop=trailing_stop, cur_bar=self._cur_bar, execute_mode=self._execute_mode, order_type=self... | Order | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Order:
def execute(self, instrument, lots, price, take_profit, stop_loss, trailing_stop):
"""执行"""
<|body_0|>
def __set_order_data(self):
"""初始化各项基本信息,并判断指令种类execute_type"""
<|body_1|>
def __get_trailing_price(self, new, old):
"""根据多空决定追踪止损取值"""
... | stack_v2_sparse_classes_75kplus_train_074226 | 11,926 | no_license | [
{
"docstring": "执行",
"name": "execute",
"signature": "def execute(self, instrument, lots, price, take_profit, stop_loss, trailing_stop)"
},
{
"docstring": "初始化各项基本信息,并判断指令种类execute_type",
"name": "__set_order_data",
"signature": "def __set_order_data(self)"
},
{
"docstring": "根据多... | 4 | stack_v2_sparse_classes_30k_val_001497 | Implement the Python class `Order` described below.
Class description:
Implement the Order class.
Method signatures and docstrings:
- def execute(self, instrument, lots, price, take_profit, stop_loss, trailing_stop): 执行
- def __set_order_data(self): 初始化各项基本信息,并判断指令种类execute_type
- def __get_trailing_price(self, new, ... | Implement the Python class `Order` described below.
Class description:
Implement the Order class.
Method signatures and docstrings:
- def execute(self, instrument, lots, price, take_profit, stop_loss, trailing_stop): 执行
- def __set_order_data(self): 初始化各项基本信息,并判断指令种类execute_type
- def __get_trailing_price(self, new, ... | ef2d3f3089c450a0d1de982d1ddabc4c782c1452 | <|skeleton|>
class Order:
def execute(self, instrument, lots, price, take_profit, stop_loss, trailing_stop):
"""执行"""
<|body_0|>
def __set_order_data(self):
"""初始化各项基本信息,并判断指令种类execute_type"""
<|body_1|>
def __get_trailing_price(self, new, old):
"""根据多空决定追踪止损取值"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Order:
def execute(self, instrument, lots, price, take_profit, stop_loss, trailing_stop):
"""执行"""
if instrument is None:
instrument = self._instrument
self._order_data = OrderData(instrument=instrument, lots=lots, price=price, take_profit=take_profit, stop_loss=stop_loss, ... | the_stack_v2_python_sparse | quant/order.py | yangjiarui/quant1 | train | 1 | |
6f322bd029936e8cb282e83087fb61feca09a95d | [
"self.similar_stock = kwargs['similar_stock']\nself.n_top = g_pick_similar_n_top\nif 'n_top' in kwargs:\n self.n_top = kwargs['n_top']\nself.threshold_similar_min = -np.inf\nif 'threshold_similar_min' in kwargs:\n self.threshold_similar_min = kwargs['threshold_similar_min']\nself.threshold_similar_max = np.in... | <|body_start_0|>
self.similar_stock = kwargs['similar_stock']
self.n_top = g_pick_similar_n_top
if 'n_top' in kwargs:
self.n_top = kwargs['n_top']
self.threshold_similar_min = -np.inf
if 'threshold_similar_min' in kwargs:
self.threshold_similar_min = kwarg... | 相似度选股因子示例类 | AbuPickSimilarNTop | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbuPickSimilarNTop:
"""相似度选股因子示例类"""
def _init_self(self, **kwargs):
"""通过kwargs设置相似度选股边际条件,相似度计算方法,返回目标数量等,配置因子参数"""
<|body_0|>
def fit_pick(self, kl_pd, target_symbol):
"""开始根据自定义相似度边际条件进行选股"""
<|body_1|>
def fit_first_choice(self, pick_worker, cho... | stack_v2_sparse_classes_75kplus_train_074227 | 4,344 | permissive | [
{
"docstring": "通过kwargs设置相似度选股边际条件,相似度计算方法,返回目标数量等,配置因子参数",
"name": "_init_self",
"signature": "def _init_self(self, **kwargs)"
},
{
"docstring": "开始根据自定义相似度边际条件进行选股",
"name": "fit_pick",
"signature": "def fit_pick(self, kl_pd, target_symbol)"
},
{
"docstring": "因子相似度批量选股接口 :par... | 3 | stack_v2_sparse_classes_30k_train_038177 | Implement the Python class `AbuPickSimilarNTop` described below.
Class description:
相似度选股因子示例类
Method signatures and docstrings:
- def _init_self(self, **kwargs): 通过kwargs设置相似度选股边际条件,相似度计算方法,返回目标数量等,配置因子参数
- def fit_pick(self, kl_pd, target_symbol): 开始根据自定义相似度边际条件进行选股
- def fit_first_choice(self, pick_worker, choice_... | Implement the Python class `AbuPickSimilarNTop` described below.
Class description:
相似度选股因子示例类
Method signatures and docstrings:
- def _init_self(self, **kwargs): 通过kwargs设置相似度选股边际条件,相似度计算方法,返回目标数量等,配置因子参数
- def fit_pick(self, kl_pd, target_symbol): 开始根据自定义相似度边际条件进行选股
- def fit_first_choice(self, pick_worker, choice_... | 2e5ab17f2d20deb3c68c927f6208ea89db7c639d | <|skeleton|>
class AbuPickSimilarNTop:
"""相似度选股因子示例类"""
def _init_self(self, **kwargs):
"""通过kwargs设置相似度选股边际条件,相似度计算方法,返回目标数量等,配置因子参数"""
<|body_0|>
def fit_pick(self, kl_pd, target_symbol):
"""开始根据自定义相似度边际条件进行选股"""
<|body_1|>
def fit_first_choice(self, pick_worker, cho... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AbuPickSimilarNTop:
"""相似度选股因子示例类"""
def _init_self(self, **kwargs):
"""通过kwargs设置相似度选股边际条件,相似度计算方法,返回目标数量等,配置因子参数"""
self.similar_stock = kwargs['similar_stock']
self.n_top = g_pick_similar_n_top
if 'n_top' in kwargs:
self.n_top = kwargs['n_top']
self.... | the_stack_v2_python_sparse | abupy/PickStockBu/ABuPickSimilarNTop.py | luqin/firefly | train | 1 |
3747a413ed68998375225d8cd7d7f6b2ee0db64b | [
"user = request.user\ndata = request.data\nresult = password_update_action.UpdatePassword.call(user=user, data=data)\nif result.failed:\n return Response(errors=dict(errors=result.error.value), status=status.HTTP_400_BAD_REQUEST)\nreturn Response(data=result.value, status=status.HTTP_201_CREATED)",
"data = req... | <|body_start_0|>
user = request.user
data = request.data
result = password_update_action.UpdatePassword.call(user=user, data=data)
if result.failed:
return Response(errors=dict(errors=result.error.value), status=status.HTTP_400_BAD_REQUEST)
return Response(data=result... | PasswordsViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PasswordsViewSet:
def change(self, request):
"""This method updates the user's password and returns an appropriate response."""
<|body_0|>
def reset(self, request):
"""This reset password view collects the data from the user and calls the ResetPassword Action to perf... | stack_v2_sparse_classes_75kplus_train_074228 | 1,856 | permissive | [
{
"docstring": "This method updates the user's password and returns an appropriate response.",
"name": "change",
"signature": "def change(self, request)"
},
{
"docstring": "This reset password view collects the data from the user and calls the ResetPassword Action to perform the necessary valida... | 2 | stack_v2_sparse_classes_30k_train_018818 | Implement the Python class `PasswordsViewSet` described below.
Class description:
Implement the PasswordsViewSet class.
Method signatures and docstrings:
- def change(self, request): This method updates the user's password and returns an appropriate response.
- def reset(self, request): This reset password view colle... | Implement the Python class `PasswordsViewSet` described below.
Class description:
Implement the PasswordsViewSet class.
Method signatures and docstrings:
- def change(self, request): This method updates the user's password and returns an appropriate response.
- def reset(self, request): This reset password view colle... | ba93610cdb5ad04fd93effbb0249139b351bc226 | <|skeleton|>
class PasswordsViewSet:
def change(self, request):
"""This method updates the user's password and returns an appropriate response."""
<|body_0|>
def reset(self, request):
"""This reset password view collects the data from the user and calls the ResetPassword Action to perf... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PasswordsViewSet:
def change(self, request):
"""This method updates the user's password and returns an appropriate response."""
user = request.user
data = request.data
result = password_update_action.UpdatePassword.call(user=user, data=data)
if result.failed:
... | the_stack_v2_python_sparse | project/api/views/passwords.py | AdejokeOgunyinka/cinch-API | train | 0 | |
dd3a6d3378d1f21e072c9b0411a2059d9e429d9e | [
"self.device_tree = device_tree\nself.logical_volume_name = logical_volume_name\nself.logical_volume_uuid = logical_volume_uuid\nself.volume_group_name = volume_group_name\nself.volume_group_uuid = volume_group_uuid",
"if dictionary is None:\n return None\ndevice_tree = cohesity_management_sdk.models.device_tr... | <|body_start_0|>
self.device_tree = device_tree
self.logical_volume_name = logical_volume_name
self.logical_volume_uuid = logical_volume_uuid
self.volume_group_name = volume_group_name
self.volume_group_uuid = volume_group_uuid
<|end_body_0|>
<|body_start_1|>
if dictiona... | Implementation of the 'VolumeInfo_LogicalVolumeInfo' model. This is extra attribute which uniquely identifies a logical volume in LVM or LDM. Attributes: device_tree (DeviceTree): The tree defining how to combine partitions to create this logical volume. logical_volume_name (string): Logical volume name. logical_volume... | VolumeInfo_LogicalVolumeInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VolumeInfo_LogicalVolumeInfo:
"""Implementation of the 'VolumeInfo_LogicalVolumeInfo' model. This is extra attribute which uniquely identifies a logical volume in LVM or LDM. Attributes: device_tree (DeviceTree): The tree defining how to combine partitions to create this logical volume. logical_v... | stack_v2_sparse_classes_75kplus_train_074229 | 2,832 | permissive | [
{
"docstring": "Constructor for the VolumeInfo_LogicalVolumeInfo class",
"name": "__init__",
"signature": "def __init__(self, device_tree=None, logical_volume_name=None, logical_volume_uuid=None, volume_group_name=None, volume_group_uuid=None)"
},
{
"docstring": "Creates an instance of this mode... | 2 | stack_v2_sparse_classes_30k_train_031711 | Implement the Python class `VolumeInfo_LogicalVolumeInfo` described below.
Class description:
Implementation of the 'VolumeInfo_LogicalVolumeInfo' model. This is extra attribute which uniquely identifies a logical volume in LVM or LDM. Attributes: device_tree (DeviceTree): The tree defining how to combine partitions t... | Implement the Python class `VolumeInfo_LogicalVolumeInfo` described below.
Class description:
Implementation of the 'VolumeInfo_LogicalVolumeInfo' model. This is extra attribute which uniquely identifies a logical volume in LVM or LDM. Attributes: device_tree (DeviceTree): The tree defining how to combine partitions t... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class VolumeInfo_LogicalVolumeInfo:
"""Implementation of the 'VolumeInfo_LogicalVolumeInfo' model. This is extra attribute which uniquely identifies a logical volume in LVM or LDM. Attributes: device_tree (DeviceTree): The tree defining how to combine partitions to create this logical volume. logical_v... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VolumeInfo_LogicalVolumeInfo:
"""Implementation of the 'VolumeInfo_LogicalVolumeInfo' model. This is extra attribute which uniquely identifies a logical volume in LVM or LDM. Attributes: device_tree (DeviceTree): The tree defining how to combine partitions to create this logical volume. logical_volume_name (s... | the_stack_v2_python_sparse | cohesity_management_sdk/models/volume_info_logical_volume_info.py | cohesity/management-sdk-python | train | 24 |
c822405f83fee6e4135b3d0a9755b56b518c55b2 | [
"self.n = n\nlocations = [-1] * n\nself.count = 0\nself.dfs(locations, 0)\nreturn self.count",
"if row == self.n:\n self.count += 1\n return\nfor i in range(self.n):\n if self.check(locations, row, i):\n locations[row] = i\n self.dfs(locations, row + 1)\n locations[row] = -1",
"for... | <|body_start_0|>
self.n = n
locations = [-1] * n
self.count = 0
self.dfs(locations, 0)
return self.count
<|end_body_0|>
<|body_start_1|>
if row == self.n:
self.count += 1
return
for i in range(self.n):
if self.check(locations, ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def totalNQueens(self, n):
""":param n: int :return: int"""
<|body_0|>
def dfs(self, locations, row):
"""递归处理 :param locations: :param row: :return:"""
<|body_1|>
def check(self, locations, row, col):
"""检查(row, col)位置是否可以放置Queen :param... | stack_v2_sparse_classes_75kplus_train_074230 | 1,708 | no_license | [
{
"docstring": ":param n: int :return: int",
"name": "totalNQueens",
"signature": "def totalNQueens(self, n)"
},
{
"docstring": "递归处理 :param locations: :param row: :return:",
"name": "dfs",
"signature": "def dfs(self, locations, row)"
},
{
"docstring": "检查(row, col)位置是否可以放置Queen ... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def totalNQueens(self, n): :param n: int :return: int
- def dfs(self, locations, row): 递归处理 :param locations: :param row: :return:
- def check(self, locations, row, col): 检查(row,... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def totalNQueens(self, n): :param n: int :return: int
- def dfs(self, locations, row): 递归处理 :param locations: :param row: :return:
- def check(self, locations, row, col): 检查(row,... | c1c5ee72b8fe608b278ca20a58bc240fdc62b599 | <|skeleton|>
class Solution:
def totalNQueens(self, n):
""":param n: int :return: int"""
<|body_0|>
def dfs(self, locations, row):
"""递归处理 :param locations: :param row: :return:"""
<|body_1|>
def check(self, locations, row, col):
"""检查(row, col)位置是否可以放置Queen :param... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def totalNQueens(self, n):
""":param n: int :return: int"""
self.n = n
locations = [-1] * n
self.count = 0
self.dfs(locations, 0)
return self.count
def dfs(self, locations, row):
"""递归处理 :param locations: :param row: :return:"""
if... | the_stack_v2_python_sparse | 52_n_queens_2.py | eazow/leetcode | train | 5 | |
45c282e5451e9b9c2e4ffd94629784853dfa1c92 | [
"log.debug('GET request from user %s for project stage %s' % (request.user, stageplan_id))\nproj = Project.objects.get(project_number=project_number)\nstage = ProjectStage.objects.get(id=stageplan_id)\nif not check_project_read_acl(proj, request.user):\n log.debug('Refusing GET request for project %s from user %... | <|body_start_0|>
log.debug('GET request from user %s for project stage %s' % (request.user, stageplan_id))
proj = Project.objects.get(project_number=project_number)
stage = ProjectStage.objects.get(id=stageplan_id)
if not check_project_read_acl(proj, request.user):
log.debug(... | URI: /api/stageplan/%project_number%/%stageplan_id%/ VERBS: GET, PUT, DELETE Handles a single instance of StagePlan | StageplanResourceHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StageplanResourceHandler:
"""URI: /api/stageplan/%project_number%/%stageplan_id%/ VERBS: GET, PUT, DELETE Handles a single instance of StagePlan"""
def read(self, request, project_number, stageplan_id):
"""View a Project Stage"""
<|body_0|>
def update(self, request, proj... | stack_v2_sparse_classes_75kplus_train_074231 | 19,350 | no_license | [
{
"docstring": "View a Project Stage",
"name": "read",
"signature": "def read(self, request, project_number, stageplan_id)"
},
{
"docstring": "Update the Project Stage",
"name": "update",
"signature": "def update(self, request, project_number, stageplan_id)"
},
{
"docstring": "Di... | 3 | stack_v2_sparse_classes_30k_train_002154 | Implement the Python class `StageplanResourceHandler` described below.
Class description:
URI: /api/stageplan/%project_number%/%stageplan_id%/ VERBS: GET, PUT, DELETE Handles a single instance of StagePlan
Method signatures and docstrings:
- def read(self, request, project_number, stageplan_id): View a Project Stage
... | Implement the Python class `StageplanResourceHandler` described below.
Class description:
URI: /api/stageplan/%project_number%/%stageplan_id%/ VERBS: GET, PUT, DELETE Handles a single instance of StagePlan
Method signatures and docstrings:
- def read(self, request, project_number, stageplan_id): View a Project Stage
... | 106a96307612318fb66246486e7226069e5508ac | <|skeleton|>
class StageplanResourceHandler:
"""URI: /api/stageplan/%project_number%/%stageplan_id%/ VERBS: GET, PUT, DELETE Handles a single instance of StagePlan"""
def read(self, request, project_number, stageplan_id):
"""View a Project Stage"""
<|body_0|>
def update(self, request, proj... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StageplanResourceHandler:
"""URI: /api/stageplan/%project_number%/%stageplan_id%/ VERBS: GET, PUT, DELETE Handles a single instance of StagePlan"""
def read(self, request, project_number, stageplan_id):
"""View a Project Stage"""
log.debug('GET request from user %s for project stage %s' %... | the_stack_v2_python_sparse | branches/rest-api-branch/django-project-management/wbs/api_views.py | NhaTrang/django-project-management | train | 0 |
66b7334d63b204537c42b33e60175cbcd252fff1 | [
"if model._meta.app_label == 'auth':\n return 'users'\nreturn None",
"if model._meta.app_label == 'auth':\n return 'users'\nreturn None",
"return True\nif obj1._meta.app_label == 'auth' or obj2._meta.app_label == 'auth':\n return True\nreturn None",
"if db == 'users':\n return model._meta.app_labe... | <|body_start_0|>
if model._meta.app_label == 'auth':
return 'users'
return None
<|end_body_0|>
<|body_start_1|>
if model._meta.app_label == 'auth':
return 'users'
return None
<|end_body_1|>
<|body_start_2|>
return True
if obj1._meta.app_label == ... | A router to control all database operations on models in the contrib.auth application | AuthRouter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthRouter:
"""A router to control all database operations on models in the contrib.auth application"""
def db_for_read(self, model, **hints):
"""Point all operations on auth models to 'credentials'"""
<|body_0|>
def db_for_write(self, model, **hints):
"""Point a... | stack_v2_sparse_classes_75kplus_train_074232 | 2,832 | no_license | [
{
"docstring": "Point all operations on auth models to 'credentials'",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "Point all operations on auth models to 'credentials'",
"name": "db_for_write",
"signature": "def db_for_write(self, model,... | 4 | null | Implement the Python class `AuthRouter` described below.
Class description:
A router to control all database operations on models in the contrib.auth application
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Point all operations on auth models to 'credentials'
- def db_for_write(self, mod... | Implement the Python class `AuthRouter` described below.
Class description:
A router to control all database operations on models in the contrib.auth application
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Point all operations on auth models to 'credentials'
- def db_for_write(self, mod... | 259d86010e1670e747440937d057ad73484ca655 | <|skeleton|>
class AuthRouter:
"""A router to control all database operations on models in the contrib.auth application"""
def db_for_read(self, model, **hints):
"""Point all operations on auth models to 'credentials'"""
<|body_0|>
def db_for_write(self, model, **hints):
"""Point a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AuthRouter:
"""A router to control all database operations on models in the contrib.auth application"""
def db_for_read(self, model, **hints):
"""Point all operations on auth models to 'credentials'"""
if model._meta.app_label == 'auth':
return 'users'
return None
... | the_stack_v2_python_sparse | routers.py | Lispython/jobboard | train | 0 |
28539162ad213c238aa4d68bfe1f299cbb3069e9 | [
"super().__init__(index, members, type, preventions)\nself.partitioner = partitioner\nself.contact_matrix = contact_matrix\nself.id_to_partition = dict.fromkeys(members)\nself.partition = partitioner.partitionGroup(members, populace)\nfor set in self.partition:\n for person in self.partition[set]:\n self.... | <|body_start_0|>
super().__init__(index, members, type, preventions)
self.partitioner = partitioner
self.contact_matrix = contact_matrix
self.id_to_partition = dict.fromkeys(members)
self.partition = partitioner.partitionGroup(members, populace)
for set in self.partition:... | being partitioned, it also holds a contact matrix and a partitioner | PartitionedEnvironment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PartitionedEnvironment:
"""being partitioned, it also holds a contact matrix and a partitioner"""
def __init__(self, index, members, type, populace, contact_matrix, partitioner, preventions=None):
""":param index: int an identifier :param members: list a list of people who attend the... | stack_v2_sparse_classes_75kplus_train_074233 | 45,926 | no_license | [
{
"docstring": ":param index: int an identifier :param members: list a list of people who attend the environment :param type: string either 'household', 'school', or 'workplace' :param preventions: dict keys should be 'household', 'school', or 'workplace'. Each should map to another dict, with keys for 'masking... | 2 | null | Implement the Python class `PartitionedEnvironment` described below.
Class description:
being partitioned, it also holds a contact matrix and a partitioner
Method signatures and docstrings:
- def __init__(self, index, members, type, populace, contact_matrix, partitioner, preventions=None): :param index: int an identi... | Implement the Python class `PartitionedEnvironment` described below.
Class description:
being partitioned, it also holds a contact matrix and a partitioner
Method signatures and docstrings:
- def __init__(self, index, members, type, populace, contact_matrix, partitioner, preventions=None): :param index: int an identi... | 666dea33ca22347e9c0656b15cd80cc5cb42eae7 | <|skeleton|>
class PartitionedEnvironment:
"""being partitioned, it also holds a contact matrix and a partitioner"""
def __init__(self, index, members, type, populace, contact_matrix, partitioner, preventions=None):
""":param index: int an identifier :param members: list a list of people who attend the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PartitionedEnvironment:
"""being partitioned, it also holds a contact matrix and a partitioner"""
def __init__(self, index, members, type, populace, contact_matrix, partitioner, preventions=None):
""":param index: int an identifier :param members: list a list of people who attend the environment ... | the_stack_v2_python_sparse | PopulaceGraphModel/ge_simResults_good/2020-10-19_21-50-18/src/ModelToolkit_bak.py | FiveCrows/SIRsims | train | 0 |
0d7435c9c3f78fea8212d02288beb662458c31ff | [
"categories = get_list_or_404(Category)\nif request.GET.get('pagination'):\n pagination = request.GET.get('pagination')\n if pagination == 'true':\n paginator = AdministratorPagination()\n results = paginator.paginate_queryset(categories, request)\n serializer = CategorySerializer(results... | <|body_start_0|>
categories = get_list_or_404(Category)
if request.GET.get('pagination'):
pagination = request.GET.get('pagination')
if pagination == 'true':
paginator = AdministratorPagination()
results = paginator.paginate_queryset(categories, re... | CategoryList | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CategoryList:
def get(self, request, format=None):
"""List all categories --- parameters: - name: pagination required: false type: string paramType: query"""
<|body_0|>
def post(self, request, format=None):
"""Create new category --- serializer: administrator.seriali... | stack_v2_sparse_classes_75kplus_train_074234 | 30,608 | permissive | [
{
"docstring": "List all categories --- parameters: - name: pagination required: false type: string paramType: query",
"name": "get",
"signature": "def get(self, request, format=None)"
},
{
"docstring": "Create new category --- serializer: administrator.serializers.CategorySerializer",
"name... | 2 | stack_v2_sparse_classes_30k_train_014530 | Implement the Python class `CategoryList` described below.
Class description:
Implement the CategoryList class.
Method signatures and docstrings:
- def get(self, request, format=None): List all categories --- parameters: - name: pagination required: false type: string paramType: query
- def post(self, request, format... | Implement the Python class `CategoryList` described below.
Class description:
Implement the CategoryList class.
Method signatures and docstrings:
- def get(self, request, format=None): List all categories --- parameters: - name: pagination required: false type: string paramType: query
- def post(self, request, format... | 73728463badb3bfd4413aa0f7aeb44a9606fdfea | <|skeleton|>
class CategoryList:
def get(self, request, format=None):
"""List all categories --- parameters: - name: pagination required: false type: string paramType: query"""
<|body_0|>
def post(self, request, format=None):
"""Create new category --- serializer: administrator.seriali... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CategoryList:
def get(self, request, format=None):
"""List all categories --- parameters: - name: pagination required: false type: string paramType: query"""
categories = get_list_or_404(Category)
if request.GET.get('pagination'):
pagination = request.GET.get('pagination')
... | the_stack_v2_python_sparse | administrator/views.py | belatrix/BackendAllStars | train | 5 | |
a4d98f5d57b730590af14185b984e342a0cef813 | [
"x = self.lrelu(self.conv1(x_in))\nx = self.lrelu(self.conv2(x))\nx = self.lrelu(self.conv3(x))\nx = self.conv4(x)\nreturn x",
"super(MidNet4, self).__init__()\nself.lrelu = nn.LeakyReLU()\nself.conv1 = nn.Conv2d(in_channels, 64, 3, 1, 4, 4)\nself.conv2 = nn.Conv2d(64, 64, 3, 1, 4, 4)\nself.conv3 = nn.Conv2d(64, ... | <|body_start_0|>
x = self.lrelu(self.conv1(x_in))
x = self.lrelu(self.conv2(x))
x = self.lrelu(self.conv3(x))
x = self.conv4(x)
return x
<|end_body_0|>
<|body_start_1|>
super(MidNet4, self).__init__()
self.lrelu = nn.LeakyReLU()
self.conv1 = nn.Conv2d(in_... | MidNet4 | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MidNet4:
def forward(self, x_in):
"""Network with dilation rate 4 :param x_in: input convolutional features :returns: processed convolutional features :rtype: Tensor"""
<|body_0|>
def __init__(self, in_channels=16):
"""FIXME! briefly describe function :param in_chann... | stack_v2_sparse_classes_75kplus_train_074235 | 8,922 | permissive | [
{
"docstring": "Network with dilation rate 4 :param x_in: input convolutional features :returns: processed convolutional features :rtype: Tensor",
"name": "forward",
"signature": "def forward(self, x_in)"
},
{
"docstring": "FIXME! briefly describe function :param in_channels: Input channels :ret... | 2 | stack_v2_sparse_classes_30k_train_008232 | Implement the Python class `MidNet4` described below.
Class description:
Implement the MidNet4 class.
Method signatures and docstrings:
- def forward(self, x_in): Network with dilation rate 4 :param x_in: input convolutional features :returns: processed convolutional features :rtype: Tensor
- def __init__(self, in_ch... | Implement the Python class `MidNet4` described below.
Class description:
Implement the MidNet4 class.
Method signatures and docstrings:
- def forward(self, x_in): Network with dilation rate 4 :param x_in: input convolutional features :returns: processed convolutional features :rtype: Tensor
- def __init__(self, in_ch... | 82c49c36b76987a46dec8479793f7cf0150839c6 | <|skeleton|>
class MidNet4:
def forward(self, x_in):
"""Network with dilation rate 4 :param x_in: input convolutional features :returns: processed convolutional features :rtype: Tensor"""
<|body_0|>
def __init__(self, in_channels=16):
"""FIXME! briefly describe function :param in_chann... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MidNet4:
def forward(self, x_in):
"""Network with dilation rate 4 :param x_in: input convolutional features :returns: processed convolutional features :rtype: Tensor"""
x = self.lrelu(self.conv1(x_in))
x = self.lrelu(self.conv2(x))
x = self.lrelu(self.conv3(x))
x = self... | the_stack_v2_python_sparse | CURL/rgb_ted.py | huawei-noah/noah-research | train | 816 | |
80cbb12e4003c66e1e08043c367f0737ea486da2 | [
"lower_file_ext = file_extension.lower()\nif lower_file_ext == '.vtk':\n return vtk.vtkPolyDataReader()\nif lower_file_ext == '.ply':\n return vtk.vtkPLYReader()\nif lower_file_ext == '.obj':\n return OBJReader()\nreturn None",
"if not file_name or not os.path.isfile(file_name):\n return None\ndata_re... | <|body_start_0|>
lower_file_ext = file_extension.lower()
if lower_file_ext == '.vtk':
return vtk.vtkPolyDataReader()
if lower_file_ext == '.ply':
return vtk.vtkPLYReader()
if lower_file_ext == '.obj':
return OBJReader()
return None
<|end_body_0... | VtkIO | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VtkIO:
def __get_reader(self, file_extension):
"""Returns a reader that can read the file type having the provided extension. Returns None if no such reader."""
<|body_0|>
def load(self, file_name):
"""Loads the data from the file 'file_name' and returns it. Returns ... | stack_v2_sparse_classes_75kplus_train_074236 | 1,198 | permissive | [
{
"docstring": "Returns a reader that can read the file type having the provided extension. Returns None if no such reader.",
"name": "__get_reader",
"signature": "def __get_reader(self, file_extension)"
},
{
"docstring": "Loads the data from the file 'file_name' and returns it. Returns None if ... | 2 | stack_v2_sparse_classes_30k_test_002108 | Implement the Python class `VtkIO` described below.
Class description:
Implement the VtkIO class.
Method signatures and docstrings:
- def __get_reader(self, file_extension): Returns a reader that can read the file type having the provided extension. Returns None if no such reader.
- def load(self, file_name): Loads t... | Implement the Python class `VtkIO` described below.
Class description:
Implement the VtkIO class.
Method signatures and docstrings:
- def __get_reader(self, file_extension): Returns a reader that can read the file type having the provided extension. Returns None if no such reader.
- def load(self, file_name): Loads t... | 6cae388a51e0509d280f55b9ebc9be3c4c45f794 | <|skeleton|>
class VtkIO:
def __get_reader(self, file_extension):
"""Returns a reader that can read the file type having the provided extension. Returns None if no such reader."""
<|body_0|>
def load(self, file_name):
"""Loads the data from the file 'file_name' and returns it. Returns ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VtkIO:
def __get_reader(self, file_extension):
"""Returns a reader that can read the file type having the provided extension. Returns None if no such reader."""
lower_file_ext = file_extension.lower()
if lower_file_ext == '.vtk':
return vtk.vtkPolyDataReader()
if lo... | the_stack_v2_python_sparse | IO/vtkio.py | zibneuro/brainvispy | train | 2 | |
bd60bf203b3cd424fe9b0f7bb0357fef3d8822d1 | [
"detail = test_mapping.TestDetail(uc.TEST_MAPPING_TEST)\nself.assertEqual(uc.TEST_MAPPING_TEST['name'], detail.name)\nself.assertTrue(detail.host)\nself.assertEqual([], detail.options)",
"detail = test_mapping.TestDetail(uc.TEST_MAPPING_TEST_WITH_OPTION)\nself.assertEqual(uc.TEST_MAPPING_TEST_WITH_OPTION['name'],... | <|body_start_0|>
detail = test_mapping.TestDetail(uc.TEST_MAPPING_TEST)
self.assertEqual(uc.TEST_MAPPING_TEST['name'], detail.name)
self.assertTrue(detail.host)
self.assertEqual([], detail.options)
<|end_body_0|>
<|body_start_1|>
detail = test_mapping.TestDetail(uc.TEST_MAPPING_... | Unit tests for test_mapping.py | TestMappingUnittests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMappingUnittests:
"""Unit tests for test_mapping.py"""
def test_parsing(self):
"""Test creating TestDetail object"""
<|body_0|>
def test_parsing_with_option(self):
"""Test creating TestDetail object with option configured"""
<|body_1|>
def test_p... | stack_v2_sparse_classes_75kplus_train_074237 | 3,630 | no_license | [
{
"docstring": "Test creating TestDetail object",
"name": "test_parsing",
"signature": "def test_parsing(self)"
},
{
"docstring": "Test creating TestDetail object with option configured",
"name": "test_parsing_with_option",
"signature": "def test_parsing_with_option(self)"
},
{
"... | 5 | stack_v2_sparse_classes_30k_val_000263 | Implement the Python class `TestMappingUnittests` described below.
Class description:
Unit tests for test_mapping.py
Method signatures and docstrings:
- def test_parsing(self): Test creating TestDetail object
- def test_parsing_with_option(self): Test creating TestDetail object with option configured
- def test_parsi... | Implement the Python class `TestMappingUnittests` described below.
Class description:
Unit tests for test_mapping.py
Method signatures and docstrings:
- def test_parsing(self): Test creating TestDetail object
- def test_parsing_with_option(self): Test creating TestDetail object with option configured
- def test_parsi... | 78a61ca023cbf1a0cecfef8b97df2b274ac3a988 | <|skeleton|>
class TestMappingUnittests:
"""Unit tests for test_mapping.py"""
def test_parsing(self):
"""Test creating TestDetail object"""
<|body_0|>
def test_parsing_with_option(self):
"""Test creating TestDetail object with option configured"""
<|body_1|>
def test_p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestMappingUnittests:
"""Unit tests for test_mapping.py"""
def test_parsing(self):
"""Test creating TestDetail object"""
detail = test_mapping.TestDetail(uc.TEST_MAPPING_TEST)
self.assertEqual(uc.TEST_MAPPING_TEST['name'], detail.name)
self.assertTrue(detail.host)
... | the_stack_v2_python_sparse | tools/asuite/atest-py2/test_mapping_unittest.py | ZYHGOD-1/Aosp11 | train | 0 |
e6164e470ea8b3e7fb60a21db9dd465ee5738e07 | [
"with self.assertRaises(ValidationError):\n miner = Miner(name='Some Miner', version='1.0.0', slug='create')\n miner.full_clean()\n miner.save()",
"miner = Miner(name='Some Miner', version='1.0.0', slug='some-miner-slug')\nminer.full_clean()\nminer.save()"
] | <|body_start_0|>
with self.assertRaises(ValidationError):
miner = Miner(name='Some Miner', version='1.0.0', slug='create')
miner.full_clean()
miner.save()
<|end_body_0|>
<|body_start_1|>
miner = Miner(name='Some Miner', version='1.0.0', slug='some-miner-slug')
... | Тестирование валидатора slug | SlugValidatorTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SlugValidatorTest:
"""Тестирование валидатора slug"""
def test_validate_invalid_slug(self):
"""Тестирование invalid slug"""
<|body_0|>
def test_validate_valid_slug(self):
"""Тестирование valid slug"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_074238 | 13,105 | permissive | [
{
"docstring": "Тестирование invalid slug",
"name": "test_validate_invalid_slug",
"signature": "def test_validate_invalid_slug(self)"
},
{
"docstring": "Тестирование valid slug",
"name": "test_validate_valid_slug",
"signature": "def test_validate_valid_slug(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_031252 | Implement the Python class `SlugValidatorTest` described below.
Class description:
Тестирование валидатора slug
Method signatures and docstrings:
- def test_validate_invalid_slug(self): Тестирование invalid slug
- def test_validate_valid_slug(self): Тестирование valid slug | Implement the Python class `SlugValidatorTest` described below.
Class description:
Тестирование валидатора slug
Method signatures and docstrings:
- def test_validate_invalid_slug(self): Тестирование invalid slug
- def test_validate_valid_slug(self): Тестирование valid slug
<|skeleton|>
class SlugValidatorTest:
"... | d173f1bee44d0752eefb53b1a0da847a3882a352 | <|skeleton|>
class SlugValidatorTest:
"""Тестирование валидатора slug"""
def test_validate_invalid_slug(self):
"""Тестирование invalid slug"""
<|body_0|>
def test_validate_valid_slug(self):
"""Тестирование valid slug"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SlugValidatorTest:
"""Тестирование валидатора slug"""
def test_validate_invalid_slug(self):
"""Тестирование invalid slug"""
with self.assertRaises(ValidationError):
miner = Miner(name='Some Miner', version='1.0.0', slug='create')
miner.full_clean()
mine... | the_stack_v2_python_sparse | miningstatistic/core/tests.py | crowmurk/miners | train | 0 |
2dc192f442495bcb6f32d9f428ebcdeb503f565c | [
"super(YetiYaraCollector, self).__init__(state, name=name, critical=critical)\nself.rule_name_filter = ''\nself.api_key = ''\nself.api_root = ''",
"self.logger.info(f'Name filter: {rule_name_filter}')\nself.rule_name_filter = rule_name_filter or ''\nself.api_key = api_key\nself.api_root = api_root",
"self.logge... | <|body_start_0|>
super(YetiYaraCollector, self).__init__(state, name=name, critical=critical)
self.rule_name_filter = ''
self.api_key = ''
self.api_root = ''
<|end_body_0|>
<|body_start_1|>
self.logger.info(f'Name filter: {rule_name_filter}')
self.rule_name_filter = rule... | Collector of Yara rules from Yeti TBB instances. Yeti TBB is Apache 2.0 licensed. Stores them in container.YaraRule containers. Attributes: rule_name_filter: A string by which to filter Yara rule names api_key: The Yeti API key to use. api_root: The Yeti HTTP API root, e.g. http://localhost:8080/api/ | YetiYaraCollector | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class YetiYaraCollector:
"""Collector of Yara rules from Yeti TBB instances. Yeti TBB is Apache 2.0 licensed. Stores them in container.YaraRule containers. Attributes: rule_name_filter: A string by which to filter Yara rule names api_key: The Yeti API key to use. api_root: The Yeti HTTP API root, e.g. ... | stack_v2_sparse_classes_75kplus_train_074239 | 2,688 | permissive | [
{
"docstring": "Initializes a YaraCollector module.",
"name": "__init__",
"signature": "def __init__(self, state: DFTimewolfState, name: Optional[str]=None, critical: bool=False) -> None"
},
{
"docstring": "Sets up the YaraCollector module. Args: rule_name_filter: A string by which to filter Yar... | 3 | stack_v2_sparse_classes_30k_train_006258 | Implement the Python class `YetiYaraCollector` described below.
Class description:
Collector of Yara rules from Yeti TBB instances. Yeti TBB is Apache 2.0 licensed. Stores them in container.YaraRule containers. Attributes: rule_name_filter: A string by which to filter Yara rule names api_key: The Yeti API key to use. ... | Implement the Python class `YetiYaraCollector` described below.
Class description:
Collector of Yara rules from Yeti TBB instances. Yeti TBB is Apache 2.0 licensed. Stores them in container.YaraRule containers. Attributes: rule_name_filter: A string by which to filter Yara rule names api_key: The Yeti API key to use. ... | bcea85b1ce7a0feb2aa28b5be4fc6ae124e8ca3c | <|skeleton|>
class YetiYaraCollector:
"""Collector of Yara rules from Yeti TBB instances. Yeti TBB is Apache 2.0 licensed. Stores them in container.YaraRule containers. Attributes: rule_name_filter: A string by which to filter Yara rule names api_key: The Yeti API key to use. api_root: The Yeti HTTP API root, e.g. ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class YetiYaraCollector:
"""Collector of Yara rules from Yeti TBB instances. Yeti TBB is Apache 2.0 licensed. Stores them in container.YaraRule containers. Attributes: rule_name_filter: A string by which to filter Yara rule names api_key: The Yeti API key to use. api_root: The Yeti HTTP API root, e.g. http://localh... | the_stack_v2_python_sparse | dftimewolf/lib/collectors/yara.py | log2timeline/dftimewolf | train | 248 |
8f330957446a85a0c05289337b71e98d81e52cdd | [
"self.words = words\nself.dictionary = defaultdict(list)\nfor index, word in enumerate(self.words):\n self.dictionary[word].append(index)",
"shortest_distance = sys.maxint\nfor index1, index2 in product(self.dictionary[word1], self.dictionary[word2]):\n if abs(index1 - index2) < shortest_distance:\n ... | <|body_start_0|>
self.words = words
self.dictionary = defaultdict(list)
for index, word in enumerate(self.words):
self.dictionary[word].append(index)
<|end_body_0|>
<|body_start_1|>
shortest_distance = sys.maxint
for index1, index2 in product(self.dictionary[word1], ... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
"""Adds a word into the data structure. :type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus_train_074240 | 1,065 | no_license | [
{
"docstring": "initialize your data structure here. :type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": "Adds a word into the data structure. :type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortes... | 2 | stack_v2_sparse_classes_30k_train_015970 | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): initialize your data structure here. :type words: List[str]
- def shortest(self, word1, word2): Adds a word into the data structure. :type word... | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): initialize your data structure here. :type words: List[str]
- def shortest(self, word1, word2): Adds a word into the data structure. :type word... | 09355094c85496cc42f8cb3241da43e0ece1e45a | <|skeleton|>
class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
"""Adds a word into the data structure. :type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
self.words = words
self.dictionary = defaultdict(list)
for index, word in enumerate(self.words):
self.dictionary[word].append(index)
def shortest(self, wo... | the_stack_v2_python_sparse | Rakesh/hash-table/shortest distance problem II.py | rakeshsukla53/interview-preparation | train | 9 | |
c658d481c662de00f32755621a63a882576e8b29 | [
"BasicInterface.__init__(self, uri, user, password)\ncorpus_path = os.environ.get('FoulWord_Corpus')\nif corpus_path is None:\n corpus_path = g_config.get_value('GraphDB', 'FoulWord_Corpus')\nself.bad_vocab_obj = BadVocab(corpus_path=corpus_path)",
"node_type = node_type.lower()\nnode_name = node_name.lower()\... | <|body_start_0|>
BasicInterface.__init__(self, uri, user, password)
corpus_path = os.environ.get('FoulWord_Corpus')
if corpus_path is None:
corpus_path = g_config.get_value('GraphDB', 'FoulWord_Corpus')
self.bad_vocab_obj = BadVocab(corpus_path=corpus_path)
<|end_body_0|>
<|... | A class focused on the create aspect of the Neo4J Implementation | CreateInterface | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateInterface:
"""A class focused on the create aspect of the Neo4J Implementation"""
def __init__(self, uri, user, password):
"""Constructor :param uri: DB URI :param user: DB user :param password: DB password"""
<|body_0|>
def merge_node(self, node_type, node_name):
... | stack_v2_sparse_classes_75kplus_train_074241 | 6,830 | no_license | [
{
"docstring": "Constructor :param uri: DB URI :param user: DB user :param password: DB password",
"name": "__init__",
"signature": "def __init__(self, uri, user, password)"
},
{
"docstring": "This function oversees creation of nodes. It ensures that only nodes of the following types are created... | 3 | stack_v2_sparse_classes_30k_train_039472 | Implement the Python class `CreateInterface` described below.
Class description:
A class focused on the create aspect of the Neo4J Implementation
Method signatures and docstrings:
- def __init__(self, uri, user, password): Constructor :param uri: DB URI :param user: DB user :param password: DB password
- def merge_no... | Implement the Python class `CreateInterface` described below.
Class description:
A class focused on the create aspect of the Neo4J Implementation
Method signatures and docstrings:
- def __init__(self, uri, user, password): Constructor :param uri: DB URI :param user: DB user :param password: DB password
- def merge_no... | 2177d43c75939a0c4906aa3761772365d4bf79e2 | <|skeleton|>
class CreateInterface:
"""A class focused on the create aspect of the Neo4J Implementation"""
def __init__(self, uri, user, password):
"""Constructor :param uri: DB URI :param user: DB user :param password: DB password"""
<|body_0|>
def merge_node(self, node_type, node_name):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CreateInterface:
"""A class focused on the create aspect of the Neo4J Implementation"""
def __init__(self, uri, user, password):
"""Constructor :param uri: DB URI :param user: DB user :param password: DB password"""
BasicInterface.__init__(self, uri, user, password)
corpus_path = ... | the_stack_v2_python_sparse | streaming/src/graph/create_interface.py | eldrad294/ICS5114_Practical_Assignment | train | 0 |
19028bcb4a6566373c2fda3703642e92755ba28c | [
"self.n_states, self.n_actions = (n_states, n_actions)\nif not exp_thres:\n exp_thres = exp_size // 10\nself.exp_size, self.exp_thres = (exp_size, exp_thres)\nself.batch_size = batch_size\nexp_dim = n_states * 2 + n_actions + 2\nself.expreplay_pool = np.zeros((exp_size, exp_dim))\nself.exp_index = 0",
"s, a, r... | <|body_start_0|>
self.n_states, self.n_actions = (n_states, n_actions)
if not exp_thres:
exp_thres = exp_size // 10
self.exp_size, self.exp_thres = (exp_size, exp_thres)
self.batch_size = batch_size
exp_dim = n_states * 2 + n_actions + 2
self.expreplay_pool = ... | 使用类似Q-Learning算法的DRL通用的经验回放池 1. 经验回放池的一条记录 (state, action, reward, done, next_state) 或简写为 (s, a, r, d, s_) 其中done的意义在于,当状态为done的时候,Q估计=r,而不是Q估计=(r + gamma * Q'max) 显然,一条记录的维度是 dim(s) + dim(a) + dim(r) + dim(d) + dim(s_) = 2 * n_states + n_actions + 2 2. 经验回放池的参数 - n_states: state的维度 - n_actions: action的维度 - exp_size: 经... | ExpReplay | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExpReplay:
"""使用类似Q-Learning算法的DRL通用的经验回放池 1. 经验回放池的一条记录 (state, action, reward, done, next_state) 或简写为 (s, a, r, d, s_) 其中done的意义在于,当状态为done的时候,Q估计=r,而不是Q估计=(r + gamma * Q'max) 显然,一条记录的维度是 dim(s) + dim(a) + dim(r) + dim(d) + dim(s_) = 2 * n_states + n_actions + 2 2. 经验回放池的参数 - n_states: state的维度... | stack_v2_sparse_classes_75kplus_train_074242 | 6,572 | permissive | [
{
"docstring": "初始化经验回放池",
"name": "__init__",
"signature": "def __init__(self, n_states, n_actions, exp_size=1000, exp_thres=None, batch_size=32)"
},
{
"docstring": "为经验回放池增加一步,我们约定“一步”包括s, a, r, d, s_五个部分 将这一步的信息整合为一条记录,放置到exp_index指定的位置。之后,exp_index以exp_size为模+1 即后来的记录会覆盖掉最早的记录 @param *step: ... | 5 | stack_v2_sparse_classes_30k_train_031147 | Implement the Python class `ExpReplay` described below.
Class description:
使用类似Q-Learning算法的DRL通用的经验回放池 1. 经验回放池的一条记录 (state, action, reward, done, next_state) 或简写为 (s, a, r, d, s_) 其中done的意义在于,当状态为done的时候,Q估计=r,而不是Q估计=(r + gamma * Q'max) 显然,一条记录的维度是 dim(s) + dim(a) + dim(r) + dim(d) + dim(s_) = 2 * n_states + n_actio... | Implement the Python class `ExpReplay` described below.
Class description:
使用类似Q-Learning算法的DRL通用的经验回放池 1. 经验回放池的一条记录 (state, action, reward, done, next_state) 或简写为 (s, a, r, d, s_) 其中done的意义在于,当状态为done的时候,Q估计=r,而不是Q估计=(r + gamma * Q'max) 显然,一条记录的维度是 dim(s) + dim(a) + dim(r) + dim(d) + dim(s_) = 2 * n_states + n_actio... | 7d88bc5392904f8f56adff4fcba157a352103f1f | <|skeleton|>
class ExpReplay:
"""使用类似Q-Learning算法的DRL通用的经验回放池 1. 经验回放池的一条记录 (state, action, reward, done, next_state) 或简写为 (s, a, r, d, s_) 其中done的意义在于,当状态为done的时候,Q估计=r,而不是Q估计=(r + gamma * Q'max) 显然,一条记录的维度是 dim(s) + dim(a) + dim(r) + dim(d) + dim(s_) = 2 * n_states + n_actions + 2 2. 经验回放池的参数 - n_states: state的维度... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExpReplay:
"""使用类似Q-Learning算法的DRL通用的经验回放池 1. 经验回放池的一条记录 (state, action, reward, done, next_state) 或简写为 (s, a, r, d, s_) 其中done的意义在于,当状态为done的时候,Q估计=r,而不是Q估计=(r + gamma * Q'max) 显然,一条记录的维度是 dim(s) + dim(a) + dim(r) + dim(d) + dim(s_) = 2 * n_states + n_actions + 2 2. 经验回放池的参数 - n_states: state的维度 - n_actions:... | the_stack_v2_python_sparse | RL4Net-lib/wjwgym-home/wjwgym/agents/Utils.py | ZealYa/RL4Net-TE | train | 0 |
94e93911f21cf62946fdea18e9fb429ecfdafc8a | [
"store_nodes = []\nif root == None:\n return None\nqueue = collections.deque([root])\nwhile queue:\n node = queue.popleft()\n if node:\n queue.append(node.left)\n queue.append(node.right)\n store_nodes.append(str(node.val))\n else:\n store_nodes.append('null')\ni = len(store_... | <|body_start_0|>
store_nodes = []
if root == None:
return None
queue = collections.deque([root])
while queue:
node = queue.popleft()
if node:
queue.append(node.left)
queue.append(node.right)
store_nodes.a... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_074243 | 2,018 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | a3630b101ed1bbe456a3272bf520ee1377bf3f37 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
store_nodes = []
if root == None:
return None
queue = collections.deque([root])
while queue:
node = queue.popleft()
if node:
... | the_stack_v2_python_sparse | Trees/serializeDeserialize_299.py | a2nagi/Competitive-Programming | train | 0 | |
a5072d7ab55fcf84c81452597cc2db5027e05c21 | [
"length = len(matrix)\ncol_cutoff = 0\nfor i in range(length):\n for j in range(length):\n if j < col_cutoff:\n matrix[i][j], matrix[j][i] = (matrix[j][i], matrix[i][j])\n col_cutoff += 1\nl_ptr = 0\nr_ptr = length - 1\nwhile r_ptr > l_ptr:\n for col in range(length):\n print(col, ... | <|body_start_0|>
length = len(matrix)
col_cutoff = 0
for i in range(length):
for j in range(length):
if j < col_cutoff:
matrix[i][j], matrix[j][i] = (matrix[j][i], matrix[i][j])
col_cutoff += 1
l_ptr = 0
r_ptr = length -... | Original strat Runtime: 56 ms, faster than 6.55% of Python online submissions for Rotate Image. Memory Usage: 12.7 MB, less than 5.41% of Python online submissions for Rotate Image. | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Original strat Runtime: 56 ms, faster than 6.55% of Python online submissions for Rotate Image. Memory Usage: 12.7 MB, less than 5.41% of Python online submissions for Rotate Image."""
def rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: None Do not return ... | stack_v2_sparse_classes_75kplus_train_074244 | 2,559 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead.",
"name": "rotate",
"signature": "def rotate(self, matrix)"
},
{
"docstring": ":type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead.",
... | 2 | stack_v2_sparse_classes_30k_train_014573 | Implement the Python class `Solution` described below.
Class description:
Original strat Runtime: 56 ms, faster than 6.55% of Python online submissions for Rotate Image. Memory Usage: 12.7 MB, less than 5.41% of Python online submissions for Rotate Image.
Method signatures and docstrings:
- def rotate(self, matrix): ... | Implement the Python class `Solution` described below.
Class description:
Original strat Runtime: 56 ms, faster than 6.55% of Python online submissions for Rotate Image. Memory Usage: 12.7 MB, less than 5.41% of Python online submissions for Rotate Image.
Method signatures and docstrings:
- def rotate(self, matrix): ... | 844f502da4d6fb9cd69cf0a1ef71da3385a4d2b4 | <|skeleton|>
class Solution:
"""Original strat Runtime: 56 ms, faster than 6.55% of Python online submissions for Rotate Image. Memory Usage: 12.7 MB, less than 5.41% of Python online submissions for Rotate Image."""
def rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: None Do not return ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""Original strat Runtime: 56 ms, faster than 6.55% of Python online submissions for Rotate Image. Memory Usage: 12.7 MB, less than 5.41% of Python online submissions for Rotate Image."""
def rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: None Do not return anything, mod... | the_stack_v2_python_sparse | 48-rotate_image.py | stevestar888/leetcode-problems | train | 2 |
7e5ebf1deea270e3abfb052d41ccdb09571cdf63 | [
"import paramiko\nprint('ssh_to_host %s@%s' % (username, hostname))\nk = paramiko.RSAKey.from_private_key_file(ssh_key)\nself.ssh_client = paramiko.SSHClient()\nself.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\ncounter = retry\nwhile counter > 0:\n try:\n self.ssh_client.connect(hostn... | <|body_start_0|>
import paramiko
print('ssh_to_host %s@%s' % (username, hostname))
k = paramiko.RSAKey.from_private_key_file(ssh_key)
self.ssh_client = paramiko.SSHClient()
self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
counter = retry
while... | SshClient | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SshClient:
def __init__(self, hostname, ssh_key=None, username=None, retry=1):
"""Create ssh connection to host Creates and returns and ssh connection to the host passed in. Args: hostname: host name or ip address of the system to connect to. retry: number of time to retry. ssh_key: full... | stack_v2_sparse_classes_75kplus_train_074245 | 32,544 | no_license | [
{
"docstring": "Create ssh connection to host Creates and returns and ssh connection to the host passed in. Args: hostname: host name or ip address of the system to connect to. retry: number of time to retry. ssh_key: full path to the ssk hey to use to connect. username: username to connect with. returns SSH cl... | 3 | stack_v2_sparse_classes_30k_val_000712 | Implement the Python class `SshClient` described below.
Class description:
Implement the SshClient class.
Method signatures and docstrings:
- def __init__(self, hostname, ssh_key=None, username=None, retry=1): Create ssh connection to host Creates and returns and ssh connection to the host passed in. Args: hostname: ... | Implement the Python class `SshClient` described below.
Class description:
Implement the SshClient class.
Method signatures and docstrings:
- def __init__(self, hostname, ssh_key=None, username=None, retry=1): Create ssh connection to host Creates and returns and ssh connection to the host passed in. Args: hostname: ... | 2e316cf1def0b72b47f79a864ed3aa778c297b95 | <|skeleton|>
class SshClient:
def __init__(self, hostname, ssh_key=None, username=None, retry=1):
"""Create ssh connection to host Creates and returns and ssh connection to the host passed in. Args: hostname: host name or ip address of the system to connect to. retry: number of time to retry. ssh_key: full... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SshClient:
def __init__(self, hostname, ssh_key=None, username=None, retry=1):
"""Create ssh connection to host Creates and returns and ssh connection to the host passed in. Args: hostname: host name or ip address of the system to connect to. retry: number of time to retry. ssh_key: full path to the s... | the_stack_v2_python_sparse | util.py | bearpelican/cluster | train | 3 | |
13fd9260cd9381095efed53315fc93605ca0d227 | [
"sleep_chain = self.chain_type((Adder(1), sleep(seconds=0.05), sleep(seconds=0.05)))\nstart_time = time.time()\nresult = list(sleep_chain.dispatch(range(5)))\nend_time = time.time()\nself.assertEqual(result, list(range(1, 6)))\nself.assertLess(end_time - start_time, 0.5)",
"if self.converter is None:\n raise u... | <|body_start_0|>
sleep_chain = self.chain_type((Adder(1), sleep(seconds=0.05), sleep(seconds=0.05)))
start_time = time.time()
result = list(sleep_chain.dispatch(range(5)))
end_time = time.time()
self.assertEqual(result, list(range(1, 6)))
self.assertLess(end_time - start_... | ConcurrentChain | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConcurrentChain:
def test_concurrent(self):
"""concurrent sleep"""
<|body_0|>
def test_convert_concurrent(self):
"""concurrent sleep from converter"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sleep_chain = self.chain_type((Adder(1), sleep(second... | stack_v2_sparse_classes_75kplus_train_074246 | 4,703 | permissive | [
{
"docstring": "concurrent sleep",
"name": "test_concurrent",
"signature": "def test_concurrent(self)"
},
{
"docstring": "concurrent sleep from converter",
"name": "test_convert_concurrent",
"signature": "def test_convert_concurrent(self)"
}
] | 2 | null | Implement the Python class `ConcurrentChain` described below.
Class description:
Implement the ConcurrentChain class.
Method signatures and docstrings:
- def test_concurrent(self): concurrent sleep
- def test_convert_concurrent(self): concurrent sleep from converter | Implement the Python class `ConcurrentChain` described below.
Class description:
Implement the ConcurrentChain class.
Method signatures and docstrings:
- def test_concurrent(self): concurrent sleep
- def test_convert_concurrent(self): concurrent sleep from converter
<|skeleton|>
class ConcurrentChain:
def test_... | 4e17f9992b4780bd0d9309202e2847df640bffe8 | <|skeleton|>
class ConcurrentChain:
def test_concurrent(self):
"""concurrent sleep"""
<|body_0|>
def test_convert_concurrent(self):
"""concurrent sleep from converter"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConcurrentChain:
def test_concurrent(self):
"""concurrent sleep"""
sleep_chain = self.chain_type((Adder(1), sleep(seconds=0.05), sleep(seconds=0.05)))
start_time = time.time()
result = list(sleep_chain.dispatch(range(5)))
end_time = time.time()
self.assertEqual(... | the_stack_v2_python_sparse | chainlet_unittests/test_chainlet/test_concurrency/testbase_primitives.py | maxfischer2781/chainlet | train | 1 | |
f1ff355becc08866b3c986d3adcb3b568c36da18 | [
"if x < 0:\n return -self.reverse(-x)\nif x == 0:\n return 0\nresult = 0\nwhile x > 0:\n result = result * 10 + x % 10\n x /= 10\nreturn result if result < 2147483648 else 0",
"if x < 0:\n x = -int(str(abs(x))[::-1])\nelse:\n x = int(str(x)[::-1])\nreturn x if x >= -2 ** 31 and x < 2 ** 31 else ... | <|body_start_0|>
if x < 0:
return -self.reverse(-x)
if x == 0:
return 0
result = 0
while x > 0:
result = result * 10 + x % 10
x /= 10
return result if result < 2147483648 else 0
<|end_body_0|>
<|body_start_1|>
if x < 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def reverse2(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if x < 0:
return -self.reverse(-x)
if x == 0:
... | stack_v2_sparse_classes_75kplus_train_074247 | 628 | no_license | [
{
"docstring": ":type x: int :rtype: int",
"name": "reverse",
"signature": "def reverse(self, x)"
},
{
"docstring": ":type x: int :rtype: int",
"name": "reverse2",
"signature": "def reverse2(self, x)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, x): :type x: int :rtype: int
- def reverse2(self, x): :type x: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, x): :type x: int :rtype: int
- def reverse2(self, x): :type x: int :rtype: int
<|skeleton|>
class Solution:
def reverse(self, x):
""":type x: int ... | 071d5ca977c98de677cfb7e78281835710c13116 | <|skeleton|>
class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def reverse2(self, x):
""":type x: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
if x < 0:
return -self.reverse(-x)
if x == 0:
return 0
result = 0
while x > 0:
result = result * 10 + x % 10
x /= 10
return result if result < 21474836... | the_stack_v2_python_sparse | reverse_integer.py | jiongyzh/leetCode | train | 0 | |
c601381d1f62c28706da15c33f20ee01c1da4966 | [
"msgs = self.get_messages(min_priority)\nmsgs = filter(lambda x: not x._read, msgs)\nreturn msgs",
"msgs = sorted(self.messagebox, key=lambda x: x.timestamp)\nmsgs = filter(lambda x: x.priority >= min_priority, msgs)\nreturn msgs"
] | <|body_start_0|>
msgs = self.get_messages(min_priority)
msgs = filter(lambda x: not x._read, msgs)
return msgs
<|end_body_0|>
<|body_start_1|>
msgs = sorted(self.messagebox, key=lambda x: x.timestamp)
msgs = filter(lambda x: x.priority >= min_priority, msgs)
return msgs
... | Adapter for all persistent objects. Provides a method, L{get_messages}, that retrieves L{Message} objects. | MessageBox | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MessageBox:
"""Adapter for all persistent objects. Provides a method, L{get_messages}, that retrieves L{Message} objects."""
def get_unread(self, min_priority=INFO):
"""Retrieve unread messages. @param min_priority: Optional minimum priority of messages to be returned; one of INFO, W... | stack_v2_sparse_classes_75kplus_train_074248 | 8,668 | no_license | [
{
"docstring": "Retrieve unread messages. @param min_priority: Optional minimum priority of messages to be returned; one of INFO, WARNING, CRITICAL @type min_priority: int @return: A list of objects implementing L{IMessage}. @rtype: list",
"name": "get_unread",
"signature": "def get_unread(self, min_pri... | 2 | stack_v2_sparse_classes_30k_train_019597 | Implement the Python class `MessageBox` described below.
Class description:
Adapter for all persistent objects. Provides a method, L{get_messages}, that retrieves L{Message} objects.
Method signatures and docstrings:
- def get_unread(self, min_priority=INFO): Retrieve unread messages. @param min_priority: Optional mi... | Implement the Python class `MessageBox` described below.
Class description:
Adapter for all persistent objects. Provides a method, L{get_messages}, that retrieves L{Message} objects.
Method signatures and docstrings:
- def get_unread(self, min_priority=INFO): Retrieve unread messages. @param min_priority: Optional mi... | 1ea508c3d2b51742bc3b448c445cd0a3dba9e798 | <|skeleton|>
class MessageBox:
"""Adapter for all persistent objects. Provides a method, L{get_messages}, that retrieves L{Message} objects."""
def get_unread(self, min_priority=INFO):
"""Retrieve unread messages. @param min_priority: Optional minimum priority of messages to be returned; one of INFO, W... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MessageBox:
"""Adapter for all persistent objects. Provides a method, L{get_messages}, that retrieves L{Message} objects."""
def get_unread(self, min_priority=INFO):
"""Retrieve unread messages. @param min_priority: Optional minimum priority of messages to be returned; one of INFO, WARNING, CRITI... | the_stack_v2_python_sparse | Products/ZenWidgets/messaging.py | zenoss/zenoss-prodbin | train | 27 |
3de7e65d8aff5eeabe000b15a93114d834d21ec2 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | The action cache API is used to query whether a given action has already been performed and, if so, retrieve its result. Unlike the [ContentAddressableStorage][google.devtools.remoteexecution.v1test.ContentAddressableStorage], which addresses blobs by their own content, the action cache addresses the [ActionResult][goo... | ActionCacheServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActionCacheServicer:
"""The action cache API is used to query whether a given action has already been performed and, if so, retrieve its result. Unlike the [ContentAddressableStorage][google.devtools.remoteexecution.v1test.ContentAddressableStorage], which addresses blobs by their own content, th... | stack_v2_sparse_classes_75kplus_train_074249 | 24,490 | no_license | [
{
"docstring": "Retrieve a cached execution result. Errors: * `NOT_FOUND`: The requested `ActionResult` is not in the cache.",
"name": "GetActionResult",
"signature": "def GetActionResult(self, request, context)"
},
{
"docstring": "Upload a new execution result. This method is intended for serve... | 2 | stack_v2_sparse_classes_30k_train_028266 | Implement the Python class `ActionCacheServicer` described below.
Class description:
The action cache API is used to query whether a given action has already been performed and, if so, retrieve its result. Unlike the [ContentAddressableStorage][google.devtools.remoteexecution.v1test.ContentAddressableStorage], which a... | Implement the Python class `ActionCacheServicer` described below.
Class description:
The action cache API is used to query whether a given action has already been performed and, if so, retrieve its result. Unlike the [ContentAddressableStorage][google.devtools.remoteexecution.v1test.ContentAddressableStorage], which a... | d7424d21aa0dc121acc4d64b427ba365a3581a20 | <|skeleton|>
class ActionCacheServicer:
"""The action cache API is used to query whether a given action has already been performed and, if so, retrieve its result. Unlike the [ContentAddressableStorage][google.devtools.remoteexecution.v1test.ContentAddressableStorage], which addresses blobs by their own content, th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ActionCacheServicer:
"""The action cache API is used to query whether a given action has already been performed and, if so, retrieve its result. Unlike the [ContentAddressableStorage][google.devtools.remoteexecution.v1test.ContentAddressableStorage], which addresses blobs by their own content, the action cach... | the_stack_v2_python_sparse | google/devtools/remoteexecution/v1test/remote_execution_pb2_grpc.py | msachtler/bazel-event-protocol-parser | train | 1 |
55deb364e57c54b36b0fee0dc54f8ce7e69f6d85 | [
"self.Wh = np.random.normal(size=(h + i, h))\nself.Wy = np.random.normal(size=(h, o))\nself.bh = np.zeros((1, h))\nself.by = np.zeros((1, o))",
"con = np.concatenate((h_prev.T, x_t.T), axis=0)\nh_next = np.tanh(np.matmul(con.T, self.Wh) + self.bh)\nsoft = np.matmul(h_next, self.Wy) + self.by\nx_max = np.max(soft,... | <|body_start_0|>
self.Wh = np.random.normal(size=(h + i, h))
self.Wy = np.random.normal(size=(h, o))
self.bh = np.zeros((1, h))
self.by = np.zeros((1, o))
<|end_body_0|>
<|body_start_1|>
con = np.concatenate((h_prev.T, x_t.T), axis=0)
h_next = np.tanh(np.matmul(con.T, se... | Represents a cell of a simple RNN | RNNCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNCell:
"""Represents a cell of a simple RNN"""
def __init__(self, i, h, o):
"""Constructor @i: dimensionality of the data @h: dimensionality of the hidden state @o: dimensionality of the outputs public instance attributes Wh, Wy, bh, by - weights and biases @Wh and bh are for the c... | stack_v2_sparse_classes_75kplus_train_074250 | 1,550 | no_license | [
{
"docstring": "Constructor @i: dimensionality of the data @h: dimensionality of the hidden state @o: dimensionality of the outputs public instance attributes Wh, Wy, bh, by - weights and biases @Wh and bh are for the concatenated hidden state and input data @wy and by are for the output",
"name": "__init__... | 2 | stack_v2_sparse_classes_30k_train_033544 | Implement the Python class `RNNCell` described below.
Class description:
Represents a cell of a simple RNN
Method signatures and docstrings:
- def __init__(self, i, h, o): Constructor @i: dimensionality of the data @h: dimensionality of the hidden state @o: dimensionality of the outputs public instance attributes Wh,... | Implement the Python class `RNNCell` described below.
Class description:
Represents a cell of a simple RNN
Method signatures and docstrings:
- def __init__(self, i, h, o): Constructor @i: dimensionality of the data @h: dimensionality of the hidden state @o: dimensionality of the outputs public instance attributes Wh,... | e20b284d5f1841952104d7d9a0274cff80eb304d | <|skeleton|>
class RNNCell:
"""Represents a cell of a simple RNN"""
def __init__(self, i, h, o):
"""Constructor @i: dimensionality of the data @h: dimensionality of the hidden state @o: dimensionality of the outputs public instance attributes Wh, Wy, bh, by - weights and biases @Wh and bh are for the c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RNNCell:
"""Represents a cell of a simple RNN"""
def __init__(self, i, h, o):
"""Constructor @i: dimensionality of the data @h: dimensionality of the hidden state @o: dimensionality of the outputs public instance attributes Wh, Wy, bh, by - weights and biases @Wh and bh are for the concatenated h... | the_stack_v2_python_sparse | supervised_learning/0x0D-RNNs/0-rnn_cell.py | jgadelugo/holbertonschool-machine_learning | train | 1 |
457a27f09f923bb89554a339c625c67b6087af90 | [
"try:\n waybillId, tmsBillCode = ISHaveWaybill().is_have_waybill(driver=driver)[:2]\n HeplerWaybill().open_menu(self.driver, 'xpath->//*[@id=\"menu\"]/div/nav/ul/li[4]/label/a')\n if waybillId == None:\n waybillId, tmsBillCode = PageWaybillCreate(self.driver).create_waybill_submit(driver=driver)\n ... | <|body_start_0|>
try:
waybillId, tmsBillCode = ISHaveWaybill().is_have_waybill(driver=driver)[:2]
HeplerWaybill().open_menu(self.driver, 'xpath->//*[@id="menu"]/div/nav/ul/li[4]/label/a')
if waybillId == None:
waybillId, tmsBillCode = PageWaybillCreate(self.dr... | 运单详情页面 | PageWaybillDetail | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PageWaybillDetail:
"""运单详情页面"""
def get_waybill(self, driver=''):
"""获取运单详情页面的运单号"""
<|body_0|>
def waybill_detail(self, tmsBillCode=''):
"""运单详情"""
<|body_1|>
def get_amt(self, tmsBillCode):
"""获取到付金额\\尾款金额"""
<|body_2|>
<|end_skele... | stack_v2_sparse_classes_75kplus_train_074251 | 2,780 | no_license | [
{
"docstring": "获取运单详情页面的运单号",
"name": "get_waybill",
"signature": "def get_waybill(self, driver='')"
},
{
"docstring": "运单详情",
"name": "waybill_detail",
"signature": "def waybill_detail(self, tmsBillCode='')"
},
{
"docstring": "获取到付金额\\\\尾款金额",
"name": "get_amt",
"signat... | 3 | stack_v2_sparse_classes_30k_train_002490 | Implement the Python class `PageWaybillDetail` described below.
Class description:
运单详情页面
Method signatures and docstrings:
- def get_waybill(self, driver=''): 获取运单详情页面的运单号
- def waybill_detail(self, tmsBillCode=''): 运单详情
- def get_amt(self, tmsBillCode): 获取到付金额\\尾款金额 | Implement the Python class `PageWaybillDetail` described below.
Class description:
运单详情页面
Method signatures and docstrings:
- def get_waybill(self, driver=''): 获取运单详情页面的运单号
- def waybill_detail(self, tmsBillCode=''): 运单详情
- def get_amt(self, tmsBillCode): 获取到付金额\\尾款金额
<|skeleton|>
class PageWaybillDetail:
"""运单详... | 9cc0f2ae11016168a22d17e2c913e662ee9802f2 | <|skeleton|>
class PageWaybillDetail:
"""运单详情页面"""
def get_waybill(self, driver=''):
"""获取运单详情页面的运单号"""
<|body_0|>
def waybill_detail(self, tmsBillCode=''):
"""运单详情"""
<|body_1|>
def get_amt(self, tmsBillCode):
"""获取到付金额\\尾款金额"""
<|body_2|>
<|end_skele... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PageWaybillDetail:
"""运单详情页面"""
def get_waybill(self, driver=''):
"""获取运单详情页面的运单号"""
try:
waybillId, tmsBillCode = ISHaveWaybill().is_have_waybill(driver=driver)[:2]
HeplerWaybill().open_menu(self.driver, 'xpath->//*[@id="menu"]/div/nav/ul/li[4]/label/a')
... | the_stack_v2_python_sparse | src/page/page_waybill_detail.py | penny1205/UI_testing | train | 0 |
5f51c2d31655fd862ba83b471dc43d846f768bb8 | [
"raw_data = '15 16 17'\nresult = list(shakemap.read_shakemap_data_from_str(raw_data))\nself.assertEqual([15, 16, 17], result)",
"raw_data = '15 16 17\\n18 19 20'\nresult = list(shakemap.read_shakemap_data_from_str(raw_data))\nself.assertEqual([15, 16, 17, 18, 19, 20], result)",
"raw_data = '15 16 17 18 19 20'\n... | <|body_start_0|>
raw_data = '15 16 17'
result = list(shakemap.read_shakemap_data_from_str(raw_data))
self.assertEqual([15, 16, 17], result)
<|end_body_0|>
<|body_start_1|>
raw_data = '15 16 17\n18 19 20'
result = list(shakemap.read_shakemap_data_from_str(raw_data))
self.... | This is the test class for reading the content from the grid_data text. | TestReadShakemapGridData | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestReadShakemapGridData:
"""This is the test class for reading the content from the grid_data text."""
def test_one_row_ints(self):
"""Test with one row of integers."""
<|body_0|>
def test_two_rows_ints(self):
"""Test with two rows of integers. Here we use a rea... | stack_v2_sparse_classes_75kplus_train_074252 | 5,316 | permissive | [
{
"docstring": "Test with one row of integers.",
"name": "test_one_row_ints",
"signature": "def test_one_row_ints(self)"
},
{
"docstring": "Test with two rows of integers. Here we use a real newline.",
"name": "test_two_rows_ints",
"signature": "def test_two_rows_ints(self)"
},
{
... | 6 | stack_v2_sparse_classes_30k_train_010384 | Implement the Python class `TestReadShakemapGridData` described below.
Class description:
This is the test class for reading the content from the grid_data text.
Method signatures and docstrings:
- def test_one_row_ints(self): Test with one row of integers.
- def test_two_rows_ints(self): Test with two rows of intege... | Implement the Python class `TestReadShakemapGridData` described below.
Class description:
This is the test class for reading the content from the grid_data text.
Method signatures and docstrings:
- def test_one_row_ints(self): Test with one row of integers.
- def test_two_rows_ints(self): Test with two rows of intege... | e6c638579f5f2572fbfe9872ec245129a0cb50a6 | <|skeleton|>
class TestReadShakemapGridData:
"""This is the test class for reading the content from the grid_data text."""
def test_one_row_ints(self):
"""Test with one row of integers."""
<|body_0|>
def test_two_rows_ints(self):
"""Test with two rows of integers. Here we use a rea... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestReadShakemapGridData:
"""This is the test class for reading the content from the grid_data text."""
def test_one_row_ints(self):
"""Test with one row of integers."""
raw_data = '15 16 17'
result = list(shakemap.read_shakemap_data_from_str(raw_data))
self.assertEqual([1... | the_stack_v2_python_sparse | test_shakemap.py | gfzriesgos/deus | train | 1 |
d88b4d638e880ef62f672a9cc46b0abccc917e5e | [
"self._name = name\nself._url = None\nself._grpc_options = dict()\nself._tlsCACerts = dict()\nself._registrar = []",
"if 'url' in info:\n self._url = info['url']\nif 'grpc_options' in info:\n self._grpc_options = info['grpc_options']\nif 'tlsCACerts' in info:\n self._tlsCACerts = info['tlsCACerts']\nif '... | <|body_start_0|>
self._name = name
self._url = None
self._grpc_options = dict()
self._tlsCACerts = dict()
self._registrar = []
<|end_body_0|>
<|body_start_1|>
if 'url' in info:
self._url = info['url']
if 'grpc_options' in info:
self._grpc_... | An organization in the network. It contains several members. | certificateAuthority | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class certificateAuthority:
"""An organization in the network. It contains several members."""
def __init__(self, name='ca'):
""":param name: Name of the organization"""
<|body_0|>
def init_with_bundle(self, info):
"""Init the peer with given info dict :param info: Dic... | stack_v2_sparse_classes_75kplus_train_074253 | 1,349 | permissive | [
{
"docstring": ":param name: Name of the organization",
"name": "__init__",
"signature": "def __init__(self, name='ca')"
},
{
"docstring": "Init the peer with given info dict :param info: Dict including all info, e.g., :return: True or False",
"name": "init_with_bundle",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_000688 | Implement the Python class `certificateAuthority` described below.
Class description:
An organization in the network. It contains several members.
Method signatures and docstrings:
- def __init__(self, name='ca'): :param name: Name of the organization
- def init_with_bundle(self, info): Init the peer with given info ... | Implement the Python class `certificateAuthority` described below.
Class description:
An organization in the network. It contains several members.
Method signatures and docstrings:
- def __init__(self, name='ca'): :param name: Name of the organization
- def init_with_bundle(self, info): Init the peer with given info ... | 0ca510569229217f81fb093682c38e1b4a0cd7c6 | <|skeleton|>
class certificateAuthority:
"""An organization in the network. It contains several members."""
def __init__(self, name='ca'):
""":param name: Name of the organization"""
<|body_0|>
def init_with_bundle(self, info):
"""Init the peer with given info dict :param info: Dic... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class certificateAuthority:
"""An organization in the network. It contains several members."""
def __init__(self, name='ca'):
""":param name: Name of the organization"""
self._name = name
self._url = None
self._grpc_options = dict()
self._tlsCACerts = dict()
self... | the_stack_v2_python_sparse | hfc/fabric/certificateAuthority.py | hyperledger/fabric-sdk-py | train | 439 |
caa1a732ffd449f5d248732e2735d78b5537b34f | [
"self.val = value\nself.left = left\nself.right = right",
"preOrder = ''\nif self:\n preOrder += str(self.val)\nif self.left:\n preOrder += ' ' + str(self.left)\nif self.right:\n preOrder += ' ' + str(self.right)\nreturn preOrder"
] | <|body_start_0|>
self.val = value
self.left = left
self.right = right
<|end_body_0|>
<|body_start_1|>
preOrder = ''
if self:
preOrder += str(self.val)
if self.left:
preOrder += ' ' + str(self.left)
if self.right:
preOrder += ' ... | TreeNode | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TreeNode:
def __init__(self, value, left=None, right=None):
""":type value: int or str, left: TreeNode, right: TreeNode"""
<|body_0|>
def __str__(self):
""":rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.val = value
self.lef... | stack_v2_sparse_classes_75kplus_train_074254 | 1,997 | no_license | [
{
"docstring": ":type value: int or str, left: TreeNode, right: TreeNode",
"name": "__init__",
"signature": "def __init__(self, value, left=None, right=None)"
},
{
"docstring": ":rtype: str",
"name": "__str__",
"signature": "def __str__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000993 | Implement the Python class `TreeNode` described below.
Class description:
Implement the TreeNode class.
Method signatures and docstrings:
- def __init__(self, value, left=None, right=None): :type value: int or str, left: TreeNode, right: TreeNode
- def __str__(self): :rtype: str | Implement the Python class `TreeNode` described below.
Class description:
Implement the TreeNode class.
Method signatures and docstrings:
- def __init__(self, value, left=None, right=None): :type value: int or str, left: TreeNode, right: TreeNode
- def __str__(self): :rtype: str
<|skeleton|>
class TreeNode:
def... | fa624b702129fa3efd6997791e4cd37c420e114e | <|skeleton|>
class TreeNode:
def __init__(self, value, left=None, right=None):
""":type value: int or str, left: TreeNode, right: TreeNode"""
<|body_0|>
def __str__(self):
""":rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TreeNode:
def __init__(self, value, left=None, right=None):
""":type value: int or str, left: TreeNode, right: TreeNode"""
self.val = value
self.left = left
self.right = right
def __str__(self):
""":rtype: str"""
preOrder = ''
if self:
p... | the_stack_v2_python_sparse | p65/p65.py | zois-tasoulas/DailyInterviewPro | train | 0 | |
22df42fe5d83a3eb523386083865265e9e4c2e2e | [
"for key in ('clock', 'label'):\n if key in kwargs:\n self._settings[key] = kwargs[key]",
"if self.active():\n if self._fade is not None:\n if self._fade_up:\n self.remove()\n else:\n self.add()\n else:\n self.remove()\nelse:\n self.add()",
"text = S... | <|body_start_0|>
for key in ('clock', 'label'):
if key in kwargs:
self._settings[key] = kwargs[key]
<|end_body_0|>
<|body_start_1|>
if self.active():
if self._fade is not None:
if self._fade_up:
self.remove()
el... | FPS counter | FPSCounter | [
"BSD-2-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FPSCounter:
"""FPS counter"""
def _config(self, **kwargs):
"""clock: ``pygame.time.Clock`` Clock used to time the game loop. label: ``str`` Text to display in front of the value."""
<|body_0|>
def toggle(self):
"""Toggle the FPS counter, adding or removing this w... | stack_v2_sparse_classes_75kplus_train_074255 | 1,517 | permissive | [
{
"docstring": "clock: ``pygame.time.Clock`` Clock used to time the game loop. label: ``str`` Text to display in front of the value.",
"name": "_config",
"signature": "def _config(self, **kwargs)"
},
{
"docstring": "Toggle the FPS counter, adding or removing this widget.",
"name": "toggle",
... | 3 | null | Implement the Python class `FPSCounter` described below.
Class description:
FPS counter
Method signatures and docstrings:
- def _config(self, **kwargs): clock: ``pygame.time.Clock`` Clock used to time the game loop. label: ``str`` Text to display in front of the value.
- def toggle(self): Toggle the FPS counter, addi... | Implement the Python class `FPSCounter` described below.
Class description:
FPS counter
Method signatures and docstrings:
- def _config(self, **kwargs): clock: ``pygame.time.Clock`` Clock used to time the game loop. label: ``str`` Text to display in front of the value.
- def toggle(self): Toggle the FPS counter, addi... | 95cb53b664f312e0830f010c0c96be94d4a4db90 | <|skeleton|>
class FPSCounter:
"""FPS counter"""
def _config(self, **kwargs):
"""clock: ``pygame.time.Clock`` Clock used to time the game loop. label: ``str`` Text to display in front of the value."""
<|body_0|>
def toggle(self):
"""Toggle the FPS counter, adding or removing this w... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FPSCounter:
"""FPS counter"""
def _config(self, **kwargs):
"""clock: ``pygame.time.Clock`` Clock used to time the game loop. label: ``str`` Text to display in front of the value."""
for key in ('clock', 'label'):
if key in kwargs:
self._settings[key] = kwargs[k... | the_stack_v2_python_sparse | pygame/GUI- widgets-SGC/sgc/widgets/fps_counter.py | furas/python-examples | train | 176 |
33dbfb8253641b023445217ab1877f204f8239ad | [
"n = min(len(src), len(tgt))\nfor i in range(n):\n tgt[i] = DCCopy.deep_corresponding_copy(src[i], tgt[i])\nif len(src) > n:\n for i in range(n, len(src)):\n _ = tgt.add()\n _ = DCCopy.deep_corresponding_copy(src[i], tgt[i])\nreturn tgt",
"n = min(len(src), len(tgt))\nfor i in range(n):\n t... | <|body_start_0|>
n = min(len(src), len(tgt))
for i in range(n):
tgt[i] = DCCopy.deep_corresponding_copy(src[i], tgt[i])
if len(src) > n:
for i in range(n, len(src)):
_ = tgt.add()
_ = DCCopy.deep_corresponding_copy(src[i], tgt[i])
r... | _DcopyProto | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _DcopyProto:
def copy_list_2_protobuf_composite_repeat(src: List, tgt, **kwargs) -> object:
"""Where there are corresponding list[i] update Target with Source Where Source is longer than Target append Source elements to Target elements :param src: Source list :param tgt: Protobuf Compose... | stack_v2_sparse_classes_75kplus_train_074256 | 20,177 | permissive | [
{
"docstring": "Where there are corresponding list[i] update Target with Source Where Source is longer than Target append Source elements to Target elements :param src: Source list :param tgt: Protobuf Composeite Repeat to merge to. :return: Updated Target",
"name": "copy_list_2_protobuf_composite_repeat",
... | 6 | stack_v2_sparse_classes_30k_train_018191 | Implement the Python class `_DcopyProto` described below.
Class description:
Implement the _DcopyProto class.
Method signatures and docstrings:
- def copy_list_2_protobuf_composite_repeat(src: List, tgt, **kwargs) -> object: Where there are corresponding list[i] update Target with Source Where Source is longer than T... | Implement the Python class `_DcopyProto` described below.
Class description:
Implement the _DcopyProto class.
Method signatures and docstrings:
- def copy_list_2_protobuf_composite_repeat(src: List, tgt, **kwargs) -> object: Where there are corresponding list[i] update Target with Source Where Source is longer than T... | 3b081696b1d226815e029cbb536fac5e4d3de9a7 | <|skeleton|>
class _DcopyProto:
def copy_list_2_protobuf_composite_repeat(src: List, tgt, **kwargs) -> object:
"""Where there are corresponding list[i] update Target with Source Where Source is longer than Target append Source elements to Target elements :param src: Source list :param tgt: Protobuf Compose... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _DcopyProto:
def copy_list_2_protobuf_composite_repeat(src: List, tgt, **kwargs) -> object:
"""Where there are corresponding list[i] update Target with Source Where Source is longer than Target append Source elements to Target elements :param src: Source list :param tgt: Protobuf Composeite Repeat to ... | the_stack_v2_python_sparse | journey11/src/lib/dcopy/dccopy.py | parrisma/AI-Intuition | train | 0 | |
18003e622fd48ca1c7eacd34128a9397e24e1cee | [
"self.d = {}\nfor i in range(len(words)):\n cur = words[i]\n if cur not in self.d:\n self.d[cur] = [i]\n else:\n self.d[cur].append(i)",
"x = self.d[word1]\ny = self.d[word2]\nres = sys.maxint\ni, j = (0, 0)\nwhile i < len(x) and j < len(y):\n res = min(res, abs(x[i] - y[j]))\n if x[i... | <|body_start_0|>
self.d = {}
for i in range(len(words)):
cur = words[i]
if cur not in self.d:
self.d[cur] = [i]
else:
self.d[cur].append(i)
<|end_body_0|>
<|body_start_1|>
x = self.d[word1]
y = self.d[word2]
res... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.d = {}
for i in range(le... | stack_v2_sparse_classes_75kplus_train_074257 | 1,811 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortest(self, word1, word2)"
}
] | 2 | null | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int
<|skeleton|>
class WordDistance:
... | 20623defecf65cbc35b194d8b60d8b211816ee4f | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
self.d = {}
for i in range(len(words)):
cur = words[i]
if cur not in self.d:
self.d[cur] = [i]
else:
self.d[cur].append(i)
def shortest(self, w... | the_stack_v2_python_sparse | in_Python/0244 Shortest Word Distance II.py | YangLiyli131/Leetcode2020 | train | 0 | |
79f5ad33c3b213df679c819b41c060746b18252e | [
"if not root:\n return '[]'\nqueue = collections.deque()\nqueue.append(root)\nres = []\nwhile queue:\n node = queue.popleft()\n if node:\n res.append(str(node.val))\n queue.append(node.left)\n queue.append(node.right)\n else:\n res.append('null')\nreturn '[' + ','.join(res) +... | <|body_start_0|>
if not root:
return '[]'
queue = collections.deque()
queue.append(root)
res = []
while queue:
node = queue.popleft()
if node:
res.append(str(node.val))
queue.append(node.left)
que... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_074258 | 1,977 | 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_037601 | 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:... | 809424acee0e63b795a46fdc51c5aef6e669d547 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return '[]'
queue = collections.deque()
queue.append(root)
res = []
while queue:
node = queue.popleft()
i... | the_stack_v2_python_sparse | python_offer/37_序列化二叉树.py | Madanfeng/JianZhiOffer | train | 0 | |
c83ce6e735fd9910d932ed0ca33158d81740a57e | [
"response_data = {}\nbase_uri = generate_base_uri(request)\ntry:\n existing_group = Group.objects.get(id=group_id)\n existing_relationship = existing_group.user_set.get(id=user_id)\nexcept ObjectDoesNotExist:\n existing_group = None\n existing_relationship = None\nif existing_group and existing_relation... | <|body_start_0|>
response_data = {}
base_uri = generate_base_uri(request)
try:
existing_group = Group.objects.get(id=group_id)
existing_relationship = existing_group.user_set.get(id=user_id)
except ObjectDoesNotExist:
existing_group = None
... | ### The GroupsUsersDetail view allows clients to interact with a specific Group-User relationship - URI: ```/api/groups/{group_id}/users/{user_id}``` - GET: Returns a JSON representation of the specified Group-User relationship - DELETE: Removes an existing Group-User relationship ### Use Cases/Notes: * Use the GroupsU... | GroupsUsersDetail | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupsUsersDetail:
"""### The GroupsUsersDetail view allows clients to interact with a specific Group-User relationship - URI: ```/api/groups/{group_id}/users/{user_id}``` - GET: Returns a JSON representation of the specified Group-User relationship - DELETE: Removes an existing Group-User relati... | stack_v2_sparse_classes_75kplus_train_074259 | 30,237 | no_license | [
{
"docstring": "GET /api/groups/{group_id}/users/{user_id}",
"name": "get",
"signature": "def get(self, request, group_id, user_id)"
},
{
"docstring": "DELETE removes/inactivates/etc. an existing group-user relationship",
"name": "delete",
"signature": "def delete(self, request, group_id... | 2 | stack_v2_sparse_classes_30k_train_005020 | Implement the Python class `GroupsUsersDetail` described below.
Class description:
### The GroupsUsersDetail view allows clients to interact with a specific Group-User relationship - URI: ```/api/groups/{group_id}/users/{user_id}``` - GET: Returns a JSON representation of the specified Group-User relationship - DELETE... | Implement the Python class `GroupsUsersDetail` described below.
Class description:
### The GroupsUsersDetail view allows clients to interact with a specific Group-User relationship - URI: ```/api/groups/{group_id}/users/{user_id}``` - GET: Returns a JSON representation of the specified Group-User relationship - DELETE... | 37966aeda6e444bbfae23babc067646ab08d4ed5 | <|skeleton|>
class GroupsUsersDetail:
"""### The GroupsUsersDetail view allows clients to interact with a specific Group-User relationship - URI: ```/api/groups/{group_id}/users/{user_id}``` - GET: Returns a JSON representation of the specified Group-User relationship - DELETE: Removes an existing Group-User relati... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GroupsUsersDetail:
"""### The GroupsUsersDetail view allows clients to interact with a specific Group-User relationship - URI: ```/api/groups/{group_id}/users/{user_id}``` - GET: Returns a JSON representation of the specified Group-User relationship - DELETE: Removes an existing Group-User relationship ### Us... | the_stack_v2_python_sparse | api_manager/groups/views.py | eduStack/edx-serverapi | train | 0 |
812018a6c7c10c8c313615447182921d220a28cb | [
"self.bot.plugin['xep_0030'].add_feature(FEATURE)\nself.bot.add_handler(MASK, self.handle_tune)\nself.tunes = {}",
"logging.info('Got Tune')\njid = xml.get('from')\ntune = xml.find(FIND)\nif tune is None:\n self.tunes[jid] = 'No tune.'\n return\nartist = tune.find('{http://jabber.org/protocol/tune}artist')\... | <|body_start_0|>
self.bot.plugin['xep_0030'].add_feature(FEATURE)
self.bot.add_handler(MASK, self.handle_tune)
self.tunes = {}
<|end_body_0|>
<|body_start_1|>
logging.info('Got Tune')
jid = xml.get('from')
tune = xml.find(FIND)
if tune is None:
self.t... | A plugin to get user tune info. | GetTune | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetTune:
"""A plugin to get user tune info."""
def _on_register(self):
"""Register tunes into disco service plugin"""
<|body_0|>
def handle_tune(self, xml):
"""Store a tune."""
<|body_1|>
def handle_gettune(self, cmd, args, msg):
"""Returns t... | stack_v2_sparse_classes_75kplus_train_074260 | 1,940 | permissive | [
{
"docstring": "Register tunes into disco service plugin",
"name": "_on_register",
"signature": "def _on_register(self)"
},
{
"docstring": "Store a tune.",
"name": "handle_tune",
"signature": "def handle_tune(self, xml)"
},
{
"docstring": "Returns the published tunes.",
"name... | 3 | stack_v2_sparse_classes_30k_train_018035 | Implement the Python class `GetTune` described below.
Class description:
A plugin to get user tune info.
Method signatures and docstrings:
- def _on_register(self): Register tunes into disco service plugin
- def handle_tune(self, xml): Store a tune.
- def handle_gettune(self, cmd, args, msg): Returns the published tu... | Implement the Python class `GetTune` described below.
Class description:
A plugin to get user tune info.
Method signatures and docstrings:
- def _on_register(self): Register tunes into disco service plugin
- def handle_tune(self, xml): Store a tune.
- def handle_gettune(self, cmd, args, msg): Returns the published tu... | 6690cc9f644d5b0c9f8eb6e3540eea336ed61847 | <|skeleton|>
class GetTune:
"""A plugin to get user tune info."""
def _on_register(self):
"""Register tunes into disco service plugin"""
<|body_0|>
def handle_tune(self, xml):
"""Store a tune."""
<|body_1|>
def handle_gettune(self, cmd, args, msg):
"""Returns t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GetTune:
"""A plugin to get user tune info."""
def _on_register(self):
"""Register tunes into disco service plugin"""
self.bot.plugin['xep_0030'].add_feature(FEATURE)
self.bot.add_handler(MASK, self.handle_tune)
self.tunes = {}
def handle_tune(self, xml):
"""S... | the_stack_v2_python_sparse | sleekbot/plugins/gettune.py | hgrecco/SleekBot | train | 2 |
1e41de733959a53c45a4cdd478d2252c255c743b | [
"for i in range(1, len(events)):\n assert events[i].obj == events[0].obj\nself.obj = events[0].obj\nself.events = events\nself.events.sort(key=lambda e: e.prob)\nprob = 0\nfor event in self.events:\n prob += event.prob\nassert util.approx(prob, 1.0)",
"f = random.random()\nevent = None\nfor i in range(len(s... | <|body_start_0|>
for i in range(1, len(events)):
assert events[i].obj == events[0].obj
self.obj = events[0].obj
self.events = events
self.events.sort(key=lambda e: e.prob)
prob = 0
for event in self.events:
prob += event.prob
assert util.ap... | A distribution as defined by the scavnger hunt problem. | Distribution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Distribution:
"""A distribution as defined by the scavnger hunt problem."""
def __init__(self, events):
"""The distribution is comprised of EVENTS. The events therein are collectively exhaustive, mutually exclusive, and describe the same object."""
<|body_0|>
def place(s... | stack_v2_sparse_classes_75kplus_train_074261 | 21,028 | no_license | [
{
"docstring": "The distribution is comprised of EVENTS. The events therein are collectively exhaustive, mutually exclusive, and describe the same object.",
"name": "__init__",
"signature": "def __init__(self, events)"
},
{
"docstring": "Generates a random location for the described object to ap... | 2 | stack_v2_sparse_classes_30k_train_019142 | Implement the Python class `Distribution` described below.
Class description:
A distribution as defined by the scavnger hunt problem.
Method signatures and docstrings:
- def __init__(self, events): The distribution is comprised of EVENTS. The events therein are collectively exhaustive, mutually exclusive, and describ... | Implement the Python class `Distribution` described below.
Class description:
A distribution as defined by the scavnger hunt problem.
Method signatures and docstrings:
- def __init__(self, events): The distribution is comprised of EVENTS. The events therein are collectively exhaustive, mutually exclusive, and describ... | bebffb2e886ba990f6b5fe6d51aa3ec4571c8d8c | <|skeleton|>
class Distribution:
"""A distribution as defined by the scavnger hunt problem."""
def __init__(self, events):
"""The distribution is comprised of EVENTS. The events therein are collectively exhaustive, mutually exclusive, and describe the same object."""
<|body_0|>
def place(s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Distribution:
"""A distribution as defined by the scavnger hunt problem."""
def __init__(self, events):
"""The distribution is comprised of EVENTS. The events therein are collectively exhaustive, mutually exclusive, and describe the same object."""
for i in range(1, len(events)):
... | the_stack_v2_python_sparse | bwi_scavenger/scripts/absim/world.py | utexas-bwi/scavenger_hunt | train | 2 |
da94460f7211ebed2ecf15af5a971f3bce950edd | [
"tokenizer = Tokenizer()\ntokenizer.fit_on_texts(descriptions.tolist())\ntextSequences = tokenizer.texts_to_sequences(descriptions.tolist())\nreturn (tokenizer, textSequences)",
"max_words = 0\nfor desc in descriptions.tolist():\n words = len(desc.split())\n if words > max_words:\n max_words = words\... | <|body_start_0|>
tokenizer = Tokenizer()
tokenizer.fit_on_texts(descriptions.tolist())
textSequences = tokenizer.texts_to_sequences(descriptions.tolist())
return (tokenizer, textSequences)
<|end_body_0|>
<|body_start_1|>
max_words = 0
for desc in descriptions.tolist():
... | Prepare text for model | PrepareText | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrepareText:
"""Prepare text for model"""
def tokenizer(descriptions):
"""Vectorize a text corpus, by turning each text into either a sequence of integers :param descriptions: Clean text :return: tokenizer - text tokenization utility class, textSequences - Converts a text to a sequen... | stack_v2_sparse_classes_75kplus_train_074262 | 5,005 | no_license | [
{
"docstring": "Vectorize a text corpus, by turning each text into either a sequence of integers :param descriptions: Clean text :return: tokenizer - text tokenization utility class, textSequences - Converts a text to a sequence of words (or tokens)",
"name": "tokenizer",
"signature": "def tokenizer(des... | 5 | stack_v2_sparse_classes_30k_train_043947 | Implement the Python class `PrepareText` described below.
Class description:
Prepare text for model
Method signatures and docstrings:
- def tokenizer(descriptions): Vectorize a text corpus, by turning each text into either a sequence of integers :param descriptions: Clean text :return: tokenizer - text tokenization u... | Implement the Python class `PrepareText` described below.
Class description:
Prepare text for model
Method signatures and docstrings:
- def tokenizer(descriptions): Vectorize a text corpus, by turning each text into either a sequence of integers :param descriptions: Clean text :return: tokenizer - text tokenization u... | 46e29554dc6433f608baa6132edd5ce89ef8d942 | <|skeleton|>
class PrepareText:
"""Prepare text for model"""
def tokenizer(descriptions):
"""Vectorize a text corpus, by turning each text into either a sequence of integers :param descriptions: Clean text :return: tokenizer - text tokenization utility class, textSequences - Converts a text to a sequen... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PrepareText:
"""Prepare text for model"""
def tokenizer(descriptions):
"""Vectorize a text corpus, by turning each text into either a sequence of integers :param descriptions: Clean text :return: tokenizer - text tokenization utility class, textSequences - Converts a text to a sequence of words (... | the_stack_v2_python_sparse | preparer/TextPreparer.py | YuliaChornenko/model-classification | train | 0 |
a585e860d622390e64d0e7cca23300bf4da28ff6 | [
"if response_key:\n return self._post('/os-certificates', {}, 'certificate', **kwargs)\nelse:\n return self._post('/os-certificates', {}, **kwargs)",
"if response_key:\n return self._get('/os-certificates/root', 'certificate', **kwargs)\nelse:\n return self._get('/os-certificates/root', **kwargs)"
] | <|body_start_0|>
if response_key:
return self._post('/os-certificates', {}, 'certificate', **kwargs)
else:
return self._post('/os-certificates', {}, **kwargs)
<|end_body_0|>
<|body_start_1|>
if response_key:
return self._get('/os-certificates/root', 'certific... | CertificateManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CertificateManager:
def create(self, response_key=True, **kwargs):
"""Create a x509 certificate for a user in tenant."""
<|body_0|>
def get(self, response_key=True, **kwargs):
"""Get root certificate."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_074263 | 787 | no_license | [
{
"docstring": "Create a x509 certificate for a user in tenant.",
"name": "create",
"signature": "def create(self, response_key=True, **kwargs)"
},
{
"docstring": "Get root certificate.",
"name": "get",
"signature": "def get(self, response_key=True, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012987 | Implement the Python class `CertificateManager` described below.
Class description:
Implement the CertificateManager class.
Method signatures and docstrings:
- def create(self, response_key=True, **kwargs): Create a x509 certificate for a user in tenant.
- def get(self, response_key=True, **kwargs): Get root certific... | Implement the Python class `CertificateManager` described below.
Class description:
Implement the CertificateManager class.
Method signatures and docstrings:
- def create(self, response_key=True, **kwargs): Create a x509 certificate for a user in tenant.
- def get(self, response_key=True, **kwargs): Get root certific... | 42f9197ba26ffb6b9dd336a524639ecbbf194365 | <|skeleton|>
class CertificateManager:
def create(self, response_key=True, **kwargs):
"""Create a x509 certificate for a user in tenant."""
<|body_0|>
def get(self, response_key=True, **kwargs):
"""Get root certificate."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CertificateManager:
def create(self, response_key=True, **kwargs):
"""Create a x509 certificate for a user in tenant."""
if response_key:
return self._post('/os-certificates', {}, 'certificate', **kwargs)
else:
return self._post('/os-certificates', {}, **kwargs)... | the_stack_v2_python_sparse | ops_client/project/nova/certs.py | tokuzfunpi/ops_client | train | 0 | |
55280ef08e8b4872244d4a46f439c0bc47a8f211 | [
"super(GCN, self).__init__()\nself.n_channels = n_channels\nself.skip_connection = skip_connection\nif isinstance(activation, str):\n self.activation = tf.keras.layers.Activation(activation)\nelif isinstance(tf.keras.layers.Activation):\n self.activation = activation\nelif activation is None:\n self.activa... | <|body_start_0|>
super(GCN, self).__init__()
self.n_channels = n_channels
self.skip_connection = skip_connection
if isinstance(activation, str):
self.activation = tf.keras.layers.Activation(activation)
elif isinstance(tf.keras.layers.Activation):
self.acti... | Implementation of Graph Convolutional Network (GCN) layer. Attributes: n_channels: Output dimensionality of the layer. skip_connection: If True, node features are propagated without neighborhood aggregation. activation: Activation function to use for the final representations. | GCN | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GCN:
"""Implementation of Graph Convolutional Network (GCN) layer. Attributes: n_channels: Output dimensionality of the layer. skip_connection: If True, node features are propagated without neighborhood aggregation. activation: Activation function to use for the final representations."""
def... | stack_v2_sparse_classes_75kplus_train_074264 | 3,255 | permissive | [
{
"docstring": "Initializes the layer with specified parameters.",
"name": "__init__",
"signature": "def __init__(self, n_channels, activation='selu', skip_connection=True)"
},
{
"docstring": "Builds the Keras model according to the input shape.",
"name": "build",
"signature": "def build... | 3 | stack_v2_sparse_classes_30k_train_041770 | Implement the Python class `GCN` described below.
Class description:
Implementation of Graph Convolutional Network (GCN) layer. Attributes: n_channels: Output dimensionality of the layer. skip_connection: If True, node features are propagated without neighborhood aggregation. activation: Activation function to use for... | Implement the Python class `GCN` described below.
Class description:
Implementation of Graph Convolutional Network (GCN) layer. Attributes: n_channels: Output dimensionality of the layer. skip_connection: If True, node features are propagated without neighborhood aggregation. activation: Activation function to use for... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class GCN:
"""Implementation of Graph Convolutional Network (GCN) layer. Attributes: n_channels: Output dimensionality of the layer. skip_connection: If True, node features are propagated without neighborhood aggregation. activation: Activation function to use for the final representations."""
def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GCN:
"""Implementation of Graph Convolutional Network (GCN) layer. Attributes: n_channels: Output dimensionality of the layer. skip_connection: If True, node features are propagated without neighborhood aggregation. activation: Activation function to use for the final representations."""
def __init__(sel... | the_stack_v2_python_sparse | graph_embedding/dmon/gcn.py | Jimmy-INL/google-research | train | 1 |
6f446e2ef3f403c60ff5f7f25eb434eea7ca3343 | [
"if not root:\n return ''\nrt = []\nstk = [root]\nwhile stk:\n newstk = []\n while stk:\n p = stk.pop(0)\n if p == None:\n rt.append('#')\n else:\n rt.append(str(p.val))\n newstk.extend([p.left, p.right])\n stk = newstk\nreturn ':'.join(rt)",
"if n... | <|body_start_0|>
if not root:
return ''
rt = []
stk = [root]
while stk:
newstk = []
while stk:
p = stk.pop(0)
if p == None:
rt.append('#')
else:
rt.append(str(p.val... | Codec1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec1:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_75kplus_train_074265 | 3,374 | 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_003694 | Implement the Python class `Codec1` described below.
Class description:
Implement the Codec1 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 :rtyp... | Implement the Python class `Codec1` described below.
Class description:
Implement the Codec1 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 :rtyp... | 0e99f9a5226507706b3ee66fd04bae813755ef40 | <|skeleton|>
class Codec1:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec1:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
rt = []
stk = [root]
while stk:
newstk = []
while stk:
p = stk.pop(0)
... | the_stack_v2_python_sparse | medium/tree/test_449_Serialize_and_Deserialize_BST.py | wuxu1019/leetcode_sophia | train | 1 | |
aef1055fa017cc1c81709134b3876bd62c0a746a | [
"self.v_2 = v_2\nself.omega = omega\nself.phi_0 = phi_0",
"cos_term = 2.0 * e * self.v_2 / self.omega * pm.cos(self.omega / (beam.beta * c) * beam.z + self.phi_0)\nbeam.xp += -beam.x * cos_term / beam.p0\nbeam.yp += beam.y * cos_term / beam.p0"
] | <|body_start_0|>
self.v_2 = v_2
self.omega = omega
self.phi_0 = phi_0
<|end_body_0|>
<|body_start_1|>
cos_term = 2.0 * e * self.v_2 / self.omega * pm.cos(self.omega / (beam.beta * c) * beam.z + self.phi_0)
beam.xp += -beam.x * cos_term / beam.p0
beam.yp += beam.y * cos_t... | Python implementation of the RFQ element acting on the particles' transverse coordinates (i.e. localized kick model). | RFQTransverseKick | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RFQTransverseKick:
"""Python implementation of the RFQ element acting on the particles' transverse coordinates (i.e. localized kick model)."""
def __init__(self, v_2, omega, phi_0):
"""An RFQ element is fully characterized by the parameters v_2: quadrupolar expansion coefficient of t... | stack_v2_sparse_classes_75kplus_train_074266 | 8,110 | permissive | [
{
"docstring": "An RFQ element is fully characterized by the parameters v_2: quadrupolar expansion coefficient of the accelerating voltage (~strength of the RFQ), in [V/m^2]. omega: Angular frequency of the RF wave, in [rad/s]. phi_0: Constant phase offset wrt. bunch center (z=0), in [rad].",
"name": "__ini... | 2 | stack_v2_sparse_classes_30k_train_029430 | Implement the Python class `RFQTransverseKick` described below.
Class description:
Python implementation of the RFQ element acting on the particles' transverse coordinates (i.e. localized kick model).
Method signatures and docstrings:
- def __init__(self, v_2, omega, phi_0): An RFQ element is fully characterized by t... | Implement the Python class `RFQTransverseKick` described below.
Class description:
Python implementation of the RFQ element acting on the particles' transverse coordinates (i.e. localized kick model).
Method signatures and docstrings:
- def __init__(self, v_2, omega, phi_0): An RFQ element is fully characterized by t... | b238bf3fbea02fcfaf8795ee54cc0e3134de477a | <|skeleton|>
class RFQTransverseKick:
"""Python implementation of the RFQ element acting on the particles' transverse coordinates (i.e. localized kick model)."""
def __init__(self, v_2, omega, phi_0):
"""An RFQ element is fully characterized by the parameters v_2: quadrupolar expansion coefficient of t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RFQTransverseKick:
"""Python implementation of the RFQ element acting on the particles' transverse coordinates (i.e. localized kick model)."""
def __init__(self, v_2, omega, phi_0):
"""An RFQ element is fully characterized by the parameters v_2: quadrupolar expansion coefficient of the accelerati... | the_stack_v2_python_sparse | PyHEADTAIL/rfq/rfq.py | PyCOMPLETE/PyHEADTAIL | train | 39 |
ba1f51320df86513a9be38a5284552e64010beff | [
"if not head or not head.next:\n return head\nlast_node = self.get_last_node(head)\nl1 = self.sort_list(head)\nl2 = self.sort_list(last_node)\nreturn self.merge(l1, l2)",
"fast = node\nslow = node\nbreak_node = node\nwhile fast and fast.next:\n fast = fast.next.next\n break_node = slow\n slow = slow.n... | <|body_start_0|>
if not head or not head.next:
return head
last_node = self.get_last_node(head)
l1 = self.sort_list(head)
l2 = self.sort_list(last_node)
return self.merge(l1, l2)
<|end_body_0|>
<|body_start_1|>
fast = node
slow = node
break_no... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sort_list(self, head: ListNode) -> ListNode:
"""对链表进行排序 Args: head: 节点 Returns: 链表"""
<|body_0|>
def get_last_node(self, node: ListNode) -> ListNode:
"""获取后部分节点 Args: node: node节点 Returns: 最后部分节点"""
<|body_1|>
def merge(self, l1: ListNode, ... | stack_v2_sparse_classes_75kplus_train_074267 | 2,630 | permissive | [
{
"docstring": "对链表进行排序 Args: head: 节点 Returns: 链表",
"name": "sort_list",
"signature": "def sort_list(self, head: ListNode) -> ListNode"
},
{
"docstring": "获取后部分节点 Args: node: node节点 Returns: 最后部分节点",
"name": "get_last_node",
"signature": "def get_last_node(self, node: ListNode) -> ListN... | 3 | stack_v2_sparse_classes_30k_train_049140 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sort_list(self, head: ListNode) -> ListNode: 对链表进行排序 Args: head: 节点 Returns: 链表
- def get_last_node(self, node: ListNode) -> ListNode: 获取后部分节点 Args: node: node节点 Returns: 最后部... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sort_list(self, head: ListNode) -> ListNode: 对链表进行排序 Args: head: 节点 Returns: 链表
- def get_last_node(self, node: ListNode) -> ListNode: 获取后部分节点 Args: node: node节点 Returns: 最后部... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def sort_list(self, head: ListNode) -> ListNode:
"""对链表进行排序 Args: head: 节点 Returns: 链表"""
<|body_0|>
def get_last_node(self, node: ListNode) -> ListNode:
"""获取后部分节点 Args: node: node节点 Returns: 最后部分节点"""
<|body_1|>
def merge(self, l1: ListNode, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def sort_list(self, head: ListNode) -> ListNode:
"""对链表进行排序 Args: head: 节点 Returns: 链表"""
if not head or not head.next:
return head
last_node = self.get_last_node(head)
l1 = self.sort_list(head)
l2 = self.sort_list(last_node)
return self.me... | the_stack_v2_python_sparse | src/leetcodepython/list/sort_list_148.py | zhangyu345293721/leetcode | train | 101 | |
6ae271287cd6168f6b9f6f6c87bdac24ceededbd | [
"from renku.core.commands.save import repo_sync\nif self.project_path is None:\n raise RenkuException('unable to sync with remote since no operation has been executed')\n_, remote_branch = repo_sync(Repo(self.project_path), remote=remote)\nreturn remote_branch",
"self.is_write = True\nresult = self.execute_op(... | <|body_start_0|>
from renku.core.commands.save import repo_sync
if self.project_path is None:
raise RenkuException('unable to sync with remote since no operation has been executed')
_, remote_branch = repo_sync(Repo(self.project_path), remote=remote)
return remote_branch
<|en... | Sync operation mixin. Extension of `RenkuOperationMixin` responsible for syncing all write operation with the remote. In case sync fails, it will create a new branch and push newly created branch to the remote and return the branch name to the client. | RenkuOpSyncMixin | [
"Apache-2.0",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RenkuOpSyncMixin:
"""Sync operation mixin. Extension of `RenkuOperationMixin` responsible for syncing all write operation with the remote. In case sync fails, it will create a new branch and push newly created branch to the remote and return the branch name to the client."""
def sync(self, r... | stack_v2_sparse_classes_75kplus_train_074268 | 14,650 | permissive | [
{
"docstring": "Sync with remote.",
"name": "sync",
"signature": "def sync(self, remote='origin')"
},
{
"docstring": "Execute operation which controller implements and sync with the remote.",
"name": "execute_and_sync",
"signature": "def execute_and_sync(self, remote='origin')"
}
] | 2 | stack_v2_sparse_classes_30k_train_010696 | Implement the Python class `RenkuOpSyncMixin` described below.
Class description:
Sync operation mixin. Extension of `RenkuOperationMixin` responsible for syncing all write operation with the remote. In case sync fails, it will create a new branch and push newly created branch to the remote and return the branch name ... | Implement the Python class `RenkuOpSyncMixin` described below.
Class description:
Sync operation mixin. Extension of `RenkuOperationMixin` responsible for syncing all write operation with the remote. In case sync fails, it will create a new branch and push newly created branch to the remote and return the branch name ... | 449ec7bca1cc435e5a8ceb278e49a422b953bb09 | <|skeleton|>
class RenkuOpSyncMixin:
"""Sync operation mixin. Extension of `RenkuOperationMixin` responsible for syncing all write operation with the remote. In case sync fails, it will create a new branch and push newly created branch to the remote and return the branch name to the client."""
def sync(self, r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RenkuOpSyncMixin:
"""Sync operation mixin. Extension of `RenkuOperationMixin` responsible for syncing all write operation with the remote. In case sync fails, it will create a new branch and push newly created branch to the remote and return the branch name to the client."""
def sync(self, remote='origin... | the_stack_v2_python_sparse | renku/service/controllers/api/mixins.py | code-inflation/renku-python | train | 0 |
f248eac9f36bc4d6a12d2fac1da5921e30bc91da | [
"ax, ay = (a // 6, a % 6)\nbx, by = (b // 6, b % 6)\nreturn abs(ax - bx) + abs(ay - by)",
"dp = [[[-1] * 30 for _ in range(30)] for _ in range(310)]\ndp[0][26][26] = 0\nn = len(word)\nfor i in range(1, n + 1):\n c = word[i - 1]\n v = ord(c) - ord('A')\n for a in range(0, 27):\n for b in range(0, 2... | <|body_start_0|>
ax, ay = (a // 6, a % 6)
bx, by = (b // 6, b % 6)
return abs(ax - bx) + abs(ay - by)
<|end_body_0|>
<|body_start_1|>
dp = [[[-1] * 30 for _ in range(30)] for _ in range(310)]
dp[0][26][26] = 0
n = len(word)
for i in range(1, n + 1):
c... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def get_dis(self, a, b):
"""获取从下标为a的字母移动到下标为b的字母的曼哈顿距离(花费) :param a: :param b: :return:"""
<|body_0|>
def minimumDistance(self, word: str) -> int:
"""dp[i][a][b] 表示输入完第i个字符时手指1放在A上, 手指2放在字母B的最小移动距离 状态表示: i: 输入到第i个字符 a或b = -1: 表示没有放置手指, 0~25: 表示手指放在字母'A'-'Z'... | stack_v2_sparse_classes_75kplus_train_074269 | 4,418 | no_license | [
{
"docstring": "获取从下标为a的字母移动到下标为b的字母的曼哈顿距离(花费) :param a: :param b: :return:",
"name": "get_dis",
"signature": "def get_dis(self, a, b)"
},
{
"docstring": "dp[i][a][b] 表示输入完第i个字符时手指1放在A上, 手指2放在字母B的最小移动距离 状态表示: i: 输入到第i个字符 a或b = -1: 表示没有放置手指, 0~25: 表示手指放在字母'A'-'Z'上 26: 表示手指还没有开始输入 状态转移: i-1的状态手指放在... | 2 | stack_v2_sparse_classes_30k_train_050615 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def get_dis(self, a, b): 获取从下标为a的字母移动到下标为b的字母的曼哈顿距离(花费) :param a: :param b: :return:
- def minimumDistance(self, word: str) -> int: dp[i][a][b] 表示输入完第i个字符时手指1放在A上, 手指2放在字母B的最小移动距... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def get_dis(self, a, b): 获取从下标为a的字母移动到下标为b的字母的曼哈顿距离(花费) :param a: :param b: :return:
- def minimumDistance(self, word: str) -> int: dp[i][a][b] 表示输入完第i个字符时手指1放在A上, 手指2放在字母B的最小移动距... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def get_dis(self, a, b):
"""获取从下标为a的字母移动到下标为b的字母的曼哈顿距离(花费) :param a: :param b: :return:"""
<|body_0|>
def minimumDistance(self, word: str) -> int:
"""dp[i][a][b] 表示输入完第i个字符时手指1放在A上, 手指2放在字母B的最小移动距离 状态表示: i: 输入到第i个字符 a或b = -1: 表示没有放置手指, 0~25: 表示手指放在字母'A'-'Z'... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def get_dis(self, a, b):
"""获取从下标为a的字母移动到下标为b的字母的曼哈顿距离(花费) :param a: :param b: :return:"""
ax, ay = (a // 6, a % 6)
bx, by = (b // 6, b % 6)
return abs(ax - bx) + abs(ay - by)
def minimumDistance(self, word: str) -> int:
"""dp[i][a][b] 表示输入完第i个字符时手指1放在A上,... | the_stack_v2_python_sparse | 1320. 二指输入的的最小距离.py | lovehhf/LeetCode | train | 0 | |
b856f7747b21d720bd74a737b9d136c9062871ca | [
"assert fanouts, 'fanouts must be specified'\nconfig = dict(fanouts=fanouts)\nconfig.update(kwargs)\nsuper().__init__(config=config)\nself.fanouts = fanouts\nself.fanouts_list = get_fanouts_list(fanouts)",
"fans = {}\nif 'ids' in inputs:\n fans['ids'] = torch.split(inputs['ids'], self.fanouts_list, dim=-1)\nif... | <|body_start_0|>
assert fanouts, 'fanouts must be specified'
config = dict(fanouts=fanouts)
config.update(kwargs)
super().__init__(config=config)
self.fanouts = fanouts
self.fanouts_list = get_fanouts_list(fanouts)
<|end_body_0|>
<|body_start_1|>
fans = {}
... | \\brief transform to convert bipartites \\details a bipartite is a dict: \\code{.py} dict( src=tensor, dst=tensor, src_feature=tensor, dst_feature=tensor, edge_weight=tensor, ) \\endcode \\par examples \\code{.py} >>> from galileo.pytorch import BipartiteTransform >>> bt = BipartiteTransform([2,3]) >>> res = bt.transfo... | BipartiteTransform | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BipartiteTransform:
"""\\brief transform to convert bipartites \\details a bipartite is a dict: \\code{.py} dict( src=tensor, dst=tensor, src_feature=tensor, dst_feature=tensor, edge_weight=tensor, ) \\endcode \\par examples \\code{.py} >>> from galileo.pytorch import BipartiteTransform >>> bt = ... | stack_v2_sparse_classes_75kplus_train_074270 | 4,264 | permissive | [
{
"docstring": "\\\\param fanouts number of multi hop",
"name": "__init__",
"signature": "def __init__(self, fanouts: list, **kwargs)"
},
{
"docstring": "\\\\param inputs dict(ids=tensor,feature=tensor,edge_weight=tensor) \\\\return list of bipartite\\\\n items in bipartites are arranged in the ... | 2 | stack_v2_sparse_classes_30k_train_030903 | Implement the Python class `BipartiteTransform` described below.
Class description:
\\brief transform to convert bipartites \\details a bipartite is a dict: \\code{.py} dict( src=tensor, dst=tensor, src_feature=tensor, dst_feature=tensor, edge_weight=tensor, ) \\endcode \\par examples \\code{.py} >>> from galileo.pyto... | Implement the Python class `BipartiteTransform` described below.
Class description:
\\brief transform to convert bipartites \\details a bipartite is a dict: \\code{.py} dict( src=tensor, dst=tensor, src_feature=tensor, dst_feature=tensor, edge_weight=tensor, ) \\endcode \\par examples \\code{.py} >>> from galileo.pyto... | 48099ec3f0331196c6812208ceb080ba618a588b | <|skeleton|>
class BipartiteTransform:
"""\\brief transform to convert bipartites \\details a bipartite is a dict: \\code{.py} dict( src=tensor, dst=tensor, src_feature=tensor, dst_feature=tensor, edge_weight=tensor, ) \\endcode \\par examples \\code{.py} >>> from galileo.pytorch import BipartiteTransform >>> bt = ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BipartiteTransform:
"""\\brief transform to convert bipartites \\details a bipartite is a dict: \\code{.py} dict( src=tensor, dst=tensor, src_feature=tensor, dst_feature=tensor, edge_weight=tensor, ) \\endcode \\par examples \\code{.py} >>> from galileo.pytorch import BipartiteTransform >>> bt = BipartiteTran... | the_stack_v2_python_sparse | galileo/framework/pytorch/python/transforms/bipartite.py | 2012fang1/galileo | train | 0 |
8b1b60905c24ed355cbcb53dac46bfd37fddbefc | [
"self._input_reader = TestInputReader()\nself._output_writer = cli_test_lib.TestOutputWriter(encoding=u'utf-8')\nself._test_tool = psort.PsortTool(input_reader=self._input_reader, output_writer=self._output_writer)",
"self._test_tool.ListOutputModules()\nraw_data = self._output_writer.ReadOutput()\nexpected_raw_d... | <|body_start_0|>
self._input_reader = TestInputReader()
self._output_writer = cli_test_lib.TestOutputWriter(encoding=u'utf-8')
self._test_tool = psort.PsortTool(input_reader=self._input_reader, output_writer=self._output_writer)
<|end_body_0|>
<|body_start_1|>
self._test_tool.ListOutput... | Tests for the psort tool. | PsortToolTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PsortToolTest:
"""Tests for the psort tool."""
def setUp(self):
"""Sets up the needed objects used throughout the test."""
<|body_0|>
def testListOutputModules(self):
"""Test the listing of output modules."""
<|body_1|>
def testProcessStorageWithMiss... | stack_v2_sparse_classes_75kplus_train_074271 | 5,058 | permissive | [
{
"docstring": "Sets up the needed objects used throughout the test.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test the listing of output modules.",
"name": "testListOutputModules",
"signature": "def testListOutputModules(self)"
},
{
"docstring": "Test ... | 3 | stack_v2_sparse_classes_30k_train_049015 | Implement the Python class `PsortToolTest` described below.
Class description:
Tests for the psort tool.
Method signatures and docstrings:
- def setUp(self): Sets up the needed objects used throughout the test.
- def testListOutputModules(self): Test the listing of output modules.
- def testProcessStorageWithMissingP... | Implement the Python class `PsortToolTest` described below.
Class description:
Tests for the psort tool.
Method signatures and docstrings:
- def setUp(self): Sets up the needed objects used throughout the test.
- def testListOutputModules(self): Test the listing of output modules.
- def testProcessStorageWithMissingP... | 923797fc00664fa9e3277781b0334d6eed5664fd | <|skeleton|>
class PsortToolTest:
"""Tests for the psort tool."""
def setUp(self):
"""Sets up the needed objects used throughout the test."""
<|body_0|>
def testListOutputModules(self):
"""Test the listing of output modules."""
<|body_1|>
def testProcessStorageWithMiss... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PsortToolTest:
"""Tests for the psort tool."""
def setUp(self):
"""Sets up the needed objects used throughout the test."""
self._input_reader = TestInputReader()
self._output_writer = cli_test_lib.TestOutputWriter(encoding=u'utf-8')
self._test_tool = psort.PsortTool(input_... | the_stack_v2_python_sparse | tools/psort_test.py | CNR-ITTIG/plasodfaxp | train | 1 |
61eb79f8a8f7217bffe45647f867fd594a6dd83e | [
"count = {n for n in nums if n > 0}\nif not count:\n return 1\nmax_n = max(count)\nfor i in range(1, max_n + 1):\n if i not in count:\n return i\nreturn i + 1",
"nums.sort()\ni, missing_positive = (0, 1)\nwhile i < len(nums) and nums[i] < 1:\n i += 1\nfor j in range(i, len(nums)):\n if nums[j] ... | <|body_start_0|>
count = {n for n in nums if n > 0}
if not count:
return 1
max_n = max(count)
for i in range(1, max_n + 1):
if i not in count:
return i
return i + 1
<|end_body_0|>
<|body_start_1|>
nums.sort()
i, missing_pos... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
"""Time complexity: O(N)"""
<|body_0|>
def firstMissingPositive_01(self, nums: List[int]) -> int:
"""Time complexity: O(NlogN)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
count = ... | stack_v2_sparse_classes_75kplus_train_074272 | 836 | no_license | [
{
"docstring": "Time complexity: O(N)",
"name": "firstMissingPositive",
"signature": "def firstMissingPositive(self, nums: List[int]) -> int"
},
{
"docstring": "Time complexity: O(NlogN)",
"name": "firstMissingPositive_01",
"signature": "def firstMissingPositive_01(self, nums: List[int])... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstMissingPositive(self, nums: List[int]) -> int: Time complexity: O(N)
- def firstMissingPositive_01(self, nums: List[int]) -> int: Time complexity: O(NlogN) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstMissingPositive(self, nums: List[int]) -> int: Time complexity: O(N)
- def firstMissingPositive_01(self, nums: List[int]) -> int: Time complexity: O(NlogN)
<|skeleton|>... | f1ff99a2d28a2b9fd690733bad9c723ed2f44079 | <|skeleton|>
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
"""Time complexity: O(N)"""
<|body_0|>
def firstMissingPositive_01(self, nums: List[int]) -> int:
"""Time complexity: O(NlogN)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
"""Time complexity: O(N)"""
count = {n for n in nums if n > 0}
if not count:
return 1
max_n = max(count)
for i in range(1, max_n + 1):
if i not in count:
return i
... | the_stack_v2_python_sparse | 0041_First_Missing_Positive/0041_First_Missing_Positive.py | pdkz/leetcode | train | 0 | |
1d7c46ce8d64b35ea3bb0f442f08dcd3f6fed32d | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | A set of methods for managing HTTP routers. | HttpRouterServiceServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HttpRouterServiceServicer:
"""A set of methods for managing HTTP routers."""
def Get(self, request, context):
"""Returns the specified HTTP router. To get the list of all available HTTP routers, make a [List] request."""
<|body_0|>
def List(self, request, context):
... | stack_v2_sparse_classes_75kplus_train_074273 | 12,714 | permissive | [
{
"docstring": "Returns the specified HTTP router. To get the list of all available HTTP routers, make a [List] request.",
"name": "Get",
"signature": "def Get(self, request, context)"
},
{
"docstring": "Lists HTTP routers in the specified folder.",
"name": "List",
"signature": "def List... | 6 | stack_v2_sparse_classes_30k_train_051964 | Implement the Python class `HttpRouterServiceServicer` described below.
Class description:
A set of methods for managing HTTP routers.
Method signatures and docstrings:
- def Get(self, request, context): Returns the specified HTTP router. To get the list of all available HTTP routers, make a [List] request.
- def Lis... | Implement the Python class `HttpRouterServiceServicer` described below.
Class description:
A set of methods for managing HTTP routers.
Method signatures and docstrings:
- def Get(self, request, context): Returns the specified HTTP router. To get the list of all available HTTP routers, make a [List] request.
- def Lis... | b906a014dd893e2697864e1e48e814a8d9fbc48c | <|skeleton|>
class HttpRouterServiceServicer:
"""A set of methods for managing HTTP routers."""
def Get(self, request, context):
"""Returns the specified HTTP router. To get the list of all available HTTP routers, make a [List] request."""
<|body_0|>
def List(self, request, context):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HttpRouterServiceServicer:
"""A set of methods for managing HTTP routers."""
def Get(self, request, context):
"""Returns the specified HTTP router. To get the list of all available HTTP routers, make a [List] request."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_... | the_stack_v2_python_sparse | yandex/cloud/apploadbalancer/v1/http_router_service_pb2_grpc.py | yandex-cloud/python-sdk | train | 63 |
f7b0ec0a660d0d36a338f682090f5fac90976436 | [
"self.style = style\nself.contents = contents\nself.dtype = dtype",
"d = dict()\nif len(self.style) > 0:\n d['style'] = self.style\nif len(self.contents) > 0:\n d['contents'] = self.contents\nif len(self.dtype) > 0:\n d['dtype'] = self.dtype\nreturn d"
] | <|body_start_0|>
self.style = style
self.contents = contents
self.dtype = dtype
<|end_body_0|>
<|body_start_1|>
d = dict()
if len(self.style) > 0:
d['style'] = self.style
if len(self.contents) > 0:
d['contents'] = self.contents
if len(self... | Node | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Node:
def __init__(self, style='', dtype='', contents=None):
"""初始化节点数据 :param style: 样式 :param dtype: 类型 :param contents: 内容列表"""
<|body_0|>
def to_dict(self):
"""返回 dict :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.style = style
... | stack_v2_sparse_classes_75kplus_train_074274 | 1,088 | no_license | [
{
"docstring": "初始化节点数据 :param style: 样式 :param dtype: 类型 :param contents: 内容列表",
"name": "__init__",
"signature": "def __init__(self, style='', dtype='', contents=None)"
},
{
"docstring": "返回 dict :return:",
"name": "to_dict",
"signature": "def to_dict(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006980 | Implement the Python class `Node` described below.
Class description:
Implement the Node class.
Method signatures and docstrings:
- def __init__(self, style='', dtype='', contents=None): 初始化节点数据 :param style: 样式 :param dtype: 类型 :param contents: 内容列表
- def to_dict(self): 返回 dict :return: | Implement the Python class `Node` described below.
Class description:
Implement the Node class.
Method signatures and docstrings:
- def __init__(self, style='', dtype='', contents=None): 初始化节点数据 :param style: 样式 :param dtype: 类型 :param contents: 内容列表
- def to_dict(self): 返回 dict :return:
<|skeleton|>
class Node:
... | a50c2e693c8a9c17050ec7dde74ac70e0d62be78 | <|skeleton|>
class Node:
def __init__(self, style='', dtype='', contents=None):
"""初始化节点数据 :param style: 样式 :param dtype: 类型 :param contents: 内容列表"""
<|body_0|>
def to_dict(self):
"""返回 dict :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Node:
def __init__(self, style='', dtype='', contents=None):
"""初始化节点数据 :param style: 样式 :param dtype: 类型 :param contents: 内容列表"""
self.style = style
self.contents = contents
self.dtype = dtype
def to_dict(self):
"""返回 dict :return:"""
d = dict()
if... | the_stack_v2_python_sparse | src/facestoryserver/json_objs.py | halfopen/facestory | train | 1 | |
6c502cd130cb43bc7936102eac919ef9acd6903a | [
"div_list = response.xpath('//div[@class=\"el\"]')[4:]\nfor div in div_list:\n item = JobItem()\n item['name'] = div.xpath('./p/span/a/text()').extract_first().strip()\n item['job_url'] = div.xpath('./p/span/a/@href').extract_first()\n item['company_name'] = div.xpath('./span[1]/a/text()').extract_first... | <|body_start_0|>
div_list = response.xpath('//div[@class="el"]')[4:]
for div in div_list:
item = JobItem()
item['name'] = div.xpath('./p/span/a/text()').extract_first().strip()
item['job_url'] = div.xpath('./p/span/a/@href').extract_first()
item['company_n... | A51jobSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class A51jobSpider:
def parse(self, response):
"""处理列表页数据 :param response: 下载器response对象==>中央引擎==>spider :return:"""
<|body_0|>
def parse_detail(self, response):
"""处理详情页信息 :param response: parse请求==>中央引擎==>下载器==>response对象 :return: item对象"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_75kplus_train_074275 | 2,876 | no_license | [
{
"docstring": "处理列表页数据 :param response: 下载器response对象==>中央引擎==>spider :return:",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "处理详情页信息 :param response: parse请求==>中央引擎==>下载器==>response对象 :return: item对象",
"name": "parse_detail",
"signature": "def parse_deta... | 2 | stack_v2_sparse_classes_30k_train_054381 | Implement the Python class `A51jobSpider` described below.
Class description:
Implement the A51jobSpider class.
Method signatures and docstrings:
- def parse(self, response): 处理列表页数据 :param response: 下载器response对象==>中央引擎==>spider :return:
- def parse_detail(self, response): 处理详情页信息 :param response: parse请求==>中央引擎==>下... | Implement the Python class `A51jobSpider` described below.
Class description:
Implement the A51jobSpider class.
Method signatures and docstrings:
- def parse(self, response): 处理列表页数据 :param response: 下载器response对象==>中央引擎==>spider :return:
- def parse_detail(self, response): 处理详情页信息 :param response: parse请求==>中央引擎==>下... | 2028638f43172ff2902aa571ad80a30f4cd9737f | <|skeleton|>
class A51jobSpider:
def parse(self, response):
"""处理列表页数据 :param response: 下载器response对象==>中央引擎==>spider :return:"""
<|body_0|>
def parse_detail(self, response):
"""处理详情页信息 :param response: parse请求==>中央引擎==>下载器==>response对象 :return: item对象"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class A51jobSpider:
def parse(self, response):
"""处理列表页数据 :param response: 下载器response对象==>中央引擎==>spider :return:"""
div_list = response.xpath('//div[@class="el"]')[4:]
for div in div_list:
item = JobItem()
item['name'] = div.xpath('./p/span/a/text()').extract_first()... | the_stack_v2_python_sparse | job/job/spiders/a51job.py | Pysuper/ScrapyProject | train | 0 | |
0f3df79cfd3f9e907a37378324754d340005be10 | [
"super().__init__(offset)\nif shadow_rgbFace is None:\n self._shadow_rgbFace = shadow_rgbFace\nelse:\n self._shadow_rgbFace = mcolors.to_rgba(shadow_rgbFace)\nif alpha is None:\n alpha = 0.3\nself._alpha = alpha\nself._rho = rho\nself._gc = kwargs",
"gc0 = renderer.new_gc()\ngc0.copy_properties(gc)\nif s... | <|body_start_0|>
super().__init__(offset)
if shadow_rgbFace is None:
self._shadow_rgbFace = shadow_rgbFace
else:
self._shadow_rgbFace = mcolors.to_rgba(shadow_rgbFace)
if alpha is None:
alpha = 0.3
self._alpha = alpha
self._rho = rho
... | A simple shadow via a filled patch. | SimplePatchShadow | [
"CC0-1.0",
"BSD-3-Clause",
"MIT",
"Bitstream-Charter",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-bakoma-fonts-1995",
"LicenseRef-scancode-unknown-license-reference",
"OFL-1.1",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimplePatchShadow:
"""A simple shadow via a filled patch."""
def __init__(self, offset=(2, -2), shadow_rgbFace=None, alpha=None, rho=0.3, **kwargs):
"""Parameters ---------- offset : (float, float), default: (2, -2) The (x, y) offset of the shadow in points. shadow_rgbFace : color Th... | stack_v2_sparse_classes_75kplus_train_074276 | 18,595 | permissive | [
{
"docstring": "Parameters ---------- offset : (float, float), default: (2, -2) The (x, y) offset of the shadow in points. shadow_rgbFace : color The shadow color. alpha : float, default: 0.3 The alpha transparency of the created shadow patch. rho : float, default: 0.3 A scale factor to apply to the rgbFace col... | 2 | stack_v2_sparse_classes_30k_train_003495 | Implement the Python class `SimplePatchShadow` described below.
Class description:
A simple shadow via a filled patch.
Method signatures and docstrings:
- def __init__(self, offset=(2, -2), shadow_rgbFace=None, alpha=None, rho=0.3, **kwargs): Parameters ---------- offset : (float, float), default: (2, -2) The (x, y) ... | Implement the Python class `SimplePatchShadow` described below.
Class description:
A simple shadow via a filled patch.
Method signatures and docstrings:
- def __init__(self, offset=(2, -2), shadow_rgbFace=None, alpha=None, rho=0.3, **kwargs): Parameters ---------- offset : (float, float), default: (2, -2) The (x, y) ... | f5042e35b945aded77b23470ead62d7eacefde92 | <|skeleton|>
class SimplePatchShadow:
"""A simple shadow via a filled patch."""
def __init__(self, offset=(2, -2), shadow_rgbFace=None, alpha=None, rho=0.3, **kwargs):
"""Parameters ---------- offset : (float, float), default: (2, -2) The (x, y) offset of the shadow in points. shadow_rgbFace : color Th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SimplePatchShadow:
"""A simple shadow via a filled patch."""
def __init__(self, offset=(2, -2), shadow_rgbFace=None, alpha=None, rho=0.3, **kwargs):
"""Parameters ---------- offset : (float, float), default: (2, -2) The (x, y) offset of the shadow in points. shadow_rgbFace : color The shadow colo... | the_stack_v2_python_sparse | contrib/python/matplotlib/py3/matplotlib/patheffects.py | catboost/catboost | train | 8,012 |
5987d5d0c7573332f1e817e46832a6e068fefb16 | [
"is_cpp = self._is_cpp(sources)\nswig_targets, new_sources = self._get_swig_targets(sources, is_cpp)\nif not swig_targets:\n return sources\nswig = self.swig or self.find_swig()\nswig_cmd = [swig, '-python']\nswig_cmd.extend(self.swig_opts)\nif is_cpp:\n swig_cmd.append('-c++')\nif not self.swig_opts:\n fo... | <|body_start_0|>
is_cpp = self._is_cpp(sources)
swig_targets, new_sources = self._get_swig_targets(sources, is_cpp)
if not swig_targets:
return sources
swig = self.swig or self.find_swig()
swig_cmd = [swig, '-python']
swig_cmd.extend(self.swig_opts)
if... | A swig-friendly build_ext extension (no pun intended). The differences of this class to build_ext in how swig files are processed are the following: - It adds a '-I' (include) swig option for each directory that contains a source file in the given Extension. - Determines whether to add the '-c++" option by checking the... | BuildExtension | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BuildExtension:
"""A swig-friendly build_ext extension (no pun intended). The differences of this class to build_ext in how swig files are processed are the following: - It adds a '-I' (include) swig option for each directory that contains a source file in the given Extension. - Determines whethe... | stack_v2_sparse_classes_75kplus_train_074277 | 7,236 | no_license | [
{
"docstring": "Walk the list of source files in 'sources', looking for SWIG interface (.i) files. Run SWIG on all that are found, and return a modified 'sources' list with SWIG source files replaced by the generated C (or C++) files.",
"name": "swig_sources",
"signature": "def swig_sources(self, source... | 4 | stack_v2_sparse_classes_30k_train_045820 | Implement the Python class `BuildExtension` described below.
Class description:
A swig-friendly build_ext extension (no pun intended). The differences of this class to build_ext in how swig files are processed are the following: - It adds a '-I' (include) swig option for each directory that contains a source file in t... | Implement the Python class `BuildExtension` described below.
Class description:
A swig-friendly build_ext extension (no pun intended). The differences of this class to build_ext in how swig files are processed are the following: - It adds a '-I' (include) swig option for each directory that contains a source file in t... | 7e597d06de055a634b4674d546334230c825db92 | <|skeleton|>
class BuildExtension:
"""A swig-friendly build_ext extension (no pun intended). The differences of this class to build_ext in how swig files are processed are the following: - It adds a '-I' (include) swig option for each directory that contains a source file in the given Extension. - Determines whethe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BuildExtension:
"""A swig-friendly build_ext extension (no pun intended). The differences of this class to build_ext in how swig files are processed are the following: - It adds a '-I' (include) swig option for each directory that contains a source file in the given Extension. - Determines whether to add the ... | the_stack_v2_python_sparse | pending/extradistutils.py | gpapadop79/gsakkis-utils | train | 0 |
0d0a318880f46604fe0e963a30334b6d1bd19cc0 | [
"self.client.force_authenticate(user=self.user)\nresponse = self.client.get(reverse('commerce:itemlist', kwargs={'version': 'v2'}))\nexpected = Item.objects.all()\nserialized = ItemSerializer(expected, many=True)\nself.assertEqual(response.json(), serialized.data)\nself.assertEqual(response.status_code, status.HTTP... | <|body_start_0|>
self.client.force_authenticate(user=self.user)
response = self.client.get(reverse('commerce:itemlist', kwargs={'version': 'v2'}))
expected = Item.objects.all()
serialized = ItemSerializer(expected, many=True)
self.assertEqual(response.json(), serialized.data)
... | GetItemsTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetItemsTest:
def test_get_all_items(self):
"""Test getting all items through api call"""
<|body_0|>
def test_get_avail_items(self):
"""Test getting all items through api call"""
<|body_1|>
def test_get_detail_item(self):
"""Test getting detail i... | stack_v2_sparse_classes_75kplus_train_074278 | 10,115 | no_license | [
{
"docstring": "Test getting all items through api call",
"name": "test_get_all_items",
"signature": "def test_get_all_items(self)"
},
{
"docstring": "Test getting all items through api call",
"name": "test_get_avail_items",
"signature": "def test_get_avail_items(self)"
},
{
"doc... | 3 | stack_v2_sparse_classes_30k_test_001324 | Implement the Python class `GetItemsTest` described below.
Class description:
Implement the GetItemsTest class.
Method signatures and docstrings:
- def test_get_all_items(self): Test getting all items through api call
- def test_get_avail_items(self): Test getting all items through api call
- def test_get_detail_item... | Implement the Python class `GetItemsTest` described below.
Class description:
Implement the GetItemsTest class.
Method signatures and docstrings:
- def test_get_all_items(self): Test getting all items through api call
- def test_get_avail_items(self): Test getting all items through api call
- def test_get_detail_item... | 82f372ecae245b1affc6f7eaa15a0785146e6ca5 | <|skeleton|>
class GetItemsTest:
def test_get_all_items(self):
"""Test getting all items through api call"""
<|body_0|>
def test_get_avail_items(self):
"""Test getting all items through api call"""
<|body_1|>
def test_get_detail_item(self):
"""Test getting detail i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GetItemsTest:
def test_get_all_items(self):
"""Test getting all items through api call"""
self.client.force_authenticate(user=self.user)
response = self.client.get(reverse('commerce:itemlist', kwargs={'version': 'v2'}))
expected = Item.objects.all()
serialized = ItemSer... | the_stack_v2_python_sparse | commerce/tests.py | Janujan/commerce-challenge | train | 0 | |
312d98cc9a1d211b5c6bccf390a19ca0c3251c49 | [
"existing_rows = self.select(table, columns)\nunique = diff(existing_rows, values, y_only=True)\nkeys = self.get_primary_key_vals(table)\npk_col = self.get_primary_key(table)\npk_index = columns.index(pk_col)\nto_insert, to_update = ([], [])\nfor index, row in enumerate(unique):\n if row[pk_index] not in keys:\n... | <|body_start_0|>
existing_rows = self.select(table, columns)
unique = diff(existing_rows, values, y_only=True)
keys = self.get_primary_key_vals(table)
pk_col = self.get_primary_key(table)
pk_index = columns.index(pk_col)
to_insert, to_update = ([], [])
for index, ... | Insert | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Insert:
def insert_uniques(self, table, columns, values):
"""Insert multiple rows into a table that do not already exist. If the rows primary key already exists, the rows values will be updated. If the rows primary key does not exists, a new row will be inserted"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_074279 | 3,676 | permissive | [
{
"docstring": "Insert multiple rows into a table that do not already exist. If the rows primary key already exists, the rows values will be updated. If the rows primary key does not exists, a new row will be inserted",
"name": "insert_uniques",
"signature": "def insert_uniques(self, table, columns, val... | 3 | stack_v2_sparse_classes_30k_train_029102 | Implement the Python class `Insert` described below.
Class description:
Implement the Insert class.
Method signatures and docstrings:
- def insert_uniques(self, table, columns, values): Insert multiple rows into a table that do not already exist. If the rows primary key already exists, the rows values will be updated... | Implement the Python class `Insert` described below.
Class description:
Implement the Insert class.
Method signatures and docstrings:
- def insert_uniques(self, table, columns, values): Insert multiple rows into a table that do not already exist. If the rows primary key already exists, the rows values will be updated... | 6964f718f4b72eb30f2259adfcfaf3090526c53d | <|skeleton|>
class Insert:
def insert_uniques(self, table, columns, values):
"""Insert multiple rows into a table that do not already exist. If the rows primary key already exists, the rows values will be updated. If the rows primary key does not exists, a new row will be inserted"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Insert:
def insert_uniques(self, table, columns, values):
"""Insert multiple rows into a table that do not already exist. If the rows primary key already exists, the rows values will be updated. If the rows primary key does not exists, a new row will be inserted"""
existing_rows = self.select(... | the_stack_v2_python_sparse | mysql/toolkit/components/manipulate/insert.py | sfneal/mysql-toolkit | train | 6 | |
3efc26ea028f06517a1396a6de6f98b8446bffc4 | [
"self.dp = defaultdict(list)\nfor i, v in enumerate(arr):\n self.dp[v].append(i)\nself.occur = sorted([(len(v), k) for k, v in self.dp.items()], reverse=True)",
"for o, v in self.occur:\n if o < threshold:\n break\n arr = self.dp[v]\n low = bisect.bisect_left(arr, left)\n high = bisect.bisec... | <|body_start_0|>
self.dp = defaultdict(list)
for i, v in enumerate(arr):
self.dp[v].append(i)
self.occur = sorted([(len(v), k) for k, v in self.dp.items()], reverse=True)
<|end_body_0|>
<|body_start_1|>
for o, v in self.occur:
if o < threshold:
br... | MajorityChecker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MajorityChecker:
def __init__(self, arr):
""":type arr: List[int]"""
<|body_0|>
def query(self, left, right, threshold):
""":type left: int :type right: int :type threshold: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.dp = d... | stack_v2_sparse_classes_75kplus_train_074280 | 3,072 | no_license | [
{
"docstring": ":type arr: List[int]",
"name": "__init__",
"signature": "def __init__(self, arr)"
},
{
"docstring": ":type left: int :type right: int :type threshold: int :rtype: int",
"name": "query",
"signature": "def query(self, left, right, threshold)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012021 | Implement the Python class `MajorityChecker` described below.
Class description:
Implement the MajorityChecker class.
Method signatures and docstrings:
- def __init__(self, arr): :type arr: List[int]
- def query(self, left, right, threshold): :type left: int :type right: int :type threshold: int :rtype: int | Implement the Python class `MajorityChecker` described below.
Class description:
Implement the MajorityChecker class.
Method signatures and docstrings:
- def __init__(self, arr): :type arr: List[int]
- def query(self, left, right, threshold): :type left: int :type right: int :type threshold: int :rtype: int
<|skelet... | 3d9e0ad2f6ed92ec969556f75d97c51ea4854719 | <|skeleton|>
class MajorityChecker:
def __init__(self, arr):
""":type arr: List[int]"""
<|body_0|>
def query(self, left, right, threshold):
""":type left: int :type right: int :type threshold: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MajorityChecker:
def __init__(self, arr):
""":type arr: List[int]"""
self.dp = defaultdict(list)
for i, v in enumerate(arr):
self.dp[v].append(i)
self.occur = sorted([(len(v), k) for k, v in self.dp.items()], reverse=True)
def query(self, left, right, threshold... | the_stack_v2_python_sparse | Solutions/1157_MajorityChecker.py | YoupengLi/leetcode-sorting | train | 3 | |
48f5a16e46e5257b01f8c844bc86e76002b3507d | [
"self.res = 0\nself.helper(root)\nreturn self.res",
"if not root:\n return 0\nl = self.helper(root.left)\nr = self.helper(root.right)\nself.res += abs(l - r)\nreturn l + r + root.val"
] | <|body_start_0|>
self.res = 0
self.helper(root)
return self.res
<|end_body_0|>
<|body_start_1|>
if not root:
return 0
l = self.helper(root.left)
r = self.helper(root.right)
self.res += abs(l - r)
return l + r + root.val
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findTilt(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def helper(self, root):
""":param root: :return: int 当前节点的子树和当前节点的和"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.res = 0
self.helper(root)
... | stack_v2_sparse_classes_75kplus_train_074281 | 1,163 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "findTilt",
"signature": "def findTilt(self, root)"
},
{
"docstring": ":param root: :return: int 当前节点的子树和当前节点的和",
"name": "helper",
"signature": "def helper(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_val_002576 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTilt(self, root): :type root: TreeNode :rtype: int
- def helper(self, root): :param root: :return: int 当前节点的子树和当前节点的和 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTilt(self, root): :type root: TreeNode :rtype: int
- def helper(self, root): :param root: :return: int 当前节点的子树和当前节点的和
<|skeleton|>
class Solution:
def findTilt(self... | beabfd31379f44ffd767fc676912db5022495b53 | <|skeleton|>
class Solution:
def findTilt(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def helper(self, root):
""":param root: :return: int 当前节点的子树和当前节点的和"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findTilt(self, root):
""":type root: TreeNode :rtype: int"""
self.res = 0
self.helper(root)
return self.res
def helper(self, root):
""":param root: :return: int 当前节点的子树和当前节点的和"""
if not root:
return 0
l = self.helper(root.l... | the_stack_v2_python_sparse | leetCode/tree/563findTilt.py | fatezy/Algorithm | train | 1 | |
afa6551874a35d8bb67c52be056ee051cd1f3597 | [
"self.__database = instance = db.Instance()\nself.__db = instance.db\nself.__users = {}",
"users = {}\nfor record in self.__users:\n uid = record['id']\n try:\n users[uid] = user.user()\n users[uid].load_user(user_id=uid)\n except Exception as e:\n return False\nreturn users",
"cur... | <|body_start_0|>
self.__database = instance = db.Instance()
self.__db = instance.db
self.__users = {}
<|end_body_0|>
<|body_start_1|>
users = {}
for record in self.__users:
uid = record['id']
try:
users[uid] = user.user()
u... | Provides abstraction of users, using the user class | users | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class users:
"""Provides abstraction of users, using the user class"""
def __init__(self):
"""Instantiates user object."""
<|body_0|>
def users(self):
""":returns: user objects in a list."""
<|body_1|>
def load_users(self):
"""Loads users into the ... | stack_v2_sparse_classes_75kplus_train_074282 | 1,092 | no_license | [
{
"docstring": "Instantiates user object.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":returns: user objects in a list.",
"name": "users",
"signature": "def users(self)"
},
{
"docstring": "Loads users into the class. :returns: True/False depending o... | 3 | null | Implement the Python class `users` described below.
Class description:
Provides abstraction of users, using the user class
Method signatures and docstrings:
- def __init__(self): Instantiates user object.
- def users(self): :returns: user objects in a list.
- def load_users(self): Loads users into the class. :returns... | Implement the Python class `users` described below.
Class description:
Provides abstraction of users, using the user class
Method signatures and docstrings:
- def __init__(self): Instantiates user object.
- def users(self): :returns: user objects in a list.
- def load_users(self): Loads users into the class. :returns... | dda1abb5c128cc2710da14b923faa45bd8711029 | <|skeleton|>
class users:
"""Provides abstraction of users, using the user class"""
def __init__(self):
"""Instantiates user object."""
<|body_0|>
def users(self):
""":returns: user objects in a list."""
<|body_1|>
def load_users(self):
"""Loads users into the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class users:
"""Provides abstraction of users, using the user class"""
def __init__(self):
"""Instantiates user object."""
self.__database = instance = db.Instance()
self.__db = instance.db
self.__users = {}
def users(self):
""":returns: user objects in a list."""
... | the_stack_v2_python_sparse | backend/app/libraries/users.py | crablab/dissertation | train | 1 |
699ec41faa8284ef87f6df49633700c65cf3f8f4 | [
"if search_opts is None:\n search_opts = {}\nqparams = {}\nfor opt, val in search_opts.iteritems():\n if val:\n qparams[opt] = val\nquery_string = '?%s' % urllib.urlencode(qparams) if qparams else ''\nret = self._list('/performance_metrics/get_list%s' % query_string, 'performance_metrics')\nreturn ret"... | <|body_start_0|>
if search_opts is None:
search_opts = {}
qparams = {}
for opt, val in search_opts.iteritems():
if val:
qparams[opt] = val
query_string = '?%s' % urllib.urlencode(qparams) if qparams else ''
ret = self._list('/performance_me... | Manage :class:`Server` resources. | PerformanceMetricsManager | [
"MIT",
"Apache-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PerformanceMetricsManager:
"""Manage :class:`Server` resources."""
def list(self, search_opts=None):
"""Get a list of ."""
<|body_0|>
def get_metrics(self, search_opts=None):
"""Get a list of metrics by metrics name and timestamp."""
<|body_1|>
def g... | stack_v2_sparse_classes_75kplus_train_074283 | 2,767 | permissive | [
{
"docstring": "Get a list of .",
"name": "list",
"signature": "def list(self, search_opts=None)"
},
{
"docstring": "Get a list of metrics by metrics name and timestamp.",
"name": "get_metrics",
"signature": "def get_metrics(self, search_opts=None)"
},
{
"docstring": "Get a list ... | 3 | null | Implement the Python class `PerformanceMetricsManager` described below.
Class description:
Manage :class:`Server` resources.
Method signatures and docstrings:
- def list(self, search_opts=None): Get a list of .
- def get_metrics(self, search_opts=None): Get a list of metrics by metrics name and timestamp.
- def get_m... | Implement the Python class `PerformanceMetricsManager` described below.
Class description:
Manage :class:`Server` resources.
Method signatures and docstrings:
- def list(self, search_opts=None): Get a list of .
- def get_metrics(self, search_opts=None): Get a list of metrics by metrics name and timestamp.
- def get_m... | 78125bfb4dd4d78ff96bc3274c8919003769c545 | <|skeleton|>
class PerformanceMetricsManager:
"""Manage :class:`Server` resources."""
def list(self, search_opts=None):
"""Get a list of ."""
<|body_0|>
def get_metrics(self, search_opts=None):
"""Get a list of metrics by metrics name and timestamp."""
<|body_1|>
def g... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PerformanceMetricsManager:
"""Manage :class:`Server` resources."""
def list(self, search_opts=None):
"""Get a list of ."""
if search_opts is None:
search_opts = {}
qparams = {}
for opt, val in search_opts.iteritems():
if val:
qparams... | the_stack_v2_python_sparse | source/python-vsmclient/vsmclient/v1/performance_metrics.py | ramkrsna/virtual-storage-manager | train | 0 |
a3999d45dfacb4f98bae684fd73a4d023c248d89 | [
"self.band_edge_energies = band_edge_energies\nself.orbital_character = orbital_character\nself.orbital_character_indices = orbital_character_indices\nself.participation_ratio = participation_ratio",
"band_edge_energies = mod_defaultdict(depth=3)\norbital_character = mod_defaultdict(depth=3)\norbital_character_in... | <|body_start_0|>
self.band_edge_energies = band_edge_energies
self.orbital_character = orbital_character
self.orbital_character_indices = orbital_character_indices
self.participation_ratio = participation_ratio
<|end_body_0|>
<|body_start_1|>
band_edge_energies = mod_defaultdict... | Class with DFT results for supercell systems. | ProcarDefectProperty | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProcarDefectProperty:
"""Class with DFT results for supercell systems."""
def __init__(self, band_edge_energies: dict, orbital_character: dict, orbital_character_indices: dict, participation_ratio: dict):
"""Args: band_edge_energies (dict): Averaged band energy over k-space as functi... | stack_v2_sparse_classes_75kplus_train_074284 | 20,839 | permissive | [
{
"docstring": "Args: band_edge_energies (dict): Averaged band energy over k-space as functions of spin and band_edge. orbital_character (dict): Orbital character at the eigenstate of each spin, band_edge (=\"hob\" or \"lub\"), and energy_position = (=\"top\" or \"bottom\") ex. {Spin.up: {\"hob\": {\"top\": {\"... | 2 | stack_v2_sparse_classes_30k_test_001087 | Implement the Python class `ProcarDefectProperty` described below.
Class description:
Class with DFT results for supercell systems.
Method signatures and docstrings:
- def __init__(self, band_edge_energies: dict, orbital_character: dict, orbital_character_indices: dict, participation_ratio: dict): Args: band_edge_ene... | Implement the Python class `ProcarDefectProperty` described below.
Class description:
Class with DFT results for supercell systems.
Method signatures and docstrings:
- def __init__(self, band_edge_energies: dict, orbital_character: dict, orbital_character_indices: dict, participation_ratio: dict): Args: band_edge_ene... | e909796c429e16982cefe549d16881039bce89e7 | <|skeleton|>
class ProcarDefectProperty:
"""Class with DFT results for supercell systems."""
def __init__(self, band_edge_energies: dict, orbital_character: dict, orbital_character_indices: dict, participation_ratio: dict):
"""Args: band_edge_energies (dict): Averaged band energy over k-space as functi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProcarDefectProperty:
"""Class with DFT results for supercell systems."""
def __init__(self, band_edge_energies: dict, orbital_character: dict, orbital_character_indices: dict, participation_ratio: dict):
"""Args: band_edge_energies (dict): Averaged band energy over k-space as functions of spin a... | the_stack_v2_python_sparse | pydefect/core/supercell_calc_results.py | obaica/pydefect | train | 0 |
896f12c4ebce5364058372856784e381ffcd1d59 | [
"nums.sort()\nans = [[]]\nlast = [[]]\nfor i, n in enumerate(nums):\n pickFrom = ans\n if i != 0 and nums[i - 1] == n:\n pickFrom = last\n last = [a + [n] for a in pickFrom]\n ans += last\nreturn ans",
"lst = [[]]\nnums = sorted(nums)\n\ndef func(nums):\n if nums is None:\n return\n ... | <|body_start_0|>
nums.sort()
ans = [[]]
last = [[]]
for i, n in enumerate(nums):
pickFrom = ans
if i != 0 and nums[i - 1] == n:
pickFrom = last
last = [a + [n] for a in pickFrom]
ans += last
return ans
<|end_body_0|>... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def subsetsWithDup(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def subsetsWithDup2(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
nums.sort()
... | stack_v2_sparse_classes_75kplus_train_074285 | 1,007 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "subsetsWithDup",
"signature": "def subsetsWithDup(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "subsetsWithDup2",
"signature": "def subsetsWithDup2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_035755 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subsetsWithDup(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def subsetsWithDup2(self, nums): :type nums: List[int] :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subsetsWithDup(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def subsetsWithDup2(self, nums): :type nums: List[int] :rtype: List[List[int]]
<|skeleton|>
class... | 93cbb01487a61e37159e8bdd4bf40f623e131c19 | <|skeleton|>
class Solution:
def subsetsWithDup(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def subsetsWithDup2(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def subsetsWithDup(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
nums.sort()
ans = [[]]
last = [[]]
for i, n in enumerate(nums):
pickFrom = ans
if i != 0 and nums[i - 1] == n:
pickFrom = last
... | the_stack_v2_python_sparse | Leetcode_medium/backtracking/90.py | HenryBalthier/Python-Learning | train | 0 | |
ae79bf3327ff9e665d8177d85461e20ef100b9ce | [
"self.last_day_num_job_errors = last_day_num_job_errors\nself.last_day_num_job_runs = last_day_num_job_runs\nself.last_day_num_job_sla_violations = last_day_num_job_sla_violations\nself.num_job_running = num_job_running\nself.objects_protected_by_policy = objects_protected_by_policy",
"if dictionary is None:\n ... | <|body_start_0|>
self.last_day_num_job_errors = last_day_num_job_errors
self.last_day_num_job_runs = last_day_num_job_runs
self.last_day_num_job_sla_violations = last_day_num_job_sla_violations
self.num_job_running = num_job_running
self.objects_protected_by_policy = objects_prot... | Implementation of the 'JobRunsTile' model. Jon Runs information. Attributes: last_day_num_job_errors (int): Number of Error runs in the last 24 hours. last_day_num_job_runs (int): Number of Job Runs in the last 24 hours. last_day_num_job_sla_violations (int): Number of SLA Violations in the last 24 hours. num_job_runni... | JobRunsTile | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JobRunsTile:
"""Implementation of the 'JobRunsTile' model. Jon Runs information. Attributes: last_day_num_job_errors (int): Number of Error runs in the last 24 hours. last_day_num_job_runs (int): Number of Job Runs in the last 24 hours. last_day_num_job_sla_violations (int): Number of SLA Violati... | stack_v2_sparse_classes_75kplus_train_074286 | 3,291 | permissive | [
{
"docstring": "Constructor for the JobRunsTile class",
"name": "__init__",
"signature": "def __init__(self, last_day_num_job_errors=None, last_day_num_job_runs=None, last_day_num_job_sla_violations=None, num_job_running=None, objects_protected_by_policy=None)"
},
{
"docstring": "Creates an inst... | 2 | stack_v2_sparse_classes_30k_train_021012 | Implement the Python class `JobRunsTile` described below.
Class description:
Implementation of the 'JobRunsTile' model. Jon Runs information. Attributes: last_day_num_job_errors (int): Number of Error runs in the last 24 hours. last_day_num_job_runs (int): Number of Job Runs in the last 24 hours. last_day_num_job_sla_... | Implement the Python class `JobRunsTile` described below.
Class description:
Implementation of the 'JobRunsTile' model. Jon Runs information. Attributes: last_day_num_job_errors (int): Number of Error runs in the last 24 hours. last_day_num_job_runs (int): Number of Job Runs in the last 24 hours. last_day_num_job_sla_... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class JobRunsTile:
"""Implementation of the 'JobRunsTile' model. Jon Runs information. Attributes: last_day_num_job_errors (int): Number of Error runs in the last 24 hours. last_day_num_job_runs (int): Number of Job Runs in the last 24 hours. last_day_num_job_sla_violations (int): Number of SLA Violati... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JobRunsTile:
"""Implementation of the 'JobRunsTile' model. Jon Runs information. Attributes: last_day_num_job_errors (int): Number of Error runs in the last 24 hours. last_day_num_job_runs (int): Number of Job Runs in the last 24 hours. last_day_num_job_sla_violations (int): Number of SLA Violations in the la... | the_stack_v2_python_sparse | cohesity_management_sdk/models/job_runs_tile.py | cohesity/management-sdk-python | train | 24 |
a13e0ff5812277bf2f1a504ebd3c8379b0d09933 | [
"c = Comment.get_by_id(int(comment_id), parent=blog_key())\nif not c:\n self.render('notfound.html')\n return\nuser_id = self.user.key().id()\nif c.user_id != user_id:\n self.redirect('/blog/%s' % str(c.key().id()))\ncontent = c.content\nself.render('editcomment.html', content=content, comment_id=comment_i... | <|body_start_0|>
c = Comment.get_by_id(int(comment_id), parent=blog_key())
if not c:
self.render('notfound.html')
return
user_id = self.user.key().id()
if c.user_id != user_id:
self.redirect('/blog/%s' % str(c.key().id()))
content = c.content
... | EditComment: New Comment Args: BlogHandler: Blog Handler | EditComment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EditComment:
"""EditComment: New Comment Args: BlogHandler: Blog Handler"""
def get(self, comment_id):
"""get: Get Args: self: This object comment_id: Comment ID"""
<|body_0|>
def post(self, comment_id):
"""post: Post Args: self: This object comment_id: Comment I... | stack_v2_sparse_classes_75kplus_train_074287 | 1,956 | no_license | [
{
"docstring": "get: Get Args: self: This object comment_id: Comment ID",
"name": "get",
"signature": "def get(self, comment_id)"
},
{
"docstring": "post: Post Args: self: This object comment_id: Comment ID",
"name": "post",
"signature": "def post(self, comment_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010993 | Implement the Python class `EditComment` described below.
Class description:
EditComment: New Comment Args: BlogHandler: Blog Handler
Method signatures and docstrings:
- def get(self, comment_id): get: Get Args: self: This object comment_id: Comment ID
- def post(self, comment_id): post: Post Args: self: This object ... | Implement the Python class `EditComment` described below.
Class description:
EditComment: New Comment Args: BlogHandler: Blog Handler
Method signatures and docstrings:
- def get(self, comment_id): get: Get Args: self: This object comment_id: Comment ID
- def post(self, comment_id): post: Post Args: self: This object ... | 936f7936b18984a5abf56661f9121f5fa4b124e4 | <|skeleton|>
class EditComment:
"""EditComment: New Comment Args: BlogHandler: Blog Handler"""
def get(self, comment_id):
"""get: Get Args: self: This object comment_id: Comment ID"""
<|body_0|>
def post(self, comment_id):
"""post: Post Args: self: This object comment_id: Comment I... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EditComment:
"""EditComment: New Comment Args: BlogHandler: Blog Handler"""
def get(self, comment_id):
"""get: Get Args: self: This object comment_id: Comment ID"""
c = Comment.get_by_id(int(comment_id), parent=blog_key())
if not c:
self.render('notfound.html')
... | the_stack_v2_python_sparse | handlers/EditComment.py | CandaceMcCall/fullstack-nanodegree-blog | train | 0 |
cbe7c34319d3eff8a66a121b292198ac9a4b4300 | [
"config = self.load_configuration(loadable)\nprint('\\n\\nTestbedLoader : \\n config = ', config, '\\n\\n')\ntestbed = Testbed(**config['testbed'])\nprint('\\n\\ntestbed = ', dir(testbed))\nif isinstance(loadable, str) and os.path.isfile(loadable):\n testbed.testbed_file = loadable\nfor name, device in config['d... | <|body_start_0|>
config = self.load_configuration(loadable)
print('\n\nTestbedLoader : \n config = ', config, '\n\n')
testbed = Testbed(**config['testbed'])
print('\n\ntestbed = ', dir(testbed))
if isinstance(loadable, str) and os.path.isfile(loadable):
testbed.testbe... | TestbedLoader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestbedLoader:
def load(self, loadable):
"""Load Function API to load a 'loadable' into corresponding physicalTestbed objects. This API is mainly responsible for creating physicalTestbed objects from the given loadable configuration, and it uses load_configuration API to do the actual lo... | stack_v2_sparse_classes_75kplus_train_074288 | 7,662 | no_license | [
{
"docstring": "Load Function API to load a 'loadable' into corresponding physicalTestbed objects. This API is mainly responsible for creating physicalTestbed objects from the given loadable configuration, and it uses load_configuration API to do the actual loading of the 'loadable' into dict format that it nee... | 4 | stack_v2_sparse_classes_30k_train_037363 | Implement the Python class `TestbedLoader` described below.
Class description:
Implement the TestbedLoader class.
Method signatures and docstrings:
- def load(self, loadable): Load Function API to load a 'loadable' into corresponding physicalTestbed objects. This API is mainly responsible for creating physicalTestbed... | Implement the Python class `TestbedLoader` described below.
Class description:
Implement the TestbedLoader class.
Method signatures and docstrings:
- def load(self, loadable): Load Function API to load a 'loadable' into corresponding physicalTestbed objects. This API is mainly responsible for creating physicalTestbed... | 22e3229d5a9a6e54cf405b011ee234a59530898e | <|skeleton|>
class TestbedLoader:
def load(self, loadable):
"""Load Function API to load a 'loadable' into corresponding physicalTestbed objects. This API is mainly responsible for creating physicalTestbed objects from the given loadable configuration, and it uses load_configuration API to do the actual lo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestbedLoader:
def load(self, loadable):
"""Load Function API to load a 'loadable' into corresponding physicalTestbed objects. This API is mainly responsible for creating physicalTestbed objects from the given loadable configuration, and it uses load_configuration API to do the actual loading of the '... | the_stack_v2_python_sparse | automation/networkSdk/TestbedLoader.py | mike03052000/test | train | 0 | |
62ba9181469bc68587bdf01abb40b86854fc38a4 | [
"rdd_rows = spark.sparkContext.parallelize([data])\nresult_df = DataWriter.df_from_rdd(rdd_rows, data, spark)\nresult_df.write.json(target_file, mode=write_mode)",
"if isinstance(rec, dict):\n return pst.StructType([pst.StructField(key, DataWriter.infer_schema(value), True) for key, value in sorted(rec.items()... | <|body_start_0|>
rdd_rows = spark.sparkContext.parallelize([data])
result_df = DataWriter.df_from_rdd(rdd_rows, data, spark)
result_df.write.json(target_file, mode=write_mode)
<|end_body_0|>
<|body_start_1|>
if isinstance(rec, dict):
return pst.StructType([pst.StructField(ke... | DataWriter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataWriter:
def write_dict_as_json(spark, data, target_file, write_mode=WriteMode.OVERWRITE):
"""TODO: 1) failing on dict with non-string keys TODO: 2) failing on list with elements of different data type"""
<|body_0|>
def infer_schema(rec):
"""infers dataframe schem... | stack_v2_sparse_classes_75kplus_train_074289 | 4,336 | no_license | [
{
"docstring": "TODO: 1) failing on dict with non-string keys TODO: 2) failing on list with elements of different data type",
"name": "write_dict_as_json",
"signature": "def write_dict_as_json(spark, data, target_file, write_mode=WriteMode.OVERWRITE)"
},
{
"docstring": "infers dataframe schema f... | 4 | stack_v2_sparse_classes_30k_train_016341 | Implement the Python class `DataWriter` described below.
Class description:
Implement the DataWriter class.
Method signatures and docstrings:
- def write_dict_as_json(spark, data, target_file, write_mode=WriteMode.OVERWRITE): TODO: 1) failing on dict with non-string keys TODO: 2) failing on list with elements of diff... | Implement the Python class `DataWriter` described below.
Class description:
Implement the DataWriter class.
Method signatures and docstrings:
- def write_dict_as_json(spark, data, target_file, write_mode=WriteMode.OVERWRITE): TODO: 1) failing on dict with non-string keys TODO: 2) failing on list with elements of diff... | 7d5d2faafcd0b2e5d35fa0e486bc3617f8e30a9e | <|skeleton|>
class DataWriter:
def write_dict_as_json(spark, data, target_file, write_mode=WriteMode.OVERWRITE):
"""TODO: 1) failing on dict with non-string keys TODO: 2) failing on list with elements of different data type"""
<|body_0|>
def infer_schema(rec):
"""infers dataframe schem... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataWriter:
def write_dict_as_json(spark, data, target_file, write_mode=WriteMode.OVERWRITE):
"""TODO: 1) failing on dict with non-string keys TODO: 2) failing on list with elements of different data type"""
rdd_rows = spark.sparkContext.parallelize([data])
result_df = DataWriter.df_fr... | the_stack_v2_python_sparse | bi/common/datawriter.py | Srinidhi-SA/mAdvisorProdML | train | 0 | |
a83ebed9ac39daf371891b224a7732d928ba1285 | [
"super().__init__(name, parent, hyperparameter_config, spatial_scale)\nself.setup_children()\npass",
"with tf.variable_scope(self.name.replace(' ', '_')):\n for computation in self.children:\n computation.build(mode, outputs)\noutputs[self] = self.children[-1]\npass",
"n_children = self.hyperparam('n_... | <|body_start_0|>
super().__init__(name, parent, hyperparameter_config, spatial_scale)
self.setup_children()
pass
<|end_body_0|>
<|body_start_1|>
with tf.variable_scope(self.name.replace(' ', '_')):
for computation in self.children:
computation.build(mode, out... | A ScaleGene which builds a sequence of convolution operations into a computation graph. Hyperparameters: n_comps (int): Number of computation Genes descending from this ConvBlockGene. TODO Attributes: | ConvBlockGene | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvBlockGene:
"""A ScaleGene which builds a sequence of convolution operations into a computation graph. Hyperparameters: n_comps (int): Number of computation Genes descending from this ConvBlockGene. TODO Attributes:"""
def __init__(self, name: str, parent: Optional[ScaleGene]=None, hyperp... | stack_v2_sparse_classes_75kplus_train_074290 | 4,221 | no_license | [
{
"docstring": "Constructor. Args: name (str): ConvolutionGene name. parent (ScaleGene): Parent Gene. hyperparameter_config (Optional[mt.HyperparameterConfig]): The HyperparameterConfig governing this Gene's hyperparameters. If none is supplied, inherit from parent. spatial_scale (Optional[int]): The spatial sc... | 4 | null | Implement the Python class `ConvBlockGene` described below.
Class description:
A ScaleGene which builds a sequence of convolution operations into a computation graph. Hyperparameters: n_comps (int): Number of computation Genes descending from this ConvBlockGene. TODO Attributes:
Method signatures and docstrings:
- de... | Implement the Python class `ConvBlockGene` described below.
Class description:
A ScaleGene which builds a sequence of convolution operations into a computation graph. Hyperparameters: n_comps (int): Number of computation Genes descending from this ConvBlockGene. TODO Attributes:
Method signatures and docstrings:
- de... | 6b78dc5e1e793a206ae3f4860d3a9ac887e663e5 | <|skeleton|>
class ConvBlockGene:
"""A ScaleGene which builds a sequence of convolution operations into a computation graph. Hyperparameters: n_comps (int): Number of computation Genes descending from this ConvBlockGene. TODO Attributes:"""
def __init__(self, name: str, parent: Optional[ScaleGene]=None, hyperp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConvBlockGene:
"""A ScaleGene which builds a sequence of convolution operations into a computation graph. Hyperparameters: n_comps (int): Number of computation Genes descending from this ConvBlockGene. TODO Attributes:"""
def __init__(self, name: str, parent: Optional[ScaleGene]=None, hyperparameter_conf... | the_stack_v2_python_sparse | example2/src/_private/genenet/genes/ConvBlockGene.py | leapmanlab/examples | train | 1 |
2a9a4deeab5579d9601b3a48b2eac76bdb755c90 | [
"super().__init__(dev_id, register_node, seq, sleep_time)\nself.dev_id = dev_id\nself.seq = seq\nself.battery_level = BATTERY_FULL\nself.duty_cycle = DUTY_CYCLE\nself.is_mobile = False\nself.net_config = BANDIT_ARMS\nself.duty_cycle_refresh = LoRa.get_future_time()\nself.duty_cycle_na = 0\nself.pre_shared_key = PRE... | <|body_start_0|>
super().__init__(dev_id, register_node, seq, sleep_time)
self.dev_id = dev_id
self.seq = seq
self.battery_level = BATTERY_FULL
self.duty_cycle = DUTY_CYCLE
self.is_mobile = False
self.net_config = BANDIT_ARMS
self.duty_cycle_refresh = LoRa... | BanditNode | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BanditNode:
def __init__(self, dev_id, algorithm='ucb', register_node=True, seq=1, sleep_time=SLEEP_TIME):
"""Bandit node constructor :param dev_id: string, end node id :param algorithm: string, name of algorithm, ucb :param register_node: boolean, set if node should itself register firs... | stack_v2_sparse_classes_75kplus_train_074291 | 3,412 | no_license | [
{
"docstring": "Bandit node constructor :param dev_id: string, end node id :param algorithm: string, name of algorithm, ucb :param register_node: boolean, set if node should itself register first :param seq: int, default sequence number value",
"name": "__init__",
"signature": "def __init__(self, dev_id... | 4 | null | Implement the Python class `BanditNode` described below.
Class description:
Implement the BanditNode class.
Method signatures and docstrings:
- def __init__(self, dev_id, algorithm='ucb', register_node=True, seq=1, sleep_time=SLEEP_TIME): Bandit node constructor :param dev_id: string, end node id :param algorithm: st... | Implement the Python class `BanditNode` described below.
Class description:
Implement the BanditNode class.
Method signatures and docstrings:
- def __init__(self, dev_id, algorithm='ucb', register_node=True, seq=1, sleep_time=SLEEP_TIME): Bandit node constructor :param dev_id: string, end node id :param algorithm: st... | bcf36f11f09acd59456919b6597cae0adb12ea3b | <|skeleton|>
class BanditNode:
def __init__(self, dev_id, algorithm='ucb', register_node=True, seq=1, sleep_time=SLEEP_TIME):
"""Bandit node constructor :param dev_id: string, end node id :param algorithm: string, name of algorithm, ucb :param register_node: boolean, set if node should itself register firs... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BanditNode:
def __init__(self, dev_id, algorithm='ucb', register_node=True, seq=1, sleep_time=SLEEP_TIME):
"""Bandit node constructor :param dev_id: string, end node id :param algorithm: string, name of algorithm, ucb :param register_node: boolean, set if node should itself register first :param seq: ... | the_stack_v2_python_sparse | src/bandit_node.py | alexandervalach/lora-ap-sim | train | 0 | |
3612751d0777021428b30a1ecf2ea91b5e529837 | [
"mocked.return_value = expected\ngithub_org_client = GithubOrgClient(org)\nself.assertEqual(github_org_client.org, expected)\nmocked.assert_called_once()",
"github_org_client = GithubOrgClient(org)\nexpected_url = 'https://api.github.com/orgs/{}/repos'.format(org)\nexpected = {'repos_url': expected_url}\nprop = '... | <|body_start_0|>
mocked.return_value = expected
github_org_client = GithubOrgClient(org)
self.assertEqual(github_org_client.org, expected)
mocked.assert_called_once()
<|end_body_0|>
<|body_start_1|>
github_org_client = GithubOrgClient(org)
expected_url = 'https://api.git... | test for the GithubOrgClient class | TestGithubOrgClient | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestGithubOrgClient:
"""test for the GithubOrgClient class"""
def test_org(self, org, expected, mocked):
"""test the GithubOrgClient.org method"""
<|body_0|>
def test_public_repos_url(self, org):
"""test the GithubOrgClient._public_repos_url method"""
<|b... | stack_v2_sparse_classes_75kplus_train_074292 | 4,084 | no_license | [
{
"docstring": "test the GithubOrgClient.org method",
"name": "test_org",
"signature": "def test_org(self, org, expected, mocked)"
},
{
"docstring": "test the GithubOrgClient._public_repos_url method",
"name": "test_public_repos_url",
"signature": "def test_public_repos_url(self, org)"
... | 4 | null | Implement the Python class `TestGithubOrgClient` described below.
Class description:
test for the GithubOrgClient class
Method signatures and docstrings:
- def test_org(self, org, expected, mocked): test the GithubOrgClient.org method
- def test_public_repos_url(self, org): test the GithubOrgClient._public_repos_url ... | Implement the Python class `TestGithubOrgClient` described below.
Class description:
test for the GithubOrgClient class
Method signatures and docstrings:
- def test_org(self, org, expected, mocked): test the GithubOrgClient.org method
- def test_public_repos_url(self, org): test the GithubOrgClient._public_repos_url ... | a09732a4f270d3dbeaf6ff1eb46c7bc0b71eaf4a | <|skeleton|>
class TestGithubOrgClient:
"""test for the GithubOrgClient class"""
def test_org(self, org, expected, mocked):
"""test the GithubOrgClient.org method"""
<|body_0|>
def test_public_repos_url(self, org):
"""test the GithubOrgClient._public_repos_url method"""
<|b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestGithubOrgClient:
"""test for the GithubOrgClient class"""
def test_org(self, org, expected, mocked):
"""test the GithubOrgClient.org method"""
mocked.return_value = expected
github_org_client = GithubOrgClient(org)
self.assertEqual(github_org_client.org, expected)
... | the_stack_v2_python_sparse | 0x09-Unittests_and_integration_tests/test_client.py | I7RANK/holbertonschool-web_back_end | train | 0 |
e42625ac0960935cec54e84c21f462fce2db99e4 | [
"def isValidSudoku(board, row, col, c):\n for i in range(9):\n if board[row][i] != '.' and board[row][i] == c:\n return False\n if board[i][col] != '.' and board[i][col] == c:\n return False\n if board[3 * (row // 3) + i // 3][3 * (col // 3) + i % 3] != '.' and board[3 ... | <|body_start_0|>
def isValidSudoku(board, row, col, c):
for i in range(9):
if board[row][i] != '.' and board[row][i] == c:
return False
if board[i][col] != '.' and board[i][col] == c:
return False
if board[3 * (r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def solveSudoku(self, board: List[List[str]]) -> None:
"""Do not return anything, modify board in-place instead."""
<|body_0|>
def solveSudoku2(self, board: List[List[str]]) -> None:
"""Do not return anything, modify board in-place instead."""
<|bod... | stack_v2_sparse_classes_75kplus_train_074293 | 2,509 | no_license | [
{
"docstring": "Do not return anything, modify board in-place instead.",
"name": "solveSudoku",
"signature": "def solveSudoku(self, board: List[List[str]]) -> None"
},
{
"docstring": "Do not return anything, modify board in-place instead.",
"name": "solveSudoku2",
"signature": "def solve... | 2 | stack_v2_sparse_classes_30k_train_048655 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def solveSudoku(self, board: List[List[str]]) -> None: Do not return anything, modify board in-place instead.
- def solveSudoku2(self, board: List[List[str]]) -> None: Do not ret... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def solveSudoku(self, board: List[List[str]]) -> None: Do not return anything, modify board in-place instead.
- def solveSudoku2(self, board: List[List[str]]) -> None: Do not ret... | 55bdff871f3a03a7a742727406809bfa3e6e1034 | <|skeleton|>
class Solution:
def solveSudoku(self, board: List[List[str]]) -> None:
"""Do not return anything, modify board in-place instead."""
<|body_0|>
def solveSudoku2(self, board: List[List[str]]) -> None:
"""Do not return anything, modify board in-place instead."""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def solveSudoku(self, board: List[List[str]]) -> None:
"""Do not return anything, modify board in-place instead."""
def isValidSudoku(board, row, col, c):
for i in range(9):
if board[row][i] != '.' and board[row][i] == c:
return False
... | the_stack_v2_python_sparse | Week_07/solveSudoku.py | Persist-GY/algorithm008-class02 | train | 0 | |
01413a68f64accadfb50f2155df616f682308907 | [
"unit = unit.rstrip('IiBb')\nblock_size = 1\nfor item in MemorySize.UNITS:\n if item == unit:\n break\n else:\n block_size <<= 10\nsize = long(size) * float(block_size)\nunit = 0\nwhile size > 1024.0 and unit < len(MemorySize.UNITS) - 1:\n size /= 1024.0\n unit += 1\nif unit > 0:\n retu... | <|body_start_0|>
unit = unit.rstrip('IiBb')
block_size = 1
for item in MemorySize.UNITS:
if item == unit:
break
else:
block_size <<= 10
size = long(size) * float(block_size)
unit = 0
while size > 1024.0 and unit < le... | Parse and convert size with optional prefix from and to numbers. | MemorySize | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MemorySize:
"""Parse and convert size with optional prefix from and to numbers."""
def num2str(size, unit='B'):
"""Pretty-print number to string consisting of size and optional prefix. >>> MemorySize.num2str(512) '512 B' >>> MemorySize.num2str(512, unit='MB') '512.0 MB'"""
<|... | stack_v2_sparse_classes_75kplus_train_074294 | 5,101 | no_license | [
{
"docstring": "Pretty-print number to string consisting of size and optional prefix. >>> MemorySize.num2str(512) '512 B' >>> MemorySize.num2str(512, unit='MB') '512.0 MB'",
"name": "num2str",
"signature": "def num2str(size, unit='B')"
},
{
"docstring": "Parse string consisting of size and prefi... | 3 | null | Implement the Python class `MemorySize` described below.
Class description:
Parse and convert size with optional prefix from and to numbers.
Method signatures and docstrings:
- def num2str(size, unit='B'): Pretty-print number to string consisting of size and optional prefix. >>> MemorySize.num2str(512) '512 B' >>> Me... | Implement the Python class `MemorySize` described below.
Class description:
Parse and convert size with optional prefix from and to numbers.
Method signatures and docstrings:
- def num2str(size, unit='B'): Pretty-print number to string consisting of size and optional prefix. >>> MemorySize.num2str(512) '512 B' >>> Me... | 1a6765deafd8679079b64dcc35f91933d37cf2dd | <|skeleton|>
class MemorySize:
"""Parse and convert size with optional prefix from and to numbers."""
def num2str(size, unit='B'):
"""Pretty-print number to string consisting of size and optional prefix. >>> MemorySize.num2str(512) '512 B' >>> MemorySize.num2str(512, unit='MB') '512.0 MB'"""
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MemorySize:
"""Parse and convert size with optional prefix from and to numbers."""
def num2str(size, unit='B'):
"""Pretty-print number to string consisting of size and optional prefix. >>> MemorySize.num2str(512) '512 B' >>> MemorySize.num2str(512, unit='MB') '512.0 MB'"""
unit = unit.rst... | the_stack_v2_python_sparse | ucs/virtualization/univention-virtual-machine-manager-daemon/umc/python/uvmm/tools.py | m-narayan/smart | train | 8 |
b221bdfc6076c89845c73d36b8bbc78e055507c9 | [
"self.state = 0\nself.pinA = pinA\nself.pinB = pinB\nself.rotary_callback = rotary_callback\nself.pin_state = 0\nself.button_timer = 0\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\nGPIO.setup(self.pinA, GPIO.IN, pull_up_down=GPIO.PUD_UP)\nGPIO.setup(self.pinB, GPIO.IN, pull_up_down=GPIO.PUD_UP)\nGPIO.add_event_... | <|body_start_0|>
self.state = 0
self.pinA = pinA
self.pinB = pinB
self.rotary_callback = rotary_callback
self.pin_state = 0
self.button_timer = 0
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(self.pinA, GPIO.IN, pull_up_down=GPIO.PUD_UP... | Rotary Encoder outputting 2 bit grey code. Some encoders have a pushbutton and LED too, these are processed separate classes, although physically they are in the same device they have individual functions. Methods: - rotary_event: uses threaded callback to read the GPIO pins on the rotary encoder. calls back a function... | RotaryEncoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RotaryEncoder:
"""Rotary Encoder outputting 2 bit grey code. Some encoders have a pushbutton and LED too, these are processed separate classes, although physically they are in the same device they have individual functions. Methods: - rotary_event: uses threaded callback to read the GPIO pins on ... | stack_v2_sparse_classes_75kplus_train_074295 | 40,088 | no_license | [
{
"docstring": ":param pinA: Rotary encoder GPIO pin channel a :type pinA: int :param pinB: Rotary encoder GPIO pin channel b :type pinB: int :param rotary_callback: Method that processes the encoder output :type rotary_callback: Method",
"name": "__init__",
"signature": "def __init__(self, pinA, pinB, ... | 2 | stack_v2_sparse_classes_30k_train_006839 | Implement the Python class `RotaryEncoder` described below.
Class description:
Rotary Encoder outputting 2 bit grey code. Some encoders have a pushbutton and LED too, these are processed separate classes, although physically they are in the same device they have individual functions. Methods: - rotary_event: uses thre... | Implement the Python class `RotaryEncoder` described below.
Class description:
Rotary Encoder outputting 2 bit grey code. Some encoders have a pushbutton and LED too, these are processed separate classes, although physically they are in the same device they have individual functions. Methods: - rotary_event: uses thre... | 622cc666019753c4736c03be0d41308212c84291 | <|skeleton|>
class RotaryEncoder:
"""Rotary Encoder outputting 2 bit grey code. Some encoders have a pushbutton and LED too, these are processed separate classes, although physically they are in the same device they have individual functions. Methods: - rotary_event: uses threaded callback to read the GPIO pins on ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RotaryEncoder:
"""Rotary Encoder outputting 2 bit grey code. Some encoders have a pushbutton and LED too, these are processed separate classes, although physically they are in the same device they have individual functions. Methods: - rotary_event: uses threaded callback to read the GPIO pins on the rotary en... | the_stack_v2_python_sparse | SonosHW.py | gshorten/SonosController | train | 5 |
1d95b498ad1913f8d572069c19897f27759c00b6 | [
"player_string = '{} {}'.format(self.user.first_name, self.user.last_name)\nif self.player_pronouns:\n player_string = '{} ({})'.format(player_string, self.player_pronouns)\nreturn player_string",
"try:\n return self.character_set.get(active_flag=True)\nexcept ObjectDoesNotExist:\n self.staff_attention_f... | <|body_start_0|>
player_string = '{} {}'.format(self.user.first_name, self.user.last_name)
if self.player_pronouns:
player_string = '{} ({})'.format(player_string, self.player_pronouns)
return player_string
<|end_body_0|>
<|body_start_1|>
try:
return self.charact... | Player of a game. An individual who is playing a game. All users are players of some sort. If you are adding a new field here (e.g., pronouns), it also needs to be added to the registration view. | Player | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Player:
"""Player of a game. An individual who is playing a game. All users are players of some sort. If you are adding a new field here (e.g., pronouns), it also needs to be added to the registration view."""
def __str__(self):
"""General display of model."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_074296 | 17,120 | no_license | [
{
"docstring": "General display of model.",
"name": "__str__",
"signature": "def __str__(self)"
},
{
"docstring": "The active character of the Player. Gets the active character from the list of characters associated with this player. TODO: if there is more than one character returned here, it sh... | 3 | stack_v2_sparse_classes_30k_train_032768 | Implement the Python class `Player` described below.
Class description:
Player of a game. An individual who is playing a game. All users are players of some sort. If you are adding a new field here (e.g., pronouns), it also needs to be added to the registration view.
Method signatures and docstrings:
- def __str__(se... | Implement the Python class `Player` described below.
Class description:
Player of a game. An individual who is playing a game. All users are players of some sort. If you are adding a new field here (e.g., pronouns), it also needs to be added to the registration view.
Method signatures and docstrings:
- def __str__(se... | 3810bcee128cd5caaea092c5135d80570e2ca734 | <|skeleton|>
class Player:
"""Player of a game. An individual who is playing a game. All users are players of some sort. If you are adding a new field here (e.g., pronouns), it also needs to be added to the registration view."""
def __str__(self):
"""General display of model."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Player:
"""Player of a game. An individual who is playing a game. All users are players of some sort. If you are adding a new field here (e.g., pronouns), it also needs to be added to the registration view."""
def __str__(self):
"""General display of model."""
player_string = '{} {}'.form... | the_stack_v2_python_sparse | talesofvalor/players/models.py | CodeCrow/talesofvalor_python | train | 4 |
3ae9d380af6393c891e8f2ec5c363742781c4bc4 | [
"if not reinit and PiMonBot.bot is not None:\n return\nPiMonBot.bot = telegram.Bot(token=PiMonBot.BOT_TOKEN)",
"if msg is None or len(str(msg)) == 0:\n return\nmsg = str(msg)\nif PiMonBot.bot is None:\n PiMonBot.init()\nPiMonBot.bot.sendMessage(parse_mode='html', chat_id=PiMonBot.CHANNEL_ID, text=msg)"
] | <|body_start_0|>
if not reinit and PiMonBot.bot is not None:
return
PiMonBot.bot = telegram.Bot(token=PiMonBot.BOT_TOKEN)
<|end_body_0|>
<|body_start_1|>
if msg is None or len(str(msg)) == 0:
return
msg = str(msg)
if PiMonBot.bot is None:
PiMo... | Uses Telegram bot service recognized by the BOT TOKEN to post alerts to a channel identified by the CHANNEL ID. To crete and obtain your BOT TOKEN, contact BotFather at https://web.telegram.org/#/im?p=@BotFather To obtain your channel id, simply create a channel and add the bot. Open your channel in Telegram web and fo... | PiMonBot | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PiMonBot:
"""Uses Telegram bot service recognized by the BOT TOKEN to post alerts to a channel identified by the CHANNEL ID. To crete and obtain your BOT TOKEN, contact BotFather at https://web.telegram.org/#/im?p=@BotFather To obtain your channel id, simply create a channel and add the bot. Open... | stack_v2_sparse_classes_75kplus_train_074297 | 2,059 | permissive | [
{
"docstring": "Initialize the telegram bot with credentials. Once created it can only be overridden with a True reinit Args: reinit (bool, optional): Set to True to force reinitialize the bot instance. Defaults to False.",
"name": "init",
"signature": "def init(reinit=False)"
},
{
"docstring": ... | 2 | stack_v2_sparse_classes_30k_train_018140 | Implement the Python class `PiMonBot` described below.
Class description:
Uses Telegram bot service recognized by the BOT TOKEN to post alerts to a channel identified by the CHANNEL ID. To crete and obtain your BOT TOKEN, contact BotFather at https://web.telegram.org/#/im?p=@BotFather To obtain your channel id, simply... | Implement the Python class `PiMonBot` described below.
Class description:
Uses Telegram bot service recognized by the BOT TOKEN to post alerts to a channel identified by the CHANNEL ID. To crete and obtain your BOT TOKEN, contact BotFather at https://web.telegram.org/#/im?p=@BotFather To obtain your channel id, simply... | 2ac0b3dbfe15ae05b40090d37c56f5ed8a1e7952 | <|skeleton|>
class PiMonBot:
"""Uses Telegram bot service recognized by the BOT TOKEN to post alerts to a channel identified by the CHANNEL ID. To crete and obtain your BOT TOKEN, contact BotFather at https://web.telegram.org/#/im?p=@BotFather To obtain your channel id, simply create a channel and add the bot. Open... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PiMonBot:
"""Uses Telegram bot service recognized by the BOT TOKEN to post alerts to a channel identified by the CHANNEL ID. To crete and obtain your BOT TOKEN, contact BotFather at https://web.telegram.org/#/im?p=@BotFather To obtain your channel id, simply create a channel and add the bot. Open your channel... | the_stack_v2_python_sparse | modules/comms/TelegramRelay.py | jaiwardhan/raspimon | train | 0 |
25c39a8d81df3a130f9113c6ca909b5bccb1d7f1 | [
"super().__init__(**kwargs)\nself.level_shift_detector = ExternalDetector(detector=LevelShiftAD(c=10.0, side='both', window=5))\nself.persisent_detector = ExternalDetector(detector=PersistAD(c=10.0, side='positive'))\nself.bump_detector = GaussianAnomalyDetector()",
"anomalies = {}\ntry:\n shifts = self.level_... | <|body_start_0|>
super().__init__(**kwargs)
self.level_shift_detector = ExternalDetector(detector=LevelShiftAD(c=10.0, side='both', window=5))
self.persisent_detector = ExternalDetector(detector=PersistAD(c=10.0, side='positive'))
self.bump_detector = GaussianAnomalyDetector()
<|end_body... | EnsambleDetector | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnsambleDetector:
def __init__(self, **kwargs):
"""Ensamble detector for anomaly detection, uses part of ADTK library and a custom Gaussian Slider."""
<|body_0|>
def detect(self, data: pd.Series) -> dict:
"""Detects anomalies in the data Args: data (pd.Series): Data ... | stack_v2_sparse_classes_75kplus_train_074298 | 6,286 | no_license | [
{
"docstring": "Ensamble detector for anomaly detection, uses part of ADTK library and a custom Gaussian Slider.",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Detects anomalies in the data Args: data (pd.Series): Data to detect anomalies. Must contain index... | 3 | stack_v2_sparse_classes_30k_train_026174 | Implement the Python class `EnsambleDetector` described below.
Class description:
Implement the EnsambleDetector class.
Method signatures and docstrings:
- def __init__(self, **kwargs): Ensamble detector for anomaly detection, uses part of ADTK library and a custom Gaussian Slider.
- def detect(self, data: pd.Series)... | Implement the Python class `EnsambleDetector` described below.
Class description:
Implement the EnsambleDetector class.
Method signatures and docstrings:
- def __init__(self, **kwargs): Ensamble detector for anomaly detection, uses part of ADTK library and a custom Gaussian Slider.
- def detect(self, data: pd.Series)... | 160e4976ab854cc255bde06f0ce014fbc224c23d | <|skeleton|>
class EnsambleDetector:
def __init__(self, **kwargs):
"""Ensamble detector for anomaly detection, uses part of ADTK library and a custom Gaussian Slider."""
<|body_0|>
def detect(self, data: pd.Series) -> dict:
"""Detects anomalies in the data Args: data (pd.Series): Data ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EnsambleDetector:
def __init__(self, **kwargs):
"""Ensamble detector for anomaly detection, uses part of ADTK library and a custom Gaussian Slider."""
super().__init__(**kwargs)
self.level_shift_detector = ExternalDetector(detector=LevelShiftAD(c=10.0, side='both', window=5))
s... | the_stack_v2_python_sparse | AnomalySearches/plt-anomaly-detector/src/model/detectors.py | cmsplt/PLTOffline | train | 2 | |
a7aa6c0124bb908d0690314e3613596f802bd61a | [
"Calibration.__init__(self, ecal_train, hcal_train, true_train, lim)\nif weights == 'gaussian':\n self.weights = lambda x: np.exp(-x ** 2 / sigma ** 2 / 2)\nelse:\n self.weights = weights\nself.n_neighbors_ecal_eq_0 = n_neighbors_ecal_eq_0\nself.n_neighbors_ecal_neq_0 = n_neighbors_ecal_neq_0\nself.algorithm ... | <|body_start_0|>
Calibration.__init__(self, ecal_train, hcal_train, true_train, lim)
if weights == 'gaussian':
self.weights = lambda x: np.exp(-x ** 2 / sigma ** 2 / 2)
else:
self.weights = weights
self.n_neighbors_ecal_eq_0 = n_neighbors_ecal_eq_0
self.n_... | Inherit from Calibration. Class to calibrate the true energy of a particle thanks to training datas. We use the a k neareast neighbours method. We do the pondered mean of the true energies of k neareast neighbours. Attributs --------- ecal_train : array ecal value to train the calibration hcal_train : array ecal value ... | KNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KNN:
"""Inherit from Calibration. Class to calibrate the true energy of a particle thanks to training datas. We use the a k neareast neighbours method. We do the pondered mean of the true energies of k neareast neighbours. Attributs --------- ecal_train : array ecal value to train the calibration... | stack_v2_sparse_classes_75kplus_train_074299 | 8,091 | no_license | [
{
"docstring": "Parameters ---------- ecal_train : array-like ecal value to train the calibration hcal_train : array-like hcal value to train the calibration true_train : array-like true value to train the calibration n_neighbors_ecal_eq_0: int Number of neighbors to use by default for k_neighbors queries. for ... | 4 | stack_v2_sparse_classes_30k_train_021241 | Implement the Python class `KNN` described below.
Class description:
Inherit from Calibration. Class to calibrate the true energy of a particle thanks to training datas. We use the a k neareast neighbours method. We do the pondered mean of the true energies of k neareast neighbours. Attributs --------- ecal_train : ar... | Implement the Python class `KNN` described below.
Class description:
Inherit from Calibration. Class to calibrate the true energy of a particle thanks to training datas. We use the a k neareast neighbours method. We do the pondered mean of the true energies of k neareast neighbours. Attributs --------- ecal_train : ar... | 53dbbd2e68986602c29008338d6c9cc96edc6d77 | <|skeleton|>
class KNN:
"""Inherit from Calibration. Class to calibrate the true energy of a particle thanks to training datas. We use the a k neareast neighbours method. We do the pondered mean of the true energies of k neareast neighbours. Attributs --------- ecal_train : array ecal value to train the calibration... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KNN:
"""Inherit from Calibration. Class to calibrate the true energy of a particle thanks to training datas. We use the a k neareast neighbours method. We do the pondered mean of the true energies of k neareast neighbours. Attributs --------- ecal_train : array ecal value to train the calibration hcal_train :... | the_stack_v2_python_sparse | pfcalibration/KNN.py | sniang/particle_flow_calibration | train | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.