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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
857f10b99d7c4fc3c331c993f1ff3112c7e66f25 | [
"dist_to_root = [0 for _ in range(len(neighbors))]\nfurthest = 0\nverticies_seen = {root}\nstack = [root]\nwhile stack:\n parent = stack.pop()\n if dist_to_root[parent] > dist_to_root[furthest]:\n furthest = parent\n for v in neighbors[parent]:\n if v not in verticies_seen:\n stack... | <|body_start_0|>
dist_to_root = [0 for _ in range(len(neighbors))]
furthest = 0
verticies_seen = {root}
stack = [root]
while stack:
parent = stack.pop()
if dist_to_root[parent] > dist_to_root[furthest]:
furthest = parent
for v i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def furthestVertex(self, neighbors, root):
"""Find the furthest vertex from the root in an undirected tree."""
<|body_0|>
def findPath(self, neighbors, v1, v2):
"""Finds a path from v1 to v2 in an undirected tree."""
<|body_1|>
def findMinHeigh... | stack_v2_sparse_classes_75kplus_train_005700 | 3,281 | no_license | [
{
"docstring": "Find the furthest vertex from the root in an undirected tree.",
"name": "furthestVertex",
"signature": "def furthestVertex(self, neighbors, root)"
},
{
"docstring": "Finds a path from v1 to v2 in an undirected tree.",
"name": "findPath",
"signature": "def findPath(self, n... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def furthestVertex(self, neighbors, root): Find the furthest vertex from the root in an undirected tree.
- def findPath(self, neighbors, v1, v2): Finds a path from v1 to v2 in an... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def furthestVertex(self, neighbors, root): Find the furthest vertex from the root in an undirected tree.
- def findPath(self, neighbors, v1, v2): Finds a path from v1 to v2 in an... | fdaecec281e854ffd15828bc30f6062b61db34d4 | <|skeleton|>
class Solution:
def furthestVertex(self, neighbors, root):
"""Find the furthest vertex from the root in an undirected tree."""
<|body_0|>
def findPath(self, neighbors, v1, v2):
"""Finds a path from v1 to v2 in an undirected tree."""
<|body_1|>
def findMinHeigh... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def furthestVertex(self, neighbors, root):
"""Find the furthest vertex from the root in an undirected tree."""
dist_to_root = [0 for _ in range(len(neighbors))]
furthest = 0
verticies_seen = {root}
stack = [root]
while stack:
parent = stack... | the_stack_v2_python_sparse | algorithms/medium/MinimumHeightTrees.py | cguerramain/leetcode | train | 0 | |
0c2a099823d5ccba1ae9c71384818ac57ce242a9 | [
"super().__init__(model=model, posterior_transform=posterior_transform)\nself.register_buffer('best_f', torch.as_tensor(best_f))\nself.maximize = maximize",
"mean, sigma = self._mean_and_sigma(X)\nu = _scaled_improvement(mean, sigma, self.best_f, self.maximize)\nreturn log_Phi(u)"
] | <|body_start_0|>
super().__init__(model=model, posterior_transform=posterior_transform)
self.register_buffer('best_f', torch.as_tensor(best_f))
self.maximize = maximize
<|end_body_0|>
<|body_start_1|>
mean, sigma = self._mean_and_sigma(X)
u = _scaled_improvement(mean, sigma, sel... | Single-outcome Log Probability of Improvement. Logarithm of the probability of improvement over the current best observed value, computed using the analytic formula under a Normal posterior distribution. Only supports the case of q=1. Requires the posterior to be Gaussian. The model must be single-outcome. The logarith... | LogProbabilityOfImprovement | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogProbabilityOfImprovement:
"""Single-outcome Log Probability of Improvement. Logarithm of the probability of improvement over the current best observed value, computed using the analytic formula under a Normal posterior distribution. Only supports the case of q=1. Requires the posterior to be G... | stack_v2_sparse_classes_75kplus_train_005701 | 46,601 | permissive | [
{
"docstring": "Single-outcome Probability of Improvement. Args: model: A fitted single-outcome model. best_f: Either a scalar or a `b`-dim Tensor (batch mode) representing the best function value observed so far (assumed noiseless). posterior_transform: A PosteriorTransform. If using a multi-output model, a Po... | 2 | stack_v2_sparse_classes_30k_train_050085 | Implement the Python class `LogProbabilityOfImprovement` described below.
Class description:
Single-outcome Log Probability of Improvement. Logarithm of the probability of improvement over the current best observed value, computed using the analytic formula under a Normal posterior distribution. Only supports the case... | Implement the Python class `LogProbabilityOfImprovement` described below.
Class description:
Single-outcome Log Probability of Improvement. Logarithm of the probability of improvement over the current best observed value, computed using the analytic formula under a Normal posterior distribution. Only supports the case... | 4cc5ed59b2e8a9c780f786830c548e05cc74d53c | <|skeleton|>
class LogProbabilityOfImprovement:
"""Single-outcome Log Probability of Improvement. Logarithm of the probability of improvement over the current best observed value, computed using the analytic formula under a Normal posterior distribution. Only supports the case of q=1. Requires the posterior to be G... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LogProbabilityOfImprovement:
"""Single-outcome Log Probability of Improvement. Logarithm of the probability of improvement over the current best observed value, computed using the analytic formula under a Normal posterior distribution. Only supports the case of q=1. Requires the posterior to be Gaussian. The ... | the_stack_v2_python_sparse | botorch/acquisition/analytic.py | pytorch/botorch | train | 2,891 |
78e10f6bc4b8a3840324f633a5fc7870948f0730 | [
"from sage.matrix.constructor import identity_matrix\nm = identity_matrix(self.base_ring(), self.degree())\nm.set_immutable()\nreturn m",
"from sage.matrix.constructor import identity_matrix\nm = identity_matrix(self.base_ring(), self.degree())\nm.set_immutable()\nreturn m",
"if self._special and x.determinant(... | <|body_start_0|>
from sage.matrix.constructor import identity_matrix
m = identity_matrix(self.base_ring(), self.degree())
m.set_immutable()
return m
<|end_body_0|>
<|body_start_1|>
from sage.matrix.constructor import identity_matrix
m = identity_matrix(self.base_ring(), ... | OrthogonalMatrixGroup_generic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrthogonalMatrixGroup_generic:
def invariant_bilinear_form(self):
"""Return the symmetric bilinear form preserved by the orthogonal group. OUTPUT: A matrix. EXAMPLES:: sage: GO(2,3,+1).invariant_bilinear_form() [0 1] [1 0] sage: GO(2,3,-1).invariant_bilinear_form() [2 1] [1 1]"""
... | stack_v2_sparse_classes_75kplus_train_005702 | 13,931 | no_license | [
{
"docstring": "Return the symmetric bilinear form preserved by the orthogonal group. OUTPUT: A matrix. EXAMPLES:: sage: GO(2,3,+1).invariant_bilinear_form() [0 1] [1 0] sage: GO(2,3,-1).invariant_bilinear_form() [2 1] [1 1]",
"name": "invariant_bilinear_form",
"signature": "def invariant_bilinear_form(... | 3 | stack_v2_sparse_classes_30k_train_036764 | Implement the Python class `OrthogonalMatrixGroup_generic` described below.
Class description:
Implement the OrthogonalMatrixGroup_generic class.
Method signatures and docstrings:
- def invariant_bilinear_form(self): Return the symmetric bilinear form preserved by the orthogonal group. OUTPUT: A matrix. EXAMPLES:: sa... | Implement the Python class `OrthogonalMatrixGroup_generic` described below.
Class description:
Implement the OrthogonalMatrixGroup_generic class.
Method signatures and docstrings:
- def invariant_bilinear_form(self): Return the symmetric bilinear form preserved by the orthogonal group. OUTPUT: A matrix. EXAMPLES:: sa... | 0d9eacbf74e2acffefde93e39f8bcbec745cdaba | <|skeleton|>
class OrthogonalMatrixGroup_generic:
def invariant_bilinear_form(self):
"""Return the symmetric bilinear form preserved by the orthogonal group. OUTPUT: A matrix. EXAMPLES:: sage: GO(2,3,+1).invariant_bilinear_form() [0 1] [1 0] sage: GO(2,3,-1).invariant_bilinear_form() [2 1] [1 1]"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OrthogonalMatrixGroup_generic:
def invariant_bilinear_form(self):
"""Return the symmetric bilinear form preserved by the orthogonal group. OUTPUT: A matrix. EXAMPLES:: sage: GO(2,3,+1).invariant_bilinear_form() [0 1] [1 0] sage: GO(2,3,-1).invariant_bilinear_form() [2 1] [1 1]"""
from sage.mat... | the_stack_v2_python_sparse | sage/src/sage/groups/matrix_gps/orthogonal.py | bopopescu/geosci | train | 0 | |
f5a6f20e03a173cf23aac44bfdbb98c9e446cce3 | [
"self.command = command\nself.result_regex = result_regexes\nself.show_output = show_output\nfor line_number, regex in result_regexes.values():\n assert '(?P<value>' in regex, f\"Regex {regex} doesn't seem to contain the group ?P<value>\"",
"with TemporaryDirectory() as direc:\n cmd = self.command.format(sy... | <|body_start_0|>
self.command = command
self.result_regex = result_regexes
self.show_output = show_output
for line_number, regex in result_regexes.values():
assert '(?P<value>' in regex, f"Regex {regex} doesn't seem to contain the group ?P<value>"
<|end_body_0|>
<|body_start... | An evaluation command that can be configured with jsonnet files. Executes a bash command, taps into the output and returns metrics extracted using regular expressions. | BashEvaluationCommand | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BashEvaluationCommand:
"""An evaluation command that can be configured with jsonnet files. Executes a bash command, taps into the output and returns metrics extracted using regular expressions."""
def __init__(self, command: str, result_regexes: Dict[str, str], show_output: bool=True) -> Non... | stack_v2_sparse_classes_75kplus_train_005703 | 8,851 | permissive | [
{
"docstring": "Sets up an evaluator. :param command: a bash command that will get executed. Use {system_output} and {gold_file} as placeholders. :param result_regexes: a dictionary mapping metric names to tuples of line number and regexes how to extract the values of the respective metrics. evaluate will retur... | 2 | stack_v2_sparse_classes_30k_train_010900 | Implement the Python class `BashEvaluationCommand` described below.
Class description:
An evaluation command that can be configured with jsonnet files. Executes a bash command, taps into the output and returns metrics extracted using regular expressions.
Method signatures and docstrings:
- def __init__(self, command:... | Implement the Python class `BashEvaluationCommand` described below.
Class description:
An evaluation command that can be configured with jsonnet files. Executes a bash command, taps into the output and returns metrics extracted using regular expressions.
Method signatures and docstrings:
- def __init__(self, command:... | 81432b9e3c165f8c0efb84a23e5a0d0493717e63 | <|skeleton|>
class BashEvaluationCommand:
"""An evaluation command that can be configured with jsonnet files. Executes a bash command, taps into the output and returns metrics extracted using regular expressions."""
def __init__(self, command: str, result_regexes: Dict[str, str], show_output: bool=True) -> Non... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BashEvaluationCommand:
"""An evaluation command that can be configured with jsonnet files. Executes a bash command, taps into the output and returns metrics extracted using regular expressions."""
def __init__(self, command: str, result_regexes: Dict[str, str], show_output: bool=True) -> None:
""... | the_stack_v2_python_sparse | graph_dependency_parser/components/evaluation/commands.py | coli-saar/am-parser | train | 30 |
8049d9e5ce670acc95061806694a4255f4273ba4 | [
"super().__init__(**kwargs)\nself.voice = kwargs.get('voice', 'fr')\nself.speed = kwargs.get('speed', 175)\nself.gap = kwargs.get('gap', 10)",
"command = ['espeak', '-v', self.voice, '-s', str(self.speed), '-g', str(self.gap), statement.text]\nsubprocess.run(command)\nreturn statement"
] | <|body_start_0|>
super().__init__(**kwargs)
self.voice = kwargs.get('voice', 'fr')
self.speed = kwargs.get('speed', 175)
self.gap = kwargs.get('gap', 10)
<|end_body_0|>
<|body_start_1|>
command = ['espeak', '-v', self.voice, '-s', str(self.speed), '-g', str(self.gap), statement.... | This is an output_adapter to give a voice to the chatbot. With the `espeak` command of linux. | EspeakAdapter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EspeakAdapter:
"""This is an output_adapter to give a voice to the chatbot. With the `espeak` command of linux."""
def __init__(self, **kwargs):
"""print_response : a boolean. True if we have to print the response voice : the voice (see espeak man) speed : the speed (see espeak man)"... | stack_v2_sparse_classes_75kplus_train_005704 | 1,321 | no_license | [
{
"docstring": "print_response : a boolean. True if we have to print the response voice : the voice (see espeak man) speed : the speed (see espeak man)",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": ":param statement: The statement that the chat bot has produ... | 2 | stack_v2_sparse_classes_30k_val_001689 | Implement the Python class `EspeakAdapter` described below.
Class description:
This is an output_adapter to give a voice to the chatbot. With the `espeak` command of linux.
Method signatures and docstrings:
- def __init__(self, **kwargs): print_response : a boolean. True if we have to print the response voice : the v... | Implement the Python class `EspeakAdapter` described below.
Class description:
This is an output_adapter to give a voice to the chatbot. With the `espeak` command of linux.
Method signatures and docstrings:
- def __init__(self, **kwargs): print_response : a boolean. True if we have to print the response voice : the v... | cfc0970e01cbe4e4a362182613fea1e2a5f881da | <|skeleton|>
class EspeakAdapter:
"""This is an output_adapter to give a voice to the chatbot. With the `espeak` command of linux."""
def __init__(self, **kwargs):
"""print_response : a boolean. True if we have to print the response voice : the voice (see espeak man) speed : the speed (see espeak man)"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EspeakAdapter:
"""This is an output_adapter to give a voice to the chatbot. With the `espeak` command of linux."""
def __init__(self, **kwargs):
"""print_response : a boolean. True if we have to print the response voice : the voice (see espeak man) speed : the speed (see espeak man)"""
su... | the_stack_v2_python_sparse | brain/output/espeak_adapter.py | LeonLenclos/alan | train | 10 |
6891fd95b5b4ab4cbdf9c86a6dbeb1c03ed619c7 | [
"self.question = question\nself.idevice = idevice\nself.answerTextArea = TextAreaField(x_(u'Option'), self.question._optionInstruc, answer)\nself.answerTextArea.idevice = idevice\nself.isCorrect = isCorrect",
"if hasattr(self, 'answerTextArea') and hasattr(self.answerTextArea, 'images'):\n for this_image in se... | <|body_start_0|>
self.question = question
self.idevice = idevice
self.answerTextArea = TextAreaField(x_(u'Option'), self.question._optionInstruc, answer)
self.answerTextArea.idevice = idevice
self.isCorrect = isCorrect
<|end_body_0|>
<|body_start_1|>
if hasattr(self, 'an... | A TestQuestion is built up of question and AnswerOptions. Each answerOption can be rendered as an XHTML element | AnswerOption | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnswerOption:
"""A TestQuestion is built up of question and AnswerOptions. Each answerOption can be rendered as an XHTML element"""
def __init__(self, question, idevice, answer='', isCorrect=False):
"""Initialize"""
<|body_0|>
def getResourcesField(self, this_resource):
... | stack_v2_sparse_classes_75kplus_train_005705 | 13,821 | no_license | [
{
"docstring": "Initialize",
"name": "__init__",
"signature": "def __init__(self, question, idevice, answer='', isCorrect=False)"
},
{
"docstring": "implement the specific resource finding mechanism for this iDevice:",
"name": "getResourcesField",
"signature": "def getResourcesField(self... | 4 | null | Implement the Python class `AnswerOption` described below.
Class description:
A TestQuestion is built up of question and AnswerOptions. Each answerOption can be rendered as an XHTML element
Method signatures and docstrings:
- def __init__(self, question, idevice, answer='', isCorrect=False): Initialize
- def getResou... | Implement the Python class `AnswerOption` described below.
Class description:
A TestQuestion is built up of question and AnswerOptions. Each answerOption can be rendered as an XHTML element
Method signatures and docstrings:
- def __init__(self, question, idevice, answer='', isCorrect=False): Initialize
- def getResou... | 1a99c1788f0eb9f1e5d8c2ced3892d00cd9449ad | <|skeleton|>
class AnswerOption:
"""A TestQuestion is built up of question and AnswerOptions. Each answerOption can be rendered as an XHTML element"""
def __init__(self, question, idevice, answer='', isCorrect=False):
"""Initialize"""
<|body_0|>
def getResourcesField(self, this_resource):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AnswerOption:
"""A TestQuestion is built up of question and AnswerOptions. Each answerOption can be rendered as an XHTML element"""
def __init__(self, question, idevice, answer='', isCorrect=False):
"""Initialize"""
self.question = question
self.idevice = idevice
self.answ... | the_stack_v2_python_sparse | eXe/rev3426-3457/right-branch-3457/exe/engine/quiztestidevice.py | joliebig/featurehouse_fstmerge_examples | train | 3 |
ab0650814e26b6a37b37fef41a14f0f8039a2c14 | [
"try:\n if 'wx_group_id' not in vals:\n wx_officialaccount_id = vals['wx_officialaccount']\n wx_officialaccount = self.env['wx.officialaccount'].search([('id', '=', wx_officialaccount_id)])\n appid = wx_officialaccount.wx_appid\n appsecret = wx_officialaccount.wx_appsecret\n gr... | <|body_start_0|>
try:
if 'wx_group_id' not in vals:
wx_officialaccount_id = vals['wx_officialaccount']
wx_officialaccount = self.env['wx.officialaccount'].search([('id', '=', wx_officialaccount_id)])
appid = wx_officialaccount.wx_appid
... | 实体:微信商品分组 | wx_product_group | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class wx_product_group:
"""实体:微信商品分组"""
def create(self, vals):
"""功能:创建小店分组 :param vals: :return:"""
<|body_0|>
def write(self, vals):
"""功能:更新小店分组 :param vals: :return:"""
<|body_1|>
def unlink(self):
"""功能:删除小店分组 :return:"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus_train_005706 | 6,138 | no_license | [
{
"docstring": "功能:创建小店分组 :param vals: :return:",
"name": "create",
"signature": "def create(self, vals)"
},
{
"docstring": "功能:更新小店分组 :param vals: :return:",
"name": "write",
"signature": "def write(self, vals)"
},
{
"docstring": "功能:删除小店分组 :return:",
"name": "unlink",
"... | 3 | stack_v2_sparse_classes_30k_train_041937 | Implement the Python class `wx_product_group` described below.
Class description:
实体:微信商品分组
Method signatures and docstrings:
- def create(self, vals): 功能:创建小店分组 :param vals: :return:
- def write(self, vals): 功能:更新小店分组 :param vals: :return:
- def unlink(self): 功能:删除小店分组 :return: | Implement the Python class `wx_product_group` described below.
Class description:
实体:微信商品分组
Method signatures and docstrings:
- def create(self, vals): 功能:创建小店分组 :param vals: :return:
- def write(self, vals): 功能:更新小店分组 :param vals: :return:
- def unlink(self): 功能:删除小店分组 :return:
<|skeleton|>
class wx_product_group:
... | 5a4fd72991c846d5cb7c5082f6bdfef5b2bca572 | <|skeleton|>
class wx_product_group:
"""实体:微信商品分组"""
def create(self, vals):
"""功能:创建小店分组 :param vals: :return:"""
<|body_0|>
def write(self, vals):
"""功能:更新小店分组 :param vals: :return:"""
<|body_1|>
def unlink(self):
"""功能:删除小店分组 :return:"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class wx_product_group:
"""实体:微信商品分组"""
def create(self, vals):
"""功能:创建小店分组 :param vals: :return:"""
try:
if 'wx_group_id' not in vals:
wx_officialaccount_id = vals['wx_officialaccount']
wx_officialaccount = self.env['wx.officialaccount'].search([('i... | the_stack_v2_python_sparse | yuancloud/plugin/wx_shop/models/product_group.py | cash2one/yuancloud | train | 0 |
0fe63b5ffccfdb9d5e28600ae4433cbb4357112b | [
"review = get_object_or_404(Review, pk=review_pk)\nreview.delete()\nreturn Response()",
"kindergarten = get_object_or_404(Kindergarten, pk=kindergarten_pk)\nreview = get_object_or_404(Review, pk=review_pk)\nserializer = ReviewCreateSerializer(review, data=request.data)\nif serializer.is_valid(raise_exception=True... | <|body_start_0|>
review = get_object_or_404(Review, pk=review_pk)
review.delete()
return Response()
<|end_body_0|>
<|body_start_1|>
kindergarten = get_object_or_404(Kindergarten, pk=kindergarten_pk)
review = get_object_or_404(Review, pk=review_pk)
serializer = ReviewCrea... | ReviewDetail | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReviewDetail:
def delete(self, request, kindergarten_pk, review_pk):
"""리뷰 삭제 ## 리뷰 삭제 - 리뷰를 삭제합니다. - 로그인한 사용자만 요청할 수 있습니다."""
<|body_0|>
def put(self, request, kindergarten_pk, review_pk):
"""리뷰 수정 ## 리뷰 수정 - 리뷰를 수정할 수 있습니다. - 로그인한 사용자만 요청할 수 있습니다."""
<|body... | stack_v2_sparse_classes_75kplus_train_005707 | 26,419 | no_license | [
{
"docstring": "리뷰 삭제 ## 리뷰 삭제 - 리뷰를 삭제합니다. - 로그인한 사용자만 요청할 수 있습니다.",
"name": "delete",
"signature": "def delete(self, request, kindergarten_pk, review_pk)"
},
{
"docstring": "리뷰 수정 ## 리뷰 수정 - 리뷰를 수정할 수 있습니다. - 로그인한 사용자만 요청할 수 있습니다.",
"name": "put",
"signature": "def put(self, request, k... | 2 | stack_v2_sparse_classes_30k_train_040377 | Implement the Python class `ReviewDetail` described below.
Class description:
Implement the ReviewDetail class.
Method signatures and docstrings:
- def delete(self, request, kindergarten_pk, review_pk): 리뷰 삭제 ## 리뷰 삭제 - 리뷰를 삭제합니다. - 로그인한 사용자만 요청할 수 있습니다.
- def put(self, request, kindergarten_pk, review_pk): 리뷰 수정 ## ... | Implement the Python class `ReviewDetail` described below.
Class description:
Implement the ReviewDetail class.
Method signatures and docstrings:
- def delete(self, request, kindergarten_pk, review_pk): 리뷰 삭제 ## 리뷰 삭제 - 리뷰를 삭제합니다. - 로그인한 사용자만 요청할 수 있습니다.
- def put(self, request, kindergarten_pk, review_pk): 리뷰 수정 ## ... | 7ab42320f71c06f21644accb42e0296eaa2042c0 | <|skeleton|>
class ReviewDetail:
def delete(self, request, kindergarten_pk, review_pk):
"""리뷰 삭제 ## 리뷰 삭제 - 리뷰를 삭제합니다. - 로그인한 사용자만 요청할 수 있습니다."""
<|body_0|>
def put(self, request, kindergarten_pk, review_pk):
"""리뷰 수정 ## 리뷰 수정 - 리뷰를 수정할 수 있습니다. - 로그인한 사용자만 요청할 수 있습니다."""
<|body... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReviewDetail:
def delete(self, request, kindergarten_pk, review_pk):
"""리뷰 삭제 ## 리뷰 삭제 - 리뷰를 삭제합니다. - 로그인한 사용자만 요청할 수 있습니다."""
review = get_object_or_404(Review, pk=review_pk)
review.delete()
return Response()
def put(self, request, kindergarten_pk, review_pk):
"""... | the_stack_v2_python_sparse | backend/kindergartens/views.py | YongjoonSeo/Children-ZIP | train | 1 | |
aff0fa406def7f903aee1b947323df8747aa2093 | [
"if word1 == '':\n return len(word2)\nif word2 == '':\n return len(word1)\nif word1[-1] == word2[-1]:\n return self.minDistanceRecursive(word1[:-1], word2[:-1])\nreplace = self.minDistanceRecursive(word1[:-1], word2[:-1])\ninsert = self.minDistanceRecursive(word1, word2[:-1])\ndelete = self.minDistanceRecu... | <|body_start_0|>
if word1 == '':
return len(word2)
if word2 == '':
return len(word1)
if word1[-1] == word2[-1]:
return self.minDistanceRecursive(word1[:-1], word2[:-1])
replace = self.minDistanceRecursive(word1[:-1], word2[:-1])
insert = self.m... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minDistanceRecursive(self, word1: str, word2: str) -> int:
""">>> sol = Solution(); >>> sol.minDistanceRecursive("horse", "ros") 3 >>> sol.minDistanceRecursive("intention", "execution") 5"""
<|body_0|>
def minDistance(self, word1: str, word2: str) -> int:
... | stack_v2_sparse_classes_75kplus_train_005708 | 2,144 | no_license | [
{
"docstring": ">>> sol = Solution(); >>> sol.minDistanceRecursive(\"horse\", \"ros\") 3 >>> sol.minDistanceRecursive(\"intention\", \"execution\") 5",
"name": "minDistanceRecursive",
"signature": "def minDistanceRecursive(self, word1: str, word2: str) -> int"
},
{
"docstring": ">>> sol = Soluti... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDistanceRecursive(self, word1: str, word2: str) -> int: >>> sol = Solution(); >>> sol.minDistanceRecursive("horse", "ros") 3 >>> sol.minDistanceRecursive("intention", "exe... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDistanceRecursive(self, word1: str, word2: str) -> int: >>> sol = Solution(); >>> sol.minDistanceRecursive("horse", "ros") 3 >>> sol.minDistanceRecursive("intention", "exe... | d679a06a72e6dc18aed95c7e79e25de87e9c18c2 | <|skeleton|>
class Solution:
def minDistanceRecursive(self, word1: str, word2: str) -> int:
""">>> sol = Solution(); >>> sol.minDistanceRecursive("horse", "ros") 3 >>> sol.minDistanceRecursive("intention", "execution") 5"""
<|body_0|>
def minDistance(self, word1: str, word2: str) -> int:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minDistanceRecursive(self, word1: str, word2: str) -> int:
""">>> sol = Solution(); >>> sol.minDistanceRecursive("horse", "ros") 3 >>> sol.minDistanceRecursive("intention", "execution") 5"""
if word1 == '':
return len(word2)
if word2 == '':
return ... | the_stack_v2_python_sparse | leetcode/72-edit-distance.py | ninjaboynaru/my-python-demo | train | 0 | |
8f3cfcf145e270c0af9ba59791237d8c7a4d81c3 | [
"if not tf.gfile.Exists(vocab_file):\n tf.logging.fatal('Vocab file %s not found.', vocab_file)\ntf.logging.info('Initializing vocabulary from file: %s', vocab_file)\nwith tf.gfile.GFile(vocab_file, mode='r') as f:\n reverse_vocab = list(f.readlines())\nreverse_vocab = [line.split()[0] for line in reverse_voc... | <|body_start_0|>
if not tf.gfile.Exists(vocab_file):
tf.logging.fatal('Vocab file %s not found.', vocab_file)
tf.logging.info('Initializing vocabulary from file: %s', vocab_file)
with tf.gfile.GFile(vocab_file, mode='r') as f:
reverse_vocab = list(f.readlines())
r... | Vocabulary class for an image-to-text model. | Vocabulary | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Vocabulary:
"""Vocabulary class for an image-to-text model."""
def __init__(self, vocab_file, start_word='<S>', end_word='</S>', unk_word='<UNK>'):
"""Initializes the vocabulary. Args: vocab_file: File containing the vocabulary, where the words are the first whitespace-separated toke... | stack_v2_sparse_classes_75kplus_train_005709 | 2,814 | permissive | [
{
"docstring": "Initializes the vocabulary. Args: vocab_file: File containing the vocabulary, where the words are the first whitespace-separated token on each line (other tokens are ignored) and the word ids are the corresponding line numbers. start_word: Special word denoting sentence start. end_word: Special ... | 3 | null | Implement the Python class `Vocabulary` described below.
Class description:
Vocabulary class for an image-to-text model.
Method signatures and docstrings:
- def __init__(self, vocab_file, start_word='<S>', end_word='</S>', unk_word='<UNK>'): Initializes the vocabulary. Args: vocab_file: File containing the vocabulary... | Implement the Python class `Vocabulary` described below.
Class description:
Vocabulary class for an image-to-text model.
Method signatures and docstrings:
- def __init__(self, vocab_file, start_word='<S>', end_word='</S>', unk_word='<UNK>'): Initializes the vocabulary. Args: vocab_file: File containing the vocabulary... | 92ec5ec3efeee852aec5c057798298cd3a8e58ae | <|skeleton|>
class Vocabulary:
"""Vocabulary class for an image-to-text model."""
def __init__(self, vocab_file, start_word='<S>', end_word='</S>', unk_word='<UNK>'):
"""Initializes the vocabulary. Args: vocab_file: File containing the vocabulary, where the words are the first whitespace-separated toke... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Vocabulary:
"""Vocabulary class for an image-to-text model."""
def __init__(self, vocab_file, start_word='<S>', end_word='</S>', unk_word='<UNK>'):
"""Initializes the vocabulary. Args: vocab_file: File containing the vocabulary, where the words are the first whitespace-separated token on each lin... | the_stack_v2_python_sparse | model_zoo/models/im2txt/im2txt/inference_utils/vocabulary.py | coderSkyChen/Action_Recognition_Zoo | train | 246 |
c2f168aeb8e967153ecd815f88ba12a86f5c25c8 | [
"super().__init__()\nself.exchange_type = 'sftp'\nself.endpoint_type = None\nself.endpoint_tag = None\nself.data_schema = None\nself.endpoint_schema = None\nself.file_type = None\nself.file_regex = None\nself.host = None\nself.port = None\nself.path = None\nself.files = None",
"self.endpoint_schema = endpoint_sch... | <|body_start_0|>
super().__init__()
self.exchange_type = 'sftp'
self.endpoint_type = None
self.endpoint_tag = None
self.data_schema = None
self.endpoint_schema = None
self.file_type = None
self.file_regex = None
self.host = None
self.port =... | SDCSFTPEndpoint | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SDCSFTPEndpoint:
def __init__(self):
"""SFTP class constructor."""
<|body_0|>
def create_exchange_endpoint(self, data_schema_, endpoint_schema_):
"""Creates a data exchange endpoint for SFTP. Establishes connection to SFTP. A list of files already that exist in the S... | stack_v2_sparse_classes_75kplus_train_005710 | 4,120 | permissive | [
{
"docstring": "SFTP class constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Creates a data exchange endpoint for SFTP. Establishes connection to SFTP. A list of files already that exist in the SFTP path are returned to self.files. :param data_schema_: Dict.... | 4 | null | Implement the Python class `SDCSFTPEndpoint` described below.
Class description:
Implement the SDCSFTPEndpoint class.
Method signatures and docstrings:
- def __init__(self): SFTP class constructor.
- def create_exchange_endpoint(self, data_schema_, endpoint_schema_): Creates a data exchange endpoint for SFTP. Establi... | Implement the Python class `SDCSFTPEndpoint` described below.
Class description:
Implement the SDCSFTPEndpoint class.
Method signatures and docstrings:
- def __init__(self): SFTP class constructor.
- def create_exchange_endpoint(self, data_schema_, endpoint_schema_): Creates a data exchange endpoint for SFTP. Establi... | 44e3d02d7ac43c8876145ae47acfbbbde67230df | <|skeleton|>
class SDCSFTPEndpoint:
def __init__(self):
"""SFTP class constructor."""
<|body_0|>
def create_exchange_endpoint(self, data_schema_, endpoint_schema_):
"""Creates a data exchange endpoint for SFTP. Establishes connection to SFTP. A list of files already that exist in the S... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SDCSFTPEndpoint:
def __init__(self):
"""SFTP class constructor."""
super().__init__()
self.exchange_type = 'sftp'
self.endpoint_type = None
self.endpoint_tag = None
self.data_schema = None
self.endpoint_schema = None
self.file_type = None
... | the_stack_v2_python_sparse | libs/sdc_etl_libs/sdc_exchange_endpoints/file_endpoints/SDCSFTPEndpoint.py | darknegma/docker-airflow | train | 0 | |
6f3cf54ae1f99c0165d5d886ebed6ff7d8e7cd10 | [
"bulb = self.bulb\ncolor_zones = bulb.color_zones\nnum_zones = self.coordinator.get_number_of_zones()\nif not self.is_on and hsbk[HSBK_BRIGHTNESS] is None:\n await self.set_power(True)\n await asyncio.sleep(LIFX_STATE_SETTLE_DELAY)\n await self.update_color_zones()\n await self.set_power(False)\nif (zon... | <|body_start_0|>
bulb = self.bulb
color_zones = bulb.color_zones
num_zones = self.coordinator.get_number_of_zones()
if not self.is_on and hsbk[HSBK_BRIGHTNESS] is None:
await self.set_power(True)
await asyncio.sleep(LIFX_STATE_SETTLE_DELAY)
await self.... | Representation of a legacy LIFX multizone device. | LIFXMultiZone | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LIFXMultiZone:
"""Representation of a legacy LIFX multizone device."""
async def set_color(self, hsbk: list[float | int | None], kwargs: dict[str, Any], duration: int=0) -> None:
"""Send a color change to the bulb."""
<|body_0|>
async def update_color_zones(self) -> None... | stack_v2_sparse_classes_75kplus_train_005711 | 17,058 | permissive | [
{
"docstring": "Send a color change to the bulb.",
"name": "set_color",
"signature": "async def set_color(self, hsbk: list[float | int | None], kwargs: dict[str, Any], duration: int=0) -> None"
},
{
"docstring": "Send a get color zones message to the device.",
"name": "update_color_zones",
... | 2 | stack_v2_sparse_classes_30k_train_018458 | Implement the Python class `LIFXMultiZone` described below.
Class description:
Representation of a legacy LIFX multizone device.
Method signatures and docstrings:
- async def set_color(self, hsbk: list[float | int | None], kwargs: dict[str, Any], duration: int=0) -> None: Send a color change to the bulb.
- async def ... | Implement the Python class `LIFXMultiZone` described below.
Class description:
Representation of a legacy LIFX multizone device.
Method signatures and docstrings:
- async def set_color(self, hsbk: list[float | int | None], kwargs: dict[str, Any], duration: int=0) -> None: Send a color change to the bulb.
- async def ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class LIFXMultiZone:
"""Representation of a legacy LIFX multizone device."""
async def set_color(self, hsbk: list[float | int | None], kwargs: dict[str, Any], duration: int=0) -> None:
"""Send a color change to the bulb."""
<|body_0|>
async def update_color_zones(self) -> None... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LIFXMultiZone:
"""Representation of a legacy LIFX multizone device."""
async def set_color(self, hsbk: list[float | int | None], kwargs: dict[str, Any], duration: int=0) -> None:
"""Send a color change to the bulb."""
bulb = self.bulb
color_zones = bulb.color_zones
num_zon... | the_stack_v2_python_sparse | homeassistant/components/lifx/light.py | home-assistant/core | train | 35,501 |
ae4e3880ffa17975430fea490f616daefa904fd9 | [
"self.client = mock.Mock(Client)\nself.shipper = Shipper(client_builder=lambda *args, **kwargs: self.client)\n\ndef _fake_blocking_call_from_thread(reactor, call, *args, **kwargs):\n d = maybeDeferred(call, *args, **kwargs)\n return self.successResultOf(d)\nself.blocking_call = mock.patch('shipper.shipper.thr... | <|body_start_0|>
self.client = mock.Mock(Client)
self.shipper = Shipper(client_builder=lambda *args, **kwargs: self.client)
def _fake_blocking_call_from_thread(reactor, call, *args, **kwargs):
d = maybeDeferred(call, *args, **kwargs)
return self.successResultOf(d)
... | Tests commands (methods on Shipper) | ShipperCommands | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShipperCommands:
"""Tests commands (methods on Shipper)"""
def setUp(self):
"""Wraps treq so that actual calls are mostly made, but that certain results can be stubbed out"""
<|body_0|>
def test_wait(self):
"""Client.wait is called for every for every container p... | stack_v2_sparse_classes_75kplus_train_005712 | 49,482 | no_license | [
{
"docstring": "Wraps treq so that actual calls are mostly made, but that certain results can be stubbed out",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Client.wait is called for every for every container passed to Shipper.wait. The result is a list tuples of container: ... | 2 | stack_v2_sparse_classes_30k_train_036106 | Implement the Python class `ShipperCommands` described below.
Class description:
Tests commands (methods on Shipper)
Method signatures and docstrings:
- def setUp(self): Wraps treq so that actual calls are mostly made, but that certain results can be stubbed out
- def test_wait(self): Client.wait is called for every ... | Implement the Python class `ShipperCommands` described below.
Class description:
Tests commands (methods on Shipper)
Method signatures and docstrings:
- def setUp(self): Wraps treq so that actual calls are mostly made, but that certain results can be stubbed out
- def test_wait(self): Client.wait is called for every ... | 0ac6653219c2701c13c508c5c4fc9bc3437eea06 | <|skeleton|>
class ShipperCommands:
"""Tests commands (methods on Shipper)"""
def setUp(self):
"""Wraps treq so that actual calls are mostly made, but that certain results can be stubbed out"""
<|body_0|>
def test_wait(self):
"""Client.wait is called for every for every container p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ShipperCommands:
"""Tests commands (methods on Shipper)"""
def setUp(self):
"""Wraps treq so that actual calls are mostly made, but that certain results can be stubbed out"""
self.client = mock.Mock(Client)
self.shipper = Shipper(client_builder=lambda *args, **kwargs: self.client)... | the_stack_v2_python_sparse | repoData/mailgun-shipper/allPythonContent.py | aCoffeeYin/pyreco | train | 0 |
56fd5285ce32ea1f8def2286a3a80c88c2db203f | [
"path = os.path.join(self.base_path, 'numbers.txt')\np = rdf_paths.PathSpec(path=path, pathtype=rdf_paths.PathSpec.PathType.OS)\nresult = self.RunAction(file_fingerprint.FingerprintFile, rdf_client_action.FingerprintRequest(pathspec=p))\ntypes = result[0].matching_types\nfingers = {}\nfor f in result[0].results:\n ... | <|body_start_0|>
path = os.path.join(self.base_path, 'numbers.txt')
p = rdf_paths.PathSpec(path=path, pathtype=rdf_paths.PathSpec.PathType.OS)
result = self.RunAction(file_fingerprint.FingerprintFile, rdf_client_action.FingerprintRequest(pathspec=p))
types = result[0].matching_types
... | Test fingerprinting files. | FilehashTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilehashTest:
"""Test fingerprinting files."""
def testHashFile(self):
"""Can we hash a file?"""
<|body_0|>
def testMissingFile(self):
"""Fail on missing file?"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
path = os.path.join(self.base_path, '... | stack_v2_sparse_classes_75kplus_train_005713 | 2,018 | permissive | [
{
"docstring": "Can we hash a file?",
"name": "testHashFile",
"signature": "def testHashFile(self)"
},
{
"docstring": "Fail on missing file?",
"name": "testMissingFile",
"signature": "def testMissingFile(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015700 | Implement the Python class `FilehashTest` described below.
Class description:
Test fingerprinting files.
Method signatures and docstrings:
- def testHashFile(self): Can we hash a file?
- def testMissingFile(self): Fail on missing file? | Implement the Python class `FilehashTest` described below.
Class description:
Test fingerprinting files.
Method signatures and docstrings:
- def testHashFile(self): Can we hash a file?
- def testMissingFile(self): Fail on missing file?
<|skeleton|>
class FilehashTest:
"""Test fingerprinting files."""
def te... | 44c0eb8c938302098ef7efae8cfd6b90bcfbb2d6 | <|skeleton|>
class FilehashTest:
"""Test fingerprinting files."""
def testHashFile(self):
"""Can we hash a file?"""
<|body_0|>
def testMissingFile(self):
"""Fail on missing file?"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FilehashTest:
"""Test fingerprinting files."""
def testHashFile(self):
"""Can we hash a file?"""
path = os.path.join(self.base_path, 'numbers.txt')
p = rdf_paths.PathSpec(path=path, pathtype=rdf_paths.PathSpec.PathType.OS)
result = self.RunAction(file_fingerprint.Fingerpri... | the_stack_v2_python_sparse | grr/client/grr_response_client/client_actions/file_fingerprint_test.py | google/grr | train | 4,683 |
61f667fa3b1cc396f5ff6c82b26a229a28e7281f | [
"dq = collections.deque()\ndq.append(root)\nres = []\nwhile len(dq):\n size = len(dq)\n temp = []\n for _ in range(size):\n node = dq.popleft()\n if node:\n dq.append(node.left)\n dq.append(node.right)\n temp.append(node.val if node else None)\n res += temp\nre... | <|body_start_0|>
dq = collections.deque()
dq.append(root)
res = []
while len(dq):
size = len(dq)
temp = []
for _ in range(size):
node = dq.popleft()
if node:
dq.append(node.left)
d... | 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_005714 | 1,818 | 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_008039 | 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:... | df3a589ea858218f689fe315d134adc957c3debd | <|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"""
dq = collections.deque()
dq.append(root)
res = []
while len(dq):
size = len(dq)
temp = []
for _ in range(size):
... | the_stack_v2_python_sparse | 297.py | supperllx/LeetCode | train | 0 | |
018b3dfef5d4cf446c9a60e46600573054b1a36e | [
"self.crash_report_fname = 'Crash_report_%s.txt' % app.name\nself.app = app\nself.call_pdb = call_pdb\nself.show_crash_traceback = show_crash_traceback\nself.info = dict(app_name=app.name, contact_name=contact_name, contact_email=contact_email, bug_tracker=bug_tracker, crash_report_fname=self.crash_report_fname)",
... | <|body_start_0|>
self.crash_report_fname = 'Crash_report_%s.txt' % app.name
self.app = app
self.call_pdb = call_pdb
self.show_crash_traceback = show_crash_traceback
self.info = dict(app_name=app.name, contact_name=contact_name, contact_email=contact_email, bug_tracker=bug_tracker... | Customizable crash handlers for IPython applications. Instances of this class provide a :meth:`__call__` method which can be used as a ``sys.excepthook``. The :meth:`__call__` signature is:: def __call__(self, etype, evalue, etb) | CrashHandler | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CrashHandler:
"""Customizable crash handlers for IPython applications. Instances of this class provide a :meth:`__call__` method which can be used as a ``sys.excepthook``. The :meth:`__call__` signature is:: def __call__(self, etype, evalue, etb)"""
def __init__(self, app, contact_name: Opti... | stack_v2_sparse_classes_75kplus_train_005715 | 8,508 | permissive | [
{
"docstring": "Create a new crash handler Parameters ---------- app : Application A running :class:`Application` instance, which will be queried at crash time for internal information. contact_name : str A string with the name of the person to contact. contact_email : str A string with the email address of the... | 3 | stack_v2_sparse_classes_30k_train_002143 | Implement the Python class `CrashHandler` described below.
Class description:
Customizable crash handlers for IPython applications. Instances of this class provide a :meth:`__call__` method which can be used as a ``sys.excepthook``. The :meth:`__call__` signature is:: def __call__(self, etype, evalue, etb)
Method sig... | Implement the Python class `CrashHandler` described below.
Class description:
Customizable crash handlers for IPython applications. Instances of this class provide a :meth:`__call__` method which can be used as a ``sys.excepthook``. The :meth:`__call__` signature is:: def __call__(self, etype, evalue, etb)
Method sig... | e5103f971233fd66b558585cce7a4f52a716cd56 | <|skeleton|>
class CrashHandler:
"""Customizable crash handlers for IPython applications. Instances of this class provide a :meth:`__call__` method which can be used as a ``sys.excepthook``. The :meth:`__call__` signature is:: def __call__(self, etype, evalue, etb)"""
def __init__(self, app, contact_name: Opti... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CrashHandler:
"""Customizable crash handlers for IPython applications. Instances of this class provide a :meth:`__call__` method which can be used as a ``sys.excepthook``. The :meth:`__call__` signature is:: def __call__(self, etype, evalue, etb)"""
def __init__(self, app, contact_name: Optional[str]=Non... | the_stack_v2_python_sparse | IPython/core/crashhandler.py | ipython/ipython | train | 13,673 |
114ac1d7c4a5a98b9735a3be7aedeb19da133ae0 | [
"if hasattr(self, 'get_context_data'):\n data = self.get_context_data(**kwargs)\nelse:\n data = kwargs\nreturn data",
"assert self.render_type in self.renders\nrender = self.renders[self.render_type]\nif collect_render_data:\n kwargs = self.get_render_data(**kwargs)\nreturn render.render(request, **kwarg... | <|body_start_0|>
if hasattr(self, 'get_context_data'):
data = self.get_context_data(**kwargs)
else:
data = kwargs
return data
<|end_body_0|>
<|body_start_1|>
assert self.render_type in self.renders
render = self.renders[self.render_type]
if collec... | Base view for all Views. This is a class based view that uses render classes to handle the preparation of an response. Render classes are classes that return a response of some kind from a view, such as a HttpResponse object or a string. The only requirement is that they have a render method that takes a request and ke... | BaseView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseView:
"""Base view for all Views. This is a class based view that uses render classes to handle the preparation of an response. Render classes are classes that return a response of some kind from a view, such as a HttpResponse object or a string. The only requirement is that they have a rende... | stack_v2_sparse_classes_75kplus_train_005716 | 28,738 | permissive | [
{
"docstring": "Because of the way mixin inheritance works we can't have a default implementation of get_context_data on the this class, so this calls that method if available and returns the resulting context.",
"name": "get_render_data",
"signature": "def get_render_data(self, **kwargs)"
},
{
... | 2 | stack_v2_sparse_classes_30k_test_001885 | Implement the Python class `BaseView` described below.
Class description:
Base view for all Views. This is a class based view that uses render classes to handle the preparation of an response. Render classes are classes that return a response of some kind from a view, such as a HttpResponse object or a string. The onl... | Implement the Python class `BaseView` described below.
Class description:
Base view for all Views. This is a class based view that uses render classes to handle the preparation of an response. Render classes are classes that return a response of some kind from a view, such as a HttpResponse object or a string. The onl... | 9f5ac28618059eef99152214c7a90ad78151629e | <|skeleton|>
class BaseView:
"""Base view for all Views. This is a class based view that uses render classes to handle the preparation of an response. Render classes are classes that return a response of some kind from a view, such as a HttpResponse object or a string. The only requirement is that they have a rende... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseView:
"""Base view for all Views. This is a class based view that uses render classes to handle the preparation of an response. Render classes are classes that return a response of some kind from a view, such as a HttpResponse object or a string. The only requirement is that they have a render method that... | the_stack_v2_python_sparse | scarlet/cms/base_views.py | markmiscavage/scarlet | train | 1 |
919584c6cf62cc75ffc99dfb0265354bc3942988 | [
"super().__init__()\nself.tau = tau\nself.self_similarity = 1 / self.tau\nself.exp_self_similarity = e ** (1 / self.tau)\nself.reduction = reduction\nself.pos_aggregation = pos_aggregation\nif self.reduction not in ['none', 'mean', 'sum']:\n raise ValueError(f'Reduction should be: mean, sum, none. But got - {sel... | <|body_start_0|>
super().__init__()
self.tau = tau
self.self_similarity = 1 / self.tau
self.exp_self_similarity = e ** (1 / self.tau)
self.reduction = reduction
self.pos_aggregation = pos_aggregation
if self.reduction not in ['none', 'mean', 'sum']:
ra... | A Contrastive embedding loss that uses targets. It has been proposed in `Supervised Contrastive Learning`_. .. _`Supervised Contrastive Learning`: https://arxiv.org/pdf/2004.11362.pdf | SupervisedContrastiveLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SupervisedContrastiveLoss:
"""A Contrastive embedding loss that uses targets. It has been proposed in `Supervised Contrastive Learning`_. .. _`Supervised Contrastive Learning`: https://arxiv.org/pdf/2004.11362.pdf"""
def __init__(self, tau: float, reduction: str='mean', pos_aggregation='in')... | stack_v2_sparse_classes_75kplus_train_005717 | 3,700 | permissive | [
{
"docstring": "Args: tau: temperature reduction: specifies the reduction to apply to the output: ``\"none\"`` | ``\"mean\"`` | ``\"sum\"``. ``\"none\"``: no reduction will be applied, ``\"mean\"``: the sum of the output will be divided by the number of positive pairs in the output, ``\"sum\"``: the output will... | 2 | null | Implement the Python class `SupervisedContrastiveLoss` described below.
Class description:
A Contrastive embedding loss that uses targets. It has been proposed in `Supervised Contrastive Learning`_. .. _`Supervised Contrastive Learning`: https://arxiv.org/pdf/2004.11362.pdf
Method signatures and docstrings:
- def __i... | Implement the Python class `SupervisedContrastiveLoss` described below.
Class description:
A Contrastive embedding loss that uses targets. It has been proposed in `Supervised Contrastive Learning`_. .. _`Supervised Contrastive Learning`: https://arxiv.org/pdf/2004.11362.pdf
Method signatures and docstrings:
- def __i... | e99f90655d0efcf22559a46e928f0f98c9807ebf | <|skeleton|>
class SupervisedContrastiveLoss:
"""A Contrastive embedding loss that uses targets. It has been proposed in `Supervised Contrastive Learning`_. .. _`Supervised Contrastive Learning`: https://arxiv.org/pdf/2004.11362.pdf"""
def __init__(self, tau: float, reduction: str='mean', pos_aggregation='in')... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SupervisedContrastiveLoss:
"""A Contrastive embedding loss that uses targets. It has been proposed in `Supervised Contrastive Learning`_. .. _`Supervised Contrastive Learning`: https://arxiv.org/pdf/2004.11362.pdf"""
def __init__(self, tau: float, reduction: str='mean', pos_aggregation='in') -> None:
... | the_stack_v2_python_sparse | catalyst/contrib/losses/supervised_contrastive.py | catalyst-team/catalyst | train | 3,038 |
2c35278c798bb382cb0e2ea29c9cbf27a6284d36 | [
"self.sent0 = sent0.rstrip(' ')\nself.sent1 = sent1.rstrip(' ')\nself.part0 = part0\nself.part1 = part1\nself.ind0 = ind0\nself.ind1 = ind1\nself.s_ind0 = s_ind0\nself.s_ind1 = s_ind1\nself.p_ind0 = p_ind0\nself.p_ind1 = p_ind1",
"if additionalTokenizer:\n simple_sentence = [x.lower() for x in tokenize(self.se... | <|body_start_0|>
self.sent0 = sent0.rstrip(' ')
self.sent1 = sent1.rstrip(' ')
self.part0 = part0
self.part1 = part1
self.ind0 = ind0
self.ind1 = ind1
self.s_ind0 = s_ind0
self.s_ind1 = s_ind1
self.p_ind0 = p_ind0
self.p_ind1 = p_ind1
<|end... | a class that represents an alignment | Alignment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Alignment:
"""a class that represents an alignment"""
def __init__(self, sent0, ind0, p_ind0, s_ind0, part0, sent1, ind1, p_ind1, s_ind1, part1):
"""All indexes are zero-based. :param sent0: the sentence from the first articles :param ind0: the absolute index of this sentence in the ... | stack_v2_sparse_classes_75kplus_train_005718 | 19,883 | no_license | [
{
"docstring": "All indexes are zero-based. :param sent0: the sentence from the first articles :param ind0: the absolute index of this sentence in the file :param p_ind0: the index of the paragraph this sentence appears in :param s_ind0: the index of this sentence relative to the beginning of the paragraph. get... | 2 | stack_v2_sparse_classes_30k_train_024943 | Implement the Python class `Alignment` described below.
Class description:
a class that represents an alignment
Method signatures and docstrings:
- def __init__(self, sent0, ind0, p_ind0, s_ind0, part0, sent1, ind1, p_ind1, s_ind1, part1): All indexes are zero-based. :param sent0: the sentence from the first articles... | Implement the Python class `Alignment` described below.
Class description:
a class that represents an alignment
Method signatures and docstrings:
- def __init__(self, sent0, ind0, p_ind0, s_ind0, part0, sent1, ind1, p_ind1, s_ind1, part1): All indexes are zero-based. :param sent0: the sentence from the first articles... | ebb8022ad1b39a60758d9aa8b40abadbb94a4a46 | <|skeleton|>
class Alignment:
"""a class that represents an alignment"""
def __init__(self, sent0, ind0, p_ind0, s_ind0, part0, sent1, ind1, p_ind1, s_ind1, part1):
"""All indexes are zero-based. :param sent0: the sentence from the first articles :param ind0: the absolute index of this sentence in the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Alignment:
"""a class that represents an alignment"""
def __init__(self, sent0, ind0, p_ind0, s_ind0, part0, sent1, ind1, p_ind1, s_ind1, part1):
"""All indexes are zero-based. :param sent0: the sentence from the first articles :param ind0: the absolute index of this sentence in the file :param p... | the_stack_v2_python_sparse | src/aligner/alignutils.py | seanderson/lexical-simplification | train | 6 |
5ab9420c6e0ec6c6e67ce2fc2ce09d830edfb5d3 | [
"Resource.__init__(self)\nself.store = store\nself.directory = directory\nself.inactivityDetector = inactivityDetector",
"self.inactivityDetector.activity()\n\ndef onSuccess(result, output):\n txt = output.getvalue()\n output.close()\n request.write(txt)\n request.finish()\n\ndef onError(failure):\n ... | <|body_start_0|>
Resource.__init__(self)
self.store = store
self.directory = directory
self.inactivityDetector = inactivityDetector
<|end_body_0|>
<|body_start_1|>
self.inactivityDetector.activity()
def onSuccess(result, output):
txt = output.getvalue()
... | The gateway resource which forwards incoming requests through gateway.Runner. | AgentGatewayResource | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AgentGatewayResource:
"""The gateway resource which forwards incoming requests through gateway.Runner."""
def __init__(self, store, directory, inactivityDetector):
"""@param store: an already opened store @param directory: a directory service @param inactivityDetector: the Inactivity... | stack_v2_sparse_classes_75kplus_train_005719 | 10,761 | permissive | [
{
"docstring": "@param store: an already opened store @param directory: a directory service @param inactivityDetector: the InactivityDetector to tell when requests come in",
"name": "__init__",
"signature": "def __init__(self, store, directory, inactivityDetector)"
},
{
"docstring": "Take the bo... | 2 | null | Implement the Python class `AgentGatewayResource` described below.
Class description:
The gateway resource which forwards incoming requests through gateway.Runner.
Method signatures and docstrings:
- def __init__(self, store, directory, inactivityDetector): @param store: an already opened store @param directory: a di... | Implement the Python class `AgentGatewayResource` described below.
Class description:
The gateway resource which forwards incoming requests through gateway.Runner.
Method signatures and docstrings:
- def __init__(self, store, directory, inactivityDetector): @param store: an already opened store @param directory: a di... | cb2962f1f1927f1e52ea405094fa3e7e180f23cb | <|skeleton|>
class AgentGatewayResource:
"""The gateway resource which forwards incoming requests through gateway.Runner."""
def __init__(self, store, directory, inactivityDetector):
"""@param store: an already opened store @param directory: a directory service @param inactivityDetector: the Inactivity... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AgentGatewayResource:
"""The gateway resource which forwards incoming requests through gateway.Runner."""
def __init__(self, store, directory, inactivityDetector):
"""@param store: an already opened store @param directory: a directory service @param inactivityDetector: the InactivityDetector to t... | the_stack_v2_python_sparse | calendarserver/tools/agent.py | ass-a2s/ccs-calendarserver | train | 2 |
be76ad3d413e402df7e6ac137d0d26a444ef98f9 | [
"super().__init__(max_number=max_number, min_number=min_number, seed=seed)\nself.stamp_size = stamp_size\nself.max_shift = max_shift if max_shift is not None else self.stamp_size / 10.0\nself.min_mag, self.max_mag = (min_mag, max_mag)\nself.mag_name = mag_name",
"if self.mag_name not in table.colnames:\n raise... | <|body_start_0|>
super().__init__(max_number=max_number, min_number=min_number, seed=seed)
self.stamp_size = stamp_size
self.max_shift = max_shift if max_shift is not None else self.stamp_size / 10.0
self.min_mag, self.max_mag = (min_mag, max_mag)
self.mag_name = mag_name
<|end_b... | Default sampling function used for producing blend catalogs. | DefaultSampling | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DefaultSampling:
"""Default sampling function used for producing blend catalogs."""
def __init__(self, max_number: int=2, min_number: int=1, stamp_size: float=24.0, max_shift: Optional[float]=None, seed: int=DEFAULT_SEED, max_mag: float=25.3, min_mag: float=-np.inf, mag_name: str='i_ab'):
... | stack_v2_sparse_classes_75kplus_train_005720 | 12,943 | permissive | [
{
"docstring": "Initializes default sampling function. Args: max_number: Defined in parent class min_number: Defined in parent class stamp_size: Size of the desired stamp. max_shift: Magnitude of maximum value of shift. If None then it is set as one-tenth the stamp size. (in arcseconds) seed: Seed to initialize... | 2 | stack_v2_sparse_classes_30k_train_020200 | Implement the Python class `DefaultSampling` described below.
Class description:
Default sampling function used for producing blend catalogs.
Method signatures and docstrings:
- def __init__(self, max_number: int=2, min_number: int=1, stamp_size: float=24.0, max_shift: Optional[float]=None, seed: int=DEFAULT_SEED, ma... | Implement the Python class `DefaultSampling` described below.
Class description:
Default sampling function used for producing blend catalogs.
Method signatures and docstrings:
- def __init__(self, max_number: int=2, min_number: int=1, stamp_size: float=24.0, max_shift: Optional[float]=None, seed: int=DEFAULT_SEED, ma... | f5b716a373f130238100db8980aa0d282822983a | <|skeleton|>
class DefaultSampling:
"""Default sampling function used for producing blend catalogs."""
def __init__(self, max_number: int=2, min_number: int=1, stamp_size: float=24.0, max_shift: Optional[float]=None, seed: int=DEFAULT_SEED, max_mag: float=25.3, min_mag: float=-np.inf, mag_name: str='i_ab'):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DefaultSampling:
"""Default sampling function used for producing blend catalogs."""
def __init__(self, max_number: int=2, min_number: int=1, stamp_size: float=24.0, max_shift: Optional[float]=None, seed: int=DEFAULT_SEED, max_mag: float=25.3, min_mag: float=-np.inf, mag_name: str='i_ab'):
"""Init... | the_stack_v2_python_sparse | btk/sampling_functions.py | LSSTDESC/BlendingToolKit | train | 22 |
1db500821af8f97a36c71e60c3941f935c34e839 | [
"resource = Monitor_Resource()\nresource.ip = ip\nresource.process_isalive = process_isalive\nresource.process_cpu_use = process_cpu_use\nresource.process_mem_use = process_mem_use\nresource.cpu_total_use = cpu_total_use\nresource.mem_free = mem_free\nresource.disk_read = disk_read\nresource.disk_write = disk_write... | <|body_start_0|>
resource = Monitor_Resource()
resource.ip = ip
resource.process_isalive = process_isalive
resource.process_cpu_use = process_cpu_use
resource.process_mem_use = process_mem_use
resource.cpu_total_use = cpu_total_use
resource.mem_free = mem_free
... | Monitor_Resource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Monitor_Resource:
def create_or_replace(cls, ip, process_isalive, process_cpu_use, process_mem_use, cpu_total_use, mem_free, disk_read, disk_write, network_upload, network_download, volume):
"""发现一台新主机的监控资源 :param ip: ip地址 :param process_isalive: 进程是否存在 :param process_cpu_use: 进程的cpu使用情况... | stack_v2_sparse_classes_75kplus_train_005721 | 13,402 | no_license | [
{
"docstring": "发现一台新主机的监控资源 :param ip: ip地址 :param process_isalive: 进程是否存在 :param process_cpu_use: 进程的cpu使用情况 :param process_mem_use: 进程的内存使用情况 :param cpu_total_use: 总cpu使用率 :param mem_free: 内存可用量 :param disk_read: 磁盘读 :param disk_write: 磁盘写 :param network_upload: 网络上传 :param network_download: 网络下载 :param volu... | 2 | stack_v2_sparse_classes_30k_train_006689 | Implement the Python class `Monitor_Resource` described below.
Class description:
Implement the Monitor_Resource class.
Method signatures and docstrings:
- def create_or_replace(cls, ip, process_isalive, process_cpu_use, process_mem_use, cpu_total_use, mem_free, disk_read, disk_write, network_upload, network_download... | Implement the Python class `Monitor_Resource` described below.
Class description:
Implement the Monitor_Resource class.
Method signatures and docstrings:
- def create_or_replace(cls, ip, process_isalive, process_cpu_use, process_mem_use, cpu_total_use, mem_free, disk_read, disk_write, network_upload, network_download... | 4febccac57bfa5f7ef46f5f57e52206c8b0a57ac | <|skeleton|>
class Monitor_Resource:
def create_or_replace(cls, ip, process_isalive, process_cpu_use, process_mem_use, cpu_total_use, mem_free, disk_read, disk_write, network_upload, network_download, volume):
"""发现一台新主机的监控资源 :param ip: ip地址 :param process_isalive: 进程是否存在 :param process_cpu_use: 进程的cpu使用情况... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Monitor_Resource:
def create_or_replace(cls, ip, process_isalive, process_cpu_use, process_mem_use, cpu_total_use, mem_free, disk_read, disk_write, network_upload, network_download, volume):
"""发现一台新主机的监控资源 :param ip: ip地址 :param process_isalive: 进程是否存在 :param process_cpu_use: 进程的cpu使用情况 :param proces... | the_stack_v2_python_sparse | item/dev/cmdb/asset/models.py | soulorman/Python | train | 0 | |
6d6d8d8605a5e7f5acde1ca9fc2a9c45bffe498d | [
"docx = entry.get('htmlx', None)\nif not docx or entry.get('_parser_error', False):\n return\nlist_containers = docx.find_all('div', {'class': 'productList'})\npage_position = 0\nfailed = 0\nprocessed = 0\nitems = []\nerrmsgs = []\nfor list_container in list_containers:\n list_items = list_container.find_all(... | <|body_start_0|>
docx = entry.get('htmlx', None)
if not docx or entry.get('_parser_error', False):
return
list_containers = docx.find_all('div', {'class': 'productList'})
page_position = 0
failed = 0
processed = 0
items = []
errmsgs = []
... | Provider_ProductListing | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Provider_ProductListing:
def extract_product_listing_items(self, entry):
"""Parse Product Listing Data"""
<|body_0|>
def parse_product_listing_item(self, xitem):
"""Parse HTML for Listed Product Data"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
d... | stack_v2_sparse_classes_75kplus_train_005722 | 10,464 | no_license | [
{
"docstring": "Parse Product Listing Data",
"name": "extract_product_listing_items",
"signature": "def extract_product_listing_items(self, entry)"
},
{
"docstring": "Parse HTML for Listed Product Data",
"name": "parse_product_listing_item",
"signature": "def parse_product_listing_item(s... | 2 | stack_v2_sparse_classes_30k_train_027409 | Implement the Python class `Provider_ProductListing` described below.
Class description:
Implement the Provider_ProductListing class.
Method signatures and docstrings:
- def extract_product_listing_items(self, entry): Parse Product Listing Data
- def parse_product_listing_item(self, xitem): Parse HTML for Listed Prod... | Implement the Python class `Provider_ProductListing` described below.
Class description:
Implement the Provider_ProductListing class.
Method signatures and docstrings:
- def extract_product_listing_items(self, entry): Parse Product Listing Data
- def parse_product_listing_item(self, xitem): Parse HTML for Listed Prod... | 38a4a3c9c7b007c8eb79757d434ed1ce806abe15 | <|skeleton|>
class Provider_ProductListing:
def extract_product_listing_items(self, entry):
"""Parse Product Listing Data"""
<|body_0|>
def parse_product_listing_item(self, xitem):
"""Parse HTML for Listed Product Data"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Provider_ProductListing:
def extract_product_listing_items(self, entry):
"""Parse Product Listing Data"""
docx = entry.get('htmlx', None)
if not docx or entry.get('_parser_error', False):
return
list_containers = docx.find_all('div', {'class': 'productList'})
... | the_stack_v2_python_sparse | stride/providers/ziengs/ziengs.py | danielnurse/ShoeCase | train | 0 | |
13475f100909764d7598cad5b048faa2f3cf4c0e | [
"success_message = ''\nform = PhotoForm()\ncontext = {'photo_form': form}\nreturn render(request, 'photos/create.html', context)",
"success_message = ''\nphoto_with_owner = Photo()\nphoto_with_owner.owner = request.user\nform = PhotoForm(request.POST, instance=photo_with_owner)\nif form.is_valid():\n new_photo... | <|body_start_0|>
success_message = ''
form = PhotoForm()
context = {'photo_form': form}
return render(request, 'photos/create.html', context)
<|end_body_0|>
<|body_start_1|>
success_message = ''
photo_with_owner = Photo()
photo_with_owner.owner = request.user
... | CreatePhotoView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreatePhotoView:
def get(self, request):
"""Muestra un formualario para crear una foto :param request: HttpRequest :return: HttpResponse"""
<|body_0|>
def post(self, request):
"""Crea una foto en base a la información del POST :param request: HttpRequest :return: Htt... | stack_v2_sparse_classes_75kplus_train_005723 | 4,604 | no_license | [
{
"docstring": "Muestra un formualario para crear una foto :param request: HttpRequest :return: HttpResponse",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Crea una foto en base a la información del POST :param request: HttpRequest :return: HttpResponse",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_015140 | Implement the Python class `CreatePhotoView` described below.
Class description:
Implement the CreatePhotoView class.
Method signatures and docstrings:
- def get(self, request): Muestra un formualario para crear una foto :param request: HttpRequest :return: HttpResponse
- def post(self, request): Crea una foto en bas... | Implement the Python class `CreatePhotoView` described below.
Class description:
Implement the CreatePhotoView class.
Method signatures and docstrings:
- def get(self, request): Muestra un formualario para crear una foto :param request: HttpRequest :return: HttpResponse
- def post(self, request): Crea una foto en bas... | 2b452a3fcb86a0d61f0a27259c87234ca2b41d43 | <|skeleton|>
class CreatePhotoView:
def get(self, request):
"""Muestra un formualario para crear una foto :param request: HttpRequest :return: HttpResponse"""
<|body_0|>
def post(self, request):
"""Crea una foto en base a la información del POST :param request: HttpRequest :return: Htt... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CreatePhotoView:
def get(self, request):
"""Muestra un formualario para crear una foto :param request: HttpRequest :return: HttpResponse"""
success_message = ''
form = PhotoForm()
context = {'photo_form': form}
return render(request, 'photos/create.html', context)
... | the_stack_v2_python_sparse | photos/views.py | Charliejms/django2.0 | train | 0 | |
269c9c5f8d21277d3660bbd9fd6d464a19b70b4c | [
"if self.request.method == 'GET':\n return [permissions.IsAuthenticated()]\nif self.request.method == 'POST':\n return (IsSurgeon(),)\nif self.request.method == 'PATCH':\n return (IsCaseSurgeonOrOncologistOrRadiotherapist(),)\nreturn (permissions.IsAuthenticated(), IsCaseSurgeon())",
"queryset = Case.obj... | <|body_start_0|>
if self.request.method == 'GET':
return [permissions.IsAuthenticated()]
if self.request.method == 'POST':
return (IsSurgeon(),)
if self.request.method == 'PATCH':
return (IsCaseSurgeonOrOncologistOrRadiotherapist(),)
return (permission... | Case CRUD | CaseViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CaseViewSet:
"""Case CRUD"""
def get_permissions(self):
"""Patients can view their cases Doctors can view their cases Surgeons can create case Surgeons can update and delete their own cases"""
<|body_0|>
def get_queryset(self):
"""Should return a list of all the ... | stack_v2_sparse_classes_75kplus_train_005724 | 15,503 | no_license | [
{
"docstring": "Patients can view their cases Doctors can view their cases Surgeons can create case Surgeons can update and delete their own cases",
"name": "get_permissions",
"signature": "def get_permissions(self)"
},
{
"docstring": "Should return a list of all the cases for the currently auth... | 3 | stack_v2_sparse_classes_30k_train_017634 | Implement the Python class `CaseViewSet` described below.
Class description:
Case CRUD
Method signatures and docstrings:
- def get_permissions(self): Patients can view their cases Doctors can view their cases Surgeons can create case Surgeons can update and delete their own cases
- def get_queryset(self): Should retu... | Implement the Python class `CaseViewSet` described below.
Class description:
Case CRUD
Method signatures and docstrings:
- def get_permissions(self): Patients can view their cases Doctors can view their cases Surgeons can create case Surgeons can update and delete their own cases
- def get_queryset(self): Should retu... | 413664d4e77020c8fcb6bf95e31e3ff9908e2b60 | <|skeleton|>
class CaseViewSet:
"""Case CRUD"""
def get_permissions(self):
"""Patients can view their cases Doctors can view their cases Surgeons can create case Surgeons can update and delete their own cases"""
<|body_0|>
def get_queryset(self):
"""Should return a list of all the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CaseViewSet:
"""Case CRUD"""
def get_permissions(self):
"""Patients can view their cases Doctors can view their cases Surgeons can create case Surgeons can update and delete their own cases"""
if self.request.method == 'GET':
return [permissions.IsAuthenticated()]
if s... | the_stack_v2_python_sparse | noccapp/views/case.py | otto-torino/nocc-server | train | 0 |
edd0c8aaf409db5ab6cfd064749659be90c5866b | [
"fake_get_session.side_effect = [requests.exceptions.ConnectionError('testing'), requests.exceptions.ConnectionError('testing'), requests.exceptions.ConnectionError('testing'), requests.exceptions.ConnectionError('testing')]\ntry:\n insightiq_api.InsightiqApi(username='bob', password='a')\nexcept Exception as do... | <|body_start_0|>
fake_get_session.side_effect = [requests.exceptions.ConnectionError('testing'), requests.exceptions.ConnectionError('testing'), requests.exceptions.ConnectionError('testing'), requests.exceptions.ConnectionError('testing')]
try:
insightiq_api.InsightiqApi(username='bob', pas... | A suite of tests for the session creation logic in InsightiqApi | TestInsightiqSessions | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestInsightiqSessions:
"""A suite of tests for the session creation logic in InsightiqApi"""
def test_session_retries(self, fake_get_session):
"""InsightiqApi - ``renew_session()`` will try 3 times to get a valid session"""
<|body_0|>
def test_connection_error(self, fake... | stack_v2_sparse_classes_75kplus_train_005725 | 16,715 | permissive | [
{
"docstring": "InsightiqApi - ``renew_session()`` will try 3 times to get a valid session",
"name": "test_session_retries",
"signature": "def test_session_retries(self, fake_get_session)"
},
{
"docstring": "InsightiqApi - failure to obtain a session raises ConnectionError",
"name": "test_co... | 2 | stack_v2_sparse_classes_30k_train_047676 | Implement the Python class `TestInsightiqSessions` described below.
Class description:
A suite of tests for the session creation logic in InsightiqApi
Method signatures and docstrings:
- def test_session_retries(self, fake_get_session): InsightiqApi - ``renew_session()`` will try 3 times to get a valid session
- def ... | Implement the Python class `TestInsightiqSessions` described below.
Class description:
A suite of tests for the session creation logic in InsightiqApi
Method signatures and docstrings:
- def test_session_retries(self, fake_get_session): InsightiqApi - ``renew_session()`` will try 3 times to get a valid session
- def ... | a44a8ee9a299c7711b3abd69d21c24f55f2ae84e | <|skeleton|>
class TestInsightiqSessions:
"""A suite of tests for the session creation logic in InsightiqApi"""
def test_session_retries(self, fake_get_session):
"""InsightiqApi - ``renew_session()`` will try 3 times to get a valid session"""
<|body_0|>
def test_connection_error(self, fake... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestInsightiqSessions:
"""A suite of tests for the session creation logic in InsightiqApi"""
def test_session_retries(self, fake_get_session):
"""InsightiqApi - ``renew_session()`` will try 3 times to get a valid session"""
fake_get_session.side_effect = [requests.exceptions.ConnectionErr... | the_stack_v2_python_sparse | iiqtools_tests/utils/test_insightiq_api.py | willnx/iiqtools | train | 5 |
bfc1228fbd81ebe4c9fd4a2582d533067dc879d2 | [
"if not nums:\n return\nfor i in range(1, len(nums)):\n if nums[i - 1] > nums[i]:\n return i - 1\nreturn len(nums) - 1",
"if not nums:\n return\nreturn self.search(nums, 0, len(nums) - 1)",
"if l == r:\n return l\nmid = (l + r) // 2\nif nums[mid] > nums[mid + 1]:\n return self.search(nums,... | <|body_start_0|>
if not nums:
return
for i in range(1, len(nums)):
if nums[i - 1] > nums[i]:
return i - 1
return len(nums) - 1
<|end_body_0|>
<|body_start_1|>
if not nums:
return
return self.search(nums, 0, len(nums) - 1)
<|end... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findPeakElement(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findPeakElement_1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def search(self, nums, l, r):
""":type nums: List[int] :type l, r:... | stack_v2_sparse_classes_75kplus_train_005726 | 2,735 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findPeakElement",
"signature": "def findPeakElement(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findPeakElement_1",
"signature": "def findPeakElement_1(self, nums)"
},
{
"docstring": ":t... | 4 | stack_v2_sparse_classes_30k_train_054117 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findPeakElement(self, nums): :type nums: List[int] :rtype: int
- def findPeakElement_1(self, nums): :type nums: List[int] :rtype: int
- def search(self, nums, l, r): :type nu... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findPeakElement(self, nums): :type nums: List[int] :rtype: int
- def findPeakElement_1(self, nums): :type nums: List[int] :rtype: int
- def search(self, nums, l, r): :type nu... | 3d9e0ad2f6ed92ec969556f75d97c51ea4854719 | <|skeleton|>
class Solution:
def findPeakElement(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findPeakElement_1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def search(self, nums, l, r):
""":type nums: List[int] :type l, r:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findPeakElement(self, nums):
""":type nums: List[int] :rtype: int"""
if not nums:
return
for i in range(1, len(nums)):
if nums[i - 1] > nums[i]:
return i - 1
return len(nums) - 1
def findPeakElement_1(self, nums):
... | the_stack_v2_python_sparse | Solutions/0162_findPeakElement.py | YoupengLi/leetcode-sorting | train | 3 | |
7e95ce8d471ea31b1e4855032196cfb7e487b488 | [
"for c in s:\n sys.stdout.write(c)\n sys.stdout.flush()\n time.sleep(long)",
"if name == 'nt':\n _ = system('cls')\nelse:\n _ = system('clear')"
] | <|body_start_0|>
for c in s:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(long)
<|end_body_0|>
<|body_start_1|>
if name == 'nt':
_ = system('cls')
else:
_ = system('clear')
<|end_body_1|>
| Visuals | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Visuals:
def delay_print(self, s: str='', long: float=0.02):
"""Prints characters in a string with slight delay to simulate a live program"""
<|body_0|>
def clear(self):
"""Clears terminal to empty"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for... | stack_v2_sparse_classes_75kplus_train_005727 | 626 | no_license | [
{
"docstring": "Prints characters in a string with slight delay to simulate a live program",
"name": "delay_print",
"signature": "def delay_print(self, s: str='', long: float=0.02)"
},
{
"docstring": "Clears terminal to empty",
"name": "clear",
"signature": "def clear(self)"
}
] | 2 | null | Implement the Python class `Visuals` described below.
Class description:
Implement the Visuals class.
Method signatures and docstrings:
- def delay_print(self, s: str='', long: float=0.02): Prints characters in a string with slight delay to simulate a live program
- def clear(self): Clears terminal to empty | Implement the Python class `Visuals` described below.
Class description:
Implement the Visuals class.
Method signatures and docstrings:
- def delay_print(self, s: str='', long: float=0.02): Prints characters in a string with slight delay to simulate a live program
- def clear(self): Clears terminal to empty
<|skelet... | 3279b9d586856a98cf002d435b6899fcb8863194 | <|skeleton|>
class Visuals:
def delay_print(self, s: str='', long: float=0.02):
"""Prints characters in a string with slight delay to simulate a live program"""
<|body_0|>
def clear(self):
"""Clears terminal to empty"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Visuals:
def delay_print(self, s: str='', long: float=0.02):
"""Prints characters in a string with slight delay to simulate a live program"""
for c in s:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(long)
def clear(self):
"""Clears terminal... | the_stack_v2_python_sparse | V3/universal/visuals.py | boogiedev/Talking-Text-Adventure | train | 0 | |
66f084da2b5cea017c5cc561f5b024f37744bf41 | [
"it = iter(test_inputs.split('\\n')) if test_inputs else None\n\ndef uinput():\n return next(it) if it else sys.stdin.readline().rstrip()\n[self.n] = map(int, uinput().split())\nself.nums = list(map(int, uinput().split()))",
"s = sum(self.nums)\nsrt = sorted(self.nums)\nminodd = 0\nfor m in srt:\n if m % 2:... | <|body_start_0|>
it = iter(test_inputs.split('\n')) if test_inputs else None
def uinput():
return next(it) if it else sys.stdin.readline().rstrip()
[self.n] = map(int, uinput().split())
self.nums = list(map(int, uinput().split()))
<|end_body_0|>
<|body_start_1|>
s =... | Shark representation | Shark | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Shark:
"""Shark representation"""
def __init__(self, test_inputs=None):
"""Default constructor"""
<|body_0|>
def calculate(self):
"""Main calcualtion function of the class"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
it = iter(test_inputs.spl... | stack_v2_sparse_classes_75kplus_train_005728 | 3,213 | permissive | [
{
"docstring": "Default constructor",
"name": "__init__",
"signature": "def __init__(self, test_inputs=None)"
},
{
"docstring": "Main calcualtion function of the class",
"name": "calculate",
"signature": "def calculate(self)"
}
] | 2 | null | Implement the Python class `Shark` described below.
Class description:
Shark representation
Method signatures and docstrings:
- def __init__(self, test_inputs=None): Default constructor
- def calculate(self): Main calcualtion function of the class | Implement the Python class `Shark` described below.
Class description:
Shark representation
Method signatures and docstrings:
- def __init__(self, test_inputs=None): Default constructor
- def calculate(self): Main calcualtion function of the class
<|skeleton|>
class Shark:
"""Shark representation"""
def __i... | ae02ea872ca91ef98630cc172a844b82cc56f621 | <|skeleton|>
class Shark:
"""Shark representation"""
def __init__(self, test_inputs=None):
"""Default constructor"""
<|body_0|>
def calculate(self):
"""Main calcualtion function of the class"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Shark:
"""Shark representation"""
def __init__(self, test_inputs=None):
"""Default constructor"""
it = iter(test_inputs.split('\n')) if test_inputs else None
def uinput():
return next(it) if it else sys.stdin.readline().rstrip()
[self.n] = map(int, uinput().sp... | the_stack_v2_python_sparse | codeforces/621A_shark.py | snsokolov/contests | train | 1 |
e2bca825121fc9e533831101fc775e0599ca9ba2 | [
"out_file = rule_details[su.NAME_KEY] + '.{}'.format(rule_details.get(su.ARCHIVE_TYPE, su.DEFAULT_FILE_COLL_ARCHIVE_TYPE))\nsu.init_rule_common(rule_details, out_file, [su.SRCS_KEY])\nrule_details[su.SRCS_KEY] = rule_details.get(su.SRCS_KEY, [])\nrule_details[su.FILE_PACKAGE_KEY] = rule_details.get(su.FILE_PACKAGE_... | <|body_start_0|>
out_file = rule_details[su.NAME_KEY] + '.{}'.format(rule_details.get(su.ARCHIVE_TYPE, su.DEFAULT_FILE_COLL_ARCHIVE_TYPE))
su.init_rule_common(rule_details, out_file, [su.SRCS_KEY])
rule_details[su.SRCS_KEY] = rule_details.get(su.SRCS_KEY, [])
rule_details[su.FILE_PACKAGE... | File Collection build utility type. | FileCollection | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileCollection:
"""File Collection build utility type."""
def setup(cls, rule_details, details_map):
"""Full setup using details map."""
<|body_0|>
def build_commands(cls, rule_details):
"""Generate build command line."""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_75kplus_train_005729 | 3,775 | permissive | [
{
"docstring": "Full setup using details map.",
"name": "setup",
"signature": "def setup(cls, rule_details, details_map)"
},
{
"docstring": "Generate build command line.",
"name": "build_commands",
"signature": "def build_commands(cls, rule_details)"
}
] | 2 | null | Implement the Python class `FileCollection` described below.
Class description:
File Collection build utility type.
Method signatures and docstrings:
- def setup(cls, rule_details, details_map): Full setup using details map.
- def build_commands(cls, rule_details): Generate build command line. | Implement the Python class `FileCollection` described below.
Class description:
File Collection build utility type.
Method signatures and docstrings:
- def setup(cls, rule_details, details_map): Full setup using details map.
- def build_commands(cls, rule_details): Generate build command line.
<|skeleton|>
class Fil... | af028dd413dd2595cb8338a5a2c2d61a95adf7c6 | <|skeleton|>
class FileCollection:
"""File Collection build utility type."""
def setup(cls, rule_details, details_map):
"""Full setup using details map."""
<|body_0|>
def build_commands(cls, rule_details):
"""Generate build command line."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FileCollection:
"""File Collection build utility type."""
def setup(cls, rule_details, details_map):
"""Full setup using details map."""
out_file = rule_details[su.NAME_KEY] + '.{}'.format(rule_details.get(su.ARCHIVE_TYPE, su.DEFAULT_FILE_COLL_ARCHIVE_TYPE))
su.init_rule_common(ru... | the_stack_v2_python_sparse | build_tool/bu.scripts/mool/file_collection.py | rocketfuel/mool | train | 3 |
327d046a785fb0863dac2cdad36a51d5fb6aaa39 | [
"def fitter_fun(x, y, n, return_vals=False):\n with _warnings.catch_warnings():\n _warnings.filterwarnings('error')\n z = np.polyfit(x, y, n)\n p = np.poly1d(z)\n if return_vals:\n return p(x)\n else:\n return p\nspectra, nsamples, nener = _tst._resize_spectra(self._spect... | <|body_start_0|>
def fitter_fun(x, y, n, return_vals=False):
with _warnings.catch_warnings():
_warnings.filterwarnings('error')
z = np.polyfit(x, y, n)
p = np.poly1d(z)
if return_vals:
return p(x)
else:
... | A "mixin" class which only contains methods but deliberately lacks an __init__ method. Usage of mixin classes is intended for easier breaking of classes into smaller units each containing appropriate methods. | Unfold_mixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Unfold_mixin:
"""A "mixin" class which only contains methods but deliberately lacks an __init__ method. Usage of mixin classes is intended for easier breaking of classes into smaller units each containing appropriate methods."""
def _unfold_function(self, n=3, merge_spectra=False):
"... | stack_v2_sparse_classes_75kplus_train_005730 | 14,443 | no_license | [
{
"docstring": "A function that performs spectral unfolding so that the mean level spacing after the procedure equals one. The routine is needed in various spectral statistics calculations, such as calculations of the spectral form factor, calculation of the number level variance or calculations of the distribu... | 4 | null | Implement the Python class `Unfold_mixin` described below.
Class description:
A "mixin" class which only contains methods but deliberately lacks an __init__ method. Usage of mixin classes is intended for easier breaking of classes into smaller units each containing appropriate methods.
Method signatures and docstring... | Implement the Python class `Unfold_mixin` described below.
Class description:
A "mixin" class which only contains methods but deliberately lacks an __init__ method. Usage of mixin classes is intended for easier breaking of classes into smaller units each containing appropriate methods.
Method signatures and docstring... | c915a41f1d2deb139d25f2251360cbfb77387b88 | <|skeleton|>
class Unfold_mixin:
"""A "mixin" class which only contains methods but deliberately lacks an __init__ method. Usage of mixin classes is intended for easier breaking of classes into smaller units each containing appropriate methods."""
def _unfold_function(self, n=3, merge_spectra=False):
"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Unfold_mixin:
"""A "mixin" class which only contains methods but deliberately lacks an __init__ method. Usage of mixin classes is intended for easier breaking of classes into smaller units each containing appropriate methods."""
def _unfold_function(self, n=3, merge_spectra=False):
"""A function ... | the_stack_v2_python_sparse | spectral_stats/utils/_unfolding.py | JanSuntajs/spectral_statistics_tools | train | 0 |
98f6110626e9a95ea5fb2398c0896f733570f358 | [
"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... | Origin Groups management service. | OriginGroupServiceServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OriginGroupServiceServicer:
"""Origin Groups management service."""
def Get(self, request, context):
"""Gets origin group with specified origin group id."""
<|body_0|>
def List(self, request, context):
"""Lists origins of origin group."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_005731 | 10,369 | permissive | [
{
"docstring": "Gets origin group with specified origin group id.",
"name": "Get",
"signature": "def Get(self, request, context)"
},
{
"docstring": "Lists origins of origin group.",
"name": "List",
"signature": "def List(self, request, context)"
},
{
"docstring": "Creates origin ... | 5 | stack_v2_sparse_classes_30k_train_043760 | Implement the Python class `OriginGroupServiceServicer` described below.
Class description:
Origin Groups management service.
Method signatures and docstrings:
- def Get(self, request, context): Gets origin group with specified origin group id.
- def List(self, request, context): Lists origins of origin group.
- def ... | Implement the Python class `OriginGroupServiceServicer` described below.
Class description:
Origin Groups management service.
Method signatures and docstrings:
- def Get(self, request, context): Gets origin group with specified origin group id.
- def List(self, request, context): Lists origins of origin group.
- def ... | b906a014dd893e2697864e1e48e814a8d9fbc48c | <|skeleton|>
class OriginGroupServiceServicer:
"""Origin Groups management service."""
def Get(self, request, context):
"""Gets origin group with specified origin group id."""
<|body_0|>
def List(self, request, context):
"""Lists origins of origin group."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OriginGroupServiceServicer:
"""Origin Groups management service."""
def Get(self, request, context):
"""Gets origin group with specified origin group id."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedE... | the_stack_v2_python_sparse | yandex/cloud/cdn/v1/origin_group_service_pb2_grpc.py | yandex-cloud/python-sdk | train | 63 |
88000392ff7ed945a764d5d379e590379727bad8 | [
"super().__init__()\nself.enc = enc\nself.dec = dec\nself.timestep = timestep\nself.seq_len = seq_len\nself.decoder_start = 0 if timestep == seq_len else timestep",
"_, (hn, cn) = self.enc(*args)\ndevice = hn.device\nseq_cont_data = args[1]\nseq_cat_data = args[0]\nbatch_size = seq_cont_data.shape[0]\ndecoder_inp... | <|body_start_0|>
super().__init__()
self.enc = enc
self.dec = dec
self.timestep = timestep
self.seq_len = seq_len
self.decoder_start = 0 if timestep == seq_len else timestep
<|end_body_0|>
<|body_start_1|>
_, (hn, cn) = self.enc(*args)
device = hn.device
... | Teacher Training based autoencoder. | AutoencoderTeacherTraining | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutoencoderTeacherTraining:
"""Teacher Training based autoencoder."""
def __init__(self, enc, dec, timestep=15, seq_len=15):
"""Initialize model with params."""
<|body_0|>
def forward(self, *args):
"""Run a forward pass of model over the data."""
<|body_1... | stack_v2_sparse_classes_75kplus_train_005732 | 15,906 | permissive | [
{
"docstring": "Initialize model with params.",
"name": "__init__",
"signature": "def __init__(self, enc, dec, timestep=15, seq_len=15)"
},
{
"docstring": "Run a forward pass of model over the data.",
"name": "forward",
"signature": "def forward(self, *args)"
},
{
"docstring": "R... | 3 | stack_v2_sparse_classes_30k_train_034775 | Implement the Python class `AutoencoderTeacherTraining` described below.
Class description:
Teacher Training based autoencoder.
Method signatures and docstrings:
- def __init__(self, enc, dec, timestep=15, seq_len=15): Initialize model with params.
- def forward(self, *args): Run a forward pass of model over the data... | Implement the Python class `AutoencoderTeacherTraining` described below.
Class description:
Teacher Training based autoencoder.
Method signatures and docstrings:
- def __init__(self, enc, dec, timestep=15, seq_len=15): Initialize model with params.
- def forward(self, *args): Run a forward pass of model over the data... | 9cdbf270487751a0ad6862b2fea2ccc0e23a0b67 | <|skeleton|>
class AutoencoderTeacherTraining:
"""Teacher Training based autoencoder."""
def __init__(self, enc, dec, timestep=15, seq_len=15):
"""Initialize model with params."""
<|body_0|>
def forward(self, *args):
"""Run a forward pass of model over the data."""
<|body_1... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AutoencoderTeacherTraining:
"""Teacher Training based autoencoder."""
def __init__(self, enc, dec, timestep=15, seq_len=15):
"""Initialize model with params."""
super().__init__()
self.enc = enc
self.dec = dec
self.timestep = timestep
self.seq_len = seq_len... | the_stack_v2_python_sparse | caspr/models/model_wrapper.py | microsoft/CASPR | train | 29 |
47868ab76c3679063561f724b7bd07662a27d5bb | [
"super().__init__(status)\nself._name = name\nself._actions = actions",
"attr = {}\nif self._actions:\n attr['actions_enabled'] = self._actions.enabled\n if self._actions.last_finished != EMPTY_TIME:\n attr['actions_last_finished'] = self._actions.last_finished\n if self._actions.last_run != EMPTY... | <|body_start_0|>
super().__init__(status)
self._name = name
self._actions = actions
<|end_body_0|>
<|body_start_1|>
attr = {}
if self._actions:
attr['actions_enabled'] = self._actions.enabled
if self._actions.last_finished != EMPTY_TIME:
a... | Representation of an ISY994 program base. | ISYProgramEntity | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ISYProgramEntity:
"""Representation of an ISY994 program base."""
def __init__(self, name: str, status, actions=None) -> None:
"""Initialize the ISY994 program-based entity."""
<|body_0|>
def extra_state_attributes(self) -> dict:
"""Get the state attributes for t... | stack_v2_sparse_classes_75kplus_train_005733 | 9,283 | permissive | [
{
"docstring": "Initialize the ISY994 program-based entity.",
"name": "__init__",
"signature": "def __init__(self, name: str, status, actions=None) -> None"
},
{
"docstring": "Get the state attributes for the device.",
"name": "extra_state_attributes",
"signature": "def extra_state_attri... | 2 | stack_v2_sparse_classes_30k_train_008622 | Implement the Python class `ISYProgramEntity` described below.
Class description:
Representation of an ISY994 program base.
Method signatures and docstrings:
- def __init__(self, name: str, status, actions=None) -> None: Initialize the ISY994 program-based entity.
- def extra_state_attributes(self) -> dict: Get the s... | Implement the Python class `ISYProgramEntity` described below.
Class description:
Representation of an ISY994 program base.
Method signatures and docstrings:
- def __init__(self, name: str, status, actions=None) -> None: Initialize the ISY994 program-based entity.
- def extra_state_attributes(self) -> dict: Get the s... | 2fee32fce03bc49e86cf2e7b741a15621a97cce5 | <|skeleton|>
class ISYProgramEntity:
"""Representation of an ISY994 program base."""
def __init__(self, name: str, status, actions=None) -> None:
"""Initialize the ISY994 program-based entity."""
<|body_0|>
def extra_state_attributes(self) -> dict:
"""Get the state attributes for t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ISYProgramEntity:
"""Representation of an ISY994 program base."""
def __init__(self, name: str, status, actions=None) -> None:
"""Initialize the ISY994 program-based entity."""
super().__init__(status)
self._name = name
self._actions = actions
def extra_state_attribut... | the_stack_v2_python_sparse | homeassistant/components/isy994/entity.py | BenWoodford/home-assistant | train | 11 |
4bb4dd9873c4f45e1d43dee83a23174fc6c14962 | [
"super(ItemAtDeskToItemOnLoan, self).before(loan, **kwargs)\nself.ensure_item_is_available(loan)\nif loan.get('start_date'):\n loan['start_date'] = parse_date(loan['start_date'])\nif loan.get('end_date'):\n loan['end_date'] = parse_date(loan['end_date'])\n_ensure_valid_loan_duration(loan)",
"loan['start_dat... | <|body_start_0|>
super(ItemAtDeskToItemOnLoan, self).before(loan, **kwargs)
self.ensure_item_is_available(loan)
if loan.get('start_date'):
loan['start_date'] = parse_date(loan['start_date'])
if loan.get('end_date'):
loan['end_date'] = parse_date(loan['end_date'])
... | Check-out action to perform a loan when item ready at desk. | ItemAtDeskToItemOnLoan | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ItemAtDeskToItemOnLoan:
"""Check-out action to perform a loan when item ready at desk."""
def before(self, loan, **kwargs):
"""Validate checkout action."""
<|body_0|>
def after(self, loan):
"""Convert dates to string before saving loan."""
<|body_1|>
<|e... | stack_v2_sparse_classes_75kplus_train_005734 | 9,784 | permissive | [
{
"docstring": "Validate checkout action.",
"name": "before",
"signature": "def before(self, loan, **kwargs)"
},
{
"docstring": "Convert dates to string before saving loan.",
"name": "after",
"signature": "def after(self, loan)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012317 | Implement the Python class `ItemAtDeskToItemOnLoan` described below.
Class description:
Check-out action to perform a loan when item ready at desk.
Method signatures and docstrings:
- def before(self, loan, **kwargs): Validate checkout action.
- def after(self, loan): Convert dates to string before saving loan. | Implement the Python class `ItemAtDeskToItemOnLoan` described below.
Class description:
Check-out action to perform a loan when item ready at desk.
Method signatures and docstrings:
- def before(self, loan, **kwargs): Validate checkout action.
- def after(self, loan): Convert dates to string before saving loan.
<|sk... | ad47dbd4e086f4d4a889d4039960f710cb291c6d | <|skeleton|>
class ItemAtDeskToItemOnLoan:
"""Check-out action to perform a loan when item ready at desk."""
def before(self, loan, **kwargs):
"""Validate checkout action."""
<|body_0|>
def after(self, loan):
"""Convert dates to string before saving loan."""
<|body_1|>
<|e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ItemAtDeskToItemOnLoan:
"""Check-out action to perform a loan when item ready at desk."""
def before(self, loan, **kwargs):
"""Validate checkout action."""
super(ItemAtDeskToItemOnLoan, self).before(loan, **kwargs)
self.ensure_item_is_available(loan)
if loan.get('start_dat... | the_stack_v2_python_sparse | invenio_circulation/transitions/transitions.py | zzacharo/invenio-circulation | train | 0 |
916a1337eef60e1b0a287c252b6ff35fc4f9a501 | [
"self.tf = tfl\nself.config = ddynrec\nself.pos_controller = pos_controller\nself.last_time = rospy.Time(0)",
"focus = self.pos_controller.transformPoseFull(self.pos_controller.alt_controller.base_link_frame, msg.look_at_position, self.pos_controller.alt_controller.odom_frame)\norientation_to_look_at = math.atan2... | <|body_start_0|>
self.tf = tfl
self.config = ddynrec
self.pos_controller = pos_controller
self.last_time = rospy.Time(0)
<|end_body_0|>
<|body_start_1|>
focus = self.pos_controller.transformPoseFull(self.pos_controller.alt_controller.base_link_frame, msg.look_at_position, self.p... | PIDPosCamController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PIDPosCamController:
def __init__(self, tfl, ddynrec, pos_controller):
""":type tfl: TransformListener :type ddynrec: DDynamicReconfigure :type pos_controller: PIDPosController"""
<|body_0|>
def cmd_pos_cam(self, msg):
"""inputs a pose for the drone to go to, and a p... | stack_v2_sparse_classes_75kplus_train_005735 | 11,625 | no_license | [
{
"docstring": ":type tfl: TransformListener :type ddynrec: DDynamicReconfigure :type pos_controller: PIDPosController",
"name": "__init__",
"signature": "def __init__(self, tfl, ddynrec, pos_controller)"
},
{
"docstring": "inputs a pose for the drone to go to, and a position for the drone to fa... | 2 | stack_v2_sparse_classes_30k_train_045867 | Implement the Python class `PIDPosCamController` described below.
Class description:
Implement the PIDPosCamController class.
Method signatures and docstrings:
- def __init__(self, tfl, ddynrec, pos_controller): :type tfl: TransformListener :type ddynrec: DDynamicReconfigure :type pos_controller: PIDPosController
- d... | Implement the Python class `PIDPosCamController` described below.
Class description:
Implement the PIDPosCamController class.
Method signatures and docstrings:
- def __init__(self, tfl, ddynrec, pos_controller): :type tfl: TransformListener :type ddynrec: DDynamicReconfigure :type pos_controller: PIDPosController
- d... | 21ea21ff1162411bb142e57b4b07feb7b7ba95e5 | <|skeleton|>
class PIDPosCamController:
def __init__(self, tfl, ddynrec, pos_controller):
""":type tfl: TransformListener :type ddynrec: DDynamicReconfigure :type pos_controller: PIDPosController"""
<|body_0|>
def cmd_pos_cam(self, msg):
"""inputs a pose for the drone to go to, and a p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PIDPosCamController:
def __init__(self, tfl, ddynrec, pos_controller):
""":type tfl: TransformListener :type ddynrec: DDynamicReconfigure :type pos_controller: PIDPosController"""
self.tf = tfl
self.config = ddynrec
self.pos_controller = pos_controller
self.last_time = ... | the_stack_v2_python_sparse | iarc_arbiter/scripts/transformers.py | Olin-Aero/olin-aerial-robotics-chess | train | 0 | |
797271c628cebb13301d985222cd181860566659 | [
"try:\n params = request._serialize()\n body = self.call('CreateQos', params)\n response = json.loads(body)\n if 'Error' not in response['Response']:\n model = models.CreateQosResponse()\n model._deserialize(response['Response'])\n return model\n else:\n code = response['R... | <|body_start_0|>
try:
params = request._serialize()
body = self.call('CreateQos', params)
response = json.loads(body)
if 'Error' not in response['Response']:
model = models.CreateQosResponse()
model._deserialize(response['Response']... | MnaClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MnaClient:
def CreateQos(self, request):
"""移动网络发起Qos加速过程 :param request: Request instance for CreateQos. :type request: :class:`tencentcloud.mna.v20210119.models.CreateQosRequest` :rtype: :class:`tencentcloud.mna.v20210119.models.CreateQosResponse`"""
<|body_0|>
def DeleteQ... | stack_v2_sparse_classes_75kplus_train_005736 | 3,225 | permissive | [
{
"docstring": "移动网络发起Qos加速过程 :param request: Request instance for CreateQos. :type request: :class:`tencentcloud.mna.v20210119.models.CreateQosRequest` :rtype: :class:`tencentcloud.mna.v20210119.models.CreateQosResponse`",
"name": "CreateQos",
"signature": "def CreateQos(self, request)"
},
{
"d... | 2 | stack_v2_sparse_classes_30k_train_044088 | Implement the Python class `MnaClient` described below.
Class description:
Implement the MnaClient class.
Method signatures and docstrings:
- def CreateQos(self, request): 移动网络发起Qos加速过程 :param request: Request instance for CreateQos. :type request: :class:`tencentcloud.mna.v20210119.models.CreateQosRequest` :rtype: :... | Implement the Python class `MnaClient` described below.
Class description:
Implement the MnaClient class.
Method signatures and docstrings:
- def CreateQos(self, request): 移动网络发起Qos加速过程 :param request: Request instance for CreateQos. :type request: :class:`tencentcloud.mna.v20210119.models.CreateQosRequest` :rtype: :... | baed8b8e84ed0e8dd19600225796a75405cb922c | <|skeleton|>
class MnaClient:
def CreateQos(self, request):
"""移动网络发起Qos加速过程 :param request: Request instance for CreateQos. :type request: :class:`tencentcloud.mna.v20210119.models.CreateQosRequest` :rtype: :class:`tencentcloud.mna.v20210119.models.CreateQosResponse`"""
<|body_0|>
def DeleteQ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MnaClient:
def CreateQos(self, request):
"""移动网络发起Qos加速过程 :param request: Request instance for CreateQos. :type request: :class:`tencentcloud.mna.v20210119.models.CreateQosRequest` :rtype: :class:`tencentcloud.mna.v20210119.models.CreateQosResponse`"""
try:
params = request._serial... | the_stack_v2_python_sparse | tencentcloud/mna/v20210119/mna_client.py | WANGMUXIAN/tencentcloud-sdk-python | train | 0 | |
7f6bf6033fa58d1e345cec78b6a83dea0f579b8a | [
"assert isinstance(term, Term)\nself.term = term\nself.weight = weight",
"if self.weight == 1.0:\n return self.term.full_label\nelse:\n return '{}@{:0.2f}%'.format(self.term.full_label, self.weight)"
] | <|body_start_0|>
assert isinstance(term, Term)
self.term = term
self.weight = weight
<|end_body_0|>
<|body_start_1|>
if self.weight == 1.0:
return self.term.full_label
else:
return '{}@{:0.2f}%'.format(self.term.full_label, self.weight)
<|end_body_1|>
| A `Term`, with a weight assigned. All consequents become `WeightedTerm`s in calculation; if a weight was not assigned, they default to a weight of 1.0. | WeightedTerm | [
"BSD-3-Clause",
"BSD-2-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WeightedTerm:
"""A `Term`, with a weight assigned. All consequents become `WeightedTerm`s in calculation; if a weight was not assigned, they default to a weight of 1.0."""
def __init__(self, term, weight=1.0):
"""Initialize the weighted consequent. Parameters ---------- term : Term A... | stack_v2_sparse_classes_75kplus_train_005737 | 6,237 | permissive | [
{
"docstring": "Initialize the weighted consequent. Parameters ---------- term : Term A fuzzy variable with specified mebership function. weight : float Weight to assign this Term",
"name": "__init__",
"signature": "def __init__(self, term, weight=1.0)"
},
{
"docstring": "String representation o... | 2 | stack_v2_sparse_classes_30k_train_028769 | Implement the Python class `WeightedTerm` described below.
Class description:
A `Term`, with a weight assigned. All consequents become `WeightedTerm`s in calculation; if a weight was not assigned, they default to a weight of 1.0.
Method signatures and docstrings:
- def __init__(self, term, weight=1.0): Initialize the... | Implement the Python class `WeightedTerm` described below.
Class description:
A `Term`, with a weight assigned. All consequents become `WeightedTerm`s in calculation; if a weight was not assigned, they default to a weight of 1.0.
Method signatures and docstrings:
- def __init__(self, term, weight=1.0): Initialize the... | d8c45c259d62955004379592e45bc64c8e002fc3 | <|skeleton|>
class WeightedTerm:
"""A `Term`, with a weight assigned. All consequents become `WeightedTerm`s in calculation; if a weight was not assigned, they default to a weight of 1.0."""
def __init__(self, term, weight=1.0):
"""Initialize the weighted consequent. Parameters ---------- term : Term A... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WeightedTerm:
"""A `Term`, with a weight assigned. All consequents become `WeightedTerm`s in calculation; if a weight was not assigned, they default to a weight of 1.0."""
def __init__(self, term, weight=1.0):
"""Initialize the weighted consequent. Parameters ---------- term : Term A fuzzy variab... | the_stack_v2_python_sparse | skfuzzy/control/term.py | scikit-fuzzy/scikit-fuzzy | train | 715 |
d250cbf3c15fcd41c20f692f38ef9b3481a69c45 | [
"auth = tweepy.OAuth1UserHandler(consumer_key=os.environ.get('TWITTER_CONSUMER_KEY', ''), consumer_secret=os.environ.get('TWITTER_CONSUMER_SECRET', ''), access_token=os.environ.get('TWITTER_ACCESS_TOKEN'), access_token_secret=os.environ.get('TWITTER_ACCESS_TOKEN_SECRET'))\nself.__v1_api: tweepy.API = tweepy.API(aut... | <|body_start_0|>
auth = tweepy.OAuth1UserHandler(consumer_key=os.environ.get('TWITTER_CONSUMER_KEY', ''), consumer_secret=os.environ.get('TWITTER_CONSUMER_SECRET', ''), access_token=os.environ.get('TWITTER_ACCESS_TOKEN'), access_token_secret=os.environ.get('TWITTER_ACCESS_TOKEN_SECRET'))
self.__v1_api: ... | Easy poster for Twitter API. Uses consumer and access token key/secret defined in the following environment variables: - `TWITTER_CONSUMER_KEY` - `TWITTER_CONSUMER_SECRET` - `TWITTER_ACCESS_TOKEN` - `TWITTER_ACCESS_TOKEN_SECRET` | TwitterPoster | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwitterPoster:
"""Easy poster for Twitter API. Uses consumer and access token key/secret defined in the following environment variables: - `TWITTER_CONSUMER_KEY` - `TWITTER_CONSUMER_SECRET` - `TWITTER_ACCESS_TOKEN` - `TWITTER_ACCESS_TOKEN_SECRET`"""
def __init__(self) -> None:
"""Cre... | stack_v2_sparse_classes_75kplus_train_005738 | 2,398 | no_license | [
{
"docstring": "Create the Twitter poster using the environment variables described above.",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Make a post to Twitter using the given `PostCreator`. Parameters ---------- post_creator : PostCreator post creator to mak... | 2 | stack_v2_sparse_classes_30k_train_025883 | Implement the Python class `TwitterPoster` described below.
Class description:
Easy poster for Twitter API. Uses consumer and access token key/secret defined in the following environment variables: - `TWITTER_CONSUMER_KEY` - `TWITTER_CONSUMER_SECRET` - `TWITTER_ACCESS_TOKEN` - `TWITTER_ACCESS_TOKEN_SECRET`
Method sig... | Implement the Python class `TwitterPoster` described below.
Class description:
Easy poster for Twitter API. Uses consumer and access token key/secret defined in the following environment variables: - `TWITTER_CONSUMER_KEY` - `TWITTER_CONSUMER_SECRET` - `TWITTER_ACCESS_TOKEN` - `TWITTER_ACCESS_TOKEN_SECRET`
Method sig... | 555c86d1b5d798888803032ba65ab9835de58478 | <|skeleton|>
class TwitterPoster:
"""Easy poster for Twitter API. Uses consumer and access token key/secret defined in the following environment variables: - `TWITTER_CONSUMER_KEY` - `TWITTER_CONSUMER_SECRET` - `TWITTER_ACCESS_TOKEN` - `TWITTER_ACCESS_TOKEN_SECRET`"""
def __init__(self) -> None:
"""Cre... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TwitterPoster:
"""Easy poster for Twitter API. Uses consumer and access token key/secret defined in the following environment variables: - `TWITTER_CONSUMER_KEY` - `TWITTER_CONSUMER_SECRET` - `TWITTER_ACCESS_TOKEN` - `TWITTER_ACCESS_TOKEN_SECRET`"""
def __init__(self) -> None:
"""Create the Twitt... | the_stack_v2_python_sparse | src/Poster/TwitterPoster.py | BenShoeman/SonicOCBot | train | 0 |
6b3a6bf0b45fef4b03fd1660326f886e2a1e9baa | [
"next_index = next_object_key(self)\nmaterial = Material(name, density, elasticity_modulus, poissons_ratio, yield_strength, ultimate_strength, _class)\nsetattr(self, str(next_index), material)\nreturn next_index",
"materials = default_materials[unit_system][material]\nname = materials['name']\ndensity = materials... | <|body_start_0|>
next_index = next_object_key(self)
material = Material(name, density, elasticity_modulus, poissons_ratio, yield_strength, ultimate_strength, _class)
setattr(self, str(next_index), material)
return next_index
<|end_body_0|>
<|body_start_1|>
materials = default_ma... | Creates an instance of the SkyCiv Materials class. | Materials | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Materials:
"""Creates an instance of the SkyCiv Materials class."""
def add_custom(self, name: str, density: float, elasticity_modulus: float, poissons_ratio: float, yield_strength: float, ultimate_strength: float, _class: Literal['steel', 'aluminium', 'masonry', 'concrete', 'wood', 'other']... | stack_v2_sparse_classes_75kplus_train_005739 | 3,248 | permissive | [
{
"docstring": "Create a custom material with the next available ID. Args: name (str): The name of the material. density (float): The density of the material. elasticity_modulus (float): The Modulus of Elasticity of the material. poissons_ratio (float): The Poisson's Ratio for the material. yield_strength (floa... | 2 | null | Implement the Python class `Materials` described below.
Class description:
Creates an instance of the SkyCiv Materials class.
Method signatures and docstrings:
- def add_custom(self, name: str, density: float, elasticity_modulus: float, poissons_ratio: float, yield_strength: float, ultimate_strength: float, _class: L... | Implement the Python class `Materials` described below.
Class description:
Creates an instance of the SkyCiv Materials class.
Method signatures and docstrings:
- def add_custom(self, name: str, density: float, elasticity_modulus: float, poissons_ratio: float, yield_strength: float, ultimate_strength: float, _class: L... | 1cf3dad7f8d451760df02886df41684add72a4eb | <|skeleton|>
class Materials:
"""Creates an instance of the SkyCiv Materials class."""
def add_custom(self, name: str, density: float, elasticity_modulus: float, poissons_ratio: float, yield_strength: float, ultimate_strength: float, _class: Literal['steel', 'aluminium', 'masonry', 'concrete', 'wood', 'other']... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Materials:
"""Creates an instance of the SkyCiv Materials class."""
def add_custom(self, name: str, density: float, elasticity_modulus: float, poissons_ratio: float, yield_strength: float, ultimate_strength: float, _class: Literal['steel', 'aluminium', 'masonry', 'concrete', 'wood', 'other']) -> int:
... | the_stack_v2_python_sparse | src/skyciv/classes/model/components/materials/materials.py | osasanchezme/skyciv-pip | train | 0 |
466b90116456c72faf1c91c79bdb91da64e40467 | [
"super(Callback, self).__init__()\nself.counter = 0\nself.registered_type = registered_type\nself.notice = notice\nself.sender = sender",
"print('Stored stage', sender.get_stage())\nprint('Got notice?', notice is self.notice)\nprint('Got sender?', sender is self.sender)\nself.counter += 1"
] | <|body_start_0|>
super(Callback, self).__init__()
self.counter = 0
self.registered_type = registered_type
self.notice = notice
self.sender = sender
<|end_body_0|>
<|body_start_1|>
print('Stored stage', sender.get_stage())
print('Got notice?', notice is self.notic... | A class that keeps track of sender / notice information. Important: This class is just an example of tracking the registered notice / sender. `Tf.Notice.Register` doesn't need an instance of a class. It can take a function, instead. | Callback | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Callback:
"""A class that keeps track of sender / notice information. Important: This class is just an example of tracking the registered notice / sender. `Tf.Notice.Register` doesn't need an instance of a class. It can take a function, instead."""
def __init__(self, registered_type, notice,... | stack_v2_sparse_classes_75kplus_train_005740 | 2,664 | permissive | [
{
"docstring": "Keep track of the given information.",
"name": "__init__",
"signature": "def __init__(self, registered_type, notice, sender)"
},
{
"docstring": "Print out the notice / sender that triggered this notice. In many cases you'd want `notice` and `sender` to be whatever was used to reg... | 2 | null | Implement the Python class `Callback` described below.
Class description:
A class that keeps track of sender / notice information. Important: This class is just an example of tracking the registered notice / sender. `Tf.Notice.Register` doesn't need an instance of a class. It can take a function, instead.
Method sign... | Implement the Python class `Callback` described below.
Class description:
A class that keeps track of sender / notice information. Important: This class is just an example of tracking the registered notice / sender. `Tf.Notice.Register` doesn't need an instance of a class. It can take a function, instead.
Method sign... | 33eac067a0a62578934105b19a2b9d8e4ea0646c | <|skeleton|>
class Callback:
"""A class that keeps track of sender / notice information. Important: This class is just an example of tracking the registered notice / sender. `Tf.Notice.Register` doesn't need an instance of a class. It can take a function, instead."""
def __init__(self, registered_type, notice,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Callback:
"""A class that keeps track of sender / notice information. Important: This class is just an example of tracking the registered notice / sender. `Tf.Notice.Register` doesn't need an instance of a class. It can take a function, instead."""
def __init__(self, registered_type, notice, sender):
... | the_stack_v2_python_sparse | features/notice_send/python/notice_send_custom.py | ColinKennedy/USD-Cookbook | train | 515 |
52078b2df4a29be015a0176e613b0d5aa750bcb1 | [
"res = super(purchase_order_line, self)._onchange_product_id()\nif self.product_id and self.product_id.purchase_pad_id:\n pad = self.product_id.purchase_pad_id\n list_line = []\n for line in pad.distribution_ids:\n vals = {'company_id': pad.company_id.id, 'type': line.type, 'value': line.value, 'acc... | <|body_start_0|>
res = super(purchase_order_line, self)._onchange_product_id()
if self.product_id and self.product_id.purchase_pad_id:
pad = self.product_id.purchase_pad_id
list_line = []
for line in pad.distribution_ids:
vals = {'company_id': pad.comp... | purchase_order_line | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class purchase_order_line:
def _onchange_product_id(self):
"""Surcharge du onchange du produit afin d'ajouter les lignes de distribution analytique"""
<|body_0|>
def create_purchase_order_line(self, purchase=False, product=None, values=None, first_qty=False, forced_qty=False, not_... | stack_v2_sparse_classes_75kplus_train_005741 | 4,289 | no_license | [
{
"docstring": "Surcharge du onchange du produit afin d'ajouter les lignes de distribution analytique",
"name": "_onchange_product_id",
"signature": "def _onchange_product_id(self)"
},
{
"docstring": "Surcharge de la méthode de création des lignes d'achat afin de prendre en compte la distributio... | 2 | stack_v2_sparse_classes_30k_val_002761 | Implement the Python class `purchase_order_line` described below.
Class description:
Implement the purchase_order_line class.
Method signatures and docstrings:
- def _onchange_product_id(self): Surcharge du onchange du produit afin d'ajouter les lignes de distribution analytique
- def create_purchase_order_line(self,... | Implement the Python class `purchase_order_line` described below.
Class description:
Implement the purchase_order_line class.
Method signatures and docstrings:
- def _onchange_product_id(self): Surcharge du onchange du produit afin d'ajouter les lignes de distribution analytique
- def create_purchase_order_line(self,... | eb394e1f79ba1995da2dcd81adfdd511c22caff9 | <|skeleton|>
class purchase_order_line:
def _onchange_product_id(self):
"""Surcharge du onchange du produit afin d'ajouter les lignes de distribution analytique"""
<|body_0|>
def create_purchase_order_line(self, purchase=False, product=None, values=None, first_qty=False, forced_qty=False, not_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class purchase_order_line:
def _onchange_product_id(self):
"""Surcharge du onchange du produit afin d'ajouter les lignes de distribution analytique"""
res = super(purchase_order_line, self)._onchange_product_id()
if self.product_id and self.product_id.purchase_pad_id:
pad = self.... | the_stack_v2_python_sparse | OpenPROD/openprod-addons/analytic_distribution/purchase.py | kazacube-mziouadi/ceci | train | 0 | |
25032bb14c010e277ab7dbe4c0c1fabf7c3a0e31 | [
"trace1 = go.Scatter(x=x, y=y, marker={'color': 'red', 'symbol': 'circle', 'size': 10}, mode='lines', name=title)\nlayout = go.Layout(title=title, xaxis={'title': 'Date'}, yaxis={'title': 'Value'})\nfigure = go.Figure([trace1], layout=layout)\ndiv = opy.plot(figure, auto_open=False, output_type='div')\nreturn div",... | <|body_start_0|>
trace1 = go.Scatter(x=x, y=y, marker={'color': 'red', 'symbol': 'circle', 'size': 10}, mode='lines', name=title)
layout = go.Layout(title=title, xaxis={'title': 'Date'}, yaxis={'title': 'Value'})
figure = go.Figure([trace1], layout=layout)
div = opy.plot(figure, auto_ope... | Plot class provides static methods for generating HTML blocks containing various plots. Intended for encapsulating the plotting functionality and for ease of writing views | Plot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Plot:
"""Plot class provides static methods for generating HTML blocks containing various plots. Intended for encapsulating the plotting functionality and for ease of writing views"""
def getLinePlot(x, y, title):
"""return an HTML div with a plot :param x: Horizontal axis data (arra... | stack_v2_sparse_classes_75kplus_train_005742 | 2,349 | no_license | [
{
"docstring": "return an HTML div with a plot :param x: Horizontal axis data (array-like) :param y: Vertical axis data (array-like) :param title: Title for the plot :return: an html div with a plot",
"name": "getLinePlot",
"signature": "def getLinePlot(x, y, title)"
},
{
"docstring": "return an... | 3 | stack_v2_sparse_classes_30k_train_004111 | Implement the Python class `Plot` described below.
Class description:
Plot class provides static methods for generating HTML blocks containing various plots. Intended for encapsulating the plotting functionality and for ease of writing views
Method signatures and docstrings:
- def getLinePlot(x, y, title): return an ... | Implement the Python class `Plot` described below.
Class description:
Plot class provides static methods for generating HTML blocks containing various plots. Intended for encapsulating the plotting functionality and for ease of writing views
Method signatures and docstrings:
- def getLinePlot(x, y, title): return an ... | 8be59123e53930d8353d7e2ac997a41ae39bf0dd | <|skeleton|>
class Plot:
"""Plot class provides static methods for generating HTML blocks containing various plots. Intended for encapsulating the plotting functionality and for ease of writing views"""
def getLinePlot(x, y, title):
"""return an HTML div with a plot :param x: Horizontal axis data (arra... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Plot:
"""Plot class provides static methods for generating HTML blocks containing various plots. Intended for encapsulating the plotting functionality and for ease of writing views"""
def getLinePlot(x, y, title):
"""return an HTML div with a plot :param x: Horizontal axis data (array-like) :para... | the_stack_v2_python_sparse | ttt/Plot.py | amalhotr/SMIL_project | train | 0 |
ea0077ea4b5d2acf22e5edbb8a6c8fce55f4013f | [
"post = self.get_object()\nif self.request.user == post.created_by:\n return True\nreturn False",
"form.instance.updated_by = self.request.user\nform.instance.updated_at = timezone.now()\nreturn super().form_valid(form)",
"context = super().get_context_data(**kwargs)\ncontext['login'] = self.request.user.is_... | <|body_start_0|>
post = self.get_object()
if self.request.user == post.created_by:
return True
return False
<|end_body_0|>
<|body_start_1|>
form.instance.updated_by = self.request.user
form.instance.updated_at = timezone.now()
return super().form_valid(form)
... | View of page when editing posts. | PostUpdateView | [
"MIT",
"Python-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostUpdateView:
"""View of page when editing posts."""
def test_func(self):
"""To check user has permission (user is created_by) to edit post."""
<|body_0|>
def form_valid(self, form):
"""Fills in fields not queried from user."""
<|body_1|>
def get_c... | stack_v2_sparse_classes_75kplus_train_005743 | 9,599 | permissive | [
{
"docstring": "To check user has permission (user is created_by) to edit post.",
"name": "test_func",
"signature": "def test_func(self)"
},
{
"docstring": "Fills in fields not queried from user.",
"name": "form_valid",
"signature": "def form_valid(self, form)"
},
{
"docstring": ... | 3 | stack_v2_sparse_classes_30k_train_025410 | Implement the Python class `PostUpdateView` described below.
Class description:
View of page when editing posts.
Method signatures and docstrings:
- def test_func(self): To check user has permission (user is created_by) to edit post.
- def form_valid(self, form): Fills in fields not queried from user.
- def get_conte... | Implement the Python class `PostUpdateView` described below.
Class description:
View of page when editing posts.
Method signatures and docstrings:
- def test_func(self): To check user has permission (user is created_by) to edit post.
- def form_valid(self, form): Fills in fields not queried from user.
- def get_conte... | 9d46c6a9e6ccfae1b9ab5db1b6bf2a6b0abe4c10 | <|skeleton|>
class PostUpdateView:
"""View of page when editing posts."""
def test_func(self):
"""To check user has permission (user is created_by) to edit post."""
<|body_0|>
def form_valid(self, form):
"""Fills in fields not queried from user."""
<|body_1|>
def get_c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PostUpdateView:
"""View of page when editing posts."""
def test_func(self):
"""To check user has permission (user is created_by) to edit post."""
post = self.get_object()
if self.request.user == post.created_by:
return True
return False
def form_valid(self... | the_stack_v2_python_sparse | acceptable-albatrosses/albatrosses_hub/forums/views.py | whywhyy/summer-code-jam-2020 | train | 2 |
c0d1df093f133e1bbddcdee6f5fd57057ba28aa4 | [
"super(SepConv, self).__init__()\nself.dconv = nn.Conv2d(in_channels, in_channels * filters, kernel_size, dilation=dilation, groups=in_channels)\nself.pconv = nn.Conv2d(in_channels * filters, out_channels, kernel_size=1)\nself.padding = dilation[0] * (kernel_size[0] - 1)",
"x = F.pad(input, [0, 0, self.padding, 0... | <|body_start_0|>
super(SepConv, self).__init__()
self.dconv = nn.Conv2d(in_channels, in_channels * filters, kernel_size, dilation=dilation, groups=in_channels)
self.pconv = nn.Conv2d(in_channels * filters, out_channels, kernel_size=1)
self.padding = dilation[0] * (kernel_size[0] - 1)
<|e... | SepConv | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SepConv:
def __init__(self, in_channels, filters, out_channels, kernel_size=(5, 2), dilation=(1, 1)):
""":param kernel_size (time, frequency)"""
<|body_0|>
def forward(self, input):
"""input: [B, C, T, F]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_005744 | 14,384 | permissive | [
{
"docstring": ":param kernel_size (time, frequency)",
"name": "__init__",
"signature": "def __init__(self, in_channels, filters, out_channels, kernel_size=(5, 2), dilation=(1, 1))"
},
{
"docstring": "input: [B, C, T, F]",
"name": "forward",
"signature": "def forward(self, input)"
}
] | 2 | stack_v2_sparse_classes_30k_train_046662 | Implement the Python class `SepConv` described below.
Class description:
Implement the SepConv class.
Method signatures and docstrings:
- def __init__(self, in_channels, filters, out_channels, kernel_size=(5, 2), dilation=(1, 1)): :param kernel_size (time, frequency)
- def forward(self, input): input: [B, C, T, F] | Implement the Python class `SepConv` described below.
Class description:
Implement the SepConv class.
Method signatures and docstrings:
- def __init__(self, in_channels, filters, out_channels, kernel_size=(5, 2), dilation=(1, 1)): :param kernel_size (time, frequency)
- def forward(self, input): input: [B, C, T, F]
<... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class SepConv:
def __init__(self, in_channels, filters, out_channels, kernel_size=(5, 2), dilation=(1, 1)):
""":param kernel_size (time, frequency)"""
<|body_0|>
def forward(self, input):
"""input: [B, C, T, F]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SepConv:
def __init__(self, in_channels, filters, out_channels, kernel_size=(5, 2), dilation=(1, 1)):
""":param kernel_size (time, frequency)"""
super(SepConv, self).__init__()
self.dconv = nn.Conv2d(in_channels, in_channels * filters, kernel_size, dilation=dilation, groups=in_channels... | the_stack_v2_python_sparse | ai/modelscope/modelscope/models/audio/aec/layers/uni_deep_fsmn.py | alldatacenter/alldata | train | 774 | |
520c85458badb9b29eaba638f48d4e2ec304597f | [
"row = len(matrix)\ncol = len(matrix[0])\nrow_zero = set()\ncol_zero = set()\nfor i in range(row):\n for j in range(col):\n if matrix[i][j] == 0:\n row_zero.add(i)\n col_zero.add(j)\nfor i in range(row):\n for j in range(col):\n if i in row_zero or j in col_zero:\n ... | <|body_start_0|>
row = len(matrix)
col = len(matrix[0])
row_zero = set()
col_zero = set()
for i in range(row):
for j in range(col):
if matrix[i][j] == 0:
row_zero.add(i)
col_zero.add(j)
for i in range(row... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def setZeroes(self, matrix):
""":type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead. O(m+n)额外空间"""
<|body_0|>
def setZeroes1(self, matrix):
""":type matrix: List[List[int]] :rtype: None Do not return anything, m... | stack_v2_sparse_classes_75kplus_train_005745 | 1,551 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead. O(m+n)额外空间",
"name": "setZeroes",
"signature": "def setZeroes(self, matrix)"
},
{
"docstring": ":type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-p... | 2 | stack_v2_sparse_classes_30k_train_035258 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes(self, matrix): :type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead. O(m+n)额外空间
- def setZeroes1(self, matrix): :type m... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes(self, matrix): :type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead. O(m+n)额外空间
- def setZeroes1(self, matrix): :type m... | 3f4284330f9771037ca59e2e6a94122e51e58540 | <|skeleton|>
class Solution:
def setZeroes(self, matrix):
""":type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead. O(m+n)额外空间"""
<|body_0|>
def setZeroes1(self, matrix):
""":type matrix: List[List[int]] :rtype: None Do not return anything, m... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def setZeroes(self, matrix):
""":type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead. O(m+n)额外空间"""
row = len(matrix)
col = len(matrix[0])
row_zero = set()
col_zero = set()
for i in range(row):
f... | the_stack_v2_python_sparse | Leetcode/73.矩阵置零.py | myf-algorithm/Leetcode | train | 1 | |
fef620bf78c997dbb489bbe788d6da598ae849cb | [
"section1 = Sections.objects.create(name='section1')\nstages = Stages.objects.bulk_create([Stages(name='stage1', f_section=section1), Stages(name='stage2', f_section=section1)])\nQuestions.objects.bulk_create([Questions(name='question1', f_stage=stages[0]), Questions(name='question2', f_stage=stages[0]), Questions(... | <|body_start_0|>
section1 = Sections.objects.create(name='section1')
stages = Stages.objects.bulk_create([Stages(name='stage1', f_section=section1), Stages(name='stage2', f_section=section1)])
Questions.objects.bulk_create([Questions(name='question1', f_stage=stages[0]), Questions(name='question... | Test for GET department with unlogin user by id | DepartmentMiddlewareTestCases | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DepartmentMiddlewareTestCases:
"""Test for GET department with unlogin user by id"""
def setUp(self):
"""Create new department and fill questions"""
<|body_0|>
def test_get_valid_department_no_login_user(self):
"""Test for GET Department with id '2' with unlogin ... | stack_v2_sparse_classes_75kplus_train_005746 | 1,633 | no_license | [
{
"docstring": "Create new department and fill questions",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test for GET Department with id '2' with unlogin user and get error",
"name": "test_get_valid_department_no_login_user",
"signature": "def test_get_valid_departme... | 2 | stack_v2_sparse_classes_30k_train_044151 | Implement the Python class `DepartmentMiddlewareTestCases` described below.
Class description:
Test for GET department with unlogin user by id
Method signatures and docstrings:
- def setUp(self): Create new department and fill questions
- def test_get_valid_department_no_login_user(self): Test for GET Department with... | Implement the Python class `DepartmentMiddlewareTestCases` described below.
Class description:
Test for GET department with unlogin user by id
Method signatures and docstrings:
- def setUp(self): Create new department and fill questions
- def test_get_valid_department_no_login_user(self): Test for GET Department with... | f448ec0453818d55c5c9d30aaa4f19e1d7ca5867 | <|skeleton|>
class DepartmentMiddlewareTestCases:
"""Test for GET department with unlogin user by id"""
def setUp(self):
"""Create new department and fill questions"""
<|body_0|>
def test_get_valid_department_no_login_user(self):
"""Test for GET Department with id '2' with unlogin ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DepartmentMiddlewareTestCases:
"""Test for GET department with unlogin user by id"""
def setUp(self):
"""Create new department and fill questions"""
section1 = Sections.objects.create(name='section1')
stages = Stages.objects.bulk_create([Stages(name='stage1', f_section=section1), ... | the_stack_v2_python_sparse | Portfolio/tech-interview/techinterview/techinterview/middleware/test_login_middleware.py | HeCToR74/Python | train | 1 |
edf3c2bd5ebe1979d2e48ca1a53ad5c6aa7ad5b6 | [
"self.d_model = d_model\nself.d_f = d_f\nself.k = k\nself.n_outp = n_outp\nself.padding = padding\nself.first_layer = self.feedforward(inp)\nself.layer_list = [self.first_layer]\nfor i in range(n_blocks):\n self.layer_list.append(self.block(self.layer_list[-1], int(2 ** (i % (np.log2(max_d_rate) + 1)))))\nself.o... | <|body_start_0|>
self.d_model = d_model
self.d_f = d_f
self.k = k
self.n_outp = n_outp
self.padding = padding
self.first_layer = self.feedforward(inp)
self.layer_list = [self.first_layer]
for i in range(n_blocks):
self.layer_list.append(self.bl... | Residual network using bottlekneck residual blocks and cyclic dilation rate. Frame-wise layer normalisation is used. | ResNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResNet:
"""Residual network using bottlekneck residual blocks and cyclic dilation rate. Frame-wise layer normalisation is used."""
def __init__(self, inp, n_outp, n_blocks, d_model, d_f, k, max_d_rate, padding, sigmoid_outp):
"""Argument/s: inp - input placeholder. n_outp - number of... | stack_v2_sparse_classes_75kplus_train_005747 | 6,159 | no_license | [
{
"docstring": "Argument/s: inp - input placeholder. n_outp - number of output nodes. n_blocks - number of bottlekneck residual blocks. d_model - model size. d_f - bottlekneck size. k - kernel size. max_d_rate - maximum dilation rate. padding - padding type. sigmoid_outp - use a sigmoid output activation.",
... | 4 | stack_v2_sparse_classes_30k_train_029149 | Implement the Python class `ResNet` described below.
Class description:
Residual network using bottlekneck residual blocks and cyclic dilation rate. Frame-wise layer normalisation is used.
Method signatures and docstrings:
- def __init__(self, inp, n_outp, n_blocks, d_model, d_f, k, max_d_rate, padding, sigmoid_outp)... | Implement the Python class `ResNet` described below.
Class description:
Residual network using bottlekneck residual blocks and cyclic dilation rate. Frame-wise layer normalisation is used.
Method signatures and docstrings:
- def __init__(self, inp, n_outp, n_blocks, d_model, d_f, k, max_d_rate, padding, sigmoid_outp)... | e455ea79ae1522397c1f46a9fc1ac65a7fabe295 | <|skeleton|>
class ResNet:
"""Residual network using bottlekneck residual blocks and cyclic dilation rate. Frame-wise layer normalisation is used."""
def __init__(self, inp, n_outp, n_blocks, d_model, d_f, k, max_d_rate, padding, sigmoid_outp):
"""Argument/s: inp - input placeholder. n_outp - number of... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResNet:
"""Residual network using bottlekneck residual blocks and cyclic dilation rate. Frame-wise layer normalisation is used."""
def __init__(self, inp, n_outp, n_blocks, d_model, d_f, k, max_d_rate, padding, sigmoid_outp):
"""Argument/s: inp - input placeholder. n_outp - number of output nodes... | the_stack_v2_python_sparse | models/snr_estimation2/network/tcn.py | celpas/SpeakerIdentificationSystem | train | 2 |
2227e76f5938bbb5d92e697fb5f1d26d7cf5c943 | [
"object.__init__(self)\nassert isinstance(modelName, str)\nself.__model_name = modelName\nif rospy.get_node_uri() is None:\n rospy.init_node('GazeboInterface', log_level=rospy.INFO, argv=rospy.myargv(argv=sys.argv), anonymous=True)\n rospy.loginfo('ConveyorBelt: Ros node initial.')",
"rospy.wait_for_service... | <|body_start_0|>
object.__init__(self)
assert isinstance(modelName, str)
self.__model_name = modelName
if rospy.get_node_uri() is None:
rospy.init_node('GazeboInterface', log_level=rospy.INFO, argv=rospy.myargv(argv=sys.argv), anonymous=True)
rospy.loginfo('Convey... | ConveyorBelt | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConveyorBelt:
def __init__(self, modelName):
""":param modelName: name in gazebo"""
<|body_0|>
def setConveyorVel(self, vel):
""":param vel: conveyor belt velocity :return: if setting success"""
<|body_1|>
def getConveyorVel(self):
""":return: cu... | stack_v2_sparse_classes_75kplus_train_005748 | 1,994 | no_license | [
{
"docstring": ":param modelName: name in gazebo",
"name": "__init__",
"signature": "def __init__(self, modelName)"
},
{
"docstring": ":param vel: conveyor belt velocity :return: if setting success",
"name": "setConveyorVel",
"signature": "def setConveyorVel(self, vel)"
},
{
"doc... | 3 | stack_v2_sparse_classes_30k_train_039102 | Implement the Python class `ConveyorBelt` described below.
Class description:
Implement the ConveyorBelt class.
Method signatures and docstrings:
- def __init__(self, modelName): :param modelName: name in gazebo
- def setConveyorVel(self, vel): :param vel: conveyor belt velocity :return: if setting success
- def getC... | Implement the Python class `ConveyorBelt` described below.
Class description:
Implement the ConveyorBelt class.
Method signatures and docstrings:
- def __init__(self, modelName): :param modelName: name in gazebo
- def setConveyorVel(self, vel): :param vel: conveyor belt velocity :return: if setting success
- def getC... | 4dbc7f8603dc4a5ba9d74d0b7296e78546c2be49 | <|skeleton|>
class ConveyorBelt:
def __init__(self, modelName):
""":param modelName: name in gazebo"""
<|body_0|>
def setConveyorVel(self, vel):
""":param vel: conveyor belt velocity :return: if setting success"""
<|body_1|>
def getConveyorVel(self):
""":return: cu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConveyorBelt:
def __init__(self, modelName):
""":param modelName: name in gazebo"""
object.__init__(self)
assert isinstance(modelName, str)
self.__model_name = modelName
if rospy.get_node_uri() is None:
rospy.init_node('GazeboInterface', log_level=rospy.INFO... | the_stack_v2_python_sparse | rllib/envs/gazebo/GazeboInterface/ConveyorBelt.py | joyxh/RL-ppo | train | 0 | |
333ab5e54404ad1ae479298b9981a8802e45fa42 | [
"username = 'someusername'\npassword = 'somepassword'\nuser = User.objects.create_user(username=username, password=password)\nuser.save()\nstation = Station.objects.create(name='somename', address='someaddress', owner=user)\nstation.save()\nresponse = self.client.get(reverse('home_station', kwargs={'pk': station.pk... | <|body_start_0|>
username = 'someusername'
password = 'somepassword'
user = User.objects.create_user(username=username, password=password)
user.save()
station = Station.objects.create(name='somename', address='someaddress', owner=user)
station.save()
response = se... | TestStationHome | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestStationHome:
def test_login_required(self):
"""Assures page demands user be logged in"""
<|body_0|>
def test_authentication(self):
"""Assures that only the rightful user can access page"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
username = ... | stack_v2_sparse_classes_75kplus_train_005749 | 24,944 | no_license | [
{
"docstring": "Assures page demands user be logged in",
"name": "test_login_required",
"signature": "def test_login_required(self)"
},
{
"docstring": "Assures that only the rightful user can access page",
"name": "test_authentication",
"signature": "def test_authentication(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_053769 | Implement the Python class `TestStationHome` described below.
Class description:
Implement the TestStationHome class.
Method signatures and docstrings:
- def test_login_required(self): Assures page demands user be logged in
- def test_authentication(self): Assures that only the rightful user can access page | Implement the Python class `TestStationHome` described below.
Class description:
Implement the TestStationHome class.
Method signatures and docstrings:
- def test_login_required(self): Assures page demands user be logged in
- def test_authentication(self): Assures that only the rightful user can access page
<|skelet... | 32c476735765574c6f99b4ba2100119647fdba80 | <|skeleton|>
class TestStationHome:
def test_login_required(self):
"""Assures page demands user be logged in"""
<|body_0|>
def test_authentication(self):
"""Assures that only the rightful user can access page"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestStationHome:
def test_login_required(self):
"""Assures page demands user be logged in"""
username = 'someusername'
password = 'somepassword'
user = User.objects.create_user(username=username, password=password)
user.save()
station = Station.objects.create(na... | the_stack_v2_python_sparse | stationrunner/tests.py | TheLycaeum/openradio | train | 6 | |
542859cfffdae60ce944345b65cd1594d6e37560 | [
"self.title = 'Covert Miles to Kilometers'\nself.root = Builder.load_file('convert_miles_km.kv')\nreturn self.root",
"result = self.get_validated_miles() + value\nself.root.ids.input_number.text = str(result)\nself.handle_calculate()",
"value = self.get_validated_miles()\nresult = value * MILES_CONVERSION\nself... | <|body_start_0|>
self.title = 'Covert Miles to Kilometers'
self.root = Builder.load_file('convert_miles_km.kv')
return self.root
<|end_body_0|>
<|body_start_1|>
result = self.get_validated_miles() + value
self.root.ids.input_number.text = str(result)
self.handle_calculat... | ConvertMtoKmApp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvertMtoKmApp:
def build(self):
"""build the Kivy app from the kv file"""
<|body_0|>
def handle_increment(self, value):
"""handle calculation (could be button press or other call), output result to label widget"""
<|body_1|>
def handle_calculate(self):... | stack_v2_sparse_classes_75kplus_train_005750 | 1,396 | no_license | [
{
"docstring": "build the Kivy app from the kv file",
"name": "build",
"signature": "def build(self)"
},
{
"docstring": "handle calculation (could be button press or other call), output result to label widget",
"name": "handle_increment",
"signature": "def handle_increment(self, value)"
... | 4 | stack_v2_sparse_classes_30k_train_002363 | Implement the Python class `ConvertMtoKmApp` described below.
Class description:
Implement the ConvertMtoKmApp class.
Method signatures and docstrings:
- def build(self): build the Kivy app from the kv file
- def handle_increment(self, value): handle calculation (could be button press or other call), output result to... | Implement the Python class `ConvertMtoKmApp` described below.
Class description:
Implement the ConvertMtoKmApp class.
Method signatures and docstrings:
- def build(self): build the Kivy app from the kv file
- def handle_increment(self, value): handle calculation (could be button press or other call), output result to... | 1ec11aaa8eee03706c14d43f62e6c9845f962ee6 | <|skeleton|>
class ConvertMtoKmApp:
def build(self):
"""build the Kivy app from the kv file"""
<|body_0|>
def handle_increment(self, value):
"""handle calculation (could be button press or other call), output result to label widget"""
<|body_1|>
def handle_calculate(self):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConvertMtoKmApp:
def build(self):
"""build the Kivy app from the kv file"""
self.title = 'Covert Miles to Kilometers'
self.root = Builder.load_file('convert_miles_km.kv')
return self.root
def handle_increment(self, value):
"""handle calculation (could be button pre... | the_stack_v2_python_sparse | prac_07/convert_miles_km.py | SamBarrett1/cp1404practicals | train | 0 | |
fe85a295c6a01d1ba18c185bd8bf8ce9b3b37003 | [
"from nestedworld_api.db import UserFriend as DbUserFriend\nfriend = DbUserFriend.query.filter(DbUserFriend.id == friend_id).first()\nreturn friend",
"from nestedworld_api.db import db\nfrom nestedworld_api.db import UserFriend as DbUserFriend\nDbUserFriend.query.filter(DbUserFriend.id == friend_id).delete()\ndb.... | <|body_start_0|>
from nestedworld_api.db import UserFriend as DbUserFriend
friend = DbUserFriend.query.filter(DbUserFriend.id == friend_id).first()
return friend
<|end_body_0|>
<|body_start_1|>
from nestedworld_api.db import db
from nestedworld_api.db import UserFriend as DbUser... | UserFriend | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserFriend:
def get(self, friend_id):
"""Retrieve informations on a specific user's friend."""
<|body_0|>
def delete(self, friend_id):
"""delete an user in to current user's friends list This request is used by a user for deleting a link between him and another exist... | stack_v2_sparse_classes_75kplus_train_005751 | 3,764 | no_license | [
{
"docstring": "Retrieve informations on a specific user's friend.",
"name": "get",
"signature": "def get(self, friend_id)"
},
{
"docstring": "delete an user in to current user's friends list This request is used by a user for deleting a link between him and another existing user as friend.",
... | 2 | null | Implement the Python class `UserFriend` described below.
Class description:
Implement the UserFriend class.
Method signatures and docstrings:
- def get(self, friend_id): Retrieve informations on a specific user's friend.
- def delete(self, friend_id): delete an user in to current user's friends list This request is u... | Implement the Python class `UserFriend` described below.
Class description:
Implement the UserFriend class.
Method signatures and docstrings:
- def get(self, friend_id): Retrieve informations on a specific user's friend.
- def delete(self, friend_id): delete an user in to current user's friends list This request is u... | af2262742b04c823d2cf6e0fa40fa0fc6456671e | <|skeleton|>
class UserFriend:
def get(self, friend_id):
"""Retrieve informations on a specific user's friend."""
<|body_0|>
def delete(self, friend_id):
"""delete an user in to current user's friends list This request is used by a user for deleting a link between him and another exist... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserFriend:
def get(self, friend_id):
"""Retrieve informations on a specific user's friend."""
from nestedworld_api.db import UserFriend as DbUserFriend
friend = DbUserFriend.query.filter(DbUserFriend.id == friend_id).first()
return friend
def delete(self, friend_id):
... | the_stack_v2_python_sparse | nestedworld_api/views/api/v1/user/friends.py | NestedWorld/NestedWorld-Server-API | train | 1 | |
090b385356a9a4205e97b46e734e41e92546a9a0 | [
"self.device = None\nif device == 'cuda':\n self.device = torch.device('cuda')\nelse:\n self.device = torch.device('cpu')\nself.model = model.to(self.device)\nself.optimizer = optimizer\nself.creterion = creterion\nself.loss_list = []\nself.eval_interval = None",
"self.model.train()\niter_per_epoch = len(tr... | <|body_start_0|>
self.device = None
if device == 'cuda':
self.device = torch.device('cuda')
else:
self.device = torch.device('cpu')
self.model = model.to(self.device)
self.optimizer = optimizer
self.creterion = creterion
self.loss_list = []... | ネットワークモデルを使用して、学習と評価を行う学習器クラス | Trainer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trainer:
"""ネットワークモデルを使用して、学習と評価を行う学習器クラス"""
def __init__(self, model, optimizer, creterion, device='cpu'):
"""コンストラクタ Args: model (BaseModel): ネットワークモデル optimizer (torch.optim.Optimizer): 最適化手法 creterion (torch.nn.Loss): 損失関数 device (str, optional): 演算を実行するデバイス. Defaults to 'cpu'.""... | stack_v2_sparse_classes_75kplus_train_005752 | 6,272 | no_license | [
{
"docstring": "コンストラクタ Args: model (BaseModel): ネットワークモデル optimizer (torch.optim.Optimizer): 最適化手法 creterion (torch.nn.Loss): 損失関数 device (str, optional): 演算を実行するデバイス. Defaults to 'cpu'.",
"name": "__init__",
"signature": "def __init__(self, model, optimizer, creterion, device='cpu')"
},
{
"doc... | 4 | stack_v2_sparse_classes_30k_train_051155 | Implement the Python class `Trainer` described below.
Class description:
ネットワークモデルを使用して、学習と評価を行う学習器クラス
Method signatures and docstrings:
- def __init__(self, model, optimizer, creterion, device='cpu'): コンストラクタ Args: model (BaseModel): ネットワークモデル optimizer (torch.optim.Optimizer): 最適化手法 creterion (torch.nn.Loss): 損失関数 ... | Implement the Python class `Trainer` described below.
Class description:
ネットワークモデルを使用して、学習と評価を行う学習器クラス
Method signatures and docstrings:
- def __init__(self, model, optimizer, creterion, device='cpu'): コンストラクタ Args: model (BaseModel): ネットワークモデル optimizer (torch.optim.Optimizer): 最適化手法 creterion (torch.nn.Loss): 損失関数 ... | d323c6428d9a3257fa77887e5b23f9914b22cbe1 | <|skeleton|>
class Trainer:
"""ネットワークモデルを使用して、学習と評価を行う学習器クラス"""
def __init__(self, model, optimizer, creterion, device='cpu'):
"""コンストラクタ Args: model (BaseModel): ネットワークモデル optimizer (torch.optim.Optimizer): 最適化手法 creterion (torch.nn.Loss): 損失関数 device (str, optional): 演算を実行するデバイス. Defaults to 'cpu'.""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Trainer:
"""ネットワークモデルを使用して、学習と評価を行う学習器クラス"""
def __init__(self, model, optimizer, creterion, device='cpu'):
"""コンストラクタ Args: model (BaseModel): ネットワークモデル optimizer (torch.optim.Optimizer): 最適化手法 creterion (torch.nn.Loss): 損失関数 device (str, optional): 演算を実行するデバイス. Defaults to 'cpu'."""
sel... | the_stack_v2_python_sparse | src/trainer.py | BARANCE/DeepConvnetByPytorch | train | 0 |
56b771852fe4bc8ae307c38408e1efeaf1fbcee8 | [
"layer = [root]\nres = []\nwhile layer:\n next_layer = []\n for x in layer:\n if x:\n next_layer += [x.left, x.right]\n temp = [x.val if x else None for x in layer]\n res += temp\n layer = next_layer\nreturn str(res)",
"l = eval(data)\nroot = TreeNode(l[0]) if l[0] != None else No... | <|body_start_0|>
layer = [root]
res = []
while layer:
next_layer = []
for x in layer:
if x:
next_layer += [x.left, x.right]
temp = [x.val if x else None for x in layer]
res += temp
layer = next_layer
... | 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_005753 | 1,570 | 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_043145 | 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:... | e5dd213411b5c82b07171c3adf4556dcf9c44207 | <|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"""
layer = [root]
res = []
while layer:
next_layer = []
for x in layer:
if x:
next_layer += [x.left, x.right]
... | the_stack_v2_python_sparse | python/449.serialize-and-deserialize-bst.py | songzy12/LeetCode | train | 4 | |
95fc8d780fa85841ff7a8fc750cca30ed71ad7c4 | [
"route = route.strip('/')\nroute_list = route.split('/')\napp_name = route_list[0]\ncontroller_name = ''\naction_name = ''\nif len(route_list) > 1:\n controller_name = route_list[1]\nelse:\n raise Exception('Route no tiene controller')\nif len(route_list) > 2:\n action_name = route_list[2]\napp = 'apps.%s.... | <|body_start_0|>
route = route.strip('/')
route_list = route.split('/')
app_name = route_list[0]
controller_name = ''
action_name = ''
if len(route_list) > 1:
controller_name = route_list[1]
else:
raise Exception('Route no tiene controller'... | Clase que permite re-dirigir a un controller, cuaya solicitud se haya realizado con ajax o no Antes:: if request.is_ajax(): request.path="/params/locality/index/" #/app/controller_path/action/$params return locality_index(request) else: return redirect("/params/locality/index/") Ahora solo use (Example):: return Redire... | Redirect | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Redirect:
"""Clase que permite re-dirigir a un controller, cuaya solicitud se haya realizado con ajax o no Antes:: if request.is_ajax(): request.path="/params/locality/index/" #/app/controller_path/action/$params return locality_index(request) else: return redirect("/params/locality/index/") Ahor... | stack_v2_sparse_classes_75kplus_train_005754 | 5,806 | permissive | [
{
"docstring": "route_list[0] = app route_list[1] = controller route_list[2] = action",
"name": "to",
"signature": "def to(request, route, params=None)"
},
{
"docstring": "route_list[0] = app route_list[1] = controller route_list[2] = action",
"name": "to_action",
"signature": "def to_ac... | 2 | stack_v2_sparse_classes_30k_train_048956 | Implement the Python class `Redirect` described below.
Class description:
Clase que permite re-dirigir a un controller, cuaya solicitud se haya realizado con ajax o no Antes:: if request.is_ajax(): request.path="/params/locality/index/" #/app/controller_path/action/$params return locality_index(request) else: return r... | Implement the Python class `Redirect` described below.
Class description:
Clase que permite re-dirigir a un controller, cuaya solicitud se haya realizado con ajax o no Antes:: if request.is_ajax(): request.path="/params/locality/index/" #/app/controller_path/action/$params return locality_index(request) else: return r... | e16f609eca0c292c8c694c7eb279fe99296b45e3 | <|skeleton|>
class Redirect:
"""Clase que permite re-dirigir a un controller, cuaya solicitud se haya realizado con ajax o no Antes:: if request.is_ajax(): request.path="/params/locality/index/" #/app/controller_path/action/$params return locality_index(request) else: return redirect("/params/locality/index/") Ahor... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Redirect:
"""Clase que permite re-dirigir a un controller, cuaya solicitud se haya realizado con ajax o no Antes:: if request.is_ajax(): request.path="/params/locality/index/" #/app/controller_path/action/$params return locality_index(request) else: return redirect("/params/locality/index/") Ahora solo use (E... | the_stack_v2_python_sparse | apps/utils/security.py | tiposaurio/backenddj | train | 0 |
6e23b475e20719565c29202f058b6ece38ea1b32 | [
"ran = random.uniform(0.7, 1)\nline = line * ran + (1 - ran)\nreturn torch.clamp(line, min=0, max=1)",
"hint_count = 0\nif random.random() < zero_p:\n if random.random() < 0.4:\n hint_count = random.randint(1, 5)\nelse:\n hint_count = random.randint(random.randint(5, 32), random.randint(42, 65))\nare... | <|body_start_0|>
ran = random.uniform(0.7, 1)
line = line * ran + (1 - ran)
return torch.clamp(line, min=0, max=1)
<|end_body_0|>
<|body_start_1|>
hint_count = 0
if random.random() < zero_p:
if random.random() < 0.4:
hint_count = random.randint(1, 5)
... | Image Data Loader Base Class | DatasetBase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatasetBase:
"""Image Data Loader Base Class"""
def _jitter(line: torch.Tensor) -> torch.Tensor:
"""Line Arts Image Luminance Data-Augmentation Args: line (Tensor): line-arts image Tensor Returns: Tensor: line-arts data"""
<|body_0|>
def _create_mask(zero_p: float=0.4) -... | stack_v2_sparse_classes_75kplus_train_005755 | 9,556 | permissive | [
{
"docstring": "Line Arts Image Luminance Data-Augmentation Args: line (Tensor): line-arts image Tensor Returns: Tensor: line-arts data",
"name": "_jitter",
"signature": "def _jitter(line: torch.Tensor) -> torch.Tensor"
},
{
"docstring": "Create Random Hint Mask (0 or 1 binary 2D Mask) Args: zer... | 3 | stack_v2_sparse_classes_30k_train_043125 | Implement the Python class `DatasetBase` described below.
Class description:
Image Data Loader Base Class
Method signatures and docstrings:
- def _jitter(line: torch.Tensor) -> torch.Tensor: Line Arts Image Luminance Data-Augmentation Args: line (Tensor): line-arts image Tensor Returns: Tensor: line-arts data
- def _... | Implement the Python class `DatasetBase` described below.
Class description:
Image Data Loader Base Class
Method signatures and docstrings:
- def _jitter(line: torch.Tensor) -> torch.Tensor: Line Arts Image Luminance Data-Augmentation Args: line (Tensor): line-arts image Tensor Returns: Tensor: line-arts data
- def _... | e303f9acd793a201f568e2a83d7e94c054e2cf42 | <|skeleton|>
class DatasetBase:
"""Image Data Loader Base Class"""
def _jitter(line: torch.Tensor) -> torch.Tensor:
"""Line Arts Image Luminance Data-Augmentation Args: line (Tensor): line-arts image Tensor Returns: Tensor: line-arts data"""
<|body_0|>
def _create_mask(zero_p: float=0.4) -... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DatasetBase:
"""Image Data Loader Base Class"""
def _jitter(line: torch.Tensor) -> torch.Tensor:
"""Line Arts Image Luminance Data-Augmentation Args: line (Tensor): line-arts image Tensor Returns: Tensor: line-arts data"""
ran = random.uniform(0.7, 1)
line = line * ran + (1 - ran)... | the_stack_v2_python_sparse | data/dataset.py | System-SW/SketchColorization | train | 3 |
c902d62a7dfe7a5c47f97e34258ecdb136882ce5 | [
"self.curr_round = 0\npayload = {'is_handshake': True}\nlst_replies = self.query_all_parties(payload)\nglobal_counts = self.global_reweighing(lst_replies)\npayload = {'global_weights': True, 'global_counts': global_counts}\nlst_replies = self.query_all_parties(payload)\nwhile not self.reach_termination_criteria(sel... | <|body_start_0|>
self.curr_round = 0
payload = {'is_handshake': True}
lst_replies = self.query_all_parties(payload)
global_counts = self.global_reweighing(lst_replies)
payload = {'global_weights': True, 'global_counts': global_counts}
lst_replies = self.query_all_parties(... | Class for iterative averaging based fusion algorithms. An iterative fusion algorithm here referred to a fusion algorithm that sends out queries at each global round to registered parties for information, and use the collected information from parties to update the global model. The type of queries sent out at each roun... | ReweighFusionHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReweighFusionHandler:
"""Class for iterative averaging based fusion algorithms. An iterative fusion algorithm here referred to a fusion algorithm that sends out queries at each global round to registered parties for information, and use the collected information from parties to update the global ... | stack_v2_sparse_classes_75kplus_train_005756 | 4,100 | permissive | [
{
"docstring": "Starts an iterative global federated learning training process.",
"name": "start_global_training",
"signature": "def start_global_training(self)"
},
{
"docstring": ":param lst_replies: party response with local DP counts for weight calculation :type lst_replies: `dict` :return: g... | 2 | stack_v2_sparse_classes_30k_train_010525 | Implement the Python class `ReweighFusionHandler` described below.
Class description:
Class for iterative averaging based fusion algorithms. An iterative fusion algorithm here referred to a fusion algorithm that sends out queries at each global round to registered parties for information, and use the collected informa... | Implement the Python class `ReweighFusionHandler` described below.
Class description:
Class for iterative averaging based fusion algorithms. An iterative fusion algorithm here referred to a fusion algorithm that sends out queries at each global round to registered parties for information, and use the collected informa... | 64ffa2ee2e906b1bd6b3dd6aabcf6fc3de862608 | <|skeleton|>
class ReweighFusionHandler:
"""Class for iterative averaging based fusion algorithms. An iterative fusion algorithm here referred to a fusion algorithm that sends out queries at each global round to registered parties for information, and use the collected information from parties to update the global ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReweighFusionHandler:
"""Class for iterative averaging based fusion algorithms. An iterative fusion algorithm here referred to a fusion algorithm that sends out queries at each global round to registered parties for information, and use the collected information from parties to update the global model. The ty... | the_stack_v2_python_sparse | debugging-constructs/ibmfl/aggregator/fusion/reweigh_fusion_handler.py | SEED-VT/FedDebug | train | 8 |
816b1945f37628be0ff9e92dc52a970ad6ce9c3f | [
"super().__init__(**kwargs)\nself.func = func\nself.args = args or {}",
"response = self.func(**self.args)\nif response.status_code > 0 and self.skippable:\n response.warning = True\n response.status_code = 0\nreturn response"
] | <|body_start_0|>
super().__init__(**kwargs)
self.func = func
self.args = args or {}
<|end_body_0|>
<|body_start_1|>
response = self.func(**self.args)
if response.status_code > 0 and self.skippable:
response.warning = True
response.status_code = 0
... | A step which execution is a function call. Is composed of a function, arguments, and a message (feedback). | FunctionStep | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FunctionStep:
"""A step which execution is a function call. Is composed of a function, arguments, and a message (feedback)."""
def __init__(self, func, args=None, **kwargs):
"""Constructor."""
<|body_0|>
def execute(self):
"""Execute the function with the given a... | stack_v2_sparse_classes_75kplus_train_005757 | 1,815 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, func, args=None, **kwargs)"
},
{
"docstring": "Execute the function with the given arguments.",
"name": "execute",
"signature": "def execute(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_022207 | Implement the Python class `FunctionStep` described below.
Class description:
A step which execution is a function call. Is composed of a function, arguments, and a message (feedback).
Method signatures and docstrings:
- def __init__(self, func, args=None, **kwargs): Constructor.
- def execute(self): Execute the func... | Implement the Python class `FunctionStep` described below.
Class description:
A step which execution is a function call. Is composed of a function, arguments, and a message (feedback).
Method signatures and docstrings:
- def __init__(self, func, args=None, **kwargs): Constructor.
- def execute(self): Execute the func... | 40573024e8ad81430afdda8fc8ceb2acbd55d7d2 | <|skeleton|>
class FunctionStep:
"""A step which execution is a function call. Is composed of a function, arguments, and a message (feedback)."""
def __init__(self, func, args=None, **kwargs):
"""Constructor."""
<|body_0|>
def execute(self):
"""Execute the function with the given a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FunctionStep:
"""A step which execution is a function call. Is composed of a function, arguments, and a message (feedback)."""
def __init__(self, func, args=None, **kwargs):
"""Constructor."""
super().__init__(**kwargs)
self.func = func
self.args = args or {}
def exec... | the_stack_v2_python_sparse | invenio_cli/commands/steps.py | inveniosoftware/invenio-cli | train | 8 |
37c342d36518244734081d7c19461129521fb5f9 | [
"self.metrics = Metrics()\nself.n = len(initial)\nself.size = pow(self.n, 2)\nself.goal = goal\nif self.n == 4:\n self.subsquare_dimensions = (2, 2)\nelif self.n == 6:\n self.subsquare_dimensions = (2, 3)\nelif self.n == 9:\n self.subsquare_dimensions = (3, 3)\nelse:\n print('Problem dimensions are not ... | <|body_start_0|>
self.metrics = Metrics()
self.n = len(initial)
self.size = pow(self.n, 2)
self.goal = goal
if self.n == 4:
self.subsquare_dimensions = (2, 2)
elif self.n == 6:
self.subsquare_dimensions = (2, 3)
elif self.n == 9:
... | This is where the problem is defined. Initial state, goal state and refactorme information that can be got from the problem | Problem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Problem:
"""This is where the problem is defined. Initial state, goal state and refactorme information that can be got from the problem"""
def __init__(self, initial, goal=None):
"""This is the constructor for the Problem class. It specifies the initial state, and possibly a goal sta... | stack_v2_sparse_classes_75kplus_train_005758 | 7,675 | no_license | [
{
"docstring": "This is the constructor for the Problem class. It specifies the initial state, and possibly a goal state, if there is a unique goal. You can add refactorme arguments if the need arises",
"name": "__init__",
"signature": "def __init__(self, initial, goal=None)"
},
{
"docstring": "... | 6 | null | Implement the Python class `Problem` described below.
Class description:
This is where the problem is defined. Initial state, goal state and refactorme information that can be got from the problem
Method signatures and docstrings:
- def __init__(self, initial, goal=None): This is the constructor for the Problem class... | Implement the Python class `Problem` described below.
Class description:
This is where the problem is defined. Initial state, goal state and refactorme information that can be got from the problem
Method signatures and docstrings:
- def __init__(self, initial, goal=None): This is the constructor for the Problem class... | 743313ac216e60661b2c036e8ec8b04f3e372928 | <|skeleton|>
class Problem:
"""This is where the problem is defined. Initial state, goal state and refactorme information that can be got from the problem"""
def __init__(self, initial, goal=None):
"""This is the constructor for the Problem class. It specifies the initial state, and possibly a goal sta... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Problem:
"""This is where the problem is defined. Initial state, goal state and refactorme information that can be got from the problem"""
def __init__(self, initial, goal=None):
"""This is the constructor for the Problem class. It specifies the initial state, and possibly a goal state, if there ... | the_stack_v2_python_sparse | sudoku/sudoku.py | ACSchil/PyAI | train | 0 |
9c46cf0764a787303feeabd2eb0cdeb535563b84 | [
"self.clusterXData = None\nself.clusterYData = None\nself.clusterZData = None\nif not clusterX and (not clusterY) and (not clusterZ):\n return\nif not clusterX or not clusterY or (not clusterZ):\n raise UserInputError('You must specify 3 valid clusters!')\nself.clusterXData = clusterData.ClusterData(clusterX)... | <|body_start_0|>
self.clusterXData = None
self.clusterYData = None
self.clusterZData = None
if not clusterX and (not clusterY) and (not clusterZ):
return
if not clusterX or not clusterY or (not clusterZ):
raise UserInputError('You must specify 3 valid clus... | ClusterBlendData class object. Contains functions to save, load and rebuild clusterBlend data. | ClusterBlendData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusterBlendData:
"""ClusterBlendData class object. Contains functions to save, load and rebuild clusterBlend data."""
def __init__(self, clusterX='', clusterY='', clusterZ=''):
"""ClusterBlendData class initializer."""
<|body_0|>
def rebuild(self):
"""Rebuild cl... | stack_v2_sparse_classes_75kplus_train_005759 | 1,519 | no_license | [
{
"docstring": "ClusterBlendData class initializer.",
"name": "__init__",
"signature": "def __init__(self, clusterX='', clusterY='', clusterZ='')"
},
{
"docstring": "Rebuild clusterBlend from object data.",
"name": "rebuild",
"signature": "def rebuild(self)"
},
{
"docstring": "Lo... | 3 | stack_v2_sparse_classes_30k_train_027628 | Implement the Python class `ClusterBlendData` described below.
Class description:
ClusterBlendData class object. Contains functions to save, load and rebuild clusterBlend data.
Method signatures and docstrings:
- def __init__(self, clusterX='', clusterY='', clusterZ=''): ClusterBlendData class initializer.
- def rebu... | Implement the Python class `ClusterBlendData` described below.
Class description:
ClusterBlendData class object. Contains functions to save, load and rebuild clusterBlend data.
Method signatures and docstrings:
- def __init__(self, clusterX='', clusterY='', clusterZ=''): ClusterBlendData class initializer.
- def rebu... | 16337badb6d1b4266f31008ceb17cfd70fec3623 | <|skeleton|>
class ClusterBlendData:
"""ClusterBlendData class object. Contains functions to save, load and rebuild clusterBlend data."""
def __init__(self, clusterX='', clusterY='', clusterZ=''):
"""ClusterBlendData class initializer."""
<|body_0|>
def rebuild(self):
"""Rebuild cl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ClusterBlendData:
"""ClusterBlendData class object. Contains functions to save, load and rebuild clusterBlend data."""
def __init__(self, clusterX='', clusterY='', clusterZ=''):
"""ClusterBlendData class initializer."""
self.clusterXData = None
self.clusterYData = None
sel... | the_stack_v2_python_sparse | glTools-master/data/clusterBlendData.py | moChen0607/pubTool | train | 0 |
e31cb6bf40ce9becb02f2ca0d14eadfd1f69b865 | [
"nums.sort()\nres = []\nfor i in xrange(len(nums) - 2):\n if i == 0 or nums[i] > nums[i - 1]:\n target = -nums[i]\n b, e = (i + 1, len(nums) - 1)\n while b < e:\n if nums[b] + nums[e] == target:\n res.append([nums[i], nums[b], nums[e]])\n b += 1\n ... | <|body_start_0|>
nums.sort()
res = []
for i in xrange(len(nums) - 2):
if i == 0 or nums[i] > nums[i - 1]:
target = -nums[i]
b, e = (i + 1, len(nums) - 1)
while b < e:
if nums[b] + nums[e] == target:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def threeSum2(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
nums.sort()
res = ... | stack_v2_sparse_classes_75kplus_train_005760 | 1,871 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum",
"signature": "def threeSum(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum2",
"signature": "def threeSum2(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def threeSum2(self, nums): :type nums: List[int] :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def threeSum2(self, nums): :type nums: List[int] :rtype: List[List[int]]
<|skeleton|>
class Solution:
... | 31b2b4dc1e5c3b1c53b333fe30b98ed04b0bdacc | <|skeleton|>
class Solution:
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def threeSum2(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
nums.sort()
res = []
for i in xrange(len(nums) - 2):
if i == 0 or nums[i] > nums[i - 1]:
target = -nums[i]
b, e = (i + 1, len(nums) - 1)
... | the_stack_v2_python_sparse | prob015_3Sum.py | Hu-Wenchao/leetcode | train | 0 | |
30c1dbeaa8885cb28c3936e8715c8739e5a14698 | [
"if self.context.get('view').action == 'create':\n if not re.match('^1[3-9]\\\\d{9}$', value):\n raise serializers.ValidationError('手机号格式不正确')\n count = User.objects.filter(mobile=value).count()\n if count > 0:\n raise serializers.ValidationError('手机号已经注册,请务重复注册')\nelif self.context.get('view... | <|body_start_0|>
if self.context.get('view').action == 'create':
if not re.match('^1[3-9]\\d{9}$', value):
raise serializers.ValidationError('手机号格式不正确')
count = User.objects.filter(mobile=value).count()
if count > 0:
raise serializers.Validatio... | 管理员用户列表序列化器类 | PermsAdminsSerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PermsAdminsSerializer:
"""管理员用户列表序列化器类"""
def validate_mobile(self, value):
"""校验手机号格式"""
<|body_0|>
def validate_username(self, value):
"""如果是更新数据, 用户名不用判断重复"""
<|body_1|>
def create(self, validated_data):
"""密码要加密保存"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus_train_005761 | 3,778 | permissive | [
{
"docstring": "校验手机号格式",
"name": "validate_mobile",
"signature": "def validate_mobile(self, value)"
},
{
"docstring": "如果是更新数据, 用户名不用判断重复",
"name": "validate_username",
"signature": "def validate_username(self, value)"
},
{
"docstring": "密码要加密保存",
"name": "create",
"sign... | 4 | stack_v2_sparse_classes_30k_train_043329 | Implement the Python class `PermsAdminsSerializer` described below.
Class description:
管理员用户列表序列化器类
Method signatures and docstrings:
- def validate_mobile(self, value): 校验手机号格式
- def validate_username(self, value): 如果是更新数据, 用户名不用判断重复
- def create(self, validated_data): 密码要加密保存
- def update(self, instance, validated_... | Implement the Python class `PermsAdminsSerializer` described below.
Class description:
管理员用户列表序列化器类
Method signatures and docstrings:
- def validate_mobile(self, value): 校验手机号格式
- def validate_username(self, value): 如果是更新数据, 用户名不用判断重复
- def create(self, validated_data): 密码要加密保存
- def update(self, instance, validated_... | d3ce2185ec3c68325e8becddce07d0a9da144325 | <|skeleton|>
class PermsAdminsSerializer:
"""管理员用户列表序列化器类"""
def validate_mobile(self, value):
"""校验手机号格式"""
<|body_0|>
def validate_username(self, value):
"""如果是更新数据, 用户名不用判断重复"""
<|body_1|>
def create(self, validated_data):
"""密码要加密保存"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PermsAdminsSerializer:
"""管理员用户列表序列化器类"""
def validate_mobile(self, value):
"""校验手机号格式"""
if self.context.get('view').action == 'create':
if not re.match('^1[3-9]\\d{9}$', value):
raise serializers.ValidationError('手机号格式不正确')
count = User.objects.fi... | the_stack_v2_python_sparse | meiduo_mall/meiduo_mall/apps/meiduo_admin/serializers/permissions.py | qls7/dianshanghoutai | train | 0 |
ae36c0c8ee5f9ee6c9d882cb856bf9f71e940051 | [
"Inventory.__init__(self, inventory_item.product_code, inventory_item.description, inventory_item.market_price, inventory_item.rental_price)\nself.brand = brand\nself.voltage = voltage",
"output_dict = {}\noutput_dict['product_code'] = self.product_code\noutput_dict['description'] = self.description\noutput_dict[... | <|body_start_0|>
Inventory.__init__(self, inventory_item.product_code, inventory_item.description, inventory_item.market_price, inventory_item.rental_price)
self.brand = brand
self.voltage = voltage
<|end_body_0|>
<|body_start_1|>
output_dict = {}
output_dict['product_code'] = s... | electrical appliance class | ElecAppliances | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElecAppliances:
"""electrical appliance class"""
def __init__(self, inventory_item, brand, voltage):
"""initializes electrical appliance item"""
<|body_0|>
def return_as_dictionary(self):
"""returns electrical appliances as a dictionary"""
<|body_1|>
<|e... | stack_v2_sparse_classes_75kplus_train_005762 | 1,047 | no_license | [
{
"docstring": "initializes electrical appliance item",
"name": "__init__",
"signature": "def __init__(self, inventory_item, brand, voltage)"
},
{
"docstring": "returns electrical appliances as a dictionary",
"name": "return_as_dictionary",
"signature": "def return_as_dictionary(self)"
... | 2 | stack_v2_sparse_classes_30k_val_002006 | Implement the Python class `ElecAppliances` described below.
Class description:
electrical appliance class
Method signatures and docstrings:
- def __init__(self, inventory_item, brand, voltage): initializes electrical appliance item
- def return_as_dictionary(self): returns electrical appliances as a dictionary | Implement the Python class `ElecAppliances` described below.
Class description:
electrical appliance class
Method signatures and docstrings:
- def __init__(self, inventory_item, brand, voltage): initializes electrical appliance item
- def return_as_dictionary(self): returns electrical appliances as a dictionary
<|sk... | 99271cd60485bd2e54f8d133c9057a2ccd6c91c2 | <|skeleton|>
class ElecAppliances:
"""electrical appliance class"""
def __init__(self, inventory_item, brand, voltage):
"""initializes electrical appliance item"""
<|body_0|>
def return_as_dictionary(self):
"""returns electrical appliances as a dictionary"""
<|body_1|>
<|e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ElecAppliances:
"""electrical appliance class"""
def __init__(self, inventory_item, brand, voltage):
"""initializes electrical appliance item"""
Inventory.__init__(self, inventory_item.product_code, inventory_item.description, inventory_item.market_price, inventory_item.rental_price)
... | the_stack_v2_python_sparse | students/ZackConnaughton/lesson01/assignment/inventory_management/elec_appliances_class.py | zconn/PythonCert220Assign | train | 2 |
053fc0a105d269fb6af68df8167b248347ece6e2 | [
"dev = self.selectedDevice(c)\ndiodeMonitorReturnString = (yield dev.query('TVAL? 0'))\ntemperatures = [float(x) * units.K for x in diodeMonitorReturnString.strip('\\x00').split(',')][:2]\nreturnValue(temperatures)",
"dev = self.selectedDevice(c)\ndev.write('*CLS')\ndiodeMonitorReturnString = (yield dev.query('VO... | <|body_start_0|>
dev = self.selectedDevice(c)
diodeMonitorReturnString = (yield dev.query('TVAL? 0'))
temperatures = [float(x) * units.K for x in diodeMonitorReturnString.strip('\x00').split(',')][:2]
returnValue(temperatures)
<|end_body_0|>
<|body_start_1|>
dev = self.selectedD... | Provides basic control for SRS SIM922 Diode Temperature Monitor Module | SIM922Server | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SIM922Server:
"""Provides basic control for SRS SIM922 Diode Temperature Monitor Module"""
def getDiodeTemperatures(self, c):
"""Get the temperatures of the Si Diode Thermometers connected to the first two slots of the SIM922."""
<|body_0|>
def getMagnetVoltage(self, c):... | stack_v2_sparse_classes_75kplus_train_005763 | 2,599 | no_license | [
{
"docstring": "Get the temperatures of the Si Diode Thermometers connected to the first two slots of the SIM922.",
"name": "getDiodeTemperatures",
"signature": "def getDiodeTemperatures(self, c)"
},
{
"docstring": "Get the voltage across the magnet. Two values are measured (third and fourth slo... | 2 | stack_v2_sparse_classes_30k_train_018587 | Implement the Python class `SIM922Server` described below.
Class description:
Provides basic control for SRS SIM922 Diode Temperature Monitor Module
Method signatures and docstrings:
- def getDiodeTemperatures(self, c): Get the temperatures of the Si Diode Thermometers connected to the first two slots of the SIM922.
... | Implement the Python class `SIM922Server` described below.
Class description:
Provides basic control for SRS SIM922 Diode Temperature Monitor Module
Method signatures and docstrings:
- def getDiodeTemperatures(self, c): Get the temperatures of the Si Diode Thermometers connected to the first two slots of the SIM922.
... | 6f041503ff9967e7ed52cfb619d9cc21d66b5ad6 | <|skeleton|>
class SIM922Server:
"""Provides basic control for SRS SIM922 Diode Temperature Monitor Module"""
def getDiodeTemperatures(self, c):
"""Get the temperatures of the Si Diode Thermometers connected to the first two slots of the SIM922."""
<|body_0|>
def getMagnetVoltage(self, c):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SIM922Server:
"""Provides basic control for SRS SIM922 Diode Temperature Monitor Module"""
def getDiodeTemperatures(self, c):
"""Get the temperatures of the Si Diode Thermometers connected to the first two slots of the SIM922."""
dev = self.selectedDevice(c)
diodeMonitorReturnStri... | the_stack_v2_python_sparse | instruments/gpibdevices/sim/sim_922_diode_temp_monitor.py | McDermott-Group/servers | train | 0 |
f021392b3d09c222de179a3146d0a324525ec536 | [
"for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n x = nums[i]\n y = nums[j]\n if x + y == target:\n return [i, j]",
"mapDic = {}\ni = 0\nfor num in nums:\n complement = target - num\n if complement in mapDic:\n return [i, mapDic.get(complement)]\n ... | <|body_start_0|>
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
x = nums[i]
y = nums[j]
if x + y == target:
return [i, j]
<|end_body_0|>
<|body_start_1|>
mapDic = {}
i = 0
for num in nums:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum2(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_75kplus_train_005764 | 2,140 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum",
"signature": "def twoSum(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum2",
"signature": "def twoSum2(self, nums, target)"
}... | 2 | stack_v2_sparse_classes_30k_train_018250 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum2(self, nums, target): :type nums: List[int] :type target: int :rtype: List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum2(self, nums, target): :type nums: List[int] :type target: int :rtype: List[... | a2ae0f1f26980fffef90b058cad8cccee705bf56 | <|skeleton|>
class Solution:
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum2(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
x = nums[i]
y = nums[j]
if x + y == target:
ret... | the_stack_v2_python_sparse | solution1.py | qingfengwuhen/Leetcode | train | 0 | |
8b2bade49ba15ba7b9d50694e6902ef9a720e6f6 | [
"if not email:\n raise ValueError(_(\"L'addresse mail est obligatoire\"))\nemail = self.normalize_email(email)\nuser = self.model(email=email, nom=nom, prenom=prenom)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(email, password=password, nom=nom, prenom=prenom... | <|body_start_0|>
if not email:
raise ValueError(_("L'addresse mail est obligatoire"))
email = self.normalize_email(email)
user = self.model(email=email, nom=nom, prenom=prenom)
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
<... | Base manager for creating users | MyUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyUserManager:
"""Base manager for creating users"""
def create_user(self, email, nom=None, prenom=None, username=None, password=None):
"""Create a basic user for your application."""
<|body_0|>
def create_superuser(self, email, password, nom=None, prenom=None):
... | stack_v2_sparse_classes_75kplus_train_005765 | 1,717 | no_license | [
{
"docstring": "Create a basic user for your application.",
"name": "create_user",
"signature": "def create_user(self, email, nom=None, prenom=None, username=None, password=None)"
},
{
"docstring": "Create a superuser of type administrator",
"name": "create_superuser",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_002850 | Implement the Python class `MyUserManager` described below.
Class description:
Base manager for creating users
Method signatures and docstrings:
- def create_user(self, email, nom=None, prenom=None, username=None, password=None): Create a basic user for your application.
- def create_superuser(self, email, password, ... | Implement the Python class `MyUserManager` described below.
Class description:
Base manager for creating users
Method signatures and docstrings:
- def create_user(self, email, nom=None, prenom=None, username=None, password=None): Create a basic user for your application.
- def create_superuser(self, email, password, ... | 5f46057eaa03973f8abe4435b23043ad914f98b8 | <|skeleton|>
class MyUserManager:
"""Base manager for creating users"""
def create_user(self, email, nom=None, prenom=None, username=None, password=None):
"""Create a basic user for your application."""
<|body_0|>
def create_superuser(self, email, password, nom=None, prenom=None):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyUserManager:
"""Base manager for creating users"""
def create_user(self, email, nom=None, prenom=None, username=None, password=None):
"""Create a basic user for your application."""
if not email:
raise ValueError(_("L'addresse mail est obligatoire"))
email = self.nor... | the_stack_v2_python_sparse | kendall/accounts/managers.py | Zadigo/test_accounts | train | 0 |
6791d2d7657c61976ca9a0de652d66b183288b48 | [
"\"\"\"\n 最长回文子串\n \"\"\"\nif len(s) <= 0:\n return ''\nmax_seq = s[0]\nfor i in range(len(s)):\n sub_str = s[i:]\n for j in range(len(sub_str) - 1, -1, -1):\n if self.isPalindrome(sub_str[:j + 1]):\n if len(max_seq) < len(sub_str[:j + 1]):\n max_seq = sub_str... | <|body_start_0|>
"""
最长回文子串
"""
if len(s) <= 0:
return ''
max_seq = s[0]
for i in range(len(s)):
sub_str = s[i:]
for j in range(len(sub_str) - 1, -1, -1):
if self.isPalindrome(sub_str[:j + 1]):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def longestPalindrome_dp(self, s):
""":type s: str :rtype: str"""
<|body_1|>
def longestPalindrome_simple(self, s):
"""以每个字符,或者是字符的间隙作为中间字符像左右扩展找最长回文子串 :param s: ... | stack_v2_sparse_classes_75kplus_train_005766 | 5,129 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "longestPalindrome_dp",
"signature": "def longestPalindrome_dp(self, s)"
},
{
"docstring": "以每个字符,或者是字符的间隙作为... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): :type s: str :rtype: str
- def longestPalindrome_dp(self, s): :type s: str :rtype: str
- def longestPalindrome_simple(self, s): 以每个字符,或者是字符的间隙作为中间... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): :type s: str :rtype: str
- def longestPalindrome_dp(self, s): :type s: str :rtype: str
- def longestPalindrome_simple(self, s): 以每个字符,或者是字符的间隙作为中间... | 09b7121628df824f432b8cdd25c55f045b013c0b | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def longestPalindrome_dp(self, s):
""":type s: str :rtype: str"""
<|body_1|>
def longestPalindrome_simple(self, s):
"""以每个字符,或者是字符的间隙作为中间字符像左右扩展找最长回文子串 :param s: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
"""
最长回文子串
"""
if len(s) <= 0:
return ''
max_seq = s[0]
for i in range(len(s)):
sub_str = s[i:]
for j in range(len(sub_str) - 1, ... | the_stack_v2_python_sparse | str_5.py | cainingning/leetcode | train | 1 | |
1812b167fb3dd6787f6aae6da7552187a614b230 | [
"def calc(tot):\n return (ListNode(tot - 10 * int(tot > 9)), int(tot > 9))\ncarry = 0\ncur = head = ListNode(0)\nwhile l1 and l2:\n cur.next, carry = calc(l1.val + l2.val + carry)\n l1, l2, cur = (l1.next, l2.next, cur.next)\nl3 = l1 if l1 else l2\nwhile l3:\n cur.next, carry = calc(l3.val + carry)\n ... | <|body_start_0|>
def calc(tot):
return (ListNode(tot - 10 * int(tot > 9)), int(tot > 9))
carry = 0
cur = head = ListNode(0)
while l1 and l2:
cur.next, carry = calc(l1.val + l2.val + carry)
l1, l2, cur = (l1.next, l2.next, cur.next)
l3 = l1 if l... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def addTwoNumbers(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def addTwoNumbers2(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_005767 | 1,571 | no_license | [
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "addTwoNumbers",
"signature": "def addTwoNumbers(self, l1, l2)"
},
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "addTwoNumbers2",
"signature": "def addTwoNumbers2(self, l1... | 2 | stack_v2_sparse_classes_30k_train_015333 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addTwoNumbers(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def addTwoNumbers2(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addTwoNumbers(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def addTwoNumbers2(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode... | 057ed5c6fe19268f36a1d5051d27b07aae0b63e0 | <|skeleton|>
class Solution:
def addTwoNumbers(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def addTwoNumbers2(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def addTwoNumbers(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
def calc(tot):
return (ListNode(tot - 10 * int(tot > 9)), int(tot > 9))
carry = 0
cur = head = ListNode(0)
while l1 and l2:
cur.next, carry = ... | the_stack_v2_python_sparse | 2020/2020-02/26/eugene.py | wavetogether/wave_algorithm_challenge | train | 3 | |
ccf4ef00a6cccc72e1abb927adc3580fdba2ffd0 | [
"self.mode = mode\nself.pixelwise = pixelwise\nself.filternan = filternan\nif self.pixelwise and self.mode == 'total':\n raise ValueError('Total mode does not support pixelwise=True.')\nself.in_feature = self.parse_features(in_feature, allowed_feature_types=partial(_is_input_ftype, mode=mode))\nself.out_feature ... | <|body_start_0|>
self.mode = mode
self.pixelwise = pixelwise
self.filternan = filternan
if self.pixelwise and self.mode == 'total':
raise ValueError('Total mode does not support pixelwise=True.')
self.in_feature = self.parse_features(in_feature, allowed_feature_types=... | An EOTask to compute the T-Digest representation of a chosen feature of an EOPatch. It integrates the [T-Digest algorithm by Ted Dunning](https://arxiv.org/abs/1902.04023) to efficiently compute quantiles of the underlying dataset into eo-learn. The output features of the tasks may be merged to compute a representation... | TDigestTask | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TDigestTask:
"""An EOTask to compute the T-Digest representation of a chosen feature of an EOPatch. It integrates the [T-Digest algorithm by Ted Dunning](https://arxiv.org/abs/1902.04023) to efficiently compute quantiles of the underlying dataset into eo-learn. The output features of the tasks ma... | stack_v2_sparse_classes_75kplus_train_005768 | 8,070 | permissive | [
{
"docstring": ":param in_feature: The input feature to compute the T-Digest representation for. :param out_feature: The output feature where to save the T-Digest representation of the chosen feature. :param mode: The mode to apply to the timestamps and bands. * `'standard'` computes the T-Digest representation... | 2 | null | Implement the Python class `TDigestTask` described below.
Class description:
An EOTask to compute the T-Digest representation of a chosen feature of an EOPatch. It integrates the [T-Digest algorithm by Ted Dunning](https://arxiv.org/abs/1902.04023) to efficiently compute quantiles of the underlying dataset into eo-lea... | Implement the Python class `TDigestTask` described below.
Class description:
An EOTask to compute the T-Digest representation of a chosen feature of an EOPatch. It integrates the [T-Digest algorithm by Ted Dunning](https://arxiv.org/abs/1902.04023) to efficiently compute quantiles of the underlying dataset into eo-lea... | a65899e4632b50c9c41a67e1f7698c09b929d840 | <|skeleton|>
class TDigestTask:
"""An EOTask to compute the T-Digest representation of a chosen feature of an EOPatch. It integrates the [T-Digest algorithm by Ted Dunning](https://arxiv.org/abs/1902.04023) to efficiently compute quantiles of the underlying dataset into eo-learn. The output features of the tasks ma... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TDigestTask:
"""An EOTask to compute the T-Digest representation of a chosen feature of an EOPatch. It integrates the [T-Digest algorithm by Ted Dunning](https://arxiv.org/abs/1902.04023) to efficiently compute quantiles of the underlying dataset into eo-learn. The output features of the tasks may be merged t... | the_stack_v2_python_sparse | ml_tools/eolearn/ml_tools/tdigest.py | sentinel-hub/eo-learn | train | 1,072 |
eec40690493c50fdfd555a606cb1d6583b76c280 | [
"self.parent = parent\nself.default_page = 0\n'Default for current page'\nself.default_page_size = 100\n'Default page size'\nself.allowed_page_sizes = (100, 200, 500)\n'Default list of allowed page sizes'",
"pg = self.parent.fetch_int('pg', default=self.default_page, required=False, multiple=False)\nif pg < 0:\n ... | <|body_start_0|>
self.parent = parent
self.default_page = 0
'Default for current page'
self.default_page_size = 100
'Default page size'
self.allowed_page_sizes = (100, 200, 500)
'Default list of allowed page sizes'
<|end_body_0|>
<|body_start_1|>
pg = sel... | PagerValidator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PagerValidator:
def __init__(self, parent):
"""Validator for parameters of a pager. We tell which page is the current page and the page size (e.g. in rows). Hence the input MultiDict is expected to have keys ``pg`` and ``ps``. *Public properties* ``default_page``: Page number to use as d... | stack_v2_sparse_classes_75kplus_train_005769 | 19,666 | no_license | [
{
"docstring": "Validator for parameters of a pager. We tell which page is the current page and the page size (e.g. in rows). Hence the input MultiDict is expected to have keys ``pg`` and ``ps``. *Public properties* ``default_page``: Page number to use as default. ``default_page_size``: Page size to use as defa... | 3 | stack_v2_sparse_classes_30k_train_044098 | Implement the Python class `PagerValidator` described below.
Class description:
Implement the PagerValidator class.
Method signatures and docstrings:
- def __init__(self, parent): Validator for parameters of a pager. We tell which page is the current page and the page size (e.g. in rows). Hence the input MultiDict is... | Implement the Python class `PagerValidator` described below.
Class description:
Implement the PagerValidator class.
Method signatures and docstrings:
- def __init__(self, parent): Validator for parameters of a pager. We tell which page is the current page and the page size (e.g. in rows). Hence the input MultiDict is... | 63864cdaff76b9aa1b8dbe795eb537b5be5add3a | <|skeleton|>
class PagerValidator:
def __init__(self, parent):
"""Validator for parameters of a pager. We tell which page is the current page and the page size (e.g. in rows). Hence the input MultiDict is expected to have keys ``pg`` and ``ps``. *Public properties* ``default_page``: Page number to use as d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PagerValidator:
def __init__(self, parent):
"""Validator for parameters of a pager. We tell which page is the current page and the page size (e.g. in rows). Hence the input MultiDict is expected to have keys ``pg`` and ``ps``. *Public properties* ``default_page``: Page number to use as default. ``defa... | the_stack_v2_python_sparse | pym/validator.py | dmdm/Parenchym | train | 0 | |
e0f3c963db63487c2b31c08017b1dc714fd35ff3 | [
"try:\n sym = table.lookup(cls._builtin_name)\n if type(sym) is Symbol:\n if not sym.is_unresolved:\n raise InternalError(f\"A symbol with the same name as builtin '{sym.name}' exists but has an interface of '{sym.interface}' instead of being unresolved.\")\n sym.specialise(DataTypeSy... | <|body_start_0|>
try:
sym = table.lookup(cls._builtin_name)
if type(sym) is Symbol:
if not sym.is_unresolved:
raise InternalError(f"A symbol with the same name as builtin '{sym.name}' exists but has an interface of '{sym.interface}' instead of being un... | Base class which all LFRic builtins subclass. Contains a builtin call, a description of its required interface and the arguments to be passed to it. | LFRicBuiltinFunctor | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LFRicBuiltinFunctor:
"""Base class which all LFRic builtins subclass. Contains a builtin call, a description of its required interface and the arguments to be passed to it."""
def create(cls, table, arguments):
"""An appropriate DataTypeSymbol is created and added to the supplied sym... | stack_v2_sparse_classes_75kplus_train_005770 | 8,947 | permissive | [
{
"docstring": "An appropriate DataTypeSymbol is created and added to the supplied symbol table (if it does not already contain one). This is then passed to the create() method in the base class to create an instance of an LFRic builtin call with the supplied list of arguments. :param table: the symbol table to... | 2 | stack_v2_sparse_classes_30k_train_005055 | Implement the Python class `LFRicBuiltinFunctor` described below.
Class description:
Base class which all LFRic builtins subclass. Contains a builtin call, a description of its required interface and the arguments to be passed to it.
Method signatures and docstrings:
- def create(cls, table, arguments): An appropriat... | Implement the Python class `LFRicBuiltinFunctor` described below.
Class description:
Base class which all LFRic builtins subclass. Contains a builtin call, a description of its required interface and the arguments to be passed to it.
Method signatures and docstrings:
- def create(cls, table, arguments): An appropriat... | 0b149bc5a76ca85c1dd086c3aa813102d0d04b56 | <|skeleton|>
class LFRicBuiltinFunctor:
"""Base class which all LFRic builtins subclass. Contains a builtin call, a description of its required interface and the arguments to be passed to it."""
def create(cls, table, arguments):
"""An appropriate DataTypeSymbol is created and added to the supplied sym... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LFRicBuiltinFunctor:
"""Base class which all LFRic builtins subclass. Contains a builtin call, a description of its required interface and the arguments to be passed to it."""
def create(cls, table, arguments):
"""An appropriate DataTypeSymbol is created and added to the supplied symbol table (if... | the_stack_v2_python_sparse | src/psyclone/domain/lfric/algorithm/psyir/lfric_kernel_functor.py | stfc/PSyclone | train | 100 |
0467959ed285c0e2fba78b57a9a690185cbf87ea | [
"list_tuple = []\nfor user in LoopUser.objects.all().order_by('name_en'):\n list_tuple.append((user.user_id, user.name_en + '-' + str(user.phone_number) + ' (' + str(user.user_id) + ')'))\nreturn list_tuple",
"if self.value():\n return queryset.filter(user_created__id=self.value())\nelse:\n return querys... | <|body_start_0|>
list_tuple = []
for user in LoopUser.objects.all().order_by('name_en'):
list_tuple.append((user.user_id, user.name_en + '-' + str(user.phone_number) + ' (' + str(user.user_id) + ')'))
return list_tuple
<|end_body_0|>
<|body_start_1|>
if self.value():
... | UserListFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserListFilter:
def lookups(self, request, model_admin):
"""Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar.""... | stack_v2_sparse_classes_75kplus_train_005771 | 25,233 | no_license | [
{
"docstring": "Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar.",
"name": "lookups",
"signature": "def lookups(self, request,... | 2 | stack_v2_sparse_classes_30k_train_002374 | Implement the Python class `UserListFilter` described below.
Class description:
Implement the UserListFilter class.
Method signatures and docstrings:
- def lookups(self, request, model_admin): Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query... | Implement the Python class `UserListFilter` described below.
Class description:
Implement the UserListFilter class.
Method signatures and docstrings:
- def lookups(self, request, model_admin): Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query... | 0b5a62bc34158a8223f166910e349b730475f99d | <|skeleton|>
class UserListFilter:
def lookups(self, request, model_admin):
"""Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar.""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserListFilter:
def lookups(self, request, model_admin):
"""Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar."""
list... | the_stack_v2_python_sparse | loop/admin.py | digitalgreenorg/dg | train | 14 | |
6772e171a7a20ecd82bf07df82fc17d3ce89ddb5 | [
"if 'primary' in validated_data:\n iprimary = instance.primary\n vprimary = validated_data['primary']\n if iprimary != vprimary:\n if iprimary and (not vprimary):\n raise PermissionDenied(\"Can't set 'primary' to False, do it by setting another email address to primary\")\n instanc... | <|body_start_0|>
if 'primary' in validated_data:
iprimary = instance.primary
vprimary = validated_data['primary']
if iprimary != vprimary:
if iprimary and (not vprimary):
raise PermissionDenied("Can't set 'primary' to False, do it by settin... | EmailAddressSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailAddressSerializer:
def update(self, instance, validated_data):
"""Prevent setting 'primary' to false, and invalidate 'verified' if the address changes."""
<|body_0|>
def create(self, validated_data, **kwargs):
"""Prevent setting 'primary' to true if there is alr... | stack_v2_sparse_classes_75kplus_train_005772 | 12,950 | no_license | [
{
"docstring": "Prevent setting 'primary' to false, and invalidate 'verified' if the address changes.",
"name": "update",
"signature": "def update(self, instance, validated_data)"
},
{
"docstring": "Prevent setting 'primary' to true if there is already another primary address, otherwise force se... | 2 | stack_v2_sparse_classes_30k_train_014106 | Implement the Python class `EmailAddressSerializer` described below.
Class description:
Implement the EmailAddressSerializer class.
Method signatures and docstrings:
- def update(self, instance, validated_data): Prevent setting 'primary' to false, and invalidate 'verified' if the address changes.
- def create(self, v... | Implement the Python class `EmailAddressSerializer` described below.
Class description:
Implement the EmailAddressSerializer class.
Method signatures and docstrings:
- def update(self, instance, validated_data): Prevent setting 'primary' to false, and invalidate 'verified' if the address changes.
- def create(self, v... | 2d88ffbb0cc54c47fd3f0124e33636331a4e3e4a | <|skeleton|>
class EmailAddressSerializer:
def update(self, instance, validated_data):
"""Prevent setting 'primary' to false, and invalidate 'verified' if the address changes."""
<|body_0|>
def create(self, validated_data, **kwargs):
"""Prevent setting 'primary' to true if there is alr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EmailAddressSerializer:
def update(self, instance, validated_data):
"""Prevent setting 'primary' to false, and invalidate 'verified' if the address changes."""
if 'primary' in validated_data:
iprimary = instance.primary
vprimary = validated_data['primary']
i... | the_stack_v2_python_sparse | gists/serializers.py | interpretation-experiment/spreadr | train | 0 | |
7f64fb8efd59d23a5417e9f9f7ad09ae9411b531 | [
"conf = Config()\ndata = shop()\ntest = Assert.Assertions()\nrequest = Request.Request(action[0], action[1])\nhost = conf.host_debug\nurls = data.url\napi_url = host + urls[4]\nresponse = request.get_request(api_url)\nassert test.assert_code(response['code'], 200)\nassert test.assert_body(response['body'], 'msg', u... | <|body_start_0|>
conf = Config()
data = shop()
test = Assert.Assertions()
request = Request.Request(action[0], action[1])
host = conf.host_debug
urls = data.url
api_url = host + urls[4]
response = request.get_request(api_url)
assert test.assert_cod... | TestReg | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestReg:
def test_01(self, action):
"""用例描述:获取账户保证金信息"""
<|body_0|>
def test_02(self, action):
"""用例描述:获取保证金记录列表"""
<|body_1|>
def test_03(self, action):
"""用例描述:获取保证金记录列表"""
<|body_2|>
def test_04(self, action):
"""用例描述:获取保证... | stack_v2_sparse_classes_75kplus_train_005773 | 2,900 | no_license | [
{
"docstring": "用例描述:获取账户保证金信息",
"name": "test_01",
"signature": "def test_01(self, action)"
},
{
"docstring": "用例描述:获取保证金记录列表",
"name": "test_02",
"signature": "def test_02(self, action)"
},
{
"docstring": "用例描述:获取保证金记录列表",
"name": "test_03",
"signature": "def test_03(se... | 4 | stack_v2_sparse_classes_30k_train_042243 | Implement the Python class `TestReg` described below.
Class description:
Implement the TestReg class.
Method signatures and docstrings:
- def test_01(self, action): 用例描述:获取账户保证金信息
- def test_02(self, action): 用例描述:获取保证金记录列表
- def test_03(self, action): 用例描述:获取保证金记录列表
- def test_04(self, action): 用例描述:获取保证金记录列表 | Implement the Python class `TestReg` described below.
Class description:
Implement the TestReg class.
Method signatures and docstrings:
- def test_01(self, action): 用例描述:获取账户保证金信息
- def test_02(self, action): 用例描述:获取保证金记录列表
- def test_03(self, action): 用例描述:获取保证金记录列表
- def test_04(self, action): 用例描述:获取保证金记录列表
<|ske... | 48998073404104a6b64975da1754404d2d5d3947 | <|skeleton|>
class TestReg:
def test_01(self, action):
"""用例描述:获取账户保证金信息"""
<|body_0|>
def test_02(self, action):
"""用例描述:获取保证金记录列表"""
<|body_1|>
def test_03(self, action):
"""用例描述:获取保证金记录列表"""
<|body_2|>
def test_04(self, action):
"""用例描述:获取保证... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestReg:
def test_01(self, action):
"""用例描述:获取账户保证金信息"""
conf = Config()
data = shop()
test = Assert.Assertions()
request = Request.Request(action[0], action[1])
host = conf.host_debug
urls = data.url
api_url = host + urls[4]
response = r... | the_stack_v2_python_sparse | TestCase/shop/test_05.py | wuyuchao1992/pytest-locust | train | 0 | |
a75ee323b35e637822431dda737bf1d0b13ed433 | [
"kwargs['formatter_class'] = lambda prog: HelpFormatter(prog, max_help_position=max_help_position)\nkwargs['description'] = __banner__ + (Colors.yellow(' {}'.format(component.strip())) if component else '')\nsuper().__init__(*args, **kwargs)\nif examples:\n self.epilog = Colors.yellow('examples:\\n') + ' {}'.f... | <|body_start_0|>
kwargs['formatter_class'] = lambda prog: HelpFormatter(prog, max_help_position=max_help_position)
kwargs['description'] = __banner__ + (Colors.yellow(' {}'.format(component.strip())) if component else '')
super().__init__(*args, **kwargs)
if examples:
self.e... | EOS ArgumentParser wrapper. | ArgumentParser | [
"Beerware"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArgumentParser:
"""EOS ArgumentParser wrapper."""
def __init__(self, *args, component=None, examples=None, max_help_position=30, **kwargs):
"""Initialization. Forces the use of an HelpFormatter with a max_help_position. Add the component name to the banner. Add examples to the epilog... | stack_v2_sparse_classes_75kplus_train_005774 | 6,145 | permissive | [
{
"docstring": "Initialization. Forces the use of an HelpFormatter with a max_help_position. Add the component name to the banner. Add examples to the epilog. Initialize the ArgumentParser. Add default arguments: version and verbosity. :param args: wrapped :param component: the EOS component name :param example... | 2 | null | Implement the Python class `ArgumentParser` described below.
Class description:
EOS ArgumentParser wrapper.
Method signatures and docstrings:
- def __init__(self, *args, component=None, examples=None, max_help_position=30, **kwargs): Initialization. Forces the use of an HelpFormatter with a max_help_position. Add the... | Implement the Python class `ArgumentParser` described below.
Class description:
EOS ArgumentParser wrapper.
Method signatures and docstrings:
- def __init__(self, *args, component=None, examples=None, max_help_position=30, **kwargs): Initialization. Forces the use of an HelpFormatter with a max_help_position. Add the... | 0cebeb2fd2d1952d6bb0d040a22f909fd5ae6efd | <|skeleton|>
class ArgumentParser:
"""EOS ArgumentParser wrapper."""
def __init__(self, *args, component=None, examples=None, max_help_position=30, **kwargs):
"""Initialization. Forces the use of an HelpFormatter with a max_help_position. Add the component name to the banner. Add examples to the epilog... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ArgumentParser:
"""EOS ArgumentParser wrapper."""
def __init__(self, *args, component=None, examples=None, max_help_position=30, **kwargs):
"""Initialization. Forces the use of an HelpFormatter with a max_help_position. Add the component name to the banner. Add examples to the epilog. Initialize ... | the_stack_v2_python_sparse | eos/utils/cli.py | YSaxon/eos | train | 0 |
046ddb9f5ed57d109ad5d458325f38980dfad022 | [
"if key.strip() == '':\n raise self.EmptyKeySpecified\nif not isinstance(key, str):\n raise self.WrongKeyFormat\nif not len(key) > 8:\n raise self.KeyTooSmall(key=key)\nself.key = self.gen_key(key_str=key)",
"if not key_str:\n key_str = 'FungoBat!'\nif not isinstance(key_str, bytes):\n key_str = ke... | <|body_start_0|>
if key.strip() == '':
raise self.EmptyKeySpecified
if not isinstance(key, str):
raise self.WrongKeyFormat
if not len(key) > 8:
raise self.KeyTooSmall(key=key)
self.key = self.gen_key(key_str=key)
<|end_body_0|>
<|body_start_1|>
... | Wrapper class for the functionality provided by pyCryptodome. | AESCrypt | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AESCrypt:
"""Wrapper class for the functionality provided by pyCryptodome."""
def __init__(self, key: str=None):
"""Initialize an instance of the AESCrypt class."""
<|body_0|>
def gen_key(key_str: str=None):
"""Generate a properly padded AES CBC key."""
<... | stack_v2_sparse_classes_75kplus_train_005775 | 17,352 | permissive | [
{
"docstring": "Initialize an instance of the AESCrypt class.",
"name": "__init__",
"signature": "def __init__(self, key: str=None)"
},
{
"docstring": "Generate a properly padded AES CBC key.",
"name": "gen_key",
"signature": "def gen_key(key_str: str=None)"
},
{
"docstring": "En... | 4 | stack_v2_sparse_classes_30k_test_000671 | Implement the Python class `AESCrypt` described below.
Class description:
Wrapper class for the functionality provided by pyCryptodome.
Method signatures and docstrings:
- def __init__(self, key: str=None): Initialize an instance of the AESCrypt class.
- def gen_key(key_str: str=None): Generate a properly padded AES ... | Implement the Python class `AESCrypt` described below.
Class description:
Wrapper class for the functionality provided by pyCryptodome.
Method signatures and docstrings:
- def __init__(self, key: str=None): Initialize an instance of the AESCrypt class.
- def gen_key(key_str: str=None): Generate a properly padded AES ... | b112fde2f3fbe44615f9a3b60b8210e89e51c1d5 | <|skeleton|>
class AESCrypt:
"""Wrapper class for the functionality provided by pyCryptodome."""
def __init__(self, key: str=None):
"""Initialize an instance of the AESCrypt class."""
<|body_0|>
def gen_key(key_str: str=None):
"""Generate a properly padded AES CBC key."""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AESCrypt:
"""Wrapper class for the functionality provided by pyCryptodome."""
def __init__(self, key: str=None):
"""Initialize an instance of the AESCrypt class."""
if key.strip() == '':
raise self.EmptyKeySpecified
if not isinstance(key, str):
raise self.W... | the_stack_v2_python_sparse | samples/authentication/aes_authentication.py | CrowdStrike/falconpy | train | 256 |
a01f40def4606dbbb33e812126fdf5e3713e20a7 | [
"n = len(nums)\ndp = [0] * (n + 2)\nfor i in reversed(range(n)):\n dp[i] = max(nums[i] + dp[i + 2], dp[i + 1])\nreturn dp[0]",
"last, now = (0, 0)\nfor x in nums:\n last, now = (now, max(last + x, now))\nreturn now"
] | <|body_start_0|>
n = len(nums)
dp = [0] * (n + 2)
for i in reversed(range(n)):
dp[i] = max(nums[i] + dp[i + 2], dp[i + 1])
return dp[0]
<|end_body_0|>
<|body_start_1|>
last, now = (0, 0)
for x in nums:
last, now = (now, max(last + x, now))
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def rob2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(nums)
dp = [0] * (n + 2)
for i in re... | stack_v2_sparse_classes_75kplus_train_005776 | 1,446 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob",
"signature": "def rob(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob2",
"signature": "def rob2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003016 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def rob2(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def rob2(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def rob(self, nums):
"... | fa6504cb5145d10952f4615478fa745f4b35ba13 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def rob2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
n = len(nums)
dp = [0] * (n + 2)
for i in reversed(range(n)):
dp[i] = max(nums[i] + dp[i + 2], dp[i + 1])
return dp[0]
def rob2(self, nums):
""":type nums: List[int] :rtype: ... | the_stack_v2_python_sparse | Algorithms/challenges/lc198_house_robber.py | snowdj/cs_course | train | 0 | |
18b7cd01cacdfa4565da4c357fdcbdb829df406d | [
"delta = 10\ncurrent_year = 2020\nresult = previous_years(delta)\nself.assertEqual(result[0], current_year - delta - 1)\nself.assertEqual(result[0], 2009)",
"Product.objects.create(name='testname', description='test description', offer=10, price=20, category='', stock=3)\nProduct.objects.create(name='testname2', ... | <|body_start_0|>
delta = 10
current_year = 2020
result = previous_years(delta)
self.assertEqual(result[0], current_year - delta - 1)
self.assertEqual(result[0], 2009)
<|end_body_0|>
<|body_start_1|>
Product.objects.create(name='testname', description='test description', ... | TestHelperFunctions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestHelperFunctions:
def test_previous_years(self):
"""testing function returning a list with range from previous year to current as user can input only int is only tested against int (delta)"""
<|body_0|>
def setUp(self):
"""filling test db with dummy products"""
... | stack_v2_sparse_classes_75kplus_train_005777 | 1,625 | no_license | [
{
"docstring": "testing function returning a list with range from previous year to current as user can input only int is only tested against int (delta)",
"name": "test_previous_years",
"signature": "def test_previous_years(self)"
},
{
"docstring": "filling test db with dummy products",
"nam... | 3 | stack_v2_sparse_classes_30k_train_050999 | Implement the Python class `TestHelperFunctions` described below.
Class description:
Implement the TestHelperFunctions class.
Method signatures and docstrings:
- def test_previous_years(self): testing function returning a list with range from previous year to current as user can input only int is only tested against ... | Implement the Python class `TestHelperFunctions` described below.
Class description:
Implement the TestHelperFunctions class.
Method signatures and docstrings:
- def test_previous_years(self): testing function returning a list with range from previous year to current as user can input only int is only tested against ... | c25fe47d386357d929242e2a6dd36666328195b0 | <|skeleton|>
class TestHelperFunctions:
def test_previous_years(self):
"""testing function returning a list with range from previous year to current as user can input only int is only tested against int (delta)"""
<|body_0|>
def setUp(self):
"""filling test db with dummy products"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestHelperFunctions:
def test_previous_years(self):
"""testing function returning a list with range from previous year to current as user can input only int is only tested against int (delta)"""
delta = 10
current_year = 2020
result = previous_years(delta)
self.assertEq... | the_stack_v2_python_sparse | helper/tests.py | SalvatoreFiengo/myecommerce | train | 0 | |
47c3e70d8f7c6df8bdebd804a44b995c9e00e14a | [
"client_mock = DumpACPITableMock()\ntable_signature_list = ['DSDT', 'XSDT', 'SSDT']\nclient_id = self.SetupClient(0)\nflow_id = flow_test_lib.TestFlowHelper(hardware.DumpACPITable.__name__, client_mock, table_signature_list=table_signature_list, client_id=client_id, creator=self.test_username)\nresults = [r.payload... | <|body_start_0|>
client_mock = DumpACPITableMock()
table_signature_list = ['DSDT', 'XSDT', 'SSDT']
client_id = self.SetupClient(0)
flow_id = flow_test_lib.TestFlowHelper(hardware.DumpACPITable.__name__, client_mock, table_signature_list=table_signature_list, client_id=client_id, creator=... | DumpACPITableTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DumpACPITableTest:
def testDumpValidACPITableOk(self):
"""Tests dumping ACPI table."""
<|body_0|>
def testDumpInvalidACPITable(self):
"""Tests dumping nonexistent ACPI table."""
<|body_1|>
def testEmptyTableSignatureList(self):
"""Tests DumpACPIT... | stack_v2_sparse_classes_75kplus_train_005778 | 6,758 | permissive | [
{
"docstring": "Tests dumping ACPI table.",
"name": "testDumpValidACPITableOk",
"signature": "def testDumpValidACPITableOk(self)"
},
{
"docstring": "Tests dumping nonexistent ACPI table.",
"name": "testDumpInvalidACPITable",
"signature": "def testDumpInvalidACPITable(self)"
},
{
... | 3 | null | Implement the Python class `DumpACPITableTest` described below.
Class description:
Implement the DumpACPITableTest class.
Method signatures and docstrings:
- def testDumpValidACPITableOk(self): Tests dumping ACPI table.
- def testDumpInvalidACPITable(self): Tests dumping nonexistent ACPI table.
- def testEmptyTableSi... | Implement the Python class `DumpACPITableTest` described below.
Class description:
Implement the DumpACPITableTest class.
Method signatures and docstrings:
- def testDumpValidACPITableOk(self): Tests dumping ACPI table.
- def testDumpInvalidACPITable(self): Tests dumping nonexistent ACPI table.
- def testEmptyTableSi... | 44c0eb8c938302098ef7efae8cfd6b90bcfbb2d6 | <|skeleton|>
class DumpACPITableTest:
def testDumpValidACPITableOk(self):
"""Tests dumping ACPI table."""
<|body_0|>
def testDumpInvalidACPITable(self):
"""Tests dumping nonexistent ACPI table."""
<|body_1|>
def testEmptyTableSignatureList(self):
"""Tests DumpACPIT... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DumpACPITableTest:
def testDumpValidACPITableOk(self):
"""Tests dumping ACPI table."""
client_mock = DumpACPITableMock()
table_signature_list = ['DSDT', 'XSDT', 'SSDT']
client_id = self.SetupClient(0)
flow_id = flow_test_lib.TestFlowHelper(hardware.DumpACPITable.__name_... | the_stack_v2_python_sparse | grr/server/grr_response_server/flows/general/hardware_test.py | google/grr | train | 4,683 | |
21d5d02c53d477439ccb7ff4c1c877065c2cbe9b | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Status: experimental interface, will change before it is deemed production ready The ledger configuration management service provides methods for the ledger administrator to change the current ledger configuration. The services provides methods to modify different aspects of the configuration. | ConfigManagementServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigManagementServiceServicer:
"""Status: experimental interface, will change before it is deemed production ready The ledger configuration management service provides methods for the ledger administrator to change the current ledger configuration. The services provides methods to modify differ... | stack_v2_sparse_classes_75kplus_train_005779 | 6,167 | permissive | [
{
"docstring": "Return the currently active time model and the current configuration generation.",
"name": "GetTimeModel",
"signature": "def GetTimeModel(self, request, context)"
},
{
"docstring": "Set the ledger time model.",
"name": "SetTimeModel",
"signature": "def SetTimeModel(self, ... | 2 | null | Implement the Python class `ConfigManagementServiceServicer` described below.
Class description:
Status: experimental interface, will change before it is deemed production ready The ledger configuration management service provides methods for the ledger administrator to change the current ledger configuration. The ser... | Implement the Python class `ConfigManagementServiceServicer` described below.
Class description:
Status: experimental interface, will change before it is deemed production ready The ledger configuration management service provides methods for the ledger administrator to change the current ledger configuration. The ser... | efdbb00e54614c0af650d7440faaffbde92ad1f4 | <|skeleton|>
class ConfigManagementServiceServicer:
"""Status: experimental interface, will change before it is deemed production ready The ledger configuration management service provides methods for the ledger administrator to change the current ledger configuration. The services provides methods to modify differ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConfigManagementServiceServicer:
"""Status: experimental interface, will change before it is deemed production ready The ledger configuration management service provides methods for the ledger administrator to change the current ledger configuration. The services provides methods to modify different aspects o... | the_stack_v2_python_sparse | python/dazl/_gen/com/daml/ledger/api/v1/admin/config_management_service_pb2_grpc.py | digital-asset/dazl-client | train | 12 |
11475faad8630a53794bddbb026a9bcedc1d8f2b | [
"data = self.get_json()\nwith self.Session() as session:\n run_id = post_observing_run(data, self.associated_user_object.id, session)\n return self.success(data={'id': run_id})",
"with self.Session() as session:\n if run_id is not None:\n options = [joinedload(ObservingRun.assignments).joinedload(... | <|body_start_0|>
data = self.get_json()
with self.Session() as session:
run_id = post_observing_run(data, self.associated_user_object.id, session)
return self.success(data={'id': run_id})
<|end_body_0|>
<|body_start_1|>
with self.Session() as session:
if run_... | ObservingRunHandler | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObservingRunHandler:
def post(self):
"""--- description: Add a new observing run tags: - observing_runs requestBody: content: application/json: schema: ObservingRunPost responses: 200: content: application/json: schema: allOf: - $ref: '#/components/schemas/Success' - type: object propert... | stack_v2_sparse_classes_75kplus_train_005780 | 8,999 | permissive | [
{
"docstring": "--- description: Add a new observing run tags: - observing_runs requestBody: content: application/json: schema: ObservingRunPost responses: 200: content: application/json: schema: allOf: - $ref: '#/components/schemas/Success' - type: object properties: data: type: object properties: id: type: in... | 4 | stack_v2_sparse_classes_30k_test_001882 | Implement the Python class `ObservingRunHandler` described below.
Class description:
Implement the ObservingRunHandler class.
Method signatures and docstrings:
- def post(self): --- description: Add a new observing run tags: - observing_runs requestBody: content: application/json: schema: ObservingRunPost responses: ... | Implement the Python class `ObservingRunHandler` described below.
Class description:
Implement the ObservingRunHandler class.
Method signatures and docstrings:
- def post(self): --- description: Add a new observing run tags: - observing_runs requestBody: content: application/json: schema: ObservingRunPost responses: ... | 161d3532ba3ba059446addcdac58ca96f39e9636 | <|skeleton|>
class ObservingRunHandler:
def post(self):
"""--- description: Add a new observing run tags: - observing_runs requestBody: content: application/json: schema: ObservingRunPost responses: 200: content: application/json: schema: allOf: - $ref: '#/components/schemas/Success' - type: object propert... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ObservingRunHandler:
def post(self):
"""--- description: Add a new observing run tags: - observing_runs requestBody: content: application/json: schema: ObservingRunPost responses: 200: content: application/json: schema: allOf: - $ref: '#/components/schemas/Success' - type: object properties: data: typ... | the_stack_v2_python_sparse | skyportal/handlers/api/observingrun.py | skyportal/skyportal | train | 80 | |
ef6540aa03f72f9f9b1e91d7ce3b66bf278bf6e3 | [
"assert checker == 'X' or checker == 'O'\nself.checker = checker\nself.num_moves = 0",
"s = 'Player '\ns += self.checker\nreturn s",
"if self.checker == 'X':\n return 'O'\nelse:\n return 'X'",
"self.num_moves += 1\nwhile True:\n col = int(input('Enter a column: '))\n if col >= 0 and col < b.width:... | <|body_start_0|>
assert checker == 'X' or checker == 'O'
self.checker = checker
self.num_moves = 0
<|end_body_0|>
<|body_start_1|>
s = 'Player '
s += self.checker
return s
<|end_body_1|>
<|body_start_2|>
if self.checker == 'X':
return 'O'
els... | Player | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Player:
def __init__(self, checker):
"""constructs a new Player object by initializing checker and num_moves."""
<|body_0|>
def __repr__(self):
"""returns a string representing a Player object."""
<|body_1|>
def opponent_checker(self):
"""this fu... | stack_v2_sparse_classes_75kplus_train_005781 | 1,172 | no_license | [
{
"docstring": "constructs a new Player object by initializing checker and num_moves.",
"name": "__init__",
"signature": "def __init__(self, checker)"
},
{
"docstring": "returns a string representing a Player object.",
"name": "__repr__",
"signature": "def __repr__(self)"
},
{
"d... | 4 | null | Implement the Python class `Player` described below.
Class description:
Implement the Player class.
Method signatures and docstrings:
- def __init__(self, checker): constructs a new Player object by initializing checker and num_moves.
- def __repr__(self): returns a string representing a Player object.
- def opponent... | Implement the Python class `Player` described below.
Class description:
Implement the Player class.
Method signatures and docstrings:
- def __init__(self, checker): constructs a new Player object by initializing checker and num_moves.
- def __repr__(self): returns a string representing a Player object.
- def opponent... | f89bbe8c9b0ec4bde46cbc61ebc408f49ee69c39 | <|skeleton|>
class Player:
def __init__(self, checker):
"""constructs a new Player object by initializing checker and num_moves."""
<|body_0|>
def __repr__(self):
"""returns a string representing a Player object."""
<|body_1|>
def opponent_checker(self):
"""this fu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Player:
def __init__(self, checker):
"""constructs a new Player object by initializing checker and num_moves."""
assert checker == 'X' or checker == 'O'
self.checker = checker
self.num_moves = 0
def __repr__(self):
"""returns a string representing a Player object."... | the_stack_v2_python_sparse | PS9/ps9part1/ps9pr2.py | NicoleeeTian/CS111 | train | 2 | |
2099630d9b204a440bf96ebe84c346f0e65c7c84 | [
"self.s1 = s1\nself.s2 = s2\nself.s3 = s3\nself.l1 = len(s1)\nself.l2 = len(s2)\nself.l3 = len(s3)\nself.dict_s3 = {}\nif self.l1 + self.l2 != self.l3:\n return False\n\ndef dfs(i, j, count):\n if (i, j) in self.dict_s3:\n return False\n print(i, j)\n if i + j >= self.l3:\n return True\n ... | <|body_start_0|>
self.s1 = s1
self.s2 = s2
self.s3 = s3
self.l1 = len(s1)
self.l2 = len(s2)
self.l3 = len(s3)
self.dict_s3 = {}
if self.l1 + self.l2 != self.l3:
return False
def dfs(i, j, count):
if (i, j) in self.dict_s3:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isInterleave(self, s1, s2, s3):
""":type s1: str :type s2: str :type s3: str :rtype: bool 32ms"""
<|body_0|>
def isInterleave_1(self, s1, s2, s3):
""":type s1: str :type s2: str :type s3: str :rtype: bool 36ms"""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_75kplus_train_005782 | 2,848 | no_license | [
{
"docstring": ":type s1: str :type s2: str :type s3: str :rtype: bool 32ms",
"name": "isInterleave",
"signature": "def isInterleave(self, s1, s2, s3)"
},
{
"docstring": ":type s1: str :type s2: str :type s3: str :rtype: bool 36ms",
"name": "isInterleave_1",
"signature": "def isInterleav... | 2 | stack_v2_sparse_classes_30k_train_026849 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isInterleave(self, s1, s2, s3): :type s1: str :type s2: str :type s3: str :rtype: bool 32ms
- def isInterleave_1(self, s1, s2, s3): :type s1: str :type s2: str :type s3: str ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isInterleave(self, s1, s2, s3): :type s1: str :type s2: str :type s3: str :rtype: bool 32ms
- def isInterleave_1(self, s1, s2, s3): :type s1: str :type s2: str :type s3: str ... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def isInterleave(self, s1, s2, s3):
""":type s1: str :type s2: str :type s3: str :rtype: bool 32ms"""
<|body_0|>
def isInterleave_1(self, s1, s2, s3):
""":type s1: str :type s2: str :type s3: str :rtype: bool 36ms"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isInterleave(self, s1, s2, s3):
""":type s1: str :type s2: str :type s3: str :rtype: bool 32ms"""
self.s1 = s1
self.s2 = s2
self.s3 = s3
self.l1 = len(s1)
self.l2 = len(s2)
self.l3 = len(s3)
self.dict_s3 = {}
if self.l1 + se... | the_stack_v2_python_sparse | InterleavingString_HARD_97.py | 953250587/leetcode-python | train | 2 | |
78a57ff2148450d76dcd07164c6d982719e28124 | [
"super(NeRF, self).__init__()\nself.D = D\nself.W = W\nself.in_channels_xyz = in_channels_xyz\nself.in_channels_dir = in_channels_dir\nself.skips = skips\nfor i in range(D):\n if i == 0:\n layer = nn.Linear(in_channels_xyz, W)\n elif i in skips:\n layer = nn.Linear(W + in_channels_xyz, W)\n e... | <|body_start_0|>
super(NeRF, self).__init__()
self.D = D
self.W = W
self.in_channels_xyz = in_channels_xyz
self.in_channels_dir = in_channels_dir
self.skips = skips
for i in range(D):
if i == 0:
layer = nn.Linear(in_channels_xyz, W)
... | NeRF | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NeRF:
def __init__(self, D=8, W=256, in_channels_xyz=672, in_channels_dir=27, skips=[4]):
"""D: number of layers for density (sigma) encoder W: number of hidden units in each layer in_channels_xyz: number of input channels for xyz (3+3*10*2=63 by default) in_channels_dir: number of input... | stack_v2_sparse_classes_75kplus_train_005783 | 8,902 | no_license | [
{
"docstring": "D: number of layers for density (sigma) encoder W: number of hidden units in each layer in_channels_xyz: number of input channels for xyz (3+3*10*2=63 by default) in_channels_dir: number of input channels for direction (3+3*4*2=27 by default) skips: add skip connection in the Dth layer",
"na... | 2 | null | Implement the Python class `NeRF` described below.
Class description:
Implement the NeRF class.
Method signatures and docstrings:
- def __init__(self, D=8, W=256, in_channels_xyz=672, in_channels_dir=27, skips=[4]): D: number of layers for density (sigma) encoder W: number of hidden units in each layer in_channels_xy... | Implement the Python class `NeRF` described below.
Class description:
Implement the NeRF class.
Method signatures and docstrings:
- def __init__(self, D=8, W=256, in_channels_xyz=672, in_channels_dir=27, skips=[4]): D: number of layers for density (sigma) encoder W: number of hidden units in each layer in_channels_xy... | 7da1d7b806f5a5ce8bd35a0041ecb43609e7cb2c | <|skeleton|>
class NeRF:
def __init__(self, D=8, W=256, in_channels_xyz=672, in_channels_dir=27, skips=[4]):
"""D: number of layers for density (sigma) encoder W: number of hidden units in each layer in_channels_xyz: number of input channels for xyz (3+3*10*2=63 by default) in_channels_dir: number of input... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NeRF:
def __init__(self, D=8, W=256, in_channels_xyz=672, in_channels_dir=27, skips=[4]):
"""D: number of layers for density (sigma) encoder W: number of hidden units in each layer in_channels_xyz: number of input channels for xyz (3+3*10*2=63 by default) in_channels_dir: number of input channels for ... | the_stack_v2_python_sparse | nsvf/model.py | nitthilan/neural_sparse_voxel_field | train | 3 | |
3b44be97536a340af916e5ed7d901d010b282321 | [
"inputSpecification = super().getInputSpecification()\norderInputType = InputTypes.makeEnumType('order', 'orderType', ['0', '1'])\ninputSpecification.addSub(InputData.parameterInputFactory('order', contentType=orderInputType), quantity=InputData.Quantity.one)\ninputSpecification.addSub(InputData.parameterInputFacto... | <|body_start_0|>
inputSpecification = super().getInputSpecification()
orderInputType = InputTypes.makeEnumType('order', 'orderType', ['0', '1'])
inputSpecification.addSub(InputData.parameterInputFactory('order', contentType=orderInputType), quantity=InputData.Quantity.one)
inputSpecifica... | Dynamic Time Warping Metric Class for measuring similarity between two variables X and Y, i.e. two temporal sequences | DTW | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DTW:
"""Dynamic Time Warping Metric Class for measuring similarity between two variables X and Y, i.e. two temporal sequences"""
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for which we are ... | stack_v2_sparse_classes_75kplus_train_005784 | 7,028 | permissive | [
{
"docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for which we are retrieving the specification @ Out, inputSpecification, InputData.ParameterInput, class to use for specifying input of cls.",
"name": "getInputSpecification",
"signatur... | 6 | stack_v2_sparse_classes_30k_train_049173 | Implement the Python class `DTW` described below.
Class description:
Dynamic Time Warping Metric Class for measuring similarity between two variables X and Y, i.e. two temporal sequences
Method signatures and docstrings:
- def getInputSpecification(cls): Method to get a reference to a class that specifies the input d... | Implement the Python class `DTW` described below.
Class description:
Dynamic Time Warping Metric Class for measuring similarity between two variables X and Y, i.e. two temporal sequences
Method signatures and docstrings:
- def getInputSpecification(cls): Method to get a reference to a class that specifies the input d... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class DTW:
"""Dynamic Time Warping Metric Class for measuring similarity between two variables X and Y, i.e. two temporal sequences"""
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for which we are ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DTW:
"""Dynamic Time Warping Metric Class for measuring similarity between two variables X and Y, i.e. two temporal sequences"""
def getInputSpecification(cls):
"""Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for which we are retrieving th... | the_stack_v2_python_sparse | ravenframework/Metrics/metrics/DTW.py | idaholab/raven | train | 201 |
048fc83c77d95284c49356adf5c16b394a2bc476 | [
"log.basicConfig(format='%(name)s::%(funcName)s %(message)s', level=log.INFO)\nlogger = log.getLogger('Miner')\nlogger.info('[{}] from \"{}\"'.format('MEM' if from_memory else 'FILE', group_name))\ndata = {}\nif from_memory:\n voltages = GetStatus(multimeters_dict[group_name])[0]['events']['V_m']\n times = Ge... | <|body_start_0|>
log.basicConfig(format='%(name)s::%(funcName)s %(message)s', level=log.INFO)
logger = log.getLogger('Miner')
logger.info('[{}] from "{}"'.format('MEM' if from_memory else 'FILE', group_name))
data = {}
if from_memory:
voltages = GetStatus(multimeters_... | Miner | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Miner:
def gather_mean_voltage(group_name, from_memory=False):
"""Gather voltage from files and calculate mean for each milliseconds Args: group_name (str): neurons group name from_memory (bool): Returns: list: mean voltage for each millisecond"""
<|body_0|>
def gather_spike... | stack_v2_sparse_classes_75kplus_train_005785 | 3,495 | permissive | [
{
"docstring": "Gather voltage from files and calculate mean for each milliseconds Args: group_name (str): neurons group name from_memory (bool): Returns: list: mean voltage for each millisecond",
"name": "gather_mean_voltage",
"signature": "def gather_mean_voltage(group_name, from_memory=False)"
},
... | 4 | stack_v2_sparse_classes_30k_val_000473 | Implement the Python class `Miner` described below.
Class description:
Implement the Miner class.
Method signatures and docstrings:
- def gather_mean_voltage(group_name, from_memory=False): Gather voltage from files and calculate mean for each milliseconds Args: group_name (str): neurons group name from_memory (bool)... | Implement the Python class `Miner` described below.
Class description:
Implement the Miner class.
Method signatures and docstrings:
- def gather_mean_voltage(group_name, from_memory=False): Gather voltage from files and calculate mean for each milliseconds Args: group_name (str): neurons group name from_memory (bool)... | f6d7bca154fb4cab503f416fa01b8dc9b0a7d046 | <|skeleton|>
class Miner:
def gather_mean_voltage(group_name, from_memory=False):
"""Gather voltage from files and calculate mean for each milliseconds Args: group_name (str): neurons group name from_memory (bool): Returns: list: mean voltage for each millisecond"""
<|body_0|>
def gather_spike... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Miner:
def gather_mean_voltage(group_name, from_memory=False):
"""Gather voltage from files and calculate mean for each milliseconds Args: group_name (str): neurons group name from_memory (bool): Returns: list: mean voltage for each millisecond"""
log.basicConfig(format='%(name)s::%(funcName)s... | the_stack_v2_python_sparse | NEST/second_level/src/tools/miner.py | late-goodbye/memristive-spinal-cord | train | 0 | |
d0ad0bf98663cf3cd081dd10771a0023cf9ea178 | [
"match = re.match('^<@([A-Za-z0-9]+)>', txt)\nif match is not None:\n return match.group(1).upper()\nreturn None",
"msg_split = message.split(' ')\ncmd_dict = {'cmd': re.split('-+\\\\w+', message)[0].strip()}\nflag_regex = re.compile('^-+(\\\\w+)')\nfor i, part in enumerate(msg_split):\n if flag_regex.match... | <|body_start_0|>
match = re.match('^<@([A-Za-z0-9]+)>', txt)
if match is not None:
return match.group(1).upper()
return None
<|end_body_0|>
<|body_start_1|>
msg_split = message.split(' ')
cmd_dict = {'cmd': re.split('-+\\w+', message)[0].strip()}
flag_regex =... | A class solely meant to help parse input from Slack into usable data | SlackInputParser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SlackInputParser:
"""A class solely meant to help parse input from Slack into usable data"""
def parse_tag_from_text(txt: str) -> Optional[str]:
"""Parses an <@{user}> mention and extracts the user id from it"""
<|body_0|>
def parse_flags_from_command(cls, message: str) ... | stack_v2_sparse_classes_75kplus_train_005786 | 6,159 | permissive | [
{
"docstring": "Parses an <@{user}> mention and extracts the user id from it",
"name": "parse_tag_from_text",
"signature": "def parse_tag_from_text(txt: str) -> Optional[str]"
},
{
"docstring": "Takes in a message string and parses out flags in the string and the values following them Args: mess... | 3 | stack_v2_sparse_classes_30k_train_052395 | Implement the Python class `SlackInputParser` described below.
Class description:
A class solely meant to help parse input from Slack into usable data
Method signatures and docstrings:
- def parse_tag_from_text(txt: str) -> Optional[str]: Parses an <@{user}> mention and extracts the user id from it
- def parse_flags_... | Implement the Python class `SlackInputParser` described below.
Class description:
A class solely meant to help parse input from Slack into usable data
Method signatures and docstrings:
- def parse_tag_from_text(txt: str) -> Optional[str]: Parses an <@{user}> mention and extracts the user id from it
- def parse_flags_... | f8c380a45605fcf2d480e6f9c87d9e889128e769 | <|skeleton|>
class SlackInputParser:
"""A class solely meant to help parse input from Slack into usable data"""
def parse_tag_from_text(txt: str) -> Optional[str]:
"""Parses an <@{user}> mention and extracts the user id from it"""
<|body_0|>
def parse_flags_from_command(cls, message: str) ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SlackInputParser:
"""A class solely meant to help parse input from Slack into usable data"""
def parse_tag_from_text(txt: str) -> Optional[str]:
"""Parses an <@{user}> mention and extracts the user id from it"""
match = re.match('^<@([A-Za-z0-9]+)>', txt)
if match is not None:
... | the_stack_v2_python_sparse | slacktools/slack_input_parser.py | barretobrock/slacktools | train | 1 |
e59fcf14c034c89f740d78d70a7f6533fb20f5aa | [
"super(MANOLayer, self).__init__(*args, **kwargs)\nself.keypoint_src = keypoint_src\nself.keypoint_dst = keypoint_dst\nself.keypoint_approximate = keypoint_approximate\nself.num_verts = self.get_num_verts()\nself.num_faces = self.get_num_faces()\nself.num_joints = get_keypoint_num(convention=self.keypoint_dst)",
... | <|body_start_0|>
super(MANOLayer, self).__init__(*args, **kwargs)
self.keypoint_src = keypoint_src
self.keypoint_dst = keypoint_dst
self.keypoint_approximate = keypoint_approximate
self.num_verts = self.get_num_verts()
self.num_faces = self.get_num_faces()
self.nu... | Extension of the official MANO implementation. | MANOLayer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MANOLayer:
"""Extension of the official MANO implementation."""
def __init__(self, *args, keypoint_src: str='mano', keypoint_dst: str='human_data', keypoint_approximate: bool=False, **kwargs):
"""Args: *args: extra arguments for MANO initialization. keypoint_src: source convention of... | stack_v2_sparse_classes_75kplus_train_005787 | 8,893 | permissive | [
{
"docstring": "Args: *args: extra arguments for MANO initialization. keypoint_src: source convention of keypoints. This convention is used for keypoints obtained from joint regressors. Keypoints then undergo conversion into keypoint_dst convention. keypoint_dst: destination convention of keypoints. This conven... | 3 | stack_v2_sparse_classes_30k_train_052880 | Implement the Python class `MANOLayer` described below.
Class description:
Extension of the official MANO implementation.
Method signatures and docstrings:
- def __init__(self, *args, keypoint_src: str='mano', keypoint_dst: str='human_data', keypoint_approximate: bool=False, **kwargs): Args: *args: extra arguments fo... | Implement the Python class `MANOLayer` described below.
Class description:
Extension of the official MANO implementation.
Method signatures and docstrings:
- def __init__(self, *args, keypoint_src: str='mano', keypoint_dst: str='human_data', keypoint_approximate: bool=False, **kwargs): Args: *args: extra arguments fo... | 9431addec32f7fbeffa1786927a854c0ab79d9ea | <|skeleton|>
class MANOLayer:
"""Extension of the official MANO implementation."""
def __init__(self, *args, keypoint_src: str='mano', keypoint_dst: str='human_data', keypoint_approximate: bool=False, **kwargs):
"""Args: *args: extra arguments for MANO initialization. keypoint_src: source convention of... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MANOLayer:
"""Extension of the official MANO implementation."""
def __init__(self, *args, keypoint_src: str='mano', keypoint_dst: str='human_data', keypoint_approximate: bool=False, **kwargs):
"""Args: *args: extra arguments for MANO initialization. keypoint_src: source convention of keypoints. T... | the_stack_v2_python_sparse | mmhuman3d/models/body_models/mano.py | open-mmlab/mmhuman3d | train | 966 |
39f01ab1643286d0d10778342d7146f85a3ca685 | [
"self.d = collections.defaultdict(int)\nself.partial = ''\nself.matches = []\nfor s, t in zip(sentences, times):\n self.d[s] = t",
"if c == '#':\n self.d[self.partial] += 1\n self.partial = ''\n self.matches = []\n return []\nif self.partial == '':\n self.matches = [(-count, s) for s, count in s... | <|body_start_0|>
self.d = collections.defaultdict(int)
self.partial = ''
self.matches = []
for s, t in zip(sentences, times):
self.d[s] = t
<|end_body_0|>
<|body_start_1|>
if c == '#':
self.d[self.partial] += 1
self.partial = ''
se... | AutocompleteSystem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
<|body_0|>
def input(self, c):
""":type c: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.d = collections.d... | stack_v2_sparse_classes_75kplus_train_005788 | 1,219 | no_license | [
{
"docstring": ":type sentences: List[str] :type times: List[int]",
"name": "__init__",
"signature": "def __init__(self, sentences, times)"
},
{
"docstring": ":type c: str :rtype: List[str]",
"name": "input",
"signature": "def input(self, c)"
}
] | 2 | stack_v2_sparse_classes_30k_train_025697 | Implement the Python class `AutocompleteSystem` described below.
Class description:
Implement the AutocompleteSystem class.
Method signatures and docstrings:
- def __init__(self, sentences, times): :type sentences: List[str] :type times: List[int]
- def input(self, c): :type c: str :rtype: List[str] | Implement the Python class `AutocompleteSystem` described below.
Class description:
Implement the AutocompleteSystem class.
Method signatures and docstrings:
- def __init__(self, sentences, times): :type sentences: List[str] :type times: List[int]
- def input(self, c): :type c: str :rtype: List[str]
<|skeleton|>
cla... | fe5c6936627c2459731ddda6f67422c217b3cc91 | <|skeleton|>
class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
<|body_0|>
def input(self, c):
""":type c: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
self.d = collections.defaultdict(int)
self.partial = ''
self.matches = []
for s, t in zip(sentences, times):
self.d[s] = t
def input(self, ... | the_stack_v2_python_sparse | 642. Design Search Autocomplete System/Python 2/solution.py | HarrrrryLi/LeetCode | train | 0 | |
82394f47d07bd12e96e80790941d0a2dc086ffca | [
"kargs.update(dict(watch_list=goals))\nkargs.update(dict(success=success))\nsuper(GoalMonitor, self)._post_init(**kargs)",
"report('ALL GOALS SATISIFIED')\nself.stop()\nself.universe.halt()"
] | <|body_start_0|>
kargs.update(dict(watch_list=goals))
kargs.update(dict(success=success))
super(GoalMonitor, self)._post_init(**kargs)
<|end_body_0|>
<|body_start_1|>
report('ALL GOALS SATISIFIED')
self.stop()
self.universe.halt()
<|end_body_1|>
| the Goal Service is a watchdog who shuts down the universe when all it's goals are completed. | GoalMonitor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoalMonitor:
"""the Goal Service is a watchdog who shuts down the universe when all it's goals are completed."""
def _post_init(self, goals=[], success=None, **kargs):
"""alias watchdog's "watch_list" argument to "goals" for a more intuitive api."""
<|body_0|>
def bark(s... | stack_v2_sparse_classes_75kplus_train_005789 | 1,460 | no_license | [
{
"docstring": "alias watchdog's \"watch_list\" argument to \"goals\" for a more intuitive api.",
"name": "_post_init",
"signature": "def _post_init(self, goals=[], success=None, **kargs)"
},
{
"docstring": "bark() is called by watchdog when everything in the goal_list tests True",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_002810 | Implement the Python class `GoalMonitor` described below.
Class description:
the Goal Service is a watchdog who shuts down the universe when all it's goals are completed.
Method signatures and docstrings:
- def _post_init(self, goals=[], success=None, **kargs): alias watchdog's "watch_list" argument to "goals" for a ... | Implement the Python class `GoalMonitor` described below.
Class description:
the Goal Service is a watchdog who shuts down the universe when all it's goals are completed.
Method signatures and docstrings:
- def _post_init(self, goals=[], success=None, **kargs): alias watchdog's "watch_list" argument to "goals" for a ... | 324b5c057a2570f84cde95ff4831e59b839858a1 | <|skeleton|>
class GoalMonitor:
"""the Goal Service is a watchdog who shuts down the universe when all it's goals are completed."""
def _post_init(self, goals=[], success=None, **kargs):
"""alias watchdog's "watch_list" argument to "goals" for a more intuitive api."""
<|body_0|>
def bark(s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GoalMonitor:
"""the Goal Service is a watchdog who shuts down the universe when all it's goals are completed."""
def _post_init(self, goals=[], success=None, **kargs):
"""alias watchdog's "watch_list" argument to "goals" for a more intuitive api."""
kargs.update(dict(watch_list=goals))
... | the_stack_v2_python_sparse | lib/cortex/services/goalmonitor.py | mattvonrocketstein/cortex | train | 1 |
8c027f71228158bbabd42c08cea08602d3c4dd55 | [
"standard_url = 'https://www.chicago.gov/city/en/depts/cdph/supp_info/boh/{}-board-of-health-meetings.html'\nurl_variant_1 = 'https://www.chicago.gov/city/en/depts/cdph/supp_info/boh/{}-board-of-health.html'\ncurrent_year = datetime.now().year\nreturn [standard_url.format(current_year), url_variant_1.format(current... | <|body_start_0|>
standard_url = 'https://www.chicago.gov/city/en/depts/cdph/supp_info/boh/{}-board-of-health-meetings.html'
url_variant_1 = 'https://www.chicago.gov/city/en/depts/cdph/supp_info/boh/{}-board-of-health.html'
current_year = datetime.now().year
return [standard_url.format(cu... | ChiPubHealthSpider | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChiPubHealthSpider:
def start_urls(self):
"""DPH generally uses a standard URL format, but sometimes deviates from the pattern. This property inserts the current year into the standard format, as well as known variants, in hopes DPH sticks to one of their conventions and this scraper doe... | stack_v2_sparse_classes_75kplus_train_005790 | 5,040 | permissive | [
{
"docstring": "DPH generally uses a standard URL format, but sometimes deviates from the pattern. This property inserts the current year into the standard format, as well as known variants, in hopes DPH sticks to one of their conventions and this scraper does not need to be updated annually.",
"name": "sta... | 5 | stack_v2_sparse_classes_30k_train_053829 | Implement the Python class `ChiPubHealthSpider` described below.
Class description:
Implement the ChiPubHealthSpider class.
Method signatures and docstrings:
- def start_urls(self): DPH generally uses a standard URL format, but sometimes deviates from the pattern. This property inserts the current year into the stand... | Implement the Python class `ChiPubHealthSpider` described below.
Class description:
Implement the ChiPubHealthSpider class.
Method signatures and docstrings:
- def start_urls(self): DPH generally uses a standard URL format, but sometimes deviates from the pattern. This property inserts the current year into the stand... | 611fce6a2705446e25a2fc33e32090a571eb35d1 | <|skeleton|>
class ChiPubHealthSpider:
def start_urls(self):
"""DPH generally uses a standard URL format, but sometimes deviates from the pattern. This property inserts the current year into the standard format, as well as known variants, in hopes DPH sticks to one of their conventions and this scraper doe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChiPubHealthSpider:
def start_urls(self):
"""DPH generally uses a standard URL format, but sometimes deviates from the pattern. This property inserts the current year into the standard format, as well as known variants, in hopes DPH sticks to one of their conventions and this scraper does not need to ... | the_stack_v2_python_sparse | city_scrapers/spiders/chi_pubhealth.py | City-Bureau/city-scrapers | train | 308 | |
2fae4983fba0c3f1e6384fa52990e36b107925d8 | [
"self.char = ''\nself.d = {}\nself.end = False",
"c, n = (word[0], len(word))\nnode = self.d.get(c)\nif not node:\n self.d[c] = Trie()\n self.d[c].char = c\n node = self.d[c]\nif n == 1:\n node.end = True\nelse:\n node.insert(word[1:])",
"node = self\nfor c in word:\n node = node.d.get(c)\n ... | <|body_start_0|>
self.char = ''
self.d = {}
self.end = False
<|end_body_0|>
<|body_start_1|>
c, n = (word[0], len(word))
node = self.d.get(c)
if not node:
self.d[c] = Trie()
self.d[c].char = c
node = self.d[c]
if n == 1:
... | Trie | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trie:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, word: str) -> None:
"""Inserts a word into the trie."""
<|body_1|>
def search(self, word: str) -> bool:
"""Returns if the word is in the trie."""
... | stack_v2_sparse_classes_75kplus_train_005791 | 1,311 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a word into the trie.",
"name": "insert",
"signature": "def insert(self, word: str) -> None"
},
{
"docstring": "Returns if the word is in the tr... | 4 | stack_v2_sparse_classes_30k_train_013025 | Implement the Python class `Trie` described below.
Class description:
Implement the Trie class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, word: str) -> None: Inserts a word into the trie.
- def search(self, word: str) -> bool: Returns if the word i... | Implement the Python class `Trie` described below.
Class description:
Implement the Trie class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, word: str) -> None: Inserts a word into the trie.
- def search(self, word: str) -> bool: Returns if the word i... | 12f62a218e827e6be2578b206dee9ce256da8d3d | <|skeleton|>
class Trie:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, word: str) -> None:
"""Inserts a word into the trie."""
<|body_1|>
def search(self, word: str) -> bool:
"""Returns if the word is in the trie."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Trie:
def __init__(self):
"""Initialize your data structure here."""
self.char = ''
self.d = {}
self.end = False
def insert(self, word: str) -> None:
"""Inserts a word into the trie."""
c, n = (word[0], len(word))
node = self.d.get(c)
if not... | the_stack_v2_python_sparse | Python3/0208_Implement_Trie.py | kiranani/playground | train | 0 | |
cc6af42850f5c651f32aed80b3d9829ddefb69b6 | [
"idxes = [e[0] for e in endpoints]\nassert idxes == sorted(idxes)\nself._interpolation = interpolation\nself._outside_value = outside_value\nself._endpoints = endpoints",
"for (l_t, l), (r_t, r) in zip(self._endpoints[:-1], self._endpoints[1:]):\n if l_t <= t and t < r_t:\n alpha = float(t - l_t) / (r_t... | <|body_start_0|>
idxes = [e[0] for e in endpoints]
assert idxes == sorted(idxes)
self._interpolation = interpolation
self._outside_value = outside_value
self._endpoints = endpoints
<|end_body_0|>
<|body_start_1|>
for (l_t, l), (r_t, r) in zip(self._endpoints[:-1], self._... | PiecewiseSchedule | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PiecewiseSchedule:
def __init__(self, endpoints, interpolation=linear_interpolation, outside_value=None):
"""Piecewise schedule. endpoints: [(int, int)] list of pairs `(time, value)` meanining that schedule should output `value` when `t==time`. All the values for time must be sorted in a... | stack_v2_sparse_classes_75kplus_train_005792 | 8,525 | no_license | [
{
"docstring": "Piecewise schedule. endpoints: [(int, int)] list of pairs `(time, value)` meanining that schedule should output `value` when `t==time`. All the values for time must be sorted in an increasing order. When t is between two times, e.g. `(time_a, value_a)` and `(time_b, value_b)`, such that `time_a ... | 2 | stack_v2_sparse_classes_30k_train_005442 | Implement the Python class `PiecewiseSchedule` described below.
Class description:
Implement the PiecewiseSchedule class.
Method signatures and docstrings:
- def __init__(self, endpoints, interpolation=linear_interpolation, outside_value=None): Piecewise schedule. endpoints: [(int, int)] list of pairs `(time, value)`... | Implement the Python class `PiecewiseSchedule` described below.
Class description:
Implement the PiecewiseSchedule class.
Method signatures and docstrings:
- def __init__(self, endpoints, interpolation=linear_interpolation, outside_value=None): Piecewise schedule. endpoints: [(int, int)] list of pairs `(time, value)`... | f1c28d9c135d98e9b0dca5f530c7d2186b8ef700 | <|skeleton|>
class PiecewiseSchedule:
def __init__(self, endpoints, interpolation=linear_interpolation, outside_value=None):
"""Piecewise schedule. endpoints: [(int, int)] list of pairs `(time, value)` meanining that schedule should output `value` when `t==time`. All the values for time must be sorted in a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PiecewiseSchedule:
def __init__(self, endpoints, interpolation=linear_interpolation, outside_value=None):
"""Piecewise schedule. endpoints: [(int, int)] list of pairs `(time, value)` meanining that schedule should output `value` when `t==time`. All the values for time must be sorted in an increasing o... | the_stack_v2_python_sparse | utils.py | YhsCandy/HouseNavAgent | train | 0 | |
6d5b82fcd467f7544606821183d3b08444962797 | [
"self.expiry_timestamp_msecs = expiry_timestamp_msecs\nself.hold_timestamp_msecs = hold_timestamp_msecs\nself.lock_timestamp_msecs = lock_timestamp_msecs\nself.mode = mode\nself.state = state",
"if dictionary is None:\n return None\nexpiry_timestamp_msecs = dictionary.get('expiryTimestampMsecs')\nhold_timestam... | <|body_start_0|>
self.expiry_timestamp_msecs = expiry_timestamp_msecs
self.hold_timestamp_msecs = hold_timestamp_msecs
self.lock_timestamp_msecs = lock_timestamp_msecs
self.mode = mode
self.state = state
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
... | Implementation of the 'FileLockStatus' model. Specifies the information of lock status for a file. Attributes: expiry_timestamp_msecs (long|int): Specifies a expiry timestamp in milliseconds until the file is locked. hold_timestamp_msecs (long|int): Specifies a override timestamp in milliseconds when an expired file is... | FileLockStatus | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileLockStatus:
"""Implementation of the 'FileLockStatus' model. Specifies the information of lock status for a file. Attributes: expiry_timestamp_msecs (long|int): Specifies a expiry timestamp in milliseconds until the file is locked. hold_timestamp_msecs (long|int): Specifies a override timesta... | stack_v2_sparse_classes_75kplus_train_005793 | 3,226 | permissive | [
{
"docstring": "Constructor for the FileLockStatus class",
"name": "__init__",
"signature": "def __init__(self, expiry_timestamp_msecs=None, hold_timestamp_msecs=None, lock_timestamp_msecs=None, mode=None, state=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: ... | 2 | stack_v2_sparse_classes_30k_val_000444 | Implement the Python class `FileLockStatus` described below.
Class description:
Implementation of the 'FileLockStatus' model. Specifies the information of lock status for a file. Attributes: expiry_timestamp_msecs (long|int): Specifies a expiry timestamp in milliseconds until the file is locked. hold_timestamp_msecs (... | Implement the Python class `FileLockStatus` described below.
Class description:
Implementation of the 'FileLockStatus' model. Specifies the information of lock status for a file. Attributes: expiry_timestamp_msecs (long|int): Specifies a expiry timestamp in milliseconds until the file is locked. hold_timestamp_msecs (... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class FileLockStatus:
"""Implementation of the 'FileLockStatus' model. Specifies the information of lock status for a file. Attributes: expiry_timestamp_msecs (long|int): Specifies a expiry timestamp in milliseconds until the file is locked. hold_timestamp_msecs (long|int): Specifies a override timesta... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FileLockStatus:
"""Implementation of the 'FileLockStatus' model. Specifies the information of lock status for a file. Attributes: expiry_timestamp_msecs (long|int): Specifies a expiry timestamp in milliseconds until the file is locked. hold_timestamp_msecs (long|int): Specifies a override timestamp in millise... | the_stack_v2_python_sparse | cohesity_management_sdk/models/file_lock_status.py | cohesity/management-sdk-python | train | 24 |
a639412340c7c976da22e0ae2f1cb875ddf94df8 | [
"r = Round.query.get(round_id)\nif r is not None:\n return r.reports_data()\nabort(404, 'Unknown round_id')",
"r = Round.query.get(round_id)\nif r is not None:\n r.heat_list_published = not r.heat_list_published\n db.session.commit()\n return OK\nabort(404, 'Unknown round_id')",
"r = Round.query.get... | <|body_start_0|>
r = Round.query.get(round_id)
if r is not None:
return r.reports_data()
abort(404, 'Unknown round_id')
<|end_body_0|>
<|body_start_1|>
r = Round.query.get(round_id)
if r is not None:
r.heat_list_published = not r.heat_list_published
... | RoundAPIReports | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoundAPIReports:
def get(self, round_id):
"""Get reports data"""
<|body_0|>
def patch(self, round_id):
"""Publishes or hides the heat list"""
<|body_1|>
def post(self, round_id):
"""Returns data to print reports"""
<|body_2|>
<|end_skele... | stack_v2_sparse_classes_75kplus_train_005794 | 25,303 | no_license | [
{
"docstring": "Get reports data",
"name": "get",
"signature": "def get(self, round_id)"
},
{
"docstring": "Publishes or hides the heat list",
"name": "patch",
"signature": "def patch(self, round_id)"
},
{
"docstring": "Returns data to print reports",
"name": "post",
"sig... | 3 | stack_v2_sparse_classes_30k_train_031693 | Implement the Python class `RoundAPIReports` described below.
Class description:
Implement the RoundAPIReports class.
Method signatures and docstrings:
- def get(self, round_id): Get reports data
- def patch(self, round_id): Publishes or hides the heat list
- def post(self, round_id): Returns data to print reports | Implement the Python class `RoundAPIReports` described below.
Class description:
Implement the RoundAPIReports class.
Method signatures and docstrings:
- def get(self, round_id): Get reports data
- def patch(self, round_id): Publishes or hides the heat list
- def post(self, round_id): Returns data to print reports
<... | 079b109fd13683a31d1d632faa5ab72cf0e78ddf | <|skeleton|>
class RoundAPIReports:
def get(self, round_id):
"""Get reports data"""
<|body_0|>
def patch(self, round_id):
"""Publishes or hides the heat list"""
<|body_1|>
def post(self, round_id):
"""Returns data to print reports"""
<|body_2|>
<|end_skele... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RoundAPIReports:
def get(self, round_id):
"""Get reports data"""
r = Round.query.get(round_id)
if r is not None:
return r.reports_data()
abort(404, 'Unknown round_id')
def patch(self, round_id):
"""Publishes or hides the heat list"""
r = Round.q... | the_stack_v2_python_sparse | backend/apis/round/apis.py | AlenAlic/DANCE | train | 0 | |
8e8882f1ef437e2cf4589b6cb9190bc70df1a60c | [
"if postorder:\n root = TreeNode(postorder.pop())\n ind = inorder.index(root.val)\n root.left = self.buildTree(inorder[:ind], postorder[:ind])\n root.right = self.buildTree(inorder[ind + 1:], postorder[ind:])\n return root\nreturn None",
"temp = []\nnodes = []\ncurrent = root\nwhile current:\n i... | <|body_start_0|>
if postorder:
root = TreeNode(postorder.pop())
ind = inorder.index(root.val)
root.left = self.buildTree(inorder[:ind], postorder[:ind])
root.right = self.buildTree(inorder[ind + 1:], postorder[ind:])
return root
return None
<|e... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def buildTree(self, inorder, postorder):
""":type inorder: List[int] :type postorder: List[int] :rtype: TreeNode"""
<|body_0|>
def inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_75kplus_train_005795 | 1,501 | no_license | [
{
"docstring": ":type inorder: List[int] :type postorder: List[int] :rtype: TreeNode",
"name": "buildTree",
"signature": "def buildTree(self, inorder, postorder)"
},
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "inorderTraversal",
"signature": "def inorderTraversal(se... | 2 | stack_v2_sparse_classes_30k_train_051870 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def buildTree(self, inorder, postorder): :type inorder: List[int] :type postorder: List[int] :rtype: TreeNode
- def inorderTraversal(self, root): :type root: TreeNode :rtype: Lis... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def buildTree(self, inorder, postorder): :type inorder: List[int] :type postorder: List[int] :rtype: TreeNode
- def inorderTraversal(self, root): :type root: TreeNode :rtype: Lis... | 6e4129d7c092be933497da2156680d25f72e42a4 | <|skeleton|>
class Solution:
def buildTree(self, inorder, postorder):
""":type inorder: List[int] :type postorder: List[int] :rtype: TreeNode"""
<|body_0|>
def inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def buildTree(self, inorder, postorder):
""":type inorder: List[int] :type postorder: List[int] :rtype: TreeNode"""
if postorder:
root = TreeNode(postorder.pop())
ind = inorder.index(root.val)
root.left = self.buildTree(inorder[:ind], postorder[:in... | the_stack_v2_python_sparse | 106_construct-binary-tree-from-inorder-and-postorder-traversal.py | setu4993/LeetCode | train | 0 | |
91c59f9b32e46ec836727fadd71e8d0c32f4b7e9 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn CloudAppSecuritySessionControl()",
"from .cloud_app_security_session_control_type import CloudAppSecuritySessionControlType\nfrom .conditional_access_session_control import ConditionalAccessSessionControl\nfrom .cloud_app_security_sess... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return CloudAppSecuritySessionControl()
<|end_body_0|>
<|body_start_1|>
from .cloud_app_security_session_control_type import CloudAppSecuritySessionControlType
from .conditional_access_session_... | CloudAppSecuritySessionControl | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CloudAppSecuritySessionControl:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CloudAppSecuritySessionControl:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator v... | stack_v2_sparse_classes_75kplus_train_005796 | 2,856 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: CloudAppSecuritySessionControl",
"name": "create_from_discriminator_value",
"signature": "def create_from_di... | 3 | stack_v2_sparse_classes_30k_train_027339 | Implement the Python class `CloudAppSecuritySessionControl` described below.
Class description:
Implement the CloudAppSecuritySessionControl class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CloudAppSecuritySessionControl: Creates a new instance of... | Implement the Python class `CloudAppSecuritySessionControl` described below.
Class description:
Implement the CloudAppSecuritySessionControl class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CloudAppSecuritySessionControl: Creates a new instance of... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class CloudAppSecuritySessionControl:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CloudAppSecuritySessionControl:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator v... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CloudAppSecuritySessionControl:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CloudAppSecuritySessionControl:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and creat... | the_stack_v2_python_sparse | msgraph/generated/models/cloud_app_security_session_control.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
202b6c8ea2cd12df4a1ed63eb25345dd2057e5bf | [
"if user_index >= self.num_users or following_index >= self.num_users:\n raise ValueError(f'Number of users is {self.num_users}, but indices {user_index} and {following_index} were requested.')\nif self.users_hat[following_index, user_index] == 0:\n self.users_hat[following_index, user_index] = 1\nelif self.i... | <|body_start_0|>
if user_index >= self.num_users or following_index >= self.num_users:
raise ValueError(f'Number of users is {self.num_users}, but indices {user_index} and {following_index} were requested.')
if self.users_hat[following_index, user_index] == 0:
self.users_hat[foll... | A mixin for classes with a :attr:`~trecs.models.recommender.BaseRecommender.users_hat` attribute to gain the basic functionality of a binary social graph. It assumes a network adjacency matrix of size `|U|x|U|`. | BinarySocialGraph | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinarySocialGraph:
"""A mixin for classes with a :attr:`~trecs.models.recommender.BaseRecommender.users_hat` attribute to gain the basic functionality of a binary social graph. It assumes a network adjacency matrix of size `|U|x|U|`."""
def follow(self, user_index, following_index):
... | stack_v2_sparse_classes_75kplus_train_005797 | 5,088 | permissive | [
{
"docstring": "Method to follow another user -- that is, to create a unidirectional link from one user to the other. Parameters ---------- user_index: int Index of the user initiating the follow. following_index: int Index of the user to be followed. Raises ------ ValueError If either of the user indices does ... | 4 | stack_v2_sparse_classes_30k_train_028411 | Implement the Python class `BinarySocialGraph` described below.
Class description:
A mixin for classes with a :attr:`~trecs.models.recommender.BaseRecommender.users_hat` attribute to gain the basic functionality of a binary social graph. It assumes a network adjacency matrix of size `|U|x|U|`.
Method signatures and d... | Implement the Python class `BinarySocialGraph` described below.
Class description:
A mixin for classes with a :attr:`~trecs.models.recommender.BaseRecommender.users_hat` attribute to gain the basic functionality of a binary social graph. It assumes a network adjacency matrix of size `|U|x|U|`.
Method signatures and d... | c4db28013f397ccad9eb5f5e530ca301599f36fb | <|skeleton|>
class BinarySocialGraph:
"""A mixin for classes with a :attr:`~trecs.models.recommender.BaseRecommender.users_hat` attribute to gain the basic functionality of a binary social graph. It assumes a network adjacency matrix of size `|U|x|U|`."""
def follow(self, user_index, following_index):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BinarySocialGraph:
"""A mixin for classes with a :attr:`~trecs.models.recommender.BaseRecommender.users_hat` attribute to gain the basic functionality of a binary social graph. It assumes a network adjacency matrix of size `|U|x|U|`."""
def follow(self, user_index, following_index):
"""Method to ... | the_stack_v2_python_sparse | trecs/components/socialgraph.py | amywinecoff/t-recs | train | 1 |
8136a2f9a9f1918c102aebeb74c9a52c3b804e99 | [
"self.label = label.upper()\nself.datee = upcomming(datee)\nself.dist = cal_dist(self.datee)\nself.dist_months = cal_months(self.dist.days)\nself.date_formated = d_format(self.datee)\nself.day_of_week = day_of_week(self.datee)",
"print(f'{self.label:} {self.date_formated} {self.day_of_week}')\nprint(f'- {self.dis... | <|body_start_0|>
self.label = label.upper()
self.datee = upcomming(datee)
self.dist = cal_dist(self.datee)
self.dist_months = cal_months(self.dist.days)
self.date_formated = d_format(self.datee)
self.day_of_week = day_of_week(self.datee)
<|end_body_0|>
<|body_start_1|>
... | Event | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Event:
def __init__(self, label, datee):
"""Individual Event information"""
<|body_0|>
def display(self):
"""Displays the distance between Event date and current date"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.label = label.upper()
... | stack_v2_sparse_classes_75kplus_train_005798 | 3,191 | no_license | [
{
"docstring": "Individual Event information",
"name": "__init__",
"signature": "def __init__(self, label, datee)"
},
{
"docstring": "Displays the distance between Event date and current date",
"name": "display",
"signature": "def display(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_039220 | Implement the Python class `Event` described below.
Class description:
Implement the Event class.
Method signatures and docstrings:
- def __init__(self, label, datee): Individual Event information
- def display(self): Displays the distance between Event date and current date | Implement the Python class `Event` described below.
Class description:
Implement the Event class.
Method signatures and docstrings:
- def __init__(self, label, datee): Individual Event information
- def display(self): Displays the distance between Event date and current date
<|skeleton|>
class Event:
def __init... | ea13e7f8151d0a10cbf5386baf21e2188bc454f9 | <|skeleton|>
class Event:
def __init__(self, label, datee):
"""Individual Event information"""
<|body_0|>
def display(self):
"""Displays the distance between Event date and current date"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Event:
def __init__(self, label, datee):
"""Individual Event information"""
self.label = label.upper()
self.datee = upcomming(datee)
self.dist = cal_dist(self.datee)
self.dist_months = cal_months(self.dist.days)
self.date_formated = d_format(self.datee)
... | the_stack_v2_python_sparse | calendar_class.py | shadowthebat/Calendar_countdown | train | 0 | |
b84ec2a98a59171eddcb784a24b3bb176f804cff | [
"x = x.contiguous()\nrois = rois.contiguous()\nin_size = B, C, H, W = x.size()\nN = rois.size(0)\nif C % (Info.group_size * Info.group_size) != 0:\n raise ValueError('The group_size must be an integral multiple of input_channel!')\nout_dim = C // (Info.group_size * Info.group_size)\noutput = t.zeros(N, out_dim, ... | <|body_start_0|>
x = x.contiguous()
rois = rois.contiguous()
in_size = B, C, H, W = x.size()
N = rois.size(0)
if C % (Info.group_size * Info.group_size) != 0:
raise ValueError('The group_size must be an integral multiple of input_channel!')
out_dim = C // (Inf... | psRoI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class psRoI:
def forward(ctx, x, rois, Info: psRoI_Info):
""":param ctx: context variable(similar to 'self') :param x: input feature map :param rois: rois generated by rpn, note:this 'rois' is indices_and_rois combined indexes and rois ==> [batch_ind, x_min, y_min, x_max, y_max] :return:"""
... | stack_v2_sparse_classes_75kplus_train_005799 | 7,285 | permissive | [
{
"docstring": ":param ctx: context variable(similar to 'self') :param x: input feature map :param rois: rois generated by rpn, note:this 'rois' is indices_and_rois combined indexes and rois ==> [batch_ind, x_min, y_min, x_max, y_max] :return:",
"name": "forward",
"signature": "def forward(ctx, x, rois,... | 2 | stack_v2_sparse_classes_30k_train_030853 | Implement the Python class `psRoI` described below.
Class description:
Implement the psRoI class.
Method signatures and docstrings:
- def forward(ctx, x, rois, Info: psRoI_Info): :param ctx: context variable(similar to 'self') :param x: input feature map :param rois: rois generated by rpn, note:this 'rois' is indices... | Implement the Python class `psRoI` described below.
Class description:
Implement the psRoI class.
Method signatures and docstrings:
- def forward(ctx, x, rois, Info: psRoI_Info): :param ctx: context variable(similar to 'self') :param x: input feature map :param rois: rois generated by rpn, note:this 'rois' is indices... | 481439bfc88b35a27c9c74aa64823c21dabb9c88 | <|skeleton|>
class psRoI:
def forward(ctx, x, rois, Info: psRoI_Info):
""":param ctx: context variable(similar to 'self') :param x: input feature map :param rois: rois generated by rpn, note:this 'rois' is indices_and_rois combined indexes and rois ==> [batch_ind, x_min, y_min, x_max, y_max] :return:"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class psRoI:
def forward(ctx, x, rois, Info: psRoI_Info):
""":param ctx: context variable(similar to 'self') :param x: input feature map :param rois: rois generated by rpn, note:this 'rois' is indices_and_rois combined indexes and rois ==> [batch_ind, x_min, y_min, x_max, y_max] :return:"""
x = x.co... | the_stack_v2_python_sparse | utils/psroi_module.py | elbert-xiao/Simple-RFCN-PyTorch | train | 14 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.