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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
321132f1ac30a4f668e8c35ae75e172a74e41be2 | [
"self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)\nself.model = AutoModelForSeq2SeqLM.from_pretrained(model_path).to(device)\nself.device = device\nself.max_length = max_length",
"model_inputs = self.tokenizer(intents, truncation=True, padding=True, max_length=self.max_length, return_tensors='pt').t... | <|body_start_0|>
self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)
self.model = AutoModelForSeq2SeqLM.from_pretrained(model_path).to(device)
self.device = device
self.max_length = max_length
<|end_body_0|>
<|body_start_1|>
model_inputs = self.tokenizer(intents, trun... | Blenderbot | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Blenderbot:
def __init__(self, tokenizer_path, model_path, max_length, device):
"""params: --- tokenizer_path: path to the tokenizer in HuggingFace (e.g., facebook/blenderbot-400M-distill) model_path: path to the model in HuggingFace (e.g., facebook/blenderbot-400M-distill) max_length: m... | stack_v2_sparse_classes_75kplus_train_004700 | 2,065 | permissive | [
{
"docstring": "params: --- tokenizer_path: path to the tokenizer in HuggingFace (e.g., facebook/blenderbot-400M-distill) model_path: path to the model in HuggingFace (e.g., facebook/blenderbot-400M-distill) max_length: maximum size of subtokens in the input and output device: cpu or gpu",
"name": "__init__... | 2 | null | Implement the Python class `Blenderbot` described below.
Class description:
Implement the Blenderbot class.
Method signatures and docstrings:
- def __init__(self, tokenizer_path, model_path, max_length, device): params: --- tokenizer_path: path to the tokenizer in HuggingFace (e.g., facebook/blenderbot-400M-distill) ... | Implement the Python class `Blenderbot` described below.
Class description:
Implement the Blenderbot class.
Method signatures and docstrings:
- def __init__(self, tokenizer_path, model_path, max_length, device): params: --- tokenizer_path: path to the tokenizer in HuggingFace (e.g., facebook/blenderbot-400M-distill) ... | 1cdacf54e49cdeb76c666e77395af877d12d3d95 | <|skeleton|>
class Blenderbot:
def __init__(self, tokenizer_path, model_path, max_length, device):
"""params: --- tokenizer_path: path to the tokenizer in HuggingFace (e.g., facebook/blenderbot-400M-distill) model_path: path to the model in HuggingFace (e.g., facebook/blenderbot-400M-distill) max_length: m... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Blenderbot:
def __init__(self, tokenizer_path, model_path, max_length, device):
"""params: --- tokenizer_path: path to the tokenizer in HuggingFace (e.g., facebook/blenderbot-400M-distill) model_path: path to the model in HuggingFace (e.g., facebook/blenderbot-400M-distill) max_length: maximum size of... | the_stack_v2_python_sparse | models/blenderbot.py | ThiagoCF05/Any2Some | train | 3 | |
e7567305494da33e8f788c7aaf4f17b5cceea618 | [
"self.config = self.trainer.config\ninput_shape = [1, 3, 192, 192] if General.data_format == 'channels_first' else [1, 192, 192, 3]\nif vega.is_torch_backend():\n if vega.is_gpu_device():\n count_input = torch.FloatTensor(*input_shape).cuda()\n elif vega.is_npu_device():\n input_shape = [1, 3, 1... | <|body_start_0|>
self.config = self.trainer.config
input_shape = [1, 3, 192, 192] if General.data_format == 'channels_first' else [1, 192, 192, 3]
if vega.is_torch_backend():
if vega.is_gpu_device():
count_input = torch.FloatTensor(*input_shape).cuda()
eli... | Construct the trainer of Adelaide-EA. | AdelaideEATrainerCallback | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdelaideEATrainerCallback:
"""Construct the trainer of Adelaide-EA."""
def before_train(self, logs=None):
"""Be called before the training process."""
<|body_0|>
def after_epoch(self, epoch, logs=None):
"""Update flops and params."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus_train_004701 | 3,041 | permissive | [
{
"docstring": "Be called before the training process.",
"name": "before_train",
"signature": "def before_train(self, logs=None)"
},
{
"docstring": "Update flops and params.",
"name": "after_epoch",
"signature": "def after_epoch(self, epoch, logs=None)"
}
] | 2 | null | Implement the Python class `AdelaideEATrainerCallback` described below.
Class description:
Construct the trainer of Adelaide-EA.
Method signatures and docstrings:
- def before_train(self, logs=None): Be called before the training process.
- def after_epoch(self, epoch, logs=None): Update flops and params. | Implement the Python class `AdelaideEATrainerCallback` described below.
Class description:
Construct the trainer of Adelaide-EA.
Method signatures and docstrings:
- def before_train(self, logs=None): Be called before the training process.
- def after_epoch(self, epoch, logs=None): Update flops and params.
<|skeleton... | 12e37a1991eb6771a2999fe0a46ddda920c47948 | <|skeleton|>
class AdelaideEATrainerCallback:
"""Construct the trainer of Adelaide-EA."""
def before_train(self, logs=None):
"""Be called before the training process."""
<|body_0|>
def after_epoch(self, epoch, logs=None):
"""Update flops and params."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AdelaideEATrainerCallback:
"""Construct the trainer of Adelaide-EA."""
def before_train(self, logs=None):
"""Be called before the training process."""
self.config = self.trainer.config
input_shape = [1, 3, 192, 192] if General.data_format == 'channels_first' else [1, 192, 192, 3]
... | the_stack_v2_python_sparse | vega/algorithms/nas/adelaide_ea/adelaide_trainer_callback.py | huawei-noah/vega | train | 850 |
4e42e313b4e8f4517cca59865a67badc6b525b39 | [
"n = len(grid)\np = [[(i, j) for j in range(n)] for i in range(n)]\nh = sorted([[grid[i][j], i, j] for j in range(n) for i in range(n)])\n\ndef f(a, b):\n if (a, b) != p[a][b]:\n p[a][b] = f(*p[a][b])\n return p[a][b]\nk = 0\nfor t in range(max(grid[0][0], grid[-1][-1]), h[-1][0]):\n while h[k][0] <... | <|body_start_0|>
n = len(grid)
p = [[(i, j) for j in range(n)] for i in range(n)]
h = sorted([[grid[i][j], i, j] for j in range(n) for i in range(n)])
def f(a, b):
if (a, b) != p[a][b]:
p[a][b] = f(*p[a][b])
return p[a][b]
k = 0
fo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def swim_in_water(grid: List[List[int]]) -> int:
"""并查集 @param grid: @return:"""
<|body_0|>
def swim_in_water_v2(grid: List[List[int]]) -> int:
"""BFS @param grid: @return:"""
<|body_1|>
def swim_in_water_v3(grid: List[List[int]]) -> int:
... | stack_v2_sparse_classes_75kplus_train_004702 | 6,600 | no_license | [
{
"docstring": "并查集 @param grid: @return:",
"name": "swim_in_water",
"signature": "def swim_in_water(grid: List[List[int]]) -> int"
},
{
"docstring": "BFS @param grid: @return:",
"name": "swim_in_water_v2",
"signature": "def swim_in_water_v2(grid: List[List[int]]) -> int"
},
{
"d... | 4 | stack_v2_sparse_classes_30k_train_053241 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swim_in_water(grid: List[List[int]]) -> int: 并查集 @param grid: @return:
- def swim_in_water_v2(grid: List[List[int]]) -> int: BFS @param grid: @return:
- def swim_in_water_v3(... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swim_in_water(grid: List[List[int]]) -> int: 并查集 @param grid: @return:
- def swim_in_water_v2(grid: List[List[int]]) -> int: BFS @param grid: @return:
- def swim_in_water_v3(... | 1d1876620a55ff88af7bc390cf1a4fd4350d8d16 | <|skeleton|>
class Solution:
def swim_in_water(grid: List[List[int]]) -> int:
"""并查集 @param grid: @return:"""
<|body_0|>
def swim_in_water_v2(grid: List[List[int]]) -> int:
"""BFS @param grid: @return:"""
<|body_1|>
def swim_in_water_v3(grid: List[List[int]]) -> int:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def swim_in_water(grid: List[List[int]]) -> int:
"""并查集 @param grid: @return:"""
n = len(grid)
p = [[(i, j) for j in range(n)] for i in range(n)]
h = sorted([[grid[i][j], i, j] for j in range(n) for i in range(n)])
def f(a, b):
if (a, b) != p[a][b... | the_stack_v2_python_sparse | 02-算法思想/广度优先搜索/778.水位上升的泳池中游泳(H).py | jh-lau/leetcode_in_python | train | 0 | |
eaaab4cae440815408d56b7578f600c0e7d1b664 | [
"current_path = request.path\nfor path in self.white_list:\n if re.match(f'^{path}$', current_path):\n return\nelse:\n allowed_url = request.session.get('allowed_url')\n setattr(request, 'button_url', request.session.get('button_url'))\n for url in allowed_url:\n if re.match(f\"^{url.get('... | <|body_start_0|>
current_path = request.path
for path in self.white_list:
if re.match(f'^{path}$', current_path):
return
else:
allowed_url = request.session.get('allowed_url')
setattr(request, 'button_url', request.session.get('button_url'))
... | UrlAuth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UrlAuth:
def process_request(self, request):
"""权限控制"""
<|body_0|>
def process_response(self, request, response):
"""权限注入"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
current_path = request.path
for path in self.white_list:
if... | stack_v2_sparse_classes_75kplus_train_004703 | 2,723 | no_license | [
{
"docstring": "权限控制",
"name": "process_request",
"signature": "def process_request(self, request)"
},
{
"docstring": "权限注入",
"name": "process_response",
"signature": "def process_response(self, request, response)"
}
] | 2 | null | Implement the Python class `UrlAuth` described below.
Class description:
Implement the UrlAuth class.
Method signatures and docstrings:
- def process_request(self, request): 权限控制
- def process_response(self, request, response): 权限注入 | Implement the Python class `UrlAuth` described below.
Class description:
Implement the UrlAuth class.
Method signatures and docstrings:
- def process_request(self, request): 权限控制
- def process_response(self, request, response): 权限注入
<|skeleton|>
class UrlAuth:
def process_request(self, request):
"""权限控制... | 4cb8304cf5c9c3562d673b48bc51e24177709d26 | <|skeleton|>
class UrlAuth:
def process_request(self, request):
"""权限控制"""
<|body_0|>
def process_response(self, request, response):
"""权限注入"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UrlAuth:
def process_request(self, request):
"""权限控制"""
current_path = request.path
for path in self.white_list:
if re.match(f'^{path}$', current_path):
return
else:
allowed_url = request.session.get('allowed_url')
setattr(req... | the_stack_v2_python_sparse | Python项目/day70/luffy_permission-最初板/rbac/rbacmiddleware/auth.py | i3ef0xh4ck/mylearn | train | 0 | |
931b328fbaf30efd4dc3ac2ffe55b64c5bb4c7a6 | [
"HyppopySolver.__init__(self, project)\nself._searchspace = None\nself.candidates_list = list()",
"self._add_member('max_iterations', int)\nself._add_hyperparameter_signature(name='domain', dtype=str, options=['uniform', 'categorical'])\nself._add_hyperparameter_signature(name='data', dtype=list)\nself._add_hyper... | <|body_start_0|>
HyppopySolver.__init__(self, project)
self._searchspace = None
self.candidates_list = list()
<|end_body_0|>
<|body_start_1|>
self._add_member('max_iterations', int)
self._add_hyperparameter_signature(name='domain', dtype=str, options=['uniform', 'categorical'])
... | OptunaSolver | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptunaSolver:
def __init__(self, project=None):
"""The constructor accepts a HyppopyProject. :param project: [HyppopyProject] project instance, default=None"""
<|body_0|>
def define_interface(self):
"""This function is called when HyppopySolver.__init__ function fini... | stack_v2_sparse_classes_75kplus_train_004704 | 6,091 | no_license | [
{
"docstring": "The constructor accepts a HyppopyProject. :param project: [HyppopyProject] project instance, default=None",
"name": "__init__",
"signature": "def __init__(self, project=None)"
},
{
"docstring": "This function is called when HyppopySolver.__init__ function finished. Child classes ... | 6 | stack_v2_sparse_classes_30k_train_014598 | Implement the Python class `OptunaSolver` described below.
Class description:
Implement the OptunaSolver class.
Method signatures and docstrings:
- def __init__(self, project=None): The constructor accepts a HyppopyProject. :param project: [HyppopyProject] project instance, default=None
- def define_interface(self): ... | Implement the Python class `OptunaSolver` described below.
Class description:
Implement the OptunaSolver class.
Method signatures and docstrings:
- def __init__(self, project=None): The constructor accepts a HyppopyProject. :param project: [HyppopyProject] project instance, default=None
- def define_interface(self): ... | 254adacd6164aceca27794611f57a7ab82e4dc29 | <|skeleton|>
class OptunaSolver:
def __init__(self, project=None):
"""The constructor accepts a HyppopyProject. :param project: [HyppopyProject] project instance, default=None"""
<|body_0|>
def define_interface(self):
"""This function is called when HyppopySolver.__init__ function fini... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OptunaSolver:
def __init__(self, project=None):
"""The constructor accepts a HyppopyProject. :param project: [HyppopyProject] project instance, default=None"""
HyppopySolver.__init__(self, project)
self._searchspace = None
self.candidates_list = list()
def define_interface... | the_stack_v2_python_sparse | hyppopy/solvers/OptunaSolver.py | MIC-DKFZ/Hyppopy | train | 27 | |
9c6a67bf5bdd5f3c195ef9e08c1c459bd31b5679 | [
"super().__init__()\nself.linear = nn.Linear(inputs_size, output_size)\nself.sigmoid = nn.Sigmoid()",
"feat_inputs.names = ('B', 'N', 'E')\nfeat_inputs = feat_inputs.flatten(('N', 'E'), 'O')\noutputs = self.linear(feat_inputs.rename(None))\noutputs.names = ('B', 'O')\noutputs = self.sigmoid(outputs)\noutputs = ou... | <|body_start_0|>
super().__init__()
self.linear = nn.Linear(inputs_size, output_size)
self.sigmoid = nn.Sigmoid()
<|end_body_0|>
<|body_start_1|>
feat_inputs.names = ('B', 'N', 'E')
feat_inputs = feat_inputs.flatten(('N', 'E'), 'O')
outputs = self.linear(feat_inputs.rena... | Model class of Logistic Regression (LR). Logistic Regression is a model to predict click-through-rate with a simple logistic regression, i.e. a linear layer plus a sigmoid transformation to make the outcome between 0 and 1, which is to represent the probability of the input is true. | LogisticRegressionModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogisticRegressionModel:
"""Model class of Logistic Regression (LR). Logistic Regression is a model to predict click-through-rate with a simple logistic regression, i.e. a linear layer plus a sigmoid transformation to make the outcome between 0 and 1, which is to represent the probability of the ... | stack_v2_sparse_classes_75kplus_train_004705 | 2,049 | permissive | [
{
"docstring": "Initialize LogisticRegressionModel Args: inputs_size (int): inputs size of logistic regression, i.e. number of fields * embedding size output_size (int, optional): output size of model. Defaults to 1",
"name": "__init__",
"signature": "def __init__(self, inputs_size: int, output_size: Op... | 2 | stack_v2_sparse_classes_30k_train_043068 | Implement the Python class `LogisticRegressionModel` described below.
Class description:
Model class of Logistic Regression (LR). Logistic Regression is a model to predict click-through-rate with a simple logistic regression, i.e. a linear layer plus a sigmoid transformation to make the outcome between 0 and 1, which ... | Implement the Python class `LogisticRegressionModel` described below.
Class description:
Model class of Logistic Regression (LR). Logistic Regression is a model to predict click-through-rate with a simple logistic regression, i.e. a linear layer plus a sigmoid transformation to make the outcome between 0 and 1, which ... | 751a43b9cd35e951d81c0d9cf46507b1777bb7ff | <|skeleton|>
class LogisticRegressionModel:
"""Model class of Logistic Regression (LR). Logistic Regression is a model to predict click-through-rate with a simple logistic regression, i.e. a linear layer plus a sigmoid transformation to make the outcome between 0 and 1, which is to represent the probability of the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LogisticRegressionModel:
"""Model class of Logistic Regression (LR). Logistic Regression is a model to predict click-through-rate with a simple logistic regression, i.e. a linear layer plus a sigmoid transformation to make the outcome between 0 and 1, which is to represent the probability of the input is true... | the_stack_v2_python_sparse | torecsys/models/ctr/logistic_regression.py | p768lwy3/torecsys | train | 98 |
a12335a9bb9918b1572134e482985aff5a84aa69 | [
"try:\n if request.GET.get('answer_id'):\n queryset = Answers.objects.get(id=request.GET.get('answer_id'))\n answer = AnswerSerializer(queryset, context={'current_user_id': _id})\n return Utils.dispatch_success(OK, answer.data)\n elif request.GET.get('question_id'):\n queryset = An... | <|body_start_0|>
try:
if request.GET.get('answer_id'):
queryset = Answers.objects.get(id=request.GET.get('answer_id'))
answer = AnswerSerializer(queryset, context={'current_user_id': _id})
return Utils.dispatch_success(OK, answer.data)
elif... | Raise answers on Community | AnswerApi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnswerApi:
"""Raise answers on Community"""
def get(self, request, _id):
"""Get all answers from Community"""
<|body_0|>
def post(self, request, _id):
"""Create new answer against the question"""
<|body_1|>
def put(self, request, _id):
"""Upd... | stack_v2_sparse_classes_75kplus_train_004706 | 28,105 | no_license | [
{
"docstring": "Get all answers from Community",
"name": "get",
"signature": "def get(self, request, _id)"
},
{
"docstring": "Create new answer against the question",
"name": "post",
"signature": "def post(self, request, _id)"
},
{
"docstring": "Update answer against the question... | 4 | stack_v2_sparse_classes_30k_train_039496 | Implement the Python class `AnswerApi` described below.
Class description:
Raise answers on Community
Method signatures and docstrings:
- def get(self, request, _id): Get all answers from Community
- def post(self, request, _id): Create new answer against the question
- def put(self, request, _id): Update answer agai... | Implement the Python class `AnswerApi` described below.
Class description:
Raise answers on Community
Method signatures and docstrings:
- def get(self, request, _id): Get all answers from Community
- def post(self, request, _id): Create new answer against the question
- def put(self, request, _id): Update answer agai... | dbcf886a7cf2d2fb12400a0f1b3e85e8da5cd56b | <|skeleton|>
class AnswerApi:
"""Raise answers on Community"""
def get(self, request, _id):
"""Get all answers from Community"""
<|body_0|>
def post(self, request, _id):
"""Create new answer against the question"""
<|body_1|>
def put(self, request, _id):
"""Upd... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AnswerApi:
"""Raise answers on Community"""
def get(self, request, _id):
"""Get all answers from Community"""
try:
if request.GET.get('answer_id'):
queryset = Answers.objects.get(id=request.GET.get('answer_id'))
answer = AnswerSerializer(queryse... | the_stack_v2_python_sparse | Python/ixcoin_backend/api/community/views.py | ionixx-tech/ix_code_samples | train | 0 |
eb45e1de909dc8180932083f03207156ed5d7870 | [
"xml_tree = ET.fromstring(xmltext)\nxml_resp = dict()\nfor _ in xml_tree:\n xml_resp[_.tag] = _.text\nreturn xml_resp",
"item = '<item><Title>{p[0]}¥{p[3]} \\n{n}{p[1]}% {k}{m:.2f}</Title> \\n <Description>{p[1]}</Description>\\n <PicUrl>{p[2]}</PicUrl>\\n <Url>{p[2... | <|body_start_0|>
xml_tree = ET.fromstring(xmltext)
xml_resp = dict()
for _ in xml_tree:
xml_resp[_.tag] = _.text
return xml_resp
<|end_body_0|>
<|body_start_1|>
item = '<item><Title>{p[0]}¥{p[3]} \n{n}{p[1]}% {k}{m:.2f}</Title> \n <Description>{p[1]}</... | 提供提取消息格式中的密文及生成回复消息格式的接口 | XMLParse | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XMLParse:
"""提供提取消息格式中的密文及生成回复消息格式的接口"""
def extract(self, xmltext):
"""提取出xml数据包中的加密消息 @param xmltext: 待提取的xml字符串 @return: 节点与内容的dict"""
<|body_0|>
def generate(self, timestamp, **kwargs):
"""生成xml消息 :param timestamp: 时间戳 :param kwargs:用户发送过来的xml内容 :return: 回复消息... | stack_v2_sparse_classes_75kplus_train_004707 | 5,675 | no_license | [
{
"docstring": "提取出xml数据包中的加密消息 @param xmltext: 待提取的xml字符串 @return: 节点与内容的dict",
"name": "extract",
"signature": "def extract(self, xmltext)"
},
{
"docstring": "生成xml消息 :param timestamp: 时间戳 :param kwargs:用户发送过来的xml内容 :return: 回复消息的xml",
"name": "generate",
"signature": "def generate(sel... | 2 | null | Implement the Python class `XMLParse` described below.
Class description:
提供提取消息格式中的密文及生成回复消息格式的接口
Method signatures and docstrings:
- def extract(self, xmltext): 提取出xml数据包中的加密消息 @param xmltext: 待提取的xml字符串 @return: 节点与内容的dict
- def generate(self, timestamp, **kwargs): 生成xml消息 :param timestamp: 时间戳 :param kwargs:用户发送过... | Implement the Python class `XMLParse` described below.
Class description:
提供提取消息格式中的密文及生成回复消息格式的接口
Method signatures and docstrings:
- def extract(self, xmltext): 提取出xml数据包中的加密消息 @param xmltext: 待提取的xml字符串 @return: 节点与内容的dict
- def generate(self, timestamp, **kwargs): 生成xml消息 :param timestamp: 时间戳 :param kwargs:用户发送过... | a641db062d4f89055abd6e81e7cd0ba32134733e | <|skeleton|>
class XMLParse:
"""提供提取消息格式中的密文及生成回复消息格式的接口"""
def extract(self, xmltext):
"""提取出xml数据包中的加密消息 @param xmltext: 待提取的xml字符串 @return: 节点与内容的dict"""
<|body_0|>
def generate(self, timestamp, **kwargs):
"""生成xml消息 :param timestamp: 时间戳 :param kwargs:用户发送过来的xml内容 :return: 回复消息... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class XMLParse:
"""提供提取消息格式中的密文及生成回复消息格式的接口"""
def extract(self, xmltext):
"""提取出xml数据包中的加密消息 @param xmltext: 待提取的xml字符串 @return: 节点与内容的dict"""
xml_tree = ET.fromstring(xmltext)
xml_resp = dict()
for _ in xml_tree:
xml_resp[_.tag] = _.text
return xml_resp
... | the_stack_v2_python_sparse | Wx/wx_class/wxs.py | MAOA-L/Blog | train | 0 |
3d5589cd6cd4305fdb88ee242cd8c590d0b25607 | [
"expected_topic = 'www.example.com'\nexpected_message = 'PROBLEM (Average) alert on [www.example.com](https://zabbix.example.com/tr_events.php?triggerid=14032&eventid=10528):\\n* Zabbix agent on www.example.com is unreachable for 5 minutes\\n* Agent ping is Up (1)'\nself.check_webhook('zabbix_alert', expected_topic... | <|body_start_0|>
expected_topic = 'www.example.com'
expected_message = 'PROBLEM (Average) alert on [www.example.com](https://zabbix.example.com/tr_events.php?triggerid=14032&eventid=10528):\n* Zabbix agent on www.example.com is unreachable for 5 minutes\n* Agent ping is Up (1)'
self.check_webhoo... | ZabbixHookTests | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZabbixHookTests:
def test_zabbix_alert_message(self) -> None:
"""Tests if zabbix alert is handled correctly"""
<|body_0|>
def test_zabbix_invalid_payload_with_missing_data(self) -> None:
"""Tests if invalid Zabbix payloads are handled correctly"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_004708 | 1,635 | permissive | [
{
"docstring": "Tests if zabbix alert is handled correctly",
"name": "test_zabbix_alert_message",
"signature": "def test_zabbix_alert_message(self) -> None"
},
{
"docstring": "Tests if invalid Zabbix payloads are handled correctly",
"name": "test_zabbix_invalid_payload_with_missing_data",
... | 2 | stack_v2_sparse_classes_30k_train_006834 | Implement the Python class `ZabbixHookTests` described below.
Class description:
Implement the ZabbixHookTests class.
Method signatures and docstrings:
- def test_zabbix_alert_message(self) -> None: Tests if zabbix alert is handled correctly
- def test_zabbix_invalid_payload_with_missing_data(self) -> None: Tests if ... | Implement the Python class `ZabbixHookTests` described below.
Class description:
Implement the ZabbixHookTests class.
Method signatures and docstrings:
- def test_zabbix_alert_message(self) -> None: Tests if zabbix alert is handled correctly
- def test_zabbix_invalid_payload_with_missing_data(self) -> None: Tests if ... | 965a25d91b6ee2db54038f5df855215fa25146b0 | <|skeleton|>
class ZabbixHookTests:
def test_zabbix_alert_message(self) -> None:
"""Tests if zabbix alert is handled correctly"""
<|body_0|>
def test_zabbix_invalid_payload_with_missing_data(self) -> None:
"""Tests if invalid Zabbix payloads are handled correctly"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ZabbixHookTests:
def test_zabbix_alert_message(self) -> None:
"""Tests if zabbix alert is handled correctly"""
expected_topic = 'www.example.com'
expected_message = 'PROBLEM (Average) alert on [www.example.com](https://zabbix.example.com/tr_events.php?triggerid=14032&eventid=10528):\n*... | the_stack_v2_python_sparse | zerver/webhooks/zabbix/tests.py | zulip/zulip | train | 20,239 | |
05d5ba533381fee995087a656975281a62bc8b17 | [
"cost_matrix = np.array([[[4, 1, 3], [2, 0, 5], [3, 2, 2]]], dtype=np.float32)\n_, adjacency_matrix = matchers.hungarian_matching(tf.constant(cost_matrix))\nadjacency_output = adjacency_matrix.numpy()\ncorrect_output = np.array([[0, 1, 0], [1, 0, 0], [0, 0, 1]], dtype=bool)\nself.assertAllEqual(adjacency_output[0],... | <|body_start_0|>
cost_matrix = np.array([[[4, 1, 3], [2, 0, 5], [3, 2, 2]]], dtype=np.float32)
_, adjacency_matrix = matchers.hungarian_matching(tf.constant(cost_matrix))
adjacency_output = adjacency_matrix.numpy()
correct_output = np.array([[0, 1, 0], [1, 0, 0], [0, 0, 1]], dtype=bool)
... | MatchersOpsTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MatchersOpsTest:
def testLinearSumAssignment(self):
"""Check a simple 2D test case of the Linear Sum Assignment problem. Ensures that the implementation of the matching algorithm is correct and functional on TPUs."""
<|body_0|>
def testBatchedLinearSumAssignment(self):
... | stack_v2_sparse_classes_75kplus_train_004709 | 3,439 | permissive | [
{
"docstring": "Check a simple 2D test case of the Linear Sum Assignment problem. Ensures that the implementation of the matching algorithm is correct and functional on TPUs.",
"name": "testLinearSumAssignment",
"signature": "def testLinearSumAssignment(self)"
},
{
"docstring": "Check a batched ... | 4 | stack_v2_sparse_classes_30k_train_006740 | Implement the Python class `MatchersOpsTest` described below.
Class description:
Implement the MatchersOpsTest class.
Method signatures and docstrings:
- def testLinearSumAssignment(self): Check a simple 2D test case of the Linear Sum Assignment problem. Ensures that the implementation of the matching algorithm is co... | Implement the Python class `MatchersOpsTest` described below.
Class description:
Implement the MatchersOpsTest class.
Method signatures and docstrings:
- def testLinearSumAssignment(self): Check a simple 2D test case of the Linear Sum Assignment problem. Ensures that the implementation of the matching algorithm is co... | d3507b550a3ade40cade60a79eb5b8978b56c7ae | <|skeleton|>
class MatchersOpsTest:
def testLinearSumAssignment(self):
"""Check a simple 2D test case of the Linear Sum Assignment problem. Ensures that the implementation of the matching algorithm is correct and functional on TPUs."""
<|body_0|>
def testBatchedLinearSumAssignment(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MatchersOpsTest:
def testLinearSumAssignment(self):
"""Check a simple 2D test case of the Linear Sum Assignment problem. Ensures that the implementation of the matching algorithm is correct and functional on TPUs."""
cost_matrix = np.array([[[4, 1, 3], [2, 0, 5], [3, 2, 2]]], dtype=np.float32)... | the_stack_v2_python_sparse | official/projects/detr/ops/matchers_test.py | jianzhnie/models | train | 2 | |
f79227895895befb9d6477caac884e53171e7c28 | [
"super().__init__(parent, Qt.FramelessWindowHint | Qt.WindowSystemMenuHint)\nself.question = str(question)\nself.style = style\nself.initUi()",
"self.questionLabel = QLabel(self.question)\nself.questionLabel.setWordWrap(True)\nstyleBtn = '\\n QPushButton {\\n font-family: Asap;\\n fon... | <|body_start_0|>
super().__init__(parent, Qt.FramelessWindowHint | Qt.WindowSystemMenuHint)
self.question = str(question)
self.style = style
self.initUi()
<|end_body_0|>
<|body_start_1|>
self.questionLabel = QLabel(self.question)
self.questionLabel.setWordWrap(True)
... | Dialog to ask a question. | QuestionDialog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionDialog:
"""Dialog to ask a question."""
def __init__(self, parent, question, style=None):
"""Init."""
<|body_0|>
def initUi(self):
"""Ui Setup."""
<|body_1|>
def paintEvent(self, event):
"""Set window background color."""
<|bo... | stack_v2_sparse_classes_75kplus_train_004710 | 27,111 | no_license | [
{
"docstring": "Init.",
"name": "__init__",
"signature": "def __init__(self, parent, question, style=None)"
},
{
"docstring": "Ui Setup.",
"name": "initUi",
"signature": "def initUi(self)"
},
{
"docstring": "Set window background color.",
"name": "paintEvent",
"signature"... | 3 | stack_v2_sparse_classes_30k_train_010899 | Implement the Python class `QuestionDialog` described below.
Class description:
Dialog to ask a question.
Method signatures and docstrings:
- def __init__(self, parent, question, style=None): Init.
- def initUi(self): Ui Setup.
- def paintEvent(self, event): Set window background color. | Implement the Python class `QuestionDialog` described below.
Class description:
Dialog to ask a question.
Method signatures and docstrings:
- def __init__(self, parent, question, style=None): Init.
- def initUi(self): Ui Setup.
- def paintEvent(self, event): Set window background color.
<|skeleton|>
class QuestionDi... | a5d18593e689123cac34af552628ed2818ca5d59 | <|skeleton|>
class QuestionDialog:
"""Dialog to ask a question."""
def __init__(self, parent, question, style=None):
"""Init."""
<|body_0|>
def initUi(self):
"""Ui Setup."""
<|body_1|>
def paintEvent(self, event):
"""Set window background color."""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QuestionDialog:
"""Dialog to ask a question."""
def __init__(self, parent, question, style=None):
"""Init."""
super().__init__(parent, Qt.FramelessWindowHint | Qt.WindowSystemMenuHint)
self.question = str(question)
self.style = style
self.initUi()
def initUi(s... | the_stack_v2_python_sparse | Dialogs.py | edgary777/lonchepos | train | 0 |
c379c42b025cc2675e18ac2b5199cd5978dd7eb0 | [
"def f(*args, **kwargs):\n if_return_label = module.return_label\n module.return_label = False\n out = module(*args, **kwargs)\n module.return_label = if_return_label\n return out\nreturn f",
"if param is not None:\n _param = param.data\nelse:\n _param = None\nif isinstance(module, (Geometric... | <|body_start_0|>
def f(*args, **kwargs):
if_return_label = module.return_label
module.return_label = False
out = module(*args, **kwargs)
module.return_label = if_return_label
return out
return f
<|end_body_0|>
<|body_start_1|>
if param... | Apply and inverse transformations for mask tensors. | MaskApplyInverse | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaskApplyInverse:
"""Apply and inverse transformations for mask tensors."""
def make_input_only_sequential(cls, module: 'kornia.augmentation.ImageSequential') -> Callable:
"""Disable all other additional inputs (e.g. ) for ImageSequential."""
<|body_0|>
def apply_trans(c... | stack_v2_sparse_classes_75kplus_train_004711 | 24,042 | permissive | [
{
"docstring": "Disable all other additional inputs (e.g. ) for ImageSequential.",
"name": "make_input_only_sequential",
"signature": "def make_input_only_sequential(cls, module: 'kornia.augmentation.ImageSequential') -> Callable"
},
{
"docstring": "Apply a transformation with respect to the par... | 3 | stack_v2_sparse_classes_30k_val_000665 | Implement the Python class `MaskApplyInverse` described below.
Class description:
Apply and inverse transformations for mask tensors.
Method signatures and docstrings:
- def make_input_only_sequential(cls, module: 'kornia.augmentation.ImageSequential') -> Callable: Disable all other additional inputs (e.g. ) for Imag... | Implement the Python class `MaskApplyInverse` described below.
Class description:
Apply and inverse transformations for mask tensors.
Method signatures and docstrings:
- def make_input_only_sequential(cls, module: 'kornia.augmentation.ImageSequential') -> Callable: Disable all other additional inputs (e.g. ) for Imag... | 03ab49feb075149c0df65d47cdb91d563b8980e2 | <|skeleton|>
class MaskApplyInverse:
"""Apply and inverse transformations for mask tensors."""
def make_input_only_sequential(cls, module: 'kornia.augmentation.ImageSequential') -> Callable:
"""Disable all other additional inputs (e.g. ) for ImageSequential."""
<|body_0|>
def apply_trans(c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MaskApplyInverse:
"""Apply and inverse transformations for mask tensors."""
def make_input_only_sequential(cls, module: 'kornia.augmentation.ImageSequential') -> Callable:
"""Disable all other additional inputs (e.g. ) for ImageSequential."""
def f(*args, **kwargs):
if_return_... | the_stack_v2_python_sparse | kornia/augmentation/container/utils.py | timgates42/kornia | train | 0 |
acd0bc0cc66c416df26241f5a8fd54ffbe0e8f9e | [
"t = parse_tree(\"(('foo' : 0.1, 'bar' : 1.0) : 2, baz)\")\nself.assertEqual(len(t.get_edges()), 2)\n(t1, b1, l1), (t2, b2, l2) = t.get_edges()\nself.assertEqual(len(t1.get_edges()), 2)\nself.assertEqual(l1, 2.0)\nself.assertEqual(t2.__class__, Leaf)\nself.assertEqual(l2, None)\nself.assertEqual(t.leaves_identifier... | <|body_start_0|>
t = parse_tree("(('foo' : 0.1, 'bar' : 1.0) : 2, baz)")
self.assertEqual(len(t.get_edges()), 2)
(t1, b1, l1), (t2, b2, l2) = t.get_edges()
self.assertEqual(len(t1.get_edges()), 2)
self.assertEqual(l1, 2.0)
self.assertEqual(t2.__class__, Leaf)
self... | Test of the parse_tree() function. | TestParseTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestParseTree:
"""Test of the parse_tree() function."""
def testTreeStructure(self):
"""Test that a parsed tree has the right structure."""
<|body_0|>
def testSpecialCases(self):
"""Test that we can parse some special cases of trees."""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus_train_004712 | 4,457 | no_license | [
{
"docstring": "Test that a parsed tree has the right structure.",
"name": "testTreeStructure",
"signature": "def testTreeStructure(self)"
},
{
"docstring": "Test that we can parse some special cases of trees.",
"name": "testSpecialCases",
"signature": "def testSpecialCases(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017595 | Implement the Python class `TestParseTree` described below.
Class description:
Test of the parse_tree() function.
Method signatures and docstrings:
- def testTreeStructure(self): Test that a parsed tree has the right structure.
- def testSpecialCases(self): Test that we can parse some special cases of trees. | Implement the Python class `TestParseTree` described below.
Class description:
Test of the parse_tree() function.
Method signatures and docstrings:
- def testTreeStructure(self): Test that a parsed tree has the right structure.
- def testSpecialCases(self): Test that we can parse some special cases of trees.
<|skele... | 40979405a43703506b84925b26bb9d2c7c9c021b | <|skeleton|>
class TestParseTree:
"""Test of the parse_tree() function."""
def testTreeStructure(self):
"""Test that a parsed tree has the right structure."""
<|body_0|>
def testSpecialCases(self):
"""Test that we can parse some special cases of trees."""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestParseTree:
"""Test of the parse_tree() function."""
def testTreeStructure(self):
"""Test that a parsed tree has the right structure."""
t = parse_tree("(('foo' : 0.1, 'bar' : 1.0) : 2, baz)")
self.assertEqual(len(t.get_edges()), 2)
(t1, b1, l1), (t2, b2, l2) = t.get_ed... | the_stack_v2_python_sparse | newick_modified/treetest.py | dtneves/SuperFine | train | 7 |
19ca179baa9faa3f4bcb283b3bcb7a1a14509a0a | [
"s = self.get(section, option).strip()\nif s:\n return [i.strip() for i in s.split(separator)]\nelse:\n return []",
"try:\n return self.get(section, option)\nexcept (NoSectionError, NoOptionError):\n return default",
"try:\n return self.getboolean(section, option)\nexcept (NoSectionError, NoOptio... | <|body_start_0|>
s = self.get(section, option).strip()
if s:
return [i.strip() for i in s.split(separator)]
else:
return []
<|end_body_0|>
<|body_start_1|>
try:
return self.get(section, option)
except (NoSectionError, NoOptionError):
... | Extended ``ConfigParser``. | BravoConfigParser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BravoConfigParser:
"""Extended ``ConfigParser``."""
def getlist(self, section, option, separator=','):
"""Coerce an option to a list, and retrieve it."""
<|body_0|>
def getdefault(self, section, option, default):
"""Retrieve an option, or a default value."""
... | stack_v2_sparse_classes_75kplus_train_004713 | 1,835 | permissive | [
{
"docstring": "Coerce an option to a list, and retrieve it.",
"name": "getlist",
"signature": "def getlist(self, section, option, separator=',')"
},
{
"docstring": "Retrieve an option, or a default value.",
"name": "getdefault",
"signature": "def getdefault(self, section, option, defaul... | 5 | null | Implement the Python class `BravoConfigParser` described below.
Class description:
Extended ``ConfigParser``.
Method signatures and docstrings:
- def getlist(self, section, option, separator=','): Coerce an option to a list, and retrieve it.
- def getdefault(self, section, option, default): Retrieve an option, or a d... | Implement the Python class `BravoConfigParser` described below.
Class description:
Extended ``ConfigParser``.
Method signatures and docstrings:
- def getlist(self, section, option, separator=','): Coerce an option to a list, and retrieve it.
- def getdefault(self, section, option, default): Retrieve an option, or a d... | ced04cdd0c6e57c99eacf9d0677877e15fddb78c | <|skeleton|>
class BravoConfigParser:
"""Extended ``ConfigParser``."""
def getlist(self, section, option, separator=','):
"""Coerce an option to a list, and retrieve it."""
<|body_0|>
def getdefault(self, section, option, default):
"""Retrieve an option, or a default value."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BravoConfigParser:
"""Extended ``ConfigParser``."""
def getlist(self, section, option, separator=','):
"""Coerce an option to a list, and retrieve it."""
s = self.get(section, option).strip()
if s:
return [i.strip() for i in s.split(separator)]
else:
... | the_stack_v2_python_sparse | bravo/config.py | Smallergamer/bravo | train | 1 |
3244790ad4990bed68e8acafdb4f5be1d19d0e46 | [
"self.last_error = 10000000\nself.best_result = 1000000\nself.start = start\nfirst_anfis_list = []\nself.teaching_inputs = teaching_inputs\nfor i in range(anfis_num):\n new_anfis = Anfis(*start)\n first_anfis_list.append(new_anfis)\nself.best_anfis = first_anfis_list[0]\npopulation = first_anfis_list\nwhile s... | <|body_start_0|>
self.last_error = 10000000
self.best_result = 1000000
self.start = start
first_anfis_list = []
self.teaching_inputs = teaching_inputs
for i in range(anfis_num):
new_anfis = Anfis(*start)
first_anfis_list.append(new_anfis)
s... | Genetic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Genetic:
def __init__(self, teaching_inputs, anfis_num, start):
"""Save in self.best_anfis ANFIS net which give the best answers :param teaching_inputs: list of teaching inputs [[[1. input, 2. input...], output], [...]] :param anfis_num: Number of ANFIS nets using in genetic teaching :pa... | stack_v2_sparse_classes_75kplus_train_004714 | 12,715 | no_license | [
{
"docstring": "Save in self.best_anfis ANFIS net which give the best answers :param teaching_inputs: list of teaching inputs [[[1. input, 2. input...], output], [...]] :param anfis_num: Number of ANFIS nets using in genetic teaching :param start: starts params of ANIFS net [inputs_len, rules, Tnorm, down_range... | 6 | stack_v2_sparse_classes_30k_train_042505 | Implement the Python class `Genetic` described below.
Class description:
Implement the Genetic class.
Method signatures and docstrings:
- def __init__(self, teaching_inputs, anfis_num, start): Save in self.best_anfis ANFIS net which give the best answers :param teaching_inputs: list of teaching inputs [[[1. input, 2.... | Implement the Python class `Genetic` described below.
Class description:
Implement the Genetic class.
Method signatures and docstrings:
- def __init__(self, teaching_inputs, anfis_num, start): Save in self.best_anfis ANFIS net which give the best answers :param teaching_inputs: list of teaching inputs [[[1. input, 2.... | 6c1d58ea4773c633c45f065b7ef52268d3319762 | <|skeleton|>
class Genetic:
def __init__(self, teaching_inputs, anfis_num, start):
"""Save in self.best_anfis ANFIS net which give the best answers :param teaching_inputs: list of teaching inputs [[[1. input, 2. input...], output], [...]] :param anfis_num: Number of ANFIS nets using in genetic teaching :pa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Genetic:
def __init__(self, teaching_inputs, anfis_num, start):
"""Save in self.best_anfis ANFIS net which give the best answers :param teaching_inputs: list of teaching inputs [[[1. input, 2. input...], output], [...]] :param anfis_num: Number of ANFIS nets using in genetic teaching :param start: sta... | the_stack_v2_python_sparse | anfis.py | KatarzynaStudzinska/declib | train | 0 | |
07e377ef7c1eaf2e9d0dcca0f9631dc41c7833c2 | [
"if p == q:\n return True\nif not p or not q or p.val != q.val:\n return False\nreturn self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)",
"if p and q:\n return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)\nreturn p is q"
] | <|body_start_0|>
if p == q:
return True
if not p or not q or 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 p and q:
return p.val == q.val and self.isSameTre... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSameTree(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool"""
<|body_0|>
def isSameTree2(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if p == q:
... | stack_v2_sparse_classes_75kplus_train_004715 | 1,090 | no_license | [
{
"docstring": ":type p: TreeNode :type q: TreeNode :rtype: bool",
"name": "isSameTree",
"signature": "def isSameTree(self, p, q)"
},
{
"docstring": ":type p: TreeNode :type q: TreeNode :rtype: bool",
"name": "isSameTree2",
"signature": "def isSameTree2(self, p, q)"
}
] | 2 | stack_v2_sparse_classes_30k_train_053576 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSameTree(self, p, q): :type p: TreeNode :type q: TreeNode :rtype: bool
- def isSameTree2(self, p, q): :type p: TreeNode :type q: TreeNode :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSameTree(self, p, q): :type p: TreeNode :type q: TreeNode :rtype: bool
- def isSameTree2(self, p, q): :type p: TreeNode :type q: TreeNode :rtype: bool
<|skeleton|>
class S... | 4a1747b6497305f3821612d9c358a6795b1690da | <|skeleton|>
class Solution:
def isSameTree(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool"""
<|body_0|>
def isSameTree2(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isSameTree(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool"""
if p == q:
return True
if not p or not q or p.val != q.val:
return False
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
def is... | the_stack_v2_python_sparse | BinaryTree/q100_same_tree.py | sevenhe716/LeetCode | train | 0 | |
acb777c2ff5a5791040833d86d9349c5ceed71ad | [
"try:\n params = request._serialize()\n headers = request.headers\n body = self.call('CreateDataRepositoryTask', params, headers=headers)\n response = json.loads(body)\n model = models.CreateDataRepositoryTaskResponse()\n model._deserialize(response['Response'])\n return model\nexcept Exception... | <|body_start_0|>
try:
params = request._serialize()
headers = request.headers
body = self.call('CreateDataRepositoryTask', params, headers=headers)
response = json.loads(body)
model = models.CreateDataRepositoryTaskResponse()
model._deseria... | GoosefsClient | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoosefsClient:
def CreateDataRepositoryTask(self, request):
"""创建数据流通任务,包括从将文件系统的数据上传到存储桶下, 以及从存储桶下载到文件系统里。 :param request: Request instance for CreateDataRepositoryTask. :type request: :class:`tencentcloud.goosefs.v20220519.models.CreateDataRepositoryTaskRequest` :rtype: :class:`tencent... | stack_v2_sparse_classes_75kplus_train_004716 | 5,830 | permissive | [
{
"docstring": "创建数据流通任务,包括从将文件系统的数据上传到存储桶下, 以及从存储桶下载到文件系统里。 :param request: Request instance for CreateDataRepositoryTask. :type request: :class:`tencentcloud.goosefs.v20220519.models.CreateDataRepositoryTaskRequest` :rtype: :class:`tencentcloud.goosefs.v20220519.models.CreateDataRepositoryTaskResponse`",
... | 5 | stack_v2_sparse_classes_30k_train_035622 | Implement the Python class `GoosefsClient` described below.
Class description:
Implement the GoosefsClient class.
Method signatures and docstrings:
- def CreateDataRepositoryTask(self, request): 创建数据流通任务,包括从将文件系统的数据上传到存储桶下, 以及从存储桶下载到文件系统里。 :param request: Request instance for CreateDataRepositoryTask. :type request: ... | Implement the Python class `GoosefsClient` described below.
Class description:
Implement the GoosefsClient class.
Method signatures and docstrings:
- def CreateDataRepositoryTask(self, request): 创建数据流通任务,包括从将文件系统的数据上传到存储桶下, 以及从存储桶下载到文件系统里。 :param request: Request instance for CreateDataRepositoryTask. :type request: ... | 505014e84bdea7e2732296821028df20c0305390 | <|skeleton|>
class GoosefsClient:
def CreateDataRepositoryTask(self, request):
"""创建数据流通任务,包括从将文件系统的数据上传到存储桶下, 以及从存储桶下载到文件系统里。 :param request: Request instance for CreateDataRepositoryTask. :type request: :class:`tencentcloud.goosefs.v20220519.models.CreateDataRepositoryTaskRequest` :rtype: :class:`tencent... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GoosefsClient:
def CreateDataRepositoryTask(self, request):
"""创建数据流通任务,包括从将文件系统的数据上传到存储桶下, 以及从存储桶下载到文件系统里。 :param request: Request instance for CreateDataRepositoryTask. :type request: :class:`tencentcloud.goosefs.v20220519.models.CreateDataRepositoryTaskRequest` :rtype: :class:`tencentcloud.goosefs.... | the_stack_v2_python_sparse | codespace/python/tencentcloud/goosefs/v20220519/goosefs_client.py | tzpBingo/github-trending | train | 49 | |
84c76c81293ffc58bc4143dc38a820744c5cb5f3 | [
"super().__init__()\nself.bn = nn.BatchNorm2d(in_channels)\nself.relu = nn.ReLU(inplace=True)\nself.conv = conv3x3(in_channels, growth_rate, **kwargs)\nself.drop_rate = drop_rate",
"out = self.bn(x)\nout = self.relu(out)\nout = self.conv(out)\nif self.drop_rate > 0:\n out = F.dropout(out, p=self.drop_rate, tra... | <|body_start_0|>
super().__init__()
self.bn = nn.BatchNorm2d(in_channels)
self.relu = nn.ReLU(inplace=True)
self.conv = conv3x3(in_channels, growth_rate, **kwargs)
self.drop_rate = drop_rate
<|end_body_0|>
<|body_start_1|>
out = self.bn(x)
out = self.relu(out)
... | Basic block | BasicBlock | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicBlock:
"""Basic block"""
def __init__(self, in_channels, growth_rate=12, drop_rate=0, **kwargs):
"""CTOR. Args: in_channels(int) expansion(int) growth_rate(int): the k value drop_rate(float): the dropout rate"""
<|body_0|>
def forward(self, x):
"""forward"""... | stack_v2_sparse_classes_75kplus_train_004717 | 6,722 | permissive | [
{
"docstring": "CTOR. Args: in_channels(int) expansion(int) growth_rate(int): the k value drop_rate(float): the dropout rate",
"name": "__init__",
"signature": "def __init__(self, in_channels, growth_rate=12, drop_rate=0, **kwargs)"
},
{
"docstring": "forward",
"name": "forward",
"signat... | 2 | null | Implement the Python class `BasicBlock` described below.
Class description:
Basic block
Method signatures and docstrings:
- def __init__(self, in_channels, growth_rate=12, drop_rate=0, **kwargs): CTOR. Args: in_channels(int) expansion(int) growth_rate(int): the k value drop_rate(float): the dropout rate
- def forward... | Implement the Python class `BasicBlock` described below.
Class description:
Basic block
Method signatures and docstrings:
- def __init__(self, in_channels, growth_rate=12, drop_rate=0, **kwargs): CTOR. Args: in_channels(int) expansion(int) growth_rate(int): the k value drop_rate(float): the dropout rate
- def forward... | f81c417d3754102c902bd153809130e12607bd7d | <|skeleton|>
class BasicBlock:
"""Basic block"""
def __init__(self, in_channels, growth_rate=12, drop_rate=0, **kwargs):
"""CTOR. Args: in_channels(int) expansion(int) growth_rate(int): the k value drop_rate(float): the dropout rate"""
<|body_0|>
def forward(self, x):
"""forward"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BasicBlock:
"""Basic block"""
def __init__(self, in_channels, growth_rate=12, drop_rate=0, **kwargs):
"""CTOR. Args: in_channels(int) expansion(int) growth_rate(int): the k value drop_rate(float): the dropout rate"""
super().__init__()
self.bn = nn.BatchNorm2d(in_channels)
... | the_stack_v2_python_sparse | gumi/models/densenet.py | kumasento/gconv-prune | train | 10 |
77beaa7bd4c490cf4948c4ca25bb5d3c25483a9d | [
"super(EditVendorDialog, self).__init__(parent=parent)\nself.setupUi(self)\nself.dbsession = Session()\nself.selected_vendor = None\nvendor_names = [result.name for result in self.dbsession.query(Vendor.name).filter(Vendor.name != 'Amazon')]\nself.vendorBox.addItems(vendor_names)\nself.accepted.connect(self.update_... | <|body_start_0|>
super(EditVendorDialog, self).__init__(parent=parent)
self.setupUi(self)
self.dbsession = Session()
self.selected_vendor = None
vendor_names = [result.name for result in self.dbsession.query(Vendor.name).filter(Vendor.name != 'Amazon')]
self.vendorBox.add... | A dialog that provides viewing and editing for Vendor features. | EditVendorDialog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EditVendorDialog:
"""A dialog that provides viewing and editing for Vendor features."""
def __init__(self, default=None, parent=None):
"""Initialize the widgets with info from the vendor specified by default. Default is a name."""
<|body_0|>
def on_vendor_changed(self):
... | stack_v2_sparse_classes_75kplus_train_004718 | 25,458 | no_license | [
{
"docstring": "Initialize the widgets with info from the vendor specified by default. Default is a name.",
"name": "__init__",
"signature": "def __init__(self, default=None, parent=None)"
},
{
"docstring": "Update the widgets with the info from the newly selected vendor.",
"name": "on_vendo... | 3 | stack_v2_sparse_classes_30k_train_012322 | Implement the Python class `EditVendorDialog` described below.
Class description:
A dialog that provides viewing and editing for Vendor features.
Method signatures and docstrings:
- def __init__(self, default=None, parent=None): Initialize the widgets with info from the vendor specified by default. Default is a name.... | Implement the Python class `EditVendorDialog` described below.
Class description:
A dialog that provides viewing and editing for Vendor features.
Method signatures and docstrings:
- def __init__(self, default=None, parent=None): Initialize the widgets with info from the vendor specified by default. Default is a name.... | 7d22707a1782125d86140c52d20eaadd2df6e4fc | <|skeleton|>
class EditVendorDialog:
"""A dialog that provides viewing and editing for Vendor features."""
def __init__(self, default=None, parent=None):
"""Initialize the widgets with info from the vendor specified by default. Default is a name."""
<|body_0|>
def on_vendor_changed(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EditVendorDialog:
"""A dialog that provides viewing and editing for Vendor features."""
def __init__(self, default=None, parent=None):
"""Initialize the widgets with info from the vendor specified by default. Default is a name."""
super(EditVendorDialog, self).__init__(parent=parent)
... | the_stack_v2_python_sparse | dialogs.py | garrettmk/Prowler | train | 1 |
c00fe289eb2b02751a4404bf79361e1a4a5837bc | [
"try:\n sport = self.kwargs['sport']\nexcept KeyError:\n sport = 'nba'\nsite_sport_manager = sports.classes.SiteSportManager()\ninjury_serializer_class = site_sport_manager.get_tsxplayer_serializer_class(sport)\nreturn injury_serializer_class",
"sport = self.kwargs['sport']\nsite_sport_manager = sports.clas... | <|body_start_0|>
try:
sport = self.kwargs['sport']
except KeyError:
sport = 'nba'
site_sport_manager = sports.classes.SiteSportManager()
injury_serializer_class = site_sport_manager.get_tsxplayer_serializer_class(sport)
return injury_serializer_class
<|end... | gets the news for the sport | TsxPlayerItemsAPIView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TsxPlayerItemsAPIView:
"""gets the news for the sport"""
def get_serializer_class(self):
"""override for having to set the self.serializer_class"""
<|body_0|>
def get_queryset(self):
"""Return a QuerySet from the LobbyContest model."""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_004719 | 26,966 | no_license | [
{
"docstring": "override for having to set the self.serializer_class",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "Return a QuerySet from the LobbyContest model.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_032367 | Implement the Python class `TsxPlayerItemsAPIView` described below.
Class description:
gets the news for the sport
Method signatures and docstrings:
- def get_serializer_class(self): override for having to set the self.serializer_class
- def get_queryset(self): Return a QuerySet from the LobbyContest model. | Implement the Python class `TsxPlayerItemsAPIView` described below.
Class description:
gets the news for the sport
Method signatures and docstrings:
- def get_serializer_class(self): override for having to set the self.serializer_class
- def get_queryset(self): Return a QuerySet from the LobbyContest model.
<|skelet... | 4796fa9d88b56f80def011e2b043ce595bfce8c4 | <|skeleton|>
class TsxPlayerItemsAPIView:
"""gets the news for the sport"""
def get_serializer_class(self):
"""override for having to set the self.serializer_class"""
<|body_0|>
def get_queryset(self):
"""Return a QuerySet from the LobbyContest model."""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TsxPlayerItemsAPIView:
"""gets the news for the sport"""
def get_serializer_class(self):
"""override for having to set the self.serializer_class"""
try:
sport = self.kwargs['sport']
except KeyError:
sport = 'nba'
site_sport_manager = sports.classes.... | the_stack_v2_python_sparse | sports/views.py | nakamotohideyoshi/draftboard-web | train | 0 |
0e3743dd91e8fe63ada2dd64e4c62730675f2494 | [
"Barrier.__init__(self)\nself.batch_size: int = batch_size\nself.keep_incomplete_batch: bool = keep_incomplete_batch\nself.default_value_data_inputs: Union[Any, StripAbsentValues] = default_value_data_inputs\nself.default_value_expected_outputs: Union[Any, StripAbsentValues] = default_value_expected_outputs",
"co... | <|body_start_0|>
Barrier.__init__(self)
self.batch_size: int = batch_size
self.keep_incomplete_batch: bool = keep_incomplete_batch
self.default_value_data_inputs: Union[Any, StripAbsentValues] = default_value_data_inputs
self.default_value_expected_outputs: Union[Any, StripAbsent... | The Joiner step joins the transformed mini batches together with mostly the DACT.minibatches and then DACT.extend method. It is used in a minibatch sequential pipeline and streaming / queued pipeline as a way to handle batches of previous steps in the pipeline. .. seealso:: :class:`~neuraxle.data_container.DataContaine... | Joiner | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Joiner:
"""The Joiner step joins the transformed mini batches together with mostly the DACT.minibatches and then DACT.extend method. It is used in a minibatch sequential pipeline and streaming / queued pipeline as a way to handle batches of previous steps in the pipeline. .. seealso:: :class:`~ne... | stack_v2_sparse_classes_75kplus_train_004720 | 26,376 | permissive | [
{
"docstring": "The Joiner step joins the transformed mini batches together with DACT.minibatches and then DACT.extend method. Note that the default value for IDs is None. .. seealso:: :class:`~neuraxle.data_container.DataContainer`, :func:`~neuraxle.data_container.DataContainer.minibatches`",
"name": "__in... | 3 | stack_v2_sparse_classes_30k_train_032795 | Implement the Python class `Joiner` described below.
Class description:
The Joiner step joins the transformed mini batches together with mostly the DACT.minibatches and then DACT.extend method. It is used in a minibatch sequential pipeline and streaming / queued pipeline as a way to handle batches of previous steps in... | Implement the Python class `Joiner` described below.
Class description:
The Joiner step joins the transformed mini batches together with mostly the DACT.minibatches and then DACT.extend method. It is used in a minibatch sequential pipeline and streaming / queued pipeline as a way to handle batches of previous steps in... | af917c984241178436a759be3b830e6d8b03245f | <|skeleton|>
class Joiner:
"""The Joiner step joins the transformed mini batches together with mostly the DACT.minibatches and then DACT.extend method. It is used in a minibatch sequential pipeline and streaming / queued pipeline as a way to handle batches of previous steps in the pipeline. .. seealso:: :class:`~ne... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Joiner:
"""The Joiner step joins the transformed mini batches together with mostly the DACT.minibatches and then DACT.extend method. It is used in a minibatch sequential pipeline and streaming / queued pipeline as a way to handle batches of previous steps in the pipeline. .. seealso:: :class:`~neuraxle.data_c... | the_stack_v2_python_sparse | neuraxle/pipeline.py | Neuraxio/Neuraxle | train | 597 |
56234c132cf3bfaed65114ab2f75fabac8fd342b | [
"res = {}\nfor attr in dir(self):\n if attr.startswith('_'):\n continue\n value = getattr(self, attr)\n if value is None or isinstance(value, Callable):\n continue\n if isinstance(value, _Opts_t):\n if (_val := value.to_dict()):\n res[attr] = _val\n else:\n res[... | <|body_start_0|>
res = {}
for attr in dir(self):
if attr.startswith('_'):
continue
value = getattr(self, attr)
if value is None or isinstance(value, Callable):
continue
if isinstance(value, _Opts_t):
if (_val... | _Opts_t | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Opts_t:
def to_dict(self) -> dict:
"""Convert a config object to a dictionary, skip keys that are not set"""
<|body_0|>
def to_flat_dict(self) -> dict:
"""Transform options object into a flat dictionary. Returns: dict: dictionary maps the namespace"""
<|body... | stack_v2_sparse_classes_75kplus_train_004721 | 5,128 | permissive | [
{
"docstring": "Convert a config object to a dictionary, skip keys that are not set",
"name": "to_dict",
"signature": "def to_dict(self) -> dict"
},
{
"docstring": "Transform options object into a flat dictionary. Returns: dict: dictionary maps the namespace",
"name": "to_flat_dict",
"si... | 2 | null | Implement the Python class `_Opts_t` described below.
Class description:
Implement the _Opts_t class.
Method signatures and docstrings:
- def to_dict(self) -> dict: Convert a config object to a dictionary, skip keys that are not set
- def to_flat_dict(self) -> dict: Transform options object into a flat dictionary. Re... | Implement the Python class `_Opts_t` described below.
Class description:
Implement the _Opts_t class.
Method signatures and docstrings:
- def to_dict(self) -> dict: Convert a config object to a dictionary, skip keys that are not set
- def to_flat_dict(self) -> dict: Transform options object into a flat dictionary. Re... | 4645704e18767051905d821447f6f211c55475f6 | <|skeleton|>
class _Opts_t:
def to_dict(self) -> dict:
"""Convert a config object to a dictionary, skip keys that are not set"""
<|body_0|>
def to_flat_dict(self) -> dict:
"""Transform options object into a flat dictionary. Returns: dict: dictionary maps the namespace"""
<|body... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _Opts_t:
def to_dict(self) -> dict:
"""Convert a config object to a dictionary, skip keys that are not set"""
res = {}
for attr in dir(self):
if attr.startswith('_'):
continue
value = getattr(self, attr)
if value is None or isinstance... | the_stack_v2_python_sparse | xtp/src/pyxtp/pyxtp/options.py | votca/votca | train | 54 | |
3ac85c52648c16149df7cedc01d084d65c78f9eb | [
"if self.feature in self.FEATURES_MAPPING:\n self.feature = self.FEATURES_MAPPING[self.feature]\nif 'type' in additional_data:\n self.feature_type = additional_data['type']",
"name = self.function_name\nif self.feature_type:\n name = '%s for %s' % (name, self.feature_type)\nreturn name",
"features = se... | <|body_start_0|>
if self.feature in self.FEATURES_MAPPING:
self.feature = self.FEATURES_MAPPING[self.feature]
if 'type' in additional_data:
self.feature_type = additional_data['type']
<|end_body_0|>
<|body_start_1|>
name = self.function_name
if self.feature_type:... | AbstractOverpassInsightFunction | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbstractOverpassInsightFunction:
def initiate(self, additional_data):
"""Initiate function :param additional_data: additional data that needed :type additional_data:dict"""
<|body_0|>
def name(self):
"""Name of insight functions :return: string of name"""
<|b... | stack_v2_sparse_classes_75kplus_train_004722 | 2,354 | permissive | [
{
"docstring": "Initiate function :param additional_data: additional data that needed :type additional_data:dict",
"name": "initiate",
"signature": "def initiate(self, additional_data)"
},
{
"docstring": "Name of insight functions :return: string of name",
"name": "name",
"signature": "d... | 3 | stack_v2_sparse_classes_30k_train_021277 | Implement the Python class `AbstractOverpassInsightFunction` described below.
Class description:
Implement the AbstractOverpassInsightFunction class.
Method signatures and docstrings:
- def initiate(self, additional_data): Initiate function :param additional_data: additional data that needed :type additional_data:dic... | Implement the Python class `AbstractOverpassInsightFunction` described below.
Class description:
Implement the AbstractOverpassInsightFunction class.
Method signatures and docstrings:
- def initiate(self, additional_data): Initiate function :param additional_data: additional data that needed :type additional_data:dic... | 53d448b8d558e88df5710a672a76ef1f9c983e57 | <|skeleton|>
class AbstractOverpassInsightFunction:
def initiate(self, additional_data):
"""Initiate function :param additional_data: additional data that needed :type additional_data:dict"""
<|body_0|>
def name(self):
"""Name of insight functions :return: string of name"""
<|b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AbstractOverpassInsightFunction:
def initiate(self, additional_data):
"""Initiate function :param additional_data: additional data that needed :type additional_data:dict"""
if self.feature in self.FEATURES_MAPPING:
self.feature = self.FEATURES_MAPPING[self.feature]
if 'type... | the_stack_v2_python_sparse | flask_project/campaign_manager/insights_functions/_abstract_overpass_insight_function.py | russbiggs/MapCampaigner | train | 0 | |
2b0f838b4e422c360cb469cda38229ed68f1666b | [
"self.lexicon_type = lexicon_type\nself.lexicon = self.setup(lexicon_file)\nself.lib_path = '../../lib/emotion_lexicon/'",
"lines = [line.strip('\\n') for line in open(lexicon_file, 'r')]\nif self.lexicon_type in self.KW:\n return lines\nfor item in lines[0].split('\\t')[1:]:\n self.emo2idx[item] = len(self... | <|body_start_0|>
self.lexicon_type = lexicon_type
self.lexicon = self.setup(lexicon_file)
self.lib_path = '../../lib/emotion_lexicon/'
<|end_body_0|>
<|body_start_1|>
lines = [line.strip('\n') for line in open(lexicon_file, 'r')]
if self.lexicon_type in self.KW:
retu... | EmoLexicon | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmoLexicon:
def __init__(self, lexicon_file, lexicon_type):
"""Initialize this class with the lexicon file :param lexicon_file: the given emotion lexicon"""
<|body_0|>
def setup(self, lexicon_file):
"""Set up the emotion to index mapping and strip newlines from lexic... | stack_v2_sparse_classes_75kplus_train_004723 | 4,426 | no_license | [
{
"docstring": "Initialize this class with the lexicon file :param lexicon_file: the given emotion lexicon",
"name": "__init__",
"signature": "def __init__(self, lexicon_file, lexicon_type)"
},
{
"docstring": "Set up the emotion to index mapping and strip newlines from lexicon lines :param lexic... | 5 | stack_v2_sparse_classes_30k_train_026866 | Implement the Python class `EmoLexicon` described below.
Class description:
Implement the EmoLexicon class.
Method signatures and docstrings:
- def __init__(self, lexicon_file, lexicon_type): Initialize this class with the lexicon file :param lexicon_file: the given emotion lexicon
- def setup(self, lexicon_file): Se... | Implement the Python class `EmoLexicon` described below.
Class description:
Implement the EmoLexicon class.
Method signatures and docstrings:
- def __init__(self, lexicon_file, lexicon_type): Initialize this class with the lexicon file :param lexicon_file: the given emotion lexicon
- def setup(self, lexicon_file): Se... | 1da8f7fb76cb9f193d3c262b07434f32caeefc09 | <|skeleton|>
class EmoLexicon:
def __init__(self, lexicon_file, lexicon_type):
"""Initialize this class with the lexicon file :param lexicon_file: the given emotion lexicon"""
<|body_0|>
def setup(self, lexicon_file):
"""Set up the emotion to index mapping and strip newlines from lexic... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EmoLexicon:
def __init__(self, lexicon_file, lexicon_type):
"""Initialize this class with the lexicon file :param lexicon_file: the given emotion lexicon"""
self.lexicon_type = lexicon_type
self.lexicon = self.setup(lexicon_file)
self.lib_path = '../../lib/emotion_lexicon/'
... | the_stack_v2_python_sparse | src/preprocessing/build_lexicon.py | jmcanal/BECR | train | 2 | |
82f6371687c791a20cb208bfa446eacbca444765 | [
"dict = {'pseudo': pseudo}\nrequete = requests.post(properties.host_ws + RESOURCE_joueurs_PATH + '/tester_pseudo/' + pseudo, json=dict, headers=header)\nres_requete = 3\nif requete.status_code == 402:\n res_requete = 1\nelif requete.status_code == 200:\n res_requete = 2\nelif requete.status_code == 401:\n ... | <|body_start_0|>
dict = {'pseudo': pseudo}
requete = requests.post(properties.host_ws + RESOURCE_joueurs_PATH + '/tester_pseudo/' + pseudo, json=dict, headers=header)
res_requete = 3
if requete.status_code == 402:
res_requete = 1
elif requete.status_code == 200:
... | RequeteCreerCompte | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RequeteCreerCompte:
def TesterPseudo(pseudo):
"""Envoie le pseudo au web service pour l'ajouter en base :param pseudo: le pseudo à ajouer :type pseudo: str :return: Si l'insertion s'est bien passée :rtype: bool"""
<|body_0|>
def CreerCompte(pseudo, mdp):
"""Envoie le... | stack_v2_sparse_classes_75kplus_train_004724 | 1,727 | no_license | [
{
"docstring": "Envoie le pseudo au web service pour l'ajouter en base :param pseudo: le pseudo à ajouer :type pseudo: str :return: Si l'insertion s'est bien passée :rtype: bool",
"name": "TesterPseudo",
"signature": "def TesterPseudo(pseudo)"
},
{
"docstring": "Envoie les informations sur le jo... | 2 | stack_v2_sparse_classes_30k_train_040128 | Implement the Python class `RequeteCreerCompte` described below.
Class description:
Implement the RequeteCreerCompte class.
Method signatures and docstrings:
- def TesterPseudo(pseudo): Envoie le pseudo au web service pour l'ajouter en base :param pseudo: le pseudo à ajouer :type pseudo: str :return: Si l'insertion s... | Implement the Python class `RequeteCreerCompte` described below.
Class description:
Implement the RequeteCreerCompte class.
Method signatures and docstrings:
- def TesterPseudo(pseudo): Envoie le pseudo au web service pour l'ajouter en base :param pseudo: le pseudo à ajouer :type pseudo: str :return: Si l'insertion s... | 17aaf28b7c51dadb1f184c700343400f778fc61d | <|skeleton|>
class RequeteCreerCompte:
def TesterPseudo(pseudo):
"""Envoie le pseudo au web service pour l'ajouter en base :param pseudo: le pseudo à ajouer :type pseudo: str :return: Si l'insertion s'est bien passée :rtype: bool"""
<|body_0|>
def CreerCompte(pseudo, mdp):
"""Envoie le... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RequeteCreerCompte:
def TesterPseudo(pseudo):
"""Envoie le pseudo au web service pour l'ajouter en base :param pseudo: le pseudo à ajouer :type pseudo: str :return: Si l'insertion s'est bien passée :rtype: bool"""
dict = {'pseudo': pseudo}
requete = requests.post(properties.host_ws + R... | the_stack_v2_python_sparse | client/requetes/requete_creer_compte.py | walid-creator/api_touratour | train | 0 | |
54ebebd9743d02d1010166895bb95a2b63a8a954 | [
"self.safe_update(**kwargs)\nif butler is not None:\n self.log.warn('Ignoring butler in extract()')\ndtables = stack_summary_table(data, self, tablename='outliers', keep_cols=['nbad_total', 'nbad_rows', 'nbad_cols', 'slot', 'amp'])\nreturn dtables",
"self.safe_update(**kwargs)\nconfig_table = get_run_config_ta... | <|body_start_0|>
self.safe_update(**kwargs)
if butler is not None:
self.log.warn('Ignoring butler in extract()')
dtables = stack_summary_table(data, self, tablename='outliers', keep_cols=['nbad_total', 'nbad_rows', 'nbad_cols', 'slot', 'amp'])
return dtables
<|end_body_0|>
<... | Summarize the results for the superbias outlier analysis | SuperdarkOutlierSummaryTask | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SuperdarkOutlierSummaryTask:
"""Summarize the results for the superbias outlier analysis"""
def extract(self, butler, data, **kwargs):
"""Make a summry table of the bias FFT data Parameters ---------- butler : `Butler` The data butler data : `dict` Dictionary (or other structure) con... | stack_v2_sparse_classes_75kplus_train_004725 | 14,784 | permissive | [
{
"docstring": "Make a summry table of the bias FFT data Parameters ---------- butler : `Butler` The data butler data : `dict` Dictionary (or other structure) contain the input data kwargs Used to override default configuration Returns ------- dtables : `TableDict` The resulting data",
"name": "extract",
... | 2 | stack_v2_sparse_classes_30k_train_014588 | Implement the Python class `SuperdarkOutlierSummaryTask` described below.
Class description:
Summarize the results for the superbias outlier analysis
Method signatures and docstrings:
- def extract(self, butler, data, **kwargs): Make a summry table of the bias FFT data Parameters ---------- butler : `Butler` The data... | Implement the Python class `SuperdarkOutlierSummaryTask` described below.
Class description:
Summarize the results for the superbias outlier analysis
Method signatures and docstrings:
- def extract(self, butler, data, **kwargs): Make a summry table of the bias FFT data Parameters ---------- butler : `Butler` The data... | 28418284fdaf2b2fb0afbeccd4324f7ad3e676c8 | <|skeleton|>
class SuperdarkOutlierSummaryTask:
"""Summarize the results for the superbias outlier analysis"""
def extract(self, butler, data, **kwargs):
"""Make a summry table of the bias FFT data Parameters ---------- butler : `Butler` The data butler data : `dict` Dictionary (or other structure) con... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SuperdarkOutlierSummaryTask:
"""Summarize the results for the superbias outlier analysis"""
def extract(self, butler, data, **kwargs):
"""Make a summry table of the bias FFT data Parameters ---------- butler : `Butler` The data butler data : `dict` Dictionary (or other structure) contain the inpu... | the_stack_v2_python_sparse | python/lsst/eo_utils/dark/superdark.py | lsst-camera-dh/EO-utilities | train | 2 |
1c7fa37203c520a8bd8bf4932e6e9adb19168e4d | [
"if not instance.data.get('stripNamespaces', False):\n self.log.debug('Skipping because strip namespaces is disabled..')\n return\ninvalid = self.get_invalid(instance)\nif invalid:\n raise RuntimeError('Clashing nodes found: {0}'.format(invalid))",
"nodes = instance.data.get('outMembersHierarchy', instan... | <|body_start_0|>
if not instance.data.get('stripNamespaces', False):
self.log.debug('Skipping because strip namespaces is disabled..')
return
invalid = self.get_invalid(instance)
if invalid:
raise RuntimeError('Clashing nodes found: {0}'.format(invalid))
<|end... | Validate nodes names do not clash when stripping namespaces. Node names need to be unique under the same parent when "strip namespaces" is enabled for the instance. This validates nodes have unique names when written without their namespaces. For example: Invalid: A namespace:A Invalid: char:group|char:A char:group|A I... | ValidateClashingNodeNames | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidateClashingNodeNames:
"""Validate nodes names do not clash when stripping namespaces. Node names need to be unique under the same parent when "strip namespaces" is enabled for the instance. This validates nodes have unique names when written without their namespaces. For example: Invalid: A ... | stack_v2_sparse_classes_75kplus_train_004726 | 2,516 | no_license | [
{
"docstring": "Process all meshes",
"name": "process",
"signature": "def process(self, instance)"
},
{
"docstring": "Get all nodes which do not match the criteria",
"name": "get_invalid",
"signature": "def get_invalid(cls, instance)"
}
] | 2 | null | Implement the Python class `ValidateClashingNodeNames` described below.
Class description:
Validate nodes names do not clash when stripping namespaces. Node names need to be unique under the same parent when "strip namespaces" is enabled for the instance. This validates nodes have unique names when written without the... | Implement the Python class `ValidateClashingNodeNames` described below.
Class description:
Validate nodes names do not clash when stripping namespaces. Node names need to be unique under the same parent when "strip namespaces" is enabled for the instance. This validates nodes have unique names when written without the... | fa1a22297c1b2cfd48c88372958360fe4004524b | <|skeleton|>
class ValidateClashingNodeNames:
"""Validate nodes names do not clash when stripping namespaces. Node names need to be unique under the same parent when "strip namespaces" is enabled for the instance. This validates nodes have unique names when written without their namespaces. For example: Invalid: A ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ValidateClashingNodeNames:
"""Validate nodes names do not clash when stripping namespaces. Node names need to be unique under the same parent when "strip namespaces" is enabled for the instance. This validates nodes have unique names when written without their namespaces. For example: Invalid: A namespace:A I... | the_stack_v2_python_sparse | colorbleed/plugins/maya/publish/validate_clashing_node_names.py | BigRoy/colorbleed-config | train | 3 |
2ee833376f246fbdeec7a258ba70303425a5cb02 | [
"start_state = SolverState()\nresult = start_state.is_consistent(example_statement)\nassert result == example_small_solverstate",
"start_state = SolverState((frozenset({Role.VILLAGER}),) * 3, path=(True,))\ninvalid_state = start_state.is_consistent(example_statement)\nassert invalid_state is None",
"possible_ro... | <|body_start_0|>
start_state = SolverState()
result = start_state.is_consistent(example_statement)
assert result == example_small_solverstate
<|end_body_0|>
<|body_start_1|>
start_state = SolverState((frozenset({Role.VILLAGER}),) * 3, path=(True,))
invalid_state = start_state.is... | Tests for the is_consistent function. | TestIsConsistent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestIsConsistent:
"""Tests for the is_consistent function."""
def test_is_consistent_on_empty_state(example_small_solverstate: SolverState, example_statement: Statement) -> None:
"""Should check a new statement against an empty SolverState for consistency."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_004727 | 11,042 | permissive | [
{
"docstring": "Should check a new statement against an empty SolverState for consistency.",
"name": "test_is_consistent_on_empty_state",
"signature": "def test_is_consistent_on_empty_state(example_small_solverstate: SolverState, example_statement: Statement) -> None"
},
{
"docstring": "Should r... | 4 | null | Implement the Python class `TestIsConsistent` described below.
Class description:
Tests for the is_consistent function.
Method signatures and docstrings:
- def test_is_consistent_on_empty_state(example_small_solverstate: SolverState, example_statement: Statement) -> None: Should check a new statement against an empty... | Implement the Python class `TestIsConsistent` described below.
Class description:
Tests for the is_consistent function.
Method signatures and docstrings:
- def test_is_consistent_on_empty_state(example_small_solverstate: SolverState, example_statement: Statement) -> None: Should check a new statement against an empty... | 6e91c2f24e72f9374c4f703bd966963ea6626e8e | <|skeleton|>
class TestIsConsistent:
"""Tests for the is_consistent function."""
def test_is_consistent_on_empty_state(example_small_solverstate: SolverState, example_statement: Statement) -> None:
"""Should check a new statement against an empty SolverState for consistency."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestIsConsistent:
"""Tests for the is_consistent function."""
def test_is_consistent_on_empty_state(example_small_solverstate: SolverState, example_statement: Statement) -> None:
"""Should check a new statement against an empty SolverState for consistency."""
start_state = SolverState()
... | the_stack_v2_python_sparse | unit_test/solvers_test.py | srijan-deepsource/wolfbot | train | 0 |
7af02a9507876043e574509e761369d30e4ecab8 | [
"if not self.is_authenticated:\n return False\nif self.is_super_admin or self.is_admin:\n return True\nreturn False",
"user = self.request.user\nif self.is_super_admin:\n ctx = {'institutions': Institution.objects.order_by('id').all(), 'logohost': admin_settings.OSF_URL}\n return self.render_to_respon... | <|body_start_0|>
if not self.is_authenticated:
return False
if self.is_super_admin or self.is_admin:
return True
return False
<|end_body_0|>
<|body_start_1|>
user = self.request.user
if self.is_super_admin:
ctx = {'institutions': Institution.o... | View for the Institution Summary Screen | InstitutionListView | [
"Apache-2.0",
"LGPL-2.0-or-later",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"MIT",
"AGPL-3.0-only",
"LicenseRef-scancode-unknown-license-reference",
"MPL-1.1",
"CPAL-1.0",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstitutionListView:
"""View for the Institution Summary Screen"""
def test_func(self):
"""check user permissions"""
<|body_0|>
def get(self, request, *args, **kwargs):
"""get contexts"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not self.... | stack_v2_sparse_classes_75kplus_train_004728 | 7,365 | permissive | [
{
"docstring": "check user permissions",
"name": "test_func",
"signature": "def test_func(self)"
},
{
"docstring": "get contexts",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002323 | Implement the Python class `InstitutionListView` described below.
Class description:
View for the Institution Summary Screen
Method signatures and docstrings:
- def test_func(self): check user permissions
- def get(self, request, *args, **kwargs): get contexts | Implement the Python class `InstitutionListView` described below.
Class description:
View for the Institution Summary Screen
Method signatures and docstrings:
- def test_func(self): check user permissions
- def get(self, request, *args, **kwargs): get contexts
<|skeleton|>
class InstitutionListView:
"""View for ... | 5d632eb6d4566d7d31cd8d6b40d1bc93c60ddf5e | <|skeleton|>
class InstitutionListView:
"""View for the Institution Summary Screen"""
def test_func(self):
"""check user permissions"""
<|body_0|>
def get(self, request, *args, **kwargs):
"""get contexts"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InstitutionListView:
"""View for the Institution Summary Screen"""
def test_func(self):
"""check user permissions"""
if not self.is_authenticated:
return False
if self.is_super_admin or self.is_admin:
return True
return False
def get(self, requ... | the_stack_v2_python_sparse | admin/rdm_addons/views.py | RCOSDP/RDM-osf.io | train | 12 |
4111fdec3727b08d197a9f54d8da5a3e7b5233fe | [
"super(ICMNetwork, self).__init__()\nself.state_rep_size = model_dict.state_representation[-1]\ninput_dim = prod(observation_space.shape)\nself.state_rep = build_sequential(input_dim, model_dict.state_representation)\ninverse_model_hiddens = model_dict.inverse_model\ninverse_model_hiddens.append(action_size)\nself.... | <|body_start_0|>
super(ICMNetwork, self).__init__()
self.state_rep_size = model_dict.state_representation[-1]
input_dim = prod(observation_space.shape)
self.state_rep = build_sequential(input_dim, model_dict.state_representation)
inverse_model_hiddens = model_dict.inverse_model
... | Intrinsic curiosity module (ICM) network | ICMNetwork | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ICMNetwork:
"""Intrinsic curiosity module (ICM) network"""
def __init__(self, observation_space, action_size, model_dict):
"""Initialize parameters and build model. :param observation_space: space of each observation :param action_size: dimension of each action :param model_dict: dic... | stack_v2_sparse_classes_75kplus_train_004729 | 2,133 | no_license | [
{
"docstring": "Initialize parameters and build model. :param observation_space: space of each observation :param action_size: dimension of each action :param model_dict: dictionary for model configuration",
"name": "__init__",
"signature": "def __init__(self, observation_space, action_size, model_dict)... | 2 | null | Implement the Python class `ICMNetwork` described below.
Class description:
Intrinsic curiosity module (ICM) network
Method signatures and docstrings:
- def __init__(self, observation_space, action_size, model_dict): Initialize parameters and build model. :param observation_space: space of each observation :param act... | Implement the Python class `ICMNetwork` described below.
Class description:
Intrinsic curiosity module (ICM) network
Method signatures and docstrings:
- def __init__(self, observation_space, action_size, model_dict): Initialize parameters and build model. :param observation_space: space of each observation :param act... | 87c0855046d3ea10272f3078ac1c766efae46089 | <|skeleton|>
class ICMNetwork:
"""Intrinsic curiosity module (ICM) network"""
def __init__(self, observation_space, action_size, model_dict):
"""Initialize parameters and build model. :param observation_space: space of each observation :param action_size: dimension of each action :param model_dict: dic... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ICMNetwork:
"""Intrinsic curiosity module (ICM) network"""
def __init__(self, observation_space, action_size, model_dict):
"""Initialize parameters and build model. :param observation_space: space of each observation :param action_size: dimension of each action :param model_dict: dictionary for m... | the_stack_v2_python_sparse | derl/intrinsic_rewards/icm/model.py | stjordanis/derl-2 | train | 0 |
8d3767b711a7d7b15486529f21f8ad54453d622a | [
"self.distance = distance\nself.pid_foward = PID(distance, 0.01, 0.0001, 0.01, 500, -500, 0.7, -0.7)\nself.pid_yaw = PID(0, 0.33, 0.0, 0.33, 500, -500, 100, -100)\nself.pid_angle = PID(0.0, 0.01, 0.0, 0.01, 500, -500, 0.3, -0.3)\nself.pid_height = PID(0.0, 0.002, 0.0002, 0.002, 500, -500, 0.3, -0.2)\ncflib.crtp.ini... | <|body_start_0|>
self.distance = distance
self.pid_foward = PID(distance, 0.01, 0.0001, 0.01, 500, -500, 0.7, -0.7)
self.pid_yaw = PID(0, 0.33, 0.0, 0.33, 500, -500, 100, -100)
self.pid_angle = PID(0.0, 0.01, 0.0, 0.01, 500, -500, 0.3, -0.3)
self.pid_height = PID(0.0, 0.002, 0.00... | Aruco_tracker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Aruco_tracker:
def __init__(self, distance):
"""Inicialização dos drivers, parâmetros do controle PID e decolagem do drone."""
<|body_0|>
def search_marker(self):
"""Interrompe o movimento se nao encontrar o marcador por tres frames consecutivos. Após 4 segundos, ini... | stack_v2_sparse_classes_75kplus_train_004730 | 3,942 | no_license | [
{
"docstring": "Inicialização dos drivers, parâmetros do controle PID e decolagem do drone.",
"name": "__init__",
"signature": "def __init__(self, distance)"
},
{
"docstring": "Interrompe o movimento se nao encontrar o marcador por tres frames consecutivos. Após 4 segundos, inicia movimento de r... | 4 | stack_v2_sparse_classes_30k_train_023057 | Implement the Python class `Aruco_tracker` described below.
Class description:
Implement the Aruco_tracker class.
Method signatures and docstrings:
- def __init__(self, distance): Inicialização dos drivers, parâmetros do controle PID e decolagem do drone.
- def search_marker(self): Interrompe o movimento se nao encon... | Implement the Python class `Aruco_tracker` described below.
Class description:
Implement the Aruco_tracker class.
Method signatures and docstrings:
- def __init__(self, distance): Inicialização dos drivers, parâmetros do controle PID e decolagem do drone.
- def search_marker(self): Interrompe o movimento se nao encon... | 8af0ca6930b326ae7bc0cd7bb9aa2d6aa62bceeb | <|skeleton|>
class Aruco_tracker:
def __init__(self, distance):
"""Inicialização dos drivers, parâmetros do controle PID e decolagem do drone."""
<|body_0|>
def search_marker(self):
"""Interrompe o movimento se nao encontrar o marcador por tres frames consecutivos. Após 4 segundos, ini... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Aruco_tracker:
def __init__(self, distance):
"""Inicialização dos drivers, parâmetros do controle PID e decolagem do drone."""
self.distance = distance
self.pid_foward = PID(distance, 0.01, 0.0001, 0.01, 500, -500, 0.7, -0.7)
self.pid_yaw = PID(0, 0.33, 0.0, 0.33, 500, -500, 10... | the_stack_v2_python_sparse | Código-fonte/Esquadrilha/aruco_tracker_pid.py | EvoSystems-com-br/IniciacaoCientifica2018_ProjetoDrones | train | 0 | |
6c1e26425d4865392e5b3caf9c5f52d0dd67d276 | [
"self.name = name\nself.legal_entity_id = legal_entity_id\nself.original_hire_date = original_hire_date\nself.latest_hire_date = latest_hire_date\nself.employment_end_date = employment_end_date\nself.address = address\nself.employment_status_code = employment_status_code\nself.employment_status_name = employment_st... | <|body_start_0|>
self.name = name
self.legal_entity_id = legal_entity_id
self.original_hire_date = original_hire_date
self.latest_hire_date = latest_hire_date
self.employment_end_date = employment_end_date
self.address = address
self.employment_status_code = emplo... | Implementation of the 'Payroll Employer Record' model. TODO: type model description here. Attributes: name (string): Name of the employer as stated by the employer in the payroll system. legal_entity_id (string): Employer identification number (EIN) original_hire_date (long|int): The original hired date of an employee ... | PayrollEmployerRecord | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PayrollEmployerRecord:
"""Implementation of the 'Payroll Employer Record' model. TODO: type model description here. Attributes: name (string): Name of the employer as stated by the employer in the payroll system. legal_entity_id (string): Employer identification number (EIN) original_hire_date (l... | stack_v2_sparse_classes_75kplus_train_004731 | 5,502 | permissive | [
{
"docstring": "Constructor for the PayrollEmployerRecord class",
"name": "__init__",
"signature": "def __init__(self, name=None, legal_entity_id=None, original_hire_date=None, latest_hire_date=None, employment_end_date=None, address=None, employment_status_code=None, employment_status_name=None, work_l... | 2 | stack_v2_sparse_classes_30k_train_053728 | Implement the Python class `PayrollEmployerRecord` described below.
Class description:
Implementation of the 'Payroll Employer Record' model. TODO: type model description here. Attributes: name (string): Name of the employer as stated by the employer in the payroll system. legal_entity_id (string): Employer identifica... | Implement the Python class `PayrollEmployerRecord` described below.
Class description:
Implementation of the 'Payroll Employer Record' model. TODO: type model description here. Attributes: name (string): Name of the employer as stated by the employer in the payroll system. legal_entity_id (string): Employer identifica... | b2ab1ded435db75c78d42261f5e4acd2a3061487 | <|skeleton|>
class PayrollEmployerRecord:
"""Implementation of the 'Payroll Employer Record' model. TODO: type model description here. Attributes: name (string): Name of the employer as stated by the employer in the payroll system. legal_entity_id (string): Employer identification number (EIN) original_hire_date (l... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PayrollEmployerRecord:
"""Implementation of the 'Payroll Employer Record' model. TODO: type model description here. Attributes: name (string): Name of the employer as stated by the employer in the payroll system. legal_entity_id (string): Employer identification number (EIN) original_hire_date (long|int): The... | the_stack_v2_python_sparse | finicityapi/models/payroll_employer_record.py | monarchmoney/finicity-python | train | 0 |
c21f72cd2aa1c6f6ccf9b3da5b556ae1f5f02f3e | [
"self.args = args\nself.kws = kws\nif not hasattr(config, 'auth_obj') and (not auth_obj):\n raise ValueError('You must specify auth_obj in config argument')\nif auth_obj:\n self.auth_obj = auth_obj\nelse:\n self.auth_obj = config.auth_obj\nself.check_func = check_func",
"self.func = func\n\ndef execute(m... | <|body_start_0|>
self.args = args
self.kws = kws
if not hasattr(config, 'auth_obj') and (not auth_obj):
raise ValueError('You must specify auth_obj in config argument')
if auth_obj:
self.auth_obj = auth_obj
else:
self.auth_obj = config.auth_obj... | A decorator that catch method access, check authentication, redirect is authentication needs. You may decorate handler methods in controllers like this:: @authenticate() def some_funk(self): # your code here... | authenticate | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class authenticate:
"""A decorator that catch method access, check authentication, redirect is authentication needs. You may decorate handler methods in controllers like this:: @authenticate() def some_funk(self): # your code here..."""
def __init__(self, check_func=None, auth_obj=None, *args, **k... | stack_v2_sparse_classes_75kplus_train_004732 | 8,941 | permissive | [
{
"docstring": "An initialization method of decorator. The auth_obj argument is a object to perform authentication function. If auth_obj is given, __call__() uses it instead of one in config object. Otherwise, it uses default authentication given in config object. The check_funk argument is a hook method called... | 2 | stack_v2_sparse_classes_30k_train_019539 | Implement the Python class `authenticate` described below.
Class description:
A decorator that catch method access, check authentication, redirect is authentication needs. You may decorate handler methods in controllers like this:: @authenticate() def some_funk(self): # your code here...
Method signatures and docstri... | Implement the Python class `authenticate` described below.
Class description:
A decorator that catch method access, check authentication, redirect is authentication needs. You may decorate handler methods in controllers like this:: @authenticate() def some_funk(self): # your code here...
Method signatures and docstri... | e1209f7d44d1c59ff9d373b7d89d414f31a9c28b | <|skeleton|>
class authenticate:
"""A decorator that catch method access, check authentication, redirect is authentication needs. You may decorate handler methods in controllers like this:: @authenticate() def some_funk(self): # your code here..."""
def __init__(self, check_func=None, auth_obj=None, *args, **k... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class authenticate:
"""A decorator that catch method access, check authentication, redirect is authentication needs. You may decorate handler methods in controllers like this:: @authenticate() def some_funk(self): # your code here..."""
def __init__(self, check_func=None, auth_obj=None, *args, **kws):
... | the_stack_v2_python_sparse | aha/controller/decorator.py | Letractively/aha-gae | train | 0 |
685db71c0fef3f4318c1bd110c1f328200b023c5 | [
"super(FunctionComponent, self).__init__(opts)\nself.options = opts.get('fn_hibp', {})\nself.PROXIES = {}\nPROXY_HTTP = self.get_config_option('hibp_proxy_http', True)\nPROXY_HTTPS = self.get_config_option('hibp_proxy_https', True)\nif PROXY_HTTP is not None:\n self.PROXIES['http'] = PROXY_HTTP\nif PROXY_HTTPS i... | <|body_start_0|>
super(FunctionComponent, self).__init__(opts)
self.options = opts.get('fn_hibp', {})
self.PROXIES = {}
PROXY_HTTP = self.get_config_option('hibp_proxy_http', True)
PROXY_HTTPS = self.get_config_option('hibp_proxy_https', True)
if PROXY_HTTP is not None:
... | Component that implements Resilient function 'have_i_been_pwned_get_pastes | FunctionComponent | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FunctionComponent:
"""Component that implements Resilient function 'have_i_been_pwned_get_pastes"""
def __init__(self, opts):
"""constructor provides access to the configuration options"""
<|body_0|>
def get_config_option(self, option_name, optional=False):
"""Gi... | stack_v2_sparse_classes_75kplus_train_004733 | 3,804 | permissive | [
{
"docstring": "constructor provides access to the configuration options",
"name": "__init__",
"signature": "def __init__(self, opts)"
},
{
"docstring": "Given option_name, checks if it is in appconfig. Raises ValueError if a mandatory option is missing",
"name": "get_config_option",
"si... | 3 | stack_v2_sparse_classes_30k_train_020893 | Implement the Python class `FunctionComponent` described below.
Class description:
Component that implements Resilient function 'have_i_been_pwned_get_pastes
Method signatures and docstrings:
- def __init__(self, opts): constructor provides access to the configuration options
- def get_config_option(self, option_name... | Implement the Python class `FunctionComponent` described below.
Class description:
Component that implements Resilient function 'have_i_been_pwned_get_pastes
Method signatures and docstrings:
- def __init__(self, opts): constructor provides access to the configuration options
- def get_config_option(self, option_name... | 2e3c4b6102555517bad22bf87fa4a06341714166 | <|skeleton|>
class FunctionComponent:
"""Component that implements Resilient function 'have_i_been_pwned_get_pastes"""
def __init__(self, opts):
"""constructor provides access to the configuration options"""
<|body_0|>
def get_config_option(self, option_name, optional=False):
"""Gi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FunctionComponent:
"""Component that implements Resilient function 'have_i_been_pwned_get_pastes"""
def __init__(self, opts):
"""constructor provides access to the configuration options"""
super(FunctionComponent, self).__init__(opts)
self.options = opts.get('fn_hibp', {})
... | the_stack_v2_python_sparse | fn_hibp/fn_hibp/components/have_i_been_pwned_get_pastes.py | jjfallete/resilient-community-apps | train | 1 |
3611107747b726340675fc4d6e4f8859bad8ffdb | [
"super().__init__()\nself.alpha = alpha\nself.centers = nn.Parameter(torch.randn(number_of_classes, number_of_features))",
"assert len(classes.shape) == 1, f'must be a 1D tensor. Got={classes.shape}'\nassert len(classes) == len(x), f'must have the same dim in input ({len(x)}) and classes ({len(classes)})!'\nflatt... | <|body_start_0|>
super().__init__()
self.alpha = alpha
self.centers = nn.Parameter(torch.randn(number_of_classes, number_of_features))
<|end_body_0|>
<|body_start_1|>
assert len(classes.shape) == 1, f'must be a 1D tensor. Got={classes.shape}'
assert len(classes) == len(x), f'mus... | Center loss, penalize the features falling further from the feature class center. In most of the available CNNs, the softmax loss function is used as the supervision signal to train the deep model. In order to enhance the discriminative power of the deeply learned features, this loss can be used as a new supervision si... | LossCenter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LossCenter:
"""Center loss, penalize the features falling further from the feature class center. In most of the available CNNs, the softmax loss function is used as the supervision signal to train the deep model. In order to enhance the discriminative power of the deeply learned features, this lo... | stack_v2_sparse_classes_75kplus_train_004734 | 21,701 | permissive | [
{
"docstring": "Args: number_of_classes: the (maximum) number of classes number_of_features: the (exact) number of features alpha: the loss will be scaled by ``alpha``",
"name": "__init__",
"signature": "def __init__(self, number_of_classes, number_of_features, alpha=1.0)"
},
{
"docstring": "Arg... | 2 | null | Implement the Python class `LossCenter` described below.
Class description:
Center loss, penalize the features falling further from the feature class center. In most of the available CNNs, the softmax loss function is used as the supervision signal to train the deep model. In order to enhance the discriminative power ... | Implement the Python class `LossCenter` described below.
Class description:
Center loss, penalize the features falling further from the feature class center. In most of the available CNNs, the softmax loss function is used as the supervision signal to train the deep model. In order to enhance the discriminative power ... | 11c59dea0072d940b036166be22b392bb9e3b066 | <|skeleton|>
class LossCenter:
"""Center loss, penalize the features falling further from the feature class center. In most of the available CNNs, the softmax loss function is used as the supervision signal to train the deep model. In order to enhance the discriminative power of the deeply learned features, this lo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LossCenter:
"""Center loss, penalize the features falling further from the feature class center. In most of the available CNNs, the softmax loss function is used as the supervision signal to train the deep model. In order to enhance the discriminative power of the deeply learned features, this loss can be use... | the_stack_v2_python_sparse | src/trw/train/losses.py | civodlu/trw | train | 12 |
3db427bc4e54fae296e6d7dc252b4bb05b8fa09b | [
"name = 'RandomSampling'\nsuper(RandomSampling, self).__init__(name, xmin, xmax, use_logger)\nif self.use_logger:\n self.logger = ml.SciopeLogger().get_logger()\n self.logger.info('Random design in {0} dimensions initialized'.format(len(self.xmin)))",
"num_variables = len(self.xmin)\nx = np.random.rand(n, n... | <|body_start_0|>
name = 'RandomSampling'
super(RandomSampling, self).__init__(name, xmin, xmax, use_logger)
if self.use_logger:
self.logger = ml.SciopeLogger().get_logger()
self.logger.info('Random design in {0} dimensions initialized'.format(len(self.xmin)))
<|end_body_0... | Random Sampling implemented through gpflowopt Properties/variables: * name (RandomSampling) * xmin (lower bound of multi-dimensional space encompassing generated points) * xmax (upper bound of multi-dimensional space encompassing generated points) * logger (a logging object to display/save events - set by derived class... | RandomSampling | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomSampling:
"""Random Sampling implemented through gpflowopt Properties/variables: * name (RandomSampling) * xmin (lower bound of multi-dimensional space encompassing generated points) * xmax (upper bound of multi-dimensional space encompassing generated points) * logger (a logging object to ... | stack_v2_sparse_classes_75kplus_train_004735 | 2,961 | permissive | [
{
"docstring": "[summary] Parameters ---------- xmin : vector or 1D array Specifies the lower bound of the hypercube within which the design is generated xmax : vector or 1D array Specifies the upper bound of the hypercube within which the design is generated use_logger : bool, optional controls whether logging... | 2 | stack_v2_sparse_classes_30k_train_013206 | Implement the Python class `RandomSampling` described below.
Class description:
Random Sampling implemented through gpflowopt Properties/variables: * name (RandomSampling) * xmin (lower bound of multi-dimensional space encompassing generated points) * xmax (upper bound of multi-dimensional space encompassing generated... | Implement the Python class `RandomSampling` described below.
Class description:
Random Sampling implemented through gpflowopt Properties/variables: * name (RandomSampling) * xmin (lower bound of multi-dimensional space encompassing generated points) * xmax (upper bound of multi-dimensional space encompassing generated... | 5122107dedcee9c39458e83d853ec35f91268780 | <|skeleton|>
class RandomSampling:
"""Random Sampling implemented through gpflowopt Properties/variables: * name (RandomSampling) * xmin (lower bound of multi-dimensional space encompassing generated points) * xmax (upper bound of multi-dimensional space encompassing generated points) * logger (a logging object to ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomSampling:
"""Random Sampling implemented through gpflowopt Properties/variables: * name (RandomSampling) * xmin (lower bound of multi-dimensional space encompassing generated points) * xmax (upper bound of multi-dimensional space encompassing generated points) * logger (a logging object to display/save ... | the_stack_v2_python_sparse | sciope/designs/random_sampling.py | rmjiang7/sciope | train | 0 |
1b0abc3c41a8b7b0786988f0119c3f3cc41113a0 | [
"super(LastLayers, self).__init__(**args)\nself.num_filters = num_filters\nself.darknet_conv_bn_leaky1 = DarknetConv2D_BN_Leaky(self.num_filters, (1, 1))\nself.darknet_conv_bn_leaky2 = DarknetConv2D_BN_Leaky(self.num_filters * 2, (3, 3))\nself.darknet_conv_bn_leaky3 = DarknetConv2D_BN_Leaky(self.num_filters, (1, 1)... | <|body_start_0|>
super(LastLayers, self).__init__(**args)
self.num_filters = num_filters
self.darknet_conv_bn_leaky1 = DarknetConv2D_BN_Leaky(self.num_filters, (1, 1))
self.darknet_conv_bn_leaky2 = DarknetConv2D_BN_Leaky(self.num_filters * 2, (3, 3))
self.darknet_conv_bn_leaky3 =... | LastLayers | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LastLayers:
def __init__(self, num_filters, **args):
"""初始化网络"""
<|body_0|>
def call(self, x, training):
"""运算部分"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(LastLayers, self).__init__(**args)
self.num_filters = num_filters
... | stack_v2_sparse_classes_75kplus_train_004736 | 12,569 | no_license | [
{
"docstring": "初始化网络",
"name": "__init__",
"signature": "def __init__(self, num_filters, **args)"
},
{
"docstring": "运算部分",
"name": "call",
"signature": "def call(self, x, training)"
}
] | 2 | stack_v2_sparse_classes_30k_train_035419 | Implement the Python class `LastLayers` described below.
Class description:
Implement the LastLayers class.
Method signatures and docstrings:
- def __init__(self, num_filters, **args): 初始化网络
- def call(self, x, training): 运算部分 | Implement the Python class `LastLayers` described below.
Class description:
Implement the LastLayers class.
Method signatures and docstrings:
- def __init__(self, num_filters, **args): 初始化网络
- def call(self, x, training): 运算部分
<|skeleton|>
class LastLayers:
def __init__(self, num_filters, **args):
"""初始... | b7549701b0b1a7e4cc2c8275df2bc6c7a3253d24 | <|skeleton|>
class LastLayers:
def __init__(self, num_filters, **args):
"""初始化网络"""
<|body_0|>
def call(self, x, training):
"""运算部分"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LastLayers:
def __init__(self, num_filters, **args):
"""初始化网络"""
super(LastLayers, self).__init__(**args)
self.num_filters = num_filters
self.darknet_conv_bn_leaky1 = DarknetConv2D_BN_Leaky(self.num_filters, (1, 1))
self.darknet_conv_bn_leaky2 = DarknetConv2D_BN_Leaky(s... | the_stack_v2_python_sparse | AIServer/ai_api/ai_models/yolo_v3/model.py | tfwcn/tensorflow2-machine-vision | train | 1 | |
d4b05a5768607848c7c8cee0a45e4c973e85dcd4 | [
"array_num = array('i', lst)\nprint(*array_num)\nreturn (array_num[0], array_num[1], array_num[2], array_num[3], array_num[4])",
"self.new_array = array('i', [])\nself.array_num = array('i', lst)\nfor index in range(len(self.array_num) - 1, -1, -1):\n self.new_array.append(self.array_num[index])\nreturn self.n... | <|body_start_0|>
array_num = array('i', lst)
print(*array_num)
return (array_num[0], array_num[1], array_num[2], array_num[3], array_num[4])
<|end_body_0|>
<|body_start_1|>
self.new_array = array('i', [])
self.array_num = array('i', lst)
for index in range(len(self.array... | programArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class programArray:
def create_int_array(self, lst):
"""Create an array of 5 integers and display the array items. Access individual element through indexes."""
<|body_0|>
def reverse_array(self, lst):
"""Reverse the order of the items in the array."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_004737 | 1,755 | no_license | [
{
"docstring": "Create an array of 5 integers and display the array items. Access individual element through indexes.",
"name": "create_int_array",
"signature": "def create_int_array(self, lst)"
},
{
"docstring": "Reverse the order of the items in the array.",
"name": "reverse_array",
"s... | 4 | null | Implement the Python class `programArray` described below.
Class description:
Implement the programArray class.
Method signatures and docstrings:
- def create_int_array(self, lst): Create an array of 5 integers and display the array items. Access individual element through indexes.
- def reverse_array(self, lst): Rev... | Implement the Python class `programArray` described below.
Class description:
Implement the programArray class.
Method signatures and docstrings:
- def create_int_array(self, lst): Create an array of 5 integers and display the array items. Access individual element through indexes.
- def reverse_array(self, lst): Rev... | 9a137436df58ff4d32c36e58f6b67679346167b9 | <|skeleton|>
class programArray:
def create_int_array(self, lst):
"""Create an array of 5 integers and display the array items. Access individual element through indexes."""
<|body_0|>
def reverse_array(self, lst):
"""Reverse the order of the items in the array."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class programArray:
def create_int_array(self, lst):
"""Create an array of 5 integers and display the array items. Access individual element through indexes."""
array_num = array('i', lst)
print(*array_num)
return (array_num[0], array_num[1], array_num[2], array_num[3], array_num[4])... | the_stack_v2_python_sparse | Array/arrayProgram.py | shivamgupta7/python-program | train | 0 | |
78c4eb503ba3c8e743a709df7c68a3051bb0931e | [
"self.start_time = datetime.datetime.now()\nself.output_file = output_file\nsuper(HeartbeatTimer, self).__init__(interval, lambda: self.__emit_heartbeat())",
"duration = RepeatingTimer.readable_duration(datetime.datetime.now() - self.start_time)\nmessage = 'Heartbeat: Powheg generation has been running for {} in ... | <|body_start_0|>
self.start_time = datetime.datetime.now()
self.output_file = output_file
super(HeartbeatTimer, self).__init__(interval, lambda: self.__emit_heartbeat())
<|end_body_0|>
<|body_start_1|>
duration = RepeatingTimer.readable_duration(datetime.datetime.now() - self.start_time... | ! Recurring heartbeat that emits a message to console and to file. @author James Robinson <james.robinson@cern.ch> | HeartbeatTimer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HeartbeatTimer:
"""! Recurring heartbeat that emits a message to console and to file. @author James Robinson <james.robinson@cern.ch>"""
def __init__(self, interval, output_file=None):
"""! Constructor. @param interval Time interval between output messages in seconds. @param output_f... | stack_v2_sparse_classes_75kplus_train_004738 | 2,373 | no_license | [
{
"docstring": "! Constructor. @param interval Time interval between output messages in seconds. @param output_file Log file to write to.",
"name": "__init__",
"signature": "def __init__(self, interval, output_file=None)"
},
{
"docstring": "! Output a heartbeat message.",
"name": "__emit_hea... | 2 | stack_v2_sparse_classes_30k_train_003282 | Implement the Python class `HeartbeatTimer` described below.
Class description:
! Recurring heartbeat that emits a message to console and to file. @author James Robinson <james.robinson@cern.ch>
Method signatures and docstrings:
- def __init__(self, interval, output_file=None): ! Constructor. @param interval Time int... | Implement the Python class `HeartbeatTimer` described below.
Class description:
! Recurring heartbeat that emits a message to console and to file. @author James Robinson <james.robinson@cern.ch>
Method signatures and docstrings:
- def __init__(self, interval, output_file=None): ! Constructor. @param interval Time int... | 22df23187ef85e9c3120122c8375ea0e7d8ea440 | <|skeleton|>
class HeartbeatTimer:
"""! Recurring heartbeat that emits a message to console and to file. @author James Robinson <james.robinson@cern.ch>"""
def __init__(self, interval, output_file=None):
"""! Constructor. @param interval Time interval between output messages in seconds. @param output_f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HeartbeatTimer:
"""! Recurring heartbeat that emits a message to console and to file. @author James Robinson <james.robinson@cern.ch>"""
def __init__(self, interval, output_file=None):
"""! Constructor. @param interval Time interval between output messages in seconds. @param output_file Log file ... | the_stack_v2_python_sparse | athena/Generators/PowhegControl/python/utility/repeating_timer.py | rushioda/PIXELVALID_athena | train | 1 |
e023f3ff28cee102c8b25395f8b54fca280d9c9f | [
"no_render = {'Comment': ['quantity', 'price', 'tax', 'total'], 'VAT': ['quantity']}\ntype_name = self.invoice_item_type.name\nif not type_name in no_render:\n return True\nif name in no_render[type_name]:\n return False\nreturn True",
"if self.invoice_item_type.name == 'Hour':\n mins = self.quantity * 6... | <|body_start_0|>
no_render = {'Comment': ['quantity', 'price', 'tax', 'total'], 'VAT': ['quantity']}
type_name = self.invoice_item_type.name
if not type_name in no_render:
return True
if name in no_render[type_name]:
return False
return True
<|end_body_0|>... | InvoiceItem | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InvoiceItem:
def should_render_field(self, name):
"""Returns True if the field should be rendered in the item list on the invoice"""
<|body_0|>
def quantity_str(self):
"""Returns a more sanely formatted quantity string, taking into account the type of the item that w... | stack_v2_sparse_classes_75kplus_train_004739 | 3,389 | permissive | [
{
"docstring": "Returns True if the field should be rendered in the item list on the invoice",
"name": "should_render_field",
"signature": "def should_render_field(self, name)"
},
{
"docstring": "Returns a more sanely formatted quantity string, taking into account the type of the item that we're... | 4 | stack_v2_sparse_classes_30k_val_002870 | Implement the Python class `InvoiceItem` described below.
Class description:
Implement the InvoiceItem class.
Method signatures and docstrings:
- def should_render_field(self, name): Returns True if the field should be rendered in the item list on the invoice
- def quantity_str(self): Returns a more sanely formatted ... | Implement the Python class `InvoiceItem` described below.
Class description:
Implement the InvoiceItem class.
Method signatures and docstrings:
- def should_render_field(self, name): Returns True if the field should be rendered in the item list on the invoice
- def quantity_str(self): Returns a more sanely formatted ... | f9be8c5ae0a1fb802bf5b7322b106e66283efea5 | <|skeleton|>
class InvoiceItem:
def should_render_field(self, name):
"""Returns True if the field should be rendered in the item list on the invoice"""
<|body_0|>
def quantity_str(self):
"""Returns a more sanely formatted quantity string, taking into account the type of the item that w... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InvoiceItem:
def should_render_field(self, name):
"""Returns True if the field should be rendered in the item list on the invoice"""
no_render = {'Comment': ['quantity', 'price', 'tax', 'total'], 'VAT': ['quantity']}
type_name = self.invoice_item_type.name
if not type_name in n... | the_stack_v2_python_sparse | nano/models/invoice_item.py | riteshverma309/nanoinvoice | train | 0 | |
aeb3ab99d75b26bd66743ad4a6bee3666807a4ab | [
"bc = helpers.MakeBarcode('part', 3, {'id': 3, 'url': 'www.google.com'}, brief=False)\nself.assertIn('part', bc)\nself.assertIn('tool', bc)\nself.assertIn('\"tool\": \"InvenTree\"', bc)\ndata = json.loads(bc)\nself.assertEqual(data['part']['id'], 3)\nself.assertEqual(data['part']['url'], 'www.google.com')",
"bc =... | <|body_start_0|>
bc = helpers.MakeBarcode('part', 3, {'id': 3, 'url': 'www.google.com'}, brief=False)
self.assertIn('part', bc)
self.assertIn('tool', bc)
self.assertIn('"tool": "InvenTree"', bc)
data = json.loads(bc)
self.assertEqual(data['part']['id'], 3)
self.as... | Tests for barcode string creation. | TestMakeBarcode | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMakeBarcode:
"""Tests for barcode string creation."""
def test_barcode_extended(self):
"""Test creation of barcode with extended data."""
<|body_0|>
def test_barcode_brief(self):
"""Test creation of simple barcode."""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_75kplus_train_004740 | 41,191 | permissive | [
{
"docstring": "Test creation of barcode with extended data.",
"name": "test_barcode_extended",
"signature": "def test_barcode_extended(self)"
},
{
"docstring": "Test creation of simple barcode.",
"name": "test_barcode_brief",
"signature": "def test_barcode_brief(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_026363 | Implement the Python class `TestMakeBarcode` described below.
Class description:
Tests for barcode string creation.
Method signatures and docstrings:
- def test_barcode_extended(self): Test creation of barcode with extended data.
- def test_barcode_brief(self): Test creation of simple barcode. | Implement the Python class `TestMakeBarcode` described below.
Class description:
Tests for barcode string creation.
Method signatures and docstrings:
- def test_barcode_extended(self): Test creation of barcode with extended data.
- def test_barcode_brief(self): Test creation of simple barcode.
<|skeleton|>
class Tes... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class TestMakeBarcode:
"""Tests for barcode string creation."""
def test_barcode_extended(self):
"""Test creation of barcode with extended data."""
<|body_0|>
def test_barcode_brief(self):
"""Test creation of simple barcode."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestMakeBarcode:
"""Tests for barcode string creation."""
def test_barcode_extended(self):
"""Test creation of barcode with extended data."""
bc = helpers.MakeBarcode('part', 3, {'id': 3, 'url': 'www.google.com'}, brief=False)
self.assertIn('part', bc)
self.assertIn('tool'... | the_stack_v2_python_sparse | InvenTree/InvenTree/tests.py | inventree/InvenTree | train | 3,077 |
775c4e98a11283314c39bc56d3be0b1b42ab3c1d | [
"re = ''\nself.d[self.idx] = longUrl\nn = self.idx\nwhile n:\n re += self.code[n % 62]\n n /= 62\nself.idx += 1\nreturn re",
"i = 0\nfor x in shortUrl:\n if 'a' <= x <= 'z':\n i = i * 62 + ord(x) - ord('a')\n elif 'A' <= x <= 'Z':\n i = i * 62 + ord(x) - ord('A') + 26\n else:\n ... | <|body_start_0|>
re = ''
self.d[self.idx] = longUrl
n = self.idx
while n:
re += self.code[n % 62]
n /= 62
self.idx += 1
return re
<|end_body_0|>
<|body_start_1|>
i = 0
for x in shortUrl:
if 'a' <= x <= 'z':
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, longUrl):
"""Encodes a URL to a shortened URL. :type longUrl: str :rtype: str"""
<|body_0|>
def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_75kplus_train_004741 | 1,069 | no_license | [
{
"docstring": "Encodes a URL to a shortened URL. :type longUrl: str :rtype: str",
"name": "encode",
"signature": "def encode(self, longUrl)"
},
{
"docstring": "Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str",
"name": "decode",
"signature": "def decode(self,... | 2 | stack_v2_sparse_classes_30k_train_023913 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, longUrl): Encodes a URL to a shortened URL. :type longUrl: str :rtype: str
- def decode(self, shortUrl): Decodes a shortened URL to its original URL. :type shortUrl: s... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, longUrl): Encodes a URL to a shortened URL. :type longUrl: str :rtype: str
- def decode(self, shortUrl): Decodes a shortened URL to its original URL. :type shortUrl: s... | 20623defecf65cbc35b194d8b60d8b211816ee4f | <|skeleton|>
class Codec:
def encode(self, longUrl):
"""Encodes a URL to a shortened URL. :type longUrl: str :rtype: str"""
<|body_0|>
def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def encode(self, longUrl):
"""Encodes a URL to a shortened URL. :type longUrl: str :rtype: str"""
re = ''
self.d[self.idx] = longUrl
n = self.idx
while n:
re += self.code[n % 62]
n /= 62
self.idx += 1
return re
def dec... | the_stack_v2_python_sparse | in_Python/0535 Encode and Decode TinyURL.py | YangLiyli131/Leetcode2020 | train | 0 | |
5cdc5cf3541f726e10066d8ddf161639dfb2d726 | [
"ttk.Frame.__init__(self, master)\nself.conflict = conflict\nself.cframe = ttk.Frame(self)\nself.columnconfigure(0, weight=1)\nself.cframe.columnconfigure(0, weight=1)\nself.dmSelIdx = None\nself.dm = None\nself.clearBtn = ttk.Button(self, text='Clear Selection', command=self.clearSel)\nself.clearBtn.grid(row=1, co... | <|body_start_0|>
ttk.Frame.__init__(self, master)
self.conflict = conflict
self.cframe = ttk.Frame(self)
self.columnconfigure(0, weight=1)
self.cframe.columnconfigure(0, weight=1)
self.dmSelIdx = None
self.dm = None
self.clearBtn = ttk.Button(self, text='C... | Displays a PreferenceRanking widget for each DM. | PreferenceRankingMaster | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PreferenceRankingMaster:
"""Displays a PreferenceRanking widget for each DM."""
def __init__(self, master, conflict):
"""Initialize a master widget for PreferenceRankings."""
<|body_0|>
def chgDM(self, event):
"""Change the selected DM."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_004742 | 12,627 | no_license | [
{
"docstring": "Initialize a master widget for PreferenceRankings.",
"name": "__init__",
"signature": "def __init__(self, master, conflict)"
},
{
"docstring": "Change the selected DM.",
"name": "chgDM",
"signature": "def chgDM(self, event)"
},
{
"docstring": "Refresh the widget c... | 6 | stack_v2_sparse_classes_30k_val_000541 | Implement the Python class `PreferenceRankingMaster` described below.
Class description:
Displays a PreferenceRanking widget for each DM.
Method signatures and docstrings:
- def __init__(self, master, conflict): Initialize a master widget for PreferenceRankings.
- def chgDM(self, event): Change the selected DM.
- def... | Implement the Python class `PreferenceRankingMaster` described below.
Class description:
Displays a PreferenceRanking widget for each DM.
Method signatures and docstrings:
- def __init__(self, master, conflict): Initialize a master widget for PreferenceRankings.
- def chgDM(self, event): Change the selected DM.
- def... | 502a12c9100962aaa0551763b74d303864967b80 | <|skeleton|>
class PreferenceRankingMaster:
"""Displays a PreferenceRanking widget for each DM."""
def __init__(self, master, conflict):
"""Initialize a master widget for PreferenceRankings."""
<|body_0|>
def chgDM(self, event):
"""Change the selected DM."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PreferenceRankingMaster:
"""Displays a PreferenceRanking widget for each DM."""
def __init__(self, master, conflict):
"""Initialize a master widget for PreferenceRankings."""
ttk.Frame.__init__(self, master)
self.conflict = conflict
self.cframe = ttk.Frame(self)
se... | the_stack_v2_python_sparse | widgets_f04_02_prefElements.py | ryosakagami/gmcr-py | train | 0 |
6f8b2dc00002a3d5a91c47cec2c0565d7fc56880 | [
"self.additional_params = additional_params\nself.app_entity = app_entity\nself.display_name = display_name\nself.entity_node_uid = entity_node_uid\nself.restore_params = restore_params\nself.task_node_uid = task_node_uid",
"if dictionary is None:\n return None\nadditional_params = cohesity_management_sdk.mode... | <|body_start_0|>
self.additional_params = additional_params
self.app_entity = app_entity
self.display_name = display_name
self.entity_node_uid = entity_node_uid
self.restore_params = restore_params
self.task_node_uid = task_node_uid
<|end_body_0|>
<|body_start_1|>
... | Implementation of the 'RestoreAppObject' model. Message that captures information about an application object being restored. Attributes: additional_params (RestoreTaskAdditionalParams): Any additional parameters associated with a restore task. app_entity (EntityProto): The application entity to restore (for example, k... | RestoreAppObject | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestoreAppObject:
"""Implementation of the 'RestoreAppObject' model. Message that captures information about an application object being restored. Attributes: additional_params (RestoreTaskAdditionalParams): Any additional parameters associated with a restore task. app_entity (EntityProto): The a... | stack_v2_sparse_classes_75kplus_train_004743 | 4,183 | permissive | [
{
"docstring": "Constructor for the RestoreAppObject class",
"name": "__init__",
"signature": "def __init__(self, additional_params=None, app_entity=None, display_name=None, entity_node_uid=None, restore_params=None, task_node_uid=None)"
},
{
"docstring": "Creates an instance of this model from ... | 2 | stack_v2_sparse_classes_30k_train_054427 | Implement the Python class `RestoreAppObject` described below.
Class description:
Implementation of the 'RestoreAppObject' model. Message that captures information about an application object being restored. Attributes: additional_params (RestoreTaskAdditionalParams): Any additional parameters associated with a restor... | Implement the Python class `RestoreAppObject` described below.
Class description:
Implementation of the 'RestoreAppObject' model. Message that captures information about an application object being restored. Attributes: additional_params (RestoreTaskAdditionalParams): Any additional parameters associated with a restor... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RestoreAppObject:
"""Implementation of the 'RestoreAppObject' model. Message that captures information about an application object being restored. Attributes: additional_params (RestoreTaskAdditionalParams): Any additional parameters associated with a restore task. app_entity (EntityProto): The a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RestoreAppObject:
"""Implementation of the 'RestoreAppObject' model. Message that captures information about an application object being restored. Attributes: additional_params (RestoreTaskAdditionalParams): Any additional parameters associated with a restore task. app_entity (EntityProto): The application en... | the_stack_v2_python_sparse | cohesity_management_sdk/models/restore_app_object.py | cohesity/management-sdk-python | train | 24 |
04f92c146745bce6f8accb8e9c3871aba0d8875a | [
"self._file_cache = injector.file_cache\nself._logger = logging.getLogger()\nself._hook_builder = HookSequenceBuilder()",
"command_type = command['commandType']\nif command_type == AgentCommand.status or not command_name:\n return None\nhook_dir = self._file_cache.get_hook_base_dir(command)\nif not hook_dir:\n... | <|body_start_0|>
self._file_cache = injector.file_cache
self._logger = logging.getLogger()
self._hook_builder = HookSequenceBuilder()
<|end_body_0|>
<|body_start_1|>
command_type = command['commandType']
if command_type == AgentCommand.status or not command_name:
ret... | Resolving hooks according to HookSequenceBuilder definitions | HooksOrchestrator | [
"GPL-1.0-or-later",
"GPL-2.0-or-later",
"OFL-1.1",
"MS-PL",
"AFL-2.1",
"GPL-2.0-only",
"Python-2.0",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HooksOrchestrator:
"""Resolving hooks according to HookSequenceBuilder definitions"""
def __init__(self, injector):
""":type injector InitializerModule"""
<|body_0|>
def resolve_hooks(self, command, command_name):
"""Resolving available hooks sequences which shou... | stack_v2_sparse_classes_75kplus_train_004744 | 5,061 | permissive | [
{
"docstring": ":type injector InitializerModule",
"name": "__init__",
"signature": "def __init__(self, injector)"
},
{
"docstring": "Resolving available hooks sequences which should be appended or prepended to script execution chain :type command dict :type command_name str :rtype ResolvedHooks... | 3 | stack_v2_sparse_classes_30k_train_010578 | Implement the Python class `HooksOrchestrator` described below.
Class description:
Resolving hooks according to HookSequenceBuilder definitions
Method signatures and docstrings:
- def __init__(self, injector): :type injector InitializerModule
- def resolve_hooks(self, command, command_name): Resolving available hooks... | Implement the Python class `HooksOrchestrator` described below.
Class description:
Resolving hooks according to HookSequenceBuilder definitions
Method signatures and docstrings:
- def __init__(self, injector): :type injector InitializerModule
- def resolve_hooks(self, command, command_name): Resolving available hooks... | 23881f23577a65de396238998e8672d6c4c5a250 | <|skeleton|>
class HooksOrchestrator:
"""Resolving hooks according to HookSequenceBuilder definitions"""
def __init__(self, injector):
""":type injector InitializerModule"""
<|body_0|>
def resolve_hooks(self, command, command_name):
"""Resolving available hooks sequences which shou... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HooksOrchestrator:
"""Resolving hooks according to HookSequenceBuilder definitions"""
def __init__(self, injector):
""":type injector InitializerModule"""
self._file_cache = injector.file_cache
self._logger = logging.getLogger()
self._hook_builder = HookSequenceBuilder()
... | the_stack_v2_python_sparse | ambari-agent/src/main/python/ambari_agent/CommandHooksOrchestrator.py | apache/ambari | train | 2,078 |
3d7a8fb5aa813cf33c023b869e14e8874ec963bc | [
"if vals.get('miscible', False) and (not vals.get('not_do_procurement', False)):\n raise osv.except_osv(_('Error!'), _(\"Cannnot put this product to do procurement, because this poduct is marked as miscible and the miscible products don't do procurement.\"))\nreturn True",
"self.check_if_procurement(cr, uid, i... | <|body_start_0|>
if vals.get('miscible', False) and (not vals.get('not_do_procurement', False)):
raise osv.except_osv(_('Error!'), _("Cannnot put this product to do procurement, because this poduct is marked as miscible and the miscible products don't do procurement."))
return True
<|end_bod... | add functionally for differentiate miscible product and not miscible product | product_product | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class product_product:
"""add functionally for differentiate miscible product and not miscible product"""
def check_if_procurement(self, cr, uid, ids, vals):
"""checks if the product has configurate well the procurement"""
<|body_0|>
def write(self, cr, uid, ids, vals, context... | stack_v2_sparse_classes_75kplus_train_004745 | 4,387 | no_license | [
{
"docstring": "checks if the product has configurate well the procurement",
"name": "check_if_procurement",
"signature": "def check_if_procurement(self, cr, uid, ids, vals)"
},
{
"docstring": "overwrites write method for checks if the procurement for the product is configurate well",
"name"... | 3 | stack_v2_sparse_classes_30k_train_002668 | Implement the Python class `product_product` described below.
Class description:
add functionally for differentiate miscible product and not miscible product
Method signatures and docstrings:
- def check_if_procurement(self, cr, uid, ids, vals): checks if the product has configurate well the procurement
- def write(s... | Implement the Python class `product_product` described below.
Class description:
add functionally for differentiate miscible product and not miscible product
Method signatures and docstrings:
- def check_if_procurement(self, cr, uid, ids, vals): checks if the product has configurate well the procurement
- def write(s... | 01c8294e969cce818a33fd06682560e0344c217c | <|skeleton|>
class product_product:
"""add functionally for differentiate miscible product and not miscible product"""
def check_if_procurement(self, cr, uid, ids, vals):
"""checks if the product has configurate well the procurement"""
<|body_0|>
def write(self, cr, uid, ids, vals, context... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class product_product:
"""add functionally for differentiate miscible product and not miscible product"""
def check_if_procurement(self, cr, uid, ids, vals):
"""checks if the product has configurate well the procurement"""
if vals.get('miscible', False) and (not vals.get('not_do_procurement', F... | the_stack_v2_python_sparse | Varios/alimentacion/__unported__/full_stock_traceability/product.py | ELNOGAL/GALIPAT_LUGO | train | 0 |
0c15ddae2e218af1157a535ea1aed93804df1782 | [
"super(Buffer, self).__init__()\nself._log = log\nself._fifo = fifo\nlog.debug('creating buffer %s/%s' % (component_name, property_name))\nself._chunk_size = get_total_seconds(chunk_size, True)\nself._component_name = component_name\nself._property_name = property_name\nself._disable = disable\nself._chunk_begin = ... | <|body_start_0|>
super(Buffer, self).__init__()
self._log = log
self._fifo = fifo
log.debug('creating buffer %s/%s' % (component_name, property_name))
self._chunk_size = get_total_seconds(chunk_size, True)
self._component_name = component_name
self._property_name ... | This buffer stores monitoring/time series data indirectly in redis. The buffer and redis are decoupled by a FIFO plus (a) consumer thread(s) that is/are managed by the registry. | Buffer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Buffer:
"""This buffer stores monitoring/time series data indirectly in redis. The buffer and redis are decoupled by a FIFO plus (a) consumer thread(s) that is/are managed by the registry."""
def __init__(self, log, fifo, chunk_size, component_name, property_name, disable):
"""ctor. ... | stack_v2_sparse_classes_75kplus_train_004746 | 19,077 | no_license | [
{
"docstring": "ctor. @param log: The logger to publish log messages. @type log: logging.Logger @param fifo: The FIFO that is the input for the redis consumer. @type fifo: ctamonitoring.property_recorder.backend.ring_buffer.RingBuffer @param component_name: Component name and @type component_name: string @param... | 5 | stack_v2_sparse_classes_30k_train_023606 | Implement the Python class `Buffer` described below.
Class description:
This buffer stores monitoring/time series data indirectly in redis. The buffer and redis are decoupled by a FIFO plus (a) consumer thread(s) that is/are managed by the registry.
Method signatures and docstrings:
- def __init__(self, log, fifo, ch... | Implement the Python class `Buffer` described below.
Class description:
This buffer stores monitoring/time series data indirectly in redis. The buffer and redis are decoupled by a FIFO plus (a) consumer thread(s) that is/are managed by the registry.
Method signatures and docstrings:
- def __init__(self, log, fifo, ch... | b0e590302a5787782bb834b36231b0595b08d60b | <|skeleton|>
class Buffer:
"""This buffer stores monitoring/time series data indirectly in redis. The buffer and redis are decoupled by a FIFO plus (a) consumer thread(s) that is/are managed by the registry."""
def __init__(self, log, fifo, chunk_size, component_name, property_name, disable):
"""ctor. ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Buffer:
"""This buffer stores monitoring/time series data indirectly in redis. The buffer and redis are decoupled by a FIFO plus (a) consumer thread(s) that is/are managed by the registry."""
def __init__(self, log, fifo, chunk_size, component_name, property_name, disable):
"""ctor. @param log: T... | the_stack_v2_python_sparse | src/ctamonitoring/property_recorder/backend/redis/registry.py | sliusar/ctamonitoring | train | 0 |
69afc1f6f565d28ac73acb18abb2bcc1a0b18bb1 | [
"resource_args.AddConversionWorkspaceResourceArg(parser, 'to describe DDLs')\ncw_flags.AddTreeTypeFlag(parser, required=False)\ncw_flags.AddCommitIdFlag(parser)\ncw_flags.AddUncomittedFlag(parser)\ncw_flags.AddFilterFlag(parser)\nparser.display_info.AddFormat('table(ddl:label=DDLs)')",
"conversion_workspace_ref =... | <|body_start_0|>
resource_args.AddConversionWorkspaceResourceArg(parser, 'to describe DDLs')
cw_flags.AddTreeTypeFlag(parser, required=False)
cw_flags.AddCommitIdFlag(parser)
cw_flags.AddUncomittedFlag(parser)
cw_flags.AddFilterFlag(parser)
parser.display_info.AddFormat('... | Describe DDLs in a Database Migration Service conversion workspace. | DescribeDDLs | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DescribeDDLs:
"""Describe DDLs in a Database Migration Service conversion workspace."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this comm... | stack_v2_sparse_classes_75kplus_train_004747 | 2,987 | permissive | [
{
"docstring": "Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments are allowed.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring"... | 2 | stack_v2_sparse_classes_30k_train_004100 | Implement the Python class `DescribeDDLs` described below.
Class description:
Describe DDLs in a Database Migration Service conversion workspace.
Method signatures and docstrings:
- def Args(parser): Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to ... | Implement the Python class `DescribeDDLs` described below.
Class description:
Describe DDLs in a Database Migration Service conversion workspace.
Method signatures and docstrings:
- def Args(parser): Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to ... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class DescribeDDLs:
"""Describe DDLs in a Database Migration Service conversion workspace."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this comm... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DescribeDDLs:
"""Describe DDLs in a Database Migration Service conversion workspace."""
def Args(parser):
"""Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Position... | the_stack_v2_python_sparse | lib/surface/database_migration/conversion_workspaces/describe_ddls.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
77fd3491e20cae336f0701f632002e31e4ea4faf | [
"if 1 not in directed_graph[i] and temp not in res:\n inner_res = temp[:]\n res.append(inner_res)\n return\nfor j in range(n):\n if directed_graph[i][j] == 1:\n temp.append(j)\n self.print_path(j, temp, res, n, directed_graph)\n temp.pop()",
"directed_graph = DirectedGraph(len(gra... | <|body_start_0|>
if 1 not in directed_graph[i] and temp not in res:
inner_res = temp[:]
res.append(inner_res)
return
for j in range(n):
if directed_graph[i][j] == 1:
temp.append(j)
self.print_path(j, temp, res, n, directed_g... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def print_path(self, i, temp, res, n, directed_graph):
"""i是第i个点"""
<|body_0|>
def allPathsSourceTarget(self, graph):
""":type graph: [[1,2], [3], [3], []] :rtype: [[0,1,3],[0,2,3]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if 1 not ... | stack_v2_sparse_classes_75kplus_train_004748 | 1,612 | no_license | [
{
"docstring": "i是第i个点",
"name": "print_path",
"signature": "def print_path(self, i, temp, res, n, directed_graph)"
},
{
"docstring": ":type graph: [[1,2], [3], [3], []] :rtype: [[0,1,3],[0,2,3]]",
"name": "allPathsSourceTarget",
"signature": "def allPathsSourceTarget(self, graph)"
}
] | 2 | stack_v2_sparse_classes_30k_train_045680 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def print_path(self, i, temp, res, n, directed_graph): i是第i个点
- def allPathsSourceTarget(self, graph): :type graph: [[1,2], [3], [3], []] :rtype: [[0,1,3],[0,2,3]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def print_path(self, i, temp, res, n, directed_graph): i是第i个点
- def allPathsSourceTarget(self, graph): :type graph: [[1,2], [3], [3], []] :rtype: [[0,1,3],[0,2,3]]
<|skeleton|>
... | 18c06a96bb14688e4a1d5fb6baf235a6b53bd3ae | <|skeleton|>
class Solution:
def print_path(self, i, temp, res, n, directed_graph):
"""i是第i个点"""
<|body_0|>
def allPathsSourceTarget(self, graph):
""":type graph: [[1,2], [3], [3], []] :rtype: [[0,1,3],[0,2,3]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def print_path(self, i, temp, res, n, directed_graph):
"""i是第i个点"""
if 1 not in directed_graph[i] and temp not in res:
inner_res = temp[:]
res.append(inner_res)
return
for j in range(n):
if directed_graph[i][j] == 1:
... | the_stack_v2_python_sparse | medium/others/all-paths-from-source-to-target.py | congyingTech/Basic-Algorithm | train | 10 | |
034c52f565ffa905099185b66e818eb920d8d926 | [
"factory = IDirectoryFactory(self, None)\nif factory is None:\n raise MethodNotAllowed('Cannot create collection: No IDirectoryFactory adapter found')\nfactory(id)",
"factory = IFileFactory(self, None)\nif factory is None:\n return None\nreturn factory(name, contentType, body)",
"parentList = super().list... | <|body_start_0|>
factory = IDirectoryFactory(self, None)
if factory is None:
raise MethodNotAllowed('Cannot create collection: No IDirectoryFactory adapter found')
factory(id)
<|end_body_0|>
<|body_start_1|>
factory = IFileFactory(self, None)
if factory is None:
... | Mixin class for WebDAV collection support. The main purpose of this class is to implement the Zope 2 WebDAV API to delegate to more granular adapters. | DAVCollectionMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DAVCollectionMixin:
"""Mixin class for WebDAV collection support. The main purpose of this class is to implement the Zope 2 WebDAV API to delegate to more granular adapters."""
def MKCOL_handler(self, id, REQUEST=None, RESPONSE=None):
"""Handle "make collection" by delegating to an I... | stack_v2_sparse_classes_75kplus_train_004749 | 26,979 | no_license | [
{
"docstring": "Handle \"make collection\" by delegating to an IDirectoryFactory adapter.",
"name": "MKCOL_handler",
"signature": "def MKCOL_handler(self, id, REQUEST=None, RESPONSE=None)"
},
{
"docstring": "Handle constructing a new object upon a PUT request by delegating to an IFileFactory ada... | 3 | stack_v2_sparse_classes_30k_val_001808 | Implement the Python class `DAVCollectionMixin` described below.
Class description:
Mixin class for WebDAV collection support. The main purpose of this class is to implement the Zope 2 WebDAV API to delegate to more granular adapters.
Method signatures and docstrings:
- def MKCOL_handler(self, id, REQUEST=None, RESPO... | Implement the Python class `DAVCollectionMixin` described below.
Class description:
Mixin class for WebDAV collection support. The main purpose of this class is to implement the Zope 2 WebDAV API to delegate to more granular adapters.
Method signatures and docstrings:
- def MKCOL_handler(self, id, REQUEST=None, RESPO... | 54110e0da3d7348038431be13fc183d5c89f2f32 | <|skeleton|>
class DAVCollectionMixin:
"""Mixin class for WebDAV collection support. The main purpose of this class is to implement the Zope 2 WebDAV API to delegate to more granular adapters."""
def MKCOL_handler(self, id, REQUEST=None, RESPONSE=None):
"""Handle "make collection" by delegating to an I... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DAVCollectionMixin:
"""Mixin class for WebDAV collection support. The main purpose of this class is to implement the Zope 2 WebDAV API to delegate to more granular adapters."""
def MKCOL_handler(self, id, REQUEST=None, RESPONSE=None):
"""Handle "make collection" by delegating to an IDirectoryFact... | the_stack_v2_python_sparse | plone/dexterity/filerepresentation.py | plone/plone.dexterity | train | 13 |
5e65142bd1a6c38411c192717e93c4002635144c | [
"with open(SLAPHUG_FILE.format(bot.root), encoding='utf-8') as file:\n self.replies = json.load(file)\n self.slapreply = self.replies['slap']\n self.hugreply = self.replies['hug']",
"if '<user>' in reply:\n reply = reply.replace('<user>', bot.twitch.display_name(user))\nif '<target>' in reply:\n re... | <|body_start_0|>
with open(SLAPHUG_FILE.format(bot.root), encoding='utf-8') as file:
self.replies = json.load(file)
self.slapreply = self.replies['slap']
self.hugreply = self.replies['hug']
<|end_body_0|>
<|body_start_1|>
if '<user>' in reply:
reply = rep... | Slap or hug a user. | SlapHug | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SlapHug:
"""Slap or hug a user."""
def __init__(self, bot):
"""Load command list."""
<|body_0|>
def replace_reply(bot, user, target, reply):
"""Replace words in the reply string and return it."""
<|body_1|>
def match(self, bot, user, msg, tag_info):
... | stack_v2_sparse_classes_75kplus_train_004750 | 2,338 | permissive | [
{
"docstring": "Load command list.",
"name": "__init__",
"signature": "def __init__(self, bot)"
},
{
"docstring": "Replace words in the reply string and return it.",
"name": "replace_reply",
"signature": "def replace_reply(bot, user, target, reply)"
},
{
"docstring": "Match if co... | 4 | stack_v2_sparse_classes_30k_train_052924 | Implement the Python class `SlapHug` described below.
Class description:
Slap or hug a user.
Method signatures and docstrings:
- def __init__(self, bot): Load command list.
- def replace_reply(bot, user, target, reply): Replace words in the reply string and return it.
- def match(self, bot, user, msg, tag_info): Matc... | Implement the Python class `SlapHug` described below.
Class description:
Slap or hug a user.
Method signatures and docstrings:
- def __init__(self, bot): Load command list.
- def replace_reply(bot, user, target, reply): Replace words in the reply string and return it.
- def match(self, bot, user, msg, tag_info): Matc... | 6bef453bf5042401ecdafcdda404452dfd982ecf | <|skeleton|>
class SlapHug:
"""Slap or hug a user."""
def __init__(self, bot):
"""Load command list."""
<|body_0|>
def replace_reply(bot, user, target, reply):
"""Replace words in the reply string and return it."""
<|body_1|>
def match(self, bot, user, msg, tag_info):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SlapHug:
"""Slap or hug a user."""
def __init__(self, bot):
"""Load command list."""
with open(SLAPHUG_FILE.format(bot.root), encoding='utf-8') as file:
self.replies = json.load(file)
self.slapreply = self.replies['slap']
self.hugreply = self.replies['h... | the_stack_v2_python_sparse | bot/commands/slaphug.py | ghostduck/monkalot | train | 0 |
f2537b2eb10ec033777ed838fee64286cc525b67 | [
"self.dates = sorted(dates, reverse=True) if dates else []\nself.today = today or date.today()\nself.white_list = list()\nself.black_list = list()\nself.run()",
"first_day = date(self.today.year, self.today.month, 1)\nlast_day = first_day - timedelta(days=1)\nreturn monthrange(last_day.year, last_day.month)[1]",
... | <|body_start_0|>
self.dates = sorted(dates, reverse=True) if dates else []
self.today = today or date.today()
self.white_list = list()
self.black_list = list()
self.run()
<|end_body_0|>
<|body_start_1|>
first_day = date(self.today.year, self.today.month, 1)
last_... | BackupAutoClean | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BackupAutoClean:
def __init__(self, dates=None, today=None):
""":param dates: list of date ids (in string format) :param today: datetime object"""
<|body_0|>
def get_last_month_length(self):
""":return: integer with the number of the days of the previous month"""
... | stack_v2_sparse_classes_75kplus_train_004751 | 3,651 | permissive | [
{
"docstring": ":param dates: list of date ids (in string format) :param today: datetime object",
"name": "__init__",
"signature": "def __init__(self, dates=None, today=None)"
},
{
"docstring": ":return: integer with the number of the days of the previous month",
"name": "get_last_month_leng... | 5 | stack_v2_sparse_classes_30k_train_014726 | Implement the Python class `BackupAutoClean` described below.
Class description:
Implement the BackupAutoClean class.
Method signatures and docstrings:
- def __init__(self, dates=None, today=None): :param dates: list of date ids (in string format) :param today: datetime object
- def get_last_month_length(self): :retu... | Implement the Python class `BackupAutoClean` described below.
Class description:
Implement the BackupAutoClean class.
Method signatures and docstrings:
- def __init__(self, dates=None, today=None): :param dates: list of date ids (in string format) :param today: datetime object
- def get_last_month_length(self): :retu... | cf0a74885b873cb2583b3870ccdf3508d3af602e | <|skeleton|>
class BackupAutoClean:
def __init__(self, dates=None, today=None):
""":param dates: list of date ids (in string format) :param today: datetime object"""
<|body_0|>
def get_last_month_length(self):
""":return: integer with the number of the days of the previous month"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BackupAutoClean:
def __init__(self, dates=None, today=None):
""":param dates: list of date ids (in string format) :param today: datetime object"""
self.dates = sorted(dates, reverse=True) if dates else []
self.today = today or date.today()
self.white_list = list()
self.... | the_stack_v2_python_sparse | AD14-flask-admin-backup-demo/app/admin_backup/autoclean.py | AngelLiang/Flask-Demos | train | 3 | |
27c837c7d32b0e76088841c52ca2b150c0ae7154 | [
"k = k % len(nums)\nfor i in range(k):\n tmp = nums[-1]\n nums[1:] = nums[:-1]\n nums[0] = tmp",
"n = len(nums)\nk = k % n\nnums[:] = nums[n - k:] + nums[:n - k]"
] | <|body_start_0|>
k = k % len(nums)
for i in range(k):
tmp = nums[-1]
nums[1:] = nums[:-1]
nums[0] = tmp
<|end_body_0|>
<|body_start_1|>
n = len(nums)
k = k % n
nums[:] = nums[n - k:] + nums[:n - k]
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate2(self, nums, k):
"""Time Limit Exceeded :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def rotate(self, nums, k):
"""Time Limit Exceeded :type nums: List[int] :type k: int :rtyp... | stack_v2_sparse_classes_75kplus_train_004752 | 866 | no_license | [
{
"docstring": "Time Limit Exceeded :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.",
"name": "rotate2",
"signature": "def rotate2(self, nums, k)"
},
{
"docstring": "Time Limit Exceeded :type nums: List[int] :type k: int :rtype: void Do not r... | 2 | stack_v2_sparse_classes_30k_train_050058 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate2(self, nums, k): Time Limit Exceeded :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.
- def rotate(self, nums, k):... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate2(self, nums, k): Time Limit Exceeded :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.
- def rotate(self, nums, k):... | 852fad258f5070c7b93c35252f7404e85e709ea6 | <|skeleton|>
class Solution:
def rotate2(self, nums, k):
"""Time Limit Exceeded :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def rotate(self, nums, k):
"""Time Limit Exceeded :type nums: List[int] :type k: int :rtyp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def rotate2(self, nums, k):
"""Time Limit Exceeded :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
k = k % len(nums)
for i in range(k):
tmp = nums[-1]
nums[1:] = nums[:-1]
nums[0] = t... | the_stack_v2_python_sparse | 101-200/189. Rotate Array.py | SunnyMarkLiu/LeetCode | train | 1 | |
4cf032a4eb9ff196da2bc49b348a07841edd801f | [
"super().__init__(root=root, split=split, transform=transform)\nself.classes = [e.strip() for e in (self.root / 'lists/classes_polygon.txt').read_text().split('\\n')]\nself.convert_polygons = ConvertPolygonsToInstanceMasks() if convert_polygons_to_masks else None",
"with self.annotations_path[index].open() as f:\... | <|body_start_0|>
super().__init__(root=root, split=split, transform=transform)
self.classes = [e.strip() for e in (self.root / 'lists/classes_polygon.txt').read_text().split('\n')]
self.convert_polygons = ConvertPolygonsToInstanceMasks() if convert_polygons_to_masks else None
<|end_body_0|>
<|b... | InstanceSegmentationDataset | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstanceSegmentationDataset:
def __init__(self, root: Path, split: Path, transform: Optional[List]=None, convert_polygons_to_masks: Optional[bool]=True):
"""See superclass for documentation"""
<|body_0|>
def _map_annotation(self, index: int):
"""See superclass for do... | stack_v2_sparse_classes_75kplus_train_004753 | 20,303 | permissive | [
{
"docstring": "See superclass for documentation",
"name": "__init__",
"signature": "def __init__(self, root: Path, split: Path, transform: Optional[List]=None, convert_polygons_to_masks: Optional[bool]=True)"
},
{
"docstring": "See superclass for documentation Notes ----- The return value is a ... | 3 | null | Implement the Python class `InstanceSegmentationDataset` described below.
Class description:
Implement the InstanceSegmentationDataset class.
Method signatures and docstrings:
- def __init__(self, root: Path, split: Path, transform: Optional[List]=None, convert_polygons_to_masks: Optional[bool]=True): See superclass ... | Implement the Python class `InstanceSegmentationDataset` described below.
Class description:
Implement the InstanceSegmentationDataset class.
Method signatures and docstrings:
- def __init__(self, root: Path, split: Path, transform: Optional[List]=None, convert_polygons_to_masks: Optional[bool]=True): See superclass ... | e6073353b30c8fa1e7b0f42db1d95bd5bede945e | <|skeleton|>
class InstanceSegmentationDataset:
def __init__(self, root: Path, split: Path, transform: Optional[List]=None, convert_polygons_to_masks: Optional[bool]=True):
"""See superclass for documentation"""
<|body_0|>
def _map_annotation(self, index: int):
"""See superclass for do... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InstanceSegmentationDataset:
def __init__(self, root: Path, split: Path, transform: Optional[List]=None, convert_polygons_to_masks: Optional[bool]=True):
"""See superclass for documentation"""
super().__init__(root=root, split=split, transform=transform)
self.classes = [e.strip() for e... | the_stack_v2_python_sparse | darwin/torch/dataset.py | co2meal/darwin-py | train | 0 | |
eb25c8e80522099bfbbd4ab32c3a6354517c87fc | [
"code = AccessToken(app_id=application.id, type='authorization_code', token=uuid.uuid4().hex[:35], date_insert=datetime.datetime.now(), id_user=user.id, expiration_date=datetime.datetime.now() + datetime.timedelta(weeks=2), is_enable=1, scopes=scope)\ntry:\n session.begin()\n session.add(code)\n session.co... | <|body_start_0|>
code = AccessToken(app_id=application.id, type='authorization_code', token=uuid.uuid4().hex[:35], date_insert=datetime.datetime.now(), id_user=user.id, expiration_date=datetime.datetime.now() + datetime.timedelta(weeks=2), is_enable=1, scopes=scope)
try:
session.begin()
... | OAuthRequestAbstract | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OAuthRequestAbstract:
def create_authorization_code(self, application, user, scope):
"""Generate an authorization code for this application, entity, scope :param APIOAuthApplicationModel application: An oauth application model :param dict entity: Entity attached to this token :rtype: API... | stack_v2_sparse_classes_75kplus_train_004754 | 2,430 | no_license | [
{
"docstring": "Generate an authorization code for this application, entity, scope :param APIOAuthApplicationModel application: An oauth application model :param dict entity: Entity attached to this token :rtype: APIOAuthTokenModel",
"name": "create_authorization_code",
"signature": "def create_authoriz... | 3 | stack_v2_sparse_classes_30k_train_028317 | Implement the Python class `OAuthRequestAbstract` described below.
Class description:
Implement the OAuthRequestAbstract class.
Method signatures and docstrings:
- def create_authorization_code(self, application, user, scope): Generate an authorization code for this application, entity, scope :param APIOAuthApplicati... | Implement the Python class `OAuthRequestAbstract` described below.
Class description:
Implement the OAuthRequestAbstract class.
Method signatures and docstrings:
- def create_authorization_code(self, application, user, scope): Generate an authorization code for this application, entity, scope :param APIOAuthApplicati... | bad19a17e983cfbcb3337026693167e9bd1b00c5 | <|skeleton|>
class OAuthRequestAbstract:
def create_authorization_code(self, application, user, scope):
"""Generate an authorization code for this application, entity, scope :param APIOAuthApplicationModel application: An oauth application model :param dict entity: Entity attached to this token :rtype: API... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OAuthRequestAbstract:
def create_authorization_code(self, application, user, scope):
"""Generate an authorization code for this application, entity, scope :param APIOAuthApplicationModel application: An oauth application model :param dict entity: Entity attached to this token :rtype: APIOAuthTokenMode... | the_stack_v2_python_sparse | API/auth/OAuthRequestAbstract.py | arlex-it/arlex | train | 0 | |
875edb081524bf4420399b8d09b5533db95e22e0 | [
"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 | [
"Apache-2.0"
] | 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_004755 | 13,114 | permissive | [
{
"docstring": "显示登录页面",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "登录的校验",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001698 | 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, req... | 9883b7380d45f30cdcc686e0319bc47c604c06f5 | <|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 | apps/user/views.py | haitaoss/dailyfresh | train | 0 |
e88f654ea304df2031b12a019ec4815fc6c65348 | [
"super(GreedyPCTRAgent, self).__init__(action_space)\nself._choice_model = choice_model\nself._belief_state = belief_state",
"del reward\ndoc_obs = observation['doc']\nself._choice_model.score_documents(self._belief_state, doc_obs.values())\nslate = self.findBestDocuments(self._choice_model.scores)\nlogging.debug... | <|body_start_0|>
super(GreedyPCTRAgent, self).__init__(action_space)
self._choice_model = choice_model
self._belief_state = belief_state
<|end_body_0|>
<|body_start_1|>
del reward
doc_obs = observation['doc']
self._choice_model.score_documents(self._belief_state, doc_obs... | An agent that recommends slates with the highest pCTR items. This agent assumes knowledge of the true underlying choice model. Note that this implicitly means it receives observations of the true user and document states. This agent myopically creates slates with items that have the highest probability of being clicked... | GreedyPCTRAgent | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GreedyPCTRAgent:
"""An agent that recommends slates with the highest pCTR items. This agent assumes knowledge of the true underlying choice model. Note that this implicitly means it receives observations of the true user and document states. This agent myopically creates slates with items that ha... | stack_v2_sparse_classes_75kplus_train_004756 | 3,737 | permissive | [
{
"docstring": "Initializes a new greedy pCTR agent. Args: action_space: A gym.spaces object that specifies the format of actions belief_state: An instantiation of AbstractUserState assumed by the agent choice_model: An instantiation of AbstractChoiceModel assumed by the agent Default to a multinomial logit cho... | 3 | stack_v2_sparse_classes_30k_train_034997 | Implement the Python class `GreedyPCTRAgent` described below.
Class description:
An agent that recommends slates with the highest pCTR items. This agent assumes knowledge of the true underlying choice model. Note that this implicitly means it receives observations of the true user and document states. This agent myopi... | Implement the Python class `GreedyPCTRAgent` described below.
Class description:
An agent that recommends slates with the highest pCTR items. This agent assumes knowledge of the true underlying choice model. Note that this implicitly means it receives observations of the true user and document states. This agent myopi... | 63fcacb177a029196abe57910bde88f737d5cca0 | <|skeleton|>
class GreedyPCTRAgent:
"""An agent that recommends slates with the highest pCTR items. This agent assumes knowledge of the true underlying choice model. Note that this implicitly means it receives observations of the true user and document states. This agent myopically creates slates with items that ha... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GreedyPCTRAgent:
"""An agent that recommends slates with the highest pCTR items. This agent assumes knowledge of the true underlying choice model. Note that this implicitly means it receives observations of the true user and document states. This agent myopically creates slates with items that have the highes... | the_stack_v2_python_sparse | recsim/agents/greedy_pctr_agent.py | kittipatv/recsim-no-tf | train | 1 |
c595cf5f401124fd4d1d87de06275a0f9760f6d8 | [
"login_url = conf.get('env', 'base_url') + '/member/login'\nlogin_data = {'mobile_phone': phone, 'pwd': pwd}\nlogin_headers = eval(conf.get('env', 'headers'))\nlogin_response = request(url=login_url, method='post', json=login_data, headers=login_headers)\nlogin_res = login_response.json()\nmember_id = str(jsonpath.... | <|body_start_0|>
login_url = conf.get('env', 'base_url') + '/member/login'
login_data = {'mobile_phone': phone, 'pwd': pwd}
login_headers = eval(conf.get('env', 'headers'))
login_response = request(url=login_url, method='post', json=login_data, headers=login_headers)
login_res = ... | 封装一个前置条件的类 | HandleBase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HandleBase:
"""封装一个前置条件的类"""
def read_user_info(cls, phone, pwd):
"""用例执行的前置条件:登录"""
<|body_0|>
def add_projcet(self):
"""添加一个项目"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
login_url = conf.get('env', 'base_url') + '/member/login'
lo... | stack_v2_sparse_classes_75kplus_train_004757 | 2,497 | no_license | [
{
"docstring": "用例执行的前置条件:登录",
"name": "read_user_info",
"signature": "def read_user_info(cls, phone, pwd)"
},
{
"docstring": "添加一个项目",
"name": "add_projcet",
"signature": "def add_projcet(self)"
}
] | 2 | null | Implement the Python class `HandleBase` described below.
Class description:
封装一个前置条件的类
Method signatures and docstrings:
- def read_user_info(cls, phone, pwd): 用例执行的前置条件:登录
- def add_projcet(self): 添加一个项目 | Implement the Python class `HandleBase` described below.
Class description:
封装一个前置条件的类
Method signatures and docstrings:
- def read_user_info(cls, phone, pwd): 用例执行的前置条件:登录
- def add_projcet(self): 添加一个项目
<|skeleton|>
class HandleBase:
"""封装一个前置条件的类"""
def read_user_info(cls, phone, pwd):
"""用例执行的前置... | 8af59d8f68fba0b3116caa34276f884976de7bc3 | <|skeleton|>
class HandleBase:
"""封装一个前置条件的类"""
def read_user_info(cls, phone, pwd):
"""用例执行的前置条件:登录"""
<|body_0|>
def add_projcet(self):
"""添加一个项目"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HandleBase:
"""封装一个前置条件的类"""
def read_user_info(cls, phone, pwd):
"""用例执行的前置条件:登录"""
login_url = conf.get('env', 'base_url') + '/member/login'
login_data = {'mobile_phone': phone, 'pwd': pwd}
login_headers = eval(conf.get('env', 'headers'))
login_response = request... | the_stack_v2_python_sparse | common/handle_Base.py | jindy-mine/bohe_api_test | train | 0 |
da54c21c67470cdb821e654825981d60f1384450 | [
"self.classes, self.class_to_idx, self.imgs = self.get_imgs_classes(image_dir_list, shuffle=True)\nself.comment_transform = comment_transform\nself.s_transform = s_transform\nself.t_transform = t_transform\nself.repeat = repeat",
"image_path = self.imgs[idx][0]\nlabel_id = self.imgs[idx][1]\nimage = self.read_ima... | <|body_start_0|>
self.classes, self.class_to_idx, self.imgs = self.get_imgs_classes(image_dir_list, shuffle=True)
self.comment_transform = comment_transform
self.s_transform = s_transform
self.t_transform = t_transform
self.repeat = repeat
<|end_body_0|>
<|body_start_1|>
... | Pytorch Dataset | KDImageFolderDataset | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KDImageFolderDataset:
"""Pytorch Dataset"""
def __init__(self, image_dir_list, comment_transform=None, s_transform=None, t_transform=None, repeat=1):
""":param image_dir_list: [image_dir]->list or `path/to/image_dir`->str :param comment_transform: :param s_transform: student transfor... | stack_v2_sparse_classes_75kplus_train_004758 | 11,116 | no_license | [
{
"docstring": ":param image_dir_list: [image_dir]->list or `path/to/image_dir`->str :param comment_transform: :param s_transform: student transform :param t_transform: teacher transform :param repeat: 所有样本数据重复次数,默认循环一次,当repeat为None时,表示无限循环<sys.maxsize",
"name": "__init__",
"signature": "def __init__(se... | 2 | stack_v2_sparse_classes_30k_train_027922 | Implement the Python class `KDImageFolderDataset` described below.
Class description:
Pytorch Dataset
Method signatures and docstrings:
- def __init__(self, image_dir_list, comment_transform=None, s_transform=None, t_transform=None, repeat=1): :param image_dir_list: [image_dir]->list or `path/to/image_dir`->str :para... | Implement the Python class `KDImageFolderDataset` described below.
Class description:
Pytorch Dataset
Method signatures and docstrings:
- def __init__(self, image_dir_list, comment_transform=None, s_transform=None, t_transform=None, repeat=1): :param image_dir_list: [image_dir]->list or `path/to/image_dir`->str :para... | 98257e64224722e54d5e593ffc53aa7f5589af99 | <|skeleton|>
class KDImageFolderDataset:
"""Pytorch Dataset"""
def __init__(self, image_dir_list, comment_transform=None, s_transform=None, t_transform=None, repeat=1):
""":param image_dir_list: [image_dir]->list or `path/to/image_dir`->str :param comment_transform: :param s_transform: student transfor... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KDImageFolderDataset:
"""Pytorch Dataset"""
def __init__(self, image_dir_list, comment_transform=None, s_transform=None, t_transform=None, repeat=1):
""":param image_dir_list: [image_dir]->list or `path/to/image_dir`->str :param comment_transform: :param s_transform: student transform :param t_tr... | the_stack_v2_python_sparse | models/dataloader/imagefolder_dataset.py | PanJinquan/torch-image-classification-pipeline | train | 3 |
f78cd926255e44ae77bfa3c6edc6bc67bbd6589f | [
"if len(strs) == 0:\n return ''\nmin_len = min([len(s) for s in strs])\nprefix = ''\nfor i in range(min_len):\n if not self.is_common_char(strs, i):\n break\n prefix += strs[0][i]\nreturn prefix",
"num_strs = len(strs)\nfor j in range(num_strs - 1):\n current_str = strs[j]\n next_str = strs[... | <|body_start_0|>
if len(strs) == 0:
return ''
min_len = min([len(s) for s in strs])
prefix = ''
for i in range(min_len):
if not self.is_common_char(strs, i):
break
prefix += strs[0][i]
return prefix
<|end_body_0|>
<|body_start_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
"""(Solution, list of str) -> str Return the longest common prefix among the strings in strs. >>> soln = Solution() >>> soln.longestCommonPrefix(["flower", "flow", "flight"]) "fl" >>> soln.longestCommonPrefix(["dog", "racec... | stack_v2_sparse_classes_75kplus_train_004759 | 2,237 | no_license | [
{
"docstring": "(Solution, list of str) -> str Return the longest common prefix among the strings in strs. >>> soln = Solution() >>> soln.longestCommonPrefix([\"flower\", \"flow\", \"flight\"]) \"fl\" >>> soln.longestCommonPrefix([\"dog\", \"racecar\", \"car\"]) \"\"",
"name": "longestCommonPrefix",
"si... | 2 | stack_v2_sparse_classes_30k_train_031388 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonPrefix(self, strs: List[str]) -> str: (Solution, list of str) -> str Return the longest common prefix among the strings in strs. >>> soln = Solution() >>> soln.l... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonPrefix(self, strs: List[str]) -> str: (Solution, list of str) -> str Return the longest common prefix among the strings in strs. >>> soln = Solution() >>> soln.l... | 6812253b90bdd5a35c6bfba8eac54da9be26d56c | <|skeleton|>
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
"""(Solution, list of str) -> str Return the longest common prefix among the strings in strs. >>> soln = Solution() >>> soln.longestCommonPrefix(["flower", "flow", "flight"]) "fl" >>> soln.longestCommonPrefix(["dog", "racec... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
"""(Solution, list of str) -> str Return the longest common prefix among the strings in strs. >>> soln = Solution() >>> soln.longestCommonPrefix(["flower", "flow", "flight"]) "fl" >>> soln.longestCommonPrefix(["dog", "racecar", "car"]) "... | the_stack_v2_python_sparse | python3/longestCommonPrefix.py | yichuanma95/leetcode-solns | train | 2 | |
0f0042bac6280e2f134fee52d022bc8c142dd402 | [
"nums = map(int, str(n))\nll = len(nums)\nans = []\n\ndef dfs(pos, prev, fr, flag):\n e = 9\n if pos >= ll:\n return\n to = 9\n if flag:\n to = nums[pos]\n for i in xrange(fr, to + 1):\n x = prev + i\n ans.append(x)\n newflag = 0\n if i <= nums[pos]:\n ... | <|body_start_0|>
nums = map(int, str(n))
ll = len(nums)
ans = []
def dfs(pos, prev, fr, flag):
e = 9
if pos >= ll:
return
to = 9
if flag:
to = nums[pos]
for i in xrange(fr, to + 1):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lexicalOrderWA(self, n):
""":type n: int :rtype: List[int]"""
<|body_0|>
def lexicalOrderWA2(self, n):
""":type n: int :rtype: List[int]"""
<|body_1|>
def lexicalOrder(self, n):
""":type n: int :rtype: List[int]"""
<|body_2|... | stack_v2_sparse_classes_75kplus_train_004760 | 3,020 | no_license | [
{
"docstring": ":type n: int :rtype: List[int]",
"name": "lexicalOrderWA",
"signature": "def lexicalOrderWA(self, n)"
},
{
"docstring": ":type n: int :rtype: List[int]",
"name": "lexicalOrderWA2",
"signature": "def lexicalOrderWA2(self, n)"
},
{
"docstring": ":type n: int :rtype:... | 3 | stack_v2_sparse_classes_30k_train_042194 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lexicalOrderWA(self, n): :type n: int :rtype: List[int]
- def lexicalOrderWA2(self, n): :type n: int :rtype: List[int]
- def lexicalOrder(self, n): :type n: int :rtype: List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lexicalOrderWA(self, n): :type n: int :rtype: List[int]
- def lexicalOrderWA2(self, n): :type n: int :rtype: List[int]
- def lexicalOrder(self, n): :type n: int :rtype: List[... | 02ebe56cd92b9f4baeee132c5077892590018650 | <|skeleton|>
class Solution:
def lexicalOrderWA(self, n):
""":type n: int :rtype: List[int]"""
<|body_0|>
def lexicalOrderWA2(self, n):
""":type n: int :rtype: List[int]"""
<|body_1|>
def lexicalOrder(self, n):
""":type n: int :rtype: List[int]"""
<|body_2|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def lexicalOrderWA(self, n):
""":type n: int :rtype: List[int]"""
nums = map(int, str(n))
ll = len(nums)
ans = []
def dfs(pos, prev, fr, flag):
e = 9
if pos >= ll:
return
to = 9
if flag:
... | the_stack_v2_python_sparse | python/leetcode.386.py | CalvinNeo/LeetCode | train | 3 | |
a3a777a18022111b81a565503bf9a2246dd90bbb | [
"super().__init__()\nif weights is not None and (not np.isclose(weights.sum(), 1)):\n raise ValueError('Weights must sum to 1.')\nself.weights = weights",
"if self.weights is None:\n m = scores.shape[-1]\n self.weights = torch.ones(m, device=scores.device) / m\nreturn scores @ self.weights"
] | <|body_start_0|>
super().__init__()
if weights is not None and (not np.isclose(weights.sum(), 1)):
raise ValueError('Weights must sum to 1.')
self.weights = weights
<|end_body_0|>
<|body_start_1|>
if self.weights is None:
m = scores.shape[-1]
self.wei... | AverageAggregator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AverageAggregator:
def __init__(self, weights: Optional[torch.Tensor]=None):
"""Averages the scores of the detectors in an ensemble. Parameters ---------- weights Optional parameter to weight the scores. If `weights` is left ``None`` then will be set to a vector of ones. Raises ------ Va... | stack_v2_sparse_classes_75kplus_train_004761 | 9,337 | permissive | [
{
"docstring": "Averages the scores of the detectors in an ensemble. Parameters ---------- weights Optional parameter to weight the scores. If `weights` is left ``None`` then will be set to a vector of ones. Raises ------ ValueError If `weights` does not sum to ``1``.",
"name": "__init__",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_007235 | Implement the Python class `AverageAggregator` described below.
Class description:
Implement the AverageAggregator class.
Method signatures and docstrings:
- def __init__(self, weights: Optional[torch.Tensor]=None): Averages the scores of the detectors in an ensemble. Parameters ---------- weights Optional parameter ... | Implement the Python class `AverageAggregator` described below.
Class description:
Implement the AverageAggregator class.
Method signatures and docstrings:
- def __init__(self, weights: Optional[torch.Tensor]=None): Averages the scores of the detectors in an ensemble. Parameters ---------- weights Optional parameter ... | 4a1b4f74a8590117965421e86c2295bff0f33e89 | <|skeleton|>
class AverageAggregator:
def __init__(self, weights: Optional[torch.Tensor]=None):
"""Averages the scores of the detectors in an ensemble. Parameters ---------- weights Optional parameter to weight the scores. If `weights` is left ``None`` then will be set to a vector of ones. Raises ------ Va... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AverageAggregator:
def __init__(self, weights: Optional[torch.Tensor]=None):
"""Averages the scores of the detectors in an ensemble. Parameters ---------- weights Optional parameter to weight the scores. If `weights` is left ``None`` then will be set to a vector of ones. Raises ------ ValueError If `w... | the_stack_v2_python_sparse | alibi_detect/od/pytorch/ensemble.py | SeldonIO/alibi-detect | train | 1,922 | |
711f41e07c4bb3e3d411357225c2232a88d00d5c | [
"self.input_fc = kwargs['input_fc']\nself.network_data_source = kwargs['network_data_source']\nself.travel_mode = kwargs['travel_mode']\nself.scratch_folder = kwargs['scratch_folder']\nself.search_tolerance = kwargs.get('search_tolerance', None)\nself.search_criteria = kwargs.get('search_criteria', None)\nself.sear... | <|body_start_0|>
self.input_fc = kwargs['input_fc']
self.network_data_source = kwargs['network_data_source']
self.travel_mode = kwargs['travel_mode']
self.scratch_folder = kwargs['scratch_folder']
self.search_tolerance = kwargs.get('search_tolerance', None)
self.search_cr... | Used for calculating network locations for a designated chunk of the input datasets. | LocationCalculator | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocationCalculator:
"""Used for calculating network locations for a designated chunk of the input datasets."""
def __init__(self, **kwargs):
"""Initialize the location calculator for the given inputs. Expected arguments: - input_fc - network_data_source - travel_mode - search_toleran... | stack_v2_sparse_classes_75kplus_train_004762 | 17,175 | permissive | [
{
"docstring": "Initialize the location calculator for the given inputs. Expected arguments: - input_fc - network_data_source - travel_mode - search_tolerance - search_criteria - search_query - scratch_folder",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Cr... | 3 | stack_v2_sparse_classes_30k_train_046579 | Implement the Python class `LocationCalculator` described below.
Class description:
Used for calculating network locations for a designated chunk of the input datasets.
Method signatures and docstrings:
- def __init__(self, **kwargs): Initialize the location calculator for the given inputs. Expected arguments: - inpu... | Implement the Python class `LocationCalculator` described below.
Class description:
Used for calculating network locations for a designated chunk of the input datasets.
Method signatures and docstrings:
- def __init__(self, **kwargs): Initialize the location calculator for the given inputs. Expected arguments: - inpu... | 47cbc3de67a7b1bf9255e07e88cba7b051db0505 | <|skeleton|>
class LocationCalculator:
"""Used for calculating network locations for a designated chunk of the input datasets."""
def __init__(self, **kwargs):
"""Initialize the location calculator for the given inputs. Expected arguments: - input_fc - network_data_source - travel_mode - search_toleran... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LocationCalculator:
"""Used for calculating network locations for a designated chunk of the input datasets."""
def __init__(self, **kwargs):
"""Initialize the location calculator for the given inputs. Expected arguments: - input_fc - network_data_source - travel_mode - search_tolerance - search_c... | the_stack_v2_python_sparse | transit-network-analysis-tools/parallel_calculate_locations.py | Esri/public-transit-tools | train | 155 |
b0a33f953ce2ea0868b27034c614ba8b8f02c92b | [
"self.__inimator = Animator()\nself.__bounds = Rect(250, 0, 0, 0)\nself.__bounds.size = self.__inimator.add_animation('moving', 500, 'peach/peach', 2, 2)\nself.__bounds.bottom = 79\nself.__timer = Timer(550)\nself.__help = load_img('misc/help', 2)\nself.__showHelp = True",
"self.__inimator.update(_dt)\nself.__tim... | <|body_start_0|>
self.__inimator = Animator()
self.__bounds = Rect(250, 0, 0, 0)
self.__bounds.size = self.__inimator.add_animation('moving', 500, 'peach/peach', 2, 2)
self.__bounds.bottom = 79
self.__timer = Timer(550)
self.__help = load_img('misc/help', 2)
self.... | Objeto que representa a la princesa Peach | Peach | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Peach:
"""Objeto que representa a la princesa Peach"""
def __init__(self):
"""Constructor"""
<|body_0|>
def update(self, _dt):
"""Actualiza todos los elementos del objeto. Parámetros: _dt -- Tiempo en milisegundos que ha transcurrido desde la última vez que se ll... | stack_v2_sparse_classes_75kplus_train_004763 | 1,396 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Actualiza todos los elementos del objeto. Parámetros: _dt -- Tiempo en milisegundos que ha transcurrido desde la última vez que se llamó el método.",
"name": "update",
"signature": "def... | 3 | stack_v2_sparse_classes_30k_train_036636 | Implement the Python class `Peach` described below.
Class description:
Objeto que representa a la princesa Peach
Method signatures and docstrings:
- def __init__(self): Constructor
- def update(self, _dt): Actualiza todos los elementos del objeto. Parámetros: _dt -- Tiempo en milisegundos que ha transcurrido desde la... | Implement the Python class `Peach` described below.
Class description:
Objeto que representa a la princesa Peach
Method signatures and docstrings:
- def __init__(self): Constructor
- def update(self, _dt): Actualiza todos los elementos del objeto. Parámetros: _dt -- Tiempo en milisegundos que ha transcurrido desde la... | 9d8a3058001d22cf252a993b3a31e648c31926e6 | <|skeleton|>
class Peach:
"""Objeto que representa a la princesa Peach"""
def __init__(self):
"""Constructor"""
<|body_0|>
def update(self, _dt):
"""Actualiza todos los elementos del objeto. Parámetros: _dt -- Tiempo en milisegundos que ha transcurrido desde la última vez que se ll... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Peach:
"""Objeto que representa a la princesa Peach"""
def __init__(self):
"""Constructor"""
self.__inimator = Animator()
self.__bounds = Rect(250, 0, 0, 0)
self.__bounds.size = self.__inimator.add_animation('moving', 500, 'peach/peach', 2, 2)
self.__bounds.bottom ... | the_stack_v2_python_sparse | Donkey Kong 1981/peach.py | lorentealberto/Speed-Coding | train | 2 |
8450b240d02591891e5eaa9ecf7e66ef7a724a0c | [
"if 'debug' in kwargs:\n warnings.warn('Keyword debug has been deprecated.', DeprecationWarning)\nif device is None:\n from .pl_server.device import Device\n device = Device.active_device\nself.device = device\nif base_addr < 0 or length < 0:\n raise ValueError('Base address or length cannot be negative... | <|body_start_0|>
if 'debug' in kwargs:
warnings.warn('Keyword debug has been deprecated.', DeprecationWarning)
if device is None:
from .pl_server.device import Device
device = Device.active_device
self.device = device
if base_addr < 0 or length < 0:
... | This class exposes API for MMIO read and write. Attributes ---------- base_addr : int The base address, not necessarily page aligned. length : int The length in bytes of the address range. array : numpy.ndarray A numpy view of the mapped range for efficient assignment device : Device A device that can interact with the... | MMIO | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MMIO:
"""This class exposes API for MMIO read and write. Attributes ---------- base_addr : int The base address, not necessarily page aligned. length : int The length in bytes of the address range. array : numpy.ndarray A numpy view of the mapped range for efficient assignment device : Device A d... | stack_v2_sparse_classes_75kplus_train_004764 | 5,926 | permissive | [
{
"docstring": "Return a new MMIO object. Parameters ---------- base_addr : int The base address of the MMIO. length : int The length in bytes; default is 4. device: Device The device that MMIO object is created for.",
"name": "__init__",
"signature": "def __init__(self, base_addr, length=4, device=None... | 4 | stack_v2_sparse_classes_30k_train_016979 | Implement the Python class `MMIO` described below.
Class description:
This class exposes API for MMIO read and write. Attributes ---------- base_addr : int The base address, not necessarily page aligned. length : int The length in bytes of the address range. array : numpy.ndarray A numpy view of the mapped range for e... | Implement the Python class `MMIO` described below.
Class description:
This class exposes API for MMIO read and write. Attributes ---------- base_addr : int The base address, not necessarily page aligned. length : int The length in bytes of the address range. array : numpy.ndarray A numpy view of the mapped range for e... | de6b6fc3a803945d59f8f06523addfe0d9b60a1c | <|skeleton|>
class MMIO:
"""This class exposes API for MMIO read and write. Attributes ---------- base_addr : int The base address, not necessarily page aligned. length : int The length in bytes of the address range. array : numpy.ndarray A numpy view of the mapped range for efficient assignment device : Device A d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MMIO:
"""This class exposes API for MMIO read and write. Attributes ---------- base_addr : int The base address, not necessarily page aligned. length : int The length in bytes of the address range. array : numpy.ndarray A numpy view of the mapped range for efficient assignment device : Device A device that ca... | the_stack_v2_python_sparse | pynq/mmio.py | schelleg/PYNQ | train | 1 |
e79b490b705321399b6e5cb043f32511a1afcd44 | [
"self.wait_until_element_is_visible(self.BUTTON_CONFIRM)\nkey_confirm_delete = 'Delete key'\nself.element_should_contain(self.DIALOG_CONTENT, key_confirm_delete)\nkey_confirm_key_name = text\nself.element_should_contain(self.DIALOG_CONTENT, key_confirm_key_name)\nself.click_element(self.BUTTON_CONFIRM)\nsleep(1)",
... | <|body_start_0|>
self.wait_until_element_is_visible(self.BUTTON_CONFIRM)
key_confirm_delete = 'Delete key'
self.element_should_contain(self.DIALOG_CONTENT, key_confirm_delete)
key_confirm_key_name = text
self.element_should_contain(self.DIALOG_CONTENT, key_confirm_key_name)
... | Pagemodel Changelog: * 27.07.2017 | Docstrings updated | Ss_keys_and_cert_dlg_delete | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ss_keys_and_cert_dlg_delete:
"""Pagemodel Changelog: * 27.07.2017 | Docstrings updated"""
def click_delete_cert_confirm(self, text):
"""Click button to confirm certificate deletion :param text: String value for text"""
<|body_0|>
def click_unregister_and_delete_cert_conf... | stack_v2_sparse_classes_75kplus_train_004765 | 3,198 | permissive | [
{
"docstring": "Click button to confirm certificate deletion :param text: String value for text",
"name": "click_delete_cert_confirm",
"signature": "def click_delete_cert_confirm(self, text)"
},
{
"docstring": "Click button to confirm certificate deletion :param text: String value for text",
... | 2 | stack_v2_sparse_classes_30k_train_048767 | Implement the Python class `Ss_keys_and_cert_dlg_delete` described below.
Class description:
Pagemodel Changelog: * 27.07.2017 | Docstrings updated
Method signatures and docstrings:
- def click_delete_cert_confirm(self, text): Click button to confirm certificate deletion :param text: String value for text
- def click... | Implement the Python class `Ss_keys_and_cert_dlg_delete` described below.
Class description:
Pagemodel Changelog: * 27.07.2017 | Docstrings updated
Method signatures and docstrings:
- def click_delete_cert_confirm(self, text): Click button to confirm certificate deletion :param text: String value for text
- def click... | e030661a0ad8ceab74dd8122b751e88025a3474a | <|skeleton|>
class Ss_keys_and_cert_dlg_delete:
"""Pagemodel Changelog: * 27.07.2017 | Docstrings updated"""
def click_delete_cert_confirm(self, text):
"""Click button to confirm certificate deletion :param text: String value for text"""
<|body_0|>
def click_unregister_and_delete_cert_conf... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Ss_keys_and_cert_dlg_delete:
"""Pagemodel Changelog: * 27.07.2017 | Docstrings updated"""
def click_delete_cert_confirm(self, text):
"""Click button to confirm certificate deletion :param text: String value for text"""
self.wait_until_element_is_visible(self.BUTTON_CONFIRM)
key_co... | the_stack_v2_python_sparse | common/xrd-ui-tests-qautomate/pagemodel/ss_keys_and_cert_dlg_delete.py | nordic-institute/X-Road-tests | train | 2 |
0bc8f06883bba94701140f5b19f89c8dcca42059 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Proto file describing the Campaign Draft service. Service to manage campaign drafts. | CampaignDraftServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CampaignDraftServiceServicer:
"""Proto file describing the Campaign Draft service. Service to manage campaign drafts."""
def GetCampaignDraft(self, request, context):
"""Returns the requested campaign draft in full detail."""
<|body_0|>
def MutateCampaignDrafts(self, req... | stack_v2_sparse_classes_75kplus_train_004766 | 10,577 | permissive | [
{
"docstring": "Returns the requested campaign draft in full detail.",
"name": "GetCampaignDraft",
"signature": "def GetCampaignDraft(self, request, context)"
},
{
"docstring": "Creates, updates, or removes campaign drafts. Operation statuses are returned.",
"name": "MutateCampaignDrafts",
... | 4 | stack_v2_sparse_classes_30k_train_037493 | Implement the Python class `CampaignDraftServiceServicer` described below.
Class description:
Proto file describing the Campaign Draft service. Service to manage campaign drafts.
Method signatures and docstrings:
- def GetCampaignDraft(self, request, context): Returns the requested campaign draft in full detail.
- de... | Implement the Python class `CampaignDraftServiceServicer` described below.
Class description:
Proto file describing the Campaign Draft service. Service to manage campaign drafts.
Method signatures and docstrings:
- def GetCampaignDraft(self, request, context): Returns the requested campaign draft in full detail.
- de... | a5b6cede64f4d9912ae6ad26927a54e40448c9fe | <|skeleton|>
class CampaignDraftServiceServicer:
"""Proto file describing the Campaign Draft service. Service to manage campaign drafts."""
def GetCampaignDraft(self, request, context):
"""Returns the requested campaign draft in full detail."""
<|body_0|>
def MutateCampaignDrafts(self, req... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CampaignDraftServiceServicer:
"""Proto file describing the Campaign Draft service. Service to manage campaign drafts."""
def GetCampaignDraft(self, request, context):
"""Returns the requested campaign draft in full detail."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context... | the_stack_v2_python_sparse | google/ads/google_ads/v5/proto/services/campaign_draft_service_pb2_grpc.py | fiboknacky/google-ads-python | train | 0 |
dd0b105c69a8379e3deba813f791b9cb73b1e711 | [
"hash_map = {}\nvote = defaultdict(int)\ncnt_max = float('-inf')\ncnt_person = -1\nfor idx, t in enumerate(times):\n vote[persons[idx]] += 1\n if vote[persons[idx]] >= cnt_max:\n cnt_person = persons[idx]\n cnt_max = vote[persons[idx]]\n hash_map[t] = cnt_person\nself.hash_map = hash_map\nsel... | <|body_start_0|>
hash_map = {}
vote = defaultdict(int)
cnt_max = float('-inf')
cnt_person = -1
for idx, t in enumerate(times):
vote[persons[idx]] += 1
if vote[persons[idx]] >= cnt_max:
cnt_person = persons[idx]
cnt_max = vot... | TopVotedCandidate | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopVotedCandidate:
def __init__(self, persons, times):
""":type persons: List[int] :type times: List[int]"""
<|body_0|>
def q(self, t):
""":type t: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
hash_map = {}
vote = defaultd... | stack_v2_sparse_classes_75kplus_train_004767 | 1,190 | permissive | [
{
"docstring": ":type persons: List[int] :type times: List[int]",
"name": "__init__",
"signature": "def __init__(self, persons, times)"
},
{
"docstring": ":type t: int :rtype: int",
"name": "q",
"signature": "def q(self, t)"
}
] | 2 | stack_v2_sparse_classes_30k_train_053795 | Implement the Python class `TopVotedCandidate` described below.
Class description:
Implement the TopVotedCandidate class.
Method signatures and docstrings:
- def __init__(self, persons, times): :type persons: List[int] :type times: List[int]
- def q(self, t): :type t: int :rtype: int | Implement the Python class `TopVotedCandidate` described below.
Class description:
Implement the TopVotedCandidate class.
Method signatures and docstrings:
- def __init__(self, persons, times): :type persons: List[int] :type times: List[int]
- def q(self, t): :type t: int :rtype: int
<|skeleton|>
class TopVotedCandi... | fc5b1744af7be93f4dd01d6ad58d2bd12f7ed33f | <|skeleton|>
class TopVotedCandidate:
def __init__(self, persons, times):
""":type persons: List[int] :type times: List[int]"""
<|body_0|>
def q(self, t):
""":type t: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TopVotedCandidate:
def __init__(self, persons, times):
""":type persons: List[int] :type times: List[int]"""
hash_map = {}
vote = defaultdict(int)
cnt_max = float('-inf')
cnt_person = -1
for idx, t in enumerate(times):
vote[persons[idx]] += 1
... | the_stack_v2_python_sparse | 911.Online-Election.py | mickey0524/leetcode | train | 27 | |
975a3228a2fcfefbfb673ea5e55c60f7e24781c5 | [
"self.protocol = protocol\nself.srp = srp\nself._atv_salt = None\nself._atv_pub_key = None",
"self.srp.initialize()\nawait self.protocol.start(skip_initial_messages=True)\nmsg = messages.crypto_pairing({TlvValue.Method: b'\\x00', TlvValue.SeqNo: b'\\x01'}, is_pairing=True)\nresp = await self.protocol.send_and_rec... | <|body_start_0|>
self.protocol = protocol
self.srp = srp
self._atv_salt = None
self._atv_pub_key = None
<|end_body_0|>
<|body_start_1|>
self.srp.initialize()
await self.protocol.start(skip_initial_messages=True)
msg = messages.crypto_pairing({TlvValue.Method: b'\... | Perform pairing and return new credentials. | MrpPairingProcedure | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MrpPairingProcedure:
"""Perform pairing and return new credentials."""
def __init__(self, protocol, srp):
"""Initialize a new MrpPairingHandler."""
<|body_0|>
async def start_pairing(self):
"""Start pairing procedure."""
<|body_1|>
async def finish_p... | stack_v2_sparse_classes_75kplus_train_004768 | 4,164 | permissive | [
{
"docstring": "Initialize a new MrpPairingHandler.",
"name": "__init__",
"signature": "def __init__(self, protocol, srp)"
},
{
"docstring": "Start pairing procedure.",
"name": "start_pairing",
"signature": "async def start_pairing(self)"
},
{
"docstring": "Finish pairing process... | 3 | stack_v2_sparse_classes_30k_train_014686 | Implement the Python class `MrpPairingProcedure` described below.
Class description:
Perform pairing and return new credentials.
Method signatures and docstrings:
- def __init__(self, protocol, srp): Initialize a new MrpPairingHandler.
- async def start_pairing(self): Start pairing procedure.
- async def finish_pairi... | Implement the Python class `MrpPairingProcedure` described below.
Class description:
Perform pairing and return new credentials.
Method signatures and docstrings:
- def __init__(self, protocol, srp): Initialize a new MrpPairingHandler.
- async def start_pairing(self): Start pairing procedure.
- async def finish_pairi... | 94f3b88f1aa122f21a21b8595952146ffc3f39bf | <|skeleton|>
class MrpPairingProcedure:
"""Perform pairing and return new credentials."""
def __init__(self, protocol, srp):
"""Initialize a new MrpPairingHandler."""
<|body_0|>
async def start_pairing(self):
"""Start pairing procedure."""
<|body_1|>
async def finish_p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MrpPairingProcedure:
"""Perform pairing and return new credentials."""
def __init__(self, protocol, srp):
"""Initialize a new MrpPairingHandler."""
self.protocol = protocol
self.srp = srp
self._atv_salt = None
self._atv_pub_key = None
async def start_pairing(s... | the_stack_v2_python_sparse | pyatv/mrp/auth.py | w2816771/pyatv | train | 0 |
f605488facc2275a78bde7da08091e75c70f6ca5 | [
"form = ArtistForm()\ncontexto = {'form': form}\nreturn render(request, self.template, contexto)",
"form = ArtistForm(request.POST)\ncontexto = {'form': form}\nif not form.is_valid():\n return render(request, self.template, contexto)\nartista = Artist.objects.create(name=form.cleaned_data['name'], image=form.c... | <|body_start_0|>
form = ArtistForm()
contexto = {'form': form}
return render(request, self.template, contexto)
<|end_body_0|>
<|body_start_1|>
form = ArtistForm(request.POST)
contexto = {'form': form}
if not form.is_valid():
return render(request, self.templa... | New Artist. | ArtistView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArtistView:
"""New Artist."""
def get(self, request):
"""Render sign up form."""
<|body_0|>
def post(self, request):
"""Receive and validate sign up form."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
form = ArtistForm()
contexto = {'f... | stack_v2_sparse_classes_75kplus_train_004769 | 1,232 | no_license | [
{
"docstring": "Render sign up form.",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Receive and validate sign up form.",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013103 | Implement the Python class `ArtistView` described below.
Class description:
New Artist.
Method signatures and docstrings:
- def get(self, request): Render sign up form.
- def post(self, request): Receive and validate sign up form. | Implement the Python class `ArtistView` described below.
Class description:
New Artist.
Method signatures and docstrings:
- def get(self, request): Render sign up form.
- def post(self, request): Receive and validate sign up form.
<|skeleton|>
class ArtistView:
"""New Artist."""
def get(self, request):
... | 3d43ecaaddb51d47a929eb5c3ec26caf3f8955c6 | <|skeleton|>
class ArtistView:
"""New Artist."""
def get(self, request):
"""Render sign up form."""
<|body_0|>
def post(self, request):
"""Receive and validate sign up form."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ArtistView:
"""New Artist."""
def get(self, request):
"""Render sign up form."""
form = ArtistForm()
contexto = {'form': form}
return render(request, self.template, contexto)
def post(self, request):
"""Receive and validate sign up form."""
form = Arti... | the_stack_v2_python_sparse | Prácticas/CatMusic/music/views.py | SaraIncin/IngenieriaSoftware | train | 0 |
6145b38b46939d669f7d673572337bb8cad2a191 | [
"question_wrapper = get_question_or_404(request.user, quiz_id, round_id, question_id)\ncontext = {'quiz_id': quiz_id, 'round_id': round_id, 'question_id': question_id, 'question': question_wrapper.host_info(), 'question_types': dict(QuestionType.choices), 'slide_types': dict(SlideType.choices), 'QuestionClass': Que... | <|body_start_0|>
question_wrapper = get_question_or_404(request.user, quiz_id, round_id, question_id)
context = {'quiz_id': quiz_id, 'round_id': round_id, 'question_id': question_id, 'question': question_wrapper.host_info(), 'question_types': dict(QuestionType.choices), 'slide_types': dict(SlideType.cho... | EditQuestionView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EditQuestionView:
def get(self, request, quiz_id, round_id, question_id):
"""Render the form to edit a question Attributes: None"""
<|body_0|>
def post(self, request, quiz_id, round_id, question_id):
"""Edit the attributes of the question model Attributes: PARAMS: - ... | stack_v2_sparse_classes_75kplus_train_004770 | 2,660 | no_license | [
{
"docstring": "Render the form to edit a question Attributes: None",
"name": "get",
"signature": "def get(self, request, quiz_id, round_id, question_id)"
},
{
"docstring": "Edit the attributes of the question model Attributes: PARAMS: - quiz_id, round_id, question_id POST: - question_info",
... | 2 | stack_v2_sparse_classes_30k_train_048416 | Implement the Python class `EditQuestionView` described below.
Class description:
Implement the EditQuestionView class.
Method signatures and docstrings:
- def get(self, request, quiz_id, round_id, question_id): Render the form to edit a question Attributes: None
- def post(self, request, quiz_id, round_id, question_... | Implement the Python class `EditQuestionView` described below.
Class description:
Implement the EditQuestionView class.
Method signatures and docstrings:
- def get(self, request, quiz_id, round_id, question_id): Render the form to edit a question Attributes: None
- def post(self, request, quiz_id, round_id, question_... | 923b8af85eda6136d4e815deb0f5c76ce22e2fc0 | <|skeleton|>
class EditQuestionView:
def get(self, request, quiz_id, round_id, question_id):
"""Render the form to edit a question Attributes: None"""
<|body_0|>
def post(self, request, quiz_id, round_id, question_id):
"""Edit the attributes of the question model Attributes: PARAMS: - ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EditQuestionView:
def get(self, request, quiz_id, round_id, question_id):
"""Render the form to edit a question Attributes: None"""
question_wrapper = get_question_or_404(request.user, quiz_id, round_id, question_id)
context = {'quiz_id': quiz_id, 'round_id': round_id, 'question_id': q... | the_stack_v2_python_sparse | quiz/views/question.py | AananthV/Quizwin | train | 0 | |
40f09033bb6759e5f7e09a8301c9b8cdb7040ae2 | [
"def preorder(root):\n serialization = []\n stack = [root]\n node = None\n while stack:\n node = stack.pop()\n serialization.append(str(node.val))\n node.right and stack.append(node.right)\n node.left and stack.append(node.left)\n return serialization\n\ndef inorder(root):... | <|body_start_0|>
def preorder(root):
serialization = []
stack = [root]
node = None
while stack:
node = stack.pop()
serialization.append(str(node.val))
node.right and stack.append(node.right)
node.left... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_004771 | 2,065 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_050897 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 97533d53c8892b6519e99f344489fa4fd4c9ab93 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def preorder(root):
serialization = []
stack = [root]
node = None
while stack:
node = stack.pop()
serializ... | the_stack_v2_python_sparse | 8. Tree/449.py | proTao/leetcode | train | 0 | |
e2e528e508d7d4c92d7add2a19d2bd03d681e926 | [
"self.POINT_HEAD_ACTION_NAME = point_head_action_name\nself.client = actionlib.SimpleActionClient(self.POINT_HEAD_ACTION_NAME, PointHeadAction)\nrospy.loginfo('Waiting for head_controller...')\nself.client.wait_for_server()",
"goal = PointHeadGoal()\ngoal.target.header.stamp = rospy.Time.now()\ngoal.target.header... | <|body_start_0|>
self.POINT_HEAD_ACTION_NAME = point_head_action_name
self.client = actionlib.SimpleActionClient(self.POINT_HEAD_ACTION_NAME, PointHeadAction)
rospy.loginfo('Waiting for head_controller...')
self.client.wait_for_server()
<|end_body_0|>
<|body_start_1|>
goal = Poi... | PointHeadClient | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PointHeadClient:
def __init__(self, point_head_action_name='head_controller/point_head'):
"""Parameters ---------- point_head_action_name : TYPE, optional DESCRIPTION. The default is "head_controller/point_head". Returns ------- None."""
<|body_0|>
def look_at(self, x=1, y=0... | stack_v2_sparse_classes_75kplus_train_004772 | 4,738 | no_license | [
{
"docstring": "Parameters ---------- point_head_action_name : TYPE, optional DESCRIPTION. The default is \"head_controller/point_head\". Returns ------- None.",
"name": "__init__",
"signature": "def __init__(self, point_head_action_name='head_controller/point_head')"
},
{
"docstring": "Paramete... | 2 | stack_v2_sparse_classes_30k_train_033677 | Implement the Python class `PointHeadClient` described below.
Class description:
Implement the PointHeadClient class.
Method signatures and docstrings:
- def __init__(self, point_head_action_name='head_controller/point_head'): Parameters ---------- point_head_action_name : TYPE, optional DESCRIPTION. The default is "... | Implement the Python class `PointHeadClient` described below.
Class description:
Implement the PointHeadClient class.
Method signatures and docstrings:
- def __init__(self, point_head_action_name='head_controller/point_head'): Parameters ---------- point_head_action_name : TYPE, optional DESCRIPTION. The default is "... | 1a8c0bc62e91dfa3d3d5567d4b78815e613e95d1 | <|skeleton|>
class PointHeadClient:
def __init__(self, point_head_action_name='head_controller/point_head'):
"""Parameters ---------- point_head_action_name : TYPE, optional DESCRIPTION. The default is "head_controller/point_head". Returns ------- None."""
<|body_0|>
def look_at(self, x=1, y=0... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PointHeadClient:
def __init__(self, point_head_action_name='head_controller/point_head'):
"""Parameters ---------- point_head_action_name : TYPE, optional DESCRIPTION. The default is "head_controller/point_head". Returns ------- None."""
self.POINT_HEAD_ACTION_NAME = point_head_action_name
... | the_stack_v2_python_sparse | mobile_manipulation/src/head_control/head_control_utils.py | osuprg/fetch_mobile_manipulation | train | 4 | |
2f9ece28686590645c682044e131c640ca2ccc4f | [
"user = getUser(username)\nif user is None:\n raise UnknownUserError([username])\ncreateTwitterUser(user, uid)",
"result = getTwitterUsers(uids=[uid]).one()\nif result is not None:\n return result[0]\nelse:\n return None"
] | <|body_start_0|>
user = getUser(username)
if user is None:
raise UnknownUserError([username])
createTwitterUser(user, uid)
<|end_body_0|>
<|body_start_1|>
result = getTwitterUsers(uids=[uid]).one()
if result is not None:
return result[0]
else:
... | The public API for L{TwitterUser}s in the model layer. | TwitterUserAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwitterUserAPI:
"""The public API for L{TwitterUser}s in the model layer."""
def create(self, username, uid):
"""Create a L{TwitterUser} mapping a UID to the specified username. @param username: The L{User.username} the UID is for. @param uid: The Twitter UID for the specified Fluidi... | stack_v2_sparse_classes_75kplus_train_004773 | 9,808 | permissive | [
{
"docstring": "Create a L{TwitterUser} mapping a UID to the specified username. @param username: The L{User.username} the UID is for. @param uid: The Twitter UID for the specified Fluidinfo user. @raise UnknownUserError: Raised if the specified L{User} doesn't exist.",
"name": "create",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_049820 | Implement the Python class `TwitterUserAPI` described below.
Class description:
The public API for L{TwitterUser}s in the model layer.
Method signatures and docstrings:
- def create(self, username, uid): Create a L{TwitterUser} mapping a UID to the specified username. @param username: The L{User.username} the UID is ... | Implement the Python class `TwitterUserAPI` described below.
Class description:
The public API for L{TwitterUser}s in the model layer.
Method signatures and docstrings:
- def create(self, username, uid): Create a L{TwitterUser} mapping a UID to the specified username. @param username: The L{User.username} the UID is ... | b5a8c8349f3eaf3364cc4efba4736c3e33b30d96 | <|skeleton|>
class TwitterUserAPI:
"""The public API for L{TwitterUser}s in the model layer."""
def create(self, username, uid):
"""Create a L{TwitterUser} mapping a UID to the specified username. @param username: The L{User.username} the UID is for. @param uid: The Twitter UID for the specified Fluidi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TwitterUserAPI:
"""The public API for L{TwitterUser}s in the model layer."""
def create(self, username, uid):
"""Create a L{TwitterUser} mapping a UID to the specified username. @param username: The L{User.username} the UID is for. @param uid: The Twitter UID for the specified Fluidinfo user. @ra... | the_stack_v2_python_sparse | fluiddb/model/user.py | fluidinfo/fluiddb | train | 3 |
6bb9624ad6794e35bfa301abc06b194e4e4d66a2 | [
"ratingData = request.data.get('rate', {})\nrating = ratingData.get('rating', None)\nnote = ratingData.get('note', None)\nif not isinstance(rating, int):\n return Response({'message': 'Rating should be an integer'}, status=status.HTTP_401_UNAUTHORIZED)\nif rating < 1 or rating > 5:\n return Response({'error':... | <|body_start_0|>
ratingData = request.data.get('rate', {})
rating = ratingData.get('rating', None)
note = ratingData.get('note', None)
if not isinstance(rating, int):
return Response({'message': 'Rating should be an integer'}, status=status.HTTP_401_UNAUTHORIZED)
if r... | RateArticlesAPIView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RateArticlesAPIView:
def post(self, request, slug):
"""Method that posts users article ratings"""
<|body_0|>
def get(self, request, slug):
"""Method that posts users article ratings"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ratingData = reques... | stack_v2_sparse_classes_75kplus_train_004774 | 24,455 | permissive | [
{
"docstring": "Method that posts users article ratings",
"name": "post",
"signature": "def post(self, request, slug)"
},
{
"docstring": "Method that posts users article ratings",
"name": "get",
"signature": "def get(self, request, slug)"
}
] | 2 | stack_v2_sparse_classes_30k_train_036647 | Implement the Python class `RateArticlesAPIView` described below.
Class description:
Implement the RateArticlesAPIView class.
Method signatures and docstrings:
- def post(self, request, slug): Method that posts users article ratings
- def get(self, request, slug): Method that posts users article ratings | Implement the Python class `RateArticlesAPIView` described below.
Class description:
Implement the RateArticlesAPIView class.
Method signatures and docstrings:
- def post(self, request, slug): Method that posts users article ratings
- def get(self, request, slug): Method that posts users article ratings
<|skeleton|>... | ebe3a4621a5baf36a9345d4b126ba73dc37acd1f | <|skeleton|>
class RateArticlesAPIView:
def post(self, request, slug):
"""Method that posts users article ratings"""
<|body_0|>
def get(self, request, slug):
"""Method that posts users article ratings"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RateArticlesAPIView:
def post(self, request, slug):
"""Method that posts users article ratings"""
ratingData = request.data.get('rate', {})
rating = ratingData.get('rating', None)
note = ratingData.get('note', None)
if not isinstance(rating, int):
return Res... | the_stack_v2_python_sparse | authors/apps/articles/views.py | andela/ah-leagueOfLegends | train | 0 | |
e7604ed3ca0b5e41f97e5f7aa3cb550eecb484dc | [
"if isinstance(key, int):\n return Option(key)\nif key not in Option._member_map_:\n return extend_enum(Option, key, default)\nreturn Option[key]",
"if not (isinstance(value, int) and 0 <= value <= 255):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nreturn extend_enum(cls, 'Unassign... | <|body_start_0|>
if isinstance(key, int):
return Option(key)
if key not in Option._member_map_:
return extend_enum(Option, key, default)
return Option[key]
<|end_body_0|>
<|body_start_1|>
if not (isinstance(value, int) and 0 <= value <= 255):
raise Va... | [Option] Mobility Options | Option | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Option:
"""[Option] Mobility Options"""
def get(key: 'int | str', default: 'int'=-1) -> 'Option':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
<|body_0|>
def _missing_(cls, value: 'int') -... | stack_v2_sparse_classes_75kplus_train_004775 | 7,031 | permissive | [
{
"docstring": "Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:",
"name": "get",
"signature": "def get(key: 'int | str', default: 'int'=-1) -> 'Option'"
},
{
"docstring": "Lookup function used when value is not found. Args... | 2 | stack_v2_sparse_classes_30k_train_046171 | Implement the Python class `Option` described below.
Class description:
[Option] Mobility Options
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'Option': Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:
- de... | Implement the Python class `Option` described below.
Class description:
[Option] Mobility Options
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'Option': Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:
- de... | a6fe49ec58f09e105bec5a00fb66d9b3f22730d9 | <|skeleton|>
class Option:
"""[Option] Mobility Options"""
def get(key: 'int | str', default: 'int'=-1) -> 'Option':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
<|body_0|>
def _missing_(cls, value: 'int') -... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Option:
"""[Option] Mobility Options"""
def get(key: 'int | str', default: 'int'=-1) -> 'Option':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
if isinstance(key, int):
return Option(key)
... | the_stack_v2_python_sparse | pcapkit/const/mh/option.py | JarryShaw/PyPCAPKit | train | 204 |
a6dc1f106b74fa38f0ac347f58cb471c772f34e3 | [
"args = post_get_parser.parse_args()\nresult_post = post_manager.get_post_by_post_uuid(post_uuid, args['user_uuid'])\nreturn (result_post, 200)",
"args = post_edit_parser.parse_args()\ntry:\n post_manager.edit_post(post_uuid, args)\n return ({'message': 'post has been edited successfully.'}, 200)\nexcept Ex... | <|body_start_0|>
args = post_get_parser.parse_args()
result_post = post_manager.get_post_by_post_uuid(post_uuid, args['user_uuid'])
return (result_post, 200)
<|end_body_0|>
<|body_start_1|>
args = post_edit_parser.parse_args()
try:
post_manager.edit_post(post_uuid, a... | PostItem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostItem:
def get(self, post_uuid, category):
"""Gets a post given its UUID"""
<|body_0|>
def put(self, post_uuid, category):
"""Updates an existing post's information"""
<|body_1|>
def delete(self, post_uuid, category):
"""Deletes a post"""
... | stack_v2_sparse_classes_75kplus_train_004776 | 4,854 | no_license | [
{
"docstring": "Gets a post given its UUID",
"name": "get",
"signature": "def get(self, post_uuid, category)"
},
{
"docstring": "Updates an existing post's information",
"name": "put",
"signature": "def put(self, post_uuid, category)"
},
{
"docstring": "Deletes a post",
"name... | 3 | stack_v2_sparse_classes_30k_train_036450 | Implement the Python class `PostItem` described below.
Class description:
Implement the PostItem class.
Method signatures and docstrings:
- def get(self, post_uuid, category): Gets a post given its UUID
- def put(self, post_uuid, category): Updates an existing post's information
- def delete(self, post_uuid, category... | Implement the Python class `PostItem` described below.
Class description:
Implement the PostItem class.
Method signatures and docstrings:
- def get(self, post_uuid, category): Gets a post given its UUID
- def put(self, post_uuid, category): Updates an existing post's information
- def delete(self, post_uuid, category... | 6a336a5a391621edf0f3f85929ab4dd3df59d6ae | <|skeleton|>
class PostItem:
def get(self, post_uuid, category):
"""Gets a post given its UUID"""
<|body_0|>
def put(self, post_uuid, category):
"""Updates an existing post's information"""
<|body_1|>
def delete(self, post_uuid, category):
"""Deletes a post"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PostItem:
def get(self, post_uuid, category):
"""Gets a post given its UUID"""
args = post_get_parser.parse_args()
result_post = post_manager.get_post_by_post_uuid(post_uuid, args['user_uuid'])
return (result_post, 200)
def put(self, post_uuid, category):
"""Update... | the_stack_v2_python_sparse | post_service/controllers/post_controller.py | garywu2/TLreaDR | train | 6 | |
5a9d44d0f051cebea90f9ae4c100f87488109118 | [
"self.ha = abstract.sdk.libs.abstracted_libs.ha.HA(device=uut)\nfor lc in self.mapping.keys:\n for key, value in lc.items():\n if lcRole and lcRole not in key:\n continue\n try:\n self.ha.reloadLc(timeout=self.timeout, steps=steps, lc=value)\n except Exception as e:\n ... | <|body_start_0|>
self.ha = abstract.sdk.libs.abstracted_libs.ha.HA(device=uut)
for lc in self.mapping.keys:
for key, value in lc.items():
if lcRole and lcRole not in key:
continue
try:
self.ha.reloadLc(timeout=self.timeo... | Trigger class for Reload LCs action | TriggerReloadLc | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TriggerReloadLc:
"""Trigger class for Reload LCs action"""
def reload(self, uut, abstract, steps, lcRole=None):
"""Reload LC and reconnect to device if needed Args: uut (`obj`): Device object. abstract (`obj`): Abstract object. steps (`step obj`): aetest step object Returns: None Rai... | stack_v2_sparse_classes_75kplus_train_004777 | 11,289 | permissive | [
{
"docstring": "Reload LC and reconnect to device if needed Args: uut (`obj`): Device object. abstract (`obj`): Abstract object. steps (`step obj`): aetest step object Returns: None Raises: pyATS Results",
"name": "reload",
"signature": "def reload(self, uut, abstract, steps, lcRole=None)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_009569 | Implement the Python class `TriggerReloadLc` described below.
Class description:
Trigger class for Reload LCs action
Method signatures and docstrings:
- def reload(self, uut, abstract, steps, lcRole=None): Reload LC and reconnect to device if needed Args: uut (`obj`): Device object. abstract (`obj`): Abstract object.... | Implement the Python class `TriggerReloadLc` described below.
Class description:
Trigger class for Reload LCs action
Method signatures and docstrings:
- def reload(self, uut, abstract, steps, lcRole=None): Reload LC and reconnect to device if needed Args: uut (`obj`): Device object. abstract (`obj`): Abstract object.... | 880a341030f53739ce509154a041030a842ee672 | <|skeleton|>
class TriggerReloadLc:
"""Trigger class for Reload LCs action"""
def reload(self, uut, abstract, steps, lcRole=None):
"""Reload LC and reconnect to device if needed Args: uut (`obj`): Device object. abstract (`obj`): Abstract object. steps (`step obj`): aetest step object Returns: None Rai... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TriggerReloadLc:
"""Trigger class for Reload LCs action"""
def reload(self, uut, abstract, steps, lcRole=None):
"""Reload LC and reconnect to device if needed Args: uut (`obj`): Device object. abstract (`obj`): Abstract object. steps (`step obj`): aetest step object Returns: None Raises: pyATS Re... | the_stack_v2_python_sparse | pkgs/sdk-pkg/src/genie/libs/sdk/triggers/ha/ha.py | karmoham/genielibs | train | 0 |
c3ab16220b5902f75045e7bbb8d1a43f0bd8deb9 | [
"super(TextLineInputter, self).__init__(dataset, batch_size)\nif self._batch_size is None:\n raise ValueError('batch_size should be provided.')\nif not hasattr(dataset, data_field_name):\n raise ValueError('dataset object has no attribute named \"{}\"'.format(data_field_name))\nself._data_files = getattr(data... | <|body_start_0|>
super(TextLineInputter, self).__init__(dataset, batch_size)
if self._batch_size is None:
raise ValueError('batch_size should be provided.')
if not hasattr(dataset, data_field_name):
raise ValueError('dataset object has no attribute named "{}"'.format(data... | Class for reading in source side lines or target side lines. | TextLineInputter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextLineInputter:
"""Class for reading in source side lines or target side lines."""
def __init__(self, dataset, data_field_name, batch_size):
"""Initializes the parameters for this inputter. Args: dataset: A `Dataset` object. data_field_name: The attribute name of dataset that has a... | stack_v2_sparse_classes_75kplus_train_004778 | 29,753 | permissive | [
{
"docstring": "Initializes the parameters for this inputter. Args: dataset: A `Dataset` object. data_field_name: The attribute name of dataset that has access to a data file. batch_size: An integer value indicating the number of sentences passed into one step. Sentences will be padded by EOS. Raises: ValueErro... | 3 | stack_v2_sparse_classes_30k_train_044082 | Implement the Python class `TextLineInputter` described below.
Class description:
Class for reading in source side lines or target side lines.
Method signatures and docstrings:
- def __init__(self, dataset, data_field_name, batch_size): Initializes the parameters for this inputter. Args: dataset: A `Dataset` object. ... | Implement the Python class `TextLineInputter` described below.
Class description:
Class for reading in source side lines or target side lines.
Method signatures and docstrings:
- def __init__(self, dataset, data_field_name, batch_size): Initializes the parameters for this inputter. Args: dataset: A `Dataset` object. ... | 01155c740705f1641ebf3134829cea0e212f2d28 | <|skeleton|>
class TextLineInputter:
"""Class for reading in source side lines or target side lines."""
def __init__(self, dataset, data_field_name, batch_size):
"""Initializes the parameters for this inputter. Args: dataset: A `Dataset` object. data_field_name: The attribute name of dataset that has a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TextLineInputter:
"""Class for reading in source side lines or target side lines."""
def __init__(self, dataset, data_field_name, batch_size):
"""Initializes the parameters for this inputter. Args: dataset: A `Dataset` object. data_field_name: The attribute name of dataset that has access to a da... | the_stack_v2_python_sparse | njunmt/data/text_inputter.py | zhaocq-nlp/NJUNMT-tf | train | 114 |
8b866c78099d0cbbf5ad687c2ce7ed91def4abe6 | [
"self.logger = logger.SecureTeaLogger(__name__, debug=debug)\nself.syn_dict = dict()\nself._THRESHOLD = 1000",
"if pkt.haslayer(scapy.IP) and pkt.haslayer(scapy.TCP):\n flag = pkt[scapy.TCP].flags\n source_ip = pkt[scapy.IP].src\n if flag == 'S':\n if self.syn_dict.get(source_ip) is None:\n ... | <|body_start_0|>
self.logger = logger.SecureTeaLogger(__name__, debug=debug)
self.syn_dict = dict()
self._THRESHOLD = 1000
<|end_body_0|>
<|body_start_1|>
if pkt.haslayer(scapy.IP) and pkt.haslayer(scapy.TCP):
flag = pkt[scapy.TCP].flags
source_ip = pkt[scapy.IP]... | SynFlood Class. | SynFlood | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SynFlood:
"""SynFlood Class."""
def __init__(self, debug=False):
"""Initialize SynFlood. Args: debug (bool): Log on terminal or not Raises: None Returns: None"""
<|body_0|>
def detect_syn_flood(self, pkt):
"""Detect SYN flood attack. Args: pkt (scapy_object): Pac... | stack_v2_sparse_classes_75kplus_train_004779 | 3,170 | permissive | [
{
"docstring": "Initialize SynFlood. Args: debug (bool): Log on terminal or not Raises: None Returns: None",
"name": "__init__",
"signature": "def __init__(self, debug=False)"
},
{
"docstring": "Detect SYN flood attack. Args: pkt (scapy_object): Packet to dissect and observe Raises: None Returns... | 3 | null | Implement the Python class `SynFlood` described below.
Class description:
SynFlood Class.
Method signatures and docstrings:
- def __init__(self, debug=False): Initialize SynFlood. Args: debug (bool): Log on terminal or not Raises: None Returns: None
- def detect_syn_flood(self, pkt): Detect SYN flood attack. Args: pk... | Implement the Python class `SynFlood` described below.
Class description:
SynFlood Class.
Method signatures and docstrings:
- def __init__(self, debug=False): Initialize SynFlood. Args: debug (bool): Log on terminal or not Raises: None Returns: None
- def detect_syn_flood(self, pkt): Detect SYN flood attack. Args: pk... | 43dec187e5848b9ced8a6b4957b6e9028d4d43cd | <|skeleton|>
class SynFlood:
"""SynFlood Class."""
def __init__(self, debug=False):
"""Initialize SynFlood. Args: debug (bool): Log on terminal or not Raises: None Returns: None"""
<|body_0|>
def detect_syn_flood(self, pkt):
"""Detect SYN flood attack. Args: pkt (scapy_object): Pac... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SynFlood:
"""SynFlood Class."""
def __init__(self, debug=False):
"""Initialize SynFlood. Args: debug (bool): Log on terminal or not Raises: None Returns: None"""
self.logger = logger.SecureTeaLogger(__name__, debug=debug)
self.syn_dict = dict()
self._THRESHOLD = 1000
... | the_stack_v2_python_sparse | securetea/lib/ids/r2l_rules/syn_flood.py | rejahrehim/SecureTea-Project | train | 1 |
234bf63c9005d3e1e95d4239536d7a91edf01da3 | [
"if not root:\n print('serialize: ', '')\n return ''\nqueue = collections.deque([root])\nstringArr = []\nstring = ''\nlayer = 1\nnum_in_layer = 2 ** (layer - 1)\nwhile queue:\n level = []\n for _ in range(len(queue)):\n node = queue.popleft()\n if node:\n queue.append(node.left)... | <|body_start_0|>
if not root:
print('serialize: ', '')
return ''
queue = collections.deque([root])
stringArr = []
string = ''
layer = 1
num_in_layer = 2 ** (layer - 1)
while queue:
level = []
for _ in range(len(queue... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_004780 | 6,668 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_046109 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | ca95110b77152258573b6f1d43e39a316cdcb459 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
print('serialize: ', '')
return ''
queue = collections.deque([root])
stringArr = []
string = ''
layer = 1
num... | the_stack_v2_python_sparse | algo/tree/_0297_SerializeAndDeserializeBinaryTree.py | ianlai/Note-Python | train | 0 | |
e455ec1d33a2049cb5e4f243dec4d077abcdee6b | [
"self.capacity = capacity\nself.record = {}\nself.linkedlist = LinkedList()",
"if key not in self.record:\n return -1\nself.linkedlist.advance(self.record[key])\nreturn self.record[key].val",
"if key not in self.record:\n node = ListNode(key, value)\n self.linkedlist.appendHead(node)\n self.record[k... | <|body_start_0|>
self.capacity = capacity
self.record = {}
self.linkedlist = LinkedList()
<|end_body_0|>
<|body_start_1|>
if key not in self.record:
return -1
self.linkedlist.advance(self.record[key])
return self.record[key].val
<|end_body_1|>
<|body_start_2... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_75kplus_train_004781 | 2,042 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: nothing",
"name": "set",
"sig... | 3 | stack_v2_sparse_classes_30k_train_036317 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing
<|skeleton|>
cla... | 3d82e6c402711057a95a6435fc29fbfcf2ee9c8f | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.record = {}
self.linkedlist = LinkedList()
def get(self, key):
""":rtype: int"""
if key not in self.record:
return -1
self.linkedlist.advance... | the_stack_v2_python_sparse | Google/LRU cache.py | KeleiAzz/LeetCode | train | 0 | |
49084f5dafc4602d0b36ad5e4a5c61ed221cdfe5 | [
"if not root:\n return None\nif not root.left and (not root.right):\n return root.val\nmax_sum_path = [0]\nself.dfs(root, max_sum_path)\nreturn max_sum_path[0]",
"if not node:\n return 0\nlsum = self.dfs(node.left, max_sum_path)\nrsum = self.dfs(node.right, max_sum_path)\nnode_sum = max([node.val, node.v... | <|body_start_0|>
if not root:
return None
if not root.left and (not root.right):
return root.val
max_sum_path = [0]
self.dfs(root, max_sum_path)
return max_sum_path[0]
<|end_body_0|>
<|body_start_1|>
if not node:
return 0
lsum ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxPathSum(self, root):
"""Given a non-empty binary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and ... | stack_v2_sparse_classes_75kplus_train_004782 | 2,386 | no_license | [
{
"docstring": "Given a non-empty binary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root. Example 1: ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxPathSum(self, root): Given a non-empty binary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes from some starting node to any ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxPathSum(self, root): Given a non-empty binary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes from some starting node to any ... | 08c6d27498e35f636045fed05a6f94b760ab69ca | <|skeleton|>
class Solution:
def maxPathSum(self, root):
"""Given a non-empty binary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxPathSum(self, root):
"""Given a non-empty binary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need ... | the_stack_v2_python_sparse | solutions/tree/124.Binary.Tree.Maximum.Path.Sum.py | ljia2/leetcode.py | train | 0 | |
3fa5d64b61e3b70681364fe428f0faada1c2c08d | [
"self.startFormatted = self.context.start.strftime('%-d %B %Y')\nself.endFormatted = self.context.end.strftime('%-d %B %Y')\nself.period = self.startFormatted + ' - ' + self.endFormatted\nif self.context.start.year == self.context.end.year:\n if self.context.start.month == self.context.end.month:\n self.p... | <|body_start_0|>
self.startFormatted = self.context.start.strftime('%-d %B %Y')
self.endFormatted = self.context.end.strftime('%-d %B %Y')
self.period = self.startFormatted + ' - ' + self.endFormatted
if self.context.start.year == self.context.end.year:
if self.context.start.... | Default view (called "@@view"") for a exhibition. The associated template is found in exhibition_templates/view.pt. | View | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class View:
"""Default view (called "@@view"") for a exhibition. The associated template is found in exhibition_templates/view.pt."""
def update(self):
"""Prepare information for the template"""
<|body_0|>
def images(self):
"""Return catalog search results of images to... | stack_v2_sparse_classes_75kplus_train_004783 | 3,830 | no_license | [
{
"docstring": "Prepare information for the template",
"name": "update",
"signature": "def update(self)"
},
{
"docstring": "Return catalog search results of images to show",
"name": "images",
"signature": "def images(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_032238 | Implement the Python class `View` described below.
Class description:
Default view (called "@@view"") for a exhibition. The associated template is found in exhibition_templates/view.pt.
Method signatures and docstrings:
- def update(self): Prepare information for the template
- def images(self): Return catalog search... | Implement the Python class `View` described below.
Class description:
Default view (called "@@view"") for a exhibition. The associated template is found in exhibition_templates/view.pt.
Method signatures and docstrings:
- def update(self): Prepare information for the template
- def images(self): Return catalog search... | da53064c6e09573676ca1cc6f0a3397808c5329f | <|skeleton|>
class View:
"""Default view (called "@@view"") for a exhibition. The associated template is found in exhibition_templates/view.pt."""
def update(self):
"""Prepare information for the template"""
<|body_0|>
def images(self):
"""Return catalog search results of images to... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class View:
"""Default view (called "@@view"") for a exhibition. The associated template is found in exhibition_templates/view.pt."""
def update(self):
"""Prepare information for the template"""
self.startFormatted = self.context.start.strftime('%-d %B %Y')
self.endFormatted = self.cont... | the_stack_v2_python_sparse | irwilot.content/irwilot/content/exhibition.py | kbat/obonato | train | 0 |
6414437c81b9ad76c593edc83c3d1c0858426c43 | [
"self.client = None\nself.username = username\nself.password = password",
"hostname = socket.gethostname()\nclient = xmpp.Client(self.jid.getDomain(), debug=[])\nserver = (self.server, 5222)\nif not client.connect(server):\n print('Cannot connect to %s server. Please, check your internet connection. Exit...' %... | <|body_start_0|>
self.client = None
self.username = username
self.password = password
<|end_body_0|>
<|body_start_1|>
hostname = socket.gethostname()
client = xmpp.Client(self.jid.getDomain(), debug=[])
server = (self.server, 5222)
if not client.connect(server):
... | Simple class to work with Facebook over XMPP protocol. | Facebook | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Facebook:
"""Simple class to work with Facebook over XMPP protocol."""
def __init__(self, username, password):
"""Remember your Facebook username and password as instance attributes."""
<|body_0|>
def connect(self):
"""Tries to connect to the Facebook using store... | stack_v2_sparse_classes_75kplus_train_004784 | 9,919 | permissive | [
{
"docstring": "Remember your Facebook username and password as instance attributes.",
"name": "__init__",
"signature": "def __init__(self, username, password)"
},
{
"docstring": "Tries to connect to the Facebook using stored credentials. If cannot - exit from the script.",
"name": "connect"... | 4 | null | Implement the Python class `Facebook` described below.
Class description:
Simple class to work with Facebook over XMPP protocol.
Method signatures and docstrings:
- def __init__(self, username, password): Remember your Facebook username and password as instance attributes.
- def connect(self): Tries to connect to the... | Implement the Python class `Facebook` described below.
Class description:
Simple class to work with Facebook over XMPP protocol.
Method signatures and docstrings:
- def __init__(self, username, password): Remember your Facebook username and password as instance attributes.
- def connect(self): Tries to connect to the... | 665d39a2bd82543d5196555f0801ef8fd4a3ee48 | <|skeleton|>
class Facebook:
"""Simple class to work with Facebook over XMPP protocol."""
def __init__(self, username, password):
"""Remember your Facebook username and password as instance attributes."""
<|body_0|>
def connect(self):
"""Tries to connect to the Facebook using store... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Facebook:
"""Simple class to work with Facebook over XMPP protocol."""
def __init__(self, username, password):
"""Remember your Facebook username and password as instance attributes."""
self.client = None
self.username = username
self.password = password
def connect(s... | the_stack_v2_python_sparse | all-gists/1756417/snippet.py | gistable/gistable | train | 76 |
4311b19d705512be78719e0e4120f2de6e02a4ff | [
"super(BasicBlock, self).__init__()\nself.expansion = 1\nself.conv_cfg = conv_cfg\nself.norm_cfg = norm_cfg\nrequires_grad = self.norm_cfg['requires_grad'] if 'requires_grad' in self.norm_cfg else False\nif self.norm_cfg['type'] == 'BN':\n self.norm1 = norm_cfg_dict[self.norm_cfg['type']][1](planes)\n self.no... | <|body_start_0|>
super(BasicBlock, self).__init__()
self.expansion = 1
self.conv_cfg = conv_cfg
self.norm_cfg = norm_cfg
requires_grad = self.norm_cfg['requires_grad'] if 'requires_grad' in self.norm_cfg else False
if self.norm_cfg['type'] == 'BN':
self.norm1 ... | This is the class of BasicBlock block for ResNet. :param inplanes: input feature map channel num :type inplanes: int :param planes: output feature map channel num :type planes: int :param stride: stride :type stride: int :param dilation: dilation :type dilation: int :param downsample: downsample :param style: style, "p... | BasicBlock | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicBlock:
"""This is the class of BasicBlock block for ResNet. :param inplanes: input feature map channel num :type inplanes: int :param planes: output feature map channel num :type planes: int :param stride: stride :type stride: int :param dilation: dilation :type dilation: int :param downsamp... | stack_v2_sparse_classes_75kplus_train_004785 | 12,203 | permissive | [
{
"docstring": "Init BasicBlock.",
"name": "__init__",
"signature": "def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, style='pytorch', with_cp=False, conv_cfg={'type': 'Conv'}, norm_cfg={'type': 'BN'})"
},
{
"docstring": "Forward compute. :param x: input feature map :t... | 2 | stack_v2_sparse_classes_30k_train_036539 | Implement the Python class `BasicBlock` described below.
Class description:
This is the class of BasicBlock block for ResNet. :param inplanes: input feature map channel num :type inplanes: int :param planes: output feature map channel num :type planes: int :param stride: stride :type stride: int :param dilation: dilat... | Implement the Python class `BasicBlock` described below.
Class description:
This is the class of BasicBlock block for ResNet. :param inplanes: input feature map channel num :type inplanes: int :param planes: output feature map channel num :type planes: int :param stride: stride :type stride: int :param dilation: dilat... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class BasicBlock:
"""This is the class of BasicBlock block for ResNet. :param inplanes: input feature map channel num :type inplanes: int :param planes: output feature map channel num :type planes: int :param stride: stride :type stride: int :param dilation: dilation :type dilation: int :param downsamp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BasicBlock:
"""This is the class of BasicBlock block for ResNet. :param inplanes: input feature map channel num :type inplanes: int :param planes: output feature map channel num :type planes: int :param stride: stride :type stride: int :param dilation: dilation :type dilation: int :param downsample: downsampl... | the_stack_v2_python_sparse | built-in/TensorFlow/Research/cv/image_classification/Cars_for_TensorFlow/automl/vega/search_space/networks/pytorch/blocks/resnet_block_det.py | Huawei-Ascend/modelzoo | train | 1 |
dd8ae374a05e8b100aaa8a1e8cc5859d79ee6624 | [
"for i in range(1, len(l)):\n key = l[i]\n j = i - 1\n while j >= 0 and l[j] > key:\n l[j + 1] = l[j]\n j -= 1\n l[j + 1] = key\nreturn l",
"for i in range(len(l))[::-1]:\n change = False\n for j in range(0, i):\n if l[j] > l[j + 1]:\n l[j], l[j + 1] = (l[j + 1], ... | <|body_start_0|>
for i in range(1, len(l)):
key = l[i]
j = i - 1
while j >= 0 and l[j] > key:
l[j + 1] = l[j]
j -= 1
l[j + 1] = key
return l
<|end_body_0|>
<|body_start_1|>
for i in range(len(l))[::-1]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def insertSort(self, l: list) -> list:
"""分为已排序区间和未排序区间。 取未排序区间中的元素,在已排序区间中找到合适的位置插入,并保证已排序区间一直有序。 场景:类似打扑克时摸牌,新摸一张时插入手里已经排好序的牌中。"""
<|body_0|>
def bubbleSort(self, l: list) -> list:
"""冒泡排序比较相邻元素,每次都至少有一个元素移到最终位置。 如果一次比较没有发生数据交换,则已经有序。"""
<|body_1|... | stack_v2_sparse_classes_75kplus_train_004786 | 2,653 | no_license | [
{
"docstring": "分为已排序区间和未排序区间。 取未排序区间中的元素,在已排序区间中找到合适的位置插入,并保证已排序区间一直有序。 场景:类似打扑克时摸牌,新摸一张时插入手里已经排好序的牌中。",
"name": "insertSort",
"signature": "def insertSort(self, l: list) -> list"
},
{
"docstring": "冒泡排序比较相邻元素,每次都至少有一个元素移到最终位置。 如果一次比较没有发生数据交换,则已经有序。",
"name": "bubbleSort",
"signature": ... | 3 | stack_v2_sparse_classes_30k_train_030726 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def insertSort(self, l: list) -> list: 分为已排序区间和未排序区间。 取未排序区间中的元素,在已排序区间中找到合适的位置插入,并保证已排序区间一直有序。 场景:类似打扑克时摸牌,新摸一张时插入手里已经排好序的牌中。
- def bubbleSort(self, l: list) -> list: 冒泡排序比较相邻元素... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def insertSort(self, l: list) -> list: 分为已排序区间和未排序区间。 取未排序区间中的元素,在已排序区间中找到合适的位置插入,并保证已排序区间一直有序。 场景:类似打扑克时摸牌,新摸一张时插入手里已经排好序的牌中。
- def bubbleSort(self, l: list) -> list: 冒泡排序比较相邻元素... | 2bbb1640589aab34f2bc42489283033cc11fb885 | <|skeleton|>
class Solution:
def insertSort(self, l: list) -> list:
"""分为已排序区间和未排序区间。 取未排序区间中的元素,在已排序区间中找到合适的位置插入,并保证已排序区间一直有序。 场景:类似打扑克时摸牌,新摸一张时插入手里已经排好序的牌中。"""
<|body_0|>
def bubbleSort(self, l: list) -> list:
"""冒泡排序比较相邻元素,每次都至少有一个元素移到最终位置。 如果一次比较没有发生数据交换,则已经有序。"""
<|body_1|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def insertSort(self, l: list) -> list:
"""分为已排序区间和未排序区间。 取未排序区间中的元素,在已排序区间中找到合适的位置插入,并保证已排序区间一直有序。 场景:类似打扑克时摸牌,新摸一张时插入手里已经排好序的牌中。"""
for i in range(1, len(l)):
key = l[i]
j = i - 1
while j >= 0 and l[j] > key:
l[j + 1] = l[j]
... | the_stack_v2_python_sparse | 000_sort.py | helloocc/algorithm | train | 1 | |
01ba26ec049704468e50b8c53d05efe1fa7c12a3 | [
"self._configuration_id = configuration_id\nself._dispatcher = dispatcher\nself._pool = eventlet.GreenPool()",
"if args or kwargs:\n task = functools.partial(task, *args, **kwargs)\ntask_description = dumps(task)\ndispatcher_event = self._dispatcher.do_task(self._configuration_id, task_description)\nreturn eve... | <|body_start_0|>
self._configuration_id = configuration_id
self._dispatcher = dispatcher
self._pool = eventlet.GreenPool()
<|end_body_0|>
<|body_start_1|>
if args or kwargs:
task = functools.partial(task, *args, **kwargs)
task_description = dumps(task)
dispat... | The processor connects to a dispatcher and uses it to perform tasks | Processor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Processor:
"""The processor connects to a dispatcher and uses it to perform tasks"""
def __init__(self, configuration_id, dispatcher):
"""The configuration_id should be the hash of a configuration which is properly registered. The dispatcher should be a Dispatcher object"""
<... | stack_v2_sparse_classes_75kplus_train_004787 | 2,327 | no_license | [
{
"docstring": "The configuration_id should be the hash of a configuration which is properly registered. The dispatcher should be a Dispatcher object",
"name": "__init__",
"signature": "def __init__(self, configuration_id, dispatcher)"
},
{
"docstring": "Basic api, send a request task is the fun... | 4 | null | Implement the Python class `Processor` described below.
Class description:
The processor connects to a dispatcher and uses it to perform tasks
Method signatures and docstrings:
- def __init__(self, configuration_id, dispatcher): The configuration_id should be the hash of a configuration which is properly registered. ... | Implement the Python class `Processor` described below.
Class description:
The processor connects to a dispatcher and uses it to perform tasks
Method signatures and docstrings:
- def __init__(self, configuration_id, dispatcher): The configuration_id should be the hash of a configuration which is properly registered. ... | 905f19e4f4d3f100bfd64b47a3d56ad00be02323 | <|skeleton|>
class Processor:
"""The processor connects to a dispatcher and uses it to perform tasks"""
def __init__(self, configuration_id, dispatcher):
"""The configuration_id should be the hash of a configuration which is properly registered. The dispatcher should be a Dispatcher object"""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Processor:
"""The processor connects to a dispatcher and uses it to perform tasks"""
def __init__(self, configuration_id, dispatcher):
"""The configuration_id should be the hash of a configuration which is properly registered. The dispatcher should be a Dispatcher object"""
self._configur... | the_stack_v2_python_sparse | pymultinode/processor.py | inyoot/pymultinodes | train | 0 |
43c6aa72a23d19d87b7a43a5cf0a26d6bbfd83fb | [
"if hash_string is None:\n hash_string = self.get_hash(uploaded_file)\nuploaded_file.name = str(uuid4())\nimage = self.model(hash=hash_string, image_file=uploaded_file)\nimage.save()\nreturn image",
"hash_string = self.get_hash(uploaded_file)\ntry:\n return self.get(hash=hash_string)\nexcept self.model.Does... | <|body_start_0|>
if hash_string is None:
hash_string = self.get_hash(uploaded_file)
uploaded_file.name = str(uuid4())
image = self.model(hash=hash_string, image_file=uploaded_file)
image.save()
return image
<|end_body_0|>
<|body_start_1|>
hash_string = self.g... | Model manager for the ProductImage model. | ProductImageManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductImageManager:
"""Model manager for the ProductImage model."""
def add_image(self, uploaded_file, hash_string=None):
"""Add an image to the database."""
<|body_0|>
def get_or_add_image(self, uploaded_file):
"""Check if an image exists in the database and re... | stack_v2_sparse_classes_75kplus_train_004788 | 9,551 | no_license | [
{
"docstring": "Add an image to the database.",
"name": "add_image",
"signature": "def add_image(self, uploaded_file, hash_string=None)"
},
{
"docstring": "Check if an image exists in the database and return or create it.",
"name": "get_or_add_image",
"signature": "def get_or_add_image(s... | 3 | stack_v2_sparse_classes_30k_train_042664 | Implement the Python class `ProductImageManager` described below.
Class description:
Model manager for the ProductImage model.
Method signatures and docstrings:
- def add_image(self, uploaded_file, hash_string=None): Add an image to the database.
- def get_or_add_image(self, uploaded_file): Check if an image exists i... | Implement the Python class `ProductImageManager` described below.
Class description:
Model manager for the ProductImage model.
Method signatures and docstrings:
- def add_image(self, uploaded_file, hash_string=None): Add an image to the database.
- def get_or_add_image(self, uploaded_file): Check if an image exists i... | ba51d4e304b1aeb296fa2fe16611c892fcdbd471 | <|skeleton|>
class ProductImageManager:
"""Model manager for the ProductImage model."""
def add_image(self, uploaded_file, hash_string=None):
"""Add an image to the database."""
<|body_0|>
def get_or_add_image(self, uploaded_file):
"""Check if an image exists in the database and re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProductImageManager:
"""Model manager for the ProductImage model."""
def add_image(self, uploaded_file, hash_string=None):
"""Add an image to the database."""
if hash_string is None:
hash_string = self.get_hash(uploaded_file)
uploaded_file.name = str(uuid4())
i... | the_stack_v2_python_sparse | inventory/models/product_image.py | stcstores/stcadmin | train | 0 |
eb13f87f06d8f855b5d8cbe95bf19691567bb65f | [
"self.PC = init_PC\nself.npc = npc_line\nself.index_error_count = 0\nself.fetch_buffer = fetch_buffer\nself.instr_cache = instruction_cache",
"return_value = 0\nself.PC = self.npc[0]\ntry:\n self.fetch_buffer['IR'] = self.instr_cache[self.PC / 4]\n self.fetch_buffer['PC'] = self.PC\n self.index_error_cou... | <|body_start_0|>
self.PC = init_PC
self.npc = npc_line
self.index_error_count = 0
self.fetch_buffer = fetch_buffer
self.instr_cache = instruction_cache
<|end_body_0|>
<|body_start_1|>
return_value = 0
self.PC = self.npc[0]
try:
self.fetch_buff... | Fetch Stage of the Pipeline. Simply used to get the next instruction. | FetchStage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FetchStage:
"""Fetch Stage of the Pipeline. Simply used to get the next instruction."""
def __init__(self, init_PC, npc_line, fetch_buffer, instruction_cache):
"""Set the PC, fetch_buffer, and instruction_cache."""
<|body_0|>
def trigger_clock(self):
"""Put the n... | stack_v2_sparse_classes_75kplus_train_004789 | 1,405 | no_license | [
{
"docstring": "Set the PC, fetch_buffer, and instruction_cache.",
"name": "__init__",
"signature": "def __init__(self, init_PC, npc_line, fetch_buffer, instruction_cache)"
},
{
"docstring": "Put the next instruction into fetch_buffer. fetch_buffer contains: + PC + IR If there is an error, incre... | 2 | null | Implement the Python class `FetchStage` described below.
Class description:
Fetch Stage of the Pipeline. Simply used to get the next instruction.
Method signatures and docstrings:
- def __init__(self, init_PC, npc_line, fetch_buffer, instruction_cache): Set the PC, fetch_buffer, and instruction_cache.
- def trigger_c... | Implement the Python class `FetchStage` described below.
Class description:
Fetch Stage of the Pipeline. Simply used to get the next instruction.
Method signatures and docstrings:
- def __init__(self, init_PC, npc_line, fetch_buffer, instruction_cache): Set the PC, fetch_buffer, and instruction_cache.
- def trigger_c... | ecac52f69633136b72c85ddf41215b556e21cf9f | <|skeleton|>
class FetchStage:
"""Fetch Stage of the Pipeline. Simply used to get the next instruction."""
def __init__(self, init_PC, npc_line, fetch_buffer, instruction_cache):
"""Set the PC, fetch_buffer, and instruction_cache."""
<|body_0|>
def trigger_clock(self):
"""Put the n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FetchStage:
"""Fetch Stage of the Pipeline. Simply used to get the next instruction."""
def __init__(self, init_PC, npc_line, fetch_buffer, instruction_cache):
"""Set the PC, fetch_buffer, and instruction_cache."""
self.PC = init_PC
self.npc = npc_line
self.index_error_cou... | the_stack_v2_python_sparse | Superscalar-Processor/fetch_stage.py | pradeep90/Processor-Simulator | train | 1 |
dbfa531f3ea253d4b9fe8cbf7b1da0c9e2bd7f93 | [
"known_pulsars = np.recfromcsv(KNOWNPSR_FILENM, delimiter=';', comments='#', usecols=(1, 2, 3, 4, 5))\nself.known_names = known_pulsars['name']\nself.known_ras = known_pulsars['rajd']\nself.known_decs = known_pulsars['decjd']\nself.known_dms = known_pulsars['dm']",
"dm = cand.info['dm']\nra = cand.info['raj_deg']... | <|body_start_0|>
known_pulsars = np.recfromcsv(KNOWNPSR_FILENM, delimiter=';', comments='#', usecols=(1, 2, 3, 4, 5))
self.known_names = known_pulsars['name']
self.known_ras = known_pulsars['rajd']
self.known_decs = known_pulsars['decjd']
self.known_dms = known_pulsars['dm']
<|en... | KnownPulsarRater | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KnownPulsarRater:
def _setup(self):
"""A setup method to be called when the Rater is initialised Inputs: None Outputs: None"""
<|body_0|>
def _compute_rating(self, cand):
"""Return a rating for the candidate. The rating value encodes how close the candidate's positio... | stack_v2_sparse_classes_75kplus_train_004790 | 2,809 | no_license | [
{
"docstring": "A setup method to be called when the Rater is initialised Inputs: None Outputs: None",
"name": "_setup",
"signature": "def _setup(self)"
},
{
"docstring": "Return a rating for the candidate. The rating value encodes how close the candidate's position and DM are to that of a known... | 2 | stack_v2_sparse_classes_30k_train_026729 | Implement the Python class `KnownPulsarRater` described below.
Class description:
Implement the KnownPulsarRater class.
Method signatures and docstrings:
- def _setup(self): A setup method to be called when the Rater is initialised Inputs: None Outputs: None
- def _compute_rating(self, cand): Return a rating for the ... | Implement the Python class `KnownPulsarRater` described below.
Class description:
Implement the KnownPulsarRater class.
Method signatures and docstrings:
- def _setup(self): A setup method to be called when the Rater is initialised Inputs: None Outputs: None
- def _compute_rating(self, cand): Return a rating for the ... | e81c4926fbe5e4da2e923b10747bf3b844715ced | <|skeleton|>
class KnownPulsarRater:
def _setup(self):
"""A setup method to be called when the Rater is initialised Inputs: None Outputs: None"""
<|body_0|>
def _compute_rating(self, cand):
"""Return a rating for the candidate. The rating value encodes how close the candidate's positio... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KnownPulsarRater:
def _setup(self):
"""A setup method to be called when the Rater is initialised Inputs: None Outputs: None"""
known_pulsars = np.recfromcsv(KNOWNPSR_FILENM, delimiter=';', comments='#', usecols=(1, 2, 3, 4, 5))
self.known_names = known_pulsars['name']
self.know... | the_stack_v2_python_sparse | pipeline/lib/python/sp_raters/known_pulsar.py | ryanslynch/GBNCC-search | train | 2 | |
2b32495cb20ca877ec69de4ddaece7ebcbd0d9c4 | [
"hi = makehi(rip='127.100.0.10')\nfc = FakeCls('test', 10, 'foo-bar')\nr = msgs.format('%(class)s@%(lineno)d aka %(label)s: %(hostname)s', hi, fc)\nself.assertEqual(r, 'test@10 aka foo-bar: 127.100.0.10')\nself.assertEqual(msgs.format('%(frobnitz)s', hi, fc, frobnitz='foobar'), 'foobar')\nself.assertEqual(msgs.form... | <|body_start_0|>
hi = makehi(rip='127.100.0.10')
fc = FakeCls('test', 10, 'foo-bar')
r = msgs.format('%(class)s@%(lineno)d aka %(label)s: %(hostname)s', hi, fc)
self.assertEqual(r, 'test@10 aka foo-bar: 127.100.0.10')
self.assertEqual(msgs.format('%(frobnitz)s', hi, fc, frobnitz=... | basicTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class basicTests:
def testFormatMsg(self):
"""Test msgs.formatmsg() against some known values."""
<|body_0|>
def testExtraDict(self):
"""Test msgs.formatmsg()'s supplementary dictionary parameter."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
hi = makeh... | stack_v2_sparse_classes_75kplus_train_004791 | 1,491 | no_license | [
{
"docstring": "Test msgs.formatmsg() against some known values.",
"name": "testFormatMsg",
"signature": "def testFormatMsg(self)"
},
{
"docstring": "Test msgs.formatmsg()'s supplementary dictionary parameter.",
"name": "testExtraDict",
"signature": "def testExtraDict(self)"
}
] | 2 | null | Implement the Python class `basicTests` described below.
Class description:
Implement the basicTests class.
Method signatures and docstrings:
- def testFormatMsg(self): Test msgs.formatmsg() against some known values.
- def testExtraDict(self): Test msgs.formatmsg()'s supplementary dictionary parameter. | Implement the Python class `basicTests` described below.
Class description:
Implement the basicTests class.
Method signatures and docstrings:
- def testFormatMsg(self): Test msgs.formatmsg() against some known values.
- def testExtraDict(self): Test msgs.formatmsg()'s supplementary dictionary parameter.
<|skeleton|>... | 41341606e831a42ba36f8e64640e98f098bf0489 | <|skeleton|>
class basicTests:
def testFormatMsg(self):
"""Test msgs.formatmsg() against some known values."""
<|body_0|>
def testExtraDict(self):
"""Test msgs.formatmsg()'s supplementary dictionary parameter."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class basicTests:
def testFormatMsg(self):
"""Test msgs.formatmsg() against some known values."""
hi = makehi(rip='127.100.0.10')
fc = FakeCls('test', 10, 'foo-bar')
r = msgs.format('%(class)s@%(lineno)d aka %(label)s: %(hostname)s', hi, fc)
self.assertEqual(r, 'test@10 aka f... | the_stack_v2_python_sparse | test_msgs.py | siebenmann/portnanny | train | 2 | |
6cd1e5948babb1db60311514d76f5a1e07a924e3 | [
"self.debug('Capturing screenshot...')\nscreencap_image = drm.screenshot()\nself.debug('Done capturing, writing to disk...')\nscreencap_path = file_utils.CreateTemporaryFile(prefix='screencap_', suffix='.png')\nscreencap_image.save(screencap_path, optimize=True)\nself.debug('Done writing to disk')\ndata = {'__scree... | <|body_start_0|>
self.debug('Capturing screenshot...')
screencap_image = drm.screenshot()
self.debug('Done capturing, writing to disk...')
screencap_path = file_utils.CreateTemporaryFile(prefix='screencap_', suffix='.png')
screencap_image.save(screencap_path, optimize=True)
... | InputFramebuf | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InputFramebuf:
def EmitScreencap(self):
"""Emits a screenshot event."""
<|body_0|>
def Main(self):
"""Main thread of the plugin."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.debug('Capturing screenshot...')
screencap_image = drm.scre... | stack_v2_sparse_classes_75kplus_train_004792 | 2,065 | permissive | [
{
"docstring": "Emits a screenshot event.",
"name": "EmitScreencap",
"signature": "def EmitScreencap(self)"
},
{
"docstring": "Main thread of the plugin.",
"name": "Main",
"signature": "def Main(self)"
}
] | 2 | null | Implement the Python class `InputFramebuf` described below.
Class description:
Implement the InputFramebuf class.
Method signatures and docstrings:
- def EmitScreencap(self): Emits a screenshot event.
- def Main(self): Main thread of the plugin. | Implement the Python class `InputFramebuf` described below.
Class description:
Implement the InputFramebuf class.
Method signatures and docstrings:
- def EmitScreencap(self): Emits a screenshot event.
- def Main(self): Main thread of the plugin.
<|skeleton|>
class InputFramebuf:
def EmitScreencap(self):
... | a1b0fccd68987d8cd9c89710adc3c04b868347ec | <|skeleton|>
class InputFramebuf:
def EmitScreencap(self):
"""Emits a screenshot event."""
<|body_0|>
def Main(self):
"""Main thread of the plugin."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InputFramebuf:
def EmitScreencap(self):
"""Emits a screenshot event."""
self.debug('Capturing screenshot...')
screencap_image = drm.screenshot()
self.debug('Done capturing, writing to disk...')
screencap_path = file_utils.CreateTemporaryFile(prefix='screencap_', suffix=... | the_stack_v2_python_sparse | py/instalog/plugins/input_drm_screencap/input_drm_screencap.py | bridder/factory | train | 0 | |
7777b2a9462c2fcaf5dc268bbee9774ce7d24915 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client['biel_otis']\nrepo.authenticate('biel_otis', 'biel_otis')\nurl = 'http://datamechanics.io/data/biel_otis/zipcodes.json'\nresponse = urlopen(url).read().decode('utf-8')\nr = json.loads(response)\nmyDict = {}\nmyDict['1'] = []\nmy... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client['biel_otis']
repo.authenticate('biel_otis', 'biel_otis')
url = 'http://datamechanics.io/data/biel_otis/zipcodes.json'
response = urlopen(url).read().decode('utf-8')
... | getZipCodeData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class getZipCodeData:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everythin... | stack_v2_sparse_classes_75kplus_train_004793 | 5,672 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | stack_v2_sparse_classes_30k_train_014428 | Implement the Python class `getZipCodeData` described below.
Class description:
Implement the getZipCodeData class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None,... | Implement the Python class `getZipCodeData` described below.
Class description:
Implement the getZipCodeData class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None,... | 97e72731ffadbeae57d7a332decd58706e7c08de | <|skeleton|>
class getZipCodeData:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everythin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class getZipCodeData:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client['biel_otis']
repo.authenticate('biel_otis', 'biel_otis')
... | the_stack_v2_python_sparse | biel_otis/getZipCodeData.py | ROODAY/course-2017-fal-proj | train | 3 | |
e3e2fab82f2db90f65cfa1d3f026498c219af66f | [
"try:\n article = Article.objects.get(slug=slug)\nexcept Article.DoesNotExist:\n raise exceptions.NotFound({'message': 'Article was not found'})\nif request.user.id:\n if not UserReadStat.objects.filter(user=request.user, article=article).exists():\n user_read_stat = UserReadStat(user=request.user, ... | <|body_start_0|>
try:
article = Article.objects.get(slug=slug)
except Article.DoesNotExist:
raise exceptions.NotFound({'message': 'Article was not found'})
if request.user.id:
if not UserReadStat.objects.filter(user=request.user, article=article).exists():
... | get, update, delete a specific article view | ArticleView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArticleView:
"""get, update, delete a specific article view"""
def get(self, request, slug):
"""Retrieve a specific article :param slug any user should view details of an article"""
<|body_0|>
def put(self, request, slug):
"""update a specific article :param slug... | stack_v2_sparse_classes_75kplus_train_004794 | 4,764 | permissive | [
{
"docstring": "Retrieve a specific article :param slug any user should view details of an article",
"name": "get",
"signature": "def get(self, request, slug)"
},
{
"docstring": "update a specific article :param slug an author can only update his/her article",
"name": "put",
"signature":... | 3 | null | Implement the Python class `ArticleView` described below.
Class description:
get, update, delete a specific article view
Method signatures and docstrings:
- def get(self, request, slug): Retrieve a specific article :param slug any user should view details of an article
- def put(self, request, slug): update a specifi... | Implement the Python class `ArticleView` described below.
Class description:
get, update, delete a specific article view
Method signatures and docstrings:
- def get(self, request, slug): Retrieve a specific article :param slug any user should view details of an article
- def put(self, request, slug): update a specifi... | 4f1fc77c2ecdf8ca15c24327d39fe661eac85785 | <|skeleton|>
class ArticleView:
"""get, update, delete a specific article view"""
def get(self, request, slug):
"""Retrieve a specific article :param slug any user should view details of an article"""
<|body_0|>
def put(self, request, slug):
"""update a specific article :param slug... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ArticleView:
"""get, update, delete a specific article view"""
def get(self, request, slug):
"""Retrieve a specific article :param slug any user should view details of an article"""
try:
article = Article.objects.get(slug=slug)
except Article.DoesNotExist:
... | the_stack_v2_python_sparse | authors/apps/articles/views/articles.py | andela/ah-code-titans | train | 0 |
893ca240beb52ef5ede2d9ef4f5d77cd75a4ca85 | [
"self.SHADOW_BLUR_RADIUS = 7\nself.WIDGET_APPLICATION_TOTAL_HEIGHT = 200\nself.WIDGET_APPLICATION_TOTAL_WIDTH = 200\nself.WIDGET_CONTENT_PADDING = 5\nself.WIDGET_CONTENT_TOTAL_HEIGHT = 200\nself.WIDGET_CONTENT_TOTAL_WIDTH = 200\nself.WIDGET_CONTENT_PADDING = 5\nself.WIDGET_CONTENT_MARGIN = 5\nself.WIDGET_ENVIRONMEN... | <|body_start_0|>
self.SHADOW_BLUR_RADIUS = 7
self.WIDGET_APPLICATION_TOTAL_HEIGHT = 200
self.WIDGET_APPLICATION_TOTAL_WIDTH = 200
self.WIDGET_CONTENT_PADDING = 5
self.WIDGET_CONTENT_TOTAL_HEIGHT = 200
self.WIDGET_CONTENT_TOTAL_WIDTH = 200
self.WIDGET_CONTENT_PADDI... | Enum to hold SASS defined variables. | SassVariables | [
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SassVariables:
"""Enum to hold SASS defined variables."""
def __init__(self):
"""Enum to hold SASS defined variables."""
<|body_0|>
def __repr__(self):
"""Return a pretty formtated representation of the enum."""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_75kplus_train_004795 | 4,986 | permissive | [
{
"docstring": "Enum to hold SASS defined variables.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Return a pretty formtated representation of the enum.",
"name": "__repr__",
"signature": "def __repr__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_043018 | Implement the Python class `SassVariables` described below.
Class description:
Enum to hold SASS defined variables.
Method signatures and docstrings:
- def __init__(self): Enum to hold SASS defined variables.
- def __repr__(self): Return a pretty formtated representation of the enum. | Implement the Python class `SassVariables` described below.
Class description:
Enum to hold SASS defined variables.
Method signatures and docstrings:
- def __init__(self): Enum to hold SASS defined variables.
- def __repr__(self): Return a pretty formtated representation of the enum.
<|skeleton|>
class SassVariables... | 74476c9f00ee43338af696da7e9cd02b273f9005 | <|skeleton|>
class SassVariables:
"""Enum to hold SASS defined variables."""
def __init__(self):
"""Enum to hold SASS defined variables."""
<|body_0|>
def __repr__(self):
"""Return a pretty formtated representation of the enum."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SassVariables:
"""Enum to hold SASS defined variables."""
def __init__(self):
"""Enum to hold SASS defined variables."""
self.SHADOW_BLUR_RADIUS = 7
self.WIDGET_APPLICATION_TOTAL_HEIGHT = 200
self.WIDGET_APPLICATION_TOTAL_WIDTH = 200
self.WIDGET_CONTENT_PADDING = 5... | the_stack_v2_python_sparse | python/anaconda/lib/python2.7/site-packages/anaconda_navigator/utils/styles.py | locolucco209/MongoScraper | train | 3 |
e9d5f911db466574d83bbbdff41d017b178f8281 | [
"if not isinstance(shear_range, (list, tuple)) or len(shear_range) != 2:\n raise ValueError('shear_range argument must be list/tuple with two values!')\nself.shear_range = shear_range\nself.reference = reference\nself.lazy = lazy",
"shear_x = random.gauss(self.shear_range[0], self.shear_range[1])\nshear_y = ra... | <|body_start_0|>
if not isinstance(shear_range, (list, tuple)) or len(shear_range) != 2:
raise ValueError('shear_range argument must be list/tuple with two values!')
self.shear_range = shear_range
self.reference = reference
self.lazy = lazy
<|end_body_0|>
<|body_start_1|>
... | Apply a Shear2D transform to an image, but with the shear parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss. | RandomShear2D | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomShear2D:
"""Apply a Shear2D transform to an image, but with the shear parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss."""
def __init__(self, shear_range, r... | stack_v2_sparse_classes_75kplus_train_004796 | 21,674 | permissive | [
{
"docstring": "Initialize a RandomShear2D object Arguments --------- shear_range : list or tuple Lower and Upper bounds on rotation parameter, in degrees. e.g. shear_range = (-10,10) will result in a random draw of the rotation parameters between -10 and 10 degrees reference : ANTsImage (optional but recommend... | 2 | stack_v2_sparse_classes_30k_train_003165 | Implement the Python class `RandomShear2D` described below.
Class description:
Apply a Shear2D transform to an image, but with the shear parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss.
M... | Implement the Python class `RandomShear2D` described below.
Class description:
Apply a Shear2D transform to an image, but with the shear parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss.
M... | 41f2dd3fcf72654f284dac1a9448033e963f0afb | <|skeleton|>
class RandomShear2D:
"""Apply a Shear2D transform to an image, but with the shear parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss."""
def __init__(self, shear_range, r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomShear2D:
"""Apply a Shear2D transform to an image, but with the shear parameters randomly generated from a user-specified range. The range is determined by a mean (first parameter) and standard deviation (second parameter) via calls to random.gauss."""
def __init__(self, shear_range, reference=None... | the_stack_v2_python_sparse | ants/contrib/sampling/affine2d.py | ANTsX/ANTsPy | train | 483 |
b3de93a206a83317794d044d0ac2a50384f4ac01 | [
"self.p_flip = p_flip\nself.Nt = int(my.rint(Nt))\nself.b0 = b0\nself.b1 = b1\nself.noise_level = noise_level\nself.aov_typ = aov_typ\nself.poissonify = poissonify",
"self.x0 = np.random.standard_normal((self.Nt,))\nself.x1 = (self.x0 > 0).astype(np.int)\nnflip = my.rint(self.p_flip * self.Nt)\nself.x1[:nflip] = ... | <|body_start_0|>
self.p_flip = p_flip
self.Nt = int(my.rint(Nt))
self.b0 = b0
self.b1 = b1
self.noise_level = noise_level
self.aov_typ = aov_typ
self.poissonify = poissonify
<|end_body_0|>
<|body_start_1|>
self.x0 = np.random.standard_normal((self.Nt,))
... | SimDiscrete | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimDiscrete:
def __init__(self, p_flip=0.9, Nt=100, b0=0.3, b1=0.9, noise_level=0.1, aov_typ=2, poissonify=False):
"""Initialize a new simulation and set parameters"""
<|body_0|>
def generate_inputs(self):
"""Set x0 (normal), x1 (binary), and noise"""
<|body_... | stack_v2_sparse_classes_75kplus_train_004797 | 4,420 | no_license | [
{
"docstring": "Initialize a new simulation and set parameters",
"name": "__init__",
"signature": "def __init__(self, p_flip=0.9, Nt=100, b0=0.3, b1=0.9, noise_level=0.1, aov_typ=2, poissonify=False)"
},
{
"docstring": "Set x0 (normal), x1 (binary), and noise",
"name": "generate_inputs",
... | 2 | stack_v2_sparse_classes_30k_test_000182 | Implement the Python class `SimDiscrete` described below.
Class description:
Implement the SimDiscrete class.
Method signatures and docstrings:
- def __init__(self, p_flip=0.9, Nt=100, b0=0.3, b1=0.9, noise_level=0.1, aov_typ=2, poissonify=False): Initialize a new simulation and set parameters
- def generate_inputs(s... | Implement the Python class `SimDiscrete` described below.
Class description:
Implement the SimDiscrete class.
Method signatures and docstrings:
- def __init__(self, p_flip=0.9, Nt=100, b0=0.3, b1=0.9, noise_level=0.1, aov_typ=2, poissonify=False): Initialize a new simulation and set parameters
- def generate_inputs(s... | 390b6089c429877dfea9c56de153bbea0380c20f | <|skeleton|>
class SimDiscrete:
def __init__(self, p_flip=0.9, Nt=100, b0=0.3, b1=0.9, noise_level=0.1, aov_typ=2, poissonify=False):
"""Initialize a new simulation and set parameters"""
<|body_0|>
def generate_inputs(self):
"""Set x0 (normal), x1 (binary), and noise"""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SimDiscrete:
def __init__(self, p_flip=0.9, Nt=100, b0=0.3, b1=0.9, noise_level=0.1, aov_typ=2, poissonify=False):
"""Initialize a new simulation and set parameters"""
self.p_flip = p_flip
self.Nt = int(my.rint(Nt))
self.b0 = b0
self.b1 = b1
self.noise_level = n... | the_stack_v2_python_sparse | 3-5-vidtrack/Sim.py | Mia9469/Rodgers2014 | train | 0 | |
95789cee0dae8807a2c2c31bf3af6f91affe250b | [
"phone = request.COOKIES.get('ph')\nnow_time = datetime.now()\nbefore_time = datetime.now() - timedelta(days=7)\nuser_info = check_user_auth_level(user_phone=phone)\nif user_info[0] == '0':\n '\\n 超级管理员\\n '\n data = func_for_general_statistics_admin(start_time=before_time, end_time=now_... | <|body_start_0|>
phone = request.COOKIES.get('ph')
now_time = datetime.now()
before_time = datetime.now() - timedelta(days=7)
user_info = check_user_auth_level(user_phone=phone)
if user_info[0] == '0':
'\n 超级管理员\n '
data = func_for_ge... | 后台首页统计表 代理商利润 使用次数 设备状态 用户总量等 | GeneralStatistics | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeneralStatistics:
"""后台首页统计表 代理商利润 使用次数 设备状态 用户总量等"""
def get(self, request):
""":param request: :return:"""
<|body_0|>
def post(self, request):
""":param request: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
phone = request.COOKIES... | stack_v2_sparse_classes_75kplus_train_004798 | 34,277 | no_license | [
{
"docstring": ":param request: :return:",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": ":param request: :return:",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006641 | Implement the Python class `GeneralStatistics` described below.
Class description:
后台首页统计表 代理商利润 使用次数 设备状态 用户总量等
Method signatures and docstrings:
- def get(self, request): :param request: :return:
- def post(self, request): :param request: :return: | Implement the Python class `GeneralStatistics` described below.
Class description:
后台首页统计表 代理商利润 使用次数 设备状态 用户总量等
Method signatures and docstrings:
- def get(self, request): :param request: :return:
- def post(self, request): :param request: :return:
<|skeleton|>
class GeneralStatistics:
"""后台首页统计表 代理商利润 使用次数 设备状... | 37b0bbff8818e73fd4897871956cfef446589e2f | <|skeleton|>
class GeneralStatistics:
"""后台首页统计表 代理商利润 使用次数 设备状态 用户总量等"""
def get(self, request):
""":param request: :return:"""
<|body_0|>
def post(self, request):
""":param request: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GeneralStatistics:
"""后台首页统计表 代理商利润 使用次数 设备状态 用户总量等"""
def get(self, request):
""":param request: :return:"""
phone = request.COOKIES.get('ph')
now_time = datetime.now()
before_time = datetime.now() - timedelta(days=7)
user_info = check_user_auth_level(user_phone=p... | the_stack_v2_python_sparse | applet_background/system_home/system_views.py | xieboxiebo/escortbed | train | 0 |
205748b941dfe8bdaa322345a11ceb5aa0b242b0 | [
"super().__init__(parent=parent)\nself.setTitle('Digitizer pulse integrals')\nself.setLabel('left', 'Pulse integral (arb.)')\nself.setLabel('bottom', 'Pulse index')\nself.addLegend(offset=(-40, 60))\nself._plots = []\nfor ch, c in zip(_DIGITIZER_CHANNEL_NAMES, _DIGITIZER_CHANNEL_COLORS):\n self._plots.append(sel... | <|body_start_0|>
super().__init__(parent=parent)
self.setTitle('Digitizer pulse integrals')
self.setLabel('left', 'Pulse integral (arb.)')
self.setLabel('bottom', 'Pulse index')
self.addLegend(offset=(-40, 60))
self._plots = []
for ch, c in zip(_DIGITIZER_CHANNEL_... | XasTimDigitizerPulsePlot class. Visualize pulse integral of each channel of the digitizer in the current train. | XasTimDigitizerPulsePlot | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XasTimDigitizerPulsePlot:
"""XasTimDigitizerPulsePlot class. Visualize pulse integral of each channel of the digitizer in the current train."""
def __init__(self, *, parent=None):
"""Initialization."""
<|body_0|>
def updateF(self, data):
"""Override."""
<... | stack_v2_sparse_classes_75kplus_train_004799 | 13,999 | permissive | [
{
"docstring": "Initialization.",
"name": "__init__",
"signature": "def __init__(self, *, parent=None)"
},
{
"docstring": "Override.",
"name": "updateF",
"signature": "def updateF(self, data)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000798 | Implement the Python class `XasTimDigitizerPulsePlot` described below.
Class description:
XasTimDigitizerPulsePlot class. Visualize pulse integral of each channel of the digitizer in the current train.
Method signatures and docstrings:
- def __init__(self, *, parent=None): Initialization.
- def updateF(self, data): O... | Implement the Python class `XasTimDigitizerPulsePlot` described below.
Class description:
XasTimDigitizerPulsePlot class. Visualize pulse integral of each channel of the digitizer in the current train.
Method signatures and docstrings:
- def __init__(self, *, parent=None): Initialization.
- def updateF(self, data): O... | a6ee28040b15ae8d110570bd9f3c37e5a3e70fc0 | <|skeleton|>
class XasTimDigitizerPulsePlot:
"""XasTimDigitizerPulsePlot class. Visualize pulse integral of each channel of the digitizer in the current train."""
def __init__(self, *, parent=None):
"""Initialization."""
<|body_0|>
def updateF(self, data):
"""Override."""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class XasTimDigitizerPulsePlot:
"""XasTimDigitizerPulsePlot class. Visualize pulse integral of each channel of the digitizer in the current train."""
def __init__(self, *, parent=None):
"""Initialization."""
super().__init__(parent=parent)
self.setTitle('Digitizer pulse integrals')
... | the_stack_v2_python_sparse | extra_foam/special_suite/xas_tim_w.py | European-XFEL/EXtra-foam | train | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.