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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
49cd1b6edf0010b4ffc8969d19b8e4b1b7b03496 | [
"self.classname = classname\nself.method = method\nself.args = args\nself.kwargs = kwargs",
"msg = _('Invalid call to method %(m)s() in a object of class %(c)r.') + ' ' + _('(probably not overridden?).') % {'m': self.method, 'c': self.classname}\nmsg += ' ' + _('Given positional arguments: %r.') % self.args\nmsg ... | <|body_start_0|>
self.classname = classname
self.method = method
self.args = args
self.kwargs = kwargs
<|end_body_0|>
<|body_start_1|>
msg = _('Invalid call to method %(m)s() in a object of class %(c)r.') + ' ' + _('(probably not overridden?).') % {'m': self.method, 'c': self.cl... | Error class indicating, that a uncallable method was called. | CallAbstractMethodError | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CallAbstractMethodError:
"""Error class indicating, that a uncallable method was called."""
def __init__(self, classname, method, *args, **kwargs):
"""Constructor."""
<|body_0|>
def __str__(self):
"""Typecasting into a string for error output."""
<|body_1... | stack_v2_sparse_classes_75kplus_train_007400 | 6,661 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, classname, method, *args, **kwargs)"
},
{
"docstring": "Typecasting into a string for error output.",
"name": "__str__",
"signature": "def __str__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_039338 | Implement the Python class `CallAbstractMethodError` described below.
Class description:
Error class indicating, that a uncallable method was called.
Method signatures and docstrings:
- def __init__(self, classname, method, *args, **kwargs): Constructor.
- def __str__(self): Typecasting into a string for error output... | Implement the Python class `CallAbstractMethodError` described below.
Class description:
Error class indicating, that a uncallable method was called.
Method signatures and docstrings:
- def __init__(self, classname, method, *args, **kwargs): Constructor.
- def __str__(self): Typecasting into a string for error output... | 9412e749d1ead346315e6a4164daad591d88711e | <|skeleton|>
class CallAbstractMethodError:
"""Error class indicating, that a uncallable method was called."""
def __init__(self, classname, method, *args, **kwargs):
"""Constructor."""
<|body_0|>
def __str__(self):
"""Typecasting into a string for error output."""
<|body_1... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CallAbstractMethodError:
"""Error class indicating, that a uncallable method was called."""
def __init__(self, classname, method, *args, **kwargs):
"""Constructor."""
self.classname = classname
self.method = method
self.args = args
self.kwargs = kwargs
def __s... | the_stack_v2_python_sparse | pb_base/errors.py | fbrehm/py_pb_base | train | 0 |
fbd39967815ccac87f48331adc11ed4bbc4ac4bc | [
"if root is None:\n return ''\ns = ''\nQ = [root]\nwhile Q:\n current = Q.pop(0)\n if current is not None:\n s += str(current.val) + ','\n if current.left:\n Q.append(current.left)\n else:\n Q.append(None)\n if current.right:\n Q.append(current.r... | <|body_start_0|>
if root is None:
return ''
s = ''
Q = [root]
while Q:
current = Q.pop(0)
if current is not None:
s += str(current.val) + ','
if current.left:
Q.append(current.left)
el... | 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_007401 | 1,896 | 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_024684 | 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:... | 0297c25492edb597c2c5210c83a2410df907ec90 | <|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 root is None:
return ''
s = ''
Q = [root]
while Q:
current = Q.pop(0)
if current is not None:
s += str(curr... | the_stack_v2_python_sparse | serialize-and-deserialize-binary-tree.py | dianaevergreen/1337code | train | 0 | |
4bd755dbe64727a3e7170fad882bb4305026cbd1 | [
"inf = float('inf')\nn = len(jobDifficulty)\n\n@lru_cache(None)\ndef dp(start, days, diff):\n if start == n:\n if days == 0:\n return diff\n else:\n return inf\n if days == 0:\n return inf\n ans = inf\n mi = 0\n for i in range(start, n - days + 1):\n ... | <|body_start_0|>
inf = float('inf')
n = len(jobDifficulty)
@lru_cache(None)
def dp(start, days, diff):
if start == n:
if days == 0:
return diff
else:
return inf
if days == 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minDifficulty(self, jobDifficulty, d):
""":type jobDifficulty: List[int] :type d: int :rtype: int"""
<|body_0|>
def minDifficulty2(self, jobDifficulty, d):
""":type jobDifficulty: List[int] :type d: int :rtype: int"""
<|body_1|>
def minDiff... | stack_v2_sparse_classes_75kplus_train_007402 | 6,592 | no_license | [
{
"docstring": ":type jobDifficulty: List[int] :type d: int :rtype: int",
"name": "minDifficulty",
"signature": "def minDifficulty(self, jobDifficulty, d)"
},
{
"docstring": ":type jobDifficulty: List[int] :type d: int :rtype: int",
"name": "minDifficulty2",
"signature": "def minDifficul... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDifficulty(self, jobDifficulty, d): :type jobDifficulty: List[int] :type d: int :rtype: int
- def minDifficulty2(self, jobDifficulty, d): :type jobDifficulty: List[int] :t... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDifficulty(self, jobDifficulty, d): :type jobDifficulty: List[int] :type d: int :rtype: int
- def minDifficulty2(self, jobDifficulty, d): :type jobDifficulty: List[int] :t... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def minDifficulty(self, jobDifficulty, d):
""":type jobDifficulty: List[int] :type d: int :rtype: int"""
<|body_0|>
def minDifficulty2(self, jobDifficulty, d):
""":type jobDifficulty: List[int] :type d: int :rtype: int"""
<|body_1|>
def minDiff... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minDifficulty(self, jobDifficulty, d):
""":type jobDifficulty: List[int] :type d: int :rtype: int"""
inf = float('inf')
n = len(jobDifficulty)
@lru_cache(None)
def dp(start, days, diff):
if start == n:
if days == 0:
... | the_stack_v2_python_sparse | M/MinimumDifficultyofaJobSchedule.py | bssrdf/pyleet | train | 2 | |
c1f5dd37c08ef2b1899b7ad945e1b3107fd1b566 | [
"sprite.Sprite.__init__(self)\nself.xvel = 0\nself.yvel = 0\nself.image = Surface((SIZE, SIZE))\nself.image.fill(Color(BACK_COLOR))\nself.rect = Rect(x, y, SIZE, SIZE)\nself.image.set_colorkey(Color(BACK_COLOR))\nself.current_dir = 'left'\nself.speed = speed",
"if self.current_dir == 'left':\n self.rect.x -= s... | <|body_start_0|>
sprite.Sprite.__init__(self)
self.xvel = 0
self.yvel = 0
self.image = Surface((SIZE, SIZE))
self.image.fill(Color(BACK_COLOR))
self.rect = Rect(x, y, SIZE, SIZE)
self.image.set_colorkey(Color(BACK_COLOR))
self.current_dir = 'left'
... | Entity | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Entity:
def __init__(self, x, y, speed=2):
"""Инициализирует сущность"""
<|body_0|>
def update_move(self):
"""Изменяет текущие координаты сущности"""
<|body_1|>
def move_in_exits(self, exits):
"""Отвечает за перемещение сущности через туннели по ... | stack_v2_sparse_classes_75kplus_train_007403 | 1,309 | no_license | [
{
"docstring": "Инициализирует сущность",
"name": "__init__",
"signature": "def __init__(self, x, y, speed=2)"
},
{
"docstring": "Изменяет текущие координаты сущности",
"name": "update_move",
"signature": "def update_move(self)"
},
{
"docstring": "Отвечает за перемещение сущности... | 3 | stack_v2_sparse_classes_30k_train_034123 | Implement the Python class `Entity` described below.
Class description:
Implement the Entity class.
Method signatures and docstrings:
- def __init__(self, x, y, speed=2): Инициализирует сущность
- def update_move(self): Изменяет текущие координаты сущности
- def move_in_exits(self, exits): Отвечает за перемещение сущ... | Implement the Python class `Entity` described below.
Class description:
Implement the Entity class.
Method signatures and docstrings:
- def __init__(self, x, y, speed=2): Инициализирует сущность
- def update_move(self): Изменяет текущие координаты сущности
- def move_in_exits(self, exits): Отвечает за перемещение сущ... | adb51eb219c6758dc553671ddc68db700a6df358 | <|skeleton|>
class Entity:
def __init__(self, x, y, speed=2):
"""Инициализирует сущность"""
<|body_0|>
def update_move(self):
"""Изменяет текущие координаты сущности"""
<|body_1|>
def move_in_exits(self, exits):
"""Отвечает за перемещение сущности через туннели по ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Entity:
def __init__(self, x, y, speed=2):
"""Инициализирует сущность"""
sprite.Sprite.__init__(self)
self.xvel = 0
self.yvel = 0
self.image = Surface((SIZE, SIZE))
self.image.fill(Color(BACK_COLOR))
self.rect = Rect(x, y, SIZE, SIZE)
self.image.... | the_stack_v2_python_sparse | entity.py | antista/pacman | train | 0 | |
5506856d790b0315ee9a2092553d08dae7830412 | [
"self._generator = generator\nself._pageSize = pageSize\nif otherOptions is None:\n otherOptions = []\nself._otherOptions = otherOptions\nself._preMessage = preMessage\nself._postMessage = postMessage\nself._emptyMessage = emptyMessage\nself._displayedItems = []\nself._displayedItemStrings = []\nself._exhaustedI... | <|body_start_0|>
self._generator = generator
self._pageSize = pageSize
if otherOptions is None:
otherOptions = []
self._otherOptions = otherOptions
self._preMessage = preMessage
self._postMessage = postMessage
self._emptyMessage = emptyMessage
... | A menu that displays a few options at a time with a "See more" option Gets options using a given generator | TerminalGeneratorMenu | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TerminalGeneratorMenu:
"""A menu that displays a few options at a time with a "See more" option Gets options using a given generator"""
def __init__(self, generator, pageSize=5, otherOptions=None, preMessage=None, postMessage=None, emptyMessage='Nothing to display'):
"""Arguments: ge... | stack_v2_sparse_classes_75kplus_train_007404 | 7,322 | no_license | [
{
"docstring": "Arguments: generator -- the generator to get the options from pageSize -- the number of items to show per page otherOptions -- any options to show below the options from the generator preMessage -- the message to show above the menu postMessage -- the message to show below the menu emptyMessage ... | 5 | stack_v2_sparse_classes_30k_val_001986 | Implement the Python class `TerminalGeneratorMenu` described below.
Class description:
A menu that displays a few options at a time with a "See more" option Gets options using a given generator
Method signatures and docstrings:
- def __init__(self, generator, pageSize=5, otherOptions=None, preMessage=None, postMessag... | Implement the Python class `TerminalGeneratorMenu` described below.
Class description:
A menu that displays a few options at a time with a "See more" option Gets options using a given generator
Method signatures and docstrings:
- def __init__(self, generator, pageSize=5, otherOptions=None, preMessage=None, postMessag... | 46b7e084234227f925a24ea2eb41ed5d9ac14b7a | <|skeleton|>
class TerminalGeneratorMenu:
"""A menu that displays a few options at a time with a "See more" option Gets options using a given generator"""
def __init__(self, generator, pageSize=5, otherOptions=None, preMessage=None, postMessage=None, emptyMessage='Nothing to display'):
"""Arguments: ge... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TerminalGeneratorMenu:
"""A menu that displays a few options at a time with a "See more" option Gets options using a given generator"""
def __init__(self, generator, pageSize=5, otherOptions=None, preMessage=None, postMessage=None, emptyMessage='Nothing to display'):
"""Arguments: generator -- th... | the_stack_v2_python_sparse | Source/TerminalMenu.py | csahmad/291-Mini-Project-1 | train | 0 |
2f443d393bfbfc2543406081dc4881350f7ff9df | [
"self.dic['__format'] = '.pltp'\nself.dic['__rel_path'] = self.path_parsed_file\nself.dic['__comment'] = ''\nself.dic['__pl'] = list()\nself.dic['__extends'] = list()\nsha1 = hashlib.sha1()\nsha1.update((self.directory.name + ':' + self.path).encode('utf-8'))\nself.dic['__sha1'] = sha1.hexdigest()",
"try:\n di... | <|body_start_0|>
self.dic['__format'] = '.pltp'
self.dic['__rel_path'] = self.path_parsed_file
self.dic['__comment'] = ''
self.dic['__pl'] = list()
self.dic['__extends'] = list()
sha1 = hashlib.sha1()
sha1.update((self.directory.name + ':' + self.path).encode('utf... | Parser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Parser:
def fill_meta(self):
"""Append meta informations to self.dic. Meta informations should starts with two underscores"""
<|body_0|>
def pl_file_line_match(self, match, line):
"""Appends file, line and lineno to self.dic['__pl'] so that it can be later processed ... | stack_v2_sparse_classes_75kplus_train_007405 | 3,340 | no_license | [
{
"docstring": "Append meta informations to self.dic. Meta informations should starts with two underscores",
"name": "fill_meta",
"signature": "def fill_meta(self)"
},
{
"docstring": "Appends file, line and lineno to self.dic['__pl'] so that it can be later processed by loader.loader. Raise load... | 3 | stack_v2_sparse_classes_30k_train_020443 | Implement the Python class `Parser` described below.
Class description:
Implement the Parser class.
Method signatures and docstrings:
- def fill_meta(self): Append meta informations to self.dic. Meta informations should starts with two underscores
- def pl_file_line_match(self, match, line): Appends file, line and li... | Implement the Python class `Parser` described below.
Class description:
Implement the Parser class.
Method signatures and docstrings:
- def fill_meta(self): Append meta informations to self.dic. Meta informations should starts with two underscores
- def pl_file_line_match(self, match, line): Appends file, line and li... | 25d64c33649b6cbb450b67fa89d8d8e9434fb59c | <|skeleton|>
class Parser:
def fill_meta(self):
"""Append meta informations to self.dic. Meta informations should starts with two underscores"""
<|body_0|>
def pl_file_line_match(self, match, line):
"""Appends file, line and lineno to self.dic['__pl'] so that it can be later processed ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Parser:
def fill_meta(self):
"""Append meta informations to self.dic. Meta informations should starts with two underscores"""
self.dic['__format'] = '.pltp'
self.dic['__rel_path'] = self.path_parsed_file
self.dic['__comment'] = ''
self.dic['__pl'] = list()
self.... | the_stack_v2_python_sparse | server/serverpl/loader/parsers/pltp.py | ddoyen/premierlangage | train | 0 | |
95bdddaa349f6253ffe1627b309acf40c541ccae | [
"rw_in = FileReaderWriter('./data.txt')\nd = rw_in.getData()\nvalues = list(map(float, d.values()))\nprint('es_mco_communicator SONO QUI values =')\nprint(values)\nvalue_names = [p.name for p in model.parameters]\nvalue_types = [p.type for p in model.parameters]\nreturn [DataValue(type=type_, name=name, value=value... | <|body_start_0|>
rw_in = FileReaderWriter('./data.txt')
d = rw_in.getData()
values = list(map(float, d.values()))
print('es_mco_communicator SONO QUI values =')
print(values)
value_names = [p.name for p in model.parameters]
value_types = [p.type for p in model.par... | The communicator is responsible for handing the communication protocol between the MCO executable (for example, the dakota executable) and the single point evaluation (our BDSS in --evaluate mode). This MCO communicator assumes that the communication happens via stdin and stdout, which is what dakota does when invoking... | ESMCOCommunicator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ESMCOCommunicator:
"""The communicator is responsible for handing the communication protocol between the MCO executable (for example, the dakota executable) and the single point evaluation (our BDSS in --evaluate mode). This MCO communicator assumes that the communication happens via stdin and st... | stack_v2_sparse_classes_75kplus_train_007406 | 3,671 | permissive | [
{
"docstring": "Receives data from the MCO (e.g. dakota) by reading from standard input the sequence of numbers that are this execution's parameter values. You can use fancier communication systems here if your MCO supports them.",
"name": "receive_from_mco",
"signature": "def receive_from_mco(self, mod... | 2 | null | Implement the Python class `ESMCOCommunicator` described below.
Class description:
The communicator is responsible for handing the communication protocol between the MCO executable (for example, the dakota executable) and the single point evaluation (our BDSS in --evaluate mode). This MCO communicator assumes that the... | Implement the Python class `ESMCOCommunicator` described below.
Class description:
The communicator is responsible for handing the communication protocol between the MCO executable (for example, the dakota executable) and the single point evaluation (our BDSS in --evaluate mode). This MCO communicator assumes that the... | f22c0ad3cc45c3b5a7f9c4fd0b20549d7dfc9aeb | <|skeleton|>
class ESMCOCommunicator:
"""The communicator is responsible for handing the communication protocol between the MCO executable (for example, the dakota executable) and the single point evaluation (our BDSS in --evaluate mode). This MCO communicator assumes that the communication happens via stdin and st... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ESMCOCommunicator:
"""The communicator is responsible for handing the communication protocol between the MCO executable (for example, the dakota executable) and the single point evaluation (our BDSS in --evaluate mode). This MCO communicator assumes that the communication happens via stdin and stdout, which i... | the_stack_v2_python_sparse | es_example/es_mco/es_mco_communicator.py | force-h2020/force-bdss-plugin-enginsoft-toy-model | train | 0 |
4bc2a3733d72773c0d277a4556936701454a7b53 | [
"if x == 1 or x == 0:\n return x\nleft = 1\nright = x\nmid = 1\nwhile left <= right:\n mid = left + (right - left) / 2\n if mid * mid > x:\n right = mid - 1\n else:\n left = mid + 1\nreturn right",
"if x == 1 or x == 0:\n return x\nleft = 1\nright = x\nmid = 1\nwhile left <= right:\n ... | <|body_start_0|>
if x == 1 or x == 0:
return x
left = 1
right = x
mid = 1
while left <= right:
mid = left + (right - left) / 2
if mid * mid > x:
right = mid - 1
else:
left = mid + 1
return rig... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mySqrt(self, x):
"""实现思路 二分查找 :param x: :return:"""
<|body_0|>
def mySqrt2(self, x):
"""实现思路 牛顿迭代法 :param x: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if x == 1 or x == 0:
return x
left = 1
ri... | stack_v2_sparse_classes_75kplus_train_007407 | 1,062 | no_license | [
{
"docstring": "实现思路 二分查找 :param x: :return:",
"name": "mySqrt",
"signature": "def mySqrt(self, x)"
},
{
"docstring": "实现思路 牛顿迭代法 :param x: :return:",
"name": "mySqrt2",
"signature": "def mySqrt2(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_025986 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mySqrt(self, x): 实现思路 二分查找 :param x: :return:
- def mySqrt2(self, x): 实现思路 牛顿迭代法 :param x: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mySqrt(self, x): 实现思路 二分查找 :param x: :return:
- def mySqrt2(self, x): 实现思路 牛顿迭代法 :param x: :return:
<|skeleton|>
class Solution:
def mySqrt(self, x):
"""实现思路 二分... | 47d5eaef3cf1adccaf42eb463a5c4548e003cb59 | <|skeleton|>
class Solution:
def mySqrt(self, x):
"""实现思路 二分查找 :param x: :return:"""
<|body_0|>
def mySqrt2(self, x):
"""实现思路 牛顿迭代法 :param x: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def mySqrt(self, x):
"""实现思路 二分查找 :param x: :return:"""
if x == 1 or x == 0:
return x
left = 1
right = x
mid = 1
while left <= right:
mid = left + (right - left) / 2
if mid * mid > x:
right = mid - 1
... | the_stack_v2_python_sparse | Week_04/69. x 的平方根.py | wffeige/algorithm015 | train | 0 | |
41efaea121c101d08b8825130f1e6d76ef31b521 | [
"if not document_id and (not project_id):\n self.endpoint = 'documents.json'\nelif not document_id and project_id:\n self.endpoint = 'projects/{0}/documents.json'.format(project_id)\nelif document_id and project_id:\n self.endpoint = 'projects/{0}/documents/{1}.json'.format(project_id, document_id)\nelse:\... | <|body_start_0|>
if not document_id and (not project_id):
self.endpoint = 'documents.json'
elif not document_id and project_id:
self.endpoint = 'projects/{0}/documents.json'.format(project_id)
elif document_id and project_id:
self.endpoint = 'projects/{0}/docu... | Actions on a document | Document | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Document:
"""Actions on a document"""
def fetch(self, document_id=None, project_id=None):
"""Get a specific document, or a list of documents, either by project, or all documents a user has access to in the basecamp account. :param document_id: integer of document :param project_id: i... | stack_v2_sparse_classes_75kplus_train_007408 | 6,292 | no_license | [
{
"docstring": "Get a specific document, or a list of documents, either by project, or all documents a user has access to in the basecamp account. :param document_id: integer of document :param project_id: integer of project :rtype dictionary: Dictionary of documents, or a single document. .. note:: There are t... | 4 | null | Implement the Python class `Document` described below.
Class description:
Actions on a document
Method signatures and docstrings:
- def fetch(self, document_id=None, project_id=None): Get a specific document, or a list of documents, either by project, or all documents a user has access to in the basecamp account. :pa... | Implement the Python class `Document` described below.
Class description:
Actions on a document
Method signatures and docstrings:
- def fetch(self, document_id=None, project_id=None): Get a specific document, or a list of documents, either by project, or all documents a user has access to in the basecamp account. :pa... | 26f4e3b9099a9c40bc699f0e72fd8d63173401ee | <|skeleton|>
class Document:
"""Actions on a document"""
def fetch(self, document_id=None, project_id=None):
"""Get a specific document, or a list of documents, either by project, or all documents a user has access to in the basecamp account. :param document_id: integer of document :param project_id: i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Document:
"""Actions on a document"""
def fetch(self, document_id=None, project_id=None):
"""Get a specific document, or a list of documents, either by project, or all documents a user has access to in the basecamp account. :param document_id: integer of document :param project_id: integer of pro... | the_stack_v2_python_sparse | basecamp/documents.py | boulderdave/py-basecamp | train | 0 |
cb1dac24687c0cc80d38c7429401bbc2a8731423 | [
"self._abbreviation_expansions_dict = abbreviation_expansions_dict\nif abbreviation_expansions_dict is not None:\n self._atomic_tokens_provided = True\n abbreviations = sorted(abbreviation_expansions_dict.keys(), key=len, reverse=True)\n expansions_containing_abbrev = sorted(self._get_expansions_containing... | <|body_start_0|>
self._abbreviation_expansions_dict = abbreviation_expansions_dict
if abbreviation_expansions_dict is not None:
self._atomic_tokens_provided = True
abbreviations = sorted(abbreviation_expansions_dict.keys(), key=len, reverse=True)
expansions_containing... | A class for tokenizing text with abbreviations and expansions. This class can be provided with an abbreviation expansions dictionary at initialization, which will be used to enforce that certain strings remain as atomic tokens after tokenization, which aids alignment. Note: Tokenizing and detokenizing is not lossless. ... | Tokenizer | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tokenizer:
"""A class for tokenizing text with abbreviations and expansions. This class can be provided with an abbreviation expansions dictionary at initialization, which will be used to enforce that certain strings remain as atomic tokens after tokenization, which aids alignment. Note: Tokenizi... | stack_v2_sparse_classes_75kplus_train_007409 | 8,781 | permissive | [
{
"docstring": "Initializes the Tokenizer. Args: abbreviation_expansions_dict: An optional dictionary mapping known abbreviations to their valid expansions. This is used to ensure that abbreviations are never broken up into separate tokens, and that expansions containing their own abbreviations are also kept as... | 5 | stack_v2_sparse_classes_30k_train_039577 | Implement the Python class `Tokenizer` described below.
Class description:
A class for tokenizing text with abbreviations and expansions. This class can be provided with an abbreviation expansions dictionary at initialization, which will be used to enforce that certain strings remain as atomic tokens after tokenizatio... | Implement the Python class `Tokenizer` described below.
Class description:
A class for tokenizing text with abbreviations and expansions. This class can be provided with an abbreviation expansions dictionary at initialization, which will be used to enforce that certain strings remain as atomic tokens after tokenizatio... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class Tokenizer:
"""A class for tokenizing text with abbreviations and expansions. This class can be provided with an abbreviation expansions dictionary at initialization, which will be used to enforce that certain strings remain as atomic tokens after tokenization, which aids alignment. Note: Tokenizi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Tokenizer:
"""A class for tokenizing text with abbreviations and expansions. This class can be provided with an abbreviation expansions dictionary at initialization, which will be used to enforce that certain strings remain as atomic tokens after tokenization, which aids alignment. Note: Tokenizing and detoke... | the_stack_v2_python_sparse | deciphering_clinical_abbreviations/tokenizer.py | Jimmy-INL/google-research | train | 1 |
d9adbdd34690f68ae968a5b462ef9fa420f53c4d | [
"super().__init__()\nself.idx = 0\nself.msg_chars = MSG_CHARS_MOON\nself.msg_ready = MSG_READY_MOON",
"if not self.showing:\n return\nchars = self.msg_chars\nmod = len(chars)\nself.idx = (self.idx + 1) % mod\nBaseProgressStatus.set_status(BaseProgressStatus.FULL_MASK.format(progress=chars[self.idx], msg=messag... | <|body_start_0|>
super().__init__()
self.idx = 0
self.msg_chars = MSG_CHARS_MOON
self.msg_ready = MSG_READY_MOON
<|end_body_0|>
<|body_start_1|>
if not self.showing:
return
chars = self.msg_chars
mod = len(chars)
self.idx = (self.idx + 1) % mo... | Progress status that shows phases of the moon. | MoonProgressStatus | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MoonProgressStatus:
"""Progress status that shows phases of the moon."""
def __init__(self):
"""Init moon progress status."""
<|body_0|>
def update_progress(self, message):
"""Show next moon phase and a custom message."""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_75kplus_train_007410 | 3,576 | permissive | [
{
"docstring": "Init moon progress status.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Show next moon phase and a custom message.",
"name": "update_progress",
"signature": "def update_progress(self, message)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003748 | Implement the Python class `MoonProgressStatus` described below.
Class description:
Progress status that shows phases of the moon.
Method signatures and docstrings:
- def __init__(self): Init moon progress status.
- def update_progress(self, message): Show next moon phase and a custom message. | Implement the Python class `MoonProgressStatus` described below.
Class description:
Progress status that shows phases of the moon.
Method signatures and docstrings:
- def __init__(self): Init moon progress status.
- def update_progress(self, message): Show next moon phase and a custom message.
<|skeleton|>
class Moo... | c2e8913052f4c9f11433f0a421fbbc4b78699fd6 | <|skeleton|>
class MoonProgressStatus:
"""Progress status that shows phases of the moon."""
def __init__(self):
"""Init moon progress status."""
<|body_0|>
def update_progress(self, message):
"""Show next moon phase and a custom message."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MoonProgressStatus:
"""Progress status that shows phases of the moon."""
def __init__(self):
"""Init moon progress status."""
super().__init__()
self.idx = 0
self.msg_chars = MSG_CHARS_MOON
self.msg_ready = MSG_READY_MOON
def update_progress(self, message):
... | the_stack_v2_python_sparse | plugin/utils/progress_status.py | niosus/EasyClangComplete | train | 677 |
a4eba6b43586cd7cc64fb5333428bec07cdf4d98 | [
"super().__init__()\nself.author = 'theosech'\nself.description = 'A point P(x,x**2) lies on the curve y=x**2. Calculate the minimum distance from the point A(2,-0.5) to the point P.'\nself.keywords = ['area of integration', 'area', 'integration']\nself.use_latex = True",
"random.seed(seed)\nnp.random.seed(seed)\... | <|body_start_0|>
super().__init__()
self.author = 'theosech'
self.description = 'A point P(x,x**2) lies on the curve y=x**2. Calculate the minimum distance from the point A(2,-0.5) to the point P.'
self.keywords = ['area of integration', 'area', 'integration']
self.use_latex = Tr... | QA_constraint | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QA_constraint:
def __init__(self):
"""Initializer for your QA question."""
<|body_0|>
def seed_all(self, seed):
"""Write the seeding functions of the libraries that you are using. Its important to seed all the libraries you are using because the framework will assume... | stack_v2_sparse_classes_75kplus_train_007411 | 5,196 | no_license | [
{
"docstring": "Initializer for your QA question.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Write the seeding functions of the libraries that you are using. Its important to seed all the libraries you are using because the framework will assume it can seed stuff ... | 6 | null | Implement the Python class `QA_constraint` described below.
Class description:
Implement the QA_constraint class.
Method signatures and docstrings:
- def __init__(self): Initializer for your QA question.
- def seed_all(self, seed): Write the seeding functions of the libraries that you are using. Its important to seed... | Implement the Python class `QA_constraint` described below.
Class description:
Implement the QA_constraint class.
Method signatures and docstrings:
- def __init__(self): Initializer for your QA question.
- def seed_all(self, seed): Write the seeding functions of the libraries that you are using. Its important to seed... | 25efe0b85f594bd777a7172ab8c1a888459977f1 | <|skeleton|>
class QA_constraint:
def __init__(self):
"""Initializer for your QA question."""
<|body_0|>
def seed_all(self, seed):
"""Write the seeding functions of the libraries that you are using. Its important to seed all the libraries you are using because the framework will assume... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QA_constraint:
def __init__(self):
"""Initializer for your QA question."""
super().__init__()
self.author = 'theosech'
self.description = 'A point P(x,x**2) lies on the curve y=x**2. Calculate the minimum distance from the point A(2,-0.5) to the point P.'
self.keywords ... | the_stack_v2_python_sparse | math_taxonomy/mathematics/single_variable_calculus/integration_area.py | brando90/MathNet-large-scale-Mathematics-Dataset-for-Machine-Learning | train | 0 | |
bbefad75a302452206416d1ca370d9445e181cf1 | [
"self.assertEqual('s53200', soundex('soundex'))\nself.assertEqual('s53200', soundex('soundeggs'))\nself.assertEqual('f46140', soundex('flurbel'))",
"self.assertEqual('a00000', soundex('a'))\nself.assertEqual('x00000', soundex('x'))\nself.assertEqual('o00000', soundex('o'))",
"self.assertEqual('s53200', soundex(... | <|body_start_0|>
self.assertEqual('s53200', soundex('soundex'))
self.assertEqual('s53200', soundex('soundeggs'))
self.assertEqual('f46140', soundex('flurbel'))
<|end_body_0|>
<|body_start_1|>
self.assertEqual('a00000', soundex('a'))
self.assertEqual('x00000', soundex('x'))
... | test class for soundex.soundex | SoundexTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SoundexTest:
"""test class for soundex.soundex"""
def test_examples(self):
"""examples"""
<|body_0|>
def test_singles(self):
"""single characters"""
<|body_1|>
def test_upperchars(self):
"""also uppercase characters"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus_train_007412 | 1,764 | no_license | [
{
"docstring": "examples",
"name": "test_examples",
"signature": "def test_examples(self)"
},
{
"docstring": "single characters",
"name": "test_singles",
"signature": "def test_singles(self)"
},
{
"docstring": "also uppercase characters",
"name": "test_upperchars",
"signa... | 6 | stack_v2_sparse_classes_30k_test_002128 | Implement the Python class `SoundexTest` described below.
Class description:
test class for soundex.soundex
Method signatures and docstrings:
- def test_examples(self): examples
- def test_singles(self): single characters
- def test_upperchars(self): also uppercase characters
- def test_tooooolong(self): more than 6 ... | Implement the Python class `SoundexTest` described below.
Class description:
test class for soundex.soundex
Method signatures and docstrings:
- def test_examples(self): examples
- def test_singles(self): single characters
- def test_upperchars(self): also uppercase characters
- def test_tooooolong(self): more than 6 ... | 73ab76af964f07dc66f7643fb3125e66a2aa6532 | <|skeleton|>
class SoundexTest:
"""test class for soundex.soundex"""
def test_examples(self):
"""examples"""
<|body_0|>
def test_singles(self):
"""single characters"""
<|body_1|>
def test_upperchars(self):
"""also uppercase characters"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SoundexTest:
"""test class for soundex.soundex"""
def test_examples(self):
"""examples"""
self.assertEqual('s53200', soundex('soundex'))
self.assertEqual('s53200', soundex('soundeggs'))
self.assertEqual('f46140', soundex('flurbel'))
def test_singles(self):
"""... | the_stack_v2_python_sparse | PyPrgs_Aufgaben/test_soundex.py | taragor/PythonUebungen | train | 0 |
835d91952c745f3fc449ec8035d4b4b734472e32 | [
"if check_scalar(std):\n std = [std] * dim\nself.std = std\nsuper().__init__(in_channels=in_channels, kernel_size=kernel_size, dim=dim, stride=stride, padding=padding, padding_mode=padding_mode, keys=keys, grad=grad, **kwargs)",
"kernel = 1\nmeshgrids = torch.meshgrid([torch.arange(size, dtype=torch.float32) f... | <|body_start_0|>
if check_scalar(std):
std = [std] * dim
self.std = std
super().__init__(in_channels=in_channels, kernel_size=kernel_size, dim=dim, stride=stride, padding=padding, padding_mode=padding_mode, keys=keys, grad=grad, **kwargs)
<|end_body_0|>
<|body_start_1|>
kern... | Perform Gaussian Smoothing. Filtering is performed seperately for each channel in the input using a depthwise convolution. This code is adapted from: 'https://discuss.pytorch.org/t/is-there-anyway-to-do-' 'gaussian-filtering-for-an-image-2d-3d-in-pytorch/12351/10' | GaussianSmoothing | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianSmoothing:
"""Perform Gaussian Smoothing. Filtering is performed seperately for each channel in the input using a depthwise convolution. This code is adapted from: 'https://discuss.pytorch.org/t/is-there-anyway-to-do-' 'gaussian-filtering-for-an-image-2d-3d-in-pytorch/12351/10'"""
de... | stack_v2_sparse_classes_75kplus_train_007413 | 5,821 | permissive | [
{
"docstring": "Args: in_channels: number of input channels kernel_size: size of kernel std: standard deviation of gaussian dim: number of spatial dimensions stride: stride of convolution padding: padding size for input padding_mode: padding mode for input. Supports all modes from :func:`torch.functional.pad` e... | 2 | stack_v2_sparse_classes_30k_train_010869 | Implement the Python class `GaussianSmoothing` described below.
Class description:
Perform Gaussian Smoothing. Filtering is performed seperately for each channel in the input using a depthwise convolution. This code is adapted from: 'https://discuss.pytorch.org/t/is-there-anyway-to-do-' 'gaussian-filtering-for-an-imag... | Implement the Python class `GaussianSmoothing` described below.
Class description:
Perform Gaussian Smoothing. Filtering is performed seperately for each channel in the input using a depthwise convolution. This code is adapted from: 'https://discuss.pytorch.org/t/is-there-anyway-to-do-' 'gaussian-filtering-for-an-imag... | ab6fbcfe7215c2a5b8e401b70909f6a32d0d167b | <|skeleton|>
class GaussianSmoothing:
"""Perform Gaussian Smoothing. Filtering is performed seperately for each channel in the input using a depthwise convolution. This code is adapted from: 'https://discuss.pytorch.org/t/is-there-anyway-to-do-' 'gaussian-filtering-for-an-image-2d-3d-in-pytorch/12351/10'"""
de... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GaussianSmoothing:
"""Perform Gaussian Smoothing. Filtering is performed seperately for each channel in the input using a depthwise convolution. This code is adapted from: 'https://discuss.pytorch.org/t/is-there-anyway-to-do-' 'gaussian-filtering-for-an-image-2d-3d-in-pytorch/12351/10'"""
def __init__(se... | the_stack_v2_python_sparse | rising/transforms/kernel.py | PhoenixDL/rising | train | 318 |
1e7c29db78f0b4829544f9f1b6266b4ecd83d4a3 | [
"if not telephone:\n raise ValueError(_('Users must have an telephone number'))\nuser = self.model(telephone=telephone, username=username, **other_fields)\nuser.is_admin = False\nif password:\n user.set_password(password)\nif is_save:\n user.save(using=self._db)\nreturn user",
"user = UserProfile.objects... | <|body_start_0|>
if not telephone:
raise ValueError(_('Users must have an telephone number'))
user = self.model(telephone=telephone, username=username, **other_fields)
user.is_admin = False
if password:
user.set_password(password)
if is_save:
u... | MyUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyUserManager:
def create_user(self, telephone, username, password=None, is_save=True, **other_fields):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, telephone, username, password=None, is_save=True, **... | stack_v2_sparse_classes_75kplus_train_007414 | 9,632 | no_license | [
{
"docstring": "Creates and saves a User with the given email, date of birth and password.",
"name": "create_user",
"signature": "def create_user(self, telephone, username, password=None, is_save=True, **other_fields)"
},
{
"docstring": "Creates and saves a superuser with the given email, date o... | 2 | stack_v2_sparse_classes_30k_train_036375 | Implement the Python class `MyUserManager` described below.
Class description:
Implement the MyUserManager class.
Method signatures and docstrings:
- def create_user(self, telephone, username, password=None, is_save=True, **other_fields): Creates and saves a User with the given email, date of birth and password.
- de... | Implement the Python class `MyUserManager` described below.
Class description:
Implement the MyUserManager class.
Method signatures and docstrings:
- def create_user(self, telephone, username, password=None, is_save=True, **other_fields): Creates and saves a User with the given email, date of birth and password.
- de... | 1fbb0941f26389cbfdc8015527ab0d426c2e2c01 | <|skeleton|>
class MyUserManager:
def create_user(self, telephone, username, password=None, is_save=True, **other_fields):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, telephone, username, password=None, is_save=True, **... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyUserManager:
def create_user(self, telephone, username, password=None, is_save=True, **other_fields):
"""Creates and saves a User with the given email, date of birth and password."""
if not telephone:
raise ValueError(_('Users must have an telephone number'))
user = self.... | the_stack_v2_python_sparse | apps/profiles/models.py | nerosketch/djing2 | train | 7 | |
77ff8850abb79572c140048c4dba7e08a1b1b4de | [
"super(PointNet, self).__init__()\nif dropout_list is None:\n dropout_list = [-1] * len(out_channels_list)\nself.layers = nn.ModuleList()\nprevious_out_channels = in_channels\nfor i, c_out in enumerate(out_channels_list):\n if i == len(out_channels_list) - 1:\n if False == norm_act_at_last:\n ... | <|body_start_0|>
super(PointNet, self).__init__()
if dropout_list is None:
dropout_list = [-1] * len(out_channels_list)
self.layers = nn.ModuleList()
previous_out_channels = in_channels
for i, c_out in enumerate(out_channels_list):
if i == len(out_channels... | PointNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PointNet:
def __init__(self, in_channels: int, out_channels_list: List[int], normalization: str='batch', norm_momentum: float=0.1, activation: str='relu', output_init_radius: float=None, norm_act_at_last: bool=False, dropout_list: List[float]=None):
"""PointNet, i.e., a series of Equivar... | stack_v2_sparse_classes_75kplus_train_007415 | 38,399 | no_license | [
{
"docstring": "PointNet, i.e., a series of EquivariantLayer :param in_channels: C in input tensors :param out_channels_list: A list of intermediate and final output channels :param normalization: normalization method, 'batch', 'instance' :param norm_momentum: momentum in normazliation layer :param activation: ... | 2 | stack_v2_sparse_classes_30k_train_030825 | Implement the Python class `PointNet` described below.
Class description:
Implement the PointNet class.
Method signatures and docstrings:
- def __init__(self, in_channels: int, out_channels_list: List[int], normalization: str='batch', norm_momentum: float=0.1, activation: str='relu', output_init_radius: float=None, n... | Implement the Python class `PointNet` described below.
Class description:
Implement the PointNet class.
Method signatures and docstrings:
- def __init__(self, in_channels: int, out_channels_list: List[int], normalization: str='batch', norm_momentum: float=0.1, activation: str='relu', output_init_radius: float=None, n... | c2c3c4e46620446ad0b51a5bd1f836a3c5b386d2 | <|skeleton|>
class PointNet:
def __init__(self, in_channels: int, out_channels_list: List[int], normalization: str='batch', norm_momentum: float=0.1, activation: str='relu', output_init_radius: float=None, norm_act_at_last: bool=False, dropout_list: List[float]=None):
"""PointNet, i.e., a series of Equivar... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PointNet:
def __init__(self, in_channels: int, out_channels_list: List[int], normalization: str='batch', norm_momentum: float=0.1, activation: str='relu', output_init_radius: float=None, norm_act_at_last: bool=False, dropout_list: List[float]=None):
"""PointNet, i.e., a series of EquivariantLayer :par... | the_stack_v2_python_sparse | models/layers_pc.py | hoboh/DeepI2P | train | 0 | |
a7b80a8f81b7ecde370f3b96a072275c40133327 | [
"filename = os.path.basename(model_path)\nprint('Loading imads model: %s' % filename)\nself.modeldict = self.load_model(model_path)\nself.core = core\nself.width = width\nself.kmers = kmers",
"model = svmutil.svm_load_model(model_file)\nmodel_dict = {'model': model}\nif check_size:\n model_dict['size'] = len(m... | <|body_start_0|>
filename = os.path.basename(model_path)
print('Loading imads model: %s' % filename)
self.modeldict = self.load_model(model_path)
self.core = core
self.width = width
self.kmers = kmers
<|end_body_0|>
<|body_start_1|>
model = svmutil.svm_load_model... | classdocs | iMADSModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class iMADSModel:
"""classdocs"""
def __init__(self, model_path, core, width, kmers):
"""Constructor"""
<|body_0|>
def load_model(self, model_file, check_size=True):
"""Taken from: https://github.com/Duke-GCB/Predict-TF-Binding Loads a svm model from a file and compute... | stack_v2_sparse_classes_75kplus_train_007416 | 2,925 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, model_path, core, width, kmers)"
},
{
"docstring": "Taken from: https://github.com/Duke-GCB/Predict-TF-Binding Loads a svm model from a file and computes its size :param model_file: The file name of the model to l... | 3 | stack_v2_sparse_classes_30k_train_015039 | Implement the Python class `iMADSModel` described below.
Class description:
classdocs
Method signatures and docstrings:
- def __init__(self, model_path, core, width, kmers): Constructor
- def load_model(self, model_file, check_size=True): Taken from: https://github.com/Duke-GCB/Predict-TF-Binding Loads a svm model fr... | Implement the Python class `iMADSModel` described below.
Class description:
classdocs
Method signatures and docstrings:
- def __init__(self, model_path, core, width, kmers): Constructor
- def load_model(self, model_file, check_size=True): Taken from: https://github.com/Duke-GCB/Predict-TF-Binding Loads a svm model fr... | 6271b7ede0cacc8fea2b93798b46efb867971478 | <|skeleton|>
class iMADSModel:
"""classdocs"""
def __init__(self, model_path, core, width, kmers):
"""Constructor"""
<|body_0|>
def load_model(self, model_file, check_size=True):
"""Taken from: https://github.com/Duke-GCB/Predict-TF-Binding Loads a svm model from a file and compute... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class iMADSModel:
"""classdocs"""
def __init__(self, model_path, core, width, kmers):
"""Constructor"""
filename = os.path.basename(model_path)
print('Loading imads model: %s' % filename)
self.modeldict = self.load_model(model_path)
self.core = core
self.width = ... | the_stack_v2_python_sparse | chip2probe/probe_generator/src_v1/probefilter/sitesfinder/imadsmodel.py | vincentiusmartin/chip2probe | train | 1 |
cf5a9c2ae802eab03e95c07333c1929a45337ad9 | [
"super().__init__()\nself.sub_blocks = nn.ModuleList()\nfor i in range(sub_blocks):\n self.sub_blocks.append(SubBlock(kernels=kernels, gate_channels=gate_channels, residual_channels=residual_channels))\nself.skip_convs = nn.Conv1d(in_channels=residual_channels, out_channels=skip_channels, kernel_size=1)\nself.di... | <|body_start_0|>
super().__init__()
self.sub_blocks = nn.ModuleList()
for i in range(sub_blocks):
self.sub_blocks.append(SubBlock(kernels=kernels, gate_channels=gate_channels, residual_channels=residual_channels))
self.skip_convs = nn.Conv1d(in_channels=residual_channels, out... | Блок, состоящий из нескольких маленьких блоков и последующим уменьшением размерности. Имеет два выхода: - Основной с уменьшенной в два раза размерностью; - Скип для суммирования последнего значения слоя с остальными скипами и расчета общего выходного значения. | Block | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Block:
"""Блок, состоящий из нескольких маленьких блоков и последующим уменьшением размерности. Имеет два выхода: - Основной с уменьшенной в два раза размерностью; - Скип для суммирования последнего значения слоя с остальными скипами и расчета общего выходного значения."""
def __init__(self,... | stack_v2_sparse_classes_75kplus_train_007417 | 13,064 | permissive | [
{
"docstring": ":param sub_blocks: Количество маленьких блоков в блоке. :param kernels: Размер сверток в signal и gate сверточных слоях. :param gate_channels: Количество каналов в signal и gate сверточных слоях маленьких блоков. :param residual_channels: Количество каналов на входе и по обходному пути маленьких... | 2 | stack_v2_sparse_classes_30k_train_013822 | Implement the Python class `Block` described below.
Class description:
Блок, состоящий из нескольких маленьких блоков и последующим уменьшением размерности. Имеет два выхода: - Основной с уменьшенной в два раза размерностью; - Скип для суммирования последнего значения слоя с остальными скипами и расчета общего выходно... | Implement the Python class `Block` described below.
Class description:
Блок, состоящий из нескольких маленьких блоков и последующим уменьшением размерности. Имеет два выхода: - Основной с уменьшенной в два раза размерностью; - Скип для суммирования последнего значения слоя с остальными скипами и расчета общего выходно... | 3a67544fd4c1bce39d67523799b76c9adfd03969 | <|skeleton|>
class Block:
"""Блок, состоящий из нескольких маленьких блоков и последующим уменьшением размерности. Имеет два выхода: - Основной с уменьшенной в два раза размерностью; - Скип для суммирования последнего значения слоя с остальными скипами и расчета общего выходного значения."""
def __init__(self,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Block:
"""Блок, состоящий из нескольких маленьких блоков и последующим уменьшением размерности. Имеет два выхода: - Основной с уменьшенной в два раза размерностью; - Скип для суммирования последнего значения слоя с остальными скипами и расчета общего выходного значения."""
def __init__(self, sub_blocks: ... | the_stack_v2_python_sparse | poptimizer/dl/models/wave_net.py | tjlee/poptimizer | train | 0 |
fe9e101556bb16400f61533c4c1913d2aac1bf75 | [
"await self.async_set_unique_id(config[CONF_USERNAME].lower())\nself._abort_if_unique_id_configured()\neight = EightSleep(config[CONF_USERNAME], config[CONF_PASSWORD], self.hass.config.time_zone, client_session=async_get_clientsession(self.hass))\ntry:\n await eight.fetch_token()\nexcept RequestError as err:\n ... | <|body_start_0|>
await self.async_set_unique_id(config[CONF_USERNAME].lower())
self._abort_if_unique_id_configured()
eight = EightSleep(config[CONF_USERNAME], config[CONF_PASSWORD], self.hass.config.time_zone, client_session=async_get_clientsession(self.hass))
try:
await eigh... | Handle a config flow for Eight Sleep. | ConfigFlow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigFlow:
"""Handle a config flow for Eight Sleep."""
async def _validate_data(self, config: dict[str, str]) -> str | None:
"""Validate input data and return any error."""
<|body_0|>
async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult:... | stack_v2_sparse_classes_75kplus_train_007418 | 2,878 | permissive | [
{
"docstring": "Validate input data and return any error.",
"name": "_validate_data",
"signature": "async def _validate_data(self, config: dict[str, str]) -> str | None"
},
{
"docstring": "Handle the initial step.",
"name": "async_step_user",
"signature": "async def async_step_user(self,... | 3 | stack_v2_sparse_classes_30k_test_002495 | Implement the Python class `ConfigFlow` described below.
Class description:
Handle a config flow for Eight Sleep.
Method signatures and docstrings:
- async def _validate_data(self, config: dict[str, str]) -> str | None: Validate input data and return any error.
- async def async_step_user(self, user_input: dict[str, ... | Implement the Python class `ConfigFlow` described below.
Class description:
Handle a config flow for Eight Sleep.
Method signatures and docstrings:
- async def _validate_data(self, config: dict[str, str]) -> str | None: Validate input data and return any error.
- async def async_step_user(self, user_input: dict[str, ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ConfigFlow:
"""Handle a config flow for Eight Sleep."""
async def _validate_data(self, config: dict[str, str]) -> str | None:
"""Validate input data and return any error."""
<|body_0|>
async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConfigFlow:
"""Handle a config flow for Eight Sleep."""
async def _validate_data(self, config: dict[str, str]) -> str | None:
"""Validate input data and return any error."""
await self.async_set_unique_id(config[CONF_USERNAME].lower())
self._abort_if_unique_id_configured()
... | the_stack_v2_python_sparse | homeassistant/components/eight_sleep/config_flow.py | home-assistant/core | train | 35,501 |
ce496292d4623868deef99a449930454008c046d | [
"self.n_clusters = n_clusters\nself.max_iter = max_iter\nself.shuffle = shuffle\nself.verbose = verbose\nself.cluster_sizes_ = np.zeros(self.n_clusters)",
"n, d = X.shape\nself.cluster_centers_ = np.zeros((self.n_clusters, d), dtype=X.dtype)\nstep = 0\nidx = np.arange(n)\nwhile step < self.max_iter:\n step = s... | <|body_start_0|>
self.n_clusters = n_clusters
self.max_iter = max_iter
self.shuffle = shuffle
self.verbose = verbose
self.cluster_sizes_ = np.zeros(self.n_clusters)
<|end_body_0|>
<|body_start_1|>
n, d = X.shape
self.cluster_centers_ = np.zeros((self.n_clusters, ... | Online Hartigan clustering. | HartiganOnline | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HartiganOnline:
"""Online Hartigan clustering."""
def __init__(self, n_clusters=2, max_iter=10, shuffle=True, verbose=False):
"""Initialize a Hartigan clusterer. :parameters: - n_clusters : int Number of clusters - max_iter : int Maximum number of passes through the data - shuffle : ... | stack_v2_sparse_classes_75kplus_train_007419 | 2,619 | no_license | [
{
"docstring": "Initialize a Hartigan clusterer. :parameters: - n_clusters : int Number of clusters - max_iter : int Maximum number of passes through the data - shuffle : bool Shuffle the data between each pass - verbose : bool Display debugging output? :variables: - cluster_centers_ : ndarray, shape=(n_cluster... | 3 | stack_v2_sparse_classes_30k_train_052468 | Implement the Python class `HartiganOnline` described below.
Class description:
Online Hartigan clustering.
Method signatures and docstrings:
- def __init__(self, n_clusters=2, max_iter=10, shuffle=True, verbose=False): Initialize a Hartigan clusterer. :parameters: - n_clusters : int Number of clusters - max_iter : i... | Implement the Python class `HartiganOnline` described below.
Class description:
Online Hartigan clustering.
Method signatures and docstrings:
- def __init__(self, n_clusters=2, max_iter=10, shuffle=True, verbose=False): Initialize a Hartigan clusterer. :parameters: - n_clusters : int Number of clusters - max_iter : i... | 229393fd47716a87ecc4b37e306c7f7592e36e51 | <|skeleton|>
class HartiganOnline:
"""Online Hartigan clustering."""
def __init__(self, n_clusters=2, max_iter=10, shuffle=True, verbose=False):
"""Initialize a Hartigan clusterer. :parameters: - n_clusters : int Number of clusters - max_iter : int Maximum number of passes through the data - shuffle : ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HartiganOnline:
"""Online Hartigan clustering."""
def __init__(self, n_clusters=2, max_iter=10, shuffle=True, verbose=False):
"""Initialize a Hartigan clusterer. :parameters: - n_clusters : int Number of clusters - max_iter : int Maximum number of passes through the data - shuffle : bool Shuffle ... | the_stack_v2_python_sparse | code/seymour_analyzers/HartiganOnline.py | bmcfee/seymour | train | 4 |
d8f645a838dd892dded051fc5a84b894ad063f1b | [
"ctx.bot.load_extension(extension_name)\nsettings.manager.setdefault('EXTENSIONS', settings.DEFAULT_EXTENSIONS)\nif extension_name not in settings.manager['EXTENSIONS']:\n settings.manager['EXTENSIONS'].append(extension_name)\n message = f'Extension {extension_name} loaded.'\nelse:\n message = f'Extension ... | <|body_start_0|>
ctx.bot.load_extension(extension_name)
settings.manager.setdefault('EXTENSIONS', settings.DEFAULT_EXTENSIONS)
if extension_name not in settings.manager['EXTENSIONS']:
settings.manager['EXTENSIONS'].append(extension_name)
message = f'Extension {extension_n... | Extension loading/unloading commands. | Extensions | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Extensions:
"""Extension loading/unloading commands."""
async def load(self, ctx, extension_name: str):
"""Enable the use of an extension. Only the bot owner can use this."""
<|body_0|>
async def rload(self, ctx, extension_name: str):
"""Reload an already-loaded ... | stack_v2_sparse_classes_75kplus_train_007420 | 3,378 | permissive | [
{
"docstring": "Enable the use of an extension. Only the bot owner can use this.",
"name": "load",
"signature": "async def load(self, ctx, extension_name: str)"
},
{
"docstring": "Reload an already-loaded extension. Only the bot owner can use this.",
"name": "rload",
"signature": "async ... | 4 | stack_v2_sparse_classes_30k_train_008543 | Implement the Python class `Extensions` described below.
Class description:
Extension loading/unloading commands.
Method signatures and docstrings:
- async def load(self, ctx, extension_name: str): Enable the use of an extension. Only the bot owner can use this.
- async def rload(self, ctx, extension_name: str): Relo... | Implement the Python class `Extensions` described below.
Class description:
Extension loading/unloading commands.
Method signatures and docstrings:
- async def load(self, ctx, extension_name: str): Enable the use of an extension. Only the bot owner can use this.
- async def rload(self, ctx, extension_name: str): Relo... | 3a456ad06814181d13d4aabefc151756c55444f4 | <|skeleton|>
class Extensions:
"""Extension loading/unloading commands."""
async def load(self, ctx, extension_name: str):
"""Enable the use of an extension. Only the bot owner can use this."""
<|body_0|>
async def rload(self, ctx, extension_name: str):
"""Reload an already-loaded ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Extensions:
"""Extension loading/unloading commands."""
async def load(self, ctx, extension_name: str):
"""Enable the use of an extension. Only the bot owner can use this."""
ctx.bot.load_extension(extension_name)
settings.manager.setdefault('EXTENSIONS', settings.DEFAULT_EXTENSIO... | the_stack_v2_python_sparse | cogs/extensions.py | sokcheng/Kitsuchan-NG | train | 1 |
8b22175c72007d4d824890682d02a76795b5f6a6 | [
"self.state_user = 'user'\nself.state_auto = 'autoformatted'\ntransitions = [{'trigger': 'start_auto', 'source': self.state_user, 'dest': self.state_auto}, {'trigger': 'end', 'source': self.state_auto, 'dest': self.state_user}]\nsuper().__init__(states=[self.state_user, self.state_auto], initial=self.state_user, tr... | <|body_start_0|>
self.state_user = 'user'
self.state_auto = 'autoformatted'
transitions = [{'trigger': 'start_auto', 'source': self.state_user, 'dest': self.state_auto}, {'trigger': 'end', 'source': self.state_auto, 'dest': self.state_user}]
super().__init__(states=[self.state_user, self... | State machine to replace content with user-specified handlers. Uses `{cts}` and `{cte}` to demarcate sections (short for calcipy_template start|end) | _ReplacementMachine | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _ReplacementMachine:
"""State machine to replace content with user-specified handlers. Uses `{cts}` and `{cte}` to demarcate sections (short for calcipy_template start|end)"""
def __init__(self) -> None:
"""Initialize the state machine."""
<|body_0|>
def _parse_line(self... | stack_v2_sparse_classes_75kplus_train_007421 | 13,523 | permissive | [
{
"docstring": "Initialize the state machine.",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Parse lines and insert new_text based on provided handler_lookup. Args: line: single line handler_lookup: Lookup dictionary for autoformatted sections path_file: optio... | 3 | stack_v2_sparse_classes_30k_train_053827 | Implement the Python class `_ReplacementMachine` described below.
Class description:
State machine to replace content with user-specified handlers. Uses `{cts}` and `{cte}` to demarcate sections (short for calcipy_template start|end)
Method signatures and docstrings:
- def __init__(self) -> None: Initialize the state... | Implement the Python class `_ReplacementMachine` described below.
Class description:
State machine to replace content with user-specified handlers. Uses `{cts}` and `{cte}` to demarcate sections (short for calcipy_template start|end)
Method signatures and docstrings:
- def __init__(self) -> None: Initialize the state... | c10d78cce727b04b6d4f633859659cdcda832630 | <|skeleton|>
class _ReplacementMachine:
"""State machine to replace content with user-specified handlers. Uses `{cts}` and `{cte}` to demarcate sections (short for calcipy_template start|end)"""
def __init__(self) -> None:
"""Initialize the state machine."""
<|body_0|>
def _parse_line(self... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _ReplacementMachine:
"""State machine to replace content with user-specified handlers. Uses `{cts}` and `{cte}` to demarcate sections (short for calcipy_template start|end)"""
def __init__(self) -> None:
"""Initialize the state machine."""
self.state_user = 'user'
self.state_auto ... | the_stack_v2_python_sparse | calcipy/doit_tasks/doc.py | amitkparekh/calcipy | train | 1 |
1f53624ea58dcc19a8c2b93aecf7a950b8552855 | [
"self.path = path_to_weights\nself.num_features = num_features\nself.model = ResNetTriple(BasicBlock, [2, 2, 2, 2], num_features=num_features)\nself.device = 'cuda:' + str(device)\nself.model.load_state_dict(torch.load(self.path))\nself.model.to(self.device)\nprint('NN was Inited!')",
"print('================PRED... | <|body_start_0|>
self.path = path_to_weights
self.num_features = num_features
self.model = ResNetTriple(BasicBlock, [2, 2, 2, 2], num_features=num_features)
self.device = 'cuda:' + str(device)
self.model.load_state_dict(torch.load(self.path))
self.model.to(self.device)
... | PickNetClassifier | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PickNetClassifier:
def __init__(self, path_to_weights: str, num_features: int, device: int):
"""Args: path_to_model -- path to weights of classification model num_features -- number of features device -- torch device"""
<|body_0|>
def predict(self, x):
"""Input: x: n... | stack_v2_sparse_classes_75kplus_train_007422 | 10,501 | no_license | [
{
"docstring": "Args: path_to_model -- path to weights of classification model num_features -- number of features device -- torch device",
"name": "__init__",
"signature": "def __init__(self, path_to_weights: str, num_features: int, device: int)"
},
{
"docstring": "Input: x: numpy array of featu... | 2 | stack_v2_sparse_classes_30k_test_000645 | Implement the Python class `PickNetClassifier` described below.
Class description:
Implement the PickNetClassifier class.
Method signatures and docstrings:
- def __init__(self, path_to_weights: str, num_features: int, device: int): Args: path_to_model -- path to weights of classification model num_features -- number ... | Implement the Python class `PickNetClassifier` described below.
Class description:
Implement the PickNetClassifier class.
Method signatures and docstrings:
- def __init__(self, path_to_weights: str, num_features: int, device: int): Args: path_to_model -- path to weights of classification model num_features -- number ... | 294baab2d4b3370798658ec9276a15ad745a9d46 | <|skeleton|>
class PickNetClassifier:
def __init__(self, path_to_weights: str, num_features: int, device: int):
"""Args: path_to_model -- path to weights of classification model num_features -- number of features device -- torch device"""
<|body_0|>
def predict(self, x):
"""Input: x: n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PickNetClassifier:
def __init__(self, path_to_weights: str, num_features: int, device: int):
"""Args: path_to_model -- path to weights of classification model num_features -- number of features device -- torch device"""
self.path = path_to_weights
self.num_features = num_features
... | the_stack_v2_python_sparse | func/vkusmart/pick_counter/neural_method_v1.py | Lonerien/smart_shop | train | 0 | |
d73b6f6562be46bd81d441c08eb73cbe2720ea9f | [
"timestamp = self._GetRowValue(query_hash, row, value_name)\nif timestamp is None:\n return None\nreturn dfdatetime_webkit_time.WebKitTime(timestamp=timestamp)",
"query_hash = hash(query)\nevent_data = EdgeLoadStatisticsResourceEventData()\nevent_data.last_update = self._GetWebKitDateTimeRowValue(query_hash, r... | <|body_start_0|>
timestamp = self._GetRowValue(query_hash, row, value_name)
if timestamp is None:
return None
return dfdatetime_webkit_time.WebKitTime(timestamp=timestamp)
<|end_body_0|>
<|body_start_1|>
query_hash = hash(query)
event_data = EdgeLoadStatisticsResourc... | SQLite parser plugin for Microsoft Edge load statistics database. | EdgeLoadStatisticsPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EdgeLoadStatisticsPlugin:
"""SQLite parser plugin for Microsoft Edge load statistics database."""
def _GetWebKitDateTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a WebKit date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identi... | stack_v2_sparse_classes_75kplus_train_007423 | 4,267 | permissive | [
{
"docstring": "Retrieves a WebKit date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced the row. row (sqlite3.Row): row. value_name (str): name of the value. Returns: dfdatetime.WebKitTime: date and time value or None if not available.",
... | 2 | stack_v2_sparse_classes_30k_train_003180 | Implement the Python class `EdgeLoadStatisticsPlugin` described below.
Class description:
SQLite parser plugin for Microsoft Edge load statistics database.
Method signatures and docstrings:
- def _GetWebKitDateTimeRowValue(self, query_hash, row, value_name): Retrieves a WebKit date and time value from the row. Args: ... | Implement the Python class `EdgeLoadStatisticsPlugin` described below.
Class description:
SQLite parser plugin for Microsoft Edge load statistics database.
Method signatures and docstrings:
- def _GetWebKitDateTimeRowValue(self, query_hash, row, value_name): Retrieves a WebKit date and time value from the row. Args: ... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class EdgeLoadStatisticsPlugin:
"""SQLite parser plugin for Microsoft Edge load statistics database."""
def _GetWebKitDateTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a WebKit date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EdgeLoadStatisticsPlugin:
"""SQLite parser plugin for Microsoft Edge load statistics database."""
def _GetWebKitDateTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a WebKit date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the quer... | the_stack_v2_python_sparse | plaso/parsers/sqlite_plugins/edge_load_statistics.py | log2timeline/plaso | train | 1,506 |
3f62db399389e302151423f7957e3cea5484372d | [
"self.pool = Pool(4)\nself.fun = fun\nself.jobs = {}\nself.jobs_look = Lock()",
"res = self.pool.apply_async(self.fun, (args,))\njob_uuid = uuid.uuid4()\nwith self.jobs_look:\n self.jobs[str(job_uuid)] = res\nreturn job_uuid",
"with self.jobs_look:\n is_complete = self.jobs[job_uuid].ready()\nreturn is_co... | <|body_start_0|>
self.pool = Pool(4)
self.fun = fun
self.jobs = {}
self.jobs_look = Lock()
<|end_body_0|>
<|body_start_1|>
res = self.pool.apply_async(self.fun, (args,))
job_uuid = uuid.uuid4()
with self.jobs_look:
self.jobs[str(job_uuid)] = res
... | Class for handling function execution Be aware that each job_id is only shared between thread of one process. Multiple workers aren't supported, as only process has access to its own function pool. TODO Move pool to separate server application (maybe new server with REST API) | FunctionPool | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FunctionPool:
"""Class for handling function execution Be aware that each job_id is only shared between thread of one process. Multiple workers aren't supported, as only process has access to its own function pool. TODO Move pool to separate server application (maybe new server with REST API)"""
... | stack_v2_sparse_classes_75kplus_train_007424 | 5,779 | no_license | [
{
"docstring": ":param fun: function to run on each task",
"name": "__init__",
"signature": "def __init__(self, fun)"
},
{
"docstring": "Adds new task to pool :param args: args witch will be passed to task :return: unique task id",
"name": "add_task",
"signature": "def add_task(self, arg... | 5 | null | Implement the Python class `FunctionPool` described below.
Class description:
Class for handling function execution Be aware that each job_id is only shared between thread of one process. Multiple workers aren't supported, as only process has access to its own function pool. TODO Move pool to separate server applicati... | Implement the Python class `FunctionPool` described below.
Class description:
Class for handling function execution Be aware that each job_id is only shared between thread of one process. Multiple workers aren't supported, as only process has access to its own function pool. TODO Move pool to separate server applicati... | c33d0f33c18ef804d519a569d65452cd6bedc17e | <|skeleton|>
class FunctionPool:
"""Class for handling function execution Be aware that each job_id is only shared between thread of one process. Multiple workers aren't supported, as only process has access to its own function pool. TODO Move pool to separate server application (maybe new server with REST API)"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FunctionPool:
"""Class for handling function execution Be aware that each job_id is only shared between thread of one process. Multiple workers aren't supported, as only process has access to its own function pool. TODO Move pool to separate server application (maybe new server with REST API)"""
def __in... | the_stack_v2_python_sparse | GDELT/functions/function_utils.py | TymofiiChumak/GDELT | train | 0 |
3fc2a68212dc0d3cd6e8f67e8ce48a396f3c6903 | [
"Thread.__init__(self)\nself.router = router\nself.config = config\nself.daemon = True",
"logging.info('%sRegister PublicKey ...', LoggerSetup.get_log_deep(1))\nif self.router.node_name == '' or self.router.public_key == '':\n logging.warning(\"%s[!] The PublicKey doesn't exist\", LoggerSetup.get_log_deep(2))\... | <|body_start_0|>
Thread.__init__(self)
self.router = router
self.config = config
self.daemon = True
<|end_body_0|>
<|body_start_1|>
logging.info('%sRegister PublicKey ...', LoggerSetup.get_log_deep(1))
if self.router.node_name == '' or self.router.public_key == '':
... | Sends the Public-Key of the Router to a given Email-Address. This is only possible if the key has been read from the wizard-page. | RegisterPublicKey | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegisterPublicKey:
"""Sends the Public-Key of the Router to a given Email-Address. This is only possible if the key has been read from the wizard-page."""
def __init__(self, router: Router, config):
""":param router: Router-object :param config: {node_name, mesh_vpn, limit_bandwidth,... | stack_v2_sparse_classes_75kplus_train_007425 | 2,678 | no_license | [
{
"docstring": ":param router: Router-object :param config: {node_name, mesh_vpn, limit_bandwidth, show_location, latitude, longitude, altitude, contact,...}",
"name": "__init__",
"signature": "def __init__(self, router: Router, config)"
},
{
"docstring": "The Public-Key is send with the Router_... | 2 | stack_v2_sparse_classes_30k_train_032140 | Implement the Python class `RegisterPublicKey` described below.
Class description:
Sends the Public-Key of the Router to a given Email-Address. This is only possible if the key has been read from the wizard-page.
Method signatures and docstrings:
- def __init__(self, router: Router, config): :param router: Router-obj... | Implement the Python class `RegisterPublicKey` described below.
Class description:
Sends the Public-Key of the Router to a given Email-Address. This is only possible if the key has been read from the wizard-page.
Method signatures and docstrings:
- def __init__(self, router: Router, config): :param router: Router-obj... | 551fb53a6d4f865f076d9485e7290699d988731c | <|skeleton|>
class RegisterPublicKey:
"""Sends the Public-Key of the Router to a given Email-Address. This is only possible if the key has been read from the wizard-page."""
def __init__(self, router: Router, config):
""":param router: Router-object :param config: {node_name, mesh_vpn, limit_bandwidth,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RegisterPublicKey:
"""Sends the Public-Key of the Router to a given Email-Address. This is only possible if the key has been read from the wizard-page."""
def __init__(self, router: Router, config):
""":param router: Router-object :param config: {node_name, mesh_vpn, limit_bandwidth, show_locatio... | the_stack_v2_python_sparse | util/register_public_key.py | PumucklOnTheAir/TestFramework | train | 9 |
d3d1c460503f3a9a83bceb566fbb2ffdd01e3dde | [
"super(InvoerFrame, self).__init__(parent, id, title, pos, size, style, name)\nself.Paneel = SubPaneel(self)\nself.Opslaan = OpslaanPaneel(self.Paneel, id)\nself.Knoppen = KnoppenPaneel(self.Paneel, butid, id)\nself.Zetten = ZettenPaneel(self.Paneel, id)\nallbox = wx.BoxSizer(wx.VERTICAL)\nallbox.Add(self.Opslaan, ... | <|body_start_0|>
super(InvoerFrame, self).__init__(parent, id, title, pos, size, style, name)
self.Paneel = SubPaneel(self)
self.Opslaan = OpslaanPaneel(self.Paneel, id)
self.Knoppen = KnoppenPaneel(self.Paneel, butid, id)
self.Zetten = ZettenPaneel(self.Paneel, id)
allbo... | Klasse maakt een frame met daarin een opslag module en de mogelijkheid om aantal zetten te bepalen voor DNA-Mind. Zie documentatie __init__ voor meer informatie. | InvoerFrame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InvoerFrame:
"""Klasse maakt een frame met daarin een opslag module en de mogelijkheid om aantal zetten te bepalen voor DNA-Mind. Zie documentatie __init__ voor meer informatie."""
def __init__(self, parent, butid, id=wx.ID_ANY, title='DNA-Mind', pos=wx.DefaultPosition, size=(300, 450), styl... | stack_v2_sparse_classes_75kplus_train_007426 | 3,857 | no_license | [
{
"docstring": "Maakt en toont InvoerScherm. De __init__ methode heeft 8 parameters nodig. parent De ouder van het paneel. butid Getal die gebruikt wordt om door te sturen naar KnoppenPaneel. Zie documentatie KnoppenPaneel voor meer informatie. id=wx.ID_ANY id voor frame. Als er geen id aanwezig is, dan zal dez... | 2 | stack_v2_sparse_classes_30k_train_036447 | Implement the Python class `InvoerFrame` described below.
Class description:
Klasse maakt een frame met daarin een opslag module en de mogelijkheid om aantal zetten te bepalen voor DNA-Mind. Zie documentatie __init__ voor meer informatie.
Method signatures and docstrings:
- def __init__(self, parent, butid, id=wx.ID_... | Implement the Python class `InvoerFrame` described below.
Class description:
Klasse maakt een frame met daarin een opslag module en de mogelijkheid om aantal zetten te bepalen voor DNA-Mind. Zie documentatie __init__ voor meer informatie.
Method signatures and docstrings:
- def __init__(self, parent, butid, id=wx.ID_... | 6093fb23294f0a5d42f61113e607d3c1fb94542f | <|skeleton|>
class InvoerFrame:
"""Klasse maakt een frame met daarin een opslag module en de mogelijkheid om aantal zetten te bepalen voor DNA-Mind. Zie documentatie __init__ voor meer informatie."""
def __init__(self, parent, butid, id=wx.ID_ANY, title='DNA-Mind', pos=wx.DefaultPosition, size=(300, 450), styl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InvoerFrame:
"""Klasse maakt een frame met daarin een opslag module en de mogelijkheid om aantal zetten te bepalen voor DNA-Mind. Zie documentatie __init__ voor meer informatie."""
def __init__(self, parent, butid, id=wx.ID_ANY, title='DNA-Mind', pos=wx.DefaultPosition, size=(300, 450), style=wx.DEFAULT_... | the_stack_v2_python_sparse | DNA-Mastermind-application/InvoerScherm.py | sdevriend/Student-Portfolio | train | 0 |
fd0d4b2d7d92219a66df5994d6159e09e8f963e7 | [
"lookupurl = 'https://itunes.apple.com/lookup?id={}'.format(appid)\nresp = requests.get(lookupurl)\ndata = resp.json()\nreturn data",
"os.makedirs(dirr) if not os.path.isdir(dirr) else False\nfn = dirr + '/' + str(f'{indexx}_') + picurl.split('/')[-1]\nr = requests.get(picurl, stream=True)\nf = open(fn, 'wb')\nfo... | <|body_start_0|>
lookupurl = 'https://itunes.apple.com/lookup?id={}'.format(appid)
resp = requests.get(lookupurl)
data = resp.json()
return data
<|end_body_0|>
<|body_start_1|>
os.makedirs(dirr) if not os.path.isdir(dirr) else False
fn = dirr + '/' + str(f'{indexx}_') + ... | Class for extracting data for apps. | StoreAppData | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StoreAppData:
"""Class for extracting data for apps."""
def get_raw_app_json(self, appid: str):
"""Retrieve app data. :param appid: ID of ios application. :type appid: str"""
<|body_0|>
def get_images(self, picurl: str, dirr: str, indexx: int):
"""Method for down... | stack_v2_sparse_classes_75kplus_train_007427 | 5,032 | permissive | [
{
"docstring": "Retrieve app data. :param appid: ID of ios application. :type appid: str",
"name": "get_raw_app_json",
"signature": "def get_raw_app_json(self, appid: str)"
},
{
"docstring": "Method for downloading app images. :param picurl: url of image to download. :type picurl: str :param dir... | 6 | stack_v2_sparse_classes_30k_test_001907 | Implement the Python class `StoreAppData` described below.
Class description:
Class for extracting data for apps.
Method signatures and docstrings:
- def get_raw_app_json(self, appid: str): Retrieve app data. :param appid: ID of ios application. :type appid: str
- def get_images(self, picurl: str, dirr: str, indexx: ... | Implement the Python class `StoreAppData` described below.
Class description:
Class for extracting data for apps.
Method signatures and docstrings:
- def get_raw_app_json(self, appid: str): Retrieve app data. :param appid: ID of ios application. :type appid: str
- def get_images(self, picurl: str, dirr: str, indexx: ... | 6f52c3772e810a0794050e22f3c67257b1a0302c | <|skeleton|>
class StoreAppData:
"""Class for extracting data for apps."""
def get_raw_app_json(self, appid: str):
"""Retrieve app data. :param appid: ID of ios application. :type appid: str"""
<|body_0|>
def get_images(self, picurl: str, dirr: str, indexx: int):
"""Method for down... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StoreAppData:
"""Class for extracting data for apps."""
def get_raw_app_json(self, appid: str):
"""Retrieve app data. :param appid: ID of ios application. :type appid: str"""
lookupurl = 'https://itunes.apple.com/lookup?id={}'.format(appid)
resp = requests.get(lookupurl)
d... | the_stack_v2_python_sparse | ios_data_client/store_data.py | samroon2/ios_data_client | train | 0 |
72359e4d92667a7a45880e4f3bfe95fc3b278cd0 | [
"print('Please wait. Setting up data for {} process.'.format(to_address))\nself.to_address = to_address\nself.email_subject = email_subject\nself.email_body = email_body\nself.from_address = my_credentials.my_email\nself.display_name = display_name\nself.attachment = attachment\nself.att_path = att_path",
"print(... | <|body_start_0|>
print('Please wait. Setting up data for {} process.'.format(to_address))
self.to_address = to_address
self.email_subject = email_subject
self.email_body = email_body
self.from_address = my_credentials.my_email
self.display_name = display_name
self... | CustomMails | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomMails:
def __init__(self, to_address, email_subject, email_body, attachment=None, att_path=None, display_name='Practical Programmer'):
"""Construct the custom mails details"""
<|body_0|>
def format_message(self):
"""Format the message into its various component... | stack_v2_sparse_classes_75kplus_train_007428 | 4,388 | no_license | [
{
"docstring": "Construct the custom mails details",
"name": "__init__",
"signature": "def __init__(self, to_address, email_subject, email_body, attachment=None, att_path=None, display_name='Practical Programmer')"
},
{
"docstring": "Format the message into its various components and return it."... | 4 | stack_v2_sparse_classes_30k_train_014794 | Implement the Python class `CustomMails` described below.
Class description:
Implement the CustomMails class.
Method signatures and docstrings:
- def __init__(self, to_address, email_subject, email_body, attachment=None, att_path=None, display_name='Practical Programmer'): Construct the custom mails details
- def for... | Implement the Python class `CustomMails` described below.
Class description:
Implement the CustomMails class.
Method signatures and docstrings:
- def __init__(self, to_address, email_subject, email_body, attachment=None, att_path=None, display_name='Practical Programmer'): Construct the custom mails details
- def for... | ba176a9029f108c39d53970ff5127be7007555ee | <|skeleton|>
class CustomMails:
def __init__(self, to_address, email_subject, email_body, attachment=None, att_path=None, display_name='Practical Programmer'):
"""Construct the custom mails details"""
<|body_0|>
def format_message(self):
"""Format the message into its various component... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomMails:
def __init__(self, to_address, email_subject, email_body, attachment=None, att_path=None, display_name='Practical Programmer'):
"""Construct the custom mails details"""
print('Please wait. Setting up data for {} process.'.format(to_address))
self.to_address = to_address
... | the_stack_v2_python_sparse | PracticeProjects/SendingMail/elaborate_mail.py | Lemmah/pyWorkSpace | train | 0 | |
ce98243afa4fc7e5ce7810748beff8c2a791c298 | [
"if surface is not None:\n self.t = surface.index\n assert np.all(self.t == profile.index.unique())\n self.surface = surface\nelse:\n self.t = profile.index.unique()\n self.surface = pd.DataFrame(index=self.t)\nself.z = profile['z'].unique()\nself.info = info\nself.N = len(self.z)\nself.info['levels'... | <|body_start_0|>
if surface is not None:
self.t = surface.index
assert np.all(self.t == profile.index.unique())
self.surface = surface
else:
self.t = profile.index.unique()
self.surface = pd.DataFrame(index=self.t)
self.z = profile['z']... | MMCdata | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MMCdata:
def __init__(self, profile, surface, info, na_values=-999.0):
"""Create object for standardized MMC data output profile: pandas.DataFrame Dataframe with datetime index and columns corresponding to the data arrays described above; a 'z' column describes the height AGL. surface: p... | stack_v2_sparse_classes_75kplus_train_007429 | 6,740 | no_license | [
{
"docstring": "Create object for standardized MMC data output profile: pandas.DataFrame Dataframe with datetime index and columns corresponding to the data arrays described above; a 'z' column describes the height AGL. surface: pandas.DataFrame, optional Dataframe with datetime index and columns corresponding ... | 3 | stack_v2_sparse_classes_30k_train_007341 | Implement the Python class `MMCdata` described below.
Class description:
Implement the MMCdata class.
Method signatures and docstrings:
- def __init__(self, profile, surface, info, na_values=-999.0): Create object for standardized MMC data output profile: pandas.DataFrame Dataframe with datetime index and columns cor... | Implement the Python class `MMCdata` described below.
Class description:
Implement the MMCdata class.
Method signatures and docstrings:
- def __init__(self, profile, surface, info, na_values=-999.0): Create object for standardized MMC data output profile: pandas.DataFrame Dataframe with datetime index and columns cor... | c34afb2a13fc0075f95a43bac99219b25b3984a2 | <|skeleton|>
class MMCdata:
def __init__(self, profile, surface, info, na_values=-999.0):
"""Create object for standardized MMC data output profile: pandas.DataFrame Dataframe with datetime index and columns corresponding to the data arrays described above; a 'z' column describes the height AGL. surface: p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MMCdata:
def __init__(self, profile, surface, info, na_values=-999.0):
"""Create object for standardized MMC data output profile: pandas.DataFrame Dataframe with datetime index and columns corresponding to the data arrays described above; a 'z' column describes the height AGL. surface: pandas.DataFram... | the_stack_v2_python_sparse | MMC/output_profile.py | ewquon/pylib | train | 2 | |
4377a9f0a75d47f06c81735614cfa0975dd2439a | [
"if name in self.oxm_fields:\n return self.oxm_fields[name].id\nelse:\n maybes = difflib.get_close_matches(name, self.oxm_fields)\n last_id = self.oxm_fields[self.ordered_oxm_fields[-1]].id\n print('Adding field ' + name + ' as ' + str(last_id + 1) + 'consider adding this with name and values')\n if ... | <|body_start_0|>
if name in self.oxm_fields:
return self.oxm_fields[name].id
else:
maybes = difflib.get_close_matches(name, self.oxm_fields)
last_id = self.oxm_fields[self.ordered_oxm_fields[-1]].id
print('Adding field ' + name + ' as ' + str(last_id + 1) ... | The base class describing an OpenFlow version. This contains constants from enums and oxm field information. This also assigns unique ID's to new OXM's seen in a Table Type Pattern using oxm_name_to_id and check_oxm_name. | OpenFlowDescription | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpenFlowDescription:
"""The base class describing an OpenFlow version. This contains constants from enums and oxm field information. This also assigns unique ID's to new OXM's seen in a Table Type Pattern using oxm_name_to_id and check_oxm_name."""
def oxm_name_to_id(self, name):
"""... | stack_v2_sparse_classes_75kplus_train_007430 | 37,012 | permissive | [
{
"docstring": "Takes an OXM name and returns a id number. Note: OXM numbers start at 0 and go up to about 60 name: The field name return: If existing the OXM match id number, otherwise the next free number is allocated and returned. This is logged to stdout.",
"name": "oxm_name_to_id",
"signature": "de... | 4 | stack_v2_sparse_classes_30k_train_041256 | Implement the Python class `OpenFlowDescription` described below.
Class description:
The base class describing an OpenFlow version. This contains constants from enums and oxm field information. This also assigns unique ID's to new OXM's seen in a Table Type Pattern using oxm_name_to_id and check_oxm_name.
Method sign... | Implement the Python class `OpenFlowDescription` described below.
Class description:
The base class describing an OpenFlow version. This contains constants from enums and oxm field information. This also assigns unique ID's to new OXM's seen in a Table Type Pattern using oxm_name_to_id and check_oxm_name.
Method sign... | bbf233a7cdbe0b86d896082fff58088957d063e6 | <|skeleton|>
class OpenFlowDescription:
"""The base class describing an OpenFlow version. This contains constants from enums and oxm field information. This also assigns unique ID's to new OXM's seen in a Table Type Pattern using oxm_name_to_id and check_oxm_name."""
def oxm_name_to_id(self, name):
"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OpenFlowDescription:
"""The base class describing an OpenFlow version. This contains constants from enums and oxm field information. This also assigns unique ID's to new OXM's seen in a Table Type Pattern using oxm_name_to_id and check_oxm_name."""
def oxm_name_to_id(self, name):
"""Takes an OXM ... | the_stack_v2_python_sparse | ofequivalence/openflow_desc.py | wandsdn/ofequivalence | train | 4 |
ee554dc4293d42926a2c638b9567e5448090ac38 | [
"QtGui.QSlider.__init__(self, QtCore.Qt.Horizontal, parent)\nself.setRange(100, 300)\nself.setValue(100)\nself.setTracking(True)\nself.setStatusTip('Zoom in the image')\nself.connect(self, QtCore.SIGNAL('valueChanged(int)'), self.updateZoom)\nself.connect(self, QtCore.SIGNAL('needUpdateStatus'), self.updateStatus)\... | <|body_start_0|>
QtGui.QSlider.__init__(self, QtCore.Qt.Horizontal, parent)
self.setRange(100, 300)
self.setValue(100)
self.setTracking(True)
self.setStatusTip('Zoom in the image')
self.connect(self, QtCore.SIGNAL('valueChanged(int)'), self.updateZoom)
self.connec... | ImageViewerZoomSlider is a slider that allows user to zoom in and out by dragging it | ImageViewerZoomSlider | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageViewerZoomSlider:
"""ImageViewerZoomSlider is a slider that allows user to zoom in and out by dragging it"""
def __init__(self, parent=None):
"""ImageViewerZoomSlider(parent: QWidget) -> ImageViewerZoomSlider Setup the ranges, status tip, etc. of the slider"""
<|body_0|>... | stack_v2_sparse_classes_75kplus_train_007431 | 14,880 | permissive | [
{
"docstring": "ImageViewerZoomSlider(parent: QWidget) -> ImageViewerZoomSlider Setup the ranges, status tip, etc. of the slider",
"name": "__init__",
"signature": "def __init__(self, parent=None)"
},
{
"docstring": "updateZoom(value: int) -> None Update the image when the slider value changed",... | 3 | stack_v2_sparse_classes_30k_train_030762 | Implement the Python class `ImageViewerZoomSlider` described below.
Class description:
ImageViewerZoomSlider is a slider that allows user to zoom in and out by dragging it
Method signatures and docstrings:
- def __init__(self, parent=None): ImageViewerZoomSlider(parent: QWidget) -> ImageViewerZoomSlider Setup the ran... | Implement the Python class `ImageViewerZoomSlider` described below.
Class description:
ImageViewerZoomSlider is a slider that allows user to zoom in and out by dragging it
Method signatures and docstrings:
- def __init__(self, parent=None): ImageViewerZoomSlider(parent: QWidget) -> ImageViewerZoomSlider Setup the ran... | 23ef56ec24b85c82416e1437a08381635328abe5 | <|skeleton|>
class ImageViewerZoomSlider:
"""ImageViewerZoomSlider is a slider that allows user to zoom in and out by dragging it"""
def __init__(self, parent=None):
"""ImageViewerZoomSlider(parent: QWidget) -> ImageViewerZoomSlider Setup the ranges, status tip, etc. of the slider"""
<|body_0|>... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImageViewerZoomSlider:
"""ImageViewerZoomSlider is a slider that allows user to zoom in and out by dragging it"""
def __init__(self, parent=None):
"""ImageViewerZoomSlider(parent: QWidget) -> ImageViewerZoomSlider Setup the ranges, status tip, etc. of the slider"""
QtGui.QSlider.__init__(... | the_stack_v2_python_sparse | vistrails_current/vistrails/packages/spreadsheet/widgets/imageviewer/imageviewer.py | lumig242/VisTrailsRecommendation | train | 3 |
202af4ffaaa0ddb71cc166f873209b1e5af0e0e3 | [
"def dfs(count, target, dp):\n if target in dp:\n return dp[target]\n tar = collections.Counter(target)\n ans = float('inf')\n for c in count:\n if c[target[0]] == 0:\n continue\n nex = []\n for k in tar.keys():\n if tar[k] > c[k]:\n nex.e... | <|body_start_0|>
def dfs(count, target, dp):
if target in dp:
return dp[target]
tar = collections.Counter(target)
ans = float('inf')
for c in count:
if c[target[0]] == 0:
continue
nex = []
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minStickers(self, stickers, target):
""":type stickers: List[str] :type target: str :rtype: int"""
<|body_0|>
def minStickers_(self, stickers, target):
""":type stickers: List[str] :type target: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_75kplus_train_007432 | 3,143 | permissive | [
{
"docstring": ":type stickers: List[str] :type target: str :rtype: int",
"name": "minStickers",
"signature": "def minStickers(self, stickers, target)"
},
{
"docstring": ":type stickers: List[str] :type target: str :rtype: int",
"name": "minStickers_",
"signature": "def minStickers_(self... | 2 | stack_v2_sparse_classes_30k_train_043893 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minStickers(self, stickers, target): :type stickers: List[str] :type target: str :rtype: int
- def minStickers_(self, stickers, target): :type stickers: List[str] :type targe... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minStickers(self, stickers, target): :type stickers: List[str] :type target: str :rtype: int
- def minStickers_(self, stickers, target): :type stickers: List[str] :type targe... | 8168f6058648f2a330a7354daf3a73a4d8a4e730 | <|skeleton|>
class Solution:
def minStickers(self, stickers, target):
""":type stickers: List[str] :type target: str :rtype: int"""
<|body_0|>
def minStickers_(self, stickers, target):
""":type stickers: List[str] :type target: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minStickers(self, stickers, target):
""":type stickers: List[str] :type target: str :rtype: int"""
def dfs(count, target, dp):
if target in dp:
return dp[target]
tar = collections.Counter(target)
ans = float('inf')
f... | the_stack_v2_python_sparse | py/leetcode/StickersWord.py | danyfang/SourceCode | train | 0 | |
259ccd6aa3c8eb5d5caba10cc4dcf3dcc5778c9a | [
"OVBox.__init__(self)\nself.signalHeader = None\nself.client = mqtt.Client('', True, None, mqtt.MQTTv31)\nself.client.connect('localhost', 1883, 60)\nself.player = int(self.setting['Player'])",
"for chunkIndex in range(len(self.input[0])):\n if type(self.input[0][chunkIndex]) == OVStreamedMatrixHeader:\n ... | <|body_start_0|>
OVBox.__init__(self)
self.signalHeader = None
self.client = mqtt.Client('', True, None, mqtt.MQTTv31)
self.client.connect('localhost', 1883, 60)
self.player = int(self.setting['Player'])
<|end_body_0|>
<|body_start_1|>
for chunkIndex in range(len(self.in... | MyOVBox | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyOVBox:
def __init__(self):
"""Creates box and connects to MQTT server"""
<|body_0|>
def process(self):
"""Processes the data chunks read in and outputs them--either within openVibe or to the MQTT server."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_007433 | 2,349 | no_license | [
{
"docstring": "Creates box and connects to MQTT server",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Processes the data chunks read in and outputs them--either within openVibe or to the MQTT server.",
"name": "process",
"signature": "def process(self)"
}
] | 2 | null | Implement the Python class `MyOVBox` described below.
Class description:
Implement the MyOVBox class.
Method signatures and docstrings:
- def __init__(self): Creates box and connects to MQTT server
- def process(self): Processes the data chunks read in and outputs them--either within openVibe or to the MQTT server. | Implement the Python class `MyOVBox` described below.
Class description:
Implement the MyOVBox class.
Method signatures and docstrings:
- def __init__(self): Creates box and connects to MQTT server
- def process(self): Processes the data chunks read in and outputs them--either within openVibe or to the MQTT server.
... | cc9f342cebe53fa4badb0eafefc6fc333138048c | <|skeleton|>
class MyOVBox:
def __init__(self):
"""Creates box and connects to MQTT server"""
<|body_0|>
def process(self):
"""Processes the data chunks read in and outputs them--either within openVibe or to the MQTT server."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyOVBox:
def __init__(self):
"""Creates box and connects to MQTT server"""
OVBox.__init__(self)
self.signalHeader = None
self.client = mqtt.Client('', True, None, mqtt.MQTTv31)
self.client.connect('localhost', 1883, 60)
self.player = int(self.setting['Player'])
... | the_stack_v2_python_sparse | openvibe_scenarios/motor-imagery-CSP/python_scripts/openVibe_mqtt_publisher.py | aubele/bci | train | 0 | |
de001a102497698125f51f0c4d73942ba887043f | [
"fips = False\nif os.name == 'nt':\n reg = winreg.ConnectRegistry(None, HKEY_LOCAL_MACHINE)\n try:\n reg = winreg.OpenKey(reg, 'System\\\\CurrentControlSet\\\\Control\\\\Lsa\\\\FipsAlgorithmPolicy')\n winreg.QueryInfoKey(reg)\n value, _ = winreg.QueryValueEx(reg, 'Enabled')\n if va... | <|body_start_0|>
fips = False
if os.name == 'nt':
reg = winreg.ConnectRegistry(None, HKEY_LOCAL_MACHINE)
try:
reg = winreg.OpenKey(reg, 'System\\CurrentControlSet\\Control\\Lsa\\FipsAlgorithmPolicy')
winreg.QueryInfoKey(reg)
value, ... | Encryption/Decryption object | Encryption | [
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encryption:
"""Encryption/Decryption object"""
def check_fips_mode_os():
"""Function to check for the OS fips mode :param key: string to encrypt with :type key: str. :returns: returns True if FIPS mode is active, False otherwise"""
<|body_0|>
def check_fips_mode_ssl():
... | stack_v2_sparse_classes_75kplus_train_007434 | 31,284 | permissive | [
{
"docstring": "Function to check for the OS fips mode :param key: string to encrypt with :type key: str. :returns: returns True if FIPS mode is active, False otherwise",
"name": "check_fips_mode_os",
"signature": "def check_fips_mode_os()"
},
{
"docstring": "Function to check for the SSL fips m... | 6 | stack_v2_sparse_classes_30k_train_002999 | Implement the Python class `Encryption` described below.
Class description:
Encryption/Decryption object
Method signatures and docstrings:
- def check_fips_mode_os(): Function to check for the OS fips mode :param key: string to encrypt with :type key: str. :returns: returns True if FIPS mode is active, False otherwis... | Implement the Python class `Encryption` described below.
Class description:
Encryption/Decryption object
Method signatures and docstrings:
- def check_fips_mode_os(): Function to check for the OS fips mode :param key: string to encrypt with :type key: str. :returns: returns True if FIPS mode is active, False otherwis... | e3b3129619acf78ffb84f844978cb713d2a1b606 | <|skeleton|>
class Encryption:
"""Encryption/Decryption object"""
def check_fips_mode_os():
"""Function to check for the OS fips mode :param key: string to encrypt with :type key: str. :returns: returns True if FIPS mode is active, False otherwise"""
<|body_0|>
def check_fips_mode_ssl():
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Encryption:
"""Encryption/Decryption object"""
def check_fips_mode_os():
"""Function to check for the OS fips mode :param key: string to encrypt with :type key: str. :returns: returns True if FIPS mode is active, False otherwise"""
fips = False
if os.name == 'nt':
reg ... | the_stack_v2_python_sparse | src/rdmc_helper.py | HewlettPackard/python-redfish-utility | train | 67 |
29bbd03862bdfe491f3fa09a17fb87316dbaa57c | [
"self.current_optim_step = 0\nself.log_save_counter = 0\nself.log_update_counter = 0\nself.seed_id = seed_id\nself.print_every_update = print_every_update if print_every_update is not None else 1\nself.start_time = time.time()\nif isinstance(log_fname, str):\n self.log_save_fname = log_fname\nelse:\n self.log... | <|body_start_0|>
self.current_optim_step = 0
self.log_save_counter = 0
self.log_update_counter = 0
self.seed_id = seed_id
self.print_every_update = print_every_update if print_every_update is not None else 1
self.start_time = time.time()
if isinstance(log_fname, s... | DeepLogger | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeepLogger:
def __init__(self, time_to_track, what_to_track, log_fname=None, network_fname=None, seed_id=0, tboard_fname=None, time_to_print=None, what_to_print=[], save_all_ckpth=False, print_every_update=None):
"""Logging object for Deep RL experiments - Parameters to specify: - Where ... | stack_v2_sparse_classes_75kplus_train_007435 | 6,858 | permissive | [
{
"docstring": "Logging object for Deep RL experiments - Parameters to specify: - Where to log agent (.ckpth) & training stats (.hdf5) to - Random seed & folderpath for tensorboard - Time index & statistics to print & Verbosity level of logger - Whether to save all or only most recent checkpoint of network",
... | 5 | null | Implement the Python class `DeepLogger` described below.
Class description:
Implement the DeepLogger class.
Method signatures and docstrings:
- def __init__(self, time_to_track, what_to_track, log_fname=None, network_fname=None, seed_id=0, tboard_fname=None, time_to_print=None, what_to_print=[], save_all_ckpth=False,... | Implement the Python class `DeepLogger` described below.
Class description:
Implement the DeepLogger class.
Method signatures and docstrings:
- def __init__(self, time_to_track, what_to_track, log_fname=None, network_fname=None, seed_id=0, tboard_fname=None, time_to_print=None, what_to_print=[], save_all_ckpth=False,... | a727390b8668dbf7352759220666548e2d1a0e2d | <|skeleton|>
class DeepLogger:
def __init__(self, time_to_track, what_to_track, log_fname=None, network_fname=None, seed_id=0, tboard_fname=None, time_to_print=None, what_to_print=[], save_all_ckpth=False, print_every_update=None):
"""Logging object for Deep RL experiments - Parameters to specify: - Where ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeepLogger:
def __init__(self, time_to_track, what_to_track, log_fname=None, network_fname=None, seed_id=0, tboard_fname=None, time_to_print=None, what_to_print=[], save_all_ckpth=False, print_every_update=None):
"""Logging object for Deep RL experiments - Parameters to specify: - Where to log agent (... | the_stack_v2_python_sparse | 03_pruning/helpers/logger.py | RobertTLange/code-and-blog | train | 75 | |
1186aaa48d77cc89a5ab15d906e6af2cbde9b74c | [
"if not root:\n return TreeNode(None)\nnode = root\n\ndef rec_reverse_tree(n):\n n.left, n.right = (n.right, n.left)\n if n.left:\n n.left = rec_reverse_tree(n.left)\n if n.right:\n n.right = rec_reverse_tree(n.right)\n return n\nroot = rec_reverse_tree(node)\nreturn root",
"if not ro... | <|body_start_0|>
if not root:
return TreeNode(None)
node = root
def rec_reverse_tree(n):
n.left, n.right = (n.right, n.left)
if n.left:
n.left = rec_reverse_tree(n.left)
if n.right:
n.right = rec_reverse_tree(n.righ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mirrorTree(self, root: TreeNode) -> TreeNode:
"""递归 :param root: :return:"""
<|body_0|>
def mirrorTree(self, root: TreeNode) -> TreeNode:
"""非递归 :param root: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
... | stack_v2_sparse_classes_75kplus_train_007436 | 2,086 | no_license | [
{
"docstring": "递归 :param root: :return:",
"name": "mirrorTree",
"signature": "def mirrorTree(self, root: TreeNode) -> TreeNode"
},
{
"docstring": "非递归 :param root: :return:",
"name": "mirrorTree",
"signature": "def mirrorTree(self, root: TreeNode) -> TreeNode"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mirrorTree(self, root: TreeNode) -> TreeNode: 递归 :param root: :return:
- def mirrorTree(self, root: TreeNode) -> TreeNode: 非递归 :param root: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mirrorTree(self, root: TreeNode) -> TreeNode: 递归 :param root: :return:
- def mirrorTree(self, root: TreeNode) -> TreeNode: 非递归 :param root: :return:
<|skeleton|>
class Solut... | b1680014ce3f55ba952a1e64241c0cbb783cc436 | <|skeleton|>
class Solution:
def mirrorTree(self, root: TreeNode) -> TreeNode:
"""递归 :param root: :return:"""
<|body_0|>
def mirrorTree(self, root: TreeNode) -> TreeNode:
"""非递归 :param root: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def mirrorTree(self, root: TreeNode) -> TreeNode:
"""递归 :param root: :return:"""
if not root:
return TreeNode(None)
node = root
def rec_reverse_tree(n):
n.left, n.right = (n.right, n.left)
if n.left:
n.left = rec_re... | the_stack_v2_python_sparse | 27.py | sun510001/leetcode_jianzhi_offer_2 | train | 0 | |
ff3e3a3373254bb8a5c29f881391c3bae2aab43f | [
"artify_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nartify_socket.connect((host, port))\nreturn artify_socket",
"artify_socket = SocketConnection.open_socket()\nartify_socket.sendall(message.encode())\nartify_socket.close()"
] | <|body_start_0|>
artify_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
artify_socket.connect((host, port))
return artify_socket
<|end_body_0|>
<|body_start_1|>
artify_socket = SocketConnection.open_socket()
artify_socket.sendall(message.encode())
artify_socke... | SocketConnection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SocketConnection:
def open_socket(host=Constants.LOCALHOST, port=Constants.PORT_CORE):
"""Args: host (string): host IP port (int): host port func open socket by host and port and returned socket client. Returns artify_socket (socket): connected client socked."""
<|body_0|>
d... | stack_v2_sparse_classes_75kplus_train_007437 | 1,066 | no_license | [
{
"docstring": "Args: host (string): host IP port (int): host port func open socket by host and port and returned socket client. Returns artify_socket (socket): connected client socked.",
"name": "open_socket",
"signature": "def open_socket(host=Constants.LOCALHOST, port=Constants.PORT_CORE)"
},
{
... | 2 | stack_v2_sparse_classes_30k_test_001396 | Implement the Python class `SocketConnection` described below.
Class description:
Implement the SocketConnection class.
Method signatures and docstrings:
- def open_socket(host=Constants.LOCALHOST, port=Constants.PORT_CORE): Args: host (string): host IP port (int): host port func open socket by host and port and retu... | Implement the Python class `SocketConnection` described below.
Class description:
Implement the SocketConnection class.
Method signatures and docstrings:
- def open_socket(host=Constants.LOCALHOST, port=Constants.PORT_CORE): Args: host (string): host IP port (int): host port func open socket by host and port and retu... | 8ea1de1bfbef03da2b253565cbd74d5b02834b5f | <|skeleton|>
class SocketConnection:
def open_socket(host=Constants.LOCALHOST, port=Constants.PORT_CORE):
"""Args: host (string): host IP port (int): host port func open socket by host and port and returned socket client. Returns artify_socket (socket): connected client socked."""
<|body_0|>
d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SocketConnection:
def open_socket(host=Constants.LOCALHOST, port=Constants.PORT_CORE):
"""Args: host (string): host IP port (int): host port func open socket by host and port and returned socket client. Returns artify_socket (socket): connected client socked."""
artify_socket = socket.socket(s... | the_stack_v2_python_sparse | utils/socket_connect.py | Reennon/ArtifyAPI | train | 2 | |
085234c01a637a1654362cb89262db6fb1e70954 | [
"if self.cleaned_data['repeat_option'] == NO_REPEAT:\n LOG.info('Saving a single training session')\n return [self.new_session()]\nelse:\n sessions = []\n step = 2 if self.cleaned_data['repeat_option'] in (MULTIPLE_BIWEEKLY, UNTIL_BIWEEKLY) else 1\n if self.cleaned_data['repeat_option'] in (MULTIPLE_... | <|body_start_0|>
if self.cleaned_data['repeat_option'] == NO_REPEAT:
LOG.info('Saving a single training session')
return [self.new_session()]
else:
sessions = []
step = 2 if self.cleaned_data['repeat_option'] in (MULTIPLE_BIWEEKLY, UNTIL_BIWEEKLY) else 1
... | A custom form for adding multiple training sessions. | TrainingSessionForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrainingSessionForm:
"""A custom form for adding multiple training sessions."""
def save_training_sessions(self):
"""Save the training sessions specified by the form data."""
<|body_0|>
def new_session(self, week_offset=0):
"""Adds a new training session at the s... | stack_v2_sparse_classes_75kplus_train_007438 | 5,224 | no_license | [
{
"docstring": "Save the training sessions specified by the form data.",
"name": "save_training_sessions",
"signature": "def save_training_sessions(self)"
},
{
"docstring": "Adds a new training session at the specified week offset.",
"name": "new_session",
"signature": "def new_session(s... | 2 | stack_v2_sparse_classes_30k_train_003943 | Implement the Python class `TrainingSessionForm` described below.
Class description:
A custom form for adding multiple training sessions.
Method signatures and docstrings:
- def save_training_sessions(self): Save the training sessions specified by the form data.
- def new_session(self, week_offset=0): Adds a new trai... | Implement the Python class `TrainingSessionForm` described below.
Class description:
A custom form for adding multiple training sessions.
Method signatures and docstrings:
- def save_training_sessions(self): Save the training sessions specified by the form data.
- def new_session(self, week_offset=0): Adds a new trai... | d85aa4522c4ffa603efa9e8625fc7253fb7550b5 | <|skeleton|>
class TrainingSessionForm:
"""A custom form for adding multiple training sessions."""
def save_training_sessions(self):
"""Save the training sessions specified by the form data."""
<|body_0|>
def new_session(self, week_offset=0):
"""Adds a new training session at the s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TrainingSessionForm:
"""A custom form for adding multiple training sessions."""
def save_training_sessions(self):
"""Save the training sessions specified by the form data."""
if self.cleaned_data['repeat_option'] == NO_REPEAT:
LOG.info('Saving a single training session')
... | the_stack_v2_python_sparse | src/training/forms.py | cshc/cshc-web | train | 3 |
7d7a033cbad6da05a444c5f414d15affe894d097 | [
"super(Postnet, self).__init__()\nself.postnet = torch.nn.ModuleList()\nfor layer in range(n_layers - 1):\n ichans = odim if layer == 0 else n_chans\n ochans = odim if layer == n_layers - 1 else n_chans\n if use_batch_norm:\n self.postnet += [torch.nn.Sequential(torch.nn.Conv1d(ichans, ochans, n_fil... | <|body_start_0|>
super(Postnet, self).__init__()
self.postnet = torch.nn.ModuleList()
for layer in range(n_layers - 1):
ichans = odim if layer == 0 else n_chans
ochans = odim if layer == n_layers - 1 else n_chans
if use_batch_norm:
self.postnet... | Postnet module for Spectrogram prediction network. This is a module of Postnet in Spectrogram prediction network, which described in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Postnet predicts refines the predicted Mel-filterbank of the decoder, which helps to compensate the de... | Postnet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Postnet:
"""Postnet module for Spectrogram prediction network. This is a module of Postnet in Spectrogram prediction network, which described in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Postnet predicts refines the predicted Mel-filterbank of the decode... | stack_v2_sparse_classes_75kplus_train_007439 | 24,375 | permissive | [
{
"docstring": "Initialize postnet module. Args: idim (int): Dimension of the inputs. odim (int): Dimension of the outputs. n_layers (int, optional): The number of layers. n_filts (int, optional): The number of filter size. n_units (int, optional): The number of filter channels. use_batch_norm (bool, optional):... | 2 | null | Implement the Python class `Postnet` described below.
Class description:
Postnet module for Spectrogram prediction network. This is a module of Postnet in Spectrogram prediction network, which described in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Postnet predicts refines the... | Implement the Python class `Postnet` described below.
Class description:
Postnet module for Spectrogram prediction network. This is a module of Postnet in Spectrogram prediction network, which described in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Postnet predicts refines the... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class Postnet:
"""Postnet module for Spectrogram prediction network. This is a module of Postnet in Spectrogram prediction network, which described in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Postnet predicts refines the predicted Mel-filterbank of the decode... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Postnet:
"""Postnet module for Spectrogram prediction network. This is a module of Postnet in Spectrogram prediction network, which described in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Postnet predicts refines the predicted Mel-filterbank of the decoder, which help... | the_stack_v2_python_sparse | espnet/nets/pytorch_backend/tacotron2/decoder.py | espnet/espnet | train | 7,242 |
45f0a3e87fd6eb86e552a7f2053132a1b7ce1f48 | [
"if y is None:\n y = x\nsuper(Pixelscale, self).__init__(x, y)",
"x_pixelscale = abs(self.x.to('arcsec/pix'))\ny_pixelscale = abs(self.y.to('arcsec/pix'))\nif not np.isclose(x_pixelscale.value, y_pixelscale.value, rtol=0.001):\n from ...core.tools.logging import log\n log.warning('Averaging the pixelscal... | <|body_start_0|>
if y is None:
y = x
super(Pixelscale, self).__init__(x, y)
<|end_body_0|>
<|body_start_1|>
x_pixelscale = abs(self.x.to('arcsec/pix'))
y_pixelscale = abs(self.y.to('arcsec/pix'))
if not np.isclose(x_pixelscale.value, y_pixelscale.value, rtol=0.001):
... | This class ... | Pixelscale | [
"GPL-1.0-or-later",
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-philippe-de-muyter",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pixelscale:
"""This class ..."""
def __init__(self, x, y=None):
"""The constructor ..."""
<|body_0|>
def average(self):
"""This function ... :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if y is None:
y = x
super(P... | stack_v2_sparse_classes_75kplus_train_007440 | 2,010 | permissive | [
{
"docstring": "The constructor ...",
"name": "__init__",
"signature": "def __init__(self, x, y=None)"
},
{
"docstring": "This function ... :return:",
"name": "average",
"signature": "def average(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_044718 | Implement the Python class `Pixelscale` described below.
Class description:
This class ...
Method signatures and docstrings:
- def __init__(self, x, y=None): The constructor ...
- def average(self): This function ... :return: | Implement the Python class `Pixelscale` described below.
Class description:
This class ...
Method signatures and docstrings:
- def __init__(self, x, y=None): The constructor ...
- def average(self): This function ... :return:
<|skeleton|>
class Pixelscale:
"""This class ..."""
def __init__(self, x, y=None):... | 62b2339beb2eb956565e1605d44d92f934361ad7 | <|skeleton|>
class Pixelscale:
"""This class ..."""
def __init__(self, x, y=None):
"""The constructor ..."""
<|body_0|>
def average(self):
"""This function ... :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Pixelscale:
"""This class ..."""
def __init__(self, x, y=None):
"""The constructor ..."""
if y is None:
y = x
super(Pixelscale, self).__init__(x, y)
def average(self):
"""This function ... :return:"""
x_pixelscale = abs(self.x.to('arcsec/pix'))
... | the_stack_v2_python_sparse | CAAPR/CAAPR_AstroMagic/PTS/pts/magic/basics/pixelscale.py | Stargrazer82301/CAAPR | train | 8 |
ed2e07a76bfac34836053d5b79eaf2386e0fe269 | [
"if output_image_topic is not None:\n self.image_publisher = rospy.Publisher(output_image_topic, ROS_Image, queue_size=10)\nelse:\n self.image_publisher = None\nrospy.Subscriber(input_image_topic, ROS_Image, self.callback)\nself.bridge = ROSBridge()\nself.ID = 0\nself.parser = argparse.ArgumentParser()\nself.... | <|body_start_0|>
if output_image_topic is not None:
self.image_publisher = rospy.Publisher(output_image_topic, ROS_Image, queue_size=10)
else:
self.image_publisher = None
rospy.Subscriber(input_image_topic, ROS_Image, self.callback)
self.bridge = ROSBridge()
... | Synthetic_Data_Generation | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Synthetic_Data_Generation:
def __init__(self, input_image_topic='/usb_cam/image_raw', output_image_topic='/opendr/synthetic_facial_images', device='cuda'):
"""Creates a ROS Node for SyntheticDataGeneration :param input_image_topic: Topic from which we are reading the input image :type in... | stack_v2_sparse_classes_75kplus_train_007441 | 5,315 | permissive | [
{
"docstring": "Creates a ROS Node for SyntheticDataGeneration :param input_image_topic: Topic from which we are reading the input image :type input_image_topic: str :param output_image_topic: Topic to which we are publishing the synthetic facial image (if None, we are not publishing any image) :type output_ima... | 3 | stack_v2_sparse_classes_30k_train_045417 | Implement the Python class `Synthetic_Data_Generation` described below.
Class description:
Implement the Synthetic_Data_Generation class.
Method signatures and docstrings:
- def __init__(self, input_image_topic='/usb_cam/image_raw', output_image_topic='/opendr/synthetic_facial_images', device='cuda'): Creates a ROS N... | Implement the Python class `Synthetic_Data_Generation` described below.
Class description:
Implement the Synthetic_Data_Generation class.
Method signatures and docstrings:
- def __init__(self, input_image_topic='/usb_cam/image_raw', output_image_topic='/opendr/synthetic_facial_images', device='cuda'): Creates a ROS N... | b3d6ce670cdf63469fc5766630eb295d67b3d788 | <|skeleton|>
class Synthetic_Data_Generation:
def __init__(self, input_image_topic='/usb_cam/image_raw', output_image_topic='/opendr/synthetic_facial_images', device='cuda'):
"""Creates a ROS Node for SyntheticDataGeneration :param input_image_topic: Topic from which we are reading the input image :type in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Synthetic_Data_Generation:
def __init__(self, input_image_topic='/usb_cam/image_raw', output_image_topic='/opendr/synthetic_facial_images', device='cuda'):
"""Creates a ROS Node for SyntheticDataGeneration :param input_image_topic: Topic from which we are reading the input image :type input_image_topi... | the_stack_v2_python_sparse | projects/opendr_ws/src/opendr_data_generation/scripts/synthetic_facial_generation_node.py | opendr-eu/opendr | train | 535 | |
8cd95eef8d4912216b8e3d465218eae3182e5d03 | [
"filename = band + '.tif'\nmodis_path = os.path.join(self._modis_dirname, date, filename)\nlandsat_path = os.path.join(self._landsat_dirname, date, filename)\nif date in index['files']:\n n_files = len(index['files'][date]['modis'])\n index['files'][date]['modis'].update({1 + n_files: modis_path})\n index[... | <|body_start_0|>
filename = band + '.tif'
modis_path = os.path.join(self._modis_dirname, date, filename)
landsat_path = os.path.join(self._landsat_dirname, date, filename)
if date in index['files']:
n_files = len(index['files'][date]['modis'])
index['files'][date]... | Extends PatchExport by handling ESTARFM input format | ESTARFMPatchExport | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ESTARFMPatchExport:
"""Extends PatchExport by handling ESTARFM input format"""
def update_index(self, index, date, band):
"""Updates patch directory information index when saving new band file Args: index (dict): patch directory information index date (str): date of file to record fo... | stack_v2_sparse_classes_75kplus_train_007442 | 8,855 | no_license | [
{
"docstring": "Updates patch directory information index when saving new band file Args: index (dict): patch directory information index date (str): date of file to record formatted as yyyy-mm-dd band (str): band corresponding to file to record",
"name": "update_index",
"signature": "def update_index(s... | 2 | null | Implement the Python class `ESTARFMPatchExport` described below.
Class description:
Extends PatchExport by handling ESTARFM input format
Method signatures and docstrings:
- def update_index(self, index, date, band): Updates patch directory information index when saving new band file Args: index (dict): patch director... | Implement the Python class `ESTARFMPatchExport` described below.
Class description:
Extends PatchExport by handling ESTARFM input format
Method signatures and docstrings:
- def update_index(self, index, date, band): Updates patch directory information index when saving new band file Args: index (dict): patch director... | 5519ec2fea784ba20bb37c21b59024a1f47519f6 | <|skeleton|>
class ESTARFMPatchExport:
"""Extends PatchExport by handling ESTARFM input format"""
def update_index(self, index, date, band):
"""Updates patch directory information index when saving new band file Args: index (dict): patch directory information index date (str): date of file to record fo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ESTARFMPatchExport:
"""Extends PatchExport by handling ESTARFM input format"""
def update_index(self, index, date, band):
"""Updates patch directory information index when saving new band file Args: index (dict): patch directory information index date (str): date of file to record formatted as yy... | the_stack_v2_python_sparse | src/prepare_data/preprocessing/ESTARFM/prepare_inputs.py | prhuppertz/ds-generative-reflectance-fusion | train | 0 |
b01ee86713da784565df5495dc388615d25730f1 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.membershipOutlierInsight'.casefold():\n ... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | GovernanceInsight | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GovernanceInsight:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> GovernanceInsight:
"""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... | stack_v2_sparse_classes_75kplus_train_007443 | 3,092 | 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: GovernanceInsight",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_v... | 3 | null | Implement the Python class `GovernanceInsight` described below.
Class description:
Implement the GovernanceInsight class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> GovernanceInsight: Creates a new instance of the appropriate class based on discrim... | Implement the Python class `GovernanceInsight` described below.
Class description:
Implement the GovernanceInsight class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> GovernanceInsight: Creates a new instance of the appropriate class based on discrim... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class GovernanceInsight:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> GovernanceInsight:
"""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... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GovernanceInsight:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> GovernanceInsight:
"""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: Gove... | the_stack_v2_python_sparse | msgraph/generated/models/governance_insight.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
480fb43eb2c50adb1bb25bd230b1db9e14188295 | [
"super(CustomNavbar, self).__init__(**kwargs)\nself.style_classes = []\nself.__css = CSSManager(self)\nself.__background_canvas = CanvasEnabled(self)",
"Window.bind(on_resize=self.resize)\nself.__css.on_load()\nself.__background_canvas.on_load()",
"self.size = (self.parent.width, 50)\nwidget_sizes = 0\ngap_widg... | <|body_start_0|>
super(CustomNavbar, self).__init__(**kwargs)
self.style_classes = []
self.__css = CSSManager(self)
self.__background_canvas = CanvasEnabled(self)
<|end_body_0|>
<|body_start_1|>
Window.bind(on_resize=self.resize)
self.__css.on_load()
self.__backg... | A custom navbar widget for use in any other parent widget. | CustomNavbar | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomNavbar:
"""A custom navbar widget for use in any other parent widget."""
def __init__(self, **kwargs):
"""initialisation for the widget, creating components necessary for it. :param kwargs: Any keyword args to pass back to the parent class."""
<|body_0|>
def on_loa... | stack_v2_sparse_classes_75kplus_train_007444 | 2,275 | no_license | [
{
"docstring": "initialisation for the widget, creating components necessary for it. :param kwargs: Any keyword args to pass back to the parent class.",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Creates necessary bindings and other information that couldn... | 3 | null | Implement the Python class `CustomNavbar` described below.
Class description:
A custom navbar widget for use in any other parent widget.
Method signatures and docstrings:
- def __init__(self, **kwargs): initialisation for the widget, creating components necessary for it. :param kwargs: Any keyword args to pass back t... | Implement the Python class `CustomNavbar` described below.
Class description:
A custom navbar widget for use in any other parent widget.
Method signatures and docstrings:
- def __init__(self, **kwargs): initialisation for the widget, creating components necessary for it. :param kwargs: Any keyword args to pass back t... | fdc3ec61eb7acd7752dd08bbc3961adb7a85388d | <|skeleton|>
class CustomNavbar:
"""A custom navbar widget for use in any other parent widget."""
def __init__(self, **kwargs):
"""initialisation for the widget, creating components necessary for it. :param kwargs: Any keyword args to pass back to the parent class."""
<|body_0|>
def on_loa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomNavbar:
"""A custom navbar widget for use in any other parent widget."""
def __init__(self, **kwargs):
"""initialisation for the widget, creating components necessary for it. :param kwargs: Any keyword args to pass back to the parent class."""
super(CustomNavbar, self).__init__(**kw... | the_stack_v2_python_sparse | rendering/custom_uix/custom_navbar.py | tom-frantz/constellation-4x | train | 0 |
1cf102ba65691ab7052e10c95b24db766096a349 | [
"if not root:\n return ''\nres = ''\nq = deque([(root, 0)])\nwhile len(q) > 0:\n cur_node, cur_idx = q.popleft()\n res += str(cur_idx) + ':' + str(cur_node.val) + ','\n if cur_node.left:\n q.append((cur_node.left, cur_idx * 2 + 1))\n if cur_node.right:\n q.append((cur_node.right, cur_id... | <|body_start_0|>
if not root:
return ''
res = ''
q = deque([(root, 0)])
while len(q) > 0:
cur_node, cur_idx = q.popleft()
res += str(cur_idx) + ':' + str(cur_node.val) + ','
if cur_node.left:
q.append((cur_node.left, cur_idx... | Codec | [
"MIT"
] | 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_007445 | 1,833 | permissive | [
{
"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_026971 | 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:... | fc5b1744af7be93f4dd01d6ad58d2bd12f7ed33f | <|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 ''
res = ''
q = deque([(root, 0)])
while len(q) > 0:
cur_node, cur_idx = q.popleft()
res += str(cur_idx) +... | the_stack_v2_python_sparse | 297.Serialize-and-Deserialize-Binary-Tree.py | mickey0524/leetcode | train | 27 | |
3d2c53cf25c2009f9dcca304a24716382603e727 | [
"assert config.embedding in [50, 100, 200, 300], ''\nassert os.path.isdir(config.filedir), ''\nfilename = 'glove.42B.%s.txt' % (str(config.embedding) + 'd')\nself.targetpath = os.path.join(config.filedir, filename)\nassert os.path.isfile(self.targetpath), ''\nself.config = config",
"print('Loading vocabulary from... | <|body_start_0|>
assert config.embedding in [50, 100, 200, 300], ''
assert os.path.isdir(config.filedir), ''
filename = 'glove.42B.%s.txt' % (str(config.embedding) + 'd')
self.targetpath = os.path.join(config.filedir, filename)
assert os.path.isfile(self.targetpath), ''
s... | Word embedding loading class for glove. | Preprocessor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Preprocessor:
"""Word embedding loading class for glove."""
def __init__(self, config):
"""Loads word embeddings and a vocabulary from a glove txt. Args: config: an instance of Configuration"""
<|body_0|>
def run(self):
"""Computes the vocabulary and the word emb... | stack_v2_sparse_classes_75kplus_train_007446 | 1,924 | permissive | [
{
"docstring": "Loads word embeddings and a vocabulary from a glove txt. Args: config: an instance of Configuration",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Computes the vocabulary and the word embeddings matrix. Outputs: vocab: A vocabulary object usd i... | 2 | stack_v2_sparse_classes_30k_train_049057 | Implement the Python class `Preprocessor` described below.
Class description:
Word embedding loading class for glove.
Method signatures and docstrings:
- def __init__(self, config): Loads word embeddings and a vocabulary from a glove txt. Args: config: an instance of Configuration
- def run(self): Computes the vocabu... | Implement the Python class `Preprocessor` described below.
Class description:
Word embedding loading class for glove.
Method signatures and docstrings:
- def __init__(self, config): Loads word embeddings and a vocabulary from a glove txt. Args: config: an instance of Configuration
- def run(self): Computes the vocabu... | aa0e6eaaaafb47fc3a5d4eb693c8f24e90b8f402 | <|skeleton|>
class Preprocessor:
"""Word embedding loading class for glove."""
def __init__(self, config):
"""Loads word embeddings and a vocabulary from a glove txt. Args: config: an instance of Configuration"""
<|body_0|>
def run(self):
"""Computes the vocabulary and the word emb... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Preprocessor:
"""Word embedding loading class for glove."""
def __init__(self, config):
"""Loads word embeddings and a vocabulary from a glove txt. Args: config: an instance of Configuration"""
assert config.embedding in [50, 100, 200, 300], ''
assert os.path.isdir(config.filedir)... | the_stack_v2_python_sparse | glove/preprocessor.py | buoyancy99/glove | train | 0 |
c76dc4f3c93d23a5a734b0ddd74ea7bc57b7cb59 | [
"subsets = self.subsets(nums)\nresult = []\nfor subset in subsets:\n sorted_subset = sorted(subset)\n if sorted_subset not in result:\n result.append(sorted_subset)\nreturn result",
"length_of_nums = len(nums)\nnumber_of_subarrays = 2 ** length_of_nums\nresult = []\nfor i in range(0, number_of_subarr... | <|body_start_0|>
subsets = self.subsets(nums)
result = []
for subset in subsets:
sorted_subset = sorted(subset)
if sorted_subset not in result:
result.append(sorted_subset)
return result
<|end_body_0|>
<|body_start_1|>
length_of_nums = len... | 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 subsets(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
subsets = self.subsets... | stack_v2_sparse_classes_75kplus_train_007447 | 1,223 | 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": "subsets",
"signature": "def subsets(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_036070 | 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 subsets(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 subsets(self, nums): :type nums: List[int] :rtype: List[List[int]]
<|skeleton|>
class Solutio... | fcf6c3d5d60d13706950247d8a2327adc5faf17e | <|skeleton|>
class Solution:
def subsetsWithDup(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def subsets(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]]"""
subsets = self.subsets(nums)
result = []
for subset in subsets:
sorted_subset = sorted(subset)
if sorted_subset not in result:
result.append(sor... | the_stack_v2_python_sparse | Medium/Subsets2.py | mangalagb/Leetcode | train | 0 | |
909e413eb0b3550304be8723aa3eae5221b607aa | [
"payload = {'token': self._token, 'usergroup': usergroup}\nif include_disabled is not None:\n payload['include_disabled'] = include_disabled\nreturn self._get('usergroups.users.list', payload=payload, **kwargs)",
"if users is not None:\n users = comma_separated_string(users)\npayload = {'token': self._token... | <|body_start_0|>
payload = {'token': self._token, 'usergroup': usergroup}
if include_disabled is not None:
payload['include_disabled'] = include_disabled
return self._get('usergroups.users.list', payload=payload, **kwargs)
<|end_body_0|>
<|body_start_1|>
if users is not None... | Users | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Users:
def list(self, usergroup: str, include_disabled: bool=None, **kwargs) -> Response:
"""List all users in a User Group https://api.slack.com/methods/usergroups.users.list :param token: Authentication token bearing required scopes. :type str: e.g. xxxx-xxxxxxxxx-xxxx :param usergroup... | stack_v2_sparse_classes_75kplus_train_007448 | 14,971 | permissive | [
{
"docstring": "List all users in a User Group https://api.slack.com/methods/usergroups.users.list :param token: Authentication token bearing required scopes. :type str: e.g. xxxx-xxxxxxxxx-xxxx :param usergroup: The encoded ID of the User Group to update. :type str: e.g. S0604QSJC :param include_disabled: Allo... | 2 | null | Implement the Python class `Users` described below.
Class description:
Implement the Users class.
Method signatures and docstrings:
- def list(self, usergroup: str, include_disabled: bool=None, **kwargs) -> Response: List all users in a User Group https://api.slack.com/methods/usergroups.users.list :param token: Auth... | Implement the Python class `Users` described below.
Class description:
Implement the Users class.
Method signatures and docstrings:
- def list(self, usergroup: str, include_disabled: bool=None, **kwargs) -> Response: List all users in a User Group https://api.slack.com/methods/usergroups.users.list :param token: Auth... | c40be4854a26084e1a368a975e220d613c14d8d8 | <|skeleton|>
class Users:
def list(self, usergroup: str, include_disabled: bool=None, **kwargs) -> Response:
"""List all users in a User Group https://api.slack.com/methods/usergroups.users.list :param token: Authentication token bearing required scopes. :type str: e.g. xxxx-xxxxxxxxx-xxxx :param usergroup... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Users:
def list(self, usergroup: str, include_disabled: bool=None, **kwargs) -> Response:
"""List all users in a User Group https://api.slack.com/methods/usergroups.users.list :param token: Authentication token bearing required scopes. :type str: e.g. xxxx-xxxxxxxxx-xxxx :param usergroup: The encoded ... | the_stack_v2_python_sparse | slack_time/methods/usergroups.py | jackwardell/SlackTime | train | 2 | |
4e78b3a554dae0c1a360343783e23e8a7e5cad8e | [
"my_logger.info('create resource')\njsondata = resource.service_template.model\nmy_logger.debug('parse json & get yaml file!!! {}'.format(jsondata))\nuuid = resource.service_template.tracking.tracking_id\nresource_type = resource.service_template.resource.resource_type\nbase_url = pecan.request.application_url\njso... | <|body_start_0|>
my_logger.info('create resource')
jsondata = resource.service_template.model
my_logger.debug('parse json & get yaml file!!! {}'.format(jsondata))
uuid = resource.service_template.tracking.tracking_id
resource_type = resource.service_template.resource.resource_typ... | creatin new resource controller. | CreateNewResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateNewResource:
"""creatin new resource controller."""
def post(self, resource):
"""Handle HTTP POST request. :param Customer (json in request body): :return: result (json format ... {'Cusetomer':{'id':'', 'links':{'own':'how host url'},'created':'1234567890'}} the response will b... | stack_v2_sparse_classes_75kplus_train_007449 | 10,382 | no_license | [
{
"docstring": "Handle HTTP POST request. :param Customer (json in request body): :return: result (json format ... {'Cusetomer':{'id':'', 'links':{'own':'how host url'},'created':'1234567890'}} the response will be 201 created if success :return 409 for conflict :return 400 bad request handle json input",
"... | 3 | stack_v2_sparse_classes_30k_train_047919 | Implement the Python class `CreateNewResource` described below.
Class description:
creatin new resource controller.
Method signatures and docstrings:
- def post(self, resource): Handle HTTP POST request. :param Customer (json in request body): :return: result (json format ... {'Cusetomer':{'id':'', 'links':{'own':'ho... | Implement the Python class `CreateNewResource` described below.
Class description:
creatin new resource controller.
Method signatures and docstrings:
- def post(self, resource): Handle HTTP POST request. :param Customer (json in request body): :return: result (json format ... {'Cusetomer':{'id':'', 'links':{'own':'ho... | 3ea2dcb191d8e41498fe062a79349c9d055224c6 | <|skeleton|>
class CreateNewResource:
"""creatin new resource controller."""
def post(self, resource):
"""Handle HTTP POST request. :param Customer (json in request body): :return: result (json format ... {'Cusetomer':{'id':'', 'links':{'own':'how host url'},'created':'1234567890'}} the response will b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CreateNewResource:
"""creatin new resource controller."""
def post(self, resource):
"""Handle HTTP POST request. :param Customer (json in request body): :return: result (json format ... {'Cusetomer':{'id':'', 'links':{'own':'how host url'},'created':'1234567890'}} the response will be 201 created... | the_stack_v2_python_sparse | orm/services/resource_distributor/rds/controllers/v1/resources/root.py | jq1581/ranger | train | 0 |
e17fac0a067f696c7703ad8d42ee0dfa8a122a8d | [
"assert nums is not None\nif len(nums) == 0:\n return 0\ni = j = 0\nwhile i < len(nums):\n if nums[i] != val:\n nums[j] = nums[i]\n j += 1\n i += 1\nreturn j",
"assert nums is not None\nif len(nums) == 0:\n return 0\ni, j = (0, len(nums) - 1)\nwhile i <= j:\n while i <= j and nums[i] ... | <|body_start_0|>
assert nums is not None
if len(nums) == 0:
return 0
i = j = 0
while i < len(nums):
if nums[i] != val:
nums[j] = nums[i]
j += 1
i += 1
return j
<|end_body_0|>
<|body_start_1|>
assert nums... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeElement_start_start(self, nums, val):
""":type nums: List[int] :type val: int :rtype: int"""
<|body_0|>
def removeElement_start_end(self, nums, val):
""":type nums: List[int] :type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_75kplus_train_007450 | 1,027 | no_license | [
{
"docstring": ":type nums: List[int] :type val: int :rtype: int",
"name": "removeElement_start_start",
"signature": "def removeElement_start_start(self, nums, val)"
},
{
"docstring": ":type nums: List[int] :type val: int :rtype: int",
"name": "removeElement_start_end",
"signature": "def... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElement_start_start(self, nums, val): :type nums: List[int] :type val: int :rtype: int
- def removeElement_start_end(self, nums, val): :type nums: List[int] :type val: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElement_start_start(self, nums, val): :type nums: List[int] :type val: int :rtype: int
- def removeElement_start_end(self, nums, val): :type nums: List[int] :type val: ... | cbe6a7e7f05eccb4f9c5fce8651c0d87e5168516 | <|skeleton|>
class Solution:
def removeElement_start_start(self, nums, val):
""":type nums: List[int] :type val: int :rtype: int"""
<|body_0|>
def removeElement_start_end(self, nums, val):
""":type nums: List[int] :type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def removeElement_start_start(self, nums, val):
""":type nums: List[int] :type val: int :rtype: int"""
assert nums is not None
if len(nums) == 0:
return 0
i = j = 0
while i < len(nums):
if nums[i] != val:
nums[j] = nums[... | the_stack_v2_python_sparse | src/array/leetcode27_RemoveElement.py | apepkuss/Cracking-Leetcode-in-Python | train | 2 | |
e5341a089e25b0b5af0e5aa33f2f23c34bf98832 | [
"self.Wf = np.random.randn(i + h, h)\nself.bf = np.zeros((1, h))\nself.Wu = np.random.randn(i + h, h)\nself.bu = np.zeros((1, h))\nself.Wc = np.random.randn(i + h, h)\nself.bc = np.zeros((1, h))\nself.Wo = np.random.randn(i + h, h)\nself.bo = np.zeros((1, h))\nself.Wy = np.random.randn(h, o)\nself.by = np.zeros((1,... | <|body_start_0|>
self.Wf = np.random.randn(i + h, h)
self.bf = np.zeros((1, h))
self.Wu = np.random.randn(i + h, h)
self.bu = np.zeros((1, h))
self.Wc = np.random.randn(i + h, h)
self.bc = np.zeros((1, h))
self.Wo = np.random.randn(i + h, h)
self.bo = np.z... | This class performs a LSTMCell | LSTMCell | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LSTMCell:
"""This class performs a LSTMCell"""
def __init__(self, i, h, o):
"""All begins here i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs"""
<|body_0|>
def forward(self, h_prev, c_prev, x_t):
... | stack_v2_sparse_classes_75kplus_train_007451 | 2,146 | permissive | [
{
"docstring": "All begins here i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs",
"name": "__init__",
"signature": "def __init__(self, i, h, o)"
},
{
"docstring": "This method calculates de forward prop for one time-step x_t ... | 2 | stack_v2_sparse_classes_30k_train_007643 | Implement the Python class `LSTMCell` described below.
Class description:
This class performs a LSTMCell
Method signatures and docstrings:
- def __init__(self, i, h, o): All begins here i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs
- def forward... | Implement the Python class `LSTMCell` described below.
Class description:
This class performs a LSTMCell
Method signatures and docstrings:
- def __init__(self, i, h, o): All begins here i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs
- def forward... | 58c367f3014919f95157426121093b9fe14d4035 | <|skeleton|>
class LSTMCell:
"""This class performs a LSTMCell"""
def __init__(self, i, h, o):
"""All begins here i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs"""
<|body_0|>
def forward(self, h_prev, c_prev, x_t):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LSTMCell:
"""This class performs a LSTMCell"""
def __init__(self, i, h, o):
"""All begins here i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs"""
self.Wf = np.random.randn(i + h, h)
self.bf = np.zeros((1, h))
... | the_stack_v2_python_sparse | supervised_learning/0x0D-RNNs/3-lstm_cell.py | linkem97/holbertonschool-machine_learning | train | 0 |
8de04dfd1d12abade9dd0d0afd7c2cba678cd986 | [
"if p.val < root.val and q.val < root.val:\n return self.lowestCommonAncestor(root.left, p, q)\nelif p.val > root.val and q.val > root.val:\n return self.lowestCommonAncestor(root.right, p, q)\nelse:\n return root",
"p_val = p.val\nq_val = q.val\nwhile root:\n root_val = root.val\n if p_val < root_... | <|body_start_0|>
if p.val < root.val and q.val < root.val:
return self.lowestCommonAncestor(root.left, p, q)
elif p.val > root.val and q.val > root.val:
return self.lowestCommonAncestor(root.right, p, q)
else:
return root
<|end_body_0|>
<|body_start_1|>
... | Solution | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root, p, q):
"""76ms"""
<|body_0|>
def lowestCommonAncestor2(self, root, p, q):
"""64ms"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if p.val < root.val and q.val < root.val:
return self.lowest... | stack_v2_sparse_classes_75kplus_train_007452 | 1,776 | permissive | [
{
"docstring": "76ms",
"name": "lowestCommonAncestor",
"signature": "def lowestCommonAncestor(self, root, p, q)"
},
{
"docstring": "64ms",
"name": "lowestCommonAncestor2",
"signature": "def lowestCommonAncestor2(self, root, p, q)"
}
] | 2 | stack_v2_sparse_classes_30k_train_033037 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root, p, q): 76ms
- def lowestCommonAncestor2(self, root, p, q): 64ms | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root, p, q): 76ms
- def lowestCommonAncestor2(self, root, p, q): 64ms
<|skeleton|>
class Solution:
def lowestCommonAncestor(self, root, p, q)... | 49a0b03c55d8a702785888d473ef96539265ce9c | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root, p, q):
"""76ms"""
<|body_0|>
def lowestCommonAncestor2(self, root, p, q):
"""64ms"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def lowestCommonAncestor(self, root, p, q):
"""76ms"""
if p.val < root.val and q.val < root.val:
return self.lowestCommonAncestor(root.left, p, q)
elif p.val > root.val and q.val > root.val:
return self.lowestCommonAncestor(root.right, p, q)
el... | the_stack_v2_python_sparse | leetcode/0235_lowest_common_ancestor_of_a_binary_search_tree.py | chaosWsF/Python-Practice | train | 1 | |
00e8a9a223e1f509baa13aba713aa7357cadc767 | [
"if len(train_val_test_ratio) != 3:\n raise ValueError('len(train_val_test_ratio) != 3')\nself.ratios = np.array(list(train_val_test_ratio), dtype=np.float32)\nself.ratios /= sum(self.ratios)",
"poj104 = super(TrainValTestSplitter, self).Split(db)\nwith db.Session() as session:\n total_count = session.query... | <|body_start_0|>
if len(train_val_test_ratio) != 3:
raise ValueError('len(train_val_test_ratio) != 3')
self.ratios = np.array(list(train_val_test_ratio), dtype=np.float32)
self.ratios /= sum(self.ratios)
<|end_body_0|>
<|body_start_1|>
poj104 = super(TrainValTestSplitter, se... | A generator train/val/test splits. | TrainValTestSplitter | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrainValTestSplitter:
"""A generator train/val/test splits."""
def __init__(self, train_val_test_ratio: Tuple[float, float, float]=(3, 1, 1)):
"""Constructor. Args: train_val_test_ratio: A triplet of ratios for the training, validation, and test sets. E.g. with the triplet (3, 1, 1),... | stack_v2_sparse_classes_75kplus_train_007453 | 8,051 | permissive | [
{
"docstring": "Constructor. Args: train_val_test_ratio: A triplet of ratios for the training, validation, and test sets. E.g. with the triplet (3, 1, 1), the training set will be 3/5 of the dataset, and the validation and test sets will each by 1/5 of the dataset.",
"name": "__init__",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_014608 | Implement the Python class `TrainValTestSplitter` described below.
Class description:
A generator train/val/test splits.
Method signatures and docstrings:
- def __init__(self, train_val_test_ratio: Tuple[float, float, float]=(3, 1, 1)): Constructor. Args: train_val_test_ratio: A triplet of ratios for the training, va... | Implement the Python class `TrainValTestSplitter` described below.
Class description:
A generator train/val/test splits.
Method signatures and docstrings:
- def __init__(self, train_val_test_ratio: Tuple[float, float, float]=(3, 1, 1)): Constructor. Args: train_val_test_ratio: A triplet of ratios for the training, va... | cd99d2c5362acd0b24ee224492bb3e8c4d4736fb | <|skeleton|>
class TrainValTestSplitter:
"""A generator train/val/test splits."""
def __init__(self, train_val_test_ratio: Tuple[float, float, float]=(3, 1, 1)):
"""Constructor. Args: train_val_test_ratio: A triplet of ratios for the training, validation, and test sets. E.g. with the triplet (3, 1, 1),... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TrainValTestSplitter:
"""A generator train/val/test splits."""
def __init__(self, train_val_test_ratio: Tuple[float, float, float]=(3, 1, 1)):
"""Constructor. Args: train_val_test_ratio: A triplet of ratios for the training, validation, and test sets. E.g. with the triplet (3, 1, 1), the training... | the_stack_v2_python_sparse | deeplearning/ml4pl/ir/split.py | Zacharias030/ProGraML | train | 0 |
f628ad9e1f15a8022aebd47d1f8c1245f86896f6 | [
"if len(collection) < 1:\n return collection\nif isinstance(collection, dict):\n return sorted(collection.items(), key=lambda x: x[0])\nif isinstance(list(collection)[0], Operation):\n key = lambda x: x.operation_id\nelif isinstance(list(collection)[0], str):\n key = lambda x: SchemaObjects.get(x).name\... | <|body_start_0|>
if len(collection) < 1:
return collection
if isinstance(collection, dict):
return sorted(collection.items(), key=lambda x: x[0])
if isinstance(list(collection)[0], Operation):
key = lambda x: x.operation_id
elif isinstance(list(collect... | SwaggerObject | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SwaggerObject:
def sorted(collection):
"""sorting dict by key, schema-collection by schema-name operations by id"""
<|body_0|>
def get_regular_properties(self, _type, *args, **kwargs):
"""Make table with properties by schema_id :param str _type: :rtype: str"""
... | stack_v2_sparse_classes_75kplus_train_007454 | 4,908 | permissive | [
{
"docstring": "sorting dict by key, schema-collection by schema-name operations by id",
"name": "sorted",
"signature": "def sorted(collection)"
},
{
"docstring": "Make table with properties by schema_id :param str _type: :rtype: str",
"name": "get_regular_properties",
"signature": "def ... | 4 | stack_v2_sparse_classes_30k_train_011404 | Implement the Python class `SwaggerObject` described below.
Class description:
Implement the SwaggerObject class.
Method signatures and docstrings:
- def sorted(collection): sorting dict by key, schema-collection by schema-name operations by id
- def get_regular_properties(self, _type, *args, **kwargs): Make table wi... | Implement the Python class `SwaggerObject` described below.
Class description:
Implement the SwaggerObject class.
Method signatures and docstrings:
- def sorted(collection): sorting dict by key, schema-collection by schema-name operations by id
- def get_regular_properties(self, _type, *args, **kwargs): Make table wi... | 43c22b5d2dc00565b939cc32782cc753d02a8434 | <|skeleton|>
class SwaggerObject:
def sorted(collection):
"""sorting dict by key, schema-collection by schema-name operations by id"""
<|body_0|>
def get_regular_properties(self, _type, *args, **kwargs):
"""Make table with properties by schema_id :param str _type: :rtype: str"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SwaggerObject:
def sorted(collection):
"""sorting dict by key, schema-collection by schema-name operations by id"""
if len(collection) < 1:
return collection
if isinstance(collection, dict):
return sorted(collection.items(), key=lambda x: x[0])
if isinst... | the_stack_v2_python_sparse | swg2rst/utils/rst.py | dborodin836/swagger2rst | train | 0 | |
4a0db914519e4c3858988240b5fd0b57ef3453f6 | [
"for key, val in cls.default.items():\n if key not in roi_data:\n roi_data[key] = val",
"roi_data = {}\nfor fieldname, value in zip(cls.default.keys(), values):\n roi_data[fieldname] = value\nreturn roi_data",
"print('------------------------------------------------------------')\nprint('If there a... | <|body_start_0|>
for key, val in cls.default.items():
if key not in roi_data:
roi_data[key] = val
<|end_body_0|>
<|body_start_1|>
roi_data = {}
for fieldname, value in zip(cls.default.keys(), values):
roi_data[fieldname] = value
return roi_data
<|... | ROI managing routines. Attributes: default (dict): ROI default data in {column: default} format. | ROIManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ROIManager:
"""ROI managing routines. Attributes: default (dict): ROI default data in {column: default} format."""
def add_default(cls, roi_data):
"""Add default for non-existing column of `roi_data`. Args: roi_data (dict): ROI data in {column: value} format."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_007455 | 4,528 | permissive | [
{
"docstring": "Add default for non-existing column of `roi_data`. Args: roi_data (dict): ROI data in {column: value} format.",
"name": "add_default",
"signature": "def add_default(cls, roi_data)"
},
{
"docstring": "Return a `roi_data` with `values` in {column: value} format. Args: values (list)... | 5 | stack_v2_sparse_classes_30k_train_020980 | Implement the Python class `ROIManager` described below.
Class description:
ROI managing routines. Attributes: default (dict): ROI default data in {column: default} format.
Method signatures and docstrings:
- def add_default(cls, roi_data): Add default for non-existing column of `roi_data`. Args: roi_data (dict): ROI... | Implement the Python class `ROIManager` described below.
Class description:
ROI managing routines. Attributes: default (dict): ROI default data in {column: default} format.
Method signatures and docstrings:
- def add_default(cls, roi_data): Add default for non-existing column of `roi_data`. Args: roi_data (dict): ROI... | c80aea96d49aef5ec1d81e97cb07ab5ba68f2f90 | <|skeleton|>
class ROIManager:
"""ROI managing routines. Attributes: default (dict): ROI default data in {column: default} format."""
def add_default(cls, roi_data):
"""Add default for non-existing column of `roi_data`. Args: roi_data (dict): ROI data in {column: value} format."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ROIManager:
"""ROI managing routines. Attributes: default (dict): ROI default data in {column: default} format."""
def add_default(cls, roi_data):
"""Add default for non-existing column of `roi_data`. Args: roi_data (dict): ROI data in {column: value} format."""
for key, val in cls.defaul... | the_stack_v2_python_sparse | babysister/roi_manager.py | tranlethaison/babysister | train | 5 |
a8a6c1d68952704daaa743f5c9df47d31eadfb57 | [
"username = self.cleaned_data['username']\nif User.objects.filter(username=username):\n raise forms.ValidationError('Nombre de usuario ya registrado.')\nreturn username",
"password = self.cleaned_data['password']\npassword2 = self.cleaned_data['password2']\nif password != password2:\n raise forms.Validation... | <|body_start_0|>
username = self.cleaned_data['username']
if User.objects.filter(username=username):
raise forms.ValidationError('Nombre de usuario ya registrado.')
return username
<|end_body_0|>
<|body_start_1|>
password = self.cleaned_data['password']
password2 = s... | RegistroUserForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistroUserForm:
def clean_username(self):
"""Comprueba que no exista un username igual en la db"""
<|body_0|>
def clean_password2(self):
"""Comprueba que password y password2 sean iguales."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
username =... | stack_v2_sparse_classes_75kplus_train_007456 | 47,643 | no_license | [
{
"docstring": "Comprueba que no exista un username igual en la db",
"name": "clean_username",
"signature": "def clean_username(self)"
},
{
"docstring": "Comprueba que password y password2 sean iguales.",
"name": "clean_password2",
"signature": "def clean_password2(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001607 | Implement the Python class `RegistroUserForm` described below.
Class description:
Implement the RegistroUserForm class.
Method signatures and docstrings:
- def clean_username(self): Comprueba que no exista un username igual en la db
- def clean_password2(self): Comprueba que password y password2 sean iguales. | Implement the Python class `RegistroUserForm` described below.
Class description:
Implement the RegistroUserForm class.
Method signatures and docstrings:
- def clean_username(self): Comprueba que no exista un username igual en la db
- def clean_password2(self): Comprueba que password y password2 sean iguales.
<|skel... | 3e3726ec4af1a665aa22360e15a62134333bf853 | <|skeleton|>
class RegistroUserForm:
def clean_username(self):
"""Comprueba que no exista un username igual en la db"""
<|body_0|>
def clean_password2(self):
"""Comprueba que password y password2 sean iguales."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RegistroUserForm:
def clean_username(self):
"""Comprueba que no exista un username igual en la db"""
username = self.cleaned_data['username']
if User.objects.filter(username=username):
raise forms.ValidationError('Nombre de usuario ya registrado.')
return username
... | the_stack_v2_python_sparse | SGMGU/forms.py | marioriguera/egresadosmario | train | 0 | |
29a90953ec86fc54a7506f678cc29c98f572097a | [
"client = switch_to_mobile(REQUIRED_MOBILES[category])\nclient.connect_mobile()\nif reset:\n current_mobile().reset_app()\nreturn client",
"one_key = OneKeyLoginPage()\nif one_key.is_on_this_page():\n return\nguide_page = GuidePage()\nif not guide_page.is_on_the_first_guide_page():\n current_mobile().res... | <|body_start_0|>
client = switch_to_mobile(REQUIRED_MOBILES[category])
client.connect_mobile()
if reset:
current_mobile().reset_app()
return client
<|end_body_0|>
<|body_start_1|>
one_key = OneKeyLoginPage()
if one_key.is_on_this_page():
return
... | 前置条件 | Preconditions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Preconditions:
"""前置条件"""
def select_mobile(category, reset=False):
"""选择手机"""
<|body_0|>
def make_already_in_one_key_login_page():
"""已经进入一键登录页"""
<|body_1|>
def login_by_one_key_login():
"""从一键登录页面登录 :return:"""
<|body_2|>
def ... | stack_v2_sparse_classes_75kplus_train_007457 | 4,416 | no_license | [
{
"docstring": "选择手机",
"name": "select_mobile",
"signature": "def select_mobile(category, reset=False)"
},
{
"docstring": "已经进入一键登录页",
"name": "make_already_in_one_key_login_page",
"signature": "def make_already_in_one_key_login_page()"
},
{
"docstring": "从一键登录页面登录 :return:",
... | 4 | stack_v2_sparse_classes_30k_train_004469 | Implement the Python class `Preconditions` described below.
Class description:
前置条件
Method signatures and docstrings:
- def select_mobile(category, reset=False): 选择手机
- def make_already_in_one_key_login_page(): 已经进入一键登录页
- def login_by_one_key_login(): 从一键登录页面登录 :return:
- def make_already_in_message_page(reset=False... | Implement the Python class `Preconditions` described below.
Class description:
前置条件
Method signatures and docstrings:
- def select_mobile(category, reset=False): 选择手机
- def make_already_in_one_key_login_page(): 已经进入一键登录页
- def login_by_one_key_login(): 从一键登录页面登录 :return:
- def make_already_in_message_page(reset=False... | 543d8e81b086376944bd64ccad7a7b7da48e794d | <|skeleton|>
class Preconditions:
"""前置条件"""
def select_mobile(category, reset=False):
"""选择手机"""
<|body_0|>
def make_already_in_one_key_login_page():
"""已经进入一键登录页"""
<|body_1|>
def login_by_one_key_login():
"""从一键登录页面登录 :return:"""
<|body_2|>
def ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Preconditions:
"""前置条件"""
def select_mobile(category, reset=False):
"""选择手机"""
client = switch_to_mobile(REQUIRED_MOBILES[category])
client.connect_mobile()
if reset:
current_mobile().reset_app()
return client
def make_already_in_one_key_login_page... | the_stack_v2_python_sparse | TestCase/m005_contacts/me_mobilehall.py | TypeLife/appium-unittest | train | 9 |
577b7a1e56e987ebcc1e9e8759a6bfa97aa3de22 | [
"self.__items = []\nself.__capacity = capacity\nself.__head = 0\nself.__tail = 0",
"if self.__tail == self.__capacity:\n if self.__head == 0:\n return False\n else:\n len = self.__tail - self.__head\n for i in range(0, len):\n self.__items[i] = self.__items[self.__head + i]\n... | <|body_start_0|>
self.__items = []
self.__capacity = capacity
self.__head = 0
self.__tail = 0
<|end_body_0|>
<|body_start_1|>
if self.__tail == self.__capacity:
if self.__head == 0:
return False
else:
len = self.__tail - se... | 定义基于数组的队列类。 | ArrayQueue | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArrayQueue:
"""定义基于数组的队列类。"""
def __init__(self, capacity):
"""初始化。"""
<|body_0|>
def enqueue(self, item):
"""入队。"""
<|body_1|>
def dequeue(self):
"""出队。"""
<|body_2|>
def print_all(self):
"""打印队列所有元素。"""
<|body_3... | stack_v2_sparse_classes_75kplus_train_007458 | 1,969 | no_license | [
{
"docstring": "初始化。",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": "入队。",
"name": "enqueue",
"signature": "def enqueue(self, item)"
},
{
"docstring": "出队。",
"name": "dequeue",
"signature": "def dequeue(self)"
},
{
"docstring":... | 4 | stack_v2_sparse_classes_30k_train_053782 | Implement the Python class `ArrayQueue` described below.
Class description:
定义基于数组的队列类。
Method signatures and docstrings:
- def __init__(self, capacity): 初始化。
- def enqueue(self, item): 入队。
- def dequeue(self): 出队。
- def print_all(self): 打印队列所有元素。 | Implement the Python class `ArrayQueue` described below.
Class description:
定义基于数组的队列类。
Method signatures and docstrings:
- def __init__(self, capacity): 初始化。
- def enqueue(self, item): 入队。
- def dequeue(self): 出队。
- def print_all(self): 打印队列所有元素。
<|skeleton|>
class ArrayQueue:
"""定义基于数组的队列类。"""
def __init_... | 5afa5c284b3936374baeb93303f35324fe2a0c9d | <|skeleton|>
class ArrayQueue:
"""定义基于数组的队列类。"""
def __init__(self, capacity):
"""初始化。"""
<|body_0|>
def enqueue(self, item):
"""入队。"""
<|body_1|>
def dequeue(self):
"""出队。"""
<|body_2|>
def print_all(self):
"""打印队列所有元素。"""
<|body_3... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ArrayQueue:
"""定义基于数组的队列类。"""
def __init__(self, capacity):
"""初始化。"""
self.__items = []
self.__capacity = capacity
self.__head = 0
self.__tail = 0
def enqueue(self, item):
"""入队。"""
if self.__tail == self.__capacity:
if self.__head... | the_stack_v2_python_sparse | 04_queue/array_queue.py | suncugb/algorithm | train | 0 |
eb4c5fc86dff7c664005e51d55409b6086e660bf | [
"is_in_time_interval.return_value = (False, datetime(2019, 1, 1, 8, 0, 0))\nsend_message(None)\nretry.assert_called_once_with(eta=datetime(2019, 1, 1, 8, 0, 0))",
"is_in_time_interval.return_value = (True, datetime(2019, 1, 1, 8, 0, 0))\nsend_message(None)\nretry.assert_not_called()"
] | <|body_start_0|>
is_in_time_interval.return_value = (False, datetime(2019, 1, 1, 8, 0, 0))
send_message(None)
retry.assert_called_once_with(eta=datetime(2019, 1, 1, 8, 0, 0))
<|end_body_0|>
<|body_start_1|>
is_in_time_interval.return_value = (True, datetime(2019, 1, 1, 8, 0, 0))
... | SendMessageTests | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SendMessageTests:
def test_retry_outside_of_safe_time(self, is_in_time_interval, retry):
"""If we are outside of the safe sending time, then we should retry"""
<|body_0|>
def test_no_retry_inside_of_safe_time(self, is_in_time_interval, retry):
"""If we are inside the... | stack_v2_sparse_classes_75kplus_train_007459 | 1,224 | permissive | [
{
"docstring": "If we are outside of the safe sending time, then we should retry",
"name": "test_retry_outside_of_safe_time",
"signature": "def test_retry_outside_of_safe_time(self, is_in_time_interval, retry)"
},
{
"docstring": "If we are inside the safe sending time, then we should send the me... | 2 | stack_v2_sparse_classes_30k_train_000818 | Implement the Python class `SendMessageTests` described below.
Class description:
Implement the SendMessageTests class.
Method signatures and docstrings:
- def test_retry_outside_of_safe_time(self, is_in_time_interval, retry): If we are outside of the safe sending time, then we should retry
- def test_no_retry_inside... | Implement the Python class `SendMessageTests` described below.
Class description:
Implement the SendMessageTests class.
Method signatures and docstrings:
- def test_retry_outside_of_safe_time(self, is_in_time_interval, retry): If we are outside of the safe sending time, then we should retry
- def test_no_retry_inside... | d90ef4dc9fa248df97ca97f07569c6c70afcd1bd | <|skeleton|>
class SendMessageTests:
def test_retry_outside_of_safe_time(self, is_in_time_interval, retry):
"""If we are outside of the safe sending time, then we should retry"""
<|body_0|>
def test_no_retry_inside_of_safe_time(self, is_in_time_interval, retry):
"""If we are inside the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SendMessageTests:
def test_retry_outside_of_safe_time(self, is_in_time_interval, retry):
"""If we are outside of the safe sending time, then we should retry"""
is_in_time_interval.return_value = (False, datetime(2019, 1, 1, 8, 0, 0))
send_message(None)
retry.assert_called_once_... | the_stack_v2_python_sparse | message_sender/test_tasks.py | praekeltfoundation/seed-message-sender | train | 0 | |
7f18bf3bf908ffb6956c632d21647ca21b46d53d | [
"self.consoleLogger: bool = app_configuration.log_to_console\nself.fileLogger: bool = app_configuration.log_to_file\nself.libraryLogger: bool = app_configuration.log_library\nself.consoleLevel: str = app_configuration.console_log_level\nself.fileLevel: str = app_configuration.file_log_level\nself.libraryLevel: str ... | <|body_start_0|>
self.consoleLogger: bool = app_configuration.log_to_console
self.fileLogger: bool = app_configuration.log_to_file
self.libraryLogger: bool = app_configuration.log_library
self.consoleLevel: str = app_configuration.console_log_level
self.fileLevel: str = app_confi... | Main abstraction for group of multiple Loggers and logging methods. There should be only one instance of this class in an running Application, multiple instances may cause undefined behavior. | Logger | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Logger:
"""Main abstraction for group of multiple Loggers and logging methods. There should be only one instance of this class in an running Application, multiple instances may cause undefined behavior."""
def __init__(self, *, app_configuration: configClass.Config):
"""Initiates des... | stack_v2_sparse_classes_75kplus_train_007460 | 7,448 | permissive | [
{
"docstring": "Initiates desired loggers based on the app configuration Args: app_configuration (configClass.Config): The app configuration",
"name": "__init__",
"signature": "def __init__(self, *, app_configuration: configClass.Config)"
},
{
"docstring": "Prints debug level message in active l... | 6 | stack_v2_sparse_classes_30k_train_036706 | Implement the Python class `Logger` described below.
Class description:
Main abstraction for group of multiple Loggers and logging methods. There should be only one instance of this class in an running Application, multiple instances may cause undefined behavior.
Method signatures and docstrings:
- def __init__(self,... | Implement the Python class `Logger` described below.
Class description:
Main abstraction for group of multiple Loggers and logging methods. There should be only one instance of this class in an running Application, multiple instances may cause undefined behavior.
Method signatures and docstrings:
- def __init__(self,... | 1a55534e67650dc88fe349f8cc15e4529b26d9c5 | <|skeleton|>
class Logger:
"""Main abstraction for group of multiple Loggers and logging methods. There should be only one instance of this class in an running Application, multiple instances may cause undefined behavior."""
def __init__(self, *, app_configuration: configClass.Config):
"""Initiates des... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Logger:
"""Main abstraction for group of multiple Loggers and logging methods. There should be only one instance of this class in an running Application, multiple instances may cause undefined behavior."""
def __init__(self, *, app_configuration: configClass.Config):
"""Initiates desired loggers ... | the_stack_v2_python_sparse | app/Logging/LoggerCore.py | Critteros/DzwoneczekBOT-old | train | 0 |
7e60399ac0ee75fbbbd27e7ef442eaaed5ef7a20 | [
"video_uuid = uuid.uuid1()\nsession_uuid = uuid.uuid1()\ntry:\n serializer = VideoSerializer(data=request.data, partial=True)\n serializer.is_valid(raise_exception=True)\n serializer.save(video_id=video_uuid, session_id=session_uuid)\n return Response({'status': 'success', 'code': 1}, status.HTTP_200_OK... | <|body_start_0|>
video_uuid = uuid.uuid1()
session_uuid = uuid.uuid1()
try:
serializer = VideoSerializer(data=request.data, partial=True)
serializer.is_valid(raise_exception=True)
serializer.save(video_id=video_uuid, session_id=session_uuid)
return... | Add notifications details and save in DB | Videos | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Videos:
"""Add notifications details and save in DB"""
def post(request):
"""Add appointment to DB"""
<|body_0|>
def put(request):
"""This has been used for ratings"""
<|body_1|>
def notify_staff(all_tokens, message):
"""Send notification to ... | stack_v2_sparse_classes_75kplus_train_007461 | 20,501 | no_license | [
{
"docstring": "Add appointment to DB",
"name": "post",
"signature": "def post(request)"
},
{
"docstring": "This has been used for ratings",
"name": "put",
"signature": "def put(request)"
},
{
"docstring": "Send notification to the doctor",
"name": "notify_staff",
"signat... | 3 | stack_v2_sparse_classes_30k_train_024291 | Implement the Python class `Videos` described below.
Class description:
Add notifications details and save in DB
Method signatures and docstrings:
- def post(request): Add appointment to DB
- def put(request): This has been used for ratings
- def notify_staff(all_tokens, message): Send notification to the doctor | Implement the Python class `Videos` described below.
Class description:
Add notifications details and save in DB
Method signatures and docstrings:
- def post(request): Add appointment to DB
- def put(request): This has been used for ratings
- def notify_staff(all_tokens, message): Send notification to the doctor
<|s... | cb811523f0867a2824a39f1e70e30ed63c57f857 | <|skeleton|>
class Videos:
"""Add notifications details and save in DB"""
def post(request):
"""Add appointment to DB"""
<|body_0|>
def put(request):
"""This has been used for ratings"""
<|body_1|>
def notify_staff(all_tokens, message):
"""Send notification to ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Videos:
"""Add notifications details and save in DB"""
def post(request):
"""Add appointment to DB"""
video_uuid = uuid.uuid1()
session_uuid = uuid.uuid1()
try:
serializer = VideoSerializer(data=request.data, partial=True)
serializer.is_valid(raise_... | the_stack_v2_python_sparse | south_fitness_server/apps/videos/views.py | GransonO/south-fitness | train | 1 |
1be6782d22637109e97bb0f814589f1b5d8d4bcb | [
"tDict = {}\nfor c in set(list(t)):\n tDict[c] = []\ni = 0\nfor c in t:\n tDict[c].append(i)\n i += 1\nlastIndex = -1\nfor c0 in s:\n if c0 in tDict:\n greaterIndex = self.find1StGreater(tDict[c0], lastIndex)\n if greaterIndex == -1:\n return False\n else:\n la... | <|body_start_0|>
tDict = {}
for c in set(list(t)):
tDict[c] = []
i = 0
for c in t:
tDict[c].append(i)
i += 1
lastIndex = -1
for c0 in s:
if c0 in tDict:
greaterIndex = self.find1StGreater(tDict[c0], lastIndex... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSubsequence(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_0|>
def find1StGreater(self, l, target):
"""在有序的列表l中查找第一个大于target的数字 :param l: :param target: :return: 返回结果 找不到返回 -1"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_75kplus_train_007462 | 1,775 | no_license | [
{
"docstring": ":type s: str :type t: str :rtype: bool",
"name": "isSubsequence",
"signature": "def isSubsequence(self, s, t)"
},
{
"docstring": "在有序的列表l中查找第一个大于target的数字 :param l: :param target: :return: 返回结果 找不到返回 -1",
"name": "find1StGreater",
"signature": "def find1StGreater(self, l,... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSubsequence(self, s, t): :type s: str :type t: str :rtype: bool
- def find1StGreater(self, l, target): 在有序的列表l中查找第一个大于target的数字 :param l: :param target: :return: 返回结果 找不到返回... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSubsequence(self, s, t): :type s: str :type t: str :rtype: bool
- def find1StGreater(self, l, target): 在有序的列表l中查找第一个大于target的数字 :param l: :param target: :return: 返回结果 找不到返回... | 7a1c3aba65f338f6e11afd2864dabd2b26142b6c | <|skeleton|>
class Solution:
def isSubsequence(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_0|>
def find1StGreater(self, l, target):
"""在有序的列表l中查找第一个大于target的数字 :param l: :param target: :return: 返回结果 找不到返回 -1"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isSubsequence(self, s, t):
""":type s: str :type t: str :rtype: bool"""
tDict = {}
for c in set(list(t)):
tDict[c] = []
i = 0
for c in t:
tDict[c].append(i)
i += 1
lastIndex = -1
for c0 in s:
... | the_stack_v2_python_sparse | exercise/leetcode/python_src/by2017_Sep/Leet392.py | SS4G/AlgorithmTraining | train | 2 | |
58c365a77cb3a8fbf63ed0bf940313624d084707 | [
"super(Domain, self).__init__(xh)\nself.dg = 0.5 * self.dxh\nreturn",
"self.p = order\nq = polys.Legendre()\nself.zp = q.zeros[order]\nself.wp = q.weights[order]\nb = polys.Lagrange()\nb.interpolate(self.zp, np.ones(self.p))\nself.Lm1 = np.zeros(self.nh * self.p)\nself.Lp1 = np.zeros(self.nh * self.p)\nself.xp = ... | <|body_start_0|>
super(Domain, self).__init__(xh)
self.dg = 0.5 * self.dxh
return
<|end_body_0|>
<|body_start_1|>
self.p = order
q = polys.Legendre()
self.zp = q.zeros[order]
self.wp = q.weights[order]
b = polys.Lagrange()
b.interpolate(self.zp, n... | Domain for a discontinuous galerkin field has attributes for cell vertex and nodal points, quadrature points and weights, cell boundary extrapolation vectors and cell jacobians, and mass matrix | Domain | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Domain:
"""Domain for a discontinuous galerkin field has attributes for cell vertex and nodal points, quadrature points and weights, cell boundary extrapolation vectors and cell jacobians, and mass matrix"""
def __init__(self, xh):
"""initialise Domain with cell vertices and sizes"""... | stack_v2_sparse_classes_75kplus_train_007463 | 4,877 | no_license | [
{
"docstring": "initialise Domain with cell vertices and sizes",
"name": "__init__",
"signature": "def __init__(self, xh)"
},
{
"docstring": "set the expansion basis type and order, and the quadrature point type calculate the physical nodal points, cell jacobians and cell boundary extrapolation ... | 2 | stack_v2_sparse_classes_30k_val_001427 | Implement the Python class `Domain` described below.
Class description:
Domain for a discontinuous galerkin field has attributes for cell vertex and nodal points, quadrature points and weights, cell boundary extrapolation vectors and cell jacobians, and mass matrix
Method signatures and docstrings:
- def __init__(sel... | Implement the Python class `Domain` described below.
Class description:
Domain for a discontinuous galerkin field has attributes for cell vertex and nodal points, quadrature points and weights, cell boundary extrapolation vectors and cell jacobians, and mass matrix
Method signatures and docstrings:
- def __init__(sel... | 35ccd15fce4df144446b84319cf467562a69a44b | <|skeleton|>
class Domain:
"""Domain for a discontinuous galerkin field has attributes for cell vertex and nodal points, quadrature points and weights, cell boundary extrapolation vectors and cell jacobians, and mass matrix"""
def __init__(self, xh):
"""initialise Domain with cell vertices and sizes"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Domain:
"""Domain for a discontinuous galerkin field has attributes for cell vertex and nodal points, quadrature points and weights, cell boundary extrapolation vectors and cell jacobians, and mass matrix"""
def __init__(self, xh):
"""initialise Domain with cell vertices and sizes"""
supe... | the_stack_v2_python_sparse | dg/fields.py | JHopeCollins/Sandbox | train | 0 |
8bb297de5fef72cffafd9d71caadbf9a70af71fc | [
"self.propVal = weakref.ref(propVal)\nself.name = name\nself.function = function\nself.enabled = enabled\nself.immediate = immediate",
"ctxName = self.propVal()._context().__class__.__name__\npvName = self.propVal()._name\nreturn '{} ({}.{})'.format(self.name, ctxName, pvName)"
] | <|body_start_0|>
self.propVal = weakref.ref(propVal)
self.name = name
self.function = function
self.enabled = enabled
self.immediate = immediate
<|end_body_0|>
<|body_start_1|>
ctxName = self.propVal()._context().__class__.__name__
pvName = self.propVal()._name
... | The ``Listener`` class is used by :class:`PropertyValue` instances to manage their listeners - see :meth:`PropertyValue.addListener`. | Listener | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Listener:
"""The ``Listener`` class is used by :class:`PropertyValue` instances to manage their listeners - see :meth:`PropertyValue.addListener`."""
def __init__(self, propVal, name, function, enabled, immediate):
"""Create a ``Listener``. :arg propVal: The ``PropertyValue`` that ow... | stack_v2_sparse_classes_75kplus_train_007464 | 47,104 | permissive | [
{
"docstring": "Create a ``Listener``. :arg propVal: The ``PropertyValue`` that owns this ``Listener``. :arg name: The listener name. :arg function: The callback function. :arg enabled: Whether the listener is enabled/disabled. :arg immediate: Whether the listener is to be called immediately, or via the :attr:`... | 2 | stack_v2_sparse_classes_30k_train_049291 | Implement the Python class `Listener` described below.
Class description:
The ``Listener`` class is used by :class:`PropertyValue` instances to manage their listeners - see :meth:`PropertyValue.addListener`.
Method signatures and docstrings:
- def __init__(self, propVal, name, function, enabled, immediate): Create a ... | Implement the Python class `Listener` described below.
Class description:
The ``Listener`` class is used by :class:`PropertyValue` instances to manage their listeners - see :meth:`PropertyValue.addListener`.
Method signatures and docstrings:
- def __init__(self, propVal, name, function, enabled, immediate): Create a ... | 57c8cf667e4b6879925f6563c1497464892535f2 | <|skeleton|>
class Listener:
"""The ``Listener`` class is used by :class:`PropertyValue` instances to manage their listeners - see :meth:`PropertyValue.addListener`."""
def __init__(self, propVal, name, function, enabled, immediate):
"""Create a ``Listener``. :arg propVal: The ``PropertyValue`` that ow... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Listener:
"""The ``Listener`` class is used by :class:`PropertyValue` instances to manage their listeners - see :meth:`PropertyValue.addListener`."""
def __init__(self, propVal, name, function, enabled, immediate):
"""Create a ``Listener``. :arg propVal: The ``PropertyValue`` that owns this ``Lis... | the_stack_v2_python_sparse | fsleyes_props/properties_value.py | neurodebian/fsleyes-props | train | 0 |
48f4d4713be4414af64900900dcc5ba3e7821ab0 | [
"super().__init__('/proc/{0}/mounts'.format(pid))\nself.mounts = []\nself.read()",
"if not self.content:\n return\nfor line in self.content.split('\\n'):\n tokens = line.split()\n if not tokens:\n continue\n name = None\n mount_point = None\n fs_type = None\n options = None\n if tok... | <|body_start_0|>
super().__init__('/proc/{0}/mounts'.format(pid))
self.mounts = []
self.read()
<|end_body_0|>
<|body_start_1|>
if not self.content:
return
for line in self.content.split('\n'):
tokens = line.split()
if not tokens:
... | Object represents the /proc/mounts file. | ProcMounts | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProcMounts:
"""Object represents the /proc/mounts file."""
def __init__(self, pid):
"""Read file by calling base class constructor then parse the contents."""
<|body_0|>
def read(self):
"""Parses contents of /proc/[pid]/mounts"""
<|body_1|>
def dump(... | stack_v2_sparse_classes_75kplus_train_007465 | 1,558 | permissive | [
{
"docstring": "Read file by calling base class constructor then parse the contents.",
"name": "__init__",
"signature": "def __init__(self, pid)"
},
{
"docstring": "Parses contents of /proc/[pid]/mounts",
"name": "read",
"signature": "def read(self)"
},
{
"docstring": "Print info... | 3 | stack_v2_sparse_classes_30k_train_038675 | Implement the Python class `ProcMounts` described below.
Class description:
Object represents the /proc/mounts file.
Method signatures and docstrings:
- def __init__(self, pid): Read file by calling base class constructor then parse the contents.
- def read(self): Parses contents of /proc/[pid]/mounts
- def dump(self... | Implement the Python class `ProcMounts` described below.
Class description:
Object represents the /proc/mounts file.
Method signatures and docstrings:
- def __init__(self, pid): Read file by calling base class constructor then parse the contents.
- def read(self): Parses contents of /proc/[pid]/mounts
- def dump(self... | 5fc781852dcdf55c3a807e97692224a28c0913f6 | <|skeleton|>
class ProcMounts:
"""Object represents the /proc/mounts file."""
def __init__(self, pid):
"""Read file by calling base class constructor then parse the contents."""
<|body_0|>
def read(self):
"""Parses contents of /proc/[pid]/mounts"""
<|body_1|>
def dump(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProcMounts:
"""Object represents the /proc/mounts file."""
def __init__(self, pid):
"""Read file by calling base class constructor then parse the contents."""
super().__init__('/proc/{0}/mounts'.format(pid))
self.mounts = []
self.read()
def read(self):
"""Pars... | the_stack_v2_python_sparse | proc_scraper/proc_mounts.py | EwanC/pyProc | train | 0 |
331a936ee6ba897fa1ac951b4b4ef9ec3dce09cd | [
"if isinstance(model_or_iterable, ModelBase) and (not admin_class):\n admin_class = ModelAdmin\nif isinstance(model_or_iterable, TopLevelDocumentMetaclass) and (not admin_class):\n admin_class = DocumentAdmin\nvalidate = lambda model, adminclass: None\nif isinstance(model_or_iterable, ModelBase) or isinstance... | <|body_start_0|>
if isinstance(model_or_iterable, ModelBase) and (not admin_class):
admin_class = ModelAdmin
if isinstance(model_or_iterable, TopLevelDocumentMetaclass) and (not admin_class):
admin_class = DocumentAdmin
validate = lambda model, adminclass: None
if... | An AdminSite object encapsulates an instance of the Django admin application, ready to be hooked in to your URLconf. Models are registered with the AdminSite using the register() method, and the get_urls() method can then be used to access Django view functions that present a full admin interface for the collection of ... | MongoAdminSite | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MongoAdminSite:
"""An AdminSite object encapsulates an instance of the Django admin application, ready to be hooked in to your URLconf. Models are registered with the AdminSite using the register() method, and the get_urls() method can then be used to access Django view functions that present a f... | stack_v2_sparse_classes_75kplus_train_007466 | 4,321 | permissive | [
{
"docstring": "Registers the given model(s) with the given admin class. The model(s) should be Model classes, not instances. If an admin class isn't given, it will use ModelAdmin (the default admin options). If keyword arguments are given -- e.g., list_display -- they'll be applied as options to the admin clas... | 2 | null | Implement the Python class `MongoAdminSite` described below.
Class description:
An AdminSite object encapsulates an instance of the Django admin application, ready to be hooked in to your URLconf. Models are registered with the AdminSite using the register() method, and the get_urls() method can then be used to access... | Implement the Python class `MongoAdminSite` described below.
Class description:
An AdminSite object encapsulates an instance of the Django admin application, ready to be hooked in to your URLconf. Models are registered with the AdminSite using the register() method, and the get_urls() method can then be used to access... | bcc2cba4a516cd1ba78421cbab21898182543644 | <|skeleton|>
class MongoAdminSite:
"""An AdminSite object encapsulates an instance of the Django admin application, ready to be hooked in to your URLconf. Models are registered with the AdminSite using the register() method, and the get_urls() method can then be used to access Django view functions that present a f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MongoAdminSite:
"""An AdminSite object encapsulates an instance of the Django admin application, ready to be hooked in to your URLconf. Models are registered with the AdminSite using the register() method, and the get_urls() method can then be used to access Django view functions that present a full admin int... | the_stack_v2_python_sparse | mongoadmin/sites.py | klavdijv/django-mongoadmin | train | 8 |
de19f670f99c36aa3880e8259bda819eae61e713 | [
"ConfigureMake.__init__(self, **kwargs)\nldconfig.__init__(self, **kwargs)\nrm.__init__(self, **kwargs)\ntar.__init__(self, **kwargs)\nwget.__init__(self, **kwargs)\nself.configure_opts = kwargs.get('configure_opts', ['--enable-cxx', '--enable-fortran'])\nself.prefix = kwargs.get('prefix', '/usr/local/hdf5')\nself.... | <|body_start_0|>
ConfigureMake.__init__(self, **kwargs)
ldconfig.__init__(self, **kwargs)
rm.__init__(self, **kwargs)
tar.__init__(self, **kwargs)
wget.__init__(self, **kwargs)
self.configure_opts = kwargs.get('configure_opts', ['--enable-cxx', '--enable-fortran'])
... | The `hdf5` building block downloads, configures, builds, and installs the [HDF5](http://www.hdfgroup.org) component. Depending on the parameters, the source will be downloaded from the web (default) or copied from a source directory in the local build context. As a side effect, this building block modifies `PATH` to in... | hdf5 | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class hdf5:
"""The `hdf5` building block downloads, configures, builds, and installs the [HDF5](http://www.hdfgroup.org) component. Depending on the parameters, the source will be downloaded from the web (default) or copied from a source directory in the local build context. As a side effect, this buil... | stack_v2_sparse_classes_75kplus_train_007467 | 10,505 | permissive | [
{
"docstring": "Initialize building block",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "String representation of the building block",
"name": "__str__",
"signature": "def __str__(self)"
},
{
"docstring": "Based on the Linux distribution, set... | 5 | stack_v2_sparse_classes_30k_val_000012 | Implement the Python class `hdf5` described below.
Class description:
The `hdf5` building block downloads, configures, builds, and installs the [HDF5](http://www.hdfgroup.org) component. Depending on the parameters, the source will be downloaded from the web (default) or copied from a source directory in the local bui... | Implement the Python class `hdf5` described below.
Class description:
The `hdf5` building block downloads, configures, builds, and installs the [HDF5](http://www.hdfgroup.org) component. Depending on the parameters, the source will be downloaded from the web (default) or copied from a source directory in the local bui... | 555093c0a5c98bd2b0114831b8c676c0c3c50dd7 | <|skeleton|>
class hdf5:
"""The `hdf5` building block downloads, configures, builds, and installs the [HDF5](http://www.hdfgroup.org) component. Depending on the parameters, the source will be downloaded from the web (default) or copied from a source directory in the local build context. As a side effect, this buil... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class hdf5:
"""The `hdf5` building block downloads, configures, builds, and installs the [HDF5](http://www.hdfgroup.org) component. Depending on the parameters, the source will be downloaded from the web (default) or copied from a source directory in the local build context. As a side effect, this building block mo... | the_stack_v2_python_sparse | hpccm/building_blocks/hdf5.py | DalavanCloud/hpc-container-maker | train | 1 |
6556a282de99381da54a0a9409e1e38689de1888 | [
"name = 'pie'\nreq = ['x', 'y']\nopt = []\nsuper().__init__(name, req, opt, **kwargs)\nvals = ['twin_x', 'twin_y']\nfor val in vals:\n if getattr(self, val):\n raise data.AxisError(f'{val} is not a valid option for pie charts')\nif self.row == 'y':\n raise data.GroupingError('Cannot group row by \"y\" ... | <|body_start_0|>
name = 'pie'
req = ['x', 'y']
opt = []
super().__init__(name, req, opt, **kwargs)
vals = ['twin_x', 'twin_y']
for val in vals:
if getattr(self, val):
raise data.AxisError(f'{val} is not a valid option for pie charts')
i... | Pie | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pie:
def __init__(self, **kwargs):
"""Pie-specific Data class to deal with operations applied to the input data (i.e., non-plotting operations) Args: kwargs: user-defined keyword args"""
<|body_0|>
def _get_data_ranges(self):
"""Pie-specific data range calculator by ... | stack_v2_sparse_classes_75kplus_train_007468 | 2,746 | no_license | [
{
"docstring": "Pie-specific Data class to deal with operations applied to the input data (i.e., non-plotting operations) Args: kwargs: user-defined keyword args",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Pie-specific data range calculator by subplot.",
... | 3 | stack_v2_sparse_classes_30k_train_040279 | Implement the Python class `Pie` described below.
Class description:
Implement the Pie class.
Method signatures and docstrings:
- def __init__(self, **kwargs): Pie-specific Data class to deal with operations applied to the input data (i.e., non-plotting operations) Args: kwargs: user-defined keyword args
- def _get_d... | Implement the Python class `Pie` described below.
Class description:
Implement the Pie class.
Method signatures and docstrings:
- def __init__(self, **kwargs): Pie-specific Data class to deal with operations applied to the input data (i.e., non-plotting operations) Args: kwargs: user-defined keyword args
- def _get_d... | c76ffdba1aef1837a0ca360bf3733b185148d5b5 | <|skeleton|>
class Pie:
def __init__(self, **kwargs):
"""Pie-specific Data class to deal with operations applied to the input data (i.e., non-plotting operations) Args: kwargs: user-defined keyword args"""
<|body_0|>
def _get_data_ranges(self):
"""Pie-specific data range calculator by ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Pie:
def __init__(self, **kwargs):
"""Pie-specific Data class to deal with operations applied to the input data (i.e., non-plotting operations) Args: kwargs: user-defined keyword args"""
name = 'pie'
req = ['x', 'y']
opt = []
super().__init__(name, req, opt, **kwargs)
... | the_stack_v2_python_sparse | src/fivecentplots/data/pie.py | endangeredoxen/fivecentplots | train | 11 | |
a65f5eb388f1eaac2f09ffe75f853e44ea037886 | [
"self.dir_list = dir_list\nself.frequencies = [{}, {}]\nself.stop_words = readLines(CONFIG_DIR + '/stop_words_new.cfg')\nself.filenames = [FEATURE_DIR + '/total_words_bow.txt', FEATURE_DIR + '/word_docs_bow.txt']",
"for word in words:\n count = 0\n if word in self.stop_words:\n continue\n if self.... | <|body_start_0|>
self.dir_list = dir_list
self.frequencies = [{}, {}]
self.stop_words = readLines(CONFIG_DIR + '/stop_words_new.cfg')
self.filenames = [FEATURE_DIR + '/total_words_bow.txt', FEATURE_DIR + '/word_docs_bow.txt']
<|end_body_0|>
<|body_start_1|>
for word in words:
... | Class to calculate the frequencies of words. | Frequency_Counter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Frequency_Counter:
"""Class to calculate the frequencies of words."""
def __init__(self, dir_list):
"""Initialize the Frequency_Counter class."""
<|body_0|>
def add_to_freq(self, words, index):
"""Adds the words to the frequency counts."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_007469 | 2,967 | no_license | [
{
"docstring": "Initialize the Frequency_Counter class.",
"name": "__init__",
"signature": "def __init__(self, dir_list)"
},
{
"docstring": "Adds the words to the frequency counts.",
"name": "add_to_freq",
"signature": "def add_to_freq(self, words, index)"
},
{
"docstring": "Pars... | 5 | stack_v2_sparse_classes_30k_train_016212 | Implement the Python class `Frequency_Counter` described below.
Class description:
Class to calculate the frequencies of words.
Method signatures and docstrings:
- def __init__(self, dir_list): Initialize the Frequency_Counter class.
- def add_to_freq(self, words, index): Adds the words to the frequency counts.
- def... | Implement the Python class `Frequency_Counter` described below.
Class description:
Class to calculate the frequencies of words.
Method signatures and docstrings:
- def __init__(self, dir_list): Initialize the Frequency_Counter class.
- def add_to_freq(self, words, index): Adds the words to the frequency counts.
- def... | cbbfc2ee034c1b5c67e8f10286b435c6d1ec80e7 | <|skeleton|>
class Frequency_Counter:
"""Class to calculate the frequencies of words."""
def __init__(self, dir_list):
"""Initialize the Frequency_Counter class."""
<|body_0|>
def add_to_freq(self, words, index):
"""Adds the words to the frequency counts."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Frequency_Counter:
"""Class to calculate the frequencies of words."""
def __init__(self, dir_list):
"""Initialize the Frequency_Counter class."""
self.dir_list = dir_list
self.frequencies = [{}, {}]
self.stop_words = readLines(CONFIG_DIR + '/stop_words_new.cfg')
se... | the_stack_v2_python_sparse | src/form_BOW.py | manishc1/DySeCor | train | 0 |
5683ea367f1d58dbc71905e15feb03a857150403 | [
"def dfs(left, right, item, ans):\n if right < left:\n return\n if left == 0 and right == 0:\n ans.append(item)\n if left > 0:\n dfs(left - 1, right, item + '(', ans)\n if right > 0:\n dfs(left, right - 1, item + ')', ans)\nans = []\ndfs(n, n, '', ans)\nreturn ans",
"def ad... | <|body_start_0|>
def dfs(left, right, item, ans):
if right < left:
return
if left == 0 and right == 0:
ans.append(item)
if left > 0:
dfs(left - 1, right, item + '(', ans)
if right > 0:
dfs(left, right... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def generateParenthesis(self, n):
""":type n: int :rtype: List[str]"""
<|body_0|>
def generateParenthesis2(self, n):
""":type n: int :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def dfs(left, right, item, ans):
... | stack_v2_sparse_classes_75kplus_train_007470 | 1,531 | no_license | [
{
"docstring": ":type n: int :rtype: List[str]",
"name": "generateParenthesis",
"signature": "def generateParenthesis(self, n)"
},
{
"docstring": ":type n: int :rtype: List[str]",
"name": "generateParenthesis2",
"signature": "def generateParenthesis2(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis(self, n): :type n: int :rtype: List[str]
- def generateParenthesis2(self, n): :type n: int :rtype: List[str] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis(self, n): :type n: int :rtype: List[str]
- def generateParenthesis2(self, n): :type n: int :rtype: List[str]
<|skeleton|>
class Solution:
def genera... | 2d5fa4cd696d5035ea8859befeadc5cc436959c9 | <|skeleton|>
class Solution:
def generateParenthesis(self, n):
""":type n: int :rtype: List[str]"""
<|body_0|>
def generateParenthesis2(self, n):
""":type n: int :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def generateParenthesis(self, n):
""":type n: int :rtype: List[str]"""
def dfs(left, right, item, ans):
if right < left:
return
if left == 0 and right == 0:
ans.append(item)
if left > 0:
dfs(left - 1,... | the_stack_v2_python_sparse | SourceCode/Python/Problem/00022.Generate Parentheses.py | roger6blog/LeetCode | train | 0 | |
e7c5b8207d45c3708ccade8e6a49532a0c207425 | [
"def dfs(i):\n for j in range(self.m):\n if M[i][j] == 1 and (not visited[j]):\n visited[j] = 1\n dfs(j)\nres = 0\nself.m, self.n = (len(M), len(M[0]))\nvisited = [0] * self.n\nfor i in range(self.m):\n for j in range(self.n):\n if not visited[i]:\n dfs(i)\n ... | <|body_start_0|>
def dfs(i):
for j in range(self.m):
if M[i][j] == 1 and (not visited[j]):
visited[j] = 1
dfs(j)
res = 0
self.m, self.n = (len(M), len(M[0]))
visited = [0] * self.n
for i in range(self.m):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findCircleNum(self, M):
""":type M: List[List[int]] :rtype: int"""
<|body_0|>
def findCircleNum_union_found(self, M):
""":type M: List[List[int]] :rtype: int [-1, 0, 1] 0, 1, 2"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def dfs(i)... | stack_v2_sparse_classes_75kplus_train_007471 | 2,383 | no_license | [
{
"docstring": ":type M: List[List[int]] :rtype: int",
"name": "findCircleNum",
"signature": "def findCircleNum(self, M)"
},
{
"docstring": ":type M: List[List[int]] :rtype: int [-1, 0, 1] 0, 1, 2",
"name": "findCircleNum_union_found",
"signature": "def findCircleNum_union_found(self, M)... | 2 | stack_v2_sparse_classes_30k_train_032445 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findCircleNum(self, M): :type M: List[List[int]] :rtype: int
- def findCircleNum_union_found(self, M): :type M: List[List[int]] :rtype: int [-1, 0, 1] 0, 1, 2 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findCircleNum(self, M): :type M: List[List[int]] :rtype: int
- def findCircleNum_union_found(self, M): :type M: List[List[int]] :rtype: int [-1, 0, 1] 0, 1, 2
<|skeleton|>
c... | 2e1751263f484709102f7f2caf18776a004c8230 | <|skeleton|>
class Solution:
def findCircleNum(self, M):
""":type M: List[List[int]] :rtype: int"""
<|body_0|>
def findCircleNum_union_found(self, M):
""":type M: List[List[int]] :rtype: int [-1, 0, 1] 0, 1, 2"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findCircleNum(self, M):
""":type M: List[List[int]] :rtype: int"""
def dfs(i):
for j in range(self.m):
if M[i][j] == 1 and (not visited[j]):
visited[j] = 1
dfs(j)
res = 0
self.m, self.n = (len(M),... | the_stack_v2_python_sparse | Python/Leetcode Daily Practice/Graph/547. Friend Circles.py | YaqianQi/Algorithm-and-Data-Structure | train | 1 | |
e24f4bd82ef3a1275d28fb5af427dc9d27c225ce | [
"self.endline = '\\n'\nself.host = host\nself.port = port\nself.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nself.sock.connect((host, port))\nself.current_data = 0\nself.current_image = 0\nself.is_new_data = False",
"total_data = []\nwhile True:\n data = self.sock.recv(65536)\n data = data.deco... | <|body_start_0|>
self.endline = '\n'
self.host = host
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((host, port))
self.current_data = 0
self.current_image = 0
self.is_new_data = False
<|end_body_0|>
<|bod... | Class which receives data from VideoCamera by built-in 'socket' interface, decodes it from json, utf-8 and base64 and makes it available for user | VideoCameraServer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VideoCameraServer:
"""Class which receives data from VideoCamera by built-in 'socket' interface, decodes it from json, utf-8 and base64 and makes it available for user"""
def __init__(self, host, port):
"""Initializes socket and opens data stream. :param host: address of a streaming ... | stack_v2_sparse_classes_75kplus_train_007472 | 6,070 | permissive | [
{
"docstring": "Initializes socket and opens data stream. :param host: address of a streaming socket :param port: port on which is the stream",
"name": "__init__",
"signature": "def __init__(self, host, port)"
},
{
"docstring": "This method is used to obtain only one object from socket. Sometime... | 6 | stack_v2_sparse_classes_30k_train_036410 | Implement the Python class `VideoCameraServer` described below.
Class description:
Class which receives data from VideoCamera by built-in 'socket' interface, decodes it from json, utf-8 and base64 and makes it available for user
Method signatures and docstrings:
- def __init__(self, host, port): Initializes socket an... | Implement the Python class `VideoCameraServer` described below.
Class description:
Class which receives data from VideoCamera by built-in 'socket' interface, decodes it from json, utf-8 and base64 and makes it available for user
Method signatures and docstrings:
- def __init__(self, host, port): Initializes socket an... | 7115f55799d9a81fdb214e20c4cdd8520dceb48e | <|skeleton|>
class VideoCameraServer:
"""Class which receives data from VideoCamera by built-in 'socket' interface, decodes it from json, utf-8 and base64 and makes it available for user"""
def __init__(self, host, port):
"""Initializes socket and opens data stream. :param host: address of a streaming ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VideoCameraServer:
"""Class which receives data from VideoCamera by built-in 'socket' interface, decodes it from json, utf-8 and base64 and makes it available for user"""
def __init__(self, host, port):
"""Initializes socket and opens data stream. :param host: address of a streaming socket :param... | the_stack_v2_python_sparse | MORSEProject/classes/video_camera_server.py | Kecz/MORSE-SLAM | train | 2 |
387f0a7814df9261ab6bfae52275aa67f158553c | [
"self.l_du_cupons = l_du_cupons\nself.f_maturity = f_maturity\nf_cupon = ((1.0 + 0.1) ** 0.5 - 1.0) * 1000.0\nsuper(NTN_F, self).__init__(1000.0, f_maturity, f_cupon)\nself.node_step = None\nself.node_maturity = None",
"if f_maturity in self.l_du_cupons:\n return (self.f_cupon, f_value)\nreturn (0.0, f_value)"... | <|body_start_0|>
self.l_du_cupons = l_du_cupons
self.f_maturity = f_maturity
f_cupon = ((1.0 + 0.1) ** 0.5 - 1.0) * 1000.0
super(NTN_F, self).__init__(1000.0, f_maturity, f_cupon)
self.node_step = None
self.node_maturity = None
<|end_body_0|>
<|body_start_1|>
if ... | A NTN-F representation. This Bond pays semestral cupons of 10 percent per year and has a face value of 1,000 | NTN_F | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NTN_F:
"""A NTN-F representation. This Bond pays semestral cupons of 10 percent per year and has a face value of 1,000"""
def __init__(self, f_maturity, l_du_cupons):
"""Initiate a NTN_F object. Save all parameters as attributes :param f_maturity: float. the maturiry of the bond expr... | stack_v2_sparse_classes_75kplus_train_007473 | 11,810 | permissive | [
{
"docstring": "Initiate a NTN_F object. Save all parameters as attributes :param f_maturity: float. the maturiry of the bond expressed in years :param l_du_cupons: list. business days for the payment of each cupon",
"name": "__init__",
"signature": "def __init__(self, f_maturity, l_du_cupons)"
},
{... | 2 | stack_v2_sparse_classes_30k_train_018370 | Implement the Python class `NTN_F` described below.
Class description:
A NTN-F representation. This Bond pays semestral cupons of 10 percent per year and has a face value of 1,000
Method signatures and docstrings:
- def __init__(self, f_maturity, l_du_cupons): Initiate a NTN_F object. Save all parameters as attribute... | Implement the Python class `NTN_F` described below.
Class description:
A NTN-F representation. This Bond pays semestral cupons of 10 percent per year and has a face value of 1,000
Method signatures and docstrings:
- def __init__(self, f_maturity, l_du_cupons): Initiate a NTN_F object. Save all parameters as attribute... | 3da761d755278d3d2de8c201b56d4ff9cb23def4 | <|skeleton|>
class NTN_F:
"""A NTN-F representation. This Bond pays semestral cupons of 10 percent per year and has a face value of 1,000"""
def __init__(self, f_maturity, l_du_cupons):
"""Initiate a NTN_F object. Save all parameters as attributes :param f_maturity: float. the maturiry of the bond expr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NTN_F:
"""A NTN-F representation. This Bond pays semestral cupons of 10 percent per year and has a face value of 1,000"""
def __init__(self, f_maturity, l_du_cupons):
"""Initiate a NTN_F object. Save all parameters as attributes :param f_maturity: float. the maturiry of the bond expressed in year... | the_stack_v2_python_sparse | shortRate/kwf_model/instruments.py | ShubraChowdhury/Investment_Finance | train | 2 |
34299128c5f55529f624d67d693a33a74200849c | [
"self.org_name = org_name\nself.org_version = org_version\nself.org_arr = re.split('\\\\s', org_name)\nself.species = '{} {}'.format(self.org_arr[0], self.org_arr[1])\nself.strain = ''\nif len(self.org_arr) > 2:\n self.strain = ' '.join(self.org_arr[2:])",
"org = re.split('\\\\s+', self.org_name)\nif len(org) ... | <|body_start_0|>
self.org_name = org_name
self.org_version = org_version
self.org_arr = re.split('\\s', org_name)
self.species = '{} {}'.format(self.org_arr[0], self.org_arr[1])
self.strain = ''
if len(self.org_arr) > 2:
self.strain = ' '.join(self.org_arr[2:]... | OrganismName | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrganismName:
def __init__(self, org_name, org_version=1):
"""class constructor for the Organism name parameters ------------- org_name: str Full name of the organism org_version: str Version string"""
<|body_0|>
def prefix(self):
"""Returns the organism prefix Retur... | stack_v2_sparse_classes_75kplus_train_007474 | 16,717 | permissive | [
{
"docstring": "class constructor for the Organism name parameters ------------- org_name: str Full name of the organism org_version: str Version string",
"name": "__init__",
"signature": "def __init__(self, org_name, org_version=1)"
},
{
"docstring": "Returns the organism prefix Returns -------... | 3 | stack_v2_sparse_classes_30k_train_030542 | Implement the Python class `OrganismName` described below.
Class description:
Implement the OrganismName class.
Method signatures and docstrings:
- def __init__(self, org_name, org_version=1): class constructor for the Organism name parameters ------------- org_name: str Full name of the organism org_version: str Ver... | Implement the Python class `OrganismName` described below.
Class description:
Implement the OrganismName class.
Method signatures and docstrings:
- def __init__(self, org_name, org_version=1): class constructor for the Organism name parameters ------------- org_name: str Full name of the organism org_version: str Ver... | 54181f04cca42b45bef0fa3f1e062e2bc70b6016 | <|skeleton|>
class OrganismName:
def __init__(self, org_name, org_version=1):
"""class constructor for the Organism name parameters ------------- org_name: str Full name of the organism org_version: str Version string"""
<|body_0|>
def prefix(self):
"""Returns the organism prefix Retur... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OrganismName:
def __init__(self, org_name, org_version=1):
"""class constructor for the Organism name parameters ------------- org_name: str Full name of the organism org_version: str Version string"""
self.org_name = org_name
self.org_version = org_version
self.org_arr = re.sp... | the_stack_v2_python_sparse | galEupy/taxomony.py | computational-genomics-lab/GAL | train | 3 | |
4c96e1ca68077afae95f025db6231141acee8279 | [
"a = Announcement(title, post_date, message=message)\ntry:\n add_and_commit(a)\nexcept Exception as e:\n DB.session.rollback()\n LOG.exception(e)\n abort(500, message='Internal server error')\nreturn {'status': 'success'}",
"a = Announcement.query.get((title, post_date))\nif a is None:\n abort(404,... | <|body_start_0|>
a = Announcement(title, post_date, message=message)
try:
add_and_commit(a)
except Exception as e:
DB.session.rollback()
LOG.exception(e)
abort(500, message='Internal server error')
return {'status': 'success'}
<|end_body_0|... | Endpoints for registering a user or retrieving registered user(s). | SingleAnnouncement | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingleAnnouncement:
"""Endpoints for registering a user or retrieving registered user(s)."""
def post(self, uid, token, title, post_date, message):
"""Creates an announcement. :param uid: UID to authenticate as :type uid: string :param token: token (really a password) for the given U... | stack_v2_sparse_classes_75kplus_train_007475 | 3,726 | no_license | [
{
"docstring": "Creates an announcement. :param uid: UID to authenticate as :type uid: string :param token: token (really a password) for the given UID :type token: string :param title: title of the announcement :type title: string :param post_date: When the announcement was submitted. In format of 'yyyy-mm-ddT... | 2 | stack_v2_sparse_classes_30k_train_014851 | Implement the Python class `SingleAnnouncement` described below.
Class description:
Endpoints for registering a user or retrieving registered user(s).
Method signatures and docstrings:
- def post(self, uid, token, title, post_date, message): Creates an announcement. :param uid: UID to authenticate as :type uid: strin... | Implement the Python class `SingleAnnouncement` described below.
Class description:
Endpoints for registering a user or retrieving registered user(s).
Method signatures and docstrings:
- def post(self, uid, token, title, post_date, message): Creates an announcement. :param uid: UID to authenticate as :type uid: strin... | ba8618a0c5a1969f73f9fa98544695d1bde09a82 | <|skeleton|>
class SingleAnnouncement:
"""Endpoints for registering a user or retrieving registered user(s)."""
def post(self, uid, token, title, post_date, message):
"""Creates an announcement. :param uid: UID to authenticate as :type uid: string :param token: token (really a password) for the given U... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SingleAnnouncement:
"""Endpoints for registering a user or retrieving registered user(s)."""
def post(self, uid, token, title, post_date, message):
"""Creates an announcement. :param uid: UID to authenticate as :type uid: string :param token: token (really a password) for the given UID :type toke... | the_stack_v2_python_sparse | services/registration/src/api/announcement.py | CruzHacks/cruzhacks-2019-registration-service | train | 0 |
1ed6f6ebaf50dd47907e522771e3872531561d76 | [
"super().__init__(*args, **kwargs)\nself.learning_rate: float = learning_rate\nself.discount_rate: float = discount_rate\nself.trace: float = 0",
"current_transition = self.trajectory[-1]\ncurrent_value: Value = self.state_values[current_transition.state]\ncurrent_value.count += 1",
"n = len(self.trajectory)\nd... | <|body_start_0|>
super().__init__(*args, **kwargs)
self.learning_rate: float = learning_rate
self.discount_rate: float = discount_rate
self.trace: float = 0
<|end_body_0|>
<|body_start_1|>
current_transition = self.trajectory[-1]
current_value: Value = self.state_values[... | Applies the temporal difference one algorithm as a learning algorithm Vt+1(s) = Vt(s) + alpha * (Gt - Vt(s)) Where alpha is the learning rate and Gt is the sum of accumulated and discounted rewards for the episode. Learns at the end of the episode from the trajectory it took after it is reset. | TemporalDifferenceOne | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TemporalDifferenceOne:
"""Applies the temporal difference one algorithm as a learning algorithm Vt+1(s) = Vt(s) + alpha * (Gt - Vt(s)) Where alpha is the learning rate and Gt is the sum of accumulated and discounted rewards for the episode. Learns at the end of the episode from the trajectory it ... | stack_v2_sparse_classes_75kplus_train_007476 | 2,526 | permissive | [
{
"docstring": "Represents an agent learning with temporal difference :param learning_rate: Either a float or a function that takes in the count (N) of that state and returns 1/N :param discount_rate: The proportion of the future rewards applies to earlier states",
"name": "__init__",
"signature": "def ... | 3 | stack_v2_sparse_classes_30k_train_027881 | Implement the Python class `TemporalDifferenceOne` described below.
Class description:
Applies the temporal difference one algorithm as a learning algorithm Vt+1(s) = Vt(s) + alpha * (Gt - Vt(s)) Where alpha is the learning rate and Gt is the sum of accumulated and discounted rewards for the episode. Learns at the end... | Implement the Python class `TemporalDifferenceOne` described below.
Class description:
Applies the temporal difference one algorithm as a learning algorithm Vt+1(s) = Vt(s) + alpha * (Gt - Vt(s)) Where alpha is the learning rate and Gt is the sum of accumulated and discounted rewards for the episode. Learns at the end... | 5d42a88776428308d35c8031c01bf5afdf080079 | <|skeleton|>
class TemporalDifferenceOne:
"""Applies the temporal difference one algorithm as a learning algorithm Vt+1(s) = Vt(s) + alpha * (Gt - Vt(s)) Where alpha is the learning rate and Gt is the sum of accumulated and discounted rewards for the episode. Learns at the end of the episode from the trajectory it ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TemporalDifferenceOne:
"""Applies the temporal difference one algorithm as a learning algorithm Vt+1(s) = Vt(s) + alpha * (Gt - Vt(s)) Where alpha is the learning rate and Gt is the sum of accumulated and discounted rewards for the episode. Learns at the end of the episode from the trajectory it took after it... | the_stack_v2_python_sparse | rl/agents/learning/temporal_difference_one_agent.py | ManuelMeraz/ReinforcementLearning | train | 1 |
b05b91cc0cfa4d85ee88571193c56607fde67a07 | [
"obj = self.new_obj\nobj.save()\ntag_obj = Tags.objects.get(id=obj.tag.id)\narticle_obj = PageDetail.objects.get(id=obj.article.id)\nif article_obj:\n article_obj.tags += ',' + tag_obj.tag_name\n article_obj.save()",
"obj = self.obj\ntag_obj = Tags.objects.get(id=obj.tag.id)\narticle_obj = PageDetail.object... | <|body_start_0|>
obj = self.new_obj
obj.save()
tag_obj = Tags.objects.get(id=obj.tag.id)
article_obj = PageDetail.objects.get(id=obj.article.id)
if article_obj:
article_obj.tags += ',' + tag_obj.tag_name
article_obj.save()
<|end_body_0|>
<|body_start_1|>
... | TagMapAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TagMapAdmin:
def save_models(self):
"""tag引用计数的更新"""
<|body_0|>
def delete_model(self):
"""删除Tag映射"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
obj = self.new_obj
obj.save()
tag_obj = Tags.objects.get(id=obj.tag.id)
articl... | stack_v2_sparse_classes_75kplus_train_007477 | 4,329 | no_license | [
{
"docstring": "tag引用计数的更新",
"name": "save_models",
"signature": "def save_models(self)"
},
{
"docstring": "删除Tag映射",
"name": "delete_model",
"signature": "def delete_model(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017070 | Implement the Python class `TagMapAdmin` described below.
Class description:
Implement the TagMapAdmin class.
Method signatures and docstrings:
- def save_models(self): tag引用计数的更新
- def delete_model(self): 删除Tag映射 | Implement the Python class `TagMapAdmin` described below.
Class description:
Implement the TagMapAdmin class.
Method signatures and docstrings:
- def save_models(self): tag引用计数的更新
- def delete_model(self): 删除Tag映射
<|skeleton|>
class TagMapAdmin:
def save_models(self):
"""tag引用计数的更新"""
<|body_0|>... | 7d86de995deacac4eb45fed31865ba8a9598c289 | <|skeleton|>
class TagMapAdmin:
def save_models(self):
"""tag引用计数的更新"""
<|body_0|>
def delete_model(self):
"""删除Tag映射"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TagMapAdmin:
def save_models(self):
"""tag引用计数的更新"""
obj = self.new_obj
obj.save()
tag_obj = Tags.objects.get(id=obj.tag.id)
article_obj = PageDetail.objects.get(id=obj.article.id)
if article_obj:
article_obj.tags += ',' + tag_obj.tag_name
... | the_stack_v2_python_sparse | apps/blog/adminx.py | SatoKoi/Blog | train | 1 | |
390c4d78b818b71e3e4da04a5d713bd23642ddab | [
"mol = ethanol\nmol.assign_fractional_bond_orders(bond_order_model='am1-wiberg')\nmod_mol = Molecule(mol)\nfor bond in mod_mol.bonds:\n bond.fractional_bond_order += 0.1\ntop = Topology.from_molecules(mol)\nmod_top = Topology.from_molecules(mod_mol)\nforcefield = ForceField('openff-2.0.0.offxml', self.xml_ff_bo_... | <|body_start_0|>
mol = ethanol
mol.assign_fractional_bond_orders(bond_order_model='am1-wiberg')
mod_mol = Molecule(mol)
for bond in mod_mol.bonds:
bond.fractional_bond_order += 0.1
top = Topology.from_molecules(mol)
mod_top = Topology.from_molecules(mod_mol)
... | TestBondOrderInterpolation | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestBondOrderInterpolation:
def test_input_bond_orders_ignored(self, ethanol):
"""Test that conformers existing in the topology are not considered in the bond order interpolation part of the parametrization process"""
<|body_0|>
def test_input_conformers_ignored(self):
... | stack_v2_sparse_classes_75kplus_train_007478 | 19,817 | permissive | [
{
"docstring": "Test that conformers existing in the topology are not considered in the bond order interpolation part of the parametrization process",
"name": "test_input_bond_orders_ignored",
"signature": "def test_input_bond_orders_ignored(self, ethanol)"
},
{
"docstring": "Test that conformer... | 3 | stack_v2_sparse_classes_30k_train_016311 | Implement the Python class `TestBondOrderInterpolation` described below.
Class description:
Implement the TestBondOrderInterpolation class.
Method signatures and docstrings:
- def test_input_bond_orders_ignored(self, ethanol): Test that conformers existing in the topology are not considered in the bond order interpol... | Implement the Python class `TestBondOrderInterpolation` described below.
Class description:
Implement the TestBondOrderInterpolation class.
Method signatures and docstrings:
- def test_input_bond_orders_ignored(self, ethanol): Test that conformers existing in the topology are not considered in the bond order interpol... | 4616f2cff477c18e2c6ca70ac4c74c28b283a4be | <|skeleton|>
class TestBondOrderInterpolation:
def test_input_bond_orders_ignored(self, ethanol):
"""Test that conformers existing in the topology are not considered in the bond order interpolation part of the parametrization process"""
<|body_0|>
def test_input_conformers_ignored(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestBondOrderInterpolation:
def test_input_bond_orders_ignored(self, ethanol):
"""Test that conformers existing in the topology are not considered in the bond order interpolation part of the parametrization process"""
mol = ethanol
mol.assign_fractional_bond_orders(bond_order_model='am... | the_stack_v2_python_sparse | openff/interchange/_tests/unit_tests/smirnoff/test_valence.py | openforcefield/openff-interchange | train | 39 | |
37665c93ccb7ead9176463f587110646458531a8 | [
"try:\n if issubclass(obj.__class__, SerializableMixin):\n return True\n if issubclass(object_mapper(obj).class_, SerializableMixin):\n return True\nexcept UnmappedInstanceError:\n return False\nreturn False",
"if self.implements_serializable(obj):\n return obj.as_dict()\nreturn super().... | <|body_start_0|>
try:
if issubclass(obj.__class__, SerializableMixin):
return True
if issubclass(object_mapper(obj).class_, SerializableMixin):
return True
except UnmappedInstanceError:
return False
return False
<|end_body_0|>
... | Extends `JSONEncoder` to support automatic serialization of objects that extends `SerializableMixin`. | CustomJSONEncoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomJSONEncoder:
"""Extends `JSONEncoder` to support automatic serialization of objects that extends `SerializableMixin`."""
def implements_serializable(obj: Any) -> bool:
"""Check whether the given object extends `SerializableMixin`. :param obj: the object for which to check :retu... | stack_v2_sparse_classes_75kplus_train_007479 | 1,315 | permissive | [
{
"docstring": "Check whether the given object extends `SerializableMixin`. :param obj: the object for which to check :return: True if the object extends `SerializableMixin`",
"name": "implements_serializable",
"signature": "def implements_serializable(obj: Any) -> bool"
},
{
"docstring": "Seria... | 2 | null | Implement the Python class `CustomJSONEncoder` described below.
Class description:
Extends `JSONEncoder` to support automatic serialization of objects that extends `SerializableMixin`.
Method signatures and docstrings:
- def implements_serializable(obj: Any) -> bool: Check whether the given object extends `Serializab... | Implement the Python class `CustomJSONEncoder` described below.
Class description:
Extends `JSONEncoder` to support automatic serialization of objects that extends `SerializableMixin`.
Method signatures and docstrings:
- def implements_serializable(obj: Any) -> bool: Check whether the given object extends `Serializab... | dc85c0dde1a9fbc00a637beba16ce519438415bb | <|skeleton|>
class CustomJSONEncoder:
"""Extends `JSONEncoder` to support automatic serialization of objects that extends `SerializableMixin`."""
def implements_serializable(obj: Any) -> bool:
"""Check whether the given object extends `SerializableMixin`. :param obj: the object for which to check :retu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomJSONEncoder:
"""Extends `JSONEncoder` to support automatic serialization of objects that extends `SerializableMixin`."""
def implements_serializable(obj: Any) -> bool:
"""Check whether the given object extends `SerializableMixin`. :param obj: the object for which to check :return: True if t... | the_stack_v2_python_sparse | backend/base/json.py | BenjaminSchubert/web-polls | train | 0 |
b279142c52b9aab65fc01fffb34a8bd1f1f0adf1 | [
"if not hasattr(self, 'starting_users'):\n self.starting_users = len(self.bucket)\n self.total_additions = 0\nif len(self.bucket.users) > self.starting_users:\n self.total_additions += 1\n self.starting_users = len(self.bucket.users)",
"self.add_additions(turn)\nif self.total_additions > self.num_addi... | <|body_start_0|>
if not hasattr(self, 'starting_users'):
self.starting_users = len(self.bucket)
self.total_additions = 0
if len(self.bucket.users) > self.starting_users:
self.total_additions += 1
self.starting_users = len(self.bucket.users)
<|end_body_0|>
... | Attacker waits until they are in a combined bucket before attacking | Patient_Attacker | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Patient_Attacker:
"""Attacker waits until they are in a combined bucket before attacking"""
def add_additions(self, turn):
"""Records number of times their bucket size increased"""
<|body_0|>
def _attack(self, manager, turn):
"""Attacks only if the bucket size ha... | stack_v2_sparse_classes_75kplus_train_007480 | 1,665 | permissive | [
{
"docstring": "Records number of times their bucket size increased",
"name": "add_additions",
"signature": "def add_additions(self, turn)"
},
{
"docstring": "Attacks only if the bucket size has increased num_additions times",
"name": "_attack",
"signature": "def _attack(self, manager, t... | 2 | stack_v2_sparse_classes_30k_train_038875 | Implement the Python class `Patient_Attacker` described below.
Class description:
Attacker waits until they are in a combined bucket before attacking
Method signatures and docstrings:
- def add_additions(self, turn): Records number of times their bucket size increased
- def _attack(self, manager, turn): Attacks only ... | Implement the Python class `Patient_Attacker` described below.
Class description:
Attacker waits until they are in a combined bucket before attacking
Method signatures and docstrings:
- def add_additions(self, turn): Records number of times their bucket size increased
- def _attack(self, manager, turn): Attacks only ... | c7d572c12322fac80d1bea1396a31deafe2beccc | <|skeleton|>
class Patient_Attacker:
"""Attacker waits until they are in a combined bucket before attacking"""
def add_additions(self, turn):
"""Records number of times their bucket size increased"""
<|body_0|>
def _attack(self, manager, turn):
"""Attacks only if the bucket size ha... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Patient_Attacker:
"""Attacker waits until they are in a combined bucket before attacking"""
def add_additions(self, turn):
"""Records number of times their bucket size increased"""
if not hasattr(self, 'starting_users'):
self.starting_users = len(self.bucket)
self.... | the_stack_v2_python_sparse | lib_ddos_simulator/attackers/patient_attacker.py | jfuruness/lib_ddos_simulator | train | 0 |
0691489dd5c8bf2d498533ef3738768c1952dfbc | [
"nodes = super().all()\nif nodes:\n return nodes[0]\nraise CardinalityViolation(self, 'none')",
"nodes = super().all()\nif nodes:\n return nodes\nraise CardinalityViolation(self, 'none')",
"if super().__len__() < 2:\n raise AttemptedCardinalityViolation('One or more expected')\nreturn super().disconnec... | <|body_start_0|>
nodes = super().all()
if nodes:
return nodes[0]
raise CardinalityViolation(self, 'none')
<|end_body_0|>
<|body_start_1|>
nodes = super().all()
if nodes:
return nodes
raise CardinalityViolation(self, 'none')
<|end_body_1|>
<|body_... | A relationship to zero or more nodes. | OneOrMore | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OneOrMore:
"""A relationship to zero or more nodes."""
def single(self):
"""Fetch one of the related nodes :return: Node"""
<|body_0|>
def all(self):
"""Returns all related nodes. :return: [node1, node2...]"""
<|body_1|>
def disconnect(self, node):
... | stack_v2_sparse_classes_75kplus_train_007481 | 3,419 | permissive | [
{
"docstring": "Fetch one of the related nodes :return: Node",
"name": "single",
"signature": "def single(self)"
},
{
"docstring": "Returns all related nodes. :return: [node1, node2...]",
"name": "all",
"signature": "def all(self)"
},
{
"docstring": "Disconnect node :param node: ... | 3 | null | Implement the Python class `OneOrMore` described below.
Class description:
A relationship to zero or more nodes.
Method signatures and docstrings:
- def single(self): Fetch one of the related nodes :return: Node
- def all(self): Returns all related nodes. :return: [node1, node2...]
- def disconnect(self, node): Disco... | Implement the Python class `OneOrMore` described below.
Class description:
A relationship to zero or more nodes.
Method signatures and docstrings:
- def single(self): Fetch one of the related nodes :return: Node
- def all(self): Returns all related nodes. :return: [node1, node2...]
- def disconnect(self, node): Disco... | 8b3de60facf2d61ea6062bf7c656d1d212adb6ac | <|skeleton|>
class OneOrMore:
"""A relationship to zero or more nodes."""
def single(self):
"""Fetch one of the related nodes :return: Node"""
<|body_0|>
def all(self):
"""Returns all related nodes. :return: [node1, node2...]"""
<|body_1|>
def disconnect(self, node):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OneOrMore:
"""A relationship to zero or more nodes."""
def single(self):
"""Fetch one of the related nodes :return: Node"""
nodes = super().all()
if nodes:
return nodes[0]
raise CardinalityViolation(self, 'none')
def all(self):
"""Returns all relat... | the_stack_v2_python_sparse | neomodel/cardinality.py | neo4j-contrib/neomodel | train | 527 |
b3bc967de5f801aa14f14def8311910bebacd16d | [
"self.address = (host, port)\nself.bufsize = bufsize\nself.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)",
"if append_null_terminator:\n msg = msg + '\\x00'\nself.sock.sendto(msg, self.address)",
"data, address = self.sock.recvfrom(self.bufsize)\nif conform_address:\n self.address = address\nret... | <|body_start_0|>
self.address = (host, port)
self.bufsize = bufsize
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
<|end_body_0|>
<|body_start_1|>
if append_null_terminator:
msg = msg + '\x00'
self.sock.sendto(msg, self.address)
<|end_body_1|>
<|body_s... | Handles the barest level of UDP communication with a server in a slightly simpler way (for our purposes) than the default socket library. | Socket | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Socket:
"""Handles the barest level of UDP communication with a server in a slightly simpler way (for our purposes) than the default socket library."""
def __init__(self, host, port, bufsize=8192):
"""host: hostname of the server we want to connect to port: port of the server we want... | stack_v2_sparse_classes_75kplus_train_007482 | 1,393 | permissive | [
{
"docstring": "host: hostname of the server we want to connect to port: port of the server we want to connect to",
"name": "__init__",
"signature": "def __init__(self, host, port, bufsize=8192)"
},
{
"docstring": "Sends a message to the server. Appends a null terminator by default.",
"name"... | 3 | null | Implement the Python class `Socket` described below.
Class description:
Handles the barest level of UDP communication with a server in a slightly simpler way (for our purposes) than the default socket library.
Method signatures and docstrings:
- def __init__(self, host, port, bufsize=8192): host: hostname of the serv... | Implement the Python class `Socket` described below.
Class description:
Handles the barest level of UDP communication with a server in a slightly simpler way (for our purposes) than the default socket library.
Method signatures and docstrings:
- def __init__(self, host, port, bufsize=8192): host: hostname of the serv... | e37708e5d9ac109e341be669eaa9739b3326a429 | <|skeleton|>
class Socket:
"""Handles the barest level of UDP communication with a server in a slightly simpler way (for our purposes) than the default socket library."""
def __init__(self, host, port, bufsize=8192):
"""host: hostname of the server we want to connect to port: port of the server we want... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Socket:
"""Handles the barest level of UDP communication with a server in a slightly simpler way (for our purposes) than the default socket library."""
def __init__(self, host, port, bufsize=8192):
"""host: hostname of the server we want to connect to port: port of the server we want to connect t... | the_stack_v2_python_sparse | player_2v2/sock.py | LiwenZhang0201/DeepRL_RoboCup | train | 6 |
ee86f6ee8c9f008e0cb32cda0caba77dd4d4d44c | [
"self.ps_list = list()\nself.load_rules = load_rules\nself.snapshot_dict = snapshot_dict\nself.parsers_dict = parsers_dict",
"cur_ps_list = get_pid_list()\nif self.ps_list != cur_ps_list:\n ps_killed = at_first_only(self.ps_list, cur_ps_list)\n ps_new = at_first_only(cur_ps_list, self.ps_list)\n self.ps_... | <|body_start_0|>
self.ps_list = list()
self.load_rules = load_rules
self.snapshot_dict = snapshot_dict
self.parsers_dict = parsers_dict
<|end_body_0|>
<|body_start_1|>
cur_ps_list = get_pid_list()
if self.ps_list != cur_ps_list:
ps_killed = at_first_only(self... | Responsible to update the given snapshot_dict with who is alive/dead. Use its 'update()' function in a loop to iteratively update the given snapshot_dict. | PsListMonitor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PsListMonitor:
"""Responsible to update the given snapshot_dict with who is alive/dead. Use its 'update()' function in a loop to iteratively update the given snapshot_dict."""
def __init__(self, load_rules: LoadConfig, snapshot_dict: dict, parsers_dict: dict):
"""Constructor. :param ... | stack_v2_sparse_classes_75kplus_train_007483 | 8,176 | no_license | [
{
"docstring": "Constructor. :param load_rules: An already initialized LoadRules object :param snapshot_dict: A dict of {pid : snapshot object}, with one entry {'*system*' : system snapshot} :param parsers_dict: A dict of all available parsers {'parser_name': ParserObject}",
"name": "__init__",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_009716 | Implement the Python class `PsListMonitor` described below.
Class description:
Responsible to update the given snapshot_dict with who is alive/dead. Use its 'update()' function in a loop to iteratively update the given snapshot_dict.
Method signatures and docstrings:
- def __init__(self, load_rules: LoadConfig, snaps... | Implement the Python class `PsListMonitor` described below.
Class description:
Responsible to update the given snapshot_dict with who is alive/dead. Use its 'update()' function in a loop to iteratively update the given snapshot_dict.
Method signatures and docstrings:
- def __init__(self, load_rules: LoadConfig, snaps... | d0cb02e418edae4c1bacc44fe840701ea0e8bf71 | <|skeleton|>
class PsListMonitor:
"""Responsible to update the given snapshot_dict with who is alive/dead. Use its 'update()' function in a loop to iteratively update the given snapshot_dict."""
def __init__(self, load_rules: LoadConfig, snapshot_dict: dict, parsers_dict: dict):
"""Constructor. :param ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PsListMonitor:
"""Responsible to update the given snapshot_dict with who is alive/dead. Use its 'update()' function in a loop to iteratively update the given snapshot_dict."""
def __init__(self, load_rules: LoadConfig, snapshot_dict: dict, parsers_dict: dict):
"""Constructor. :param load_rules: A... | the_stack_v2_python_sparse | main.py | yarinschiller/hamato-yoshi | train | 2 |
b9037bcc476f188d3c3aa0f4711c1f43f8baead4 | [
"super().__init__()\nself.in_chans = in_chans\nself.out_chans = out_chans\nself.chans = chans\nself.num_pool_layers = num_pool_layers\nself.drop_prob = drop_prob\nself.down_sample_layers = nn.ModuleList([Conv3dBlock(in_chans, chans, drop_prob)])\nch = chans\nfor _ in range(num_pool_layers - 1):\n self.down_sampl... | <|body_start_0|>
super().__init__()
self.in_chans = in_chans
self.out_chans = out_chans
self.chans = chans
self.num_pool_layers = num_pool_layers
self.drop_prob = drop_prob
self.down_sample_layers = nn.ModuleList([Conv3dBlock(in_chans, chans, drop_prob)])
... | Implementation of the 3D UNet, as presented in O. Ronneberger, P. Fischer, and Thomas Brox. References ---------- .. O. Ronneberger, P. Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assisted intervention, pa... | UNet3D | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UNet3D:
"""Implementation of the 3D UNet, as presented in O. Ronneberger, P. Fischer, and Thomas Brox. References ---------- .. O. Ronneberger, P. Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and ... | stack_v2_sparse_classes_75kplus_train_007484 | 5,686 | permissive | [
{
"docstring": "Parameters ---------- in_chans : int Number of input channels. out_chans : int Number of output channels. chans : int Number of output channels of the first convolutional layer. num_pool_layers : int Number of down-sampling and up-sampling layers. drop_prob : float Dropout probability. block : n... | 2 | stack_v2_sparse_classes_30k_train_024673 | Implement the Python class `UNet3D` described below.
Class description:
Implementation of the 3D UNet, as presented in O. Ronneberger, P. Fischer, and Thomas Brox. References ---------- .. O. Ronneberger, P. Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Con... | Implement the Python class `UNet3D` described below.
Class description:
Implementation of the 3D UNet, as presented in O. Ronneberger, P. Fischer, and Thomas Brox. References ---------- .. O. Ronneberger, P. Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Con... | 6d15dd55ca5ed6fc9fbfd31d8488ee7bab453066 | <|skeleton|>
class UNet3D:
"""Implementation of the 3D UNet, as presented in O. Ronneberger, P. Fischer, and Thomas Brox. References ---------- .. O. Ronneberger, P. Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UNet3D:
"""Implementation of the 3D UNet, as presented in O. Ronneberger, P. Fischer, and Thomas Brox. References ---------- .. O. Ronneberger, P. Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assi... | the_stack_v2_python_sparse | mridc/collections/segmentation/models/unet3d_base/unet3d_block.py | wdika/mridc | train | 40 |
80389afa393eb20ebc3429fcae5962fffb1f7523 | [
"self.name = name\nself.kernel_regularizer = kernel_regularizer\nself.bias_regularizer = bias_regularizer",
"func_name = 'get_critic_logits'\nnetwork = X\nprint_obj('\\n' + func_name, 'network', network)\nwith tf.variable_scope('critic', reuse=tf.AUTO_REUSE):\n for i in range(len(params['critic_num_filters']))... | <|body_start_0|>
self.name = name
self.kernel_regularizer = kernel_regularizer
self.bias_regularizer = bias_regularizer
<|end_body_0|>
<|body_start_1|>
func_name = 'get_critic_logits'
network = X
print_obj('\n' + func_name, 'network', network)
with tf.variable_sc... | Critic that takes image input and outputs logits. Fields: name: str, name of `Critic`. kernel_regularizer: `l1_l2_regularizer` object, regularizar for kernel variables. bias_regularizer: `l1_l2_regularizer` object, regularizar for bias variables. | Critic | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Critic:
"""Critic that takes image input and outputs logits. Fields: name: str, name of `Critic`. kernel_regularizer: `l1_l2_regularizer` object, regularizar for kernel variables. bias_regularizer: `l1_l2_regularizer` object, regularizar for bias variables."""
def __init__(self, kernel_regul... | stack_v2_sparse_classes_75kplus_train_007485 | 6,232 | permissive | [
{
"docstring": "Instantiates and builds critic network. Args: kernel_regularizer: `l1_l2_regularizer` object, regularizar for kernel variables. bias_regularizer: `l1_l2_regularizer` object, regularizar for bias variables. name: str, name of critic.",
"name": "__init__",
"signature": "def __init__(self, ... | 3 | stack_v2_sparse_classes_30k_train_028145 | Implement the Python class `Critic` described below.
Class description:
Critic that takes image input and outputs logits. Fields: name: str, name of `Critic`. kernel_regularizer: `l1_l2_regularizer` object, regularizar for kernel variables. bias_regularizer: `l1_l2_regularizer` object, regularizar for bias variables.
... | Implement the Python class `Critic` described below.
Class description:
Critic that takes image input and outputs logits. Fields: name: str, name of `Critic`. kernel_regularizer: `l1_l2_regularizer` object, regularizar for kernel variables. bias_regularizer: `l1_l2_regularizer` object, regularizar for bias variables.
... | f7c21af221f366b075d351deeeb00a1b266ac3e3 | <|skeleton|>
class Critic:
"""Critic that takes image input and outputs logits. Fields: name: str, name of `Critic`. kernel_regularizer: `l1_l2_regularizer` object, regularizar for kernel variables. bias_regularizer: `l1_l2_regularizer` object, regularizar for bias variables."""
def __init__(self, kernel_regul... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Critic:
"""Critic that takes image input and outputs logits. Fields: name: str, name of `Critic`. kernel_regularizer: `l1_l2_regularizer` object, regularizar for kernel variables. bias_regularizer: `l1_l2_regularizer` object, regularizar for bias variables."""
def __init__(self, kernel_regularizer, bias_... | the_stack_v2_python_sparse | machine_learning/gan/wgan/tf_wgan/wgan_module/trainer/critic.py | ryangillard/artificial_intelligence | train | 4 |
ed7fdad8762b168fd5acd2d516983ebf4dc1cbb5 | [
"res = super(sale_order_line, self).product_id_change(cr, uid, ids, pricelist, product, qty=qty, uom=uom, qty_uos=qty_uos, uos=uos, name=name, partner_id=partner_id, lang=lang, update_tax=update_tax, date_order=date_order, packaging=packaging, fiscal_position=fiscal_position, flag=flag, context=context)\nif product... | <|body_start_0|>
res = super(sale_order_line, self).product_id_change(cr, uid, ids, pricelist, product, qty=qty, uom=uom, qty_uos=qty_uos, uos=uos, name=name, partner_id=partner_id, lang=lang, update_tax=update_tax, date_order=date_order, packaging=packaging, fiscal_position=fiscal_position, flag=flag, context=... | sale_order_line | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class sale_order_line:
def product_id_change(self, cr, uid, ids, pricelist, product, qty=0, uom=False, qty_uos=0, uos=False, name='', partner_id=False, lang=False, update_tax=True, date_order=False, packaging=False, fiscal_position=False, flag=False, context=None):
"""check product if event ty... | stack_v2_sparse_classes_75kplus_train_007486 | 4,853 | no_license | [
{
"docstring": "check product if event type",
"name": "product_id_change",
"signature": "def product_id_change(self, cr, uid, ids, pricelist, product, qty=0, uom=False, qty_uos=0, uos=False, name='', partner_id=False, lang=False, update_tax=True, date_order=False, packaging=False, fiscal_position=False,... | 2 | stack_v2_sparse_classes_30k_train_051840 | Implement the Python class `sale_order_line` described below.
Class description:
Implement the sale_order_line class.
Method signatures and docstrings:
- def product_id_change(self, cr, uid, ids, pricelist, product, qty=0, uom=False, qty_uos=0, uos=False, name='', partner_id=False, lang=False, update_tax=True, date_o... | Implement the Python class `sale_order_line` described below.
Class description:
Implement the sale_order_line class.
Method signatures and docstrings:
- def product_id_change(self, cr, uid, ids, pricelist, product, qty=0, uom=False, qty_uos=0, uos=False, name='', partner_id=False, lang=False, update_tax=True, date_o... | e6b06ea17fa44e35e3c99a83c6f3ec433c33c894 | <|skeleton|>
class sale_order_line:
def product_id_change(self, cr, uid, ids, pricelist, product, qty=0, uom=False, qty_uos=0, uos=False, name='', partner_id=False, lang=False, update_tax=True, date_order=False, packaging=False, fiscal_position=False, flag=False, context=None):
"""check product if event ty... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class sale_order_line:
def product_id_change(self, cr, uid, ids, pricelist, product, qty=0, uom=False, qty_uos=0, uos=False, name='', partner_id=False, lang=False, update_tax=True, date_order=False, packaging=False, fiscal_position=False, flag=False, context=None):
"""check product if event type"""
... | the_stack_v2_python_sparse | event_sale/event_sale.py | rvalyi/openerp-addons | train | 2 | |
d0a54b39fed77226579e8a12690d2c2a161cdf6d | [
"if dict_type == self.STOP_WORDS:\n f = codecs.open(self.STOPWORDS_FILE, 'r', 'utf-8')\nelse:\n f = codecs.open(self.COMPONENT_FILE, 'r', 'utf-8')\nif f:\n content = f.read()\n content = content.replace('\\r\\n', ' ')\n kw_list = content.split(' ')\n try:\n kw_list.remove('')\n except Va... | <|body_start_0|>
if dict_type == self.STOP_WORDS:
f = codecs.open(self.STOPWORDS_FILE, 'r', 'utf-8')
else:
f = codecs.open(self.COMPONENT_FILE, 'r', 'utf-8')
if f:
content = f.read()
content = content.replace('\r\n', ' ')
kw_list = cont... | 更新词库 | UpdateKw | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateKw:
"""更新词库"""
def update_dict(self, dict_type=CommentJiebaDB.STOP_WORDS):
"""从stopwords.txt中更新无效词/停用词库 或 从component.txt中更新组合词库 默认更新的是无效词库 dict_type = 1时,更新的是组合词库"""
<|body_0|>
def read_kw(self, kw_tb='kw_search'):
"""从kw表或者kw_search表中读取未归类的数据 当kw_tb == kw的... | stack_v2_sparse_classes_75kplus_train_007487 | 5,771 | no_license | [
{
"docstring": "从stopwords.txt中更新无效词/停用词库 或 从component.txt中更新组合词库 默认更新的是无效词库 dict_type = 1时,更新的是组合词库",
"name": "update_dict",
"signature": "def update_dict(self, dict_type=CommentJiebaDB.STOP_WORDS)"
},
{
"docstring": "从kw表或者kw_search表中读取未归类的数据 当kw_tb == kw的时候,从kw表中读取,否则从kw_search表中读取",
"nam... | 2 | stack_v2_sparse_classes_30k_train_015394 | Implement the Python class `UpdateKw` described below.
Class description:
更新词库
Method signatures and docstrings:
- def update_dict(self, dict_type=CommentJiebaDB.STOP_WORDS): 从stopwords.txt中更新无效词/停用词库 或 从component.txt中更新组合词库 默认更新的是无效词库 dict_type = 1时,更新的是组合词库
- def read_kw(self, kw_tb='kw_search'): 从kw表或者kw_search表中读... | Implement the Python class `UpdateKw` described below.
Class description:
更新词库
Method signatures and docstrings:
- def update_dict(self, dict_type=CommentJiebaDB.STOP_WORDS): 从stopwords.txt中更新无效词/停用词库 或 从component.txt中更新组合词库 默认更新的是无效词库 dict_type = 1时,更新的是组合词库
- def read_kw(self, kw_tb='kw_search'): 从kw表或者kw_search表中读... | 0288830d0b5d48e6037ae852ec69aa94dcfa9cf3 | <|skeleton|>
class UpdateKw:
"""更新词库"""
def update_dict(self, dict_type=CommentJiebaDB.STOP_WORDS):
"""从stopwords.txt中更新无效词/停用词库 或 从component.txt中更新组合词库 默认更新的是无效词库 dict_type = 1时,更新的是组合词库"""
<|body_0|>
def read_kw(self, kw_tb='kw_search'):
"""从kw表或者kw_search表中读取未归类的数据 当kw_tb == kw的... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UpdateKw:
"""更新词库"""
def update_dict(self, dict_type=CommentJiebaDB.STOP_WORDS):
"""从stopwords.txt中更新无效词/停用词库 或 从component.txt中更新组合词库 默认更新的是无效词库 dict_type = 1时,更新的是组合词库"""
if dict_type == self.STOP_WORDS:
f = codecs.open(self.STOPWORDS_FILE, 'r', 'utf-8')
else:
... | the_stack_v2_python_sparse | jieba/kwtb.py | jeawy/comment | train | 0 |
ac1c3aa9e64d4773e93327f3808d8d8b03cb45b5 | [
"self.pi_means = means\nself.pi_variances = variances\nself.relative_weight = relative_weight\nself.weight = weight\nself.rev_KL = MFN_MFN_reverse_KLD(means, variances)\nself.KL = MFN_MFN_KLD(means, variances)",
"revKL = self.rev_KL(q_params, q_parser, converter)\nKL = self.KL(q_params, q_parser, converter)\nretu... | <|body_start_0|>
self.pi_means = means
self.pi_variances = variances
self.relative_weight = relative_weight
self.weight = weight
self.rev_KL = MFN_MFN_reverse_KLD(means, variances)
self.KL = MFN_MFN_KLD(means, variances)
<|end_body_0|>
<|body_start_1|>
revKL = se... | Jeffrey's Divergence where q and pi are both mean field normals. This is just KLD(q||pi) + KLD(pi||q) Internal states of the object: means Means of the prior (one mean for each variable) variances Variances of the prior (one for each variable) relative_weight relative_weight * KLD(q||pi) + (1-relw) * KLD(pi||q) | MFN_MFN_JeffreysD | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MFN_MFN_JeffreysD:
"""Jeffrey's Divergence where q and pi are both mean field normals. This is just KLD(q||pi) + KLD(pi||q) Internal states of the object: means Means of the prior (one mean for each variable) variances Variances of the prior (one for each variable) relative_weight relative_weight... | stack_v2_sparse_classes_75kplus_train_007488 | 14,750 | no_license | [
{
"docstring": "MFN for prior specified by vector of means & variances",
"name": "__init__",
"signature": "def __init__(self, means, variances, relative_weight=0.5, weight=1.0)"
},
{
"docstring": "Compute relative_weight * KLD(q||pi) + (1-relw) * KLD(pi||q)",
"name": "prior_retularizer",
... | 2 | stack_v2_sparse_classes_30k_train_030119 | Implement the Python class `MFN_MFN_JeffreysD` described below.
Class description:
Jeffrey's Divergence where q and pi are both mean field normals. This is just KLD(q||pi) + KLD(pi||q) Internal states of the object: means Means of the prior (one mean for each variable) variances Variances of the prior (one for each va... | Implement the Python class `MFN_MFN_JeffreysD` described below.
Class description:
Jeffrey's Divergence where q and pi are both mean field normals. This is just KLD(q||pi) + KLD(pi||q) Internal states of the object: means Means of the prior (one mean for each variable) variances Variances of the prior (one for each va... | 6e51c10227ca8300853f2341906503d072cc0685 | <|skeleton|>
class MFN_MFN_JeffreysD:
"""Jeffrey's Divergence where q and pi are both mean field normals. This is just KLD(q||pi) + KLD(pi||q) Internal states of the object: means Means of the prior (one mean for each variable) variances Variances of the prior (one for each variable) relative_weight relative_weight... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MFN_MFN_JeffreysD:
"""Jeffrey's Divergence where q and pi are both mean field normals. This is just KLD(q||pi) + KLD(pi||q) Internal states of the object: means Means of the prior (one mean for each variable) variances Variances of the prior (one for each variable) relative_weight relative_weight * KLD(q||pi)... | the_stack_v2_python_sparse | Divergence.py | JeremiasKnoblauch/GVI_consistency | train | 0 |
3350b8b3eaf7c7fc966c5d43d5392108e91dc28d | [
"super(LCPController, self).__init__(manager)\nself._logger = logging.getLogger(__name__)\nself._credential_factory = LCPCredentialFactory()\nself._lcp_server_factory = LCPServerFactory()",
"self._logger.info('Started fetching an authenticated patron associated with the request')\npatron = self.authenticated_patr... | <|body_start_0|>
super(LCPController, self).__init__(manager)
self._logger = logging.getLogger(__name__)
self._credential_factory = LCPCredentialFactory()
self._lcp_server_factory = LCPServerFactory()
<|end_body_0|>
<|body_start_1|>
self._logger.info('Started fetching an authent... | Contains API endpoints related to LCP workflow | LCPController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LCPController:
"""Contains API endpoints related to LCP workflow"""
def __init__(self, manager):
"""Initializes a new instance of LCPController class :param manager: CirculationManager object :type manager: CirculationManager"""
<|body_0|>
def _get_patron(self):
... | stack_v2_sparse_classes_75kplus_train_007489 | 4,383 | permissive | [
{
"docstring": "Initializes a new instance of LCPController class :param manager: CirculationManager object :type manager: CirculationManager",
"name": "__init__",
"signature": "def __init__(self, manager)"
},
{
"docstring": "Returns a patron associated with the request (if any) :return: Patron ... | 6 | stack_v2_sparse_classes_30k_train_045915 | Implement the Python class `LCPController` described below.
Class description:
Contains API endpoints related to LCP workflow
Method signatures and docstrings:
- def __init__(self, manager): Initializes a new instance of LCPController class :param manager: CirculationManager object :type manager: CirculationManager
-... | Implement the Python class `LCPController` described below.
Class description:
Contains API endpoints related to LCP workflow
Method signatures and docstrings:
- def __init__(self, manager): Initializes a new instance of LCPController class :param manager: CirculationManager object :type manager: CirculationManager
-... | 662cc7e0721d0153857c8c17a37e2a6df86f8ce6 | <|skeleton|>
class LCPController:
"""Contains API endpoints related to LCP workflow"""
def __init__(self, manager):
"""Initializes a new instance of LCPController class :param manager: CirculationManager object :type manager: CirculationManager"""
<|body_0|>
def _get_patron(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LCPController:
"""Contains API endpoints related to LCP workflow"""
def __init__(self, manager):
"""Initializes a new instance of LCPController class :param manager: CirculationManager object :type manager: CirculationManager"""
super(LCPController, self).__init__(manager)
self._l... | the_stack_v2_python_sparse | api/lcp/controller.py | NYPL-Simplified/circulation | train | 20 |
7216e9d6e386b3c76b50d533832904ba0bf1c9c2 | [
"self.value = val\nself.left = None\nself.right = None",
"if val <= self.value:\n if self.left:\n self.left.add(val)\n else:\n self.left = Node(val)\nelif self.right:\n self.right.add(val)\nelse:\n self.right = Node(val)"
] | <|body_start_0|>
self.value = val
self.left = None
self.right = None
<|end_body_0|>
<|body_start_1|>
if val <= self.value:
if self.left:
self.left.add(val)
else:
self.left = Node(val)
elif self.right:
self.right... | Node | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Node:
def __init__(self, val=None):
"""创建一个 node"""
<|body_0|>
def add(self, val):
"""增加一个子 node"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.value = val
self.left = None
self.right = None
<|end_body_0|>
<|body_start_1|>
... | stack_v2_sparse_classes_75kplus_train_007490 | 1,232 | no_license | [
{
"docstring": "创建一个 node",
"name": "__init__",
"signature": "def __init__(self, val=None)"
},
{
"docstring": "增加一个子 node",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010389 | Implement the Python class `Node` described below.
Class description:
Implement the Node class.
Method signatures and docstrings:
- def __init__(self, val=None): 创建一个 node
- def add(self, val): 增加一个子 node | Implement the Python class `Node` described below.
Class description:
Implement the Node class.
Method signatures and docstrings:
- def __init__(self, val=None): 创建一个 node
- def add(self, val): 增加一个子 node
<|skeleton|>
class Node:
def __init__(self, val=None):
"""创建一个 node"""
<|body_0|>
def ... | 5aafa888ba7e148df8abaac18101e795f74f4130 | <|skeleton|>
class Node:
def __init__(self, val=None):
"""创建一个 node"""
<|body_0|>
def add(self, val):
"""增加一个子 node"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Node:
def __init__(self, val=None):
"""创建一个 node"""
self.value = val
self.left = None
self.right = None
def add(self, val):
"""增加一个子 node"""
if val <= self.value:
if self.left:
self.left.add(val)
else:
... | the_stack_v2_python_sparse | 树/binary_search_tree.py | Shawn91/Algorithms | train | 0 | |
98591d4e7d02f8819aa4aa546c686af5b7beca18 | [
"head, tail = ntpath.split(source)\n\ndef remove_ending(file):\n return os.path.splitext(file)[0]\nreturn remove_ending(tail) or remove_ending(ntpath.basename(head))",
"with open(source) as data_file:\n data = json.load(data_file, encoding='utf-8', object_pairs_hook=OrderedDict)\n events = []\n metada... | <|body_start_0|>
head, tail = ntpath.split(source)
def remove_ending(file):
return os.path.splitext(file)[0]
return remove_ending(tail) or remove_ending(ntpath.basename(head))
<|end_body_0|>
<|body_start_1|>
with open(source) as data_file:
data = json.load(data_... | Converts event data provided by Facebook's Graph API into CSV format | EventJsonToCsv | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventJsonToCsv:
"""Converts event data provided by Facebook's Graph API into CSV format"""
def strip_file(self, source):
"""Removes the path and file extension from a given filepath :param source: The path of the file :return: The filename without any path info or file extension"""
... | stack_v2_sparse_classes_75kplus_train_007491 | 2,947 | no_license | [
{
"docstring": "Removes the path and file extension from a given filepath :param source: The path of the file :return: The filename without any path info or file extension",
"name": "strip_file",
"signature": "def strip_file(self, source)"
},
{
"docstring": "Does the actual conversion Takes a .j... | 2 | stack_v2_sparse_classes_30k_train_046892 | Implement the Python class `EventJsonToCsv` described below.
Class description:
Converts event data provided by Facebook's Graph API into CSV format
Method signatures and docstrings:
- def strip_file(self, source): Removes the path and file extension from a given filepath :param source: The path of the file :return: ... | Implement the Python class `EventJsonToCsv` described below.
Class description:
Converts event data provided by Facebook's Graph API into CSV format
Method signatures and docstrings:
- def strip_file(self, source): Removes the path and file extension from a given filepath :param source: The path of the file :return: ... | 8bfd6ce8e27d61f429955614dbbdccf93f9dc817 | <|skeleton|>
class EventJsonToCsv:
"""Converts event data provided by Facebook's Graph API into CSV format"""
def strip_file(self, source):
"""Removes the path and file extension from a given filepath :param source: The path of the file :return: The filename without any path info or file extension"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EventJsonToCsv:
"""Converts event data provided by Facebook's Graph API into CSV format"""
def strip_file(self, source):
"""Removes the path and file extension from a given filepath :param source: The path of the file :return: The filename without any path info or file extension"""
head, ... | the_stack_v2_python_sparse | Social/facebookCrawler/EventJsonToCsv.py | CUTLER-H2020/DataCrawlers | train | 3 |
990428655336455438ba90e6bc327262f322b25d | [
"TestStepBase.__init__(self, tc_conf, global_conf, ts_conf, factory)\nself._equipment_manager = None\nself._equipment_parameters = None",
"TestStepBase.run(self, context)\nself._equipment_manager = self._factory.create_equipment_manager()\nself._equipment_parameters = self._global_conf.benchConfig.get_parameters(... | <|body_start_0|>
TestStepBase.__init__(self, tc_conf, global_conf, ts_conf, factory)
self._equipment_manager = None
self._equipment_parameters = None
<|end_body_0|>
<|body_start_1|>
TestStepBase.run(self, context)
self._equipment_manager = self._factory.create_equipment_manager(... | Implements a base test step which involves an equipment .. uml:: class TestStepBase class EquipmentTestStepBase { run(context) } TestStepBase <|- EquipmentTestStepBase | EquipmentTestStepBase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EquipmentTestStepBase:
"""Implements a base test step which involves an equipment .. uml:: class TestStepBase class EquipmentTestStepBase { run(context) } TestStepBase <|- EquipmentTestStepBase"""
def __init__(self, tc_conf, global_conf, ts_conf, factory):
"""Constructor"""
<... | stack_v2_sparse_classes_75kplus_train_007492 | 2,659 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, tc_conf, global_conf, ts_conf, factory)"
},
{
"docstring": "Runs the test step :type context: :py:class:`~acs.Core.TestStep.TestStepContext` :param context: test case context :raise: AcsConfigException, TestEquipm... | 2 | stack_v2_sparse_classes_30k_train_050849 | Implement the Python class `EquipmentTestStepBase` described below.
Class description:
Implements a base test step which involves an equipment .. uml:: class TestStepBase class EquipmentTestStepBase { run(context) } TestStepBase <|- EquipmentTestStepBase
Method signatures and docstrings:
- def __init__(self, tc_conf,... | Implement the Python class `EquipmentTestStepBase` described below.
Class description:
Implements a base test step which involves an equipment .. uml:: class TestStepBase class EquipmentTestStepBase { run(context) } TestStepBase <|- EquipmentTestStepBase
Method signatures and docstrings:
- def __init__(self, tc_conf,... | 59564f826f205fe7fab64f45b88b1a6dde6900af | <|skeleton|>
class EquipmentTestStepBase:
"""Implements a base test step which involves an equipment .. uml:: class TestStepBase class EquipmentTestStepBase { run(context) } TestStepBase <|- EquipmentTestStepBase"""
def __init__(self, tc_conf, global_conf, ts_conf, factory):
"""Constructor"""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EquipmentTestStepBase:
"""Implements a base test step which involves an equipment .. uml:: class TestStepBase class EquipmentTestStepBase { run(context) } TestStepBase <|- EquipmentTestStepBase"""
def __init__(self, tc_conf, global_conf, ts_conf, factory):
"""Constructor"""
TestStepBase._... | the_stack_v2_python_sparse | acs/acs/Core/TestStep/EquipmentTestStepBase.py | wangji1/test-framework-and-suites-for-android | train | 0 |
3481a86a983bd969337fb33de6b639bc806a1c1b | [
"tk.Frame.__init__(self, *args, **kwargs)\nself.model = model\nself.initialize_widgets()\nself.layout_widgets()",
"self.grid_progress = tk.Frame(self)\nself.label_title = tk.Label(self.grid_progress, text='Simulating radio observations...', font=('Arial', 20, 'bold'))\nself.label_info = tk.Label(self.grid_progres... | <|body_start_0|>
tk.Frame.__init__(self, *args, **kwargs)
self.model = model
self.initialize_widgets()
self.layout_widgets()
<|end_body_0|>
<|body_start_1|>
self.grid_progress = tk.Frame(self)
self.label_title = tk.Label(self.grid_progress, text='Simulating radio observa... | Subclass of tk.Frame. This class creates and layouts widgets for the third page of the GUI. This class shows a loading label until pipeline is finished. | ProgressPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProgressPage:
"""Subclass of tk.Frame. This class creates and layouts widgets for the third page of the GUI. This class shows a loading label until pipeline is finished."""
def __init__(self, model, *args, **kwargs):
"""This methods will be called when an object of this class is inst... | stack_v2_sparse_classes_75kplus_train_007493 | 1,588 | no_license | [
{
"docstring": "This methods will be called when an object of this class is instantiated. It initializes variables and calls methods. :param model: the input model :param args: arguments :param kwargs: keyword arguments",
"name": "__init__",
"signature": "def __init__(self, model, *args, **kwargs)"
},... | 3 | stack_v2_sparse_classes_30k_train_028301 | Implement the Python class `ProgressPage` described below.
Class description:
Subclass of tk.Frame. This class creates and layouts widgets for the third page of the GUI. This class shows a loading label until pipeline is finished.
Method signatures and docstrings:
- def __init__(self, model, *args, **kwargs): This me... | Implement the Python class `ProgressPage` described below.
Class description:
Subclass of tk.Frame. This class creates and layouts widgets for the third page of the GUI. This class shows a loading label until pipeline is finished.
Method signatures and docstrings:
- def __init__(self, model, *args, **kwargs): This me... | 8152080f00249c4f63beb02106f11104a90a9621 | <|skeleton|>
class ProgressPage:
"""Subclass of tk.Frame. This class creates and layouts widgets for the third page of the GUI. This class shows a loading label until pipeline is finished."""
def __init__(self, model, *args, **kwargs):
"""This methods will be called when an object of this class is inst... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProgressPage:
"""Subclass of tk.Frame. This class creates and layouts widgets for the third page of the GUI. This class shows a loading label until pipeline is finished."""
def __init__(self, model, *args, **kwargs):
"""This methods will be called when an object of this class is instantiated. It ... | the_stack_v2_python_sparse | SATRO/Modules/UserInterface/progresspage.py | Beniiii/dt_radio_telescope | train | 0 |
6e3f40715f8a6cd83d41f632df9abf2f9f5acd03 | [
"self.player = player1\nself.hits = player1.hits\nself.misses = player1.misses\nself.print_accuracy()",
"total = self.hits + self.misses\nprint(responses[21])\nprint(responses[18] % (self.hits / total * 100, total))\nif Save_Accuracy:\n with open('score_data.txt', 'a') as file:\n file.write('\\n%s' % st... | <|body_start_0|>
self.player = player1
self.hits = player1.hits
self.misses = player1.misses
self.print_accuracy()
<|end_body_0|>
<|body_start_1|>
total = self.hits + self.misses
print(responses[21])
print(responses[18] % (self.hits / total * 100, total))
... | This Class Exception is used for flow control and to display data when called. | GameWin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GameWin:
"""This Class Exception is used for flow control and to display data when called."""
def __init__(self, player1):
"""The __init__ computes a players accuracy and displays it. :param player1:"""
<|body_0|>
def print_accuracy(self):
"""This function is use... | stack_v2_sparse_classes_75kplus_train_007494 | 29,261 | permissive | [
{
"docstring": "The __init__ computes a players accuracy and displays it. :param player1:",
"name": "__init__",
"signature": "def __init__(self, player1)"
},
{
"docstring": "This function is used to computer and display player accuracy.",
"name": "print_accuracy",
"signature": "def print... | 2 | stack_v2_sparse_classes_30k_train_012870 | Implement the Python class `GameWin` described below.
Class description:
This Class Exception is used for flow control and to display data when called.
Method signatures and docstrings:
- def __init__(self, player1): The __init__ computes a players accuracy and displays it. :param player1:
- def print_accuracy(self):... | Implement the Python class `GameWin` described below.
Class description:
This Class Exception is used for flow control and to display data when called.
Method signatures and docstrings:
- def __init__(self, player1): The __init__ computes a players accuracy and displays it. :param player1:
- def print_accuracy(self):... | 2b6e173bf739bda2926bf3d4a300d9a36cb9b85c | <|skeleton|>
class GameWin:
"""This Class Exception is used for flow control and to display data when called."""
def __init__(self, player1):
"""The __init__ computes a players accuracy and displays it. :param player1:"""
<|body_0|>
def print_accuracy(self):
"""This function is use... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GameWin:
"""This Class Exception is used for flow control and to display data when called."""
def __init__(self, player1):
"""The __init__ computes a players accuracy and displays it. :param player1:"""
self.player = player1
self.hits = player1.hits
self.misses = player1.m... | the_stack_v2_python_sparse | Old/Other_Scripts/Battleship_new_ai_0_9_7_wcomments.py | zeziba/Battleship_revisited | train | 0 |
13a0970e3c65919070d847fb2bf32a83e05b6088 | [
"prev_num_ways, num_ways, pre_digit = (0, int(s > ''), '')\nfor cur_digit in s:\n p_num_ways = prev_num_ways\n prev_num_ways = num_ways\n num_ways = (cur_digit > '0') * num_ways + (9 < int(pre_digit + cur_digit) < 27) * p_num_ways\n pre_digit = cur_digit\nreturn num_ways",
"if s is None or len(s) == 0... | <|body_start_0|>
prev_num_ways, num_ways, pre_digit = (0, int(s > ''), '')
for cur_digit in s:
p_num_ways = prev_num_ways
prev_num_ways = num_ways
num_ways = (cur_digit > '0') * num_ways + (9 < int(pre_digit + cur_digit) < 27) * p_num_ways
pre_digit = cur_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numDecodings(self, s):
""":type s: str :rtype: int num_ways tells the number of ways prev_num_ways tells the previous number of ways cur_digit is the current digit pre_digit is the previous digit beats 84.18%"""
<|body_0|>
def numDecodings1(self, s):
""... | stack_v2_sparse_classes_75kplus_train_007495 | 1,659 | no_license | [
{
"docstring": ":type s: str :rtype: int num_ways tells the number of ways prev_num_ways tells the previous number of ways cur_digit is the current digit pre_digit is the previous digit beats 84.18%",
"name": "numDecodings",
"signature": "def numDecodings(self, s)"
},
{
"docstring": ":type s: st... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numDecodings(self, s): :type s: str :rtype: int num_ways tells the number of ways prev_num_ways tells the previous number of ways cur_digit is the current digit pre_digit is ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numDecodings(self, s): :type s: str :rtype: int num_ways tells the number of ways prev_num_ways tells the previous number of ways cur_digit is the current digit pre_digit is ... | 7e0e917c15d3e35f49da3a00ef395bd5ff180d79 | <|skeleton|>
class Solution:
def numDecodings(self, s):
""":type s: str :rtype: int num_ways tells the number of ways prev_num_ways tells the previous number of ways cur_digit is the current digit pre_digit is the previous digit beats 84.18%"""
<|body_0|>
def numDecodings1(self, s):
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def numDecodings(self, s):
""":type s: str :rtype: int num_ways tells the number of ways prev_num_ways tells the previous number of ways cur_digit is the current digit pre_digit is the previous digit beats 84.18%"""
prev_num_ways, num_ways, pre_digit = (0, int(s > ''), '')
fo... | the_stack_v2_python_sparse | LeetCode/091_decode_ways.py | yao23/Machine_Learning_Playground | train | 12 | |
cab1175a1f05b916f942b1f7256aeebfa52af0fa | [
"super(IPAMAddressPool, self).__init__()\nself.schema_class = 'ipam_address_pool_schema.IPAMAddressPoolSchema'\nself.set_connection(vsm.get_connection())\nself.set_create_endpoint('/services/ipam/pools/scope/globalroot-0')\nself.set_read_endpoint('/services/ipam/pools')\nself.set_delete_endpoint('/services/ipam/poo... | <|body_start_0|>
super(IPAMAddressPool, self).__init__()
self.schema_class = 'ipam_address_pool_schema.IPAMAddressPoolSchema'
self.set_connection(vsm.get_connection())
self.set_create_endpoint('/services/ipam/pools/scope/globalroot-0')
self.set_read_endpoint('/services/ipam/pools... | IPAMAddressPool | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IPAMAddressPool:
def __init__(self, vsm):
"""Constructor to create IPAMAddressPool managed object @param vsm object on which IPAM address pool has to be configured"""
<|body_0|>
def delete(self, schema_object=None, url_parameters=None):
"""When delete ippool, the sch... | stack_v2_sparse_classes_75kplus_train_007496 | 2,254 | no_license | [
{
"docstring": "Constructor to create IPAMAddressPool managed object @param vsm object on which IPAM address pool has to be configured",
"name": "__init__",
"signature": "def __init__(self, vsm)"
},
{
"docstring": "When delete ippool, the scheam_obj should be set None.",
"name": "delete",
... | 2 | stack_v2_sparse_classes_30k_train_029462 | Implement the Python class `IPAMAddressPool` described below.
Class description:
Implement the IPAMAddressPool class.
Method signatures and docstrings:
- def __init__(self, vsm): Constructor to create IPAMAddressPool managed object @param vsm object on which IPAM address pool has to be configured
- def delete(self, s... | Implement the Python class `IPAMAddressPool` described below.
Class description:
Implement the IPAMAddressPool class.
Method signatures and docstrings:
- def __init__(self, vsm): Constructor to create IPAMAddressPool managed object @param vsm object on which IPAM address pool has to be configured
- def delete(self, s... | 5b55817c050b637e2747084290f6206d2e622938 | <|skeleton|>
class IPAMAddressPool:
def __init__(self, vsm):
"""Constructor to create IPAMAddressPool managed object @param vsm object on which IPAM address pool has to be configured"""
<|body_0|>
def delete(self, schema_object=None, url_parameters=None):
"""When delete ippool, the sch... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IPAMAddressPool:
def __init__(self, vsm):
"""Constructor to create IPAMAddressPool managed object @param vsm object on which IPAM address pool has to be configured"""
super(IPAMAddressPool, self).__init__()
self.schema_class = 'ipam_address_pool_schema.IPAMAddressPoolSchema'
se... | the_stack_v2_python_sparse | SystemTesting/pylib/nsx/vsm/ipam_address_pool/ipam_address_pool.py | Cloudxtreme/MyProject | train | 0 | |
5d148267feda7ced61fd42724430edf36f69c76b | [
"config = casper_formatters.FormatterConfig.from_dict({'rename_labels': {'SL:MUSIC_ITEM': 'SL:THING', 'SL:PLAYLIST': ''}})\nexemplar_outputs, orig_output = casper_formatters.top_funcall_processor([_MUSIC_EXAMPLES[0], _MUSIC_EXAMPLES[1]], _MUSIC_EXAMPLES[2], config)\nself.assertEqual(exemplar_outputs, ['[IN add to p... | <|body_start_0|>
config = casper_formatters.FormatterConfig.from_dict({'rename_labels': {'SL:MUSIC_ITEM': 'SL:THING', 'SL:PLAYLIST': ''}})
exemplar_outputs, orig_output = casper_formatters.top_funcall_processor([_MUSIC_EXAMPLES[0], _MUSIC_EXAMPLES[1]], _MUSIC_EXAMPLES[2], config)
self.assertEqua... | TopFuncallProcessorTest | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopFuncallProcessorTest:
def test_rename_labels(self):
"""Tests rename on the labels."""
<|body_0|>
def test_anonymize(self):
"""Tests anonymization."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
config = casper_formatters.FormatterConfig.from_dic... | stack_v2_sparse_classes_75kplus_train_007497 | 7,201 | permissive | [
{
"docstring": "Tests rename on the labels.",
"name": "test_rename_labels",
"signature": "def test_rename_labels(self)"
},
{
"docstring": "Tests anonymization.",
"name": "test_anonymize",
"signature": "def test_anonymize(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_035862 | Implement the Python class `TopFuncallProcessorTest` described below.
Class description:
Implement the TopFuncallProcessorTest class.
Method signatures and docstrings:
- def test_rename_labels(self): Tests rename on the labels.
- def test_anonymize(self): Tests anonymization. | Implement the Python class `TopFuncallProcessorTest` described below.
Class description:
Implement the TopFuncallProcessorTest class.
Method signatures and docstrings:
- def test_rename_labels(self): Tests rename on the labels.
- def test_anonymize(self): Tests anonymization.
<|skeleton|>
class TopFuncallProcessorTe... | ac9447064195e06de48cc91ff642f7fffa28ffe8 | <|skeleton|>
class TopFuncallProcessorTest:
def test_rename_labels(self):
"""Tests rename on the labels."""
<|body_0|>
def test_anonymize(self):
"""Tests anonymization."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TopFuncallProcessorTest:
def test_rename_labels(self):
"""Tests rename on the labels."""
config = casper_formatters.FormatterConfig.from_dict({'rename_labels': {'SL:MUSIC_ITEM': 'SL:THING', 'SL:PLAYLIST': ''}})
exemplar_outputs, orig_output = casper_formatters.top_funcall_processor([_M... | the_stack_v2_python_sparse | language/casper/augment/casper_formatters_test.py | google-research/language | train | 1,567 | |
61ec6565de9752f5c567aa81cf1e4c403c4d9b24 | [
"if ref is not None:\n if not isinstance(ref, pd.Index):\n if hasattr(ref, 'columns') and isinstance(ref.index, pd.Index):\n ref = ref.columns\n else:\n ref = pd.Index(ref)\n obj = self._get_indices(ref, obj)\nif np.issubdtype(type(obj), np.integer):\n obj = int(obj)\nif isinsta... | <|body_start_0|>
if ref is not None:
if not isinstance(ref, pd.Index):
if hasattr(ref, 'columns') and isinstance(ref.index, pd.Index):
ref = ref.columns
else:
ref = pd.Index(ref)
obj = self._get_indices(ref, obj)
if ... | Mixin class with utilities for by-column applicates. | _ColumnEstimator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _ColumnEstimator:
"""Mixin class with utilities for by-column applicates."""
def _coerce_to_pd_index(self, obj, ref=None):
"""Coerce obj to pandas Index, replacing ints by index elements. Parameters ---------- obj : iterable of pandas compatible index elements or int ref : reference ... | stack_v2_sparse_classes_75kplus_train_007498 | 36,566 | permissive | [
{
"docstring": "Coerce obj to pandas Index, replacing ints by index elements. Parameters ---------- obj : iterable of pandas compatible index elements or int ref : reference index, coercible to pd.Index, optional, default=None Returns ------- obj coerced to pd.Index if ref was passed, and if obj had int or np.i... | 4 | stack_v2_sparse_classes_30k_train_041004 | Implement the Python class `_ColumnEstimator` described below.
Class description:
Mixin class with utilities for by-column applicates.
Method signatures and docstrings:
- def _coerce_to_pd_index(self, obj, ref=None): Coerce obj to pandas Index, replacing ints by index elements. Parameters ---------- obj : iterable of... | Implement the Python class `_ColumnEstimator` described below.
Class description:
Mixin class with utilities for by-column applicates.
Method signatures and docstrings:
- def _coerce_to_pd_index(self, obj, ref=None): Coerce obj to pandas Index, replacing ints by index elements. Parameters ---------- obj : iterable of... | 70b2bfaaa597eb31bc3a1032366dcc0e1f4c8a9f | <|skeleton|>
class _ColumnEstimator:
"""Mixin class with utilities for by-column applicates."""
def _coerce_to_pd_index(self, obj, ref=None):
"""Coerce obj to pandas Index, replacing ints by index elements. Parameters ---------- obj : iterable of pandas compatible index elements or int ref : reference ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _ColumnEstimator:
"""Mixin class with utilities for by-column applicates."""
def _coerce_to_pd_index(self, obj, ref=None):
"""Coerce obj to pandas Index, replacing ints by index elements. Parameters ---------- obj : iterable of pandas compatible index elements or int ref : reference index, coerci... | the_stack_v2_python_sparse | sktime/base/_meta.py | sktime/sktime | train | 1,117 |
47d9058d22808641d67097d05b2c83062dd64671 | [
"self.resource = resource\nself.loader = loader\nself.variable_manager = variable_manager\nself.inventory = Inventory(loader=self.loader, variable_manager=self.variable_manager, host_list=[])\nself.gen_inventory()",
"my_group = Group(name=groupname)\nif groupvars:\n for key, value in groupvars.iteritems():\n ... | <|body_start_0|>
self.resource = resource
self.loader = loader
self.variable_manager = variable_manager
self.inventory = Inventory(loader=self.loader, variable_manager=self.variable_manager, host_list=[])
self.gen_inventory()
<|end_body_0|>
<|body_start_1|>
my_group = Gr... | this is my ansible inventory object. | MyInventory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyInventory:
"""this is my ansible inventory object."""
def __init__(self, resource, loader, variable_manager):
"""resource的数据格式是一个列表字典,比如 { "group1": { "hosts": [{"hostname": "10.10.10.10", "port": "22", "username": "test", "password": "mypass"}, ...], "vars": {"var1": value1, "var2... | stack_v2_sparse_classes_75kplus_train_007499 | 18,742 | no_license | [
{
"docstring": "resource的数据格式是一个列表字典,比如 { \"group1\": { \"hosts\": [{\"hostname\": \"10.10.10.10\", \"port\": \"22\", \"username\": \"test\", \"password\": \"mypass\"}, ...], \"vars\": {\"var1\": value1, \"var2\": value2, ...} } } 如果你只传入1个列表,这默认该列表内的所有主机属于my_group组,比如 [{\"hostname\": \"10.10.10.10\", \"port\": ... | 3 | null | Implement the Python class `MyInventory` described below.
Class description:
this is my ansible inventory object.
Method signatures and docstrings:
- def __init__(self, resource, loader, variable_manager): resource的数据格式是一个列表字典,比如 { "group1": { "hosts": [{"hostname": "10.10.10.10", "port": "22", "username": "test", "p... | Implement the Python class `MyInventory` described below.
Class description:
this is my ansible inventory object.
Method signatures and docstrings:
- def __init__(self, resource, loader, variable_manager): resource的数据格式是一个列表字典,比如 { "group1": { "hosts": [{"hostname": "10.10.10.10", "port": "22", "username": "test", "p... | 9d9e34c14c4effb79ec342ca8fabd426199a282a | <|skeleton|>
class MyInventory:
"""this is my ansible inventory object."""
def __init__(self, resource, loader, variable_manager):
"""resource的数据格式是一个列表字典,比如 { "group1": { "hosts": [{"hostname": "10.10.10.10", "port": "22", "username": "test", "password": "mypass"}, ...], "vars": {"var1": value1, "var2... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyInventory:
"""this is my ansible inventory object."""
def __init__(self, resource, loader, variable_manager):
"""resource的数据格式是一个列表字典,比如 { "group1": { "hosts": [{"hostname": "10.10.10.10", "port": "22", "username": "test", "password": "mypass"}, ...], "vars": {"var1": value1, "var2": value2, ..... | the_stack_v2_python_sparse | api/ansible_api.py | wuhfen/eva | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.