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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1e0238e0b22f1046f157c9af5371a21df2f47972 | [
"iccfobject.icCFObject.__init__(self, *args, UID_=iccfobject.ANY_UID, **kwargs)\nself.requisites = []\nself.img_filename = os.path.dirname(os.path.dirname(__file__)) + '/img/table.png'",
"if Res_ is None:\n return\nself.name = Res_[0][1][5][1][2]\nself.requisites = []\nfor res in Res_[2][2:]:\n requisite = ... | <|body_start_0|>
iccfobject.icCFObject.__init__(self, *args, UID_=iccfobject.ANY_UID, **kwargs)
self.requisites = []
self.img_filename = os.path.dirname(os.path.dirname(__file__)) + '/img/table.png'
<|end_body_0|>
<|body_start_1|>
if Res_ is None:
return
self.name = ... | Класс элемента табличной части документа. | icCFDocTab | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class icCFDocTab:
"""Класс элемента табличной части документа."""
def __init__(self, *args, **kwargs):
"""Конструктор. ВНИМАНИЕ! Если UID не определн (NONE_UID), то должен UID-любой (ANY_UID), чтобы отличать объекты от папок."""
<|body_0|>
def init(self, Res_=None):
""... | stack_v2_sparse_classes_75kplus_train_072200 | 10,445 | no_license | [
{
"docstring": "Конструктор. ВНИМАНИЕ! Если UID не определн (NONE_UID), то должен UID-любой (ANY_UID), чтобы отличать объекты от папок.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Инициализировать внутренние атрибуты по ресурсу.",
"name": "init... | 2 | stack_v2_sparse_classes_30k_train_013410 | Implement the Python class `icCFDocTab` described below.
Class description:
Класс элемента табличной части документа.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Конструктор. ВНИМАНИЕ! Если UID не определн (NONE_UID), то должен UID-любой (ANY_UID), чтобы отличать объекты от папок.
- def i... | Implement the Python class `icCFDocTab` described below.
Class description:
Класс элемента табличной части документа.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Конструктор. ВНИМАНИЕ! Если UID не определн (NONE_UID), то должен UID-любой (ANY_UID), чтобы отличать объекты от папок.
- def i... | e96f00f8260b2df8a882298e54276d1aa011e31c | <|skeleton|>
class icCFDocTab:
"""Класс элемента табличной части документа."""
def __init__(self, *args, **kwargs):
"""Конструктор. ВНИМАНИЕ! Если UID не определн (NONE_UID), то должен UID-любой (ANY_UID), чтобы отличать объекты от папок."""
<|body_0|>
def init(self, Res_=None):
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class icCFDocTab:
"""Класс элемента табличной части документа."""
def __init__(self, *args, **kwargs):
"""Конструктор. ВНИМАНИЕ! Если UID не определн (NONE_UID), то должен UID-любой (ANY_UID), чтобы отличать объекты от папок."""
iccfobject.icCFObject.__init__(self, *args, UID_=iccfobject.ANY_UI... | the_stack_v2_python_sparse | icpatcher/cf_obj/iccfdocument.py | XHermitOne/cf_patcher | train | 0 |
62b1a44f5e30692e4bd52c60bae5b04cd68440ff | [
"files = []\npattern_obj = re.compile(pattern)\nfor path, _, filenames in os.walk(root):\n for filename in filenames:\n if pattern_obj.match(filename) is not None:\n files.append(os.path.join(path, filename).replace('\\\\', '/'))\nreturn files",
"files = FFC.find_files(root, filename_pattern)... | <|body_start_0|>
files = []
pattern_obj = re.compile(pattern)
for path, _, filenames in os.walk(root):
for filename in filenames:
if pattern_obj.match(filename) is not None:
files.append(os.path.join(path, filename).replace('\\', '/'))
retu... | FFC Find File Contents | FFC | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FFC:
"""FFC Find File Contents"""
def find_files(root, pattern='.*'):
"""ex.1 >>> root = './folder01' >>> FFC.find_files(root) [ './folder01/file_01_01.txt', './folder01/file_01_02.txt', './folder01/file_01_03.pdf', './folder01/folder02/file_02_01.txt' ] ex.2 >>> root = './folder01' ... | stack_v2_sparse_classes_75kplus_train_072201 | 3,588 | no_license | [
{
"docstring": "ex.1 >>> root = './folder01' >>> FFC.find_files(root) [ './folder01/file_01_01.txt', './folder01/file_01_02.txt', './folder01/file_01_03.pdf', './folder01/folder02/file_02_01.txt' ] ex.2 >>> root = './folder01' >>> pattern = r'.*\\\\.txt' >>> FFC.find_files(root, pattern) [ './folder01/file_01_0... | 2 | stack_v2_sparse_classes_30k_train_052055 | Implement the Python class `FFC` described below.
Class description:
FFC Find File Contents
Method signatures and docstrings:
- def find_files(root, pattern='.*'): ex.1 >>> root = './folder01' >>> FFC.find_files(root) [ './folder01/file_01_01.txt', './folder01/file_01_02.txt', './folder01/file_01_03.pdf', './folder01... | Implement the Python class `FFC` described below.
Class description:
FFC Find File Contents
Method signatures and docstrings:
- def find_files(root, pattern='.*'): ex.1 >>> root = './folder01' >>> FFC.find_files(root) [ './folder01/file_01_01.txt', './folder01/file_01_02.txt', './folder01/file_01_03.pdf', './folder01... | 2196b96eb7e67e13bf2176c17bfb28cde7d04f1a | <|skeleton|>
class FFC:
"""FFC Find File Contents"""
def find_files(root, pattern='.*'):
"""ex.1 >>> root = './folder01' >>> FFC.find_files(root) [ './folder01/file_01_01.txt', './folder01/file_01_02.txt', './folder01/file_01_03.pdf', './folder01/folder02/file_02_01.txt' ] ex.2 >>> root = './folder01' ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FFC:
"""FFC Find File Contents"""
def find_files(root, pattern='.*'):
"""ex.1 >>> root = './folder01' >>> FFC.find_files(root) [ './folder01/file_01_01.txt', './folder01/file_01_02.txt', './folder01/file_01_03.pdf', './folder01/folder02/file_02_01.txt' ] ex.2 >>> root = './folder01' >>> pattern =... | the_stack_v2_python_sparse | python/find_file_content/find_file_contents.py | Ya-Za/codes | train | 0 |
3cccbf793c314f62b5250a098d7b8b26ad9ac595 | [
"self.ex_content = '^[O.\\\\nU ]+$'\nself.ex_choice = '^[1-9][0-9]+$'\nself.dir_to_search = args\nself.maps = []\nself.nb_carte = -1",
"if self.nb_carte <= 0:\n print('no map found', file=sys.stderr)\n sys.exit(1)\nprint('Labytinthes existant :')\nfor i, carte in enumerate(self.maps):\n print(' {} - {}'... | <|body_start_0|>
self.ex_content = '^[O.\\nU ]+$'
self.ex_choice = '^[1-9][0-9]+$'
self.dir_to_search = args
self.maps = []
self.nb_carte = -1
<|end_body_0|>
<|body_start_1|>
if self.nb_carte <= 0:
print('no map found', file=sys.stderr)
sys.exit(1... | classe qui permet de recurpere les maps d'un dossier choisi | Maps | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Maps:
"""classe qui permet de recurpere les maps d'un dossier choisi"""
def __init__(self, *args):
"""fonction constructeur de la classe"""
<|body_0|>
def displayMenu(self):
"""affiche toute les maps trouver raise une erreur si aucun map n'a etait trouver"""
... | stack_v2_sparse_classes_75kplus_train_072202 | 3,286 | no_license | [
{
"docstring": "fonction constructeur de la classe",
"name": "__init__",
"signature": "def __init__(self, *args)"
},
{
"docstring": "affiche toute les maps trouver raise une erreur si aucun map n'a etait trouver",
"name": "displayMenu",
"signature": "def displayMenu(self)"
},
{
"... | 6 | null | Implement the Python class `Maps` described below.
Class description:
classe qui permet de recurpere les maps d'un dossier choisi
Method signatures and docstrings:
- def __init__(self, *args): fonction constructeur de la classe
- def displayMenu(self): affiche toute les maps trouver raise une erreur si aucun map n'a ... | Implement the Python class `Maps` described below.
Class description:
classe qui permet de recurpere les maps d'un dossier choisi
Method signatures and docstrings:
- def __init__(self, *args): fonction constructeur de la classe
- def displayMenu(self): affiche toute les maps trouver raise une erreur si aucun map n'a ... | 0fb074ba5421870ebb36a2b6f5eb9107fd02f296 | <|skeleton|>
class Maps:
"""classe qui permet de recurpere les maps d'un dossier choisi"""
def __init__(self, *args):
"""fonction constructeur de la classe"""
<|body_0|>
def displayMenu(self):
"""affiche toute les maps trouver raise une erreur si aucun map n'a etait trouver"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Maps:
"""classe qui permet de recurpere les maps d'un dossier choisi"""
def __init__(self, *args):
"""fonction constructeur de la classe"""
self.ex_content = '^[O.\\nU ]+$'
self.ex_choice = '^[1-9][0-9]+$'
self.dir_to_search = args
self.maps = []
self.nb_ca... | the_stack_v2_python_sparse | activity/labyrinthe_2/Class/Maps.py | FirelightFlagboy/OPC-python | train | 0 |
09acf4bd8667cd25a043564452c6daf34b567b14 | [
"m, n = pic_dt.shape\nif resize is None:\n n_new, m_new = (np.round(x_scale * n).astype(int), np.round(y_scale * m).astype(int))\nelse:\n n_new, m_new = resize\nfx, fy = (n / n_new, m / m_new)\nidx_x_orign = np.array(list(range(n_new)) * m_new).reshape(m_new, n_new)\nidx_y_orign = np.repeat(list(range(m_new))... | <|body_start_0|>
m, n = pic_dt.shape
if resize is None:
n_new, m_new = (np.round(x_scale * n).astype(int), np.round(y_scale * m).astype(int))
else:
n_new, m_new = resize
fx, fy = (n / n_new, m / m_new)
idx_x_orign = np.array(list(range(n_new)) * m_new).res... | 图片缩放:包含两个方法 INTER_NEAREST 最近邻插值 INTER_LINEAR 双线性插值 例子: pic_sc = pic_scale() pic_sc.pic_resize(img_dt, resize, fx=None, fy=None, interpolation = pic_sc.INTER_LINEAR) | pic_scale | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class pic_scale:
"""图片缩放:包含两个方法 INTER_NEAREST 最近邻插值 INTER_LINEAR 双线性插值 例子: pic_sc = pic_scale() pic_sc.pic_resize(img_dt, resize, fx=None, fy=None, interpolation = pic_sc.INTER_LINEAR)"""
def INTER_NEAREST(self, pic_dt, resize, x_scale=None, y_scale=None):
"""最近邻插值(图片 m * n * 图层) param pic... | stack_v2_sparse_classes_75kplus_train_072203 | 5,079 | no_license | [
{
"docstring": "最近邻插值(图片 m * n * 图层) param pic_dt: 为一个图片的一个图层的数据 len(pic_dt) == 2 param resize: set (长, 宽) param x_scale: float 长度缩放大小 param y_scale: float 宽带缩放大小",
"name": "INTER_NEAREST",
"signature": "def INTER_NEAREST(self, pic_dt, resize, x_scale=None, y_scale=None)"
},
{
"docstring": "找位置,... | 4 | stack_v2_sparse_classes_30k_train_039602 | Implement the Python class `pic_scale` described below.
Class description:
图片缩放:包含两个方法 INTER_NEAREST 最近邻插值 INTER_LINEAR 双线性插值 例子: pic_sc = pic_scale() pic_sc.pic_resize(img_dt, resize, fx=None, fy=None, interpolation = pic_sc.INTER_LINEAR)
Method signatures and docstrings:
- def INTER_NEAREST(self, pic_dt, resize, x_... | Implement the Python class `pic_scale` described below.
Class description:
图片缩放:包含两个方法 INTER_NEAREST 最近邻插值 INTER_LINEAR 双线性插值 例子: pic_sc = pic_scale() pic_sc.pic_resize(img_dt, resize, fx=None, fy=None, interpolation = pic_sc.INTER_LINEAR)
Method signatures and docstrings:
- def INTER_NEAREST(self, pic_dt, resize, x_... | 122c43776c2b10bd5f9b9a299bdbf9739173ad46 | <|skeleton|>
class pic_scale:
"""图片缩放:包含两个方法 INTER_NEAREST 最近邻插值 INTER_LINEAR 双线性插值 例子: pic_sc = pic_scale() pic_sc.pic_resize(img_dt, resize, fx=None, fy=None, interpolation = pic_sc.INTER_LINEAR)"""
def INTER_NEAREST(self, pic_dt, resize, x_scale=None, y_scale=None):
"""最近邻插值(图片 m * n * 图层) param pic... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class pic_scale:
"""图片缩放:包含两个方法 INTER_NEAREST 最近邻插值 INTER_LINEAR 双线性插值 例子: pic_sc = pic_scale() pic_sc.pic_resize(img_dt, resize, fx=None, fy=None, interpolation = pic_sc.INTER_LINEAR)"""
def INTER_NEAREST(self, pic_dt, resize, x_scale=None, y_scale=None):
"""最近邻插值(图片 m * n * 图层) param pic_dt: 为一个图片的一个... | the_stack_v2_python_sparse | DataWhale计算机视觉入门/图片缩放.py | scchy/My_Learn | train | 4 |
e40ec0d6591dfb256b7d6d848564c6dc8b8027a5 | [
"_install.install.initialize_options(self)\nself.single_version_externally_managed = None\nif _option_defaults.has_key('install'):\n for opt_name, default in _option_defaults['install']:\n setattr(self, opt_name, default)",
"_install.install.finalize_options(self)\nif _option_inherits.has_key('install')... | <|body_start_0|>
_install.install.initialize_options(self)
self.single_version_externally_managed = None
if _option_defaults.has_key('install'):
for opt_name, default in _option_defaults['install']:
setattr(self, opt_name, default)
<|end_body_0|>
<|body_start_1|>
... | Extended installer to reflect the additional data options | Install | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Install:
"""Extended installer to reflect the additional data options"""
def initialize_options(self):
"""Prepare for new options"""
<|body_0|>
def finalize_options(self):
"""Finalize options"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
_inst... | stack_v2_sparse_classes_75kplus_train_072204 | 10,042 | permissive | [
{
"docstring": "Prepare for new options",
"name": "initialize_options",
"signature": "def initialize_options(self)"
},
{
"docstring": "Finalize options",
"name": "finalize_options",
"signature": "def finalize_options(self)"
}
] | 2 | null | Implement the Python class `Install` described below.
Class description:
Extended installer to reflect the additional data options
Method signatures and docstrings:
- def initialize_options(self): Prepare for new options
- def finalize_options(self): Finalize options | Implement the Python class `Install` described below.
Class description:
Extended installer to reflect the additional data options
Method signatures and docstrings:
- def initialize_options(self): Prepare for new options
- def finalize_options(self): Finalize options
<|skeleton|>
class Install:
"""Extended insta... | 53102de187a48ac2cfc241fef54dcbc29c453a8e | <|skeleton|>
class Install:
"""Extended installer to reflect the additional data options"""
def initialize_options(self):
"""Prepare for new options"""
<|body_0|>
def finalize_options(self):
"""Finalize options"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Install:
"""Extended installer to reflect the additional data options"""
def initialize_options(self):
"""Prepare for new options"""
_install.install.initialize_options(self)
self.single_version_externally_managed = None
if _option_defaults.has_key('install'):
... | the_stack_v2_python_sparse | common/py_vulcanize/third_party/rcssmin/_setup/py2/commands.py | catapult-project/catapult | train | 2,032 |
a9bcd469ac06483b6679e449cafb32d77768abc4 | [
"if 'username' in request.COOKIES:\n username = request.COOKIES.get('username')\n checked = 'checked'\nelse:\n username = ''\n checked = ''\nreturn render(request, 'login.html', {'username': username, 'checked': checked})",
"username = request.POST.get('username')\npassword = request.POST.get('pwd')\n... | <|body_start_0|>
if 'username' in request.COOKIES:
username = request.COOKIES.get('username')
checked = 'checked'
else:
username = ''
checked = ''
return render(request, 'login.html', {'username': username, 'checked': checked})
<|end_body_0|>
<|bo... | 登录 | LoginView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoginView:
"""登录"""
def get(self, request):
"""显示登录页面"""
<|body_0|>
def post(self, request):
"""登录校验"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if 'username' in request.COOKIES:
username = request.COOKIES.get('username')
... | stack_v2_sparse_classes_75kplus_train_072205 | 13,097 | no_license | [
{
"docstring": "显示登录页面",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "登录校验",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_028601 | Implement the Python class `LoginView` described below.
Class description:
登录
Method signatures and docstrings:
- def get(self, request): 显示登录页面
- def post(self, request): 登录校验 | Implement the Python class `LoginView` described below.
Class description:
登录
Method signatures and docstrings:
- def get(self, request): 显示登录页面
- def post(self, request): 登录校验
<|skeleton|>
class LoginView:
"""登录"""
def get(self, request):
"""显示登录页面"""
<|body_0|>
def post(self, request)... | e5cdc7c2d1f31e271a9d9cae1528bcf0a525ebe1 | <|skeleton|>
class LoginView:
"""登录"""
def get(self, request):
"""显示登录页面"""
<|body_0|>
def post(self, request):
"""登录校验"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LoginView:
"""登录"""
def get(self, request):
"""显示登录页面"""
if 'username' in request.COOKIES:
username = request.COOKIES.get('username')
checked = 'checked'
else:
username = ''
checked = ''
return render(request, 'login.html', {... | the_stack_v2_python_sparse | django/项目/dailyfresh/apps/user/views.py | 123qq97/dj_test | train | 0 |
3ace605741b2d99b274645bc6f29ef0491d9178f | [
"super().__init__(root)\nself.p = root.p\nself.root = root\nttk.Label(self, text='AGGIUNGI ETF').grid(row=0, column=0, columnspan=2, pady=10)\nttk.Label(self, text='Ticker', anchor='w', justify='left').grid(row=1, column=0, padx=5, pady=5)\nttk.Label(self, text='Data Acquisto', anchor='w', justify='left').grid(row=... | <|body_start_0|>
super().__init__(root)
self.p = root.p
self.root = root
ttk.Label(self, text='AGGIUNGI ETF').grid(row=0, column=0, columnspan=2, pady=10)
ttk.Label(self, text='Ticker', anchor='w', justify='left').grid(row=1, column=0, padx=5, pady=5)
ttk.Label(self, text... | Class representing a Frame responsable for the adding of an ETF | AddEtf | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddEtf:
"""Class representing a Frame responsable for the adding of an ETF"""
def __init__(self, root):
"""Given the master instaciate a class handling the adding function :param root: ttk.Frame"""
<|body_0|>
def add_etf(self):
"""When the Add button is clicked t... | stack_v2_sparse_classes_75kplus_train_072206 | 2,872 | no_license | [
{
"docstring": "Given the master instaciate a class handling the adding function :param root: ttk.Frame",
"name": "__init__",
"signature": "def __init__(self, root)"
},
{
"docstring": "When the Add button is clicked try adding the ETF. Display the result on the adjacent label. :return None",
... | 2 | null | Implement the Python class `AddEtf` described below.
Class description:
Class representing a Frame responsable for the adding of an ETF
Method signatures and docstrings:
- def __init__(self, root): Given the master instaciate a class handling the adding function :param root: ttk.Frame
- def add_etf(self): When the Ad... | Implement the Python class `AddEtf` described below.
Class description:
Class representing a Frame responsable for the adding of an ETF
Method signatures and docstrings:
- def __init__(self, root): Given the master instaciate a class handling the adding function :param root: ttk.Frame
- def add_etf(self): When the Ad... | 07da81d3715090abcfa6dc7e36cd693c27062fa5 | <|skeleton|>
class AddEtf:
"""Class representing a Frame responsable for the adding of an ETF"""
def __init__(self, root):
"""Given the master instaciate a class handling the adding function :param root: ttk.Frame"""
<|body_0|>
def add_etf(self):
"""When the Add button is clicked t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AddEtf:
"""Class representing a Frame responsable for the adding of an ETF"""
def __init__(self, root):
"""Given the master instaciate a class handling the adding function :param root: ttk.Frame"""
super().__init__(root)
self.p = root.p
self.root = root
ttk.Label(s... | the_stack_v2_python_sparse | pyetf/frames/main_page/add_etf.py | Alfre2000/PortfolioManager | train | 0 |
f1733a067212a77c6c208d96d1e98800b14ea1f2 | [
"Model.__init__(self)\nself.nS = nS\nself.nH = nH\nself.nM = nM\nself.nTGT = nTGT\nself.device = device\nself.enc = Encoder(nM=nM, nH=nH, device=device, nS=nS)\nself.norm = PyTorchWrapper(PytorchLayerNorm(nM=nM, device=device))\nself.dec = clone(DecoderLayer(nM=nM, nH=nH, device=device), nS)\nself.proj = with_resha... | <|body_start_0|>
Model.__init__(self)
self.nS = nS
self.nH = nH
self.nM = nM
self.nTGT = nTGT
self.device = device
self.enc = Encoder(nM=nM, nH=nH, device=device, nS=nS)
self.norm = PyTorchWrapper(PytorchLayerNorm(nM=nM, device=device))
self.dec = ... | EncoderDecoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderDecoder:
def __init__(self, nS=1, nH=6, nM=300, nTGT=10000, device='cpu'):
"""EncoderDecoder consists of an encoder stack, a decoder stack and an output layer which is a linear + softmax. Parameters explanation: nS: the number of encoders/decoders in the stack nH: the number of he... | stack_v2_sparse_classes_75kplus_train_072207 | 6,133 | permissive | [
{
"docstring": "EncoderDecoder consists of an encoder stack, a decoder stack and an output layer which is a linear + softmax. Parameters explanation: nS: the number of encoders/decoders in the stack nH: the number of heads in the multiheaded attention nM: the token's embedding size nTGT: the number of unique wo... | 2 | null | Implement the Python class `EncoderDecoder` described below.
Class description:
Implement the EncoderDecoder class.
Method signatures and docstrings:
- def __init__(self, nS=1, nH=6, nM=300, nTGT=10000, device='cpu'): EncoderDecoder consists of an encoder stack, a decoder stack and an output layer which is a linear +... | Implement the Python class `EncoderDecoder` described below.
Class description:
Implement the EncoderDecoder class.
Method signatures and docstrings:
- def __init__(self, nS=1, nH=6, nM=300, nTGT=10000, device='cpu'): EncoderDecoder consists of an encoder stack, a decoder stack and an output layer which is a linear +... | 92b328ff7ab99c368d31699817487e82cbe1cb9c | <|skeleton|>
class EncoderDecoder:
def __init__(self, nS=1, nH=6, nM=300, nTGT=10000, device='cpu'):
"""EncoderDecoder consists of an encoder stack, a decoder stack and an output layer which is a linear + softmax. Parameters explanation: nS: the number of encoders/decoders in the stack nH: the number of he... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EncoderDecoder:
def __init__(self, nS=1, nH=6, nM=300, nTGT=10000, device='cpu'):
"""EncoderDecoder consists of an encoder stack, a decoder stack and an output layer which is a linear + softmax. Parameters explanation: nS: the number of encoders/decoders in the stack nH: the number of heads in the mul... | the_stack_v2_python_sparse | thinc/neural/_classes/encoder_decoder.py | giannisdaras/thinc | train | 10 | |
c56ac94690fbec2ea84a0b954e0c54627a0dcb52 | [
"super().__init__(*args, **kwargs)\nself._gs_mix = float(gs_mix)\nassert 0.0 < self._gs_mix < 1.0, 'Mixing factor must be 0 < fac < 1'",
"assert self.imgpair is not None, 'Must have an image pair'\ndhs_step = self.imgpair.get_dhs_step_by_side(side, self._step_size)\ngs_step = self.imgpair.get_last_step_by_side(si... | <|body_start_0|>
super().__init__(*args, **kwargs)
self._gs_mix = float(gs_mix)
assert 0.0 < self._gs_mix < 1.0, 'Mixing factor must be 0 < fac < 1'
<|end_body_0|>
<|body_start_1|>
assert self.imgpair is not None, 'Must have an image pair'
dhs_step = self.imgpair.get_dhs_step_by... | Dewar-Healy-Stewart method, augmented with Growing String (GS) method. The DHS step (stepping along the linear interpolated path between the two images) is mixed with a GS step (linear interpolation along last and current position of one image) in a fixed ratio. Proposed by J. Kilmes, D. R. Bowler, A. Michaelides, J. P... | DHSGS | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DHSGS:
"""Dewar-Healy-Stewart method, augmented with Growing String (GS) method. The DHS step (stepping along the linear interpolated path between the two images) is mixed with a GS step (linear interpolation along last and current position of one image) in a fixed ratio. Proposed by J. Kilmes, D... | stack_v2_sparse_classes_75kplus_train_072208 | 26,310 | permissive | [
{
"docstring": "Arguments and other keyword arguments follow DHS, please see :py:meth:`DHS <autode.bracket.dhs.DHS.__init__>` Keyword Args: gs_mix (float): Represents the percentage of mixing of the Growing String step with the DHS step. 0.3 means 0.3 * GS_step + (1-0.3) * DHS_step It is not recommended to set ... | 2 | stack_v2_sparse_classes_30k_train_045706 | Implement the Python class `DHSGS` described below.
Class description:
Dewar-Healy-Stewart method, augmented with Growing String (GS) method. The DHS step (stepping along the linear interpolated path between the two images) is mixed with a GS step (linear interpolation along last and current position of one image) in ... | Implement the Python class `DHSGS` described below.
Class description:
Dewar-Healy-Stewart method, augmented with Growing String (GS) method. The DHS step (stepping along the linear interpolated path between the two images) is mixed with a GS step (linear interpolation along last and current position of one image) in ... | 4d6667592f083dfcf38de6b75c4222c0a0e7b60b | <|skeleton|>
class DHSGS:
"""Dewar-Healy-Stewart method, augmented with Growing String (GS) method. The DHS step (stepping along the linear interpolated path between the two images) is mixed with a GS step (linear interpolation along last and current position of one image) in a fixed ratio. Proposed by J. Kilmes, D... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DHSGS:
"""Dewar-Healy-Stewart method, augmented with Growing String (GS) method. The DHS step (stepping along the linear interpolated path between the two images) is mixed with a GS step (linear interpolation along last and current position of one image) in a fixed ratio. Proposed by J. Kilmes, D. R. Bowler, ... | the_stack_v2_python_sparse | autode/bracket/dhs.py | duartegroup/autodE | train | 132 |
a171616c200fddcadaffc9a70ab9203b6e70aace | [
"self.output_dir = output_dir\nif not Path(output_dir).exists():\n os.mkdir(output_dir)\n print(f'MemeGenerator created directory: {output_dir}')\ntry:\n fontFile = os.path.dirname(__file__) + '/fonts/Roboto-Black.ttf'\n self.font_quote = ImageFont.truetype(fontFile, size=30)\n self.font_author = Ima... | <|body_start_0|>
self.output_dir = output_dir
if not Path(output_dir).exists():
os.mkdir(output_dir)
print(f'MemeGenerator created directory: {output_dir}')
try:
fontFile = os.path.dirname(__file__) + '/fonts/Roboto-Black.ttf'
self.font_quote = Ima... | MemeGenerator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MemeGenerator:
def __init__(self, output_dir: str):
"""Create a MemeGenerator Argument: output_dir {str} -- the directory for storing pictures."""
<|body_0|>
def make_meme(self, in_path: str, quote: str, author: str, width: int=500) -> str:
"""Create a meme With a qu... | stack_v2_sparse_classes_75kplus_train_072209 | 2,707 | no_license | [
{
"docstring": "Create a MemeGenerator Argument: output_dir {str} -- the directory for storing pictures.",
"name": "__init__",
"signature": "def __init__(self, output_dir: str)"
},
{
"docstring": "Create a meme With a quote Arguments: in_path {str} -- the file location for the input image. text ... | 2 | stack_v2_sparse_classes_30k_train_049345 | Implement the Python class `MemeGenerator` described below.
Class description:
Implement the MemeGenerator class.
Method signatures and docstrings:
- def __init__(self, output_dir: str): Create a MemeGenerator Argument: output_dir {str} -- the directory for storing pictures.
- def make_meme(self, in_path: str, quote:... | Implement the Python class `MemeGenerator` described below.
Class description:
Implement the MemeGenerator class.
Method signatures and docstrings:
- def __init__(self, output_dir: str): Create a MemeGenerator Argument: output_dir {str} -- the directory for storing pictures.
- def make_meme(self, in_path: str, quote:... | 194c0a7c39527df6c3a29c64676541acb40f295a | <|skeleton|>
class MemeGenerator:
def __init__(self, output_dir: str):
"""Create a MemeGenerator Argument: output_dir {str} -- the directory for storing pictures."""
<|body_0|>
def make_meme(self, in_path: str, quote: str, author: str, width: int=500) -> str:
"""Create a meme With a qu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MemeGenerator:
def __init__(self, output_dir: str):
"""Create a MemeGenerator Argument: output_dir {str} -- the directory for storing pictures."""
self.output_dir = output_dir
if not Path(output_dir).exists():
os.mkdir(output_dir)
print(f'MemeGenerator created d... | the_stack_v2_python_sparse | MemeEngine/MemeGenerator.py | janroijen/meme-generator | train | 0 | |
f39b358718032abce243ea16cbddce4deb5fe10d | [
"self.tik_instance = tik.Tik()\nself.each_loop = shape[axis]\nself.dsize = get_data_size(dtype)\nself.each, self.each_tail = self.get_each(shape, axis)\nself.reserved = self.get_reserved()\nself.dtype = dtype",
"self.each = VALUE_ONE\nfor k in range(axis + VALUE_ONE, len(shape)):\n self.each = self.each * shap... | <|body_start_0|>
self.tik_instance = tik.Tik()
self.each_loop = shape[axis]
self.dsize = get_data_size(dtype)
self.each, self.each_tail = self.get_each(shape, axis)
self.reserved = self.get_reserved()
self.dtype = dtype
<|end_body_0|>
<|body_start_1|>
self.each =... | Function: use to store cumsum base parameters Modify : 2019-10-08 | CumBase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CumBase:
"""Function: use to store cumsum base parameters Modify : 2019-10-08"""
def __init__(self, shape, axis, dtype):
"""init the base param of cumsum Parameters ---------- shape: the shape of tensor axis: cumulative axis dtype: the data type of tensor Returns ------- None"""
... | stack_v2_sparse_classes_75kplus_train_072210 | 34,281 | no_license | [
{
"docstring": "init the base param of cumsum Parameters ---------- shape: the shape of tensor axis: cumulative axis dtype: the data type of tensor Returns ------- None",
"name": "__init__",
"signature": "def __init__(self, shape, axis, dtype)"
},
{
"docstring": "Calculate the length of each sep... | 3 | stack_v2_sparse_classes_30k_val_000785 | Implement the Python class `CumBase` described below.
Class description:
Function: use to store cumsum base parameters Modify : 2019-10-08
Method signatures and docstrings:
- def __init__(self, shape, axis, dtype): init the base param of cumsum Parameters ---------- shape: the shape of tensor axis: cumulative axis dt... | Implement the Python class `CumBase` described below.
Class description:
Function: use to store cumsum base parameters Modify : 2019-10-08
Method signatures and docstrings:
- def __init__(self, shape, axis, dtype): init the base param of cumsum Parameters ---------- shape: the shape of tensor axis: cumulative axis dt... | 148511a31bfd195df889291946c43bb585acb546 | <|skeleton|>
class CumBase:
"""Function: use to store cumsum base parameters Modify : 2019-10-08"""
def __init__(self, shape, axis, dtype):
"""init the base param of cumsum Parameters ---------- shape: the shape of tensor axis: cumulative axis dtype: the data type of tensor Returns ------- None"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CumBase:
"""Function: use to store cumsum base parameters Modify : 2019-10-08"""
def __init__(self, shape, axis, dtype):
"""init the base param of cumsum Parameters ---------- shape: the shape of tensor axis: cumulative axis dtype: the data type of tensor Returns ------- None"""
self.tik_... | the_stack_v2_python_sparse | convertor/huawei/impl/cum_computer.py | jizhuoran/caffe-huawei-atlas-convertor | train | 4 |
035657c6b6c9e1d0e365009106411ebd00015572 | [
"u_name = data_utils.rand_name('user')\nu_email = u_name + '@testmail.tm'\nu_password = data_utils.rand_password()\nself.assertRaises(lib_exc.NotFound, self.users_client.create_user, name=u_name, password=u_password, email=u_email, domain_id=data_utils.rand_uuid_hex())",
"password = data_utils.rand_password()\nus... | <|body_start_0|>
u_name = data_utils.rand_name('user')
u_email = u_name + '@testmail.tm'
u_password = data_utils.rand_password()
self.assertRaises(lib_exc.NotFound, self.users_client.create_user, name=u_name, password=u_password, email=u_email, domain_id=data_utils.rand_uuid_hex())
<|end... | Negative tests of keystone users | UsersNegativeTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UsersNegativeTest:
"""Negative tests of keystone users"""
def test_create_user_for_non_existent_domain(self):
"""Attempt to create a user in a non-existent domain should fail"""
<|body_0|>
def test_authentication_for_disabled_user(self):
"""Attempt to authenticat... | stack_v2_sparse_classes_75kplus_train_072211 | 2,185 | permissive | [
{
"docstring": "Attempt to create a user in a non-existent domain should fail",
"name": "test_create_user_for_non_existent_domain",
"signature": "def test_create_user_for_non_existent_domain(self)"
},
{
"docstring": "Attempt to authenticate for disabled user should fail",
"name": "test_authe... | 2 | stack_v2_sparse_classes_30k_train_036094 | Implement the Python class `UsersNegativeTest` described below.
Class description:
Negative tests of keystone users
Method signatures and docstrings:
- def test_create_user_for_non_existent_domain(self): Attempt to create a user in a non-existent domain should fail
- def test_authentication_for_disabled_user(self): A... | Implement the Python class `UsersNegativeTest` described below.
Class description:
Negative tests of keystone users
Method signatures and docstrings:
- def test_create_user_for_non_existent_domain(self): Attempt to create a user in a non-existent domain should fail
- def test_authentication_for_disabled_user(self): A... | 3932a799e620a20d7abf7b89e21b520683a1809b | <|skeleton|>
class UsersNegativeTest:
"""Negative tests of keystone users"""
def test_create_user_for_non_existent_domain(self):
"""Attempt to create a user in a non-existent domain should fail"""
<|body_0|>
def test_authentication_for_disabled_user(self):
"""Attempt to authenticat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UsersNegativeTest:
"""Negative tests of keystone users"""
def test_create_user_for_non_existent_domain(self):
"""Attempt to create a user in a non-existent domain should fail"""
u_name = data_utils.rand_name('user')
u_email = u_name + '@testmail.tm'
u_password = data_utils... | the_stack_v2_python_sparse | tempest/api/identity/admin/v3/test_users_negative.py | openstack/tempest | train | 270 |
c402149239b15407022a9b072d92d929820a964f | [
"self.main_path = main_path\nself.ch_list = ch_list\nself.win = win\nself.time_bins = time_bins\nself.feature_labels = []\nfor n in ch_list:\n self.feature_labels += [x.__name__ + '_' + str(n) for x in param_list]\nself.feature_labels += [x.__name__ for x in cross_ch_param_list]\nself.feature_labels = np.array(s... | <|body_start_0|>
self.main_path = main_path
self.ch_list = ch_list
self.win = win
self.time_bins = time_bins
self.feature_labels = []
for n in ch_list:
self.feature_labels += [x.__name__ + '_' + str(n) for x in param_list]
self.feature_labels += [x.__n... | Class -> GetCatalogue Retrieves seizure properties and saves to organized csv for each feature specified in param_list and cross_ch_param_list. | GetCatalogue | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetCatalogue:
"""Class -> GetCatalogue Retrieves seizure properties and saves to organized csv for each feature specified in param_list and cross_ch_param_list."""
def __init__(self, main_path):
"""GetCatalogue(main_path) Parameters ---------- input_path : STRING, Raw data path."""
... | stack_v2_sparse_classes_75kplus_train_072212 | 9,758 | permissive | [
{
"docstring": "GetCatalogue(main_path) Parameters ---------- input_path : STRING, Raw data path.",
"name": "__init__",
"signature": "def __init__(self, main_path)"
},
{
"docstring": "multi_folder(self) Loop though folder paths and append seizure properties to csv Parameters ---------- main_path... | 4 | stack_v2_sparse_classes_30k_train_040037 | Implement the Python class `GetCatalogue` described below.
Class description:
Class -> GetCatalogue Retrieves seizure properties and saves to organized csv for each feature specified in param_list and cross_ch_param_list.
Method signatures and docstrings:
- def __init__(self, main_path): GetCatalogue(main_path) Param... | Implement the Python class `GetCatalogue` described below.
Class description:
Class -> GetCatalogue Retrieves seizure properties and saves to organized csv for each feature specified in param_list and cross_ch_param_list.
Method signatures and docstrings:
- def __init__(self, main_path): GetCatalogue(main_path) Param... | fd238749a8b80af1bd0902f737bc9017c4e29756 | <|skeleton|>
class GetCatalogue:
"""Class -> GetCatalogue Retrieves seizure properties and saves to organized csv for each feature specified in param_list and cross_ch_param_list."""
def __init__(self, main_path):
"""GetCatalogue(main_path) Parameters ---------- input_path : STRING, Raw data path."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GetCatalogue:
"""Class -> GetCatalogue Retrieves seizure properties and saves to organized csv for each feature specified in param_list and cross_ch_param_list."""
def __init__(self, main_path):
"""GetCatalogue(main_path) Parameters ---------- input_path : STRING, Raw data path."""
self.m... | the_stack_v2_python_sparse | model_selection/get_seizure_catalogue.py | bhargavaganti/logic_seizedetect | train | 0 |
ce6ea196bc0450ee5d284cee0046a395c36214d6 | [
"self.player = player\nself.team = team\ntry:\n self.page = wikipedia.page(player)\n self.soup = BeautifulSoup(self.page.html())\nexcept wikipedia.exceptions.DisambiguationError as e:\n self._get_correct_page(e.options, team)\nself._gen_table()",
"best_candidate = None\nbest_yob = None\nfor option in opt... | <|body_start_0|>
self.player = player
self.team = team
try:
self.page = wikipedia.page(player)
self.soup = BeautifulSoup(self.page.html())
except wikipedia.exceptions.DisambiguationError as e:
self._get_correct_page(e.options, team)
self._gen_t... | WikipediaPlayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WikipediaPlayer:
def __init__(self, player, team):
"""initializes self.page to the correct wikipedia resource"""
<|body_0|>
def _get_correct_page(self, options, team):
"""gets appropiate wikipedia among options considering wether team is in html and age"""
<|... | stack_v2_sparse_classes_75kplus_train_072213 | 12,481 | permissive | [
{
"docstring": "initializes self.page to the correct wikipedia resource",
"name": "__init__",
"signature": "def __init__(self, player, team)"
},
{
"docstring": "gets appropiate wikipedia among options considering wether team is in html and age",
"name": "_get_correct_page",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_033081 | Implement the Python class `WikipediaPlayer` described below.
Class description:
Implement the WikipediaPlayer class.
Method signatures and docstrings:
- def __init__(self, player, team): initializes self.page to the correct wikipedia resource
- def _get_correct_page(self, options, team): gets appropiate wikipedia am... | Implement the Python class `WikipediaPlayer` described below.
Class description:
Implement the WikipediaPlayer class.
Method signatures and docstrings:
- def __init__(self, player, team): initializes self.page to the correct wikipedia resource
- def _get_correct_page(self, options, team): gets appropiate wikipedia am... | e3951450713f7cfaead070998e1b84d392114283 | <|skeleton|>
class WikipediaPlayer:
def __init__(self, player, team):
"""initializes self.page to the correct wikipedia resource"""
<|body_0|>
def _get_correct_page(self, options, team):
"""gets appropiate wikipedia among options considering wether team is in html and age"""
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WikipediaPlayer:
def __init__(self, player, team):
"""initializes self.page to the correct wikipedia resource"""
self.player = player
self.team = team
try:
self.page = wikipedia.page(player)
self.soup = BeautifulSoup(self.page.html())
except wiki... | the_stack_v2_python_sparse | basketball_reference/utils.py | nbaprediction/nba_prediction | train | 3 | |
4b49e5dafe85bdf719ea71f7ca194712e047becf | [
"pattern = re.compile(pattern)\nfor node, path in self._explore(node=folder, path=primitives.path()):\n match = pattern.match(str(path))\n if match:\n yield (node, match)\nreturn",
"yield (node, path)\nif not node.isFolder:\n return\nfor name, child in node.contents.items():\n yield from self._... | <|body_start_0|>
pattern = re.compile(pattern)
for node, path in self._explore(node=folder, path=primitives.path()):
match = pattern.match(str(path))
if match:
yield (node, match)
return
<|end_body_0|>
<|body_start_1|>
yield (node, path)
i... | A visitor that generates a list of the contents of a filesystem | Finder | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Finder:
"""A visitor that generates a list of the contents of a filesystem"""
def explore(self, folder, pattern='.*'):
"""Traverse the folder and return contents that match the given pattern"""
<|body_0|>
def _explore(self, node, path):
"""The recursive workhorse... | stack_v2_sparse_classes_75kplus_train_072214 | 1,535 | permissive | [
{
"docstring": "Traverse the folder and return contents that match the given pattern",
"name": "explore",
"signature": "def explore(self, folder, pattern='.*')"
},
{
"docstring": "The recursive workhorse for folder exploration",
"name": "_explore",
"signature": "def _explore(self, node, ... | 2 | stack_v2_sparse_classes_30k_train_029329 | Implement the Python class `Finder` described below.
Class description:
A visitor that generates a list of the contents of a filesystem
Method signatures and docstrings:
- def explore(self, folder, pattern='.*'): Traverse the folder and return contents that match the given pattern
- def _explore(self, node, path): Th... | Implement the Python class `Finder` described below.
Class description:
A visitor that generates a list of the contents of a filesystem
Method signatures and docstrings:
- def explore(self, folder, pattern='.*'): Traverse the folder and return contents that match the given pattern
- def _explore(self, node, path): Th... | d741c44ffb3e9e1f726bf492202ac8738bb4aa1c | <|skeleton|>
class Finder:
"""A visitor that generates a list of the contents of a filesystem"""
def explore(self, folder, pattern='.*'):
"""Traverse the folder and return contents that match the given pattern"""
<|body_0|>
def _explore(self, node, path):
"""The recursive workhorse... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Finder:
"""A visitor that generates a list of the contents of a filesystem"""
def explore(self, folder, pattern='.*'):
"""Traverse the folder and return contents that match the given pattern"""
pattern = re.compile(pattern)
for node, path in self._explore(node=folder, path=primiti... | the_stack_v2_python_sparse | packages/pyre/filesystem/Finder.py | pyre/pyre | train | 27 |
038253d8d04870fe6448a327cec1e8a9cbcf7583 | [
"for row in matrix:\n for num in row:\n print(num, end=' ')\n print()",
"n = len(matrix)\nresult = []\nfor j in range(n):\n curr = []\n i = 0\n while i < n and j > -1:\n curr.append(matrix[i][j])\n i += 1\n j -= 1\n result.append(curr)\nfor i in range(1, n):\n curr... | <|body_start_0|>
for row in matrix:
for num in row:
print(num, end=' ')
print()
<|end_body_0|>
<|body_start_1|>
n = len(matrix)
result = []
for j in range(n):
curr = []
i = 0
while i < n and j > -1:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def display(self, matrix):
"""Prints out 2-D matrix."""
<|body_0|>
def anti_diagonals(self, matrix):
"""Returns a new matrix(array of arrays) consisting of anti diagonals. Time complexity: O(n ^ n). Space complexity: O(n)."""
<|body_1|>
def ant... | stack_v2_sparse_classes_75kplus_train_072215 | 2,436 | no_license | [
{
"docstring": "Prints out 2-D matrix.",
"name": "display",
"signature": "def display(self, matrix)"
},
{
"docstring": "Returns a new matrix(array of arrays) consisting of anti diagonals. Time complexity: O(n ^ n). Space complexity: O(n).",
"name": "anti_diagonals",
"signature": "def ant... | 3 | stack_v2_sparse_classes_30k_train_001109 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def display(self, matrix): Prints out 2-D matrix.
- def anti_diagonals(self, matrix): Returns a new matrix(array of arrays) consisting of anti diagonals. Time complexity: O(n ^ n... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def display(self, matrix): Prints out 2-D matrix.
- def anti_diagonals(self, matrix): Returns a new matrix(array of arrays) consisting of anti diagonals. Time complexity: O(n ^ n... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class Solution:
def display(self, matrix):
"""Prints out 2-D matrix."""
<|body_0|>
def anti_diagonals(self, matrix):
"""Returns a new matrix(array of arrays) consisting of anti diagonals. Time complexity: O(n ^ n). Space complexity: O(n)."""
<|body_1|>
def ant... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def display(self, matrix):
"""Prints out 2-D matrix."""
for row in matrix:
for num in row:
print(num, end=' ')
print()
def anti_diagonals(self, matrix):
"""Returns a new matrix(array of arrays) consisting of anti diagonals. Time co... | the_stack_v2_python_sparse | Matrix_problems/anti_diagonals.py | vladn90/Algorithms | train | 0 | |
cf5d6991d93d68a34599efaf02b1169557da563c | [
"pair_nb = 0\nfound = []\nfor n in reversed(nums):\n pair_nb += bisect.bisect_left(found, n / 2)\n bisect.insort_right(found, n)\nreturn pair_nb",
"def lowest(val: int) -> int:\n if val % 2 == 1:\n return val // 2\n else:\n return val // 2 - 1\nall_nums = set(nums)\nfor n in nums:\n a... | <|body_start_0|>
pair_nb = 0
found = []
for n in reversed(nums):
pair_nb += bisect.bisect_left(found, n / 2)
bisect.insort_right(found, n)
return pair_nb
<|end_body_0|>
<|body_start_1|>
def lowest(val: int) -> int:
if val % 2 == 1:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reversePairs(self, nums: List[int]) -> int:
"""Binary search based solution: - add elements from right to left - binary search for elements higher at each element Complexity is O(N^2) because of the insertion in array. With TreeMap, would still be O(N^2) to compute the dist... | stack_v2_sparse_classes_75kplus_train_072216 | 2,739 | no_license | [
{
"docstring": "Binary search based solution: - add elements from right to left - binary search for elements higher at each element Complexity is O(N^2) because of the insertion in array. With TreeMap, would still be O(N^2) to compute the distance. Beats 42% (1800ms)",
"name": "reversePairs",
"signature... | 2 | stack_v2_sparse_classes_30k_train_022701 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reversePairs(self, nums: List[int]) -> int: Binary search based solution: - add elements from right to left - binary search for elements higher at each element Complexity is ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reversePairs(self, nums: List[int]) -> int: Binary search based solution: - add elements from right to left - binary search for elements higher at each element Complexity is ... | 3ffcfee5cedf421d5de6d0dec4ba53b0eecbbff8 | <|skeleton|>
class Solution:
def reversePairs(self, nums: List[int]) -> int:
"""Binary search based solution: - add elements from right to left - binary search for elements higher at each element Complexity is O(N^2) because of the insertion in array. With TreeMap, would still be O(N^2) to compute the dist... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reversePairs(self, nums: List[int]) -> int:
"""Binary search based solution: - add elements from right to left - binary search for elements higher at each element Complexity is O(N^2) because of the insertion in array. With TreeMap, would still be O(N^2) to compute the distance. Beats 42... | the_stack_v2_python_sparse | arrays/ReversePairs_HARD.py | QuentinDuval/PythonExperiments | train | 3 | |
88ddc618fabe7d263f17f589d98e6c9ef47ce7a8 | [
"super(GANLoss, self).__init__()\nself.register_buffer('real_label', torch.tensor(target_real_label))\nself.register_buffer('fake_label', torch.tensor(target_fake_label))\nself.gan_mode = gan_mode\nif gan_mode == 'lsgan':\n self.loss = nn.MSELoss()\nelif gan_mode == 'vanilla':\n self.loss = nn.BCEWithLogitsLo... | <|body_start_0|>
super(GANLoss, self).__init__()
self.register_buffer('real_label', torch.tensor(target_real_label))
self.register_buffer('fake_label', torch.tensor(target_fake_label))
self.gan_mode = gan_mode
if gan_mode == 'lsgan':
self.loss = nn.MSELoss()
e... | Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input. | GANLoss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GANLoss:
"""Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input."""
def __init__(self, gan_mode, target_real_label=-100.0, target_fake_label=100.0):
"""Initialize the GANLoss class. Parameter... | stack_v2_sparse_classes_75kplus_train_072217 | 15,130 | no_license | [
{
"docstring": "Initialize the GANLoss class. Parameters: gan_mode (str) - - the type of GAN objective. It currently supports vanilla, lsgan, and wgangp. target_real_label (bool) - - label for a real image target_fake_label (bool) - - label of a fake image Note: Do not use sigmoid as the last layer of Discrimin... | 3 | null | Implement the Python class `GANLoss` described below.
Class description:
Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input.
Method signatures and docstrings:
- def __init__(self, gan_mode, target_real_label=-100.0, target_f... | Implement the Python class `GANLoss` described below.
Class description:
Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input.
Method signatures and docstrings:
- def __init__(self, gan_mode, target_real_label=-100.0, target_f... | 732f41f010f3ae9b2b0aaed8d9808b2d2adcf053 | <|skeleton|>
class GANLoss:
"""Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input."""
def __init__(self, gan_mode, target_real_label=-100.0, target_fake_label=100.0):
"""Initialize the GANLoss class. Parameter... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GANLoss:
"""Define different GAN objectives. The GANLoss class abstracts away the need to create the target label tensor that has the same size as the input."""
def __init__(self, gan_mode, target_real_label=-100.0, target_fake_label=100.0):
"""Initialize the GANLoss class. Parameters: gan_mode (... | the_stack_v2_python_sparse | src/model/unet3d.py | githubbingb/GAN-based-Semantic-Segmentation- | train | 0 |
a65e02d10f4ec6f263099ffb97d369b8ce60dc58 | [
"try:\n handler = visitor.autogen\nexcept AttributeError:\n return super().identify(visitor=visitor, **kwds)\nreturn handler(language=self, **kwds)",
"yield from super().report()\nyield f' dialect: {self.dialect}'\nreturn"
] | <|body_start_0|>
try:
handler = visitor.autogen
except AttributeError:
return super().identify(visitor=visitor, **kwds)
return handler(language=self, **kwds)
<|end_body_0|>
<|body_start_1|>
yield from super().report()
yield f' dialect: {self.dialect}'
... | A category of source artifacts that are templates that expand into other artifacts | Autogen | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Autogen:
"""A category of source artifacts that are templates that expand into other artifacts"""
def identify(self, visitor, **kwds):
"""Ask {visitor} to process one of my source files"""
<|body_0|>
def report(self):
"""Generate a report"""
<|body_1|>
<... | stack_v2_sparse_classes_75kplus_train_072218 | 1,846 | permissive | [
{
"docstring": "Ask {visitor} to process one of my source files",
"name": "identify",
"signature": "def identify(self, visitor, **kwds)"
},
{
"docstring": "Generate a report",
"name": "report",
"signature": "def report(self)"
}
] | 2 | null | Implement the Python class `Autogen` described below.
Class description:
A category of source artifacts that are templates that expand into other artifacts
Method signatures and docstrings:
- def identify(self, visitor, **kwds): Ask {visitor} to process one of my source files
- def report(self): Generate a report | Implement the Python class `Autogen` described below.
Class description:
A category of source artifacts that are templates that expand into other artifacts
Method signatures and docstrings:
- def identify(self, visitor, **kwds): Ask {visitor} to process one of my source files
- def report(self): Generate a report
<|... | d741c44ffb3e9e1f726bf492202ac8738bb4aa1c | <|skeleton|>
class Autogen:
"""A category of source artifacts that are templates that expand into other artifacts"""
def identify(self, visitor, **kwds):
"""Ask {visitor} to process one of my source files"""
<|body_0|>
def report(self):
"""Generate a report"""
<|body_1|>
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Autogen:
"""A category of source artifacts that are templates that expand into other artifacts"""
def identify(self, visitor, **kwds):
"""Ask {visitor} to process one of my source files"""
try:
handler = visitor.autogen
except AttributeError:
return super()... | the_stack_v2_python_sparse | packages/merlin/languages/Autogen.py | pyre/pyre | train | 27 |
ebe34b5ef54df06e32fc428ca137f24d7da63308 | [
"client = Http_client()\nclient.get(url=url, params=jsondata, header=headers)\nassert client.status_code == checkpoint['status_code']\nassert len(client.jsonResponse['data']) == checkpoint['data']\nassert client.elapsed <= 20.0",
"client = Http_client()\nclient.get(url=url, params=eval(jsondata), header=headers)\... | <|body_start_0|>
client = Http_client()
client.get(url=url, params=jsondata, header=headers)
assert client.status_code == checkpoint['status_code']
assert len(client.jsonResponse['data']) == checkpoint['data']
assert client.elapsed <= 20.0
<|end_body_0|>
<|body_start_1|>
... | Test_GetAllStrategyInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_GetAllStrategyInfo:
def test_GetAllStrategyInfo200(self, url, jsondata, headers, checkpoint):
"""用例描述:Test_GetAllStrategyInfo200方法用于获取所有策略信息接口 json数据包含禅道上多条用例的校验,具体对body中不同功能的传参检查"""
<|body_0|>
def test_GetAllStrategyInfo_name_mode200(self, url, jsondata, headers, check... | stack_v2_sparse_classes_75kplus_train_072219 | 5,553 | no_license | [
{
"docstring": "用例描述:Test_GetAllStrategyInfo200方法用于获取所有策略信息接口 json数据包含禅道上多条用例的校验,具体对body中不同功能的传参检查",
"name": "test_GetAllStrategyInfo200",
"signature": "def test_GetAllStrategyInfo200(self, url, jsondata, headers, checkpoint)"
},
{
"docstring": "用例描述:Test_GetAllStrategyInfo200方法用于获取所有策略信息接口 json... | 4 | stack_v2_sparse_classes_30k_train_001166 | Implement the Python class `Test_GetAllStrategyInfo` described below.
Class description:
Implement the Test_GetAllStrategyInfo class.
Method signatures and docstrings:
- def test_GetAllStrategyInfo200(self, url, jsondata, headers, checkpoint): 用例描述:Test_GetAllStrategyInfo200方法用于获取所有策略信息接口 json数据包含禅道上多条用例的校验,具体对body中不... | Implement the Python class `Test_GetAllStrategyInfo` described below.
Class description:
Implement the Test_GetAllStrategyInfo class.
Method signatures and docstrings:
- def test_GetAllStrategyInfo200(self, url, jsondata, headers, checkpoint): 用例描述:Test_GetAllStrategyInfo200方法用于获取所有策略信息接口 json数据包含禅道上多条用例的校验,具体对body中不... | ab922c82c2454a3397ddbf4cd0771067734e1111 | <|skeleton|>
class Test_GetAllStrategyInfo:
def test_GetAllStrategyInfo200(self, url, jsondata, headers, checkpoint):
"""用例描述:Test_GetAllStrategyInfo200方法用于获取所有策略信息接口 json数据包含禅道上多条用例的校验,具体对body中不同功能的传参检查"""
<|body_0|>
def test_GetAllStrategyInfo_name_mode200(self, url, jsondata, headers, check... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test_GetAllStrategyInfo:
def test_GetAllStrategyInfo200(self, url, jsondata, headers, checkpoint):
"""用例描述:Test_GetAllStrategyInfo200方法用于获取所有策略信息接口 json数据包含禅道上多条用例的校验,具体对body中不同功能的传参检查"""
client = Http_client()
client.get(url=url, params=jsondata, header=headers)
assert client.... | the_stack_v2_python_sparse | Case/AS/Http/DocPolicyMgnt/test_GetAllStrategyInfo.py | GWenPeng/Apitest_framework | train | 0 | |
eed2bbbee19b54156cd53711d13af9e5329fe822 | [
"self.generate_short_description()\nif self.price is None:\n self.currency = None\nsuper(Offer, self).save(*args, **kwargs)\nself.generate_slug_and_permalink()\nsuper(Offer, self).save()",
"unique_title_es = '{slug}-{id}'.format(slug=self.title_es, id=self.id)\nunique_title_en = '{slug}-{id}'.format(slug=self.... | <|body_start_0|>
self.generate_short_description()
if self.price is None:
self.currency = None
super(Offer, self).save(*args, **kwargs)
self.generate_slug_and_permalink()
super(Offer, self).save()
<|end_body_0|>
<|body_start_1|>
unique_title_es = '{slug}-{id}... | Offer definition | Offer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Offer:
"""Offer definition"""
def save(self, *args, **kwargs):
"""Create Offer"""
<|body_0|>
def generate_slug_and_permalink(self):
"""Generate a unique slug and unique permalink"""
<|body_1|>
def generate_short_description(self):
"""Generate... | stack_v2_sparse_classes_75kplus_train_072220 | 8,128 | no_license | [
{
"docstring": "Create Offer",
"name": "save",
"signature": "def save(self, *args, **kwargs)"
},
{
"docstring": "Generate a unique slug and unique permalink",
"name": "generate_slug_and_permalink",
"signature": "def generate_slug_and_permalink(self)"
},
{
"docstring": "Generate o... | 3 | stack_v2_sparse_classes_30k_train_002628 | Implement the Python class `Offer` described below.
Class description:
Offer definition
Method signatures and docstrings:
- def save(self, *args, **kwargs): Create Offer
- def generate_slug_and_permalink(self): Generate a unique slug and unique permalink
- def generate_short_description(self): Generate offer short_de... | Implement the Python class `Offer` described below.
Class description:
Offer definition
Method signatures and docstrings:
- def save(self, *args, **kwargs): Create Offer
- def generate_slug_and_permalink(self): Generate a unique slug and unique permalink
- def generate_short_description(self): Generate offer short_de... | 4dc6362ef624eb6591aad9d5c7de95eee40a01c9 | <|skeleton|>
class Offer:
"""Offer definition"""
def save(self, *args, **kwargs):
"""Create Offer"""
<|body_0|>
def generate_slug_and_permalink(self):
"""Generate a unique slug and unique permalink"""
<|body_1|>
def generate_short_description(self):
"""Generate... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Offer:
"""Offer definition"""
def save(self, *args, **kwargs):
"""Create Offer"""
self.generate_short_description()
if self.price is None:
self.currency = None
super(Offer, self).save(*args, **kwargs)
self.generate_slug_and_permalink()
super(Off... | the_stack_v2_python_sparse | app/offers/models.py | arielMilan1899/orbita-api | train | 0 |
0da4dbf872686d52e81232857338deaa0950e0e3 | [
"if stop is None:\n self.start, self.stop = (0, start)\nelse:\n self.start = start\n self.stop = stop\nself.step = step\nif self.start < self.stop:\n assert self.step > 0, 'Need a positive Step here'\nif self.start > self.stop:\n assert self.step < 0, 'Need a negative Step here'",
"n = self.start\n... | <|body_start_0|>
if stop is None:
self.start, self.stop = (0, start)
else:
self.start = start
self.stop = stop
self.step = step
if self.start < self.stop:
assert self.step > 0, 'Need a positive Step here'
if self.start > self.stop:
... | Create an iterable inexhaustable range-like object. three input parameters: start, stop=None, step=1 __iter__ but not __next__ is implemented to make objects of this class inexhaustable like range() | IterateMe_3 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IterateMe_3:
"""Create an iterable inexhaustable range-like object. three input parameters: start, stop=None, step=1 __iter__ but not __next__ is implemented to make objects of this class inexhaustable like range()"""
def __init__(self, start, stop=None, step=1):
"""Parameters: start... | stack_v2_sparse_classes_75kplus_train_072221 | 6,278 | no_license | [
{
"docstring": "Parameters: start, stop (defaults to None), step (defaults to 1).",
"name": "__init__",
"signature": "def __init__(self, start, stop=None, step=1)"
},
{
"docstring": "Implement iter with yield statement.",
"name": "__iter__",
"signature": "def __iter__(self)"
}
] | 2 | null | Implement the Python class `IterateMe_3` described below.
Class description:
Create an iterable inexhaustable range-like object. three input parameters: start, stop=None, step=1 __iter__ but not __next__ is implemented to make objects of this class inexhaustable like range()
Method signatures and docstrings:
- def __... | Implement the Python class `IterateMe_3` described below.
Class description:
Create an iterable inexhaustable range-like object. three input parameters: start, stop=None, step=1 __iter__ but not __next__ is implemented to make objects of this class inexhaustable like range()
Method signatures and docstrings:
- def __... | eb151196178f27b23911fd937e082034fc17af3f | <|skeleton|>
class IterateMe_3:
"""Create an iterable inexhaustable range-like object. three input parameters: start, stop=None, step=1 __iter__ but not __next__ is implemented to make objects of this class inexhaustable like range()"""
def __init__(self, start, stop=None, step=1):
"""Parameters: start... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IterateMe_3:
"""Create an iterable inexhaustable range-like object. three input parameters: start, stop=None, step=1 __iter__ but not __next__ is implemented to make objects of this class inexhaustable like range()"""
def __init__(self, start, stop=None, step=1):
"""Parameters: start, stop (defau... | the_stack_v2_python_sparse | students/alex_skrn/Lesson01/iterator_1.py | pinstripezebra/Sp2018-Online | train | 0 |
dca124a6c768faea689a05d8c1dffc3f670b8467 | [
"super(DecoderBlock, self).__init__()\nself.mha1 = MultiHeadAttention(dm, h)\nself.mha2 = MultiHeadAttention(dm, h)\nself.dense_hidden = tf.keras.layers.Dense(units=hidden, activation='relu')\nself.dense_output = tf.keras.layers.Dense(units=dm)\nself.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\ns... | <|body_start_0|>
super(DecoderBlock, self).__init__()
self.mha1 = MultiHeadAttention(dm, h)
self.mha2 = MultiHeadAttention(dm, h)
self.dense_hidden = tf.keras.layers.Dense(units=hidden, activation='relu')
self.dense_output = tf.keras.layers.Dense(units=dm)
self.layernorm1... | Class representation of a decoder block for a transformer | DecoderBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecoderBlock:
"""Class representation of a decoder block for a transformer"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""dm: Dimensionality of the model h: Number of heads hidden: Number of hidden units in the fully connected layer drop_rate: Dropout rate"""
<|body_... | stack_v2_sparse_classes_75kplus_train_072222 | 2,892 | no_license | [
{
"docstring": "dm: Dimensionality of the model h: Number of heads hidden: Number of hidden units in the fully connected layer drop_rate: Dropout rate",
"name": "__init__",
"signature": "def __init__(self, dm, h, hidden, drop_rate=0.1)"
},
{
"docstring": "x: tensor of shape (batch, target_seq_le... | 2 | stack_v2_sparse_classes_30k_train_053674 | Implement the Python class `DecoderBlock` described below.
Class description:
Class representation of a decoder block for a transformer
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): dm: Dimensionality of the model h: Number of heads hidden: Number of hidden units in the fully c... | Implement the Python class `DecoderBlock` described below.
Class description:
Class representation of a decoder block for a transformer
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): dm: Dimensionality of the model h: Number of heads hidden: Number of hidden units in the fully c... | 2757c8526290197d45a4de33cda71e686ddcbf1c | <|skeleton|>
class DecoderBlock:
"""Class representation of a decoder block for a transformer"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""dm: Dimensionality of the model h: Number of heads hidden: Number of hidden units in the fully connected layer drop_rate: Dropout rate"""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DecoderBlock:
"""Class representation of a decoder block for a transformer"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""dm: Dimensionality of the model h: Number of heads hidden: Number of hidden units in the fully connected layer drop_rate: Dropout rate"""
super(DecoderBlock, ... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/8-transformer_decoder_block.py | 95ktsmith/holbertonschool-machine_learning | train | 0 |
799dd7999dd12775909826786a0967da3a03f5bd | [
"with self.assertRaises(NotImplementedError):\n loss = StrongConvexMixin()\n getattr(loss, fn, None)(*args)",
"loss = StrongConvexMixin()\nret = getattr(loss, fn, None)(*args)\nself.assertNone(ret)"
] | <|body_start_0|>
with self.assertRaises(NotImplementedError):
loss = StrongConvexMixin()
getattr(loss, fn, None)(*args)
<|end_body_0|>
<|body_start_1|>
loss = StrongConvexMixin()
ret = getattr(loss, fn, None)(*args)
self.assertNone(ret)
<|end_body_1|>
| Tests for the StrongConvexMixin. | StrongConvexMixinTests | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StrongConvexMixinTests:
"""Tests for the StrongConvexMixin."""
def test_not_implemented(self, fn, args):
"""Test that the given fn's are not implemented on the mixin. Args: fn: fn on Mixin to test args: arguments to fn of Mixin"""
<|body_0|>
def test_return_none(self, fn... | stack_v2_sparse_classes_75kplus_train_072223 | 14,409 | permissive | [
{
"docstring": "Test that the given fn's are not implemented on the mixin. Args: fn: fn on Mixin to test args: arguments to fn of Mixin",
"name": "test_not_implemented",
"signature": "def test_not_implemented(self, fn, args)"
},
{
"docstring": "Test that fn of Mixin returns None. Args: fn: fn of... | 2 | stack_v2_sparse_classes_30k_train_035269 | Implement the Python class `StrongConvexMixinTests` described below.
Class description:
Tests for the StrongConvexMixin.
Method signatures and docstrings:
- def test_not_implemented(self, fn, args): Test that the given fn's are not implemented on the mixin. Args: fn: fn on Mixin to test args: arguments to fn of Mixin... | Implement the Python class `StrongConvexMixinTests` described below.
Class description:
Tests for the StrongConvexMixin.
Method signatures and docstrings:
- def test_not_implemented(self, fn, args): Test that the given fn's are not implemented on the mixin. Args: fn: fn on Mixin to test args: arguments to fn of Mixin... | c92610e37aa340932ed2d963813e0890035a22bc | <|skeleton|>
class StrongConvexMixinTests:
"""Tests for the StrongConvexMixin."""
def test_not_implemented(self, fn, args):
"""Test that the given fn's are not implemented on the mixin. Args: fn: fn on Mixin to test args: arguments to fn of Mixin"""
<|body_0|>
def test_return_none(self, fn... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StrongConvexMixinTests:
"""Tests for the StrongConvexMixin."""
def test_not_implemented(self, fn, args):
"""Test that the given fn's are not implemented on the mixin. Args: fn: fn on Mixin to test args: arguments to fn of Mixin"""
with self.assertRaises(NotImplementedError):
l... | the_stack_v2_python_sparse | tensorflow_privacy/privacy/bolt_on/losses_test.py | tensorflow/privacy | train | 1,881 |
8df9985608b2a9310d1b7175d79b3c793966dc94 | [
"if notes_gui.showing:\n ctx.tags = []\n notes_gui.hide()\nelse:\n update_notes()\n ctx.tags = ['user.notes_showing']\n notes_gui.show()",
"curtime = datetime.now().strftime('%Y-%m-%d %H%M%S')\nfile_path = NOTES_DIR / f'{curtime}.txt'\nfile_path.touch()\nsubprocess.Popen(['notepad', str(file_path)]... | <|body_start_0|>
if notes_gui.showing:
ctx.tags = []
notes_gui.hide()
else:
update_notes()
ctx.tags = ['user.notes_showing']
notes_gui.show()
<|end_body_0|>
<|body_start_1|>
curtime = datetime.now().strftime('%Y-%m-%d %H%M%S')
... | Actions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Actions:
def notes_gui_toggle():
"""Toggle the notes gui"""
<|body_0|>
def create_note():
"""Create a new note"""
<|body_1|>
def delete_note(n: int):
"""Delete note number n"""
<|body_2|>
def show_note(n: int):
"""Show note n... | stack_v2_sparse_classes_75kplus_train_072224 | 3,193 | no_license | [
{
"docstring": "Toggle the notes gui",
"name": "notes_gui_toggle",
"signature": "def notes_gui_toggle()"
},
{
"docstring": "Create a new note",
"name": "create_note",
"signature": "def create_note()"
},
{
"docstring": "Delete note number n",
"name": "delete_note",
"signat... | 4 | stack_v2_sparse_classes_30k_train_027096 | Implement the Python class `Actions` described below.
Class description:
Implement the Actions class.
Method signatures and docstrings:
- def notes_gui_toggle(): Toggle the notes gui
- def create_note(): Create a new note
- def delete_note(n: int): Delete note number n
- def show_note(n: int): Show note number n | Implement the Python class `Actions` described below.
Class description:
Implement the Actions class.
Method signatures and docstrings:
- def notes_gui_toggle(): Toggle the notes gui
- def create_note(): Create a new note
- def delete_note(n: int): Delete note number n
- def show_note(n: int): Show note number n
<|s... | 03c6479989ab4231d8ae6bbab24ac8b57c3ef809 | <|skeleton|>
class Actions:
def notes_gui_toggle():
"""Toggle the notes gui"""
<|body_0|>
def create_note():
"""Create a new note"""
<|body_1|>
def delete_note(n: int):
"""Delete note number n"""
<|body_2|>
def show_note(n: int):
"""Show note n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Actions:
def notes_gui_toggle():
"""Toggle the notes gui"""
if notes_gui.showing:
ctx.tags = []
notes_gui.hide()
else:
update_notes()
ctx.tags = ['user.notes_showing']
notes_gui.show()
def create_note():
"""Create... | the_stack_v2_python_sparse | gui/notes/notes_gui.py | mrob95/MR-talon | train | 15 | |
648e0737aa194181b8bdb42a36aedeb77b06d131 | [
"login_url = self.ip + '/api/user/mis/login.do'\nlogin_params = {'username': self.username, 'password': self.password}\nr = requests.post(url=login_url, params=login_params)\nreturn r.json()",
"url = self.ip + '/api/user/mis/login.do'\nheader = {'Token': self.login_with_password()['data']['loginUser']['token']}\n... | <|body_start_0|>
login_url = self.ip + '/api/user/mis/login.do'
login_params = {'username': self.username, 'password': self.password}
r = requests.post(url=login_url, params=login_params)
return r.json()
<|end_body_0|>
<|body_start_1|>
url = self.ip + '/api/user/mis/login.do'
... | Login | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Login:
def login_with_password(self):
"""使用 用户名、密码 登录 :return:"""
<|body_0|>
def login_with_token(self):
"""使用 token 登录 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
login_url = self.ip + '/api/user/mis/login.do'
login_params = {'... | stack_v2_sparse_classes_75kplus_train_072225 | 844 | no_license | [
{
"docstring": "使用 用户名、密码 登录 :return:",
"name": "login_with_password",
"signature": "def login_with_password(self)"
},
{
"docstring": "使用 token 登录 :return:",
"name": "login_with_token",
"signature": "def login_with_token(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_029505 | Implement the Python class `Login` described below.
Class description:
Implement the Login class.
Method signatures and docstrings:
- def login_with_password(self): 使用 用户名、密码 登录 :return:
- def login_with_token(self): 使用 token 登录 :return: | Implement the Python class `Login` described below.
Class description:
Implement the Login class.
Method signatures and docstrings:
- def login_with_password(self): 使用 用户名、密码 登录 :return:
- def login_with_token(self): 使用 token 登录 :return:
<|skeleton|>
class Login:
def login_with_password(self):
"""使用 用户名... | 26d2ae773a999fd8446e18f9c0719d46402b19aa | <|skeleton|>
class Login:
def login_with_password(self):
"""使用 用户名、密码 登录 :return:"""
<|body_0|>
def login_with_token(self):
"""使用 token 登录 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Login:
def login_with_password(self):
"""使用 用户名、密码 登录 :return:"""
login_url = self.ip + '/api/user/mis/login.do'
login_params = {'username': self.username, 'password': self.password}
r = requests.post(url=login_url, params=login_params)
return r.json()
def login_wi... | the_stack_v2_python_sparse | api/login.py | Leofighting/dimi_api_test | train | 0 | |
956d84d1fdc2bd1fe7981dbaa69770d39368ef0d | [
"if self.cleaned_data['image_id'] < 0:\n raise ValidationError('The given image id is incorrect.')\nif self.cleaned_data['tag_group_id'] < 0:\n raise ValidationError('The given tag group id is incorrect.')\nreturn self.cleaned_data",
"try:\n group = TagGroup.objects.get(pk__exact=self.cleaned_data['tag_g... | <|body_start_0|>
if self.cleaned_data['image_id'] < 0:
raise ValidationError('The given image id is incorrect.')
if self.cleaned_data['tag_group_id'] < 0:
raise ValidationError('The given tag group id is incorrect.')
return self.cleaned_data
<|end_body_0|>
<|body_start_1... | SingleGetForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingleGetForm:
def clean(self):
"""Cleans the data for this form to normalize parameters."""
<|body_0|>
def submit(self, request):
"""Submits the form for getting a TagGroup once the form has cleaned the input data."""
<|body_1|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_75kplus_train_072226 | 7,434 | no_license | [
{
"docstring": "Cleans the data for this form to normalize parameters.",
"name": "clean",
"signature": "def clean(self)"
},
{
"docstring": "Submits the form for getting a TagGroup once the form has cleaned the input data.",
"name": "submit",
"signature": "def submit(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_029012 | Implement the Python class `SingleGetForm` described below.
Class description:
Implement the SingleGetForm class.
Method signatures and docstrings:
- def clean(self): Cleans the data for this form to normalize parameters.
- def submit(self, request): Submits the form for getting a TagGroup once the form has cleaned t... | Implement the Python class `SingleGetForm` described below.
Class description:
Implement the SingleGetForm class.
Method signatures and docstrings:
- def clean(self): Cleans the data for this form to normalize parameters.
- def submit(self, request): Submits the form for getting a TagGroup once the form has cleaned t... | 22c1ce3c5a8e4ed99c2f014672d60ad3c5a4003c | <|skeleton|>
class SingleGetForm:
def clean(self):
"""Cleans the data for this form to normalize parameters."""
<|body_0|>
def submit(self, request):
"""Submits the form for getting a TagGroup once the form has cleaned the input data."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SingleGetForm:
def clean(self):
"""Cleans the data for this form to normalize parameters."""
if self.cleaned_data['image_id'] < 0:
raise ValidationError('The given image id is incorrect.')
if self.cleaned_data['tag_group_id'] < 0:
raise ValidationError('The give... | the_stack_v2_python_sparse | biodig/rest/v2/TagGroups/forms.py | asmariyaz23/BioDIG | train | 0 | |
ea342d2d50996796325636ad35fcb381ee353dcb | [
"try:\n technology_type = TechnologyType.objects.get(pk=pk)\n serializer = TechnologyTypeSerializer(technology_type, context={'request': request})\n return Response(serializer.data)\nexcept Exception as ex:\n return HttpResponseServerError(ex)",
"technology_types = TechnologyType.objects.all()\nserial... | <|body_start_0|>
try:
technology_type = TechnologyType.objects.get(pk=pk)
serializer = TechnologyTypeSerializer(technology_type, context={'request': request})
return Response(serializer.data)
except Exception as ex:
return HttpResponseServerError(ex)
<|end... | Technology Types for codeProject | TechnologyTypes | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TechnologyTypes:
"""Technology Types for codeProject"""
def retrieve(self, request, pk=None):
"""Handle GET requests for technology type Returns: Response -- JSON serialized technology type instance"""
<|body_0|>
def list(self, request):
"""Handle GET requests to... | stack_v2_sparse_classes_75kplus_train_072227 | 1,728 | no_license | [
{
"docstring": "Handle GET requests for technology type Returns: Response -- JSON serialized technology type instance",
"name": "retrieve",
"signature": "def retrieve(self, request, pk=None)"
},
{
"docstring": "Handle GET requests to technology types resource Returns: Response -- JSON serialized... | 2 | stack_v2_sparse_classes_30k_train_028091 | Implement the Python class `TechnologyTypes` described below.
Class description:
Technology Types for codeProject
Method signatures and docstrings:
- def retrieve(self, request, pk=None): Handle GET requests for technology type Returns: Response -- JSON serialized technology type instance
- def list(self, request): H... | Implement the Python class `TechnologyTypes` described below.
Class description:
Technology Types for codeProject
Method signatures and docstrings:
- def retrieve(self, request, pk=None): Handle GET requests for technology type Returns: Response -- JSON serialized technology type instance
- def list(self, request): H... | edcb6749de745b57404b7fbaf31db33f8c9e0351 | <|skeleton|>
class TechnologyTypes:
"""Technology Types for codeProject"""
def retrieve(self, request, pk=None):
"""Handle GET requests for technology type Returns: Response -- JSON serialized technology type instance"""
<|body_0|>
def list(self, request):
"""Handle GET requests to... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TechnologyTypes:
"""Technology Types for codeProject"""
def retrieve(self, request, pk=None):
"""Handle GET requests for technology type Returns: Response -- JSON serialized technology type instance"""
try:
technology_type = TechnologyType.objects.get(pk=pk)
serial... | the_stack_v2_python_sparse | codeprojectAPIapp/views/technology_types.py | shanemiller89/codeProject-API | train | 1 |
ceab7d611160663aa0f71bcd078e3f56c910b26f | [
"attributes = node.attributes\nself.individual_address = IndividualAddress(self.get_attribute_value(attributes.get('IndividualAddress')))\nself.tool_key = self.get_attribute_value(attributes.get('ToolKey'))\nself.management_password = self.get_attribute_value(attributes.get('ManagementPassword'))\nself.authenticati... | <|body_start_0|>
attributes = node.attributes
self.individual_address = IndividualAddress(self.get_attribute_value(attributes.get('IndividualAddress')))
self.tool_key = self.get_attribute_value(attributes.get('ToolKey'))
self.management_password = self.get_attribute_value(attributes.get(... | Device in a knxkeys file. | XMLDevice | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XMLDevice:
"""Device in a knxkeys file."""
def parse_xml(self, node: Element) -> None:
"""Parse all needed attributes from the given node map."""
<|body_0|>
def decrypt_attributes(self, password_hash: bytes, initialization_vector: bytes) -> None:
"""Decrypt attri... | stack_v2_sparse_classes_75kplus_train_072228 | 19,593 | permissive | [
{
"docstring": "Parse all needed attributes from the given node map.",
"name": "parse_xml",
"signature": "def parse_xml(self, node: Element) -> None"
},
{
"docstring": "Decrypt attributes.",
"name": "decrypt_attributes",
"signature": "def decrypt_attributes(self, password_hash: bytes, in... | 2 | stack_v2_sparse_classes_30k_train_021352 | Implement the Python class `XMLDevice` described below.
Class description:
Device in a knxkeys file.
Method signatures and docstrings:
- def parse_xml(self, node: Element) -> None: Parse all needed attributes from the given node map.
- def decrypt_attributes(self, password_hash: bytes, initialization_vector: bytes) -... | Implement the Python class `XMLDevice` described below.
Class description:
Device in a knxkeys file.
Method signatures and docstrings:
- def parse_xml(self, node: Element) -> None: Parse all needed attributes from the given node map.
- def decrypt_attributes(self, password_hash: bytes, initialization_vector: bytes) -... | 48d4e31365c15e632b275f0d129cd9f2b2b5717d | <|skeleton|>
class XMLDevice:
"""Device in a knxkeys file."""
def parse_xml(self, node: Element) -> None:
"""Parse all needed attributes from the given node map."""
<|body_0|>
def decrypt_attributes(self, password_hash: bytes, initialization_vector: bytes) -> None:
"""Decrypt attri... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class XMLDevice:
"""Device in a knxkeys file."""
def parse_xml(self, node: Element) -> None:
"""Parse all needed attributes from the given node map."""
attributes = node.attributes
self.individual_address = IndividualAddress(self.get_attribute_value(attributes.get('IndividualAddress')))... | the_stack_v2_python_sparse | xknx/secure/keyring.py | XKNX/xknx | train | 248 |
5d1aadb7c69aab49f4a3ba6a4c20d9919aaa38fb | [
"iqCustomComboCtrl.__init__(self, *args, **kwargs)\nself.choice = list()\nself.filter_env = None\nself.choice_idx = -1\nself.data = None",
"if data is None:\n self.data = list()\nelse:\n self.data = data\n choice = [element['description'] for element in self.data]\n self.setChoice(choice)\nreturn self... | <|body_start_0|>
iqCustomComboCtrl.__init__(self, *args, **kwargs)
self.choice = list()
self.filter_env = None
self.choice_idx = -1
self.data = None
<|end_body_0|>
<|body_start_1|>
if data is None:
self.data = list()
else:
self.data = data... | The control class is an extended selection from the specified list. | iqCustomChoice | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class iqCustomChoice:
"""The control class is an extended selection from the specified list."""
def __init__(self, *args, **kwargs):
"""Constructor."""
<|body_0|>
def setData(self, data=None):
"""Set data."""
<|body_1|>
def setChoice(self, choice=None):
... | stack_v2_sparse_classes_75kplus_train_072229 | 19,825 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Set data.",
"name": "setData",
"signature": "def setData(self, data=None)"
},
{
"docstring": "Set choices.",
"name": "setChoice",
"signature": "def set... | 4 | stack_v2_sparse_classes_30k_train_006507 | Implement the Python class `iqCustomChoice` described below.
Class description:
The control class is an extended selection from the specified list.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Constructor.
- def setData(self, data=None): Set data.
- def setChoice(self, choice=None): Set ch... | Implement the Python class `iqCustomChoice` described below.
Class description:
The control class is an extended selection from the specified list.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Constructor.
- def setData(self, data=None): Set data.
- def setChoice(self, choice=None): Set ch... | 7550e242746cb2fb1219474463f8db21f8e3e114 | <|skeleton|>
class iqCustomChoice:
"""The control class is an extended selection from the specified list."""
def __init__(self, *args, **kwargs):
"""Constructor."""
<|body_0|>
def setData(self, data=None):
"""Set data."""
<|body_1|>
def setChoice(self, choice=None):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class iqCustomChoice:
"""The control class is an extended selection from the specified list."""
def __init__(self, *args, **kwargs):
"""Constructor."""
iqCustomComboCtrl.__init__(self, *args, **kwargs)
self.choice = list()
self.filter_env = None
self.choice_idx = -1
... | the_stack_v2_python_sparse | iq/components/wx_filterchoicectrl/filter_builder_ctrl.py | XHermitOne/iq_framework | train | 1 |
bea4f410da1fbbc646cb77d8a41bab9957d81f97 | [
"hashtbl = MyHashTable(5)\nhashtbl.insert(5, 21)\nself.assertEqual(hashtbl.hashlist[0], [(5, 21)])\nself.assertEqual(hashtbl.get(5), (5, 21))\nwith self.assertRaises(LookupError):\n hashtbl.get(6)\nself.assertEqual(hashtbl.size(), 1)\nself.assertEqual(hashtbl.collisions(), 0)\nself.assertEqual(hashtbl.load_facto... | <|body_start_0|>
hashtbl = MyHashTable(5)
hashtbl.insert(5, 21)
self.assertEqual(hashtbl.hashlist[0], [(5, 21)])
self.assertEqual(hashtbl.get(5), (5, 21))
with self.assertRaises(LookupError):
hashtbl.get(6)
self.assertEqual(hashtbl.size(), 1)
self.asse... | Test Cases for Hash Table | TestHash | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestHash:
"""Test Cases for Hash Table"""
def test_hash(self):
"""Tests Hash Table #1"""
<|body_0|>
def test_hash2(self):
"""Tests Hash Table #2"""
<|body_1|>
def test_random(self):
"""Tests Random Hash"""
<|body_2|>
def test_reh... | stack_v2_sparse_classes_75kplus_train_072230 | 2,442 | no_license | [
{
"docstring": "Tests Hash Table #1",
"name": "test_hash",
"signature": "def test_hash(self)"
},
{
"docstring": "Tests Hash Table #2",
"name": "test_hash2",
"signature": "def test_hash2(self)"
},
{
"docstring": "Tests Random Hash",
"name": "test_random",
"signature": "def... | 5 | null | Implement the Python class `TestHash` described below.
Class description:
Test Cases for Hash Table
Method signatures and docstrings:
- def test_hash(self): Tests Hash Table #1
- def test_hash2(self): Tests Hash Table #2
- def test_random(self): Tests Random Hash
- def test_rehash(self): Tests Rehash
- def test_colli... | Implement the Python class `TestHash` described below.
Class description:
Test Cases for Hash Table
Method signatures and docstrings:
- def test_hash(self): Tests Hash Table #1
- def test_hash2(self): Tests Hash Table #2
- def test_random(self): Tests Random Hash
- def test_rehash(self): Tests Rehash
- def test_colli... | c8d0c8dd916aea0224b6adc5f3e6876200b90c93 | <|skeleton|>
class TestHash:
"""Test Cases for Hash Table"""
def test_hash(self):
"""Tests Hash Table #1"""
<|body_0|>
def test_hash2(self):
"""Tests Hash Table #2"""
<|body_1|>
def test_random(self):
"""Tests Random Hash"""
<|body_2|>
def test_reh... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestHash:
"""Test Cases for Hash Table"""
def test_hash(self):
"""Tests Hash Table #1"""
hashtbl = MyHashTable(5)
hashtbl.insert(5, 21)
self.assertEqual(hashtbl.hashlist[0], [(5, 21)])
self.assertEqual(hashtbl.get(5), (5, 21))
with self.assertRaises(LookupE... | the_stack_v2_python_sparse | Lab8/sep_chain_ht_tests.py | Alyssajan298/CPE-202 | train | 0 |
33723ce8855306b035c8552bdd6d5c906bfb1899 | [
"if self.action == 'create':\n return ResponseWriteableSerializer\nreturn super().get_serializer_class()",
"children_ids = Child.objects.filter(user__id=self.request.user.id).values_list('id', flat=True)\nif 'study_uuid' in self.kwargs:\n study_uuid = self.kwargs['study_uuid']\n queryset = Response.objec... | <|body_start_0|>
if self.action == 'create':
return ResponseWriteableSerializer
return super().get_serializer_class()
<|end_body_0|>
<|body_start_1|>
children_ids = Child.objects.filter(user__id=self.request.user.id).values_list('id', flat=True)
if 'study_uuid' in self.kwarg... | Allows viewing a list of responses, retrieving a response, creating a response, or updating a response. You can view responses to studies that you have permission to view, or responses by your own children. | ResponseViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResponseViewSet:
"""Allows viewing a list of responses, retrieving a response, creating a response, or updating a response. You can view responses to studies that you have permission to view, or responses by your own children."""
def get_serializer_class(self):
"""Return a different ... | stack_v2_sparse_classes_75kplus_train_072231 | 10,514 | permissive | [
{
"docstring": "Return a different serializer for create views",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "Overrides queryset. Shows responses that you either have permission to view, or responses by your own children",
"name": "get_quer... | 2 | stack_v2_sparse_classes_30k_train_003597 | Implement the Python class `ResponseViewSet` described below.
Class description:
Allows viewing a list of responses, retrieving a response, creating a response, or updating a response. You can view responses to studies that you have permission to view, or responses by your own children.
Method signatures and docstrin... | Implement the Python class `ResponseViewSet` described below.
Class description:
Allows viewing a list of responses, retrieving a response, creating a response, or updating a response. You can view responses to studies that you have permission to view, or responses by your own children.
Method signatures and docstrin... | 621fbb8b25100a21fd94721d39003b5d4f651dc5 | <|skeleton|>
class ResponseViewSet:
"""Allows viewing a list of responses, retrieving a response, creating a response, or updating a response. You can view responses to studies that you have permission to view, or responses by your own children."""
def get_serializer_class(self):
"""Return a different ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResponseViewSet:
"""Allows viewing a list of responses, retrieving a response, creating a response, or updating a response. You can view responses to studies that you have permission to view, or responses by your own children."""
def get_serializer_class(self):
"""Return a different serializer fo... | the_stack_v2_python_sparse | api/views.py | enrobyn/lookit-api | train | 0 |
df5362bfbb807eea49b0842a2bc7df10d047dced | [
"result = []\nfor i in range(1, n + 1):\n if i ** 2 <= n:\n result.append(i ** 2)\n else:\n break\nreturn result",
"result = []\nsqlist = self.SQlist(n)\n\ndef helper(n, bl=[]):\n if sum(bl) == n:\n result.append(bl)\n elif sum(bl) < n:\n for i in sqlist:\n new_b... | <|body_start_0|>
result = []
for i in range(1, n + 1):
if i ** 2 <= n:
result.append(i ** 2)
else:
break
return result
<|end_body_0|>
<|body_start_1|>
result = []
sqlist = self.SQlist(n)
def helper(n, bl=[]):
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def SQlist(self, n):
"""find all possible square number up to n"""
<|body_0|>
def numSquares(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = []
for i in range(1, n + 1):
if... | stack_v2_sparse_classes_75kplus_train_072232 | 7,404 | permissive | [
{
"docstring": "find all possible square number up to n",
"name": "SQlist",
"signature": "def SQlist(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "numSquares",
"signature": "def numSquares(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_037364 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def SQlist(self, n): find all possible square number up to n
- def numSquares(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def SQlist(self, n): find all possible square number up to n
- def numSquares(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def SQlist(self, n):
"... | 143422321cbc3715ca08f6c3af8f960a55887ced | <|skeleton|>
class Solution:
def SQlist(self, n):
"""find all possible square number up to n"""
<|body_0|>
def numSquares(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def SQlist(self, n):
"""find all possible square number up to n"""
result = []
for i in range(1, n + 1):
if i ** 2 <= n:
result.append(i ** 2)
else:
break
return result
def numSquares(self, n):
""":t... | the_stack_v2_python_sparse | LeetCode/LC279_perfect_squares.py | jxie0755/Learning_Python | train | 0 | |
70d8b105b5cc77b1e1a1f1cf6c4c5af35c741017 | [
"self.allowed_url_patterns = allowed_url_patterns\nself.blocked_url_patterns = blocked_url_patterns\nself.blocked_url_categories = blocked_url_categories",
"if dictionary is None:\n return None\nallowed_url_patterns = meraki_sdk.models.allowed_url_patterns_model.AllowedUrlPatternsModel.from_dictionary(dictiona... | <|body_start_0|>
self.allowed_url_patterns = allowed_url_patterns
self.blocked_url_patterns = blocked_url_patterns
self.blocked_url_categories = blocked_url_categories
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
allowed_url_patterns = meraki_sd... | Implementation of the 'ContentFiltering' model. The content filtering settings for your group policy Attributes: allowed_url_patterns (AllowedUrlPatternsModel): Settings for whitelisted URL patterns blocked_url_patterns (BlockedUrlPatternsModel): Settings for blacklisted URL patterns blocked_url_categories (BlockedUrlC... | ContentFilteringModel | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContentFilteringModel:
"""Implementation of the 'ContentFiltering' model. The content filtering settings for your group policy Attributes: allowed_url_patterns (AllowedUrlPatternsModel): Settings for whitelisted URL patterns blocked_url_patterns (BlockedUrlPatternsModel): Settings for blacklisted... | stack_v2_sparse_classes_75kplus_train_072233 | 2,945 | permissive | [
{
"docstring": "Constructor for the ContentFilteringModel class",
"name": "__init__",
"signature": "def __init__(self, allowed_url_patterns=None, blocked_url_patterns=None, blocked_url_categories=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dict... | 2 | stack_v2_sparse_classes_30k_train_011847 | Implement the Python class `ContentFilteringModel` described below.
Class description:
Implementation of the 'ContentFiltering' model. The content filtering settings for your group policy Attributes: allowed_url_patterns (AllowedUrlPatternsModel): Settings for whitelisted URL patterns blocked_url_patterns (BlockedUrlP... | Implement the Python class `ContentFilteringModel` described below.
Class description:
Implementation of the 'ContentFiltering' model. The content filtering settings for your group policy Attributes: allowed_url_patterns (AllowedUrlPatternsModel): Settings for whitelisted URL patterns blocked_url_patterns (BlockedUrlP... | 9894089eb013318243ae48869cc5130eb37f80c0 | <|skeleton|>
class ContentFilteringModel:
"""Implementation of the 'ContentFiltering' model. The content filtering settings for your group policy Attributes: allowed_url_patterns (AllowedUrlPatternsModel): Settings for whitelisted URL patterns blocked_url_patterns (BlockedUrlPatternsModel): Settings for blacklisted... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ContentFilteringModel:
"""Implementation of the 'ContentFiltering' model. The content filtering settings for your group policy Attributes: allowed_url_patterns (AllowedUrlPatternsModel): Settings for whitelisted URL patterns blocked_url_patterns (BlockedUrlPatternsModel): Settings for blacklisted URL patterns... | the_stack_v2_python_sparse | meraki_sdk/models/content_filtering_model.py | RaulCatalano/meraki-python-sdk | train | 1 |
ceca836ab5c6a71942adf9f27768eac913c7447a | [
"super().__init__(name)\nself.linear_state = MotionState()\nself.steps_per_rev = steps_per_rev\nself.steps_per_unit = steps_per_rev / (2 * wheel_radius * math.pi)",
"if timestamp == self.last_timestamp:\n return\ndelta_position = pos - self.state.x\nself.state.x = pos\nnew_velocity = delta_position / timestamp... | <|body_start_0|>
super().__init__(name)
self.linear_state = MotionState()
self.steps_per_rev = steps_per_rev
self.steps_per_unit = steps_per_rev / (2 * wheel_radius * math.pi)
<|end_body_0|>
<|body_start_1|>
if timestamp == self.last_timestamp:
return
delta_p... | StepperMotor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StepperMotor:
def __init__(self, steps_per_rev, wheel_radius, name):
"""Represents the state of a stepper motor. Important note: kinematic units for the state are in terms of steps (steps per second, etc.). For the linear state, access linear_state. Parameters ---------- steps_per_rev: i... | stack_v2_sparse_classes_75kplus_train_072234 | 5,479 | permissive | [
{
"docstring": "Represents the state of a stepper motor. Important note: kinematic units for the state are in terms of steps (steps per second, etc.). For the linear state, access linear_state. Parameters ---------- steps_per_rev: int Steps per driveshaft revolution. wheel_radius: float Radius of the wheel atta... | 2 | stack_v2_sparse_classes_30k_train_033903 | Implement the Python class `StepperMotor` described below.
Class description:
Implement the StepperMotor class.
Method signatures and docstrings:
- def __init__(self, steps_per_rev, wheel_radius, name): Represents the state of a stepper motor. Important note: kinematic units for the state are in terms of steps (steps... | Implement the Python class `StepperMotor` described below.
Class description:
Implement the StepperMotor class.
Method signatures and docstrings:
- def __init__(self, steps_per_rev, wheel_radius, name): Represents the state of a stepper motor. Important note: kinematic units for the state are in terms of steps (steps... | 4e91e86c86bfbdd8d4639b0994e96e890a2f741e | <|skeleton|>
class StepperMotor:
def __init__(self, steps_per_rev, wheel_radius, name):
"""Represents the state of a stepper motor. Important note: kinematic units for the state are in terms of steps (steps per second, etc.). For the linear state, access linear_state. Parameters ---------- steps_per_rev: i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StepperMotor:
def __init__(self, steps_per_rev, wheel_radius, name):
"""Represents the state of a stepper motor. Important note: kinematic units for the state are in terms of steps (steps per second, etc.). For the linear state, access linear_state. Parameters ---------- steps_per_rev: int Steps per d... | the_stack_v2_python_sparse | drivers/core/robotcore.py | ut-ras/r5-2019 | train | 5 | |
aa72afd5cd63e8a88417e213b38c7794cbbf8bf0 | [
"errors = []\nbreadcrumbs = \"<a href='/'>home</a> › data files\"\ndata = view_util.get_user_files(request)\nif data is None:\n errors.append('No user file found')\ntemplate_values = {'breadcrumbs': breadcrumbs, 'file_list': data, 'user_alert': errors}\nreturn template_values",
"template_values = self._... | <|body_start_0|>
errors = []
breadcrumbs = "<a href='/'>home</a> › data files"
data = view_util.get_user_files(request)
if data is None:
errors.append('No user file found')
template_values = {'breadcrumbs': breadcrumbs, 'file_list': data, 'user_alert': errors}
... | Process a file request | FileView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileView:
"""Process a file request"""
def _get_template_values(self, request):
"""Return template dict"""
<|body_0|>
def get(self, request, *args, **kwargs):
"""Process a GET request"""
<|body_1|>
def post(self, request, *args, **kwargs):
""... | stack_v2_sparse_classes_75kplus_train_072235 | 38,410 | permissive | [
{
"docstring": "Return template dict",
"name": "_get_template_values",
"signature": "def _get_template_values(self, request)"
},
{
"docstring": "Process a GET request",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Process a POST request... | 3 | stack_v2_sparse_classes_30k_train_021432 | Implement the Python class `FileView` described below.
Class description:
Process a file request
Method signatures and docstrings:
- def _get_template_values(self, request): Return template dict
- def get(self, request, *args, **kwargs): Process a GET request
- def post(self, request, *args, **kwargs): Process a POST... | Implement the Python class `FileView` described below.
Class description:
Process a file request
Method signatures and docstrings:
- def _get_template_values(self, request): Return template dict
- def get(self, request, *args, **kwargs): Process a GET request
- def post(self, request, *args, **kwargs): Process a POST... | 8381a0a1e64fb8df89a28e4729cb2957e0ebce57 | <|skeleton|>
class FileView:
"""Process a file request"""
def _get_template_values(self, request):
"""Return template dict"""
<|body_0|>
def get(self, request, *args, **kwargs):
"""Process a GET request"""
<|body_1|>
def post(self, request, *args, **kwargs):
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FileView:
"""Process a file request"""
def _get_template_values(self, request):
"""Return template dict"""
errors = []
breadcrumbs = "<a href='/'>home</a> › data files"
data = view_util.get_user_files(request)
if data is None:
errors.append('No u... | the_stack_v2_python_sparse | web_reflectivity/fitting/views.py | neutrons/web_reflectivity | train | 1 |
8490fd537ed5d3c28cd597e45f54b5668d6934b4 | [
"super().__init__()\nif init_method == 'zeros':\n self._learned_defaults = nn.Parameter(torch.zeros(feature_dim), requires_grad=not freeze)\nelif init_method == 'gaussian':\n self._learned_defaults = nn.Parameter(torch.Tensor(feature_dim), requires_grad=not freeze)\n nn.init.normal_(self._learned_defaults)... | <|body_start_0|>
super().__init__()
if init_method == 'zeros':
self._learned_defaults = nn.Parameter(torch.zeros(feature_dim), requires_grad=not freeze)
elif init_method == 'gaussian':
self._learned_defaults = nn.Parameter(torch.Tensor(feature_dim), requires_grad=not free... | Learns default values to fill invalid entries within input tensors. The invalid entries are represented by a mask which is passed into forward alongside the input tensor. Note the default value is only used if all entries in the batch row are invalid rather than just a portion of invalid entries within each batch row. | LearnMaskedDefault | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LearnMaskedDefault:
"""Learns default values to fill invalid entries within input tensors. The invalid entries are represented by a mask which is passed into forward alongside the input tensor. Note the default value is only used if all entries in the batch row are invalid rather than just a port... | stack_v2_sparse_classes_75kplus_train_072236 | 13,032 | permissive | [
{
"docstring": "Args: feature_dim (int): the size of the default value parameter, this must match the input tensor size. init_method (str): the initial default value parameter. Options: 'guassian' 'zeros' freeze (bool): If True, the learned default parameter weights are frozen.",
"name": "__init__",
"si... | 2 | stack_v2_sparse_classes_30k_train_045121 | Implement the Python class `LearnMaskedDefault` described below.
Class description:
Learns default values to fill invalid entries within input tensors. The invalid entries are represented by a mask which is passed into forward alongside the input tensor. Note the default value is only used if all entries in the batch ... | Implement the Python class `LearnMaskedDefault` described below.
Class description:
Learns default values to fill invalid entries within input tensors. The invalid entries are represented by a mask which is passed into forward alongside the input tensor. Note the default value is only used if all entries in the batch ... | 16f2abf2f8aa174915316007622bbb260215dee8 | <|skeleton|>
class LearnMaskedDefault:
"""Learns default values to fill invalid entries within input tensors. The invalid entries are represented by a mask which is passed into forward alongside the input tensor. Note the default value is only used if all entries in the batch row are invalid rather than just a port... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LearnMaskedDefault:
"""Learns default values to fill invalid entries within input tensors. The invalid entries are represented by a mask which is passed into forward alongside the input tensor. Note the default value is only used if all entries in the batch row are invalid rather than just a portion of invali... | the_stack_v2_python_sparse | pytorchvideo/models/masked_multistream.py | xchani/pytorchvideo | train | 0 |
138eb3ab5e261f8bc5ec13406a1c5a1a472aa0a6 | [
"self.application_id_local = kwargs.pop('id')\nself.adult = kwargs.pop('adult')\nself._all_emails = kwargs.pop('email_list')\nsuper(OtherPeopleAdultDetailsForm, self).__init__(*args, **kwargs)\nfull_stop_stripper(self)\nif AdultInHome.objects.filter(application_id=self.application_id_local, adult=self.adult).count(... | <|body_start_0|>
self.application_id_local = kwargs.pop('id')
self.adult = kwargs.pop('adult')
self._all_emails = kwargs.pop('email_list')
super(OtherPeopleAdultDetailsForm, self).__init__(*args, **kwargs)
full_stop_stripper(self)
if AdultInHome.objects.filter(application... | GOV.UK form for the People in your home: adult details page | OtherPeopleAdultDetailsForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OtherPeopleAdultDetailsForm:
"""GOV.UK form for the People in your home: adult details page"""
def __init__(self, *args, **kwargs):
"""Method to configure the initialisation of the People in your home: adult details form :param args: arguments passed to the form :param kwargs: keywor... | stack_v2_sparse_classes_75kplus_train_072237 | 20,631 | no_license | [
{
"docstring": "Method to configure the initialisation of the People in your home: adult details form :param args: arguments passed to the form :param kwargs: keyword arguments passed to the form, e.g. application ID",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"... | 6 | stack_v2_sparse_classes_30k_train_045843 | Implement the Python class `OtherPeopleAdultDetailsForm` described below.
Class description:
GOV.UK form for the People in your home: adult details page
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Method to configure the initialisation of the People in your home: adult details form :param... | Implement the Python class `OtherPeopleAdultDetailsForm` described below.
Class description:
GOV.UK form for the People in your home: adult details page
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Method to configure the initialisation of the People in your home: adult details form :param... | fa6ca6a8164763e1dfe1581702ca5d36e44859de | <|skeleton|>
class OtherPeopleAdultDetailsForm:
"""GOV.UK form for the People in your home: adult details page"""
def __init__(self, *args, **kwargs):
"""Method to configure the initialisation of the People in your home: adult details form :param args: arguments passed to the form :param kwargs: keywor... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OtherPeopleAdultDetailsForm:
"""GOV.UK form for the People in your home: adult details page"""
def __init__(self, *args, **kwargs):
"""Method to configure the initialisation of the People in your home: adult details form :param args: arguments passed to the form :param kwargs: keyword arguments p... | the_stack_v2_python_sparse | application/forms/other_people.py | IS-JAQU-CAZ/OFS-MORE-Childminder-Website | train | 0 |
a332b5e037c576d6837ab467e24087681c182a85 | [
"super().__init__()\nself.conv_layers = []\nself.bn_layers = []\nper_conv_filter_size = filters / groups\nif groups <= 1 or groups >= filters:\n raise ValueError('Number of groups should be greater than 1 and less than the output filters.')\nself.batch_norm_layer = batch_norm_layer\nself.use_batch_norm = False\n... | <|body_start_0|>
super().__init__()
self.conv_layers = []
self.bn_layers = []
per_conv_filter_size = filters / groups
if groups <= 1 or groups >= filters:
raise ValueError('Number of groups should be greater than 1 and less than the output filters.')
self.batc... | 2D group convolution as a keras model. | GroupConv2DKerasModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupConv2DKerasModel:
"""2D group convolution as a keras model."""
def __init__(self, filters: int, kernel_size: tuple[int, int], groups: int, batch_norm_layer: Optional[tf.keras.layers.Layer]=None, bn_epsilon: float=0.001, bn_momentum: float=0.99, data_format: str='channels_last', padding:... | stack_v2_sparse_classes_75kplus_train_072238 | 19,671 | permissive | [
{
"docstring": "Creates a 2D group convolution layer as a keras model. Args: filters: Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution). kernel_size: An integer or tuple/list of 2 integers, specifying the height and width of the 2D convolution window. Can be ... | 2 | null | Implement the Python class `GroupConv2DKerasModel` described below.
Class description:
2D group convolution as a keras model.
Method signatures and docstrings:
- def __init__(self, filters: int, kernel_size: tuple[int, int], groups: int, batch_norm_layer: Optional[tf.keras.layers.Layer]=None, bn_epsilon: float=0.001,... | Implement the Python class `GroupConv2DKerasModel` described below.
Class description:
2D group convolution as a keras model.
Method signatures and docstrings:
- def __init__(self, filters: int, kernel_size: tuple[int, int], groups: int, batch_norm_layer: Optional[tf.keras.layers.Layer]=None, bn_epsilon: float=0.001,... | d3507b550a3ade40cade60a79eb5b8978b56c7ae | <|skeleton|>
class GroupConv2DKerasModel:
"""2D group convolution as a keras model."""
def __init__(self, filters: int, kernel_size: tuple[int, int], groups: int, batch_norm_layer: Optional[tf.keras.layers.Layer]=None, bn_epsilon: float=0.001, bn_momentum: float=0.99, data_format: str='channels_last', padding:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GroupConv2DKerasModel:
"""2D group convolution as a keras model."""
def __init__(self, filters: int, kernel_size: tuple[int, int], groups: int, batch_norm_layer: Optional[tf.keras.layers.Layer]=None, bn_epsilon: float=0.001, bn_momentum: float=0.99, data_format: str='channels_last', padding: str='valid',... | the_stack_v2_python_sparse | official/projects/edgetpu/vision/modeling/custom_layers.py | jianzhnie/models | train | 2 |
878a24eb27ab552a816697767efb528bebb0be53 | [
"true_pred = always_true()\nself.id_pred = true_pred\nself.args_pred = true_pred\nself.severity_pred = true_pred\nself.time_pred = true_pred\nif is_predicate(id_pred):\n self.id_pred = id_pred\nif is_predicate(args_pred):\n self.args_pred = args_pred\nif is_predicate(severity_pred):\n self.severity_pred = ... | <|body_start_0|>
true_pred = always_true()
self.id_pred = true_pred
self.args_pred = true_pred
self.severity_pred = true_pred
self.time_pred = true_pred
if is_predicate(id_pred):
self.id_pred = id_pred
if is_predicate(args_pred):
self.args_... | event_predicate | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class event_predicate:
def __init__(self, id_pred=None, args_pred=None, severity_pred=None, time_pred=None):
"""A predicate for specifying an EventData object from data_types.event_data. This predicate can be used to search a history. If arguments passed into this constructor are not subclasse... | stack_v2_sparse_classes_75kplus_train_072239 | 19,146 | permissive | [
{
"docstring": "A predicate for specifying an EventData object from data_types.event_data. This predicate can be used to search a history. If arguments passed into this constructor are not subclasses of predicate, they will be ignored. If an argument is unspecified, the predicate will ignore that field when eva... | 3 | stack_v2_sparse_classes_30k_train_023276 | Implement the Python class `event_predicate` described below.
Class description:
Implement the event_predicate class.
Method signatures and docstrings:
- def __init__(self, id_pred=None, args_pred=None, severity_pred=None, time_pred=None): A predicate for specifying an EventData object from data_types.event_data. Thi... | Implement the Python class `event_predicate` described below.
Class description:
Implement the event_predicate class.
Method signatures and docstrings:
- def __init__(self, id_pred=None, args_pred=None, severity_pred=None, time_pred=None): A predicate for specifying an EventData object from data_types.event_data. Thi... | aa663303327587146390dde67b83b9bf4e916d54 | <|skeleton|>
class event_predicate:
def __init__(self, id_pred=None, args_pred=None, severity_pred=None, time_pred=None):
"""A predicate for specifying an EventData object from data_types.event_data. This predicate can be used to search a history. If arguments passed into this constructor are not subclasse... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class event_predicate:
def __init__(self, id_pred=None, args_pred=None, severity_pred=None, time_pred=None):
"""A predicate for specifying an EventData object from data_types.event_data. This predicate can be used to search a history. If arguments passed into this constructor are not subclasses of predicate... | the_stack_v2_python_sparse | Gds/src/fprime_gds/common/testing_fw/predicates.py | suriyaa/fprime | train | 1 | |
023b6195184f48824608ca87300910c5b9353b8b | [
"c = Client()\nr = c.get(reverse('entry_example'))\nself.assertEqual(r.content.decode('utf-8').find('Hotel') > -1, True)",
"c = Client()\nr = c.get(reverse('entry_vg', args=('20647',)), follow=True)\nself.assertEqual(r.status_code, 200)\nself.assertEqual(r.content.decode('utf-8').find('Flax') > -1, True)",
"c =... | <|body_start_0|>
c = Client()
r = c.get(reverse('entry_example'))
self.assertEqual(r.content.decode('utf-8').find('Hotel') > -1, True)
<|end_body_0|>
<|body_start_1|>
c = Client()
r = c.get(reverse('entry_vg', args=('20647',)), follow=True)
self.assertEqual(r.status_code... | Tests for the entries. | EntryTest | [
"Zlib"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EntryTest:
"""Tests for the entries."""
def test_view_get_example_entry(self):
"""Test static example entry view."""
<|body_0|>
def test_view_flax(self):
"""Test name of the place."""
<|body_1|>
def test_view_other_enjoy(self):
"""Test catego... | stack_v2_sparse_classes_75kplus_train_072240 | 3,966 | permissive | [
{
"docstring": "Test static example entry view.",
"name": "test_view_get_example_entry",
"signature": "def test_view_get_example_entry(self)"
},
{
"docstring": "Test name of the place.",
"name": "test_view_flax",
"signature": "def test_view_flax(self)"
},
{
"docstring": "Test cat... | 4 | stack_v2_sparse_classes_30k_test_000665 | Implement the Python class `EntryTest` described below.
Class description:
Tests for the entries.
Method signatures and docstrings:
- def test_view_get_example_entry(self): Test static example entry view.
- def test_view_flax(self): Test name of the place.
- def test_view_other_enjoy(self): Test category other in Enj... | Implement the Python class `EntryTest` described below.
Class description:
Tests for the entries.
Method signatures and docstrings:
- def test_view_get_example_entry(self): Test static example entry view.
- def test_view_flax(self): Test name of the place.
- def test_view_other_enjoy(self): Test category other in Enj... | 652d62bdbfbfbff4872697bcfcde5da4ce44f98a | <|skeleton|>
class EntryTest:
"""Tests for the entries."""
def test_view_get_example_entry(self):
"""Test static example entry view."""
<|body_0|>
def test_view_flax(self):
"""Test name of the place."""
<|body_1|>
def test_view_other_enjoy(self):
"""Test catego... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EntryTest:
"""Tests for the entries."""
def test_view_get_example_entry(self):
"""Test static example entry view."""
c = Client()
r = c.get(reverse('entry_example'))
self.assertEqual(r.content.decode('utf-8').find('Hotel') > -1, True)
def test_view_flax(self):
... | the_stack_v2_python_sparse | vegbasketapp/vegbasketapp/frontend/tests.py | VeggieSailor/vegbasket | train | 1 |
7f7a2b69931cbbc5e10fac19745324e8d2e4719e | [
"headers['Authorization'] = self._basic_auth()\nheaders['Accept'] = 'application/json'\nheaders['Content-Type'] = 'application/json'\nreturn headers",
"credentials = b('{}:{}'.format(self.user_id, self.key))\ncredentials = base64.b64encode(credentials)\nreturn 'Basic {}'.format(credentials.decode('ascii'))"
] | <|body_start_0|>
headers['Authorization'] = self._basic_auth()
headers['Accept'] = 'application/json'
headers['Content-Type'] = 'application/json'
return headers
<|end_body_0|>
<|body_start_1|>
credentials = b('{}:{}'.format(self.user_id, self.key))
credentials = base64.... | Connection class for UpcloudDriver | UpcloudConnection | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpcloudConnection:
"""Connection class for UpcloudDriver"""
def add_default_headers(self, headers):
"""Adds headers that are needed for all requests"""
<|body_0|>
def _basic_auth(self):
"""Constructs basic auth header content string"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_072241 | 10,531 | permissive | [
{
"docstring": "Adds headers that are needed for all requests",
"name": "add_default_headers",
"signature": "def add_default_headers(self, headers)"
},
{
"docstring": "Constructs basic auth header content string",
"name": "_basic_auth",
"signature": "def _basic_auth(self)"
}
] | 2 | null | Implement the Python class `UpcloudConnection` described below.
Class description:
Connection class for UpcloudDriver
Method signatures and docstrings:
- def add_default_headers(self, headers): Adds headers that are needed for all requests
- def _basic_auth(self): Constructs basic auth header content string | Implement the Python class `UpcloudConnection` described below.
Class description:
Connection class for UpcloudDriver
Method signatures and docstrings:
- def add_default_headers(self, headers): Adds headers that are needed for all requests
- def _basic_auth(self): Constructs basic auth header content string
<|skelet... | abba8c1719a8bda6db8efde2d46fd1b423ae4304 | <|skeleton|>
class UpcloudConnection:
"""Connection class for UpcloudDriver"""
def add_default_headers(self, headers):
"""Adds headers that are needed for all requests"""
<|body_0|>
def _basic_auth(self):
"""Constructs basic auth header content string"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UpcloudConnection:
"""Connection class for UpcloudDriver"""
def add_default_headers(self, headers):
"""Adds headers that are needed for all requests"""
headers['Authorization'] = self._basic_auth()
headers['Accept'] = 'application/json'
headers['Content-Type'] = 'applicati... | the_stack_v2_python_sparse | libcloud/compute/drivers/upcloud.py | apache/libcloud | train | 1,644 |
58ea64943f01258f862d43f0205e6793605a8ad8 | [
"left, right = (0, len(A) - 1)\nwhile left < right and A[left] < A[left + 1]:\n left += 1\nwhile right > 0 and A[right] < A[right - 1]:\n right -= 1\nreturn 0 < left == right < len(A) - 1",
"i = 0\nwhile i + 1 < len(A) and A[i] < A[i + 1]:\n i += 1\nif i == len(A) - 1 or i == 0:\n return False\nwhile ... | <|body_start_0|>
left, right = (0, len(A) - 1)
while left < right and A[left] < A[left + 1]:
left += 1
while right > 0 and A[right] < A[right - 1]:
right -= 1
return 0 < left == right < len(A) - 1
<|end_body_0|>
<|body_start_1|>
i = 0
while i + 1 ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def validMountainArray(A: List[int]) -> bool:
"""双指针找峰顶 :param A: :return:"""
<|body_0|>
def validMountainArray2(A: List[int]) -> bool:
"""先找到峰顶 :param A: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
left, right = (0, len(A) - ... | stack_v2_sparse_classes_75kplus_train_072242 | 973 | no_license | [
{
"docstring": "双指针找峰顶 :param A: :return:",
"name": "validMountainArray",
"signature": "def validMountainArray(A: List[int]) -> bool"
},
{
"docstring": "先找到峰顶 :param A: :return:",
"name": "validMountainArray2",
"signature": "def validMountainArray2(A: List[int]) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_train_048819 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validMountainArray(A: List[int]) -> bool: 双指针找峰顶 :param A: :return:
- def validMountainArray2(A: List[int]) -> bool: 先找到峰顶 :param A: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validMountainArray(A: List[int]) -> bool: 双指针找峰顶 :param A: :return:
- def validMountainArray2(A: List[int]) -> bool: 先找到峰顶 :param A: :return:
<|skeleton|>
class Solution:
... | 578cacff5851c5c2522981693c34e3c318002d30 | <|skeleton|>
class Solution:
def validMountainArray(A: List[int]) -> bool:
"""双指针找峰顶 :param A: :return:"""
<|body_0|>
def validMountainArray2(A: List[int]) -> bool:
"""先找到峰顶 :param A: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def validMountainArray(A: List[int]) -> bool:
"""双指针找峰顶 :param A: :return:"""
left, right = (0, len(A) - 1)
while left < right and A[left] < A[left + 1]:
left += 1
while right > 0 and A[right] < A[right - 1]:
right -= 1
return 0 < left ... | the_stack_v2_python_sparse | 有效的山脉数组.py | cjrzs/MyLeetCode | train | 8 | |
2689ffa7724fa8338298faf819d01db62cf57b4b | [
"super(MyWindow, self).__init__(parent)\nself.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowSystemMenuHint)\nself.setStyleSheet('background-color:cyan;')",
"desktop = QApplication.desktop()\nrect = desktop.availableGeometry()\nself.setGeometry(rect)\nself.show()"
] | <|body_start_0|>
super(MyWindow, self).__init__(parent)
self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowSystemMenuHint)
self.setStyleSheet('background-color:cyan;')
<|end_body_0|>
<|body_start_1|>
desktop = QApplication.desktop()
rect = desktop.availableGeometry()
... | 自定义窗口类 | MyWindow | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyWindow:
"""自定义窗口类"""
def __init__(self, parent=None):
"""构造函数"""
<|body_0|>
def showMaximized(self):
"""最大化"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(MyWindow, self).__init__(parent)
self.setWindowFlags(Qt.FramelessWindowHi... | stack_v2_sparse_classes_75kplus_train_072243 | 1,579 | no_license | [
{
"docstring": "构造函数",
"name": "__init__",
"signature": "def __init__(self, parent=None)"
},
{
"docstring": "最大化",
"name": "showMaximized",
"signature": "def showMaximized(self)"
}
] | 2 | null | Implement the Python class `MyWindow` described below.
Class description:
自定义窗口类
Method signatures and docstrings:
- def __init__(self, parent=None): 构造函数
- def showMaximized(self): 最大化 | Implement the Python class `MyWindow` described below.
Class description:
自定义窗口类
Method signatures and docstrings:
- def __init__(self, parent=None): 构造函数
- def showMaximized(self): 最大化
<|skeleton|>
class MyWindow:
"""自定义窗口类"""
def __init__(self, parent=None):
"""构造函数"""
<|body_0|>
def ... | d25106fb4654fd19293946c596f6f3ecb7fd8ad0 | <|skeleton|>
class MyWindow:
"""自定义窗口类"""
def __init__(self, parent=None):
"""构造函数"""
<|body_0|>
def showMaximized(self):
"""最大化"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyWindow:
"""自定义窗口类"""
def __init__(self, parent=None):
"""构造函数"""
super(MyWindow, self).__init__(parent)
self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowSystemMenuHint)
self.setStyleSheet('background-color:cyan;')
def showMaximized(self):
"""最大化"""
... | the_stack_v2_python_sparse | src/uidemo/noframeDemo.py | winsomexiao/PyDemo | train | 1 |
1c14239a03d56df053ebcddf41168fb9455b0810 | [
"self.timeout = 5\nself.verbose = False\nself.buffer = 4096\nself.secret = None\nself.crypt = AES\nself.crypt_chunk_size = 16\nself.max_queue = 10",
"if not cls._instance:\n cls._instance = cls()\nreturn cls._instance",
"conf = ConfigParser()\nconf.read(path)\nif not conf.has_section(CONFIG_SECTION):\n re... | <|body_start_0|>
self.timeout = 5
self.verbose = False
self.buffer = 4096
self.secret = None
self.crypt = AES
self.crypt_chunk_size = 16
self.max_queue = 10
<|end_body_0|>
<|body_start_1|>
if not cls._instance:
cls._instance = cls()
re... | Simple object to hold jsonrpctcp configuration options | Config | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Config:
"""Simple object to hold jsonrpctcp configuration options"""
def __init__(self):
"""The default values for the configuration."""
<|body_0|>
def instance(cls):
"""Retrieves singleton"""
<|body_1|>
def load(self, path):
"""Loads setting... | stack_v2_sparse_classes_75kplus_train_072244 | 1,930 | permissive | [
{
"docstring": "The default values for the configuration.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Retrieves singleton",
"name": "instance",
"signature": "def instance(cls)"
},
{
"docstring": "Loads settings from a configuration file.",
"name... | 3 | stack_v2_sparse_classes_30k_train_004005 | Implement the Python class `Config` described below.
Class description:
Simple object to hold jsonrpctcp configuration options
Method signatures and docstrings:
- def __init__(self): The default values for the configuration.
- def instance(cls): Retrieves singleton
- def load(self, path): Loads settings from a config... | Implement the Python class `Config` described below.
Class description:
Simple object to hold jsonrpctcp configuration options
Method signatures and docstrings:
- def __init__(self): The default values for the configuration.
- def instance(cls): Retrieves singleton
- def load(self, path): Loads settings from a config... | 53897607f04bc390ff3b6ee8f052c74d90f825e9 | <|skeleton|>
class Config:
"""Simple object to hold jsonrpctcp configuration options"""
def __init__(self):
"""The default values for the configuration."""
<|body_0|>
def instance(cls):
"""Retrieves singleton"""
<|body_1|>
def load(self, path):
"""Loads setting... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Config:
"""Simple object to hold jsonrpctcp configuration options"""
def __init__(self):
"""The default values for the configuration."""
self.timeout = 5
self.verbose = False
self.buffer = 4096
self.secret = None
self.crypt = AES
self.crypt_chunk_si... | the_stack_v2_python_sparse | jsonrpctcp/config.py | sancelot/jsonrpctcp | train | 1 |
199c04627152517106d09e6714bbfbfdba8040d4 | [
"self.token = self.root_collection['response']['collections'][0]['links']['http://oauth.net/core/2.0/endpoint/token']['href']\ncookie_handler = HTTPCookieProcessor()\nself.cookies = cookie_handler.cookiejar\nself.opener = build_opener(cookie_handler)",
"self.logged_in = False\nself.cookies.clear()\nurl = self.tok... | <|body_start_0|>
self.token = self.root_collection['response']['collections'][0]['links']['http://oauth.net/core/2.0/endpoint/token']['href']
cookie_handler = HTTPCookieProcessor()
self.cookies = cookie_handler.cookiejar
self.opener = build_opener(cookie_handler)
<|end_body_0|>
<|body_s... | Authentication | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Authentication:
def __init__(self):
"""https://familysearch.org/developers/docs/api/resources#authentication Set up the URLs for authentication."""
<|body_0|>
def login(self, username, password):
"""Log into FamilySearch using Basic Authentication. This mechanism is ... | stack_v2_sparse_classes_75kplus_train_072245 | 5,976 | permissive | [
{
"docstring": "https://familysearch.org/developers/docs/api/resources#authentication Set up the URLs for authentication.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Log into FamilySearch using Basic Authentication. This mechanism is available only to approved deve... | 6 | stack_v2_sparse_classes_30k_train_016236 | Implement the Python class `Authentication` described below.
Class description:
Implement the Authentication class.
Method signatures and docstrings:
- def __init__(self): https://familysearch.org/developers/docs/api/resources#authentication Set up the URLs for authentication.
- def login(self, username, password): L... | Implement the Python class `Authentication` described below.
Class description:
Implement the Authentication class.
Method signatures and docstrings:
- def __init__(self): https://familysearch.org/developers/docs/api/resources#authentication Set up the URLs for authentication.
- def login(self, username, password): L... | 78ff962b9dc4a7a580f1dc94e1094fa214d2d7ae | <|skeleton|>
class Authentication:
def __init__(self):
"""https://familysearch.org/developers/docs/api/resources#authentication Set up the URLs for authentication."""
<|body_0|>
def login(self, username, password):
"""Log into FamilySearch using Basic Authentication. This mechanism is ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Authentication:
def __init__(self):
"""https://familysearch.org/developers/docs/api/resources#authentication Set up the URLs for authentication."""
self.token = self.root_collection['response']['collections'][0]['links']['http://oauth.net/core/2.0/endpoint/token']['href']
cookie_handle... | the_stack_v2_python_sparse | familysearch/authentication_.py | dangerwheeler/familysearch-python-sdk-opensource | train | 1 | |
2662eab3094ce1b4b0db9369edac940ffe9ada52 | [
"self.wrapped_exc = exception\nself.status_int = self.wrapped_exc.status_int\nself._body_function = body_function or _default_body_function",
"fault_data, metadata = self._body_function(self.wrapped_exc)\ncontent_type = req.best_match_content_type()\nserializer = {'application/json': JSONDictSerializer()}[content... | <|body_start_0|>
self.wrapped_exc = exception
self.status_int = self.wrapped_exc.status_int
self._body_function = body_function or _default_body_function
<|end_body_0|>
<|body_start_1|>
fault_data, metadata = self._body_function(self.wrapped_exc)
content_type = req.best_match_co... | Generates an HTTP response from a webob HTTP exception. | Fault | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fault:
"""Generates an HTTP response from a webob HTTP exception."""
def __init__(self, exception, body_function=None):
"""Creates a Fault for the given webob.exc.exception."""
<|body_0|>
def __call__(self, req):
"""Generate a WSGI response based on the exception... | stack_v2_sparse_classes_75kplus_train_072246 | 29,625 | permissive | [
{
"docstring": "Creates a Fault for the given webob.exc.exception.",
"name": "__init__",
"signature": "def __init__(self, exception, body_function=None)"
},
{
"docstring": "Generate a WSGI response based on the exception passed to ctor.",
"name": "__call__",
"signature": "def __call__(se... | 2 | stack_v2_sparse_classes_30k_train_052028 | Implement the Python class `Fault` described below.
Class description:
Generates an HTTP response from a webob HTTP exception.
Method signatures and docstrings:
- def __init__(self, exception, body_function=None): Creates a Fault for the given webob.exc.exception.
- def __call__(self, req): Generate a WSGI response b... | Implement the Python class `Fault` described below.
Class description:
Generates an HTTP response from a webob HTTP exception.
Method signatures and docstrings:
- def __init__(self, exception, body_function=None): Creates a Fault for the given webob.exc.exception.
- def __call__(self, req): Generate a WSGI response b... | dde31aae392b80341f6440eb38db1583563d7d1f | <|skeleton|>
class Fault:
"""Generates an HTTP response from a webob HTTP exception."""
def __init__(self, exception, body_function=None):
"""Creates a Fault for the given webob.exc.exception."""
<|body_0|>
def __call__(self, req):
"""Generate a WSGI response based on the exception... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Fault:
"""Generates an HTTP response from a webob HTTP exception."""
def __init__(self, exception, body_function=None):
"""Creates a Fault for the given webob.exc.exception."""
self.wrapped_exc = exception
self.status_int = self.wrapped_exc.status_int
self._body_function =... | the_stack_v2_python_sparse | neutron/wsgi.py | openstack/neutron | train | 1,174 |
310ccac25b05026cd0ceb0262f4ef04869692e10 | [
"cmds = ['resize', filename, size]\noutput, return_code = self.command(cmds)\nif return_code == 0:\n return True\nelse:\n return False",
"flags = []\nif output_format:\n flags.append(['-O', output_format])\ncmds = ['convert'] + flags + [filename, output_filename]\noutput, return_code = self.command(cmds)... | <|body_start_0|>
cmds = ['resize', filename, size]
output, return_code = self.command(cmds)
if return_code == 0:
return True
else:
return False
<|end_body_0|>
<|body_start_1|>
flags = []
if output_format:
flags.append(['-O', output_for... | CloudInit | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CloudInit:
def resize(self, filename: str, size: str):
"""Resize disk images using `qemu-img resize`. :param filename: Path on the local filesystem to the image file. :param size: Size to set for the disk image. If you specify + or -, it will add or remove disk space from the image. e.g.... | stack_v2_sparse_classes_75kplus_train_072247 | 3,092 | permissive | [
{
"docstring": "Resize disk images using `qemu-img resize`. :param filename: Path on the local filesystem to the image file. :param size: Size to set for the disk image. If you specify + or -, it will add or remove disk space from the image. e.g. 60G, +10G :returns: boolean if the operation was successful.",
... | 4 | null | Implement the Python class `CloudInit` described below.
Class description:
Implement the CloudInit class.
Method signatures and docstrings:
- def resize(self, filename: str, size: str): Resize disk images using `qemu-img resize`. :param filename: Path on the local filesystem to the image file. :param size: Size to se... | Implement the Python class `CloudInit` described below.
Class description:
Implement the CloudInit class.
Method signatures and docstrings:
- def resize(self, filename: str, size: str): Resize disk images using `qemu-img resize`. :param filename: Path on the local filesystem to the image file. :param size: Size to se... | 30d105154dcf5aa34af120db384fab95c4d5765c | <|skeleton|>
class CloudInit:
def resize(self, filename: str, size: str):
"""Resize disk images using `qemu-img resize`. :param filename: Path on the local filesystem to the image file. :param size: Size to set for the disk image. If you specify + or -, it will add or remove disk space from the image. e.g.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CloudInit:
def resize(self, filename: str, size: str):
"""Resize disk images using `qemu-img resize`. :param filename: Path on the local filesystem to the image file. :param size: Size to set for the disk image. If you specify + or -, it will add or remove disk space from the image. e.g. 60G, +10G :re... | the_stack_v2_python_sparse | utils-app/utils/cloudinit.py | mgtrrz/echome | train | 2 | |
77bbc498738c8174c74f106afa9b877bffd16016 | [
"self.key = aKey\nself.crc = 0\nfor x in self.key:\n intX = ord(x)\n self.crc = self.crc ^ intX",
"kIdx = 0\ncryptStr = ''\nfor x in range(len(aString)):\n cryptStr = cryptStr + chr(ord(aString[x]) ^ ord(self.key[kIdx]))\n kIdx = (kIdx + 1) % len(self.key)\nreturn cryptStr"
] | <|body_start_0|>
self.key = aKey
self.crc = 0
for x in self.key:
intX = ord(x)
self.crc = self.crc ^ intX
<|end_body_0|>
<|body_start_1|>
kIdx = 0
cryptStr = ''
for x in range(len(aString)):
cryptStr = cryptStr + chr(ord(aString[x]) ^ ... | PEcrypt - very, very simple word key encryption system uses cyclic XOR between the keyword character bytes and the string to be encrypted/decrypted. Therefore, the same function and keyword will encrypt the string the first time and decrypt it if called on the encrypted string. | PEcrypt | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PEcrypt:
"""PEcrypt - very, very simple word key encryption system uses cyclic XOR between the keyword character bytes and the string to be encrypted/decrypted. Therefore, the same function and keyword will encrypt the string the first time and decrypt it if called on the encrypted string."""
... | stack_v2_sparse_classes_75kplus_train_072248 | 3,796 | no_license | [
{
"docstring": "Initialise the class with the key that is used to encrypt/decrypt strings",
"name": "__init__",
"signature": "def __init__(self, aKey)"
},
{
"docstring": "Encrypt/Decrypt the passed string object and return the encrypted string",
"name": "Crypt",
"signature": "def Crypt(s... | 2 | stack_v2_sparse_classes_30k_test_003040 | Implement the Python class `PEcrypt` described below.
Class description:
PEcrypt - very, very simple word key encryption system uses cyclic XOR between the keyword character bytes and the string to be encrypted/decrypted. Therefore, the same function and keyword will encrypt the string the first time and decrypt it if... | Implement the Python class `PEcrypt` described below.
Class description:
PEcrypt - very, very simple word key encryption system uses cyclic XOR between the keyword character bytes and the string to be encrypted/decrypted. Therefore, the same function and keyword will encrypt the string the first time and decrypt it if... | b4c81010a1476721cabc2621b17d92fead9314b4 | <|skeleton|>
class PEcrypt:
"""PEcrypt - very, very simple word key encryption system uses cyclic XOR between the keyword character bytes and the string to be encrypted/decrypted. Therefore, the same function and keyword will encrypt the string the first time and decrypt it if called on the encrypted string."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PEcrypt:
"""PEcrypt - very, very simple word key encryption system uses cyclic XOR between the keyword character bytes and the string to be encrypted/decrypted. Therefore, the same function and keyword will encrypt the string the first time and decrypt it if called on the encrypted string."""
def __init_... | the_stack_v2_python_sparse | BASE SCRIPTS/XOR decryption.py | btrif/Python_dev_repo | train | 0 |
9db7c40c3e23c144188df31219c4201cd1f83fec | [
"form_pk = self.kwargs.get('pk')\nif self.action == 'list' and form_pk is None:\n return OSMSiteMapSerializer\nreturn super().get_serializer_class()",
"form_pk = self.kwargs.get('pk')\nif form_pk:\n queryset = queryset.filter(pk=form_pk)\nreturn super().filter_queryset(queryset)",
"obj = super().get_objec... | <|body_start_0|>
form_pk = self.kwargs.get('pk')
if self.action == 'list' and form_pk is None:
return OSMSiteMapSerializer
return super().get_serializer_class()
<|end_body_0|>
<|body_start_1|>
form_pk = self.kwargs.get('pk')
if form_pk:
queryset = queryse... | This endpoint provides public access to OSM submitted data in OSM format. No authentication is required. Where: * `pk` - the form unique identifier * `dataid` - submission data unique identifier * `owner` - username of the owner(user/organization) of the data point ## GET JSON List of data end points Lists the data end... | OsmViewSet | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OsmViewSet:
"""This endpoint provides public access to OSM submitted data in OSM format. No authentication is required. Where: * `pk` - the form unique identifier * `dataid` - submission data unique identifier * `owner` - username of the owner(user/organization) of the data point ## GET JSON List... | stack_v2_sparse_classes_75kplus_train_072249 | 6,952 | permissive | [
{
"docstring": "Returns the OSMSiteMapSerializer class when list API is invoked.",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "Filters the queryset using the ``pk`` when used.",
"name": "filter_queryset",
"signature": "def filter_query... | 5 | stack_v2_sparse_classes_30k_train_048280 | Implement the Python class `OsmViewSet` described below.
Class description:
This endpoint provides public access to OSM submitted data in OSM format. No authentication is required. Where: * `pk` - the form unique identifier * `dataid` - submission data unique identifier * `owner` - username of the owner(user/organizat... | Implement the Python class `OsmViewSet` described below.
Class description:
This endpoint provides public access to OSM submitted data in OSM format. No authentication is required. Where: * `pk` - the form unique identifier * `dataid` - submission data unique identifier * `owner` - username of the owner(user/organizat... | e5bdec91cb47179172b515bbcb91701262ff3377 | <|skeleton|>
class OsmViewSet:
"""This endpoint provides public access to OSM submitted data in OSM format. No authentication is required. Where: * `pk` - the form unique identifier * `dataid` - submission data unique identifier * `owner` - username of the owner(user/organization) of the data point ## GET JSON List... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OsmViewSet:
"""This endpoint provides public access to OSM submitted data in OSM format. No authentication is required. Where: * `pk` - the form unique identifier * `dataid` - submission data unique identifier * `owner` - username of the owner(user/organization) of the data point ## GET JSON List of data end ... | the_stack_v2_python_sparse | onadata/apps/api/viewsets/osm_viewset.py | onaio/onadata | train | 177 |
98b5b5a9d7c346cdfb6518d0830ea3814fd70f7a | [
"test_task = {'run_time': None, 'last_update': None}\nstats = TurbiniaStats()\nstats.add_task(test_task)\nself.assertIn(test_task, stats.tasks)\nself.assertEqual(stats.count, 1)",
"last_update = datetime.now()\ntest_task1 = {'run_time': timedelta(minutes=3), 'last_update': last_update}\ntest_task2 = {'run_time': ... | <|body_start_0|>
test_task = {'run_time': None, 'last_update': None}
stats = TurbiniaStats()
stats.add_task(test_task)
self.assertIn(test_task, stats.tasks)
self.assertEqual(stats.count, 1)
<|end_body_0|>
<|body_start_1|>
last_update = datetime.now()
test_task1 =... | Test TurbiniaStats class. | TestTurbiniaStats | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestTurbiniaStats:
"""Test TurbiniaStats class."""
def testTurbiniaStatsAddTask(self):
"""Tests TurbiniaStats.add_task() method."""
<|body_0|>
def testTurbiniaStatsCalculateStats(self):
"""Tests TurbiniaStats.calculateStats() method."""
<|body_1|>
de... | stack_v2_sparse_classes_75kplus_train_072250 | 31,299 | permissive | [
{
"docstring": "Tests TurbiniaStats.add_task() method.",
"name": "testTurbiniaStatsAddTask",
"signature": "def testTurbiniaStatsAddTask(self)"
},
{
"docstring": "Tests TurbiniaStats.calculateStats() method.",
"name": "testTurbiniaStatsCalculateStats",
"signature": "def testTurbiniaStatsC... | 5 | stack_v2_sparse_classes_30k_train_035910 | Implement the Python class `TestTurbiniaStats` described below.
Class description:
Test TurbiniaStats class.
Method signatures and docstrings:
- def testTurbiniaStatsAddTask(self): Tests TurbiniaStats.add_task() method.
- def testTurbiniaStatsCalculateStats(self): Tests TurbiniaStats.calculateStats() method.
- def te... | Implement the Python class `TestTurbiniaStats` described below.
Class description:
Test TurbiniaStats class.
Method signatures and docstrings:
- def testTurbiniaStatsAddTask(self): Tests TurbiniaStats.add_task() method.
- def testTurbiniaStatsCalculateStats(self): Tests TurbiniaStats.calculateStats() method.
- def te... | e73717549c6919e869ce4963449c36f227e3ccd6 | <|skeleton|>
class TestTurbiniaStats:
"""Test TurbiniaStats class."""
def testTurbiniaStatsAddTask(self):
"""Tests TurbiniaStats.add_task() method."""
<|body_0|>
def testTurbiniaStatsCalculateStats(self):
"""Tests TurbiniaStats.calculateStats() method."""
<|body_1|>
de... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestTurbiniaStats:
"""Test TurbiniaStats class."""
def testTurbiniaStatsAddTask(self):
"""Tests TurbiniaStats.add_task() method."""
test_task = {'run_time': None, 'last_update': None}
stats = TurbiniaStats()
stats.add_task(test_task)
self.assertIn(test_task, stats.... | the_stack_v2_python_sparse | turbinia/client_test.py | Ash515/turbinia | train | 6 |
278a2ac80920a9e32fd77b3c254e2bfe70710849 | [
"assert type(n_bins) is int\nassert n_bins > 0\nassert isinstance(bin_boundaries_policy, BinBoundariesPolicy)\nsuper().__init__(n_bins=n_bins, bin_boundaries_policy=bin_boundaries_policy)",
"if positive_scores is None:\n assert model is not None, 'When positive_scores are not provided, model has to be, here is... | <|body_start_0|>
assert type(n_bins) is int
assert n_bins > 0
assert isinstance(bin_boundaries_policy, BinBoundariesPolicy)
super().__init__(n_bins=n_bins, bin_boundaries_policy=bin_boundaries_policy)
<|end_body_0|>
<|body_start_1|>
if positive_scores is None:
assert... | BinaryBinningPolicy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinaryBinningPolicy:
def __init__(self, n_bins, bin_boundaries_policy):
"""Initializes a specific class binning policy, which sends samples into the n_bins bins created by the bin_boundaries_policy, based on the score the model gives for the positive class. Args: n_bins: int, number of b... | stack_v2_sparse_classes_75kplus_train_072251 | 6,913 | permissive | [
{
"docstring": "Initializes a specific class binning policy, which sends samples into the n_bins bins created by the bin_boundaries_policy, based on the score the model gives for the positive class. Args: n_bins: int, number of bins used to divide the interval. bin_boundaries_policy: BinBoundariesPolicy, defini... | 2 | stack_v2_sparse_classes_30k_train_026097 | Implement the Python class `BinaryBinningPolicy` described below.
Class description:
Implement the BinaryBinningPolicy class.
Method signatures and docstrings:
- def __init__(self, n_bins, bin_boundaries_policy): Initializes a specific class binning policy, which sends samples into the n_bins bins created by the bin_... | Implement the Python class `BinaryBinningPolicy` described below.
Class description:
Implement the BinaryBinningPolicy class.
Method signatures and docstrings:
- def __init__(self, n_bins, bin_boundaries_policy): Initializes a specific class binning policy, which sends samples into the n_bins bins created by the bin_... | 9bfa81dd7a39ebe069c5b11b8e7a9bf9017e9350 | <|skeleton|>
class BinaryBinningPolicy:
def __init__(self, n_bins, bin_boundaries_policy):
"""Initializes a specific class binning policy, which sends samples into the n_bins bins created by the bin_boundaries_policy, based on the score the model gives for the positive class. Args: n_bins: int, number of b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BinaryBinningPolicy:
def __init__(self, n_bins, bin_boundaries_policy):
"""Initializes a specific class binning policy, which sends samples into the n_bins bins created by the bin_boundaries_policy, based on the score the model gives for the positive class. Args: n_bins: int, number of bins used to di... | the_stack_v2_python_sparse | explicalib/calibration/evaluation/prototype/binning/legacy.py | euranova/estimating_eces | train | 4 | |
aafd898abc8995b12e285e12e55d82d63ababc4f | [
"if authorization_header is None:\n return None\nelif type(authorization_header) != str:\n return None\nelif 'Basic' not in authorization_header:\n return None\nelse:\n return authorization_header.split('Basic ', 1)[1]",
"if base64_authorization_header is None:\n return None\nelif type(base64_autho... | <|body_start_0|>
if authorization_header is None:
return None
elif type(authorization_header) != str:
return None
elif 'Basic' not in authorization_header:
return None
else:
return authorization_header.split('Basic ', 1)[1]
<|end_body_0|>
... | Creating BasicAuth class inheriting from Auth | BasicAuth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicAuth:
"""Creating BasicAuth class inheriting from Auth"""
def extract_base64_authorization_header(self, authorization_header):
"""validates authorization header"""
<|body_0|>
def decode_base64_authorization_header(self, base64_authorization_header):
"""decod... | stack_v2_sparse_classes_75kplus_train_072252 | 3,289 | no_license | [
{
"docstring": "validates authorization header",
"name": "extract_base64_authorization_header",
"signature": "def extract_base64_authorization_header(self, authorization_header)"
},
{
"docstring": "decodes base64 value",
"name": "decode_base64_authorization_header",
"signature": "def dec... | 5 | stack_v2_sparse_classes_30k_train_047235 | Implement the Python class `BasicAuth` described below.
Class description:
Creating BasicAuth class inheriting from Auth
Method signatures and docstrings:
- def extract_base64_authorization_header(self, authorization_header): validates authorization header
- def decode_base64_authorization_header(self, base64_authori... | Implement the Python class `BasicAuth` described below.
Class description:
Creating BasicAuth class inheriting from Auth
Method signatures and docstrings:
- def extract_base64_authorization_header(self, authorization_header): validates authorization header
- def decode_base64_authorization_header(self, base64_authori... | ada5397c0dfce39df19e8d5f5a4ff12a17aca020 | <|skeleton|>
class BasicAuth:
"""Creating BasicAuth class inheriting from Auth"""
def extract_base64_authorization_header(self, authorization_header):
"""validates authorization header"""
<|body_0|>
def decode_base64_authorization_header(self, base64_authorization_header):
"""decod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BasicAuth:
"""Creating BasicAuth class inheriting from Auth"""
def extract_base64_authorization_header(self, authorization_header):
"""validates authorization header"""
if authorization_header is None:
return None
elif type(authorization_header) != str:
ret... | the_stack_v2_python_sparse | 0x02-restful_api_users/api/v1/auth/basic_auth.py | madejean/holbertonschool-webstack_back_end | train | 0 |
dabeaf7d14cd918d5ae92e58ae0a128fa0efe0f6 | [
"self.width = width\nself.height = height\nself.food = deque(food)\nself.snake = deque([[0, 0]])\nself.direct = {'U': [-1, 0], 'L': [0, -1], 'R': [0, +1], 'D': [1, 0]}\nprint('start from: 0, 0')",
"r0, c0 = self.snake[0]\nr1, c1 = self.direct[direction]\nnew_head = [r0 + r1, c0 + c1]\nif new_head[0] < 0 or new_he... | <|body_start_0|>
self.width = width
self.height = height
self.food = deque(food)
self.snake = deque([[0, 0]])
self.direct = {'U': [-1, 0], 'L': [0, -1], 'R': [0, +1], 'D': [1, 0]}
print('start from: 0, 0')
<|end_body_0|>
<|body_start_1|>
r0, c0 = self.snake[0]
... | SnakeGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :typ... | stack_v2_sparse_classes_75kplus_train_072253 | 2,136 | no_license | [
{
"docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int :type height: int :type food: List[List[int]]",
... | 2 | stack_v2_sparse_classes_30k_train_006626 | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E... | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width, height, food): Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E... | bf98c8fa31043a45b3d21cfe78d4e08f9cac9de6 | <|skeleton|>
class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :typ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SnakeGame:
def __init__(self, width, height, food):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int :... | the_stack_v2_python_sparse | interviews/Palantir/353_design_snake_game.py | mistrydarshan99/Leetcode-3 | train | 0 | |
7c0691e37058110fab8a976ded266ab51fb38443 | [
"sc.logger.info(u'创作页面初始状态检查测试开始')\ntime.sleep(2)\nel_home = sc.driver.find_element_by_id('com.quvideo.xiaoying:id/img_creation')\nel_home.click()\ntime.sleep(0.5)\nsc.capture_screen(inspect.stack()[0][3], sc.path_lists[0])\nassert el_home is not None",
"sc.logger.info(u'创作页面下拉刷新测试开始')\nstart_x = self.width // 2\... | <|body_start_0|>
sc.logger.info(u'创作页面初始状态检查测试开始')
time.sleep(2)
el_home = sc.driver.find_element_by_id('com.quvideo.xiaoying:id/img_creation')
el_home.click()
time.sleep(0.5)
sc.capture_screen(inspect.stack()[0][3], sc.path_lists[0])
assert el_home is not None
<|... | 创作页面的测试类,分步截图 | TestCreationUI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCreationUI:
"""创作页面的测试类,分步截图"""
def test_origin():
"""测试创作页面初始UI状态"""
<|body_0|>
def test_refresh(self):
"""测试下拉刷新"""
<|body_1|>
def test_swipe_vertical(self):
"""测试上下方向的滑动"""
<|body_2|>
def test_origin_home(self):
""... | stack_v2_sparse_classes_75kplus_train_072254 | 2,643 | no_license | [
{
"docstring": "测试创作页面初始UI状态",
"name": "test_origin",
"signature": "def test_origin()"
},
{
"docstring": "测试下拉刷新",
"name": "test_refresh",
"signature": "def test_refresh(self)"
},
{
"docstring": "测试上下方向的滑动",
"name": "test_swipe_vertical",
"signature": "def test_swipe_vert... | 4 | stack_v2_sparse_classes_30k_test_002021 | Implement the Python class `TestCreationUI` described below.
Class description:
创作页面的测试类,分步截图
Method signatures and docstrings:
- def test_origin(): 测试创作页面初始UI状态
- def test_refresh(self): 测试下拉刷新
- def test_swipe_vertical(self): 测试上下方向的滑动
- def test_origin_home(self): 测试创作页home tab的功能 | Implement the Python class `TestCreationUI` described below.
Class description:
创作页面的测试类,分步截图
Method signatures and docstrings:
- def test_origin(): 测试创作页面初始UI状态
- def test_refresh(self): 测试下拉刷新
- def test_swipe_vertical(self): 测试上下方向的滑动
- def test_origin_home(self): 测试创作页home tab的功能
<|skeleton|>
class TestCreationU... | b1190e3df62fa85562c14625c06a9794b8ce29a0 | <|skeleton|>
class TestCreationUI:
"""创作页面的测试类,分步截图"""
def test_origin():
"""测试创作页面初始UI状态"""
<|body_0|>
def test_refresh(self):
"""测试下拉刷新"""
<|body_1|>
def test_swipe_vertical(self):
"""测试上下方向的滑动"""
<|body_2|>
def test_origin_home(self):
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestCreationUI:
"""创作页面的测试类,分步截图"""
def test_origin():
"""测试创作页面初始UI状态"""
sc.logger.info(u'创作页面初始状态检查测试开始')
time.sleep(2)
el_home = sc.driver.find_element_by_id('com.quvideo.xiaoying:id/img_creation')
el_home.click()
time.sleep(0.5)
sc.capture_scree... | the_stack_v2_python_sparse | Android/VivaVideo/test_creations/test_ui.py | hicheng/UItest | train | 0 |
ecb87e24dc713f7467b42d098fd7bf717ef36a7f | [
"driver = instance.driver\nWebDriverWait(driver, 100).until(lambda driver: driver.find_element_by_name(self.locator))\ndriver.find_element_by_name(self.locator).send_keys(value)",
"driver = instance.driver\nWebDriverWait(driver, 100).until(lambda driver: driver.find_element_by_name(self.locator))\nelement = drive... | <|body_start_0|>
driver = instance.driver
WebDriverWait(driver, 100).until(lambda driver: driver.find_element_by_name(self.locator))
driver.find_element_by_name(self.locator).send_keys(value)
<|end_body_0|>
<|body_start_1|>
driver = instance.driver
WebDriverWait(driver, 100).unt... | Used for base page | BasePageElement | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasePageElement:
"""Used for base page"""
def __set__(self, instance, value):
"""sets text for element to be located"""
<|body_0|>
def __get__(self, instance, owner):
"""Get text out of element"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dri... | stack_v2_sparse_classes_75kplus_train_072255 | 764 | no_license | [
{
"docstring": "sets text for element to be located",
"name": "__set__",
"signature": "def __set__(self, instance, value)"
},
{
"docstring": "Get text out of element",
"name": "__get__",
"signature": "def __get__(self, instance, owner)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004334 | Implement the Python class `BasePageElement` described below.
Class description:
Used for base page
Method signatures and docstrings:
- def __set__(self, instance, value): sets text for element to be located
- def __get__(self, instance, owner): Get text out of element | Implement the Python class `BasePageElement` described below.
Class description:
Used for base page
Method signatures and docstrings:
- def __set__(self, instance, value): sets text for element to be located
- def __get__(self, instance, owner): Get text out of element
<|skeleton|>
class BasePageElement:
"""Used... | 4a0b3f6ef59ff49b36fd143cd867710619849bf4 | <|skeleton|>
class BasePageElement:
"""Used for base page"""
def __set__(self, instance, value):
"""sets text for element to be located"""
<|body_0|>
def __get__(self, instance, owner):
"""Get text out of element"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BasePageElement:
"""Used for base page"""
def __set__(self, instance, value):
"""sets text for element to be located"""
driver = instance.driver
WebDriverWait(driver, 100).until(lambda driver: driver.find_element_by_name(self.locator))
driver.find_element_by_name(self.loca... | the_stack_v2_python_sparse | PageObject/try1/element.py | smiroshnikov/telegramBotforMiningControl | train | 0 |
aa356e2c6acb117e9d5e7a6c04db18487a0ae17e | [
"_logger.debug('Initializing board')\nself.material = []\nself.piece_dictionary = dict()\nself.initialize_board()",
"self.material.append(piece_obj)\npiece_key = str(piece_obj.x) + str(piece_obj.y)\nself.piece_dictionary[piece_key] = piece_obj\n_logger.debug('Placed piece: %s' % piece_obj.name)",
"piece_identif... | <|body_start_0|>
_logger.debug('Initializing board')
self.material = []
self.piece_dictionary = dict()
self.initialize_board()
<|end_body_0|>
<|body_start_1|>
self.material.append(piece_obj)
piece_key = str(piece_obj.x) + str(piece_obj.y)
self.piece_dictionary[pi... | Board | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Board:
def __init__(self):
"""Material : A list of all piece objects on the board Piece_Dictionary : Every piece on the board has an entry in this dictionary (Eg: {"11" : Rook_obj} for a Rook at (1,1)"""
<|body_0|>
def place_piece(self, piece_obj):
"""Append the newl... | stack_v2_sparse_classes_75kplus_train_072256 | 4,259 | no_license | [
{
"docstring": "Material : A list of all piece objects on the board Piece_Dictionary : Every piece on the board has an entry in this dictionary (Eg: {\"11\" : Rook_obj} for a Rook at (1,1)",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Append the newly placed piece to... | 6 | stack_v2_sparse_classes_30k_train_032701 | Implement the Python class `Board` described below.
Class description:
Implement the Board class.
Method signatures and docstrings:
- def __init__(self): Material : A list of all piece objects on the board Piece_Dictionary : Every piece on the board has an entry in this dictionary (Eg: {"11" : Rook_obj} for a Rook at... | Implement the Python class `Board` described below.
Class description:
Implement the Board class.
Method signatures and docstrings:
- def __init__(self): Material : A list of all piece objects on the board Piece_Dictionary : Every piece on the board has an entry in this dictionary (Eg: {"11" : Rook_obj} for a Rook at... | d4e453c4dae322f5de8c0f967195e6b5b38cf6a2 | <|skeleton|>
class Board:
def __init__(self):
"""Material : A list of all piece objects on the board Piece_Dictionary : Every piece on the board has an entry in this dictionary (Eg: {"11" : Rook_obj} for a Rook at (1,1)"""
<|body_0|>
def place_piece(self, piece_obj):
"""Append the newl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Board:
def __init__(self):
"""Material : A list of all piece objects on the board Piece_Dictionary : Every piece on the board has an entry in this dictionary (Eg: {"11" : Rook_obj} for a Rook at (1,1)"""
_logger.debug('Initializing board')
self.material = []
self.piece_dictiona... | the_stack_v2_python_sparse | chadarangapu_aata/model/board.py | tesrohit/Chadarangapu-Aata | train | 0 | |
f7784ffbba91fe11d88ea8b6270d08e1a4d6b677 | [
"parent_folder = normcase(dirname(dirname(__file__)))\nnew_folder = cnf.get_values('PATHS', 'files_folder')\nfile_path = join(parent_folder, new_folder, file_name)\nreturn file_path",
"target_path = self.get_path(file_name)\nwith open(target_path, 'a+', encoding='utf-8') as target_file:\n target_file.seek(0)\n... | <|body_start_0|>
parent_folder = normcase(dirname(dirname(__file__)))
new_folder = cnf.get_values('PATHS', 'files_folder')
file_path = join(parent_folder, new_folder, file_name)
return file_path
<|end_body_0|>
<|body_start_1|>
target_path = self.get_path(file_name)
with ... | Files | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Files:
def get_path(self, file_name):
"""Generate path to /files directory. 'files' folder name is configurable"""
<|body_0|>
def append_file(self, text, file_name):
"""Open target file. If there are already records - add new section after 2 newlines, if no - add at ... | stack_v2_sparse_classes_75kplus_train_072257 | 977 | no_license | [
{
"docstring": "Generate path to /files directory. 'files' folder name is configurable",
"name": "get_path",
"signature": "def get_path(self, file_name)"
},
{
"docstring": "Open target file. If there are already records - add new section after 2 newlines, if no - add at the beginning of the file... | 2 | stack_v2_sparse_classes_30k_train_007553 | Implement the Python class `Files` described below.
Class description:
Implement the Files class.
Method signatures and docstrings:
- def get_path(self, file_name): Generate path to /files directory. 'files' folder name is configurable
- def append_file(self, text, file_name): Open target file. If there are already r... | Implement the Python class `Files` described below.
Class description:
Implement the Files class.
Method signatures and docstrings:
- def get_path(self, file_name): Generate path to /files directory. 'files' folder name is configurable
- def append_file(self, text, file_name): Open target file. If there are already r... | b0098854650c5dceb5b15203b3cfc79ab9f44fb2 | <|skeleton|>
class Files:
def get_path(self, file_name):
"""Generate path to /files directory. 'files' folder name is configurable"""
<|body_0|>
def append_file(self, text, file_name):
"""Open target file. If there are already records - add new section after 2 newlines, if no - add at ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Files:
def get_path(self, file_name):
"""Generate path to /files directory. 'files' folder name is configurable"""
parent_folder = normcase(dirname(dirname(__file__)))
new_folder = cnf.get_values('PATHS', 'files_folder')
file_path = join(parent_folder, new_folder, file_name)
... | the_stack_v2_python_sparse | Classes_Homework_5/modules/file.py | Nradionenko/DQE_Python_Homework | train | 0 | |
57d6d5e4d9eb53340f3ab34c8790f97805938378 | [
"query = query.replace('(', ' ( ')\nnormalized = query.replace(')', ' ) ')\nreturn normalized",
"if query.count('(') != query.count(')'):\n raise QueryException('Parentheses dont match')\nif query[0] in ['AND', 'OR', ')']:\n raise QueryException('Invalid First Term')\ni = 1\nwhile i < len(query):\n if ty... | <|body_start_0|>
query = query.replace('(', ' ( ')
normalized = query.replace(')', ' ) ')
return normalized
<|end_body_0|>
<|body_start_1|>
if query.count('(') != query.count(')'):
raise QueryException('Parentheses dont match')
if query[0] in ['AND', 'OR', ')']:
... | Manages parsing boolean query strings, and converting them to a postfix list. | QueryParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QueryParser:
"""Manages parsing boolean query strings, and converting them to a postfix list."""
def _normalize_query(self, query):
"""Normalizes the braces in the query to be padded with spaces. Allows easy splitting of the query."""
<|body_0|>
def _validate_query(self,... | stack_v2_sparse_classes_75kplus_train_072258 | 5,387 | no_license | [
{
"docstring": "Normalizes the braces in the query to be padded with spaces. Allows easy splitting of the query.",
"name": "_normalize_query",
"signature": "def _normalize_query(self, query)"
},
{
"docstring": "Validates the order and overall construction of the query :exception: QueryException ... | 5 | stack_v2_sparse_classes_30k_train_026309 | Implement the Python class `QueryParser` described below.
Class description:
Manages parsing boolean query strings, and converting them to a postfix list.
Method signatures and docstrings:
- def _normalize_query(self, query): Normalizes the braces in the query to be padded with spaces. Allows easy splitting of the qu... | Implement the Python class `QueryParser` described below.
Class description:
Manages parsing boolean query strings, and converting them to a postfix list.
Method signatures and docstrings:
- def _normalize_query(self, query): Normalizes the braces in the query to be padded with spaces. Allows easy splitting of the qu... | 54481dfd88637572b92b8e17ba6ef6458fade9a4 | <|skeleton|>
class QueryParser:
"""Manages parsing boolean query strings, and converting them to a postfix list."""
def _normalize_query(self, query):
"""Normalizes the braces in the query to be padded with spaces. Allows easy splitting of the query."""
<|body_0|>
def _validate_query(self,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QueryParser:
"""Manages parsing boolean query strings, and converting them to a postfix list."""
def _normalize_query(self, query):
"""Normalizes the braces in the query to be padded with spaces. Allows easy splitting of the query."""
query = query.replace('(', ' ( ')
normalized =... | the_stack_v2_python_sparse | web/bfex/components/search_engine/parser.py | MandyMeindersma/BFEX | train | 0 |
cba652c5afe1e908f94300846fa37995e7f21bd2 | [
"self._cpu = cpu.Cpu()\nself._memory_controller = memory.MemoryController()\nself._video_controller = video.VideoController()",
"print('System.power_on()')\nself._cpu.power_on()\nself._memory_controller.power_on()\nself._video_controller.power_on()"
] | <|body_start_0|>
self._cpu = cpu.Cpu()
self._memory_controller = memory.MemoryController()
self._video_controller = video.VideoController()
<|end_body_0|>
<|body_start_1|>
print('System.power_on()')
self._cpu.power_on()
self._memory_controller.power_on()
self._vi... | Represents a computer system. | System | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class System:
"""Represents a computer system."""
def __init__(self):
"""Creates and initializes the system components."""
<|body_0|>
def power_on(self):
"""Powers on the system components."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self._cpu = c... | stack_v2_sparse_classes_75kplus_train_072259 | 550 | permissive | [
{
"docstring": "Creates and initializes the system components.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Powers on the system components.",
"name": "power_on",
"signature": "def power_on(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_025265 | Implement the Python class `System` described below.
Class description:
Represents a computer system.
Method signatures and docstrings:
- def __init__(self): Creates and initializes the system components.
- def power_on(self): Powers on the system components. | Implement the Python class `System` described below.
Class description:
Represents a computer system.
Method signatures and docstrings:
- def __init__(self): Creates and initializes the system components.
- def power_on(self): Powers on the system components.
<|skeleton|>
class System:
"""Represents a computer s... | 2a54293181c1c2b1a2b840ddee4d4d80177efb33 | <|skeleton|>
class System:
"""Represents a computer system."""
def __init__(self):
"""Creates and initializes the system components."""
<|body_0|>
def power_on(self):
"""Powers on the system components."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class System:
"""Represents a computer system."""
def __init__(self):
"""Creates and initializes the system components."""
self._cpu = cpu.Cpu()
self._memory_controller = memory.MemoryController()
self._video_controller = video.VideoController()
def power_on(self):
... | the_stack_v2_python_sparse | data/train/python/79af5ca3359d7199f6a3221b325aafcefb287cbfsystem.py | harshp8l/deep-learning-lang-detection | train | 0 |
8daee1e138557af68be00d3b7b47fb34b57bf654 | [
"analysis = Analysis.objects.get(id=analysis_id)\nwith transaction.atomic():\n property_view_ids = set(property_view_ids)\n property_views = PropertyView.objects.filter(id__in=property_view_ids, property__organization_id=analysis.organization_id)\n missing_property_views = property_view_ids - set(property_... | <|body_start_0|>
analysis = Analysis.objects.get(id=analysis_id)
with transaction.atomic():
property_view_ids = set(property_view_ids)
property_views = PropertyView.objects.filter(id__in=property_view_ids, property__organization_id=analysis.organization_id)
missing_pr... | The AnalysisPropertyView provides a "snapshot" of a property at the time an analysis was run. | AnalysisPropertyView | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnalysisPropertyView:
"""The AnalysisPropertyView provides a "snapshot" of a property at the time an analysis was run."""
def batch_create(cls, analysis_id, property_view_ids):
"""Creates AnalysisPropertyViews from provided PropertyView IDs. The method returns a tuple, the first valu... | stack_v2_sparse_classes_75kplus_train_072260 | 5,119 | permissive | [
{
"docstring": "Creates AnalysisPropertyViews from provided PropertyView IDs. The method returns a tuple, the first value being a dictionary of the created AnalysisPropertyView IDs with the key as the original property_view_id, the second value being a list of BatchCreateErrors. Intended to be used when initial... | 2 | stack_v2_sparse_classes_30k_train_022772 | Implement the Python class `AnalysisPropertyView` described below.
Class description:
The AnalysisPropertyView provides a "snapshot" of a property at the time an analysis was run.
Method signatures and docstrings:
- def batch_create(cls, analysis_id, property_view_ids): Creates AnalysisPropertyViews from provided Pro... | Implement the Python class `AnalysisPropertyView` described below.
Class description:
The AnalysisPropertyView provides a "snapshot" of a property at the time an analysis was run.
Method signatures and docstrings:
- def batch_create(cls, analysis_id, property_view_ids): Creates AnalysisPropertyViews from provided Pro... | 680b6a2b45f3c568d779d8ac86553a0b08c384c8 | <|skeleton|>
class AnalysisPropertyView:
"""The AnalysisPropertyView provides a "snapshot" of a property at the time an analysis was run."""
def batch_create(cls, analysis_id, property_view_ids):
"""Creates AnalysisPropertyViews from provided PropertyView IDs. The method returns a tuple, the first valu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AnalysisPropertyView:
"""The AnalysisPropertyView provides a "snapshot" of a property at the time an analysis was run."""
def batch_create(cls, analysis_id, property_view_ids):
"""Creates AnalysisPropertyViews from provided PropertyView IDs. The method returns a tuple, the first value being a dic... | the_stack_v2_python_sparse | seed/models/analysis_property_views.py | SEED-platform/seed | train | 108 |
2e063e64cb40c8bb17694cfa47e4dd61338e6d70 | [
"self.name = name.lower()\nself.exp_value = exp_value.lower() if isinstance(exp_value, str) else str(exp_value).lower()\nself.column_index = column_index if isinstance(column_index, int) else -1\nself.truth_value = truth_value",
"if self.truth_value is not None:\n return self.truth_value\nelif self.column_inde... | <|body_start_0|>
self.name = name.lower()
self.exp_value = exp_value.lower() if isinstance(exp_value, str) else str(exp_value).lower()
self.column_index = column_index if isinstance(column_index, int) else -1
self.truth_value = truth_value
<|end_body_0|>
<|body_start_1|>
if self... | FeatureValue | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureValue:
def __init__(self, name: str, column_index, exp_value, truth_value: bool=None):
"""Initialises a new FeatureValue that plays the role of a boolean. It can either have a truth value or it can have a column index and expected value that will be used to determine its truth val... | stack_v2_sparse_classes_75kplus_train_072261 | 16,699 | no_license | [
{
"docstring": "Initialises a new FeatureValue that plays the role of a boolean. It can either have a truth value or it can have a column index and expected value that will be used to determine its truth value Parameters ---------- name : str the name of the FeatureValue column_index : int the index of the colu... | 2 | null | Implement the Python class `FeatureValue` described below.
Class description:
Implement the FeatureValue class.
Method signatures and docstrings:
- def __init__(self, name: str, column_index, exp_value, truth_value: bool=None): Initialises a new FeatureValue that plays the role of a boolean. It can either have a trut... | Implement the Python class `FeatureValue` described below.
Class description:
Implement the FeatureValue class.
Method signatures and docstrings:
- def __init__(self, name: str, column_index, exp_value, truth_value: bool=None): Initialises a new FeatureValue that plays the role of a boolean. It can either have a trut... | 152027e4be258f77cb082a5c5a3cc72013c93ca4 | <|skeleton|>
class FeatureValue:
def __init__(self, name: str, column_index, exp_value, truth_value: bool=None):
"""Initialises a new FeatureValue that plays the role of a boolean. It can either have a truth value or it can have a column index and expected value that will be used to determine its truth val... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FeatureValue:
def __init__(self, name: str, column_index, exp_value, truth_value: bool=None):
"""Initialises a new FeatureValue that plays the role of a boolean. It can either have a truth value or it can have a column index and expected value that will be used to determine its truth value Parameters ... | the_stack_v2_python_sparse | implication_classes.py | GuidoBekkers/textClassifier | train | 1 | |
1755ba81b0f11d4d4130ceff0b6418d46da612a9 | [
"import da.lwc.file\na_valid_unit_test = '/module/spec/spec_name.py'\nassert da.lwc.file.is_test_related(a_valid_unit_test) == True",
"import da.lwc.file\na_valid_module = '/module/name.py'\nassert da.lwc.file.is_test_related(a_valid_module) == False"
] | <|body_start_0|>
import da.lwc.file
a_valid_unit_test = '/module/spec/spec_name.py'
assert da.lwc.file.is_test_related(a_valid_unit_test) == True
<|end_body_0|>
<|body_start_1|>
import da.lwc.file
a_valid_module = '/module/name.py'
assert da.lwc.file.is_test_related(a_va... | Specify the is_test_related() function. | SpecifyIsTestRelated | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpecifyIsTestRelated:
"""Specify the is_test_related() function."""
def it_returns_true_when_given_a_valid_unit_test_path(self):
"""When given a valid test path, is_test_related() shall return True."""
<|body_0|>
def it_returns_false_when_given_a_valid_module_path(self):... | stack_v2_sparse_classes_75kplus_train_072262 | 16,001 | permissive | [
{
"docstring": "When given a valid test path, is_test_related() shall return True.",
"name": "it_returns_true_when_given_a_valid_unit_test_path",
"signature": "def it_returns_true_when_given_a_valid_unit_test_path(self)"
},
{
"docstring": "When given a valid module path, is_test_related() shall ... | 2 | null | Implement the Python class `SpecifyIsTestRelated` described below.
Class description:
Specify the is_test_related() function.
Method signatures and docstrings:
- def it_returns_true_when_given_a_valid_unit_test_path(self): When given a valid test path, is_test_related() shall return True.
- def it_returns_false_when_... | Implement the Python class `SpecifyIsTestRelated` described below.
Class description:
Specify the is_test_related() function.
Method signatures and docstrings:
- def it_returns_true_when_given_a_valid_unit_test_path(self): When given a valid test path, is_test_related() shall return True.
- def it_returns_false_when_... | 04a13be2792323e3f9fdb83fd236a8e9cfe6aa2d | <|skeleton|>
class SpecifyIsTestRelated:
"""Specify the is_test_related() function."""
def it_returns_true_when_given_a_valid_unit_test_path(self):
"""When given a valid test path, is_test_related() shall return True."""
<|body_0|>
def it_returns_false_when_given_a_valid_module_path(self):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpecifyIsTestRelated:
"""Specify the is_test_related() function."""
def it_returns_true_when_given_a_valid_unit_test_path(self):
"""When given a valid test path, is_test_related() shall return True."""
import da.lwc.file
a_valid_unit_test = '/module/spec/spec_name.py'
asse... | the_stack_v2_python_sparse | a3_src/h70_internal/da/lwc/spec/spec_file.py | wtpayne/hiai | train | 5 |
9cdd6124162806fe7bad4fe84331f279604903d2 | [
"if which_challenge not in ('singlecoil', 'multicoil'):\n raise ValueError(f'Challenge should either be \"singlecoil\" or \"multicoil\"')\nself.mask_func = mask_func\nself.resolution = resolution\nself.which_challenge = which_challenge\nself.use_seed = use_seed",
"kspace = T.to_tensor(kspace)\nif self.mask_fun... | <|body_start_0|>
if which_challenge not in ('singlecoil', 'multicoil'):
raise ValueError(f'Challenge should either be "singlecoil" or "multicoil"')
self.mask_func = mask_func
self.resolution = resolution
self.which_challenge = which_challenge
self.use_seed = use_seed
... | Data Transformer for training U-Net models. | DataTransform | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataTransform:
"""Data Transformer for training U-Net models."""
def __init__(self, resolution, which_challenge, mask_func=None, use_seed=True):
"""Args: mask_func (common.subsample.MaskFunc): A function that can create a mask of appropriate shape. resolution (int): Resolution of the... | stack_v2_sparse_classes_75kplus_train_072263 | 17,413 | no_license | [
{
"docstring": "Args: mask_func (common.subsample.MaskFunc): A function that can create a mask of appropriate shape. resolution (int): Resolution of the image. which_challenge (str): Either \"singlecoil\" or \"multicoil\" denoting the dataset. use_seed (bool): If true, this class computes a pseudo random number... | 2 | stack_v2_sparse_classes_30k_train_017779 | Implement the Python class `DataTransform` described below.
Class description:
Data Transformer for training U-Net models.
Method signatures and docstrings:
- def __init__(self, resolution, which_challenge, mask_func=None, use_seed=True): Args: mask_func (common.subsample.MaskFunc): A function that can create a mask ... | Implement the Python class `DataTransform` described below.
Class description:
Data Transformer for training U-Net models.
Method signatures and docstrings:
- def __init__(self, resolution, which_challenge, mask_func=None, use_seed=True): Args: mask_func (common.subsample.MaskFunc): A function that can create a mask ... | 219652c8a08c4f2f682acd9f95a4e1b3fd36b70b | <|skeleton|>
class DataTransform:
"""Data Transformer for training U-Net models."""
def __init__(self, resolution, which_challenge, mask_func=None, use_seed=True):
"""Args: mask_func (common.subsample.MaskFunc): A function that can create a mask of appropriate shape. resolution (int): Resolution of the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataTransform:
"""Data Transformer for training U-Net models."""
def __init__(self, resolution, which_challenge, mask_func=None, use_seed=True):
"""Args: mask_func (common.subsample.MaskFunc): A function that can create a mask of appropriate shape. resolution (int): Resolution of the image. which... | the_stack_v2_python_sparse | dc_rsn_fastmri/train.py | Bala93/Holistic-MRI-Reconstruction | train | 1 |
18a4b237e218500cd3e19f2e942ebf484e3037d4 | [
"self.min_dt = min_dt\nself.max_dt = max_dt\nself.mean_dt = loc_dt\nself.std_dt = scale_dt\nsuper(GaussianDt, self).__init__(discrete_values=discrete_values)",
"if batch_size is None and env_states is None:\n raise ValueError('env_states and batch_size cannot be both None.')\nbatch_size = batch_size or env_sta... | <|body_start_0|>
self.min_dt = min_dt
self.max_dt = max_dt
self.mean_dt = loc_dt
self.std_dt = scale_dt
super(GaussianDt, self).__init__(discrete_values=discrete_values)
<|end_body_0|>
<|body_start_1|>
if batch_size is None and env_states is None:
raise Value... | Sample an additional vector of clipped gaussian random variables, and stores it in an attribute called `dt`. | GaussianDt | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianDt:
"""Sample an additional vector of clipped gaussian random variables, and stores it in an attribute called `dt`."""
def __init__(self, min_dt: float=1.0, max_dt: float=1.0, loc_dt: float=0.0, scale_dt: float=1.0, discrete_values: bool=False):
"""Initialize a :class:`Gaussi... | stack_v2_sparse_classes_75kplus_train_072264 | 8,063 | permissive | [
{
"docstring": "Initialize a :class:`GaussianDt`. Args: min_dt: Minimum dt that will be predicted by the model. max_dt: Maximum dt that will be predicted by the model. loc_dt: Mean of the gaussian random variable that will model dt. scale_dt: Standard deviation of the gaussian random variable that will model dt... | 2 | stack_v2_sparse_classes_30k_train_052872 | Implement the Python class `GaussianDt` described below.
Class description:
Sample an additional vector of clipped gaussian random variables, and stores it in an attribute called `dt`.
Method signatures and docstrings:
- def __init__(self, min_dt: float=1.0, max_dt: float=1.0, loc_dt: float=0.0, scale_dt: float=1.0, ... | Implement the Python class `GaussianDt` described below.
Class description:
Sample an additional vector of clipped gaussian random variables, and stores it in an attribute called `dt`.
Method signatures and docstrings:
- def __init__(self, min_dt: float=1.0, max_dt: float=1.0, loc_dt: float=0.0, scale_dt: float=1.0, ... | 5e69c50e5b220859d65406d803086406b50a8e78 | <|skeleton|>
class GaussianDt:
"""Sample an additional vector of clipped gaussian random variables, and stores it in an attribute called `dt`."""
def __init__(self, min_dt: float=1.0, max_dt: float=1.0, loc_dt: float=0.0, scale_dt: float=1.0, discrete_values: bool=False):
"""Initialize a :class:`Gaussi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GaussianDt:
"""Sample an additional vector of clipped gaussian random variables, and stores it in an attribute called `dt`."""
def __init__(self, min_dt: float=1.0, max_dt: float=1.0, loc_dt: float=0.0, scale_dt: float=1.0, discrete_values: bool=False):
"""Initialize a :class:`GaussianDt`. Args: ... | the_stack_v2_python_sparse | fragile/core/dt_samplers.py | sergio-hcsoft/fragile-1 | train | 0 |
72a3f7fa0e9fbefeb143cb4a4b02caceceb0833c | [
"if not postorder:\n return None\nval = postorder[-1]\nindex = inorder.index(val)\nleft_inorder = inorder[:index]\nright_inorder = inorder[index + 1:]\nleft_postorder = postorder[0:len(left_inorder)]\nright_postorder = postorder[len(left_inorder):-1]\nnode = TreeNode(val)\nnode.left = self.buildTree(left_inorder... | <|body_start_0|>
if not postorder:
return None
val = postorder[-1]
index = inorder.index(val)
left_inorder = inorder[:index]
right_inorder = inorder[index + 1:]
left_postorder = postorder[0:len(left_inorder)]
right_postorder = postorder[len(left_inorde... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def buildTree(self, inorder, postorder):
"""根据中序遍历和后序遍历,构造二叉树 :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode"""
<|body_0|>
def buildTree2(self, inorder, postorder):
"""根据中序遍历和后序遍历,构造二叉树 :type preorder: List[int] :type inorder: List[int]... | stack_v2_sparse_classes_75kplus_train_072265 | 2,465 | no_license | [
{
"docstring": "根据中序遍历和后序遍历,构造二叉树 :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode",
"name": "buildTree",
"signature": "def buildTree(self, inorder, postorder)"
},
{
"docstring": "根据中序遍历和后序遍历,构造二叉树 :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode",
"name... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def buildTree(self, inorder, postorder): 根据中序遍历和后序遍历,构造二叉树 :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode
- def buildTree2(self, inorder, postorder): 根据中序遍历和... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def buildTree(self, inorder, postorder): 根据中序遍历和后序遍历,构造二叉树 :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode
- def buildTree2(self, inorder, postorder): 根据中序遍历和... | 04d87d76b762f6ea7cfb3a453382b2d7d4e154dc | <|skeleton|>
class Solution:
def buildTree(self, inorder, postorder):
"""根据中序遍历和后序遍历,构造二叉树 :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode"""
<|body_0|>
def buildTree2(self, inorder, postorder):
"""根据中序遍历和后序遍历,构造二叉树 :type preorder: List[int] :type inorder: List[int]... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def buildTree(self, inorder, postorder):
"""根据中序遍历和后序遍历,构造二叉树 :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode"""
if not postorder:
return None
val = postorder[-1]
index = inorder.index(val)
left_inorder = inorder[:index]
... | the_stack_v2_python_sparse | leetcode/106 Construct Binary Tree from Inorder and Postorder Traversal.py | mofei952/algorithm_exercise | train | 1 | |
9edc7a4053adec1689281234b00ae6416d57e5cf | [
"if user_id:\n session_id = super().create_session(user_id)\n if not session_id:\n return\n new_user = UserSession(user_id=user_id, session_id=session_id)\n new_user.save()\n return session_id",
"if not session_id:\n return\ntry:\n us_list = UserSession.search({session_id: session_id})... | <|body_start_0|>
if user_id:
session_id = super().create_session(user_id)
if not session_id:
return
new_user = UserSession(user_id=user_id, session_id=session_id)
new_user.save()
return session_id
<|end_body_0|>
<|body_start_1|>
... | SessionDBAuth class. | SessionDBAuth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionDBAuth:
"""SessionDBAuth class."""
def create_session(self, user_id=None):
"""create_session."""
<|body_0|>
def user_id_for_session_id(self, session_id=None):
"""user_id_for_session_id."""
<|body_1|>
def destroy_session(self, request=None) -> ... | stack_v2_sparse_classes_75kplus_train_072266 | 1,857 | no_license | [
{
"docstring": "create_session.",
"name": "create_session",
"signature": "def create_session(self, user_id=None)"
},
{
"docstring": "user_id_for_session_id.",
"name": "user_id_for_session_id",
"signature": "def user_id_for_session_id(self, session_id=None)"
},
{
"docstring": "des... | 3 | stack_v2_sparse_classes_30k_train_040779 | Implement the Python class `SessionDBAuth` described below.
Class description:
SessionDBAuth class.
Method signatures and docstrings:
- def create_session(self, user_id=None): create_session.
- def user_id_for_session_id(self, session_id=None): user_id_for_session_id.
- def destroy_session(self, request=None) -> bool... | Implement the Python class `SessionDBAuth` described below.
Class description:
SessionDBAuth class.
Method signatures and docstrings:
- def create_session(self, user_id=None): create_session.
- def user_id_for_session_id(self, session_id=None): user_id_for_session_id.
- def destroy_session(self, request=None) -> bool... | baeba1aaf9919c22c11fad80884cde4532a61bed | <|skeleton|>
class SessionDBAuth:
"""SessionDBAuth class."""
def create_session(self, user_id=None):
"""create_session."""
<|body_0|>
def user_id_for_session_id(self, session_id=None):
"""user_id_for_session_id."""
<|body_1|>
def destroy_session(self, request=None) -> ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SessionDBAuth:
"""SessionDBAuth class."""
def create_session(self, user_id=None):
"""create_session."""
if user_id:
session_id = super().create_session(user_id)
if not session_id:
return
new_user = UserSession(user_id=user_id, session_id... | the_stack_v2_python_sparse | 0x07-Session_authentication/api/v1/auth/session_db_auth.py | vik407/holbertonschool-web_back_end | train | 2 |
a4d1cd96ef6f289a26fd456306c6001617b3d5b8 | [
"logger.debug('self=%s model=%s' % (self, model.__dict__))\nif settings.DATABASE_APPS_MAPPING.has_key(model._meta.app_label):\n return settings.DATABASE_APPS_MAPPING[model._meta.app_label]\nreturn None",
"logger.debug('self=%s model=%s' % (self, model.__dict__))\nif settings.DATABASE_APPS_MAPPING.has_key(model... | <|body_start_0|>
logger.debug('self=%s model=%s' % (self, model.__dict__))
if settings.DATABASE_APPS_MAPPING.has_key(model._meta.app_label):
return settings.DATABASE_APPS_MAPPING[model._meta.app_label]
return None
<|end_body_0|>
<|body_start_1|>
logger.debug('self=%s model=%... | A router to control all database operations on models for different databases. In case an app is not set in settings.DATABASE_APPS_MAPPING, the router will fallback to the `default` database. Settings example: DATABASE_APPS_MAPPING = {'app1': 'db1', 'app2': 'db2'} | DatabaseAppsRouter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatabaseAppsRouter:
"""A router to control all database operations on models for different databases. In case an app is not set in settings.DATABASE_APPS_MAPPING, the router will fallback to the `default` database. Settings example: DATABASE_APPS_MAPPING = {'app1': 'db1', 'app2': 'db2'}"""
d... | stack_v2_sparse_classes_75kplus_train_072267 | 2,349 | no_license | [
{
"docstring": "\"Point all read operations to the specific database.",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "Point all write operations to the specific database.",
"name": "db_for_write",
"signature": "def db_for_write(self, model... | 4 | stack_v2_sparse_classes_30k_train_008600 | Implement the Python class `DatabaseAppsRouter` described below.
Class description:
A router to control all database operations on models for different databases. In case an app is not set in settings.DATABASE_APPS_MAPPING, the router will fallback to the `default` database. Settings example: DATABASE_APPS_MAPPING = {... | Implement the Python class `DatabaseAppsRouter` described below.
Class description:
A router to control all database operations on models for different databases. In case an app is not set in settings.DATABASE_APPS_MAPPING, the router will fallback to the `default` database. Settings example: DATABASE_APPS_MAPPING = {... | fd37868fa3c502e4d228090c21aac14865657aa1 | <|skeleton|>
class DatabaseAppsRouter:
"""A router to control all database operations on models for different databases. In case an app is not set in settings.DATABASE_APPS_MAPPING, the router will fallback to the `default` database. Settings example: DATABASE_APPS_MAPPING = {'app1': 'db1', 'app2': 'db2'}"""
d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DatabaseAppsRouter:
"""A router to control all database operations on models for different databases. In case an app is not set in settings.DATABASE_APPS_MAPPING, the router will fallback to the `default` database. Settings example: DATABASE_APPS_MAPPING = {'app1': 'db1', 'app2': 'db2'}"""
def db_for_rea... | the_stack_v2_python_sparse | runner/router.py | tonyPayetDev/resellingsaiyan | train | 0 |
ed61f5989a0edcd2f04cd026399000562531b2e1 | [
"self.number = number\nself.expected_max_verse_number = expected_max_verse_number\nself.missing_verses = []\nself.found = False\nself.usfm = ''",
"previous_line = ''\nnewlines = ['\\n\\\\s5']\ni = 0\nfor line in self.usfm.splitlines():\n if line in ['', ' ', '\\n']:\n continue\n if i < len(chunks):\n... | <|body_start_0|>
self.number = number
self.expected_max_verse_number = expected_max_verse_number
self.missing_verses = []
self.found = False
self.usfm = ''
<|end_body_0|>
<|body_start_1|>
previous_line = ''
newlines = ['\n\\s5']
i = 0
for line in ... | Chapter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Chapter:
def __init__(self, number, expected_max_verse_number):
""":type number: int :type expected_max_verse_number: int"""
<|body_0|>
def apply_chunks(self, chunks):
""":type chunks: list<Chunk>"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self... | stack_v2_sparse_classes_75kplus_train_072268 | 17,137 | permissive | [
{
"docstring": ":type number: int :type expected_max_verse_number: int",
"name": "__init__",
"signature": "def __init__(self, number, expected_max_verse_number)"
},
{
"docstring": ":type chunks: list<Chunk>",
"name": "apply_chunks",
"signature": "def apply_chunks(self, chunks)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020836 | Implement the Python class `Chapter` described below.
Class description:
Implement the Chapter class.
Method signatures and docstrings:
- def __init__(self, number, expected_max_verse_number): :type number: int :type expected_max_verse_number: int
- def apply_chunks(self, chunks): :type chunks: list<Chunk> | Implement the Python class `Chapter` described below.
Class description:
Implement the Chapter class.
Method signatures and docstrings:
- def __init__(self, number, expected_max_verse_number): :type number: int :type expected_max_verse_number: int
- def apply_chunks(self, chunks): :type chunks: list<Chunk>
<|skeleto... | 70482b5e50282097af7a7cb96aebd2b23759a5d2 | <|skeleton|>
class Chapter:
def __init__(self, number, expected_max_verse_number):
""":type number: int :type expected_max_verse_number: int"""
<|body_0|>
def apply_chunks(self, chunks):
""":type chunks: list<Chunk>"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Chapter:
def __init__(self, number, expected_max_verse_number):
""":type number: int :type expected_max_verse_number: int"""
self.number = number
self.expected_max_verse_number = expected_max_verse_number
self.missing_verses = []
self.found = False
self.usfm = '... | the_stack_v2_python_sparse | app_code/bible/content.py | unfoldingWord-dev/uw-publish | train | 0 | |
94673a8584459328362a2ca33e1a09bd1b08fbb2 | [
"N = len(height)\nsol = [-1] * N\nst = []\nst_idx = []\nif is_prev == True:\n R = range(N - 1, 0 - 1, -1)\nelse:\n R = range(0, N)\nfor i in R:\n t = height[i]\n if len(st) == 0:\n pass\n elif t < st[-1]:\n sol[i] = st_idx[-1]\n elif t >= st[-1]:\n while t >= st[-1]:\n ... | <|body_start_0|>
N = len(height)
sol = [-1] * N
st = []
st_idx = []
if is_prev == True:
R = range(N - 1, 0 - 1, -1)
else:
R = range(0, N)
for i in R:
t = height[i]
if len(st) == 0:
pass
el... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nextB(self, height, is_prev):
"""Returns index of the next big element if is_prev == False then it returns the indexes of the previous big element"""
<|body_0|>
def trap(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus_train_072269 | 5,262 | no_license | [
{
"docstring": "Returns index of the next big element if is_prev == False then it returns the indexes of the previous big element",
"name": "nextB",
"signature": "def nextB(self, height, is_prev)"
},
{
"docstring": ":type height: List[int] :rtype: int",
"name": "trap",
"signature": "def ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextB(self, height, is_prev): Returns index of the next big element if is_prev == False then it returns the indexes of the previous big element
- def trap(self, height): :typ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextB(self, height, is_prev): Returns index of the next big element if is_prev == False then it returns the indexes of the previous big element
- def trap(self, height): :typ... | f4ac2609f8809ee543074a11dafc08726046f6a2 | <|skeleton|>
class Solution:
def nextB(self, height, is_prev):
"""Returns index of the next big element if is_prev == False then it returns the indexes of the previous big element"""
<|body_0|>
def trap(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def nextB(self, height, is_prev):
"""Returns index of the next big element if is_prev == False then it returns the indexes of the previous big element"""
N = len(height)
sol = [-1] * N
st = []
st_idx = []
if is_prev == True:
R = range(N - 1... | the_stack_v2_python_sparse | LeetCode/42_trapping-rain-water.py | curiousTauseef/Algorithms_and_solutions | train | 0 | |
6dc3727bf910fb13f4cab62cb2914ff8917b3932 | [
"s = specialmanage(self.driver)\ns.open_specialmanage()\nself.assertEqual(s.verify(), True)\ns.delete_obj()\nself.assertEqual(s.result(), '您确定要删除这条信息吗')\ns.confirm()\nself.assertEqual(s.result(), '删除成功')\nfunction.screenshot(self.driver, 'delete_special.jpg')",
"s = specialmanage(self.driver)\ns.open_specialmanag... | <|body_start_0|>
s = specialmanage(self.driver)
s.open_specialmanage()
self.assertEqual(s.verify(), True)
s.delete_obj()
self.assertEqual(s.result(), '您确定要删除这条信息吗')
s.confirm()
self.assertEqual(s.result(), '删除成功')
function.screenshot(self.driver, 'delete_s... | Test042_Special_Delete_P1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test042_Special_Delete_P1:
def test_special_delete(self):
"""删除专业"""
<|body_0|>
def test_special_delete_cancle(self):
"""取消删除专业"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
s = specialmanage(self.driver)
s.open_specialmanage()
sel... | stack_v2_sparse_classes_75kplus_train_072270 | 1,113 | no_license | [
{
"docstring": "删除专业",
"name": "test_special_delete",
"signature": "def test_special_delete(self)"
},
{
"docstring": "取消删除专业",
"name": "test_special_delete_cancle",
"signature": "def test_special_delete_cancle(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007367 | Implement the Python class `Test042_Special_Delete_P1` described below.
Class description:
Implement the Test042_Special_Delete_P1 class.
Method signatures and docstrings:
- def test_special_delete(self): 删除专业
- def test_special_delete_cancle(self): 取消删除专业 | Implement the Python class `Test042_Special_Delete_P1` described below.
Class description:
Implement the Test042_Special_Delete_P1 class.
Method signatures and docstrings:
- def test_special_delete(self): 删除专业
- def test_special_delete_cancle(self): 取消删除专业
<|skeleton|>
class Test042_Special_Delete_P1:
def test_... | 6f42c25249fc642cecc270578a180820988d45b5 | <|skeleton|>
class Test042_Special_Delete_P1:
def test_special_delete(self):
"""删除专业"""
<|body_0|>
def test_special_delete_cancle(self):
"""取消删除专业"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test042_Special_Delete_P1:
def test_special_delete(self):
"""删除专业"""
s = specialmanage(self.driver)
s.open_specialmanage()
self.assertEqual(s.verify(), True)
s.delete_obj()
self.assertEqual(s.result(), '您确定要删除这条信息吗')
s.confirm()
self.assertEqual(... | the_stack_v2_python_sparse | GlxssLive_web/TestCase/Manage_Special/Test042_special_delete_P1.py | rrmiracle/GlxssLive | train | 0 | |
cc7bed8a5e31083fb096ecfe0756ec08afa34d0a | [
"super(EmonHubEmoncmsReporter, self).__init__(reporterName, queue, **kwargs)\nself._defaults.update({'batchsize': 100})\nself._cms_settings = {'apikey': '', 'url': 'http://emoncms.org'}\nself._settings.update(self._defaults)\nself._item_limit = 250",
"super(EmonHubEmoncmsReporter, self).set(**kwargs)\nfor key, se... | <|body_start_0|>
super(EmonHubEmoncmsReporter, self).__init__(reporterName, queue, **kwargs)
self._defaults.update({'batchsize': 100})
self._cms_settings = {'apikey': '', 'url': 'http://emoncms.org'}
self._settings.update(self._defaults)
self._item_limit = 250
<|end_body_0|>
<|b... | EmonHubEmoncmsReporter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmonHubEmoncmsReporter:
def __init__(self, reporterName, queue, **kwargs):
"""Initialize reporter"""
<|body_0|>
def set(self, **kwargs):
""":param kwargs: :return:"""
<|body_1|>
def _process_post(self, databuffer):
"""Send data to server."""
... | stack_v2_sparse_classes_75kplus_train_072271 | 12,930 | permissive | [
{
"docstring": "Initialize reporter",
"name": "__init__",
"signature": "def __init__(self, reporterName, queue, **kwargs)"
},
{
"docstring": ":param kwargs: :return:",
"name": "set",
"signature": "def set(self, **kwargs)"
},
{
"docstring": "Send data to server.",
"name": "_pr... | 3 | null | Implement the Python class `EmonHubEmoncmsReporter` described below.
Class description:
Implement the EmonHubEmoncmsReporter class.
Method signatures and docstrings:
- def __init__(self, reporterName, queue, **kwargs): Initialize reporter
- def set(self, **kwargs): :param kwargs: :return:
- def _process_post(self, da... | Implement the Python class `EmonHubEmoncmsReporter` described below.
Class description:
Implement the EmonHubEmoncmsReporter class.
Method signatures and docstrings:
- def __init__(self, reporterName, queue, **kwargs): Initialize reporter
- def set(self, **kwargs): :param kwargs: :return:
- def _process_post(self, da... | 7176b1066c2d38bf8c6c169584c38175b26d5401 | <|skeleton|>
class EmonHubEmoncmsReporter:
def __init__(self, reporterName, queue, **kwargs):
"""Initialize reporter"""
<|body_0|>
def set(self, **kwargs):
""":param kwargs: :return:"""
<|body_1|>
def _process_post(self, databuffer):
"""Send data to server."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EmonHubEmoncmsReporter:
def __init__(self, reporterName, queue, **kwargs):
"""Initialize reporter"""
super(EmonHubEmoncmsReporter, self).__init__(reporterName, queue, **kwargs)
self._defaults.update({'batchsize': 100})
self._cms_settings = {'apikey': '', 'url': 'http://emoncms.... | the_stack_v2_python_sparse | hub/emonhub/src/emonhub_reporter.py | horizon-institute/chariot | train | 1 | |
578dad0d3bbc3201b35b7afda42aec3fd9617fca | [
"self.geodb_client = geodb_client\nself.geodb_db = geodb_db\nself.geodb_collection = geodb_collection\nself.geodb_kwargs = kwargs\nself._dataset_crs: CRS | None = None\nsuper().__init__(feature=feature, reproject=reproject, clip=clip)",
"if self._dataset_crs is None:\n srid = self.geodb_client.get_collection_s... | <|body_start_0|>
self.geodb_client = geodb_client
self.geodb_db = geodb_db
self.geodb_collection = geodb_collection
self.geodb_kwargs = kwargs
self._dataset_crs: CRS | None = None
super().__init__(feature=feature, reproject=reproject, clip=clip)
<|end_body_0|>
<|body_sta... | A task for importing vector data from `geoDB <https://eurodatacube.com/marketplace/services/edc_geodb>`__ into EOPatch | GeoDBVectorImportTask | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeoDBVectorImportTask:
"""A task for importing vector data from `geoDB <https://eurodatacube.com/marketplace/services/edc_geodb>`__ into EOPatch"""
def __init__(self, feature: FeatureSpec, geodb_client: Any, geodb_collection: str, geodb_db: str, reproject: bool=True, clip: bool=False, **kwar... | stack_v2_sparse_classes_75kplus_train_072272 | 3,023 | permissive | [
{
"docstring": ":param feature: A vector feature into which to import data :param geodb_client: an instance of GeoDBClient :param geodb_collection: The name of the collection to be queried :param geodb_db: The name of the database the collection resides in [current database] :param reproject: Should the geometr... | 3 | null | Implement the Python class `GeoDBVectorImportTask` described below.
Class description:
A task for importing vector data from `geoDB <https://eurodatacube.com/marketplace/services/edc_geodb>`__ into EOPatch
Method signatures and docstrings:
- def __init__(self, feature: FeatureSpec, geodb_client: Any, geodb_collection... | Implement the Python class `GeoDBVectorImportTask` described below.
Class description:
A task for importing vector data from `geoDB <https://eurodatacube.com/marketplace/services/edc_geodb>`__ into EOPatch
Method signatures and docstrings:
- def __init__(self, feature: FeatureSpec, geodb_client: Any, geodb_collection... | a65899e4632b50c9c41a67e1f7698c09b929d840 | <|skeleton|>
class GeoDBVectorImportTask:
"""A task for importing vector data from `geoDB <https://eurodatacube.com/marketplace/services/edc_geodb>`__ into EOPatch"""
def __init__(self, feature: FeatureSpec, geodb_client: Any, geodb_collection: str, geodb_db: str, reproject: bool=True, clip: bool=False, **kwar... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GeoDBVectorImportTask:
"""A task for importing vector data from `geoDB <https://eurodatacube.com/marketplace/services/edc_geodb>`__ into EOPatch"""
def __init__(self, feature: FeatureSpec, geodb_client: Any, geodb_collection: str, geodb_db: str, reproject: bool=True, clip: bool=False, **kwargs: Any):
... | the_stack_v2_python_sparse | io/eolearn/io/extra/geodb.py | sentinel-hub/eo-learn | train | 1,072 |
fff985ceb4be7bf4784fa2e30d259e1ebc272ec3 | [
"self.pprint = lambda x: json.dumps(x, indent=4, sort_keys=True, default=str, ensure_ascii=False)\nself.lxml_response_parser = lambda xml_obj: jxmlease.parse_etree(xml_obj)\nself.jxmlease_response_to_dict = lambda xml_obj: json.loads(self.pprint(xml_obj))\nself.lxml_response_to_dict = lambda xml_obj: eval(self.ppri... | <|body_start_0|>
self.pprint = lambda x: json.dumps(x, indent=4, sort_keys=True, default=str, ensure_ascii=False)
self.lxml_response_parser = lambda xml_obj: jxmlease.parse_etree(xml_obj)
self.jxmlease_response_to_dict = lambda xml_obj: json.loads(self.pprint(xml_obj))
self.lxml_response... | XML related methods | xml_tool | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class xml_tool:
"""XML related methods"""
def __init__(self):
"""INIT"""
<|body_0|>
def xml_to_pure_dict(self, xml_structure, **kwargs):
"""Transit XML structure to pure python DICT whatever it is from jxml, jxmlease or xml string :param BOOL pprint: *OPTIONAL* pretty ... | stack_v2_sparse_classes_75kplus_train_072273 | 3,144 | no_license | [
{
"docstring": "INIT",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Transit XML structure to pure python DICT whatever it is from jxml, jxmlease or xml string :param BOOL pprint: *OPTIONAL* pretty print DICT to stdout. default: False :return: DICT contain xml structur... | 3 | null | Implement the Python class `xml_tool` described below.
Class description:
XML related methods
Method signatures and docstrings:
- def __init__(self): INIT
- def xml_to_pure_dict(self, xml_structure, **kwargs): Transit XML structure to pure python DICT whatever it is from jxml, jxmlease or xml string :param BOOL pprin... | Implement the Python class `xml_tool` described below.
Class description:
XML related methods
Method signatures and docstrings:
- def __init__(self): INIT
- def xml_to_pure_dict(self, xml_structure, **kwargs): Transit XML structure to pure python DICT whatever it is from jxml, jxmlease or xml string :param BOOL pprin... | 3966c63d48557b0b94303896eed7a767593a4832 | <|skeleton|>
class xml_tool:
"""XML related methods"""
def __init__(self):
"""INIT"""
<|body_0|>
def xml_to_pure_dict(self, xml_structure, **kwargs):
"""Transit XML structure to pure python DICT whatever it is from jxml, jxmlease or xml string :param BOOL pprint: *OPTIONAL* pretty ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class xml_tool:
"""XML related methods"""
def __init__(self):
"""INIT"""
self.pprint = lambda x: json.dumps(x, indent=4, sort_keys=True, default=str, ensure_ascii=False)
self.lxml_response_parser = lambda xml_obj: jxmlease.parse_etree(xml_obj)
self.jxmlease_response_to_dict = la... | the_stack_v2_python_sparse | NITA/lib/jnpr/toby/utils/xml_tool.py | fengyun4623/file | train | 0 |
fe418098dead5b83336d00fe93e645aca3e7ee34 | [
"super().__init__()\nself.base = base\nassert isinstance(self.base, ValueFunctionBase)\nself.outputs = namedtuple('Outputs', ['value', 'state_out'])",
"outs = self.base(ob) if state_in is None else self.base(ob, state_in)\nif isinstance(outs, tuple):\n value, state_out = outs\nelse:\n value, state_out = (ou... | <|body_start_0|>
super().__init__()
self.base = base
assert isinstance(self.base, ValueFunctionBase)
self.outputs = namedtuple('Outputs', ['value', 'state_out'])
<|end_body_0|>
<|body_start_1|>
outs = self.base(ob) if state_in is None else self.base(ob, state_in)
if isin... | Value function module. | ValueFunction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValueFunction:
"""Value function module."""
def __init__(self, base):
"""Init."""
<|body_0|>
def forward(self, ob, state_in=None):
"""Forward."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__()
self.base = base
as... | stack_v2_sparse_classes_75kplus_train_072274 | 1,416 | no_license | [
{
"docstring": "Init.",
"name": "__init__",
"signature": "def __init__(self, base)"
},
{
"docstring": "Forward.",
"name": "forward",
"signature": "def forward(self, ob, state_in=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_053368 | Implement the Python class `ValueFunction` described below.
Class description:
Value function module.
Method signatures and docstrings:
- def __init__(self, base): Init.
- def forward(self, ob, state_in=None): Forward. | Implement the Python class `ValueFunction` described below.
Class description:
Value function module.
Method signatures and docstrings:
- def __init__(self, base): Init.
- def forward(self, ob, state_in=None): Forward.
<|skeleton|>
class ValueFunction:
"""Value function module."""
def __init__(self, base):
... | e71c4b12955b01bfb907aa31c91ded6bcd8aaec8 | <|skeleton|>
class ValueFunction:
"""Value function module."""
def __init__(self, base):
"""Init."""
<|body_0|>
def forward(self, ob, state_in=None):
"""Forward."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ValueFunction:
"""Value function module."""
def __init__(self, base):
"""Init."""
super().__init__()
self.base = base
assert isinstance(self.base, ValueFunctionBase)
self.outputs = namedtuple('Outputs', ['value', 'state_out'])
def forward(self, ob, state_in=No... | the_stack_v2_python_sparse | dl/rl/modules/value_function.py | cbschaff/dl | train | 1 |
d49930de02a0c7ea332a6527730a6d78c60342f7 | [
"self.start = start\nself.goal = goal\nself.grid = grid\nself.best = Node(start)\nself.best.g = 0\nself.best.f = 0\nself.closed = closed.copy()\nself.opened = Opened()\nself.opened.load(opened)\nif self.opened.is_empty():\n self.opened.push(self.best)\nself._run()",
"node = self.best\nif not node:\n return ... | <|body_start_0|>
self.start = start
self.goal = goal
self.grid = grid
self.best = Node(start)
self.best.g = 0
self.best.f = 0
self.closed = closed.copy()
self.opened = Opened()
self.opened.load(opened)
if self.opened.is_empty():
... | ============================================================================ Description: AStar ============================================================================ | AStarH | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AStarH:
"""============================================================================ Description: AStar ============================================================================"""
def __init__(self, grid, start, goal, opened=set(), closed=set()):
"""===========================... | stack_v2_sparse_classes_75kplus_train_072275 | 6,232 | no_license | [
{
"docstring": "=================================================================== Description: A* Algorithm. =================================================================== Arguments: ------------------------------------------------------------------- 1. grid : Grid. 2. start : int (Start's Id). 3. goal :... | 5 | stack_v2_sparse_classes_30k_train_027707 | Implement the Python class `AStarH` described below.
Class description:
============================================================================ Description: AStar ============================================================================
Method signatures and docstrings:
- def __init__(self, grid, start, goal,... | Implement the Python class `AStarH` described below.
Class description:
============================================================================ Description: AStar ============================================================================
Method signatures and docstrings:
- def __init__(self, grid, start, goal,... | ef4d6218bc48d3c988f287187e6e3feec05d88cd | <|skeleton|>
class AStarH:
"""============================================================================ Description: AStar ============================================================================"""
def __init__(self, grid, start, goal, opened=set(), closed=set()):
"""===========================... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AStarH:
"""============================================================================ Description: AStar ============================================================================"""
def __init__(self, grid, start, goal, opened=set(), closed=set()):
"""========================================... | the_stack_v2_python_sparse | f_astar/c_astar_h.py | valdas1966/old | train | 0 |
cbeccddb5d6c8d11f1e7abc36756e6213413386c | [
"self.first_register = False\ndecorator_name = ''.join(('@', Implement.__name__.lower()))\nself.decorator_name = decorator_name\nself.args = args\nself.kwargs = kwargs\nself.scope = CONTEXT.in_pycompss()\nself.core_element = None\nself.core_element_configured = False\nif self.scope:\n check_arguments(MANDATORY_A... | <|body_start_0|>
self.first_register = False
decorator_name = ''.join(('@', Implement.__name__.lower()))
self.decorator_name = decorator_name
self.args = args
self.kwargs = kwargs
self.scope = CONTEXT.in_pycompss()
self.core_element = None
self.core_elemen... | Implement decorator class. This decorator also preserves the argspec, but includes the __init__ and __call__ methods, useful on implementation task creation. | Implement | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Implement:
"""Implement decorator class. This decorator also preserves the argspec, but includes the __init__ and __call__ methods, useful on implementation task creation."""
def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:
"""Store arguments passed to the decorat... | stack_v2_sparse_classes_75kplus_train_072276 | 6,895 | permissive | [
{
"docstring": "Store arguments passed to the decorator. self = itself. args = not used. kwargs = dictionary with the given implement parameters. :param args: Arguments. :param kwargs: Keyword arguments.",
"name": "__init__",
"signature": "def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> N... | 3 | stack_v2_sparse_classes_30k_test_000090 | Implement the Python class `Implement` described below.
Class description:
Implement decorator class. This decorator also preserves the argspec, but includes the __init__ and __call__ methods, useful on implementation task creation.
Method signatures and docstrings:
- def __init__(self, *args: typing.Any, **kwargs: t... | Implement the Python class `Implement` described below.
Class description:
Implement decorator class. This decorator also preserves the argspec, but includes the __init__ and __call__ methods, useful on implementation task creation.
Method signatures and docstrings:
- def __init__(self, *args: typing.Any, **kwargs: t... | 5f7a31436d0e6f5acbeb66fa36ab8aad18dc4092 | <|skeleton|>
class Implement:
"""Implement decorator class. This decorator also preserves the argspec, but includes the __init__ and __call__ methods, useful on implementation task creation."""
def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:
"""Store arguments passed to the decorat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Implement:
"""Implement decorator class. This decorator also preserves the argspec, but includes the __init__ and __call__ methods, useful on implementation task creation."""
def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:
"""Store arguments passed to the decorator. self = it... | the_stack_v2_python_sparse | compss/programming_model/bindings/python/src/pycompss/api/implement.py | bsc-wdc/compss | train | 39 |
7dd1822b730aa7c21e28c2e2f5266bb296329369 | [
"self.max_len = min(trace_len, max_evaluations)\nself.iteration = []\nself.fitness = []\nself.next_iteration = 0\nif self.max_len > 0:\n self.interval = max_evaluations // self.max_len",
"if self.max_len > 0:\n if iteration >= self.next_iteration:\n self.fitness.append(fitness)\n self.iteratio... | <|body_start_0|>
self.max_len = min(trace_len, max_evaluations)
self.iteration = []
self.fitness = []
self.next_iteration = 0
if self.max_len > 0:
self.interval = max_evaluations // self.max_len
<|end_body_0|>
<|body_start_1|>
if self.max_len > 0:
... | 记录不同iteration对应的fitness | FitnessTrace | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FitnessTrace:
"""记录不同iteration对应的fitness"""
def __init__(self, trace_len, max_evaluations):
"""Create the object instance. :param trace_len: Max length of fitness-trace. Zero if no fitness-trace is wanted. :param max_evaluations: Number of optimization iterations that will be perform... | stack_v2_sparse_classes_75kplus_train_072277 | 3,090 | no_license | [
{
"docstring": "Create the object instance. :param trace_len: Max length of fitness-trace. Zero if no fitness-trace is wanted. :param max_evaluations: Number of optimization iterations that will be performed. :return: Object instance.",
"name": "__init__",
"signature": "def __init__(self, trace_len, max... | 2 | stack_v2_sparse_classes_30k_train_024633 | Implement the Python class `FitnessTrace` described below.
Class description:
记录不同iteration对应的fitness
Method signatures and docstrings:
- def __init__(self, trace_len, max_evaluations): Create the object instance. :param trace_len: Max length of fitness-trace. Zero if no fitness-trace is wanted. :param max_evaluation... | Implement the Python class `FitnessTrace` described below.
Class description:
记录不同iteration对应的fitness
Method signatures and docstrings:
- def __init__(self, trace_len, max_evaluations): Create the object instance. :param trace_len: Max length of fitness-trace. Zero if no fitness-trace is wanted. :param max_evaluation... | 1157e5abc004af624f182879105f9284f97ef08c | <|skeleton|>
class FitnessTrace:
"""记录不同iteration对应的fitness"""
def __init__(self, trace_len, max_evaluations):
"""Create the object instance. :param trace_len: Max length of fitness-trace. Zero if no fitness-trace is wanted. :param max_evaluations: Number of optimization iterations that will be perform... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FitnessTrace:
"""记录不同iteration对应的fitness"""
def __init__(self, trace_len, max_evaluations):
"""Create the object instance. :param trace_len: Max length of fitness-trace. Zero if no fitness-trace is wanted. :param max_evaluations: Number of optimization iterations that will be performed. :return: ... | the_stack_v2_python_sparse | Programme/python/two qubit gate/CZgate/IBM/Qubits module/swarmops/FitnessTrace.py | ChenZha/Quantum-Computation | train | 6 |
7bb51c9c08561ffda8401ab6b98a0071eb3c7fa4 | [
"if self.models:\n import django\n import django.core.management\n from django.core.exceptions import ImproperlyConfigured\n dbfile = django.conf.settings.DATABASES['default']['NAME']\n if django.VERSION[0] == 1 and django.VERSION[1] >= 7:\n for connection in django.db.connections.all():\n ... | <|body_start_0|>
if self.models:
import django
import django.core.management
from django.core.exceptions import ImproperlyConfigured
dbfile = django.conf.settings.DATABASES['default']['NAME']
if django.VERSION[0] == 1 and django.VERSION[1] >= 7:
... | Test case class for Django database models | DBModelTestCase | [
"LicenseRef-scancode-unknown-license-reference",
"mpich2",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DBModelTestCase:
"""Test case class for Django database models"""
def test_syncdb(self):
"""Create the test database and sync the schema"""
<|body_0|>
def test_cleandb(self):
"""Ensure that we a) can connect to the database; b) start with a clean database"""
... | stack_v2_sparse_classes_75kplus_train_072278 | 12,205 | permissive | [
{
"docstring": "Create the test database and sync the schema",
"name": "test_syncdb",
"signature": "def test_syncdb(self)"
},
{
"docstring": "Ensure that we a) can connect to the database; b) start with a clean database",
"name": "test_cleandb",
"signature": "def test_cleandb(self)"
}
... | 2 | stack_v2_sparse_classes_30k_train_011703 | Implement the Python class `DBModelTestCase` described below.
Class description:
Test case class for Django database models
Method signatures and docstrings:
- def test_syncdb(self): Create the test database and sync the schema
- def test_cleandb(self): Ensure that we a) can connect to the database; b) start with a c... | Implement the Python class `DBModelTestCase` described below.
Class description:
Test case class for Django database models
Method signatures and docstrings:
- def test_syncdb(self): Create the test database and sync the schema
- def test_cleandb(self): Ensure that we a) can connect to the database; b) start with a c... | 8605cd3d0cb4d549cb8b43de945d447f6d82892a | <|skeleton|>
class DBModelTestCase:
"""Test case class for Django database models"""
def test_syncdb(self):
"""Create the test database and sync the schema"""
<|body_0|>
def test_cleandb(self):
"""Ensure that we a) can connect to the database; b) start with a clean database"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DBModelTestCase:
"""Test case class for Django database models"""
def test_syncdb(self):
"""Create the test database and sync the schema"""
if self.models:
import django
import django.core.management
from django.core.exceptions import ImproperlyConfigur... | the_stack_v2_python_sparse | testsuite/common.py | Bcfg2/bcfg2 | train | 56 |
dbdd9f777e41dd16832c075db145f1d1e32cd076 | [
"m, n = (len(dungeon), len(dungeon[0]))\ndp = [[1] * n for i in range(m)]\ndp[m - 1][n - 1] = max(1, 1 - dungeon[m - 1][n - 1])\nfor i in range(m - 2, -1, -1):\n dp[i][n - 1] = max(1, dp[i + 1][n - 1] - dungeon[i][n - 1])\nfor j in range(n - 1, -1, -1):\n dp[m - 1][j] = max(1, dp[m - 1][j + 1] - dungeon[m - 1... | <|body_start_0|>
m, n = (len(dungeon), len(dungeon[0]))
dp = [[1] * n for i in range(m)]
dp[m - 1][n - 1] = max(1, 1 - dungeon[m - 1][n - 1])
for i in range(m - 2, -1, -1):
dp[i][n - 1] = max(1, dp[i + 1][n - 1] - dungeon[i][n - 1])
for j in range(n - 1, -1, -1):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def calculateMinimumHP1(self, dungeon):
"""dynamic programming: let dp[i][j] be the minimum health point required for cell (i, j); dp[i][j] = min(max(1, dp[i+1][j] - dungeon[i][j]), max(1, dp[i][j+1] - dungeon[i][j]))"""
<|body_0|>
def calculateMinimumHP1(self, dun... | stack_v2_sparse_classes_75kplus_train_072279 | 2,996 | no_license | [
{
"docstring": "dynamic programming: let dp[i][j] be the minimum health point required for cell (i, j); dp[i][j] = min(max(1, dp[i+1][j] - dungeon[i][j]), max(1, dp[i][j+1] - dungeon[i][j]))",
"name": "calculateMinimumHP1",
"signature": "def calculateMinimumHP1(self, dungeon)"
},
{
"docstring": ... | 2 | stack_v2_sparse_classes_30k_train_054627 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calculateMinimumHP1(self, dungeon): dynamic programming: let dp[i][j] be the minimum health point required for cell (i, j); dp[i][j] = min(max(1, dp[i+1][j] - dungeon[i][j]),... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calculateMinimumHP1(self, dungeon): dynamic programming: let dp[i][j] be the minimum health point required for cell (i, j); dp[i][j] = min(max(1, dp[i+1][j] - dungeon[i][j]),... | 6ff1941ff213a843013100ac7033e2d4f90fbd6a | <|skeleton|>
class Solution:
def calculateMinimumHP1(self, dungeon):
"""dynamic programming: let dp[i][j] be the minimum health point required for cell (i, j); dp[i][j] = min(max(1, dp[i+1][j] - dungeon[i][j]), max(1, dp[i][j+1] - dungeon[i][j]))"""
<|body_0|>
def calculateMinimumHP1(self, dun... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def calculateMinimumHP1(self, dungeon):
"""dynamic programming: let dp[i][j] be the minimum health point required for cell (i, j); dp[i][j] = min(max(1, dp[i+1][j] - dungeon[i][j]), max(1, dp[i][j+1] - dungeon[i][j]))"""
m, n = (len(dungeon), len(dungeon[0]))
dp = [[1] * n fo... | the_stack_v2_python_sparse | Leetcode 0174. Dungeon Game.py | Chaoran-sjsu/leetcode | train | 0 | |
ac62548350bb2f5a43e01f83e7cc6183cf9055ee | [
"if not nums:\n return 0\ndp = [[0 for i in range(2)] for _ in range(len(nums))]\ndp[0][0] = 0\ndp[0][1] = nums[0]\nfor i in range(1, len(nums)):\n dp[i][0] = max(dp[i - 1][0], dp[i - 1][1])\n dp[i][1] = dp[i - 1][0] + nums[i]\nreturn max(dp[-1])",
"if not nums:\n return 0\nif len(nums) == 1:\n ret... | <|body_start_0|>
if not nums:
return 0
dp = [[0 for i in range(2)] for _ in range(len(nums))]
dp[0][0] = 0
dp[0][1] = nums[0]
for i in range(1, len(nums)):
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1])
dp[i][1] = dp[i - 1][0] + nums[i]
ret... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rob(self, nums: List[int]) -> int:
"""0表示不偷,1表示偷 状态转移方程为dp[i][1] = dp[i - 1][0] + nums[i] dp[i][0] = max(dp[i - 1][0], dp[i][1]) :param nums: :return:"""
<|body_0|>
def rob1(self, nums: List[int]) -> int:
"""空间优化 o(n) 状态转移方程为dp[i] = max(dp[i - 2] + nums... | stack_v2_sparse_classes_75kplus_train_072280 | 2,431 | no_license | [
{
"docstring": "0表示不偷,1表示偷 状态转移方程为dp[i][1] = dp[i - 1][0] + nums[i] dp[i][0] = max(dp[i - 1][0], dp[i][1]) :param nums: :return:",
"name": "rob",
"signature": "def rob(self, nums: List[int]) -> int"
},
{
"docstring": "空间优化 o(n) 状态转移方程为dp[i] = max(dp[i - 2] + nums[i], dp[i - 1]),表示偷窃当前房间和不偷窃当前房间 ... | 3 | stack_v2_sparse_classes_30k_train_035313 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums: List[int]) -> int: 0表示不偷,1表示偷 状态转移方程为dp[i][1] = dp[i - 1][0] + nums[i] dp[i][0] = max(dp[i - 1][0], dp[i][1]) :param nums: :return:
- def rob1(self, nums: Lis... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums: List[int]) -> int: 0表示不偷,1表示偷 状态转移方程为dp[i][1] = dp[i - 1][0] + nums[i] dp[i][0] = max(dp[i - 1][0], dp[i][1]) :param nums: :return:
- def rob1(self, nums: Lis... | 9acba92695c06406f12f997a720bfe1deb9464a8 | <|skeleton|>
class Solution:
def rob(self, nums: List[int]) -> int:
"""0表示不偷,1表示偷 状态转移方程为dp[i][1] = dp[i - 1][0] + nums[i] dp[i][0] = max(dp[i - 1][0], dp[i][1]) :param nums: :return:"""
<|body_0|>
def rob1(self, nums: List[int]) -> int:
"""空间优化 o(n) 状态转移方程为dp[i] = max(dp[i - 2] + nums... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def rob(self, nums: List[int]) -> int:
"""0表示不偷,1表示偷 状态转移方程为dp[i][1] = dp[i - 1][0] + nums[i] dp[i][0] = max(dp[i - 1][0], dp[i][1]) :param nums: :return:"""
if not nums:
return 0
dp = [[0 for i in range(2)] for _ in range(len(nums))]
dp[0][0] = 0
... | the_stack_v2_python_sparse | datastructure/dp_exercise/Rob.py | yinhuax/leet_code | train | 0 | |
096573f2bca70e8d3ded0fe79343445a56c6bf05 | [
"if not p and (not q):\n return True\nif not p or not q:\n return False\nif p.val != q.val:\n return False\nreturn self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)",
"if not p and (not q):\n return True\nstack = [p, q]\nwhile stack:\n rgt, lft = (stack.pop(), stack.pop())\n ... | <|body_start_0|>
if not p and (not q):
return True
if not p or not q:
return False
if p.val != q.val:
return False
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
<|end_body_0|>
<|body_start_1|>
if not p and (not q... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSameTree(self, p, q):
"""Recursion"""
<|body_0|>
def isSameTree(self, p, q):
"""Iteration"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not p and (not q):
return True
if not p or not q:
return Fal... | stack_v2_sparse_classes_75kplus_train_072281 | 927 | no_license | [
{
"docstring": "Recursion",
"name": "isSameTree",
"signature": "def isSameTree(self, p, q)"
},
{
"docstring": "Iteration",
"name": "isSameTree",
"signature": "def isSameTree(self, p, q)"
}
] | 2 | stack_v2_sparse_classes_30k_train_042056 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSameTree(self, p, q): Recursion
- def isSameTree(self, p, q): Iteration | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSameTree(self, p, q): Recursion
- def isSameTree(self, p, q): Iteration
<|skeleton|>
class Solution:
def isSameTree(self, p, q):
"""Recursion"""
<|bod... | 1269b05a51e834e620d0adf4c3a10fe1a917b458 | <|skeleton|>
class Solution:
def isSameTree(self, p, q):
"""Recursion"""
<|body_0|>
def isSameTree(self, p, q):
"""Iteration"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isSameTree(self, p, q):
"""Recursion"""
if not p and (not q):
return True
if not p or not q:
return False
if p.val != q.val:
return False
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
... | the_stack_v2_python_sparse | leetcode/python/same_tree.py | rioshen/Problems | train | 1 | |
8cde3ad6fe45973fbc75ad87986a27d0b8f8a12e | [
"self._app = _app\nself.viewer = viewer\nself.tournament = None",
"from app.controllers.edit_tournament import EditTournamentController\nself._app.change_controller(EditTournamentController(self.tournament, False))\nself.viewer.warning = ''\nreturn False",
"from app.models.tournament import Tournament\nnumber =... | <|body_start_0|>
self._app = _app
self.viewer = viewer
self.tournament = None
<|end_body_0|>
<|body_start_1|>
from app.controllers.edit_tournament import EditTournamentController
self._app.change_controller(EditTournamentController(self.tournament, False))
self.viewer.wa... | Project go_to_edit_tournament command class. | GotoEditTournament | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GotoEditTournament:
"""Project go_to_edit_tournament command class."""
def __init__(self, _app, viewer):
"""Init go_to_edit_tournament command class."""
<|body_0|>
def exe_command(self):
"""Execute command and return False to not exit application."""
<|bo... | stack_v2_sparse_classes_75kplus_train_072282 | 9,466 | no_license | [
{
"docstring": "Init go_to_edit_tournament command class.",
"name": "__init__",
"signature": "def __init__(self, _app, viewer)"
},
{
"docstring": "Execute command and return False to not exit application.",
"name": "exe_command",
"signature": "def exe_command(self)"
},
{
"docstri... | 3 | null | Implement the Python class `GotoEditTournament` described below.
Class description:
Project go_to_edit_tournament command class.
Method signatures and docstrings:
- def __init__(self, _app, viewer): Init go_to_edit_tournament command class.
- def exe_command(self): Execute command and return False to not exit applica... | Implement the Python class `GotoEditTournament` described below.
Class description:
Project go_to_edit_tournament command class.
Method signatures and docstrings:
- def __init__(self, _app, viewer): Init go_to_edit_tournament command class.
- def exe_command(self): Execute command and return False to not exit applica... | be6089cd71c762f23725b61e8d2745cfabe4f0c0 | <|skeleton|>
class GotoEditTournament:
"""Project go_to_edit_tournament command class."""
def __init__(self, _app, viewer):
"""Init go_to_edit_tournament command class."""
<|body_0|>
def exe_command(self):
"""Execute command and return False to not exit application."""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GotoEditTournament:
"""Project go_to_edit_tournament command class."""
def __init__(self, _app, viewer):
"""Init go_to_edit_tournament command class."""
self._app = _app
self.viewer = viewer
self.tournament = None
def exe_command(self):
"""Execute command and ... | the_stack_v2_python_sparse | app/commands/navigation.py | FortranVBA/DAP4 | train | 0 |
108ec58d2cfeb0000a64fa232d066f3c354186e5 | [
"filter_dict = {}\nif self.dashboard.project:\n filter_dict['project'] = self.dashboard.project\nfilters = FilterObject.objects.filter(dashboard_object=self).select_subclasses()\nfor filter_object in filters:\n filter_dict[filter_object.filter_by] = filter_object.filter_value\nreturn filter_dict",
"if not s... | <|body_start_0|>
filter_dict = {}
if self.dashboard.project:
filter_dict['project'] = self.dashboard.project
filters = FilterObject.objects.filter(dashboard_object=self).select_subclasses()
for filter_object in filters:
filter_dict[filter_object.filter_by] = filte... | DashboardObject | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DashboardObject:
def filters(self):
"""Return collection of filters in a dictionary format @return: Dict with filters"""
<|body_0|>
def get_vpi_data(self):
"""Return data for vpi's included in this dashboard @return: VPI data in either a dictionary or float format.""... | stack_v2_sparse_classes_75kplus_train_072283 | 4,092 | permissive | [
{
"docstring": "Return collection of filters in a dictionary format @return: Dict with filters",
"name": "filters",
"signature": "def filters(self)"
},
{
"docstring": "Return data for vpi's included in this dashboard @return: VPI data in either a dictionary or float format.",
"name": "get_vp... | 3 | stack_v2_sparse_classes_30k_train_039384 | Implement the Python class `DashboardObject` described below.
Class description:
Implement the DashboardObject class.
Method signatures and docstrings:
- def filters(self): Return collection of filters in a dictionary format @return: Dict with filters
- def get_vpi_data(self): Return data for vpi's included in this d... | Implement the Python class `DashboardObject` described below.
Class description:
Implement the DashboardObject class.
Method signatures and docstrings:
- def filters(self): Return collection of filters in a dictionary format @return: Dict with filters
- def get_vpi_data(self): Return data for vpi's included in this d... | d925bd475967e60fc7e80de8f2225c5ed85726fb | <|skeleton|>
class DashboardObject:
def filters(self):
"""Return collection of filters in a dictionary format @return: Dict with filters"""
<|body_0|>
def get_vpi_data(self):
"""Return data for vpi's included in this dashboard @return: VPI data in either a dictionary or float format.""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DashboardObject:
def filters(self):
"""Return collection of filters in a dictionary format @return: Dict with filters"""
filter_dict = {}
if self.dashboard.project:
filter_dict['project'] = self.dashboard.project
filters = FilterObject.objects.filter(dashboard_objec... | the_stack_v2_python_sparse | dashboard/models.py | arjenpoppe/istimewa-bvp | train | 0 | |
466171e0da9874e9635228007ce5ab28b604010e | [
"self.np_shape = params['shape'][::-1]\nself.np_dtype = params['dtype']\nself.seed = params['seed']\nself.rng = np.random.default_rng(self.seed)",
"probabilities = [1.0 - settings.FLIP_PROBABILITY, settings.FLIP_PROBABILITY]\na = self.rng.choice([0, 1], p=probabilities, size=self.np_shape)\na = np.array(a, dtype=... | <|body_start_0|>
self.np_shape = params['shape'][::-1]
self.np_dtype = params['dtype']
self.seed = params['seed']
self.rng = np.random.default_rng(self.seed)
<|end_body_0|>
<|body_start_1|>
probabilities = [1.0 - settings.FLIP_PROBABILITY, settings.FLIP_PROBABILITY]
a = ... | Class defining the random flip implementation. | RandomFlipFunction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomFlipFunction:
"""Class defining the random flip implementation."""
def __init__(self, params):
""":params params: dictionary of params conatining shape: output shape of this class. dtype: output dtype of this class. seed: seed to be used for randomization."""
<|body_0|>... | stack_v2_sparse_classes_75kplus_train_072284 | 7,328 | no_license | [
{
"docstring": ":params params: dictionary of params conatining shape: output shape of this class. dtype: output dtype of this class. seed: seed to be used for randomization.",
"name": "__init__",
"signature": "def __init__(self, params)"
},
{
"docstring": ":returns : random flip values calculat... | 2 | stack_v2_sparse_classes_30k_train_017614 | Implement the Python class `RandomFlipFunction` described below.
Class description:
Class defining the random flip implementation.
Method signatures and docstrings:
- def __init__(self, params): :params params: dictionary of params conatining shape: output shape of this class. dtype: output dtype of this class. seed:... | Implement the Python class `RandomFlipFunction` described below.
Class description:
Class defining the random flip implementation.
Method signatures and docstrings:
- def __init__(self, params): :params params: dictionary of params conatining shape: output shape of this class. dtype: output dtype of this class. seed:... | 3ca77c4a5fb62c60372e8a2839b1fccc3c4e4212 | <|skeleton|>
class RandomFlipFunction:
"""Class defining the random flip implementation."""
def __init__(self, params):
""":params params: dictionary of params conatining shape: output shape of this class. dtype: output dtype of this class. seed: seed to be used for randomization."""
<|body_0|>... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomFlipFunction:
"""Class defining the random flip implementation."""
def __init__(self, params):
""":params params: dictionary of params conatining shape: output shape of this class. dtype: output dtype of this class. seed: seed to be used for randomization."""
self.np_shape = params[... | the_stack_v2_python_sparse | TensorFlow/computer_vision/common/resnet_media_pipe.py | HabanaAI/Model-References | train | 108 |
f0d4a5a02869a3726b369da64dcf972eb08d3c00 | [
"if Serial.objects.count():\n return Serial.objects.first()\nreturn Serial.objects.create(next_serial=settings.JTB_NEXT_TIN or 1)",
"if not Serial.objects.count():\n Serial.create_instance()\nserial = Serial.objects.select_for_update().first()\nnext_serial = serial.next_serial\nserial.next_serial += 1\nseri... | <|body_start_0|>
if Serial.objects.count():
return Serial.objects.first()
return Serial.objects.create(next_serial=settings.JTB_NEXT_TIN or 1)
<|end_body_0|>
<|body_start_1|>
if not Serial.objects.count():
Serial.create_instance()
serial = Serial.objects.select_f... | Maintains a serial counter for generating Tax Identification Numbers (TIN) | Serial | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Serial:
"""Maintains a serial counter for generating Tax Identification Numbers (TIN)"""
def create_instance():
"""Returns the singleton instance. Creates one if none exists."""
<|body_0|>
def get_next_serial():
"""Get and update next serial with row locking"""
... | stack_v2_sparse_classes_75kplus_train_072285 | 11,026 | no_license | [
{
"docstring": "Returns the singleton instance. Creates one if none exists.",
"name": "create_instance",
"signature": "def create_instance()"
},
{
"docstring": "Get and update next serial with row locking",
"name": "get_next_serial",
"signature": "def get_next_serial()"
}
] | 2 | stack_v2_sparse_classes_30k_train_029878 | Implement the Python class `Serial` described below.
Class description:
Maintains a serial counter for generating Tax Identification Numbers (TIN)
Method signatures and docstrings:
- def create_instance(): Returns the singleton instance. Creates one if none exists.
- def get_next_serial(): Get and update next serial ... | Implement the Python class `Serial` described below.
Class description:
Maintains a serial counter for generating Tax Identification Numbers (TIN)
Method signatures and docstrings:
- def create_instance(): Returns the singleton instance. Creates one if none exists.
- def get_next_serial(): Get and update next serial ... | 98157e3816d8953e25370ae29802c46b5630bfab | <|skeleton|>
class Serial:
"""Maintains a serial counter for generating Tax Identification Numbers (TIN)"""
def create_instance():
"""Returns the singleton instance. Creates one if none exists."""
<|body_0|>
def get_next_serial():
"""Get and update next serial with row locking"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Serial:
"""Maintains a serial counter for generating Tax Identification Numbers (TIN)"""
def create_instance():
"""Returns the singleton instance. Creates one if none exists."""
if Serial.objects.count():
return Serial.objects.first()
return Serial.objects.create(next_... | the_stack_v2_python_sparse | TaxApp/api/models.py | donvikky/TaxApp | train | 0 |
f212d38fd65ed9b25baa2e5431ccd937e2c4a2d7 | [
"super().__init__(node, control, unique_id, description, device_info)\nself._memory_change_handler: EventListener | None = None\nself._attr_current_option = None",
"await super().async_added_to_hass()\nif (last_state := (await self.async_get_last_state())) and last_state.state not in (STATE_UNKNOWN, STATE_UNAVAIL... | <|body_start_0|>
super().__init__(node, control, unique_id, description, device_info)
self._memory_change_handler: EventListener | None = None
self._attr_current_option = None
<|end_body_0|>
<|body_start_1|>
await super().async_added_to_hass()
if (last_state := (await self.async... | Representation of a ISY/IoX Backlight Select entity. | ISYBacklightSelectEntity | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ISYBacklightSelectEntity:
"""Representation of a ISY/IoX Backlight Select entity."""
def __init__(self, node: Node, control: str, unique_id: str, description: SelectEntityDescription, device_info: DeviceInfo | None) -> None:
"""Initialize the ISY Backlight Select entity."""
<... | stack_v2_sparse_classes_75kplus_train_072286 | 7,639 | permissive | [
{
"docstring": "Initialize the ISY Backlight Select entity.",
"name": "__init__",
"signature": "def __init__(self, node: Node, control: str, unique_id: str, description: SelectEntityDescription, device_info: DeviceInfo | None) -> None"
},
{
"docstring": "Load the last known state when added to h... | 4 | stack_v2_sparse_classes_30k_train_012873 | Implement the Python class `ISYBacklightSelectEntity` described below.
Class description:
Representation of a ISY/IoX Backlight Select entity.
Method signatures and docstrings:
- def __init__(self, node: Node, control: str, unique_id: str, description: SelectEntityDescription, device_info: DeviceInfo | None) -> None:... | Implement the Python class `ISYBacklightSelectEntity` described below.
Class description:
Representation of a ISY/IoX Backlight Select entity.
Method signatures and docstrings:
- def __init__(self, node: Node, control: str, unique_id: str, description: SelectEntityDescription, device_info: DeviceInfo | None) -> None:... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ISYBacklightSelectEntity:
"""Representation of a ISY/IoX Backlight Select entity."""
def __init__(self, node: Node, control: str, unique_id: str, description: SelectEntityDescription, device_info: DeviceInfo | None) -> None:
"""Initialize the ISY Backlight Select entity."""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ISYBacklightSelectEntity:
"""Representation of a ISY/IoX Backlight Select entity."""
def __init__(self, node: Node, control: str, unique_id: str, description: SelectEntityDescription, device_info: DeviceInfo | None) -> None:
"""Initialize the ISY Backlight Select entity."""
super().__init... | the_stack_v2_python_sparse | homeassistant/components/isy994/select.py | home-assistant/core | train | 35,501 |
1257f331664a932310bf86d85822320daa90ff29 | [
"if not isinstance(config, dict):\n config = {}\nconfig.setdefault('unrar_tool', '')\nreturn config",
"if isinstance(config, bool) and (not config):\n return\nconfig = self.prepare_config(config)\nutils.rarfile_set_tool_path(config)\nfor entry in task.entries:\n archive_path = entry.get('location', '')\n... | <|body_start_0|>
if not isinstance(config, dict):
config = {}
config.setdefault('unrar_tool', '')
return config
<|end_body_0|>
<|body_start_1|>
if isinstance(config, bool) and (not config):
return
config = self.prepare_config(config)
utils.rarfile... | Accepts entries that are valid Zip or RAR archives This plugin requires the rarfile Python module and unrar command line utility to handle RAR archives. Configuration: unrar_tool: Specifies the path of the unrar tool. Only necessary if its location is not defined in the operating system's PATH environment variable. | FilterArchives | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilterArchives:
"""Accepts entries that are valid Zip or RAR archives This plugin requires the rarfile Python module and unrar command line utility to handle RAR archives. Configuration: unrar_tool: Specifies the path of the unrar tool. Only necessary if its location is not defined in the operati... | stack_v2_sparse_classes_75kplus_train_072287 | 1,634 | permissive | [
{
"docstring": "Prepare config for processing",
"name": "prepare_config",
"signature": "def prepare_config(self, config)"
},
{
"docstring": "Task handler for archives",
"name": "on_task_filter",
"signature": "def on_task_filter(self, task, config)"
}
] | 2 | null | Implement the Python class `FilterArchives` described below.
Class description:
Accepts entries that are valid Zip or RAR archives This plugin requires the rarfile Python module and unrar command line utility to handle RAR archives. Configuration: unrar_tool: Specifies the path of the unrar tool. Only necessary if its... | Implement the Python class `FilterArchives` described below.
Class description:
Accepts entries that are valid Zip or RAR archives This plugin requires the rarfile Python module and unrar command line utility to handle RAR archives. Configuration: unrar_tool: Specifies the path of the unrar tool. Only necessary if its... | 2b7e8314d103c94cf4552bd0152699eeca0ad159 | <|skeleton|>
class FilterArchives:
"""Accepts entries that are valid Zip or RAR archives This plugin requires the rarfile Python module and unrar command line utility to handle RAR archives. Configuration: unrar_tool: Specifies the path of the unrar tool. Only necessary if its location is not defined in the operati... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FilterArchives:
"""Accepts entries that are valid Zip or RAR archives This plugin requires the rarfile Python module and unrar command line utility to handle RAR archives. Configuration: unrar_tool: Specifies the path of the unrar tool. Only necessary if its location is not defined in the operating system's P... | the_stack_v2_python_sparse | flexget/components/archives/archives.py | BrutuZ/Flexget | train | 1 |
1cd07d6965a0c87a2f991fefc95f113b662e666b | [
"if 'device_a_name' not in kwargs or 'device_z_name' not in kwargs:\n raise ValueError('device_a_name and device_z_name are mandatory')\nif not kwargs['device_a_name'] or not kwargs['device_z_name']:\n raise ValueError('device_a_name and device_z_name are mandatory and must not be None')\nkeys_to_copy = ['dev... | <|body_start_0|>
if 'device_a_name' not in kwargs or 'device_z_name' not in kwargs:
raise ValueError('device_a_name and device_z_name are mandatory')
if not kwargs['device_a_name'] or not kwargs['device_z_name']:
raise ValueError('device_a_name and device_z_name are mandatory and... | Cable Model based on DiffSyncModel. | Cable | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cable:
"""Cable Model based on DiffSyncModel."""
def __init__(self, *args, **kwargs):
"""Ensure the cable is unique by ordering the devices alphabetically."""
<|body_0|>
def get_device_intf(self, side):
"""Get the device name and the interface name for a given si... | stack_v2_sparse_classes_75kplus_train_072288 | 6,055 | permissive | [
{
"docstring": "Ensure the cable is unique by ordering the devices alphabetically.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Get the device name and the interface name for a given side. Args: side (str): site to query, must be either a or z Raise... | 2 | stack_v2_sparse_classes_30k_train_036745 | Implement the Python class `Cable` described below.
Class description:
Cable Model based on DiffSyncModel.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Ensure the cable is unique by ordering the devices alphabetically.
- def get_device_intf(self, side): Get the device name and the interfac... | Implement the Python class `Cable` described below.
Class description:
Cable Model based on DiffSyncModel.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Ensure the cable is unique by ordering the devices alphabetically.
- def get_device_intf(self, side): Get the device name and the interfac... | 1530eb838727b2b6fbec515b2d06d902e88f9b35 | <|skeleton|>
class Cable:
"""Cable Model based on DiffSyncModel."""
def __init__(self, *args, **kwargs):
"""Ensure the cable is unique by ordering the devices alphabetically."""
<|body_0|>
def get_device_intf(self, side):
"""Get the device name and the interface name for a given si... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Cable:
"""Cable Model based on DiffSyncModel."""
def __init__(self, *args, **kwargs):
"""Ensure the cable is unique by ordering the devices alphabetically."""
if 'device_a_name' not in kwargs or 'device_z_name' not in kwargs:
raise ValueError('device_a_name and device_z_name a... | the_stack_v2_python_sparse | network_importer/models.py | gladpark/network-importer | train | 0 |
857353a2daf7e0e0a63695ee984cc0b558519b43 | [
"app_bundle = bundles[-1]\ntry:\n self.import_bundle_modules(app_bundle)[0]\nexcept IndexError:\n routes = self.collect_from_bundle(app_bundle)\nelse:\n try:\n routes = self.get_explicit_routes(app_bundle)\n except AttributeError as e:\n if not app_bundle.is_single_module:\n rai... | <|body_start_0|>
app_bundle = bundles[-1]
try:
self.import_bundle_modules(app_bundle)[0]
except IndexError:
routes = self.collect_from_bundle(app_bundle)
else:
try:
routes = self.get_explicit_routes(app_bundle)
except Attrib... | Registers routes. | RegisterRoutesHook | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegisterRoutesHook:
"""Registers routes."""
def run_hook(self, app: FlaskUnchained, bundles: List[Bundle], unchained_config: Optional[Dict[str, Any]]=None) -> None:
"""Discover and register routes."""
<|body_0|>
def process_objects(self, app: FlaskUnchained, routes: Iter... | stack_v2_sparse_classes_75kplus_train_072289 | 6,728 | permissive | [
{
"docstring": "Discover and register routes.",
"name": "run_hook",
"signature": "def run_hook(self, app: FlaskUnchained, bundles: List[Bundle], unchained_config: Optional[Dict[str, Any]]=None) -> None"
},
{
"docstring": "Organize routes by where they came from, and then register them with the a... | 5 | stack_v2_sparse_classes_30k_train_040756 | Implement the Python class `RegisterRoutesHook` described below.
Class description:
Registers routes.
Method signatures and docstrings:
- def run_hook(self, app: FlaskUnchained, bundles: List[Bundle], unchained_config: Optional[Dict[str, Any]]=None) -> None: Discover and register routes.
- def process_objects(self, a... | Implement the Python class `RegisterRoutesHook` described below.
Class description:
Registers routes.
Method signatures and docstrings:
- def run_hook(self, app: FlaskUnchained, bundles: List[Bundle], unchained_config: Optional[Dict[str, Any]]=None) -> None: Discover and register routes.
- def process_objects(self, a... | a1f1323f63f59760e430001efef43af9b829ebed | <|skeleton|>
class RegisterRoutesHook:
"""Registers routes."""
def run_hook(self, app: FlaskUnchained, bundles: List[Bundle], unchained_config: Optional[Dict[str, Any]]=None) -> None:
"""Discover and register routes."""
<|body_0|>
def process_objects(self, app: FlaskUnchained, routes: Iter... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RegisterRoutesHook:
"""Registers routes."""
def run_hook(self, app: FlaskUnchained, bundles: List[Bundle], unchained_config: Optional[Dict[str, Any]]=None) -> None:
"""Discover and register routes."""
app_bundle = bundles[-1]
try:
self.import_bundle_modules(app_bundle)... | the_stack_v2_python_sparse | flask_unchained/bundles/controller/hooks/register_routes_hook.py | briancappello/flask-unchained | train | 77 |
73b881c2e96c706d93f24ccd092879c85e318812 | [
"if type(capacity) != int:\n raise Exception('Error: Type error: %s' % type(capacity))\n'@blank(If the value passed in for capacity is less than or equal to 0, an exception indicating the illegal capacity is raised.)'\nif capacity <= 0:\n raise Exception('Error: illegal capacity: %d' % capacity)\n'@helpDescri... | <|body_start_0|>
if type(capacity) != int:
raise Exception('Error: Type error: %s' % type(capacity))
'@blank(If the value passed in for capacity is less than or equal to 0, an exception indicating the illegal capacity is raised.)'
if capacity <= 0:
raise Exception('Error:... | @helpDescription(The capacity, or the maximum length allowed in the queue, is passed in as an integer when the BoundedQueue class is initialized.) | BoundedQueue | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BoundedQueue:
"""@helpDescription(The capacity, or the maximum length allowed in the queue, is passed in as an integer when the BoundedQueue class is initialized.)"""
def __init__(self, capacity):
"""@helpDescription(The value passed in for capacity of a queue must be a positive inte... | stack_v2_sparse_classes_75kplus_train_072290 | 4,389 | no_license | [
{
"docstring": "@helpDescription(The value passed in for capacity of a queue must be a positive integer. If the value is not, an exception indicating the TypeError is raised.)",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": "@blank(In order the to enqueue anot... | 4 | stack_v2_sparse_classes_30k_train_039722 | Implement the Python class `BoundedQueue` described below.
Class description:
@helpDescription(The capacity, or the maximum length allowed in the queue, is passed in as an integer when the BoundedQueue class is initialized.)
Method signatures and docstrings:
- def __init__(self, capacity): @helpDescription(The value ... | Implement the Python class `BoundedQueue` described below.
Class description:
@helpDescription(The capacity, or the maximum length allowed in the queue, is passed in as an integer when the BoundedQueue class is initialized.)
Method signatures and docstrings:
- def __init__(self, capacity): @helpDescription(The value ... | 688638f6c3fa3d31c4f8be6391147d773e1aa9dd | <|skeleton|>
class BoundedQueue:
"""@helpDescription(The capacity, or the maximum length allowed in the queue, is passed in as an integer when the BoundedQueue class is initialized.)"""
def __init__(self, capacity):
"""@helpDescription(The value passed in for capacity of a queue must be a positive inte... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BoundedQueue:
"""@helpDescription(The capacity, or the maximum length allowed in the queue, is passed in as an integer when the BoundedQueue class is initialized.)"""
def __init__(self, capacity):
"""@helpDescription(The value passed in for capacity of a queue must be a positive integer. If the v... | the_stack_v2_python_sparse | python/py_queue_class/challenge/1/queue_class_challenge.py | cskamil/PcExParser | train | 1 |
cb426c9b7aae48791e6013bc88bdb62d37bffbe0 | [
"if not is_administrator(self.context['request'].user):\n raise serializers.ValidationError(constants.PERMISSION_ADMINISTRATOR_REQUIRED)\nreturn data",
"if is_customers(user):\n raise serializers.ValidationError('User already has customer permissions')\nreturn user"
] | <|body_start_0|>
if not is_administrator(self.context['request'].user):
raise serializers.ValidationError(constants.PERMISSION_ADMINISTRATOR_REQUIRED)
return data
<|end_body_0|>
<|body_start_1|>
if is_customers(user):
raise serializers.ValidationError('User already has c... | CustomerSerializerCreate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomerSerializerCreate:
def validate(self, data):
"""Administrator permissions needed"""
<|body_0|>
def validate_user(self, user):
"""Ensure user is not already moderator or higher"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not is_administ... | stack_v2_sparse_classes_75kplus_train_072291 | 4,493 | no_license | [
{
"docstring": "Administrator permissions needed",
"name": "validate",
"signature": "def validate(self, data)"
},
{
"docstring": "Ensure user is not already moderator or higher",
"name": "validate_user",
"signature": "def validate_user(self, user)"
}
] | 2 | stack_v2_sparse_classes_30k_train_044284 | Implement the Python class `CustomerSerializerCreate` described below.
Class description:
Implement the CustomerSerializerCreate class.
Method signatures and docstrings:
- def validate(self, data): Administrator permissions needed
- def validate_user(self, user): Ensure user is not already moderator or higher | Implement the Python class `CustomerSerializerCreate` described below.
Class description:
Implement the CustomerSerializerCreate class.
Method signatures and docstrings:
- def validate(self, data): Administrator permissions needed
- def validate_user(self, user): Ensure user is not already moderator or higher
<|skel... | d17fcc79b175831bae9c2e0a3a536a384b1a562b | <|skeleton|>
class CustomerSerializerCreate:
def validate(self, data):
"""Administrator permissions needed"""
<|body_0|>
def validate_user(self, user):
"""Ensure user is not already moderator or higher"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomerSerializerCreate:
def validate(self, data):
"""Administrator permissions needed"""
if not is_administrator(self.context['request'].user):
raise serializers.ValidationError(constants.PERMISSION_ADMINISTRATOR_REQUIRED)
return data
def validate_user(self, user):
... | the_stack_v2_python_sparse | app/users/serializers/customers.py | Empire-Synergy-Solutions/Altaviz_Backend | train | 0 | |
e4ee08938bd9106e6c0f1d1ca0d18a06a202bbbd | [
"if type(self.nburn) in [float, int]:\n logger.info(f'Discarding {self.nburn} steps for burn-in')\nelif self.result.max_autocorrelation_time is None:\n logger.info(f'Autocorrelation time not calculated, discarding {self.nburn} steps for burn-in')\nelse:\n logger.info(f'Discarding {self.nburn} steps for bur... | <|body_start_0|>
if type(self.nburn) in [float, int]:
logger.info(f'Discarding {self.nburn} steps for burn-in')
elif self.result.max_autocorrelation_time is None:
logger.info(f'Autocorrelation time not calculated, discarding {self.nburn} steps for burn-in')
else:
... | MCMCSampler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MCMCSampler:
def print_nburn_logging_info(self):
"""Prints logging info as to how nburn was calculated"""
<|body_0|>
def calculate_autocorrelation(self, samples, c=3):
"""Uses the `emcee.autocorr` module to estimate the autocorrelation Parameters ========== samples: ... | stack_v2_sparse_classes_75kplus_train_072292 | 36,082 | permissive | [
{
"docstring": "Prints logging info as to how nburn was calculated",
"name": "print_nburn_logging_info",
"signature": "def print_nburn_logging_info(self)"
},
{
"docstring": "Uses the `emcee.autocorr` module to estimate the autocorrelation Parameters ========== samples: array_like A chain of samp... | 2 | stack_v2_sparse_classes_30k_train_002651 | Implement the Python class `MCMCSampler` described below.
Class description:
Implement the MCMCSampler class.
Method signatures and docstrings:
- def print_nburn_logging_info(self): Prints logging info as to how nburn was calculated
- def calculate_autocorrelation(self, samples, c=3): Uses the `emcee.autocorr` module... | Implement the Python class `MCMCSampler` described below.
Class description:
Implement the MCMCSampler class.
Method signatures and docstrings:
- def print_nburn_logging_info(self): Prints logging info as to how nburn was calculated
- def calculate_autocorrelation(self, samples, c=3): Uses the `emcee.autocorr` module... | 9c1dda6cc1510692ce4ac75c608de5fae53e971c | <|skeleton|>
class MCMCSampler:
def print_nburn_logging_info(self):
"""Prints logging info as to how nburn was calculated"""
<|body_0|>
def calculate_autocorrelation(self, samples, c=3):
"""Uses the `emcee.autocorr` module to estimate the autocorrelation Parameters ========== samples: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MCMCSampler:
def print_nburn_logging_info(self):
"""Prints logging info as to how nburn was calculated"""
if type(self.nburn) in [float, int]:
logger.info(f'Discarding {self.nburn} steps for burn-in')
elif self.result.max_autocorrelation_time is None:
logger.inf... | the_stack_v2_python_sparse | bilby/core/sampler/base_sampler.py | khunsang/bilby | train | 0 | |
4b828af27dba1b0203f10ad0c536c68364991282 | [
"os.environ['SDL_VIDEO_CENTERED'] = '1'\npg.init()\npg.display.set_caption('Drag the Red Square')\nself.screen = pg.display.set_mode(SCREEN_SIZE)\nself.screen_rect = self.screen.get_rect()\nself.clock = pg.time.Clock()\nself.fps = 60.0\nself.done = False\nself.keys = pg.key.get_pressed()\nself.player = Character(0,... | <|body_start_0|>
os.environ['SDL_VIDEO_CENTERED'] = '1'
pg.init()
pg.display.set_caption('Drag the Red Square')
self.screen = pg.display.set_mode(SCREEN_SIZE)
self.screen_rect = self.screen.get_rect()
self.clock = pg.time.Clock()
self.fps = 60.0
self.done ... | A control class to manage our event and game loops. | Control | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Control:
"""A control class to manage our event and game loops."""
def __init__(self):
"""Here we have set up the pygame session within the init. Sometimes it is more convenient to do this elsewhere."""
<|body_0|>
def event_loop(self):
"""This is the event loop f... | stack_v2_sparse_classes_75kplus_train_072293 | 3,624 | no_license | [
{
"docstring": "Here we have set up the pygame session within the init. Sometimes it is more convenient to do this elsewhere.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "This is the event loop for the whole program. Regardless of the complexity of a program, there ... | 3 | stack_v2_sparse_classes_30k_train_048816 | Implement the Python class `Control` described below.
Class description:
A control class to manage our event and game loops.
Method signatures and docstrings:
- def __init__(self): Here we have set up the pygame session within the init. Sometimes it is more convenient to do this elsewhere.
- def event_loop(self): Thi... | Implement the Python class `Control` described below.
Class description:
A control class to manage our event and game loops.
Method signatures and docstrings:
- def __init__(self): Here we have set up the pygame session within the init. Sometimes it is more convenient to do this elsewhere.
- def event_loop(self): Thi... | 7fc4e0d98d06b4e28b09844babb2452e229a603c | <|skeleton|>
class Control:
"""A control class to manage our event and game loops."""
def __init__(self):
"""Here we have set up the pygame session within the init. Sometimes it is more convenient to do this elsewhere."""
<|body_0|>
def event_loop(self):
"""This is the event loop f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Control:
"""A control class to manage our event and game loops."""
def __init__(self):
"""Here we have set up the pygame session within the init. Sometimes it is more convenient to do this elsewhere."""
os.environ['SDL_VIDEO_CENTERED'] = '1'
pg.init()
pg.display.set_captio... | the_stack_v2_python_sparse | meks-pygame-samples/drag_text.py | pk00749/Example_Python | train | 1 |
04a097418d8a4882ebeeae1fe9d0b8fa44322271 | [
"self.model = model\nself.is_dngo = is_dngo\nif cost_model is not None:\n self.cost_model = cost_model\nself.estimators = []\nfor _ in range(self.model.n_hypers):\n estimator = deepcopy(acquisition_func)\n estimator.model = None\n if cost_model is not None:\n estimator.cost_model = None\n self... | <|body_start_0|>
self.model = model
self.is_dngo = is_dngo
if cost_model is not None:
self.cost_model = cost_model
self.estimators = []
for _ in range(self.model.n_hypers):
estimator = deepcopy(acquisition_func)
estimator.model = None
... | IntegratedAcquisition | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IntegratedAcquisition:
def __init__(self, model, acquisition_func, X_lower, X_upper, cost_model=None, is_dngo=False):
"""Meta acquisition function that allows to marginalise the acquisition function over GP hyperparameter. Parameters ---------- model: Model object The model of the object... | stack_v2_sparse_classes_75kplus_train_072294 | 4,715 | permissive | [
{
"docstring": "Meta acquisition function that allows to marginalise the acquisition function over GP hyperparameter. Parameters ---------- model: Model object The model of the objective function, it has to be an instance of GaussianProcessMCMC or GPyModelMCMC. acquisition_func: BaseAcquisitionFunction object T... | 3 | stack_v2_sparse_classes_30k_train_035203 | Implement the Python class `IntegratedAcquisition` described below.
Class description:
Implement the IntegratedAcquisition class.
Method signatures and docstrings:
- def __init__(self, model, acquisition_func, X_lower, X_upper, cost_model=None, is_dngo=False): Meta acquisition function that allows to marginalise the ... | Implement the Python class `IntegratedAcquisition` described below.
Class description:
Implement the IntegratedAcquisition class.
Method signatures and docstrings:
- def __init__(self, model, acquisition_func, X_lower, X_upper, cost_model=None, is_dngo=False): Meta acquisition function that allows to marginalise the ... | c2ce2e78bd98236618c99fe3453fc24389d48ead | <|skeleton|>
class IntegratedAcquisition:
def __init__(self, model, acquisition_func, X_lower, X_upper, cost_model=None, is_dngo=False):
"""Meta acquisition function that allows to marginalise the acquisition function over GP hyperparameter. Parameters ---------- model: Model object The model of the object... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IntegratedAcquisition:
def __init__(self, model, acquisition_func, X_lower, X_upper, cost_model=None, is_dngo=False):
"""Meta acquisition function that allows to marginalise the acquisition function over GP hyperparameter. Parameters ---------- model: Model object The model of the objective function, ... | the_stack_v2_python_sparse | RoBO/build/lib.linux-x86_64-2.7/robo/acquisition/integrated_acquisition.py | mrenoon/datafreezethaw | train | 5 | |
7bb80d23ebd9a44b8d75317185b957d58ada50b6 | [
"super(BOW, self).__init__()\nself.dict_size = conf_dict['dict_size']\nself.task_mode = conf_dict['task_mode']\nself.emb_dim = conf_dict['net']['emb_dim']\nself.bow_dim = conf_dict['net']['bow_dim']\nself.seq_len = conf_dict['seq_len']\nself.emb_layer = layers.EmbeddingLayer(self.dict_size, self.emb_dim, 'emb').ops... | <|body_start_0|>
super(BOW, self).__init__()
self.dict_size = conf_dict['dict_size']
self.task_mode = conf_dict['task_mode']
self.emb_dim = conf_dict['net']['emb_dim']
self.bow_dim = conf_dict['net']['bow_dim']
self.seq_len = conf_dict['seq_len']
self.emb_layer = ... | BOW | BOW | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BOW:
"""BOW"""
def __init__(self, conf_dict):
"""initialize"""
<|body_0|>
def forward(self, left, right):
"""Forward network"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(BOW, self).__init__()
self.dict_size = conf_dict['dict_siz... | stack_v2_sparse_classes_75kplus_train_072295 | 2,790 | permissive | [
{
"docstring": "initialize",
"name": "__init__",
"signature": "def __init__(self, conf_dict)"
},
{
"docstring": "Forward network",
"name": "forward",
"signature": "def forward(self, left, right)"
}
] | 2 | null | Implement the Python class `BOW` described below.
Class description:
BOW
Method signatures and docstrings:
- def __init__(self, conf_dict): initialize
- def forward(self, left, right): Forward network | Implement the Python class `BOW` described below.
Class description:
BOW
Method signatures and docstrings:
- def __init__(self, conf_dict): initialize
- def forward(self, left, right): Forward network
<|skeleton|>
class BOW:
"""BOW"""
def __init__(self, conf_dict):
"""initialize"""
<|body_0|... | a60babdf382aba71fe447b3259441b4bed947414 | <|skeleton|>
class BOW:
"""BOW"""
def __init__(self, conf_dict):
"""initialize"""
<|body_0|>
def forward(self, left, right):
"""Forward network"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BOW:
"""BOW"""
def __init__(self, conf_dict):
"""initialize"""
super(BOW, self).__init__()
self.dict_size = conf_dict['dict_size']
self.task_mode = conf_dict['task_mode']
self.emb_dim = conf_dict['net']['emb_dim']
self.bow_dim = conf_dict['net']['bow_dim']
... | the_stack_v2_python_sparse | dygraph/similarity_net/nets/bow.py | littletomatodonkey/models | train | 5 |
b14753bc53bb3ea0459d9fcd49eb3fefa656e052 | [
"if note_1.get_date() != note_2.get_date():\n return\nnote_start_1 = note_1.get_start()\nnote_start_2 = note_2.get_start()\nnote_end_1 = note_1.get_end()\nnote_end_2 = note_2.get_end()\nexception_message = 'Заметки \"' + note_1.get_title() + '\" и \"' + note_2.get_title()\nexception_message += '\" перекрываются ... | <|body_start_0|>
if note_1.get_date() != note_2.get_date():
return
note_start_1 = note_1.get_start()
note_start_2 = note_2.get_start()
note_end_1 = note_1.get_end()
note_end_2 = note_2.get_end()
exception_message = 'Заметки "' + note_1.get_title() + '" и "' + ... | класс, предоставляющий методы для сравнения заметок по времени | NoteComparator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoteComparator:
"""класс, предоставляющий методы для сравнения заметок по времени"""
def compare_two_notes(note_1: Note, note_2: Note):
"""функция сравнивающая две заметки на предмет перекрытия по времени"""
<|body_0|>
def compare_note_with_array(note: Note, array):
... | stack_v2_sparse_classes_75kplus_train_072296 | 2,600 | no_license | [
{
"docstring": "функция сравнивающая две заметки на предмет перекрытия по времени",
"name": "compare_two_notes",
"signature": "def compare_two_notes(note_1: Note, note_2: Note)"
},
{
"docstring": "сравнение заметки со списком заметок",
"name": "compare_note_with_array",
"signature": "def... | 3 | stack_v2_sparse_classes_30k_train_006460 | Implement the Python class `NoteComparator` described below.
Class description:
класс, предоставляющий методы для сравнения заметок по времени
Method signatures and docstrings:
- def compare_two_notes(note_1: Note, note_2: Note): функция сравнивающая две заметки на предмет перекрытия по времени
- def compare_note_wit... | Implement the Python class `NoteComparator` described below.
Class description:
класс, предоставляющий методы для сравнения заметок по времени
Method signatures and docstrings:
- def compare_two_notes(note_1: Note, note_2: Note): функция сравнивающая две заметки на предмет перекрытия по времени
- def compare_note_wit... | 1f8f4fff5a52cf25beb4d737019a1d98e96921d0 | <|skeleton|>
class NoteComparator:
"""класс, предоставляющий методы для сравнения заметок по времени"""
def compare_two_notes(note_1: Note, note_2: Note):
"""функция сравнивающая две заметки на предмет перекрытия по времени"""
<|body_0|>
def compare_note_with_array(note: Note, array):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NoteComparator:
"""класс, предоставляющий методы для сравнения заметок по времени"""
def compare_two_notes(note_1: Note, note_2: Note):
"""функция сравнивающая две заметки на предмет перекрытия по времени"""
if note_1.get_date() != note_2.get_date():
return
note_start_... | the_stack_v2_python_sparse | utility/note_comparator.py | NoValeria/organiser | train | 0 |
e2ee32bc0ef9c75d390207400f9a39758fc21886 | [
"if not p and (not q):\n return True\nif not p or not q:\n return False\nif p.val != q.val:\n return False\nreturn self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)",
"from collections import deque\n\ndef check(p, q):\n if not p and (not q):\n return True\n if not p or no... | <|body_start_0|>
if not p and (not q):
return True
if not p or not q:
return False
if p.val != q.val:
return False
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
<|end_body_0|>
<|body_start_1|>
from collections im... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSameTree(self, p, q):
"""Recursion time O(N) space O(log(n)) in the best case of completely balanced tree and O(n) in the worst case of completely unbalanced tree, to keep a recursion stack. :type p: TreeNode :type q: TreeNode :rtype: bool"""
<|body_0|>
def i... | stack_v2_sparse_classes_75kplus_train_072297 | 1,443 | no_license | [
{
"docstring": "Recursion time O(N) space O(log(n)) in the best case of completely balanced tree and O(n) in the worst case of completely unbalanced tree, to keep a recursion stack. :type p: TreeNode :type q: TreeNode :rtype: bool",
"name": "isSameTree",
"signature": "def isSameTree(self, p, q)"
},
... | 2 | stack_v2_sparse_classes_30k_train_031139 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSameTree(self, p, q): Recursion time O(N) space O(log(n)) in the best case of completely balanced tree and O(n) in the worst case of completely unbalanced tree, to keep a r... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSameTree(self, p, q): Recursion time O(N) space O(log(n)) in the best case of completely balanced tree and O(n) in the worst case of completely unbalanced tree, to keep a r... | 85f71621c54f6b0029f3a2746f022f89dd7419d9 | <|skeleton|>
class Solution:
def isSameTree(self, p, q):
"""Recursion time O(N) space O(log(n)) in the best case of completely balanced tree and O(n) in the worst case of completely unbalanced tree, to keep a recursion stack. :type p: TreeNode :type q: TreeNode :rtype: bool"""
<|body_0|>
def i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isSameTree(self, p, q):
"""Recursion time O(N) space O(log(n)) in the best case of completely balanced tree and O(n) in the worst case of completely unbalanced tree, to keep a recursion stack. :type p: TreeNode :type q: TreeNode :rtype: bool"""
if not p and (not q):
r... | the_stack_v2_python_sparse | LeetCode/Tree/100_same_tree.py | XyK0907/for_work | train | 0 | |
2f87dda8f91eb64b1d2486e9ecad0191ac3cad1a | [
"controller = ImageController(db)\ndata = controller.next()\nreturn serialize(data)",
"data = request.json\ndata = deserialize(data)\nprint('Received data: ', data)\ncontroller = ImageController(db)\ncontroller.classify(data)\nreturn serialize(controller.next())"
] | <|body_start_0|>
controller = ImageController(db)
data = controller.next()
return serialize(data)
<|end_body_0|>
<|body_start_1|>
data = request.json
data = deserialize(data)
print('Received data: ', data)
controller = ImageController(db)
controller.class... | Generates the next image to be displayed, and receives the label corresponding to that image. | Image | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Image:
"""Generates the next image to be displayed, and receives the label corresponding to that image."""
def get(self):
"""Returns the next image to be displayed."""
<|body_0|>
def post(self):
"""Classifies an image. data: 'image': { '_id': MongoDB ObjectId, 'f... | stack_v2_sparse_classes_75kplus_train_072298 | 3,299 | no_license | [
{
"docstring": "Returns the next image to be displayed.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Classifies an image. data: 'image': { '_id': MongoDB ObjectId, 'filename': filename of the image } 'tags': the classifications of the image. They look something like: [ [ x_co... | 2 | stack_v2_sparse_classes_30k_train_043449 | Implement the Python class `Image` described below.
Class description:
Generates the next image to be displayed, and receives the label corresponding to that image.
Method signatures and docstrings:
- def get(self): Returns the next image to be displayed.
- def post(self): Classifies an image. data: 'image': { '_id':... | Implement the Python class `Image` described below.
Class description:
Generates the next image to be displayed, and receives the label corresponding to that image.
Method signatures and docstrings:
- def get(self): Returns the next image to be displayed.
- def post(self): Classifies an image. data: 'image': { '_id':... | 3aec625f40fdd81b6b2948c95d6a783421aaf266 | <|skeleton|>
class Image:
"""Generates the next image to be displayed, and receives the label corresponding to that image."""
def get(self):
"""Returns the next image to be displayed."""
<|body_0|>
def post(self):
"""Classifies an image. data: 'image': { '_id': MongoDB ObjectId, 'f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Image:
"""Generates the next image to be displayed, and receives the label corresponding to that image."""
def get(self):
"""Returns the next image to be displayed."""
controller = ImageController(db)
data = controller.next()
return serialize(data)
def post(self):
... | the_stack_v2_python_sparse | server/server.py | o-hill/invasive | train | 0 |
5b6ba3fc63728f5879f24e82335c8bb6db171f0e | [
"self._code_uri = code_uri\nself._base_dir = base_dir\nself._code_dir = str(pathlib.Path(self._base_dir, self._code_uri).resolve())\nself._runtime = runtime\nself._manifest_path_override = manifest_path_override\nself._hash_generator = hash_generator\nself._calculated = False\nself._hash = None",
"if self._manife... | <|body_start_0|>
self._code_uri = code_uri
self._base_dir = base_dir
self._code_dir = str(pathlib.Path(self._base_dir, self._code_uri).resolve())
self._runtime = runtime
self._manifest_path_override = manifest_path_override
self._hash_generator = hash_generator
se... | DependencyHashGenerator | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DependencyHashGenerator:
def __init__(self, code_uri: str, base_dir: str, runtime: str, manifest_path_override: Optional[str]=None, hash_generator: Any=None):
"""Parameters ---------- code_uri : str Relative path specified in the function/layer resource base_dir : str Absolute path which... | stack_v2_sparse_classes_75kplus_train_072299 | 2,886 | permissive | [
{
"docstring": "Parameters ---------- code_uri : str Relative path specified in the function/layer resource base_dir : str Absolute path which the function/layer dir is located runtime : str Runtime of the function/layer manifest_path_override : Optional[str], optional Override default manifest path for each ru... | 3 | stack_v2_sparse_classes_30k_train_051877 | Implement the Python class `DependencyHashGenerator` described below.
Class description:
Implement the DependencyHashGenerator class.
Method signatures and docstrings:
- def __init__(self, code_uri: str, base_dir: str, runtime: str, manifest_path_override: Optional[str]=None, hash_generator: Any=None): Parameters ---... | Implement the Python class `DependencyHashGenerator` described below.
Class description:
Implement the DependencyHashGenerator class.
Method signatures and docstrings:
- def __init__(self, code_uri: str, base_dir: str, runtime: str, manifest_path_override: Optional[str]=None, hash_generator: Any=None): Parameters ---... | b297ff015f2b69d7c74059c2d42ece1c29ea73ee | <|skeleton|>
class DependencyHashGenerator:
def __init__(self, code_uri: str, base_dir: str, runtime: str, manifest_path_override: Optional[str]=None, hash_generator: Any=None):
"""Parameters ---------- code_uri : str Relative path specified in the function/layer resource base_dir : str Absolute path which... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DependencyHashGenerator:
def __init__(self, code_uri: str, base_dir: str, runtime: str, manifest_path_override: Optional[str]=None, hash_generator: Any=None):
"""Parameters ---------- code_uri : str Relative path specified in the function/layer resource base_dir : str Absolute path which the function/... | the_stack_v2_python_sparse | samcli/lib/build/dependency_hash_generator.py | aws/aws-sam-cli | train | 1,402 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.