blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a50606d4829c6c0e7e8ae375b078b6975e49f490 | [
"loop = self._get_loop(loop)\nif not loop:\n super(AsyncioContextProvider, self).activate(context)\n return context\ntask = asyncio.Task.current_task(loop=loop)\nif task:\n setattr(task, self._CONTEXT_ATTR, context)\nreturn context",
"try:\n return loop or asyncio.get_event_loop()\nexcept RuntimeError... | <|body_start_0|>
loop = self._get_loop(loop)
if not loop:
super(AsyncioContextProvider, self).activate(context)
return context
task = asyncio.Task.current_task(loop=loop)
if task:
setattr(task, self._CONTEXT_ATTR, context)
return context
<|end_... | Manages the active context for asyncio execution. Framework instrumentation that is built on top of the ``asyncio`` library, should use this provider when contextvars are not available (Python versions less than 3.7). This Context Provider inherits from ``DefaultContextProvider`` because it uses a thread-local storage ... | AsyncioContextProvider | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsyncioContextProvider:
"""Manages the active context for asyncio execution. Framework instrumentation that is built on top of the ``asyncio`` library, should use this provider when contextvars are not available (Python versions less than 3.7). This Context Provider inherits from ``DefaultContext... | stack_v2_sparse_classes_36k_train_032600 | 2,855 | permissive | [
{
"docstring": "Sets the scoped ``Context`` for the current running ``Task``.",
"name": "activate",
"signature": "def activate(self, context, loop=None)"
},
{
"docstring": "Helper to try and resolve the current loop",
"name": "_get_loop",
"signature": "def _get_loop(self, loop=None)"
}... | 4 | null | Implement the Python class `AsyncioContextProvider` described below.
Class description:
Manages the active context for asyncio execution. Framework instrumentation that is built on top of the ``asyncio`` library, should use this provider when contextvars are not available (Python versions less than 3.7). This Context ... | Implement the Python class `AsyncioContextProvider` described below.
Class description:
Manages the active context for asyncio execution. Framework instrumentation that is built on top of the ``asyncio`` library, should use this provider when contextvars are not available (Python versions less than 3.7). This Context ... | 1e3bd6d4edef5cda5a0831a6a7ec8e4046659d17 | <|skeleton|>
class AsyncioContextProvider:
"""Manages the active context for asyncio execution. Framework instrumentation that is built on top of the ``asyncio`` library, should use this provider when contextvars are not available (Python versions less than 3.7). This Context Provider inherits from ``DefaultContext... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AsyncioContextProvider:
"""Manages the active context for asyncio execution. Framework instrumentation that is built on top of the ``asyncio`` library, should use this provider when contextvars are not available (Python versions less than 3.7). This Context Provider inherits from ``DefaultContextProvider`` be... | the_stack_v2_python_sparse | ddtrace/contrib/asyncio/provider.py | DataDog/dd-trace-py | train | 461 |
2946bafeae85c964b419590530fb04836e1a7f69 | [
"if len(A) <= 1:\n return 0\nA = sorted(A)\n\ndef min_len(low_1, high_1, low_2, high_2, K):\n assert low_2 - low_1 >= 0\n temp = low_2 - low_1\n if temp <= 2 * K:\n if temp % 2 == 0:\n return max(high_2 - low_2, high_1 - low_1)\n else:\n print('temp', temp)\n ... | <|body_start_0|>
if len(A) <= 1:
return 0
A = sorted(A)
def min_len(low_1, high_1, low_2, high_2, K):
assert low_2 - low_1 >= 0
temp = low_2 - low_1
if temp <= 2 * K:
if temp % 2 == 0:
return max(high_2 - low_2,... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def smallestRangeII(self, A, K):
"""理解错误,我选择的是0-K范围内的,使得整个最小,而题目是给定了K :type A: List[int] :type K: int :rtype: int"""
<|body_0|>
def smallestRangeII_1(self, A, K):
""":type A: List[int] :type K: int :rtype: int 72 ms"""
<|body_1|>
def smallestRa... | stack_v2_sparse_classes_36k_train_032601 | 3,372 | no_license | [
{
"docstring": "理解错误,我选择的是0-K范围内的,使得整个最小,而题目是给定了K :type A: List[int] :type K: int :rtype: int",
"name": "smallestRangeII",
"signature": "def smallestRangeII(self, A, K)"
},
{
"docstring": ":type A: List[int] :type K: int :rtype: int 72 ms",
"name": "smallestRangeII_1",
"signature": "def ... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def smallestRangeII(self, A, K): 理解错误,我选择的是0-K范围内的,使得整个最小,而题目是给定了K :type A: List[int] :type K: int :rtype: int
- def smallestRangeII_1(self, A, K): :type A: List[int] :type K: in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def smallestRangeII(self, A, K): 理解错误,我选择的是0-K范围内的,使得整个最小,而题目是给定了K :type A: List[int] :type K: int :rtype: int
- def smallestRangeII_1(self, A, K): :type A: List[int] :type K: in... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def smallestRangeII(self, A, K):
"""理解错误,我选择的是0-K范围内的,使得整个最小,而题目是给定了K :type A: List[int] :type K: int :rtype: int"""
<|body_0|>
def smallestRangeII_1(self, A, K):
""":type A: List[int] :type K: int :rtype: int 72 ms"""
<|body_1|>
def smallestRa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def smallestRangeII(self, A, K):
"""理解错误,我选择的是0-K范围内的,使得整个最小,而题目是给定了K :type A: List[int] :type K: int :rtype: int"""
if len(A) <= 1:
return 0
A = sorted(A)
def min_len(low_1, high_1, low_2, high_2, K):
assert low_2 - low_1 >= 0
tem... | the_stack_v2_python_sparse | SmallestRangeII_MID_910.py | 953250587/leetcode-python | train | 2 | |
366e978d701a42be3f16784c986fe28b292c6663 | [
"check_type(logits, 'logits', (np.ndarray, tensor.Variable, list), 'Categorical')\nif self._validate_args(logits):\n self.logits = logits\nelse:\n self.logits = self._to_variable(logits)[0]",
"check_type(other, 'other', Categorical, 'kl_divergence')\nlogits = self.logits - nn.reduce_max(self.logits, dim=-1,... | <|body_start_0|>
check_type(logits, 'logits', (np.ndarray, tensor.Variable, list), 'Categorical')
if self._validate_args(logits):
self.logits = logits
else:
self.logits = self._to_variable(logits)[0]
<|end_body_0|>
<|body_start_1|>
check_type(other, 'other', Cate... | Categorical distribution is a discrete probability distribution that describes the possible results of a random variable that can take on one of K possible categories, with the probability of each category separately specified. The probability mass function (pmf) is: .. math:: pmf(k; p_i) = \\prod_{i=1}^{k} p_i^{[x=i]}... | Categorical | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Categorical:
"""Categorical distribution is a discrete probability distribution that describes the possible results of a random variable that can take on one of K possible categories, with the probability of each category separately specified. The probability mass function (pmf) is: .. math:: pmf... | stack_v2_sparse_classes_36k_train_032602 | 22,509 | permissive | [
{
"docstring": "Args: logits(list|numpy.ndarray|Variable): The logits input of categorical distribution. The data type is float32.",
"name": "__init__",
"signature": "def __init__(self, logits)"
},
{
"docstring": "The KL-divergence between two Categorical distributions. Args: other (Categorical)... | 3 | stack_v2_sparse_classes_30k_train_010209 | Implement the Python class `Categorical` described below.
Class description:
Categorical distribution is a discrete probability distribution that describes the possible results of a random variable that can take on one of K possible categories, with the probability of each category separately specified. The probabilit... | Implement the Python class `Categorical` described below.
Class description:
Categorical distribution is a discrete probability distribution that describes the possible results of a random variable that can take on one of K possible categories, with the probability of each category separately specified. The probabilit... | a1b640bc66a5cc9583de503e7406aeba67565e8d | <|skeleton|>
class Categorical:
"""Categorical distribution is a discrete probability distribution that describes the possible results of a random variable that can take on one of K possible categories, with the probability of each category separately specified. The probability mass function (pmf) is: .. math:: pmf... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Categorical:
"""Categorical distribution is a discrete probability distribution that describes the possible results of a random variable that can take on one of K possible categories, with the probability of each category separately specified. The probability mass function (pmf) is: .. math:: pmf(k; p_i) = \\... | the_stack_v2_python_sparse | python/paddle/fluid/layers/distributions.py | hutuxian/Paddle | train | 8 |
e7f94c9341cf37b7c81fc3f0c768eb2154c4ef14 | [
"super().__init__()\nself.input_dim = input_dim\nself.hidden_dim = hidden_dim\nself.rep_dim = rep_dim\nself.encoder = nn.Sequential(nn.Linear(self.input_dim, self.hidden_dim), nn.ReLU(), nn.Linear(self.hidden_dim, self.rep_dim))\nself.encoder_r_z = nn.Linear(self.rep_dim, self.rep_dim)",
"encoder_input = torch.ca... | <|body_start_0|>
super().__init__()
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.rep_dim = rep_dim
self.encoder = nn.Sequential(nn.Linear(self.input_dim, self.hidden_dim), nn.ReLU(), nn.Linear(self.hidden_dim, self.rep_dim))
self.encoder_r_z = nn.Linear(se... | Deterministic Encoder | Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
"""Deterministic Encoder"""
def __init__(self, input_dim, hidden_dim, rep_dim):
"""Np deterministic encoder Args: input_dim : x_dim + y_dim hidden_dim : hidden_dim rep_dim : representation dim layer_sizes : the array of each lyaer size in encoding MLP"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_032603 | 12,534 | no_license | [
{
"docstring": "Np deterministic encoder Args: input_dim : x_dim + y_dim hidden_dim : hidden_dim rep_dim : representation dim layer_sizes : the array of each lyaer size in encoding MLP",
"name": "__init__",
"signature": "def __init__(self, input_dim, hidden_dim, rep_dim)"
},
{
"docstring": "Ecod... | 2 | stack_v2_sparse_classes_30k_train_013770 | Implement the Python class `Encoder` described below.
Class description:
Deterministic Encoder
Method signatures and docstrings:
- def __init__(self, input_dim, hidden_dim, rep_dim): Np deterministic encoder Args: input_dim : x_dim + y_dim hidden_dim : hidden_dim rep_dim : representation dim layer_sizes : the array o... | Implement the Python class `Encoder` described below.
Class description:
Deterministic Encoder
Method signatures and docstrings:
- def __init__(self, input_dim, hidden_dim, rep_dim): Np deterministic encoder Args: input_dim : x_dim + y_dim hidden_dim : hidden_dim rep_dim : representation dim layer_sizes : the array o... | c7e1bfb49ebaec6937ed7b186689227f95a43e0f | <|skeleton|>
class Encoder:
"""Deterministic Encoder"""
def __init__(self, input_dim, hidden_dim, rep_dim):
"""Np deterministic encoder Args: input_dim : x_dim + y_dim hidden_dim : hidden_dim rep_dim : representation dim layer_sizes : the array of each lyaer size in encoding MLP"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Encoder:
"""Deterministic Encoder"""
def __init__(self, input_dim, hidden_dim, rep_dim):
"""Np deterministic encoder Args: input_dim : x_dim + y_dim hidden_dim : hidden_dim rep_dim : representation dim layer_sizes : the array of each lyaer size in encoding MLP"""
super().__init__()
... | the_stack_v2_python_sparse | model/CNP/cnp.py | MingyuKim87/MLwM | train | 0 |
dc89d15012ae5c5d3dad65a971802ab2e38cc38d | [
"self.model = model\npath = self.model_path()\nself.tool = Model.load(path)\nif not self.tool:\n raise IOError(\"Cannot load model from file '%s'\" % path)\nself.error = ProcessingError()\nself.conllu_reader = ConlluReader()\nself.tokenizer = self.tool.newTokenizer(Model.DEFAULT)",
"if self.model.startswith('/... | <|body_start_0|>
self.model = model
path = self.model_path()
self.tool = Model.load(path)
if not self.tool:
raise IOError("Cannot load model from file '%s'" % path)
self.error = ProcessingError()
self.conllu_reader = ConlluReader()
self.tokenizer = sel... | Wrapper for UDPipe (more pythonic than ufal.udpipe). | UDPipe | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UDPipe:
"""Wrapper for UDPipe (more pythonic than ufal.udpipe)."""
def __init__(self, model):
"""Create the UDPipe tool object."""
<|body_0|>
def model_path(self):
"""Return absolute path to the model file to be loaded."""
<|body_1|>
def tag_parse_tr... | stack_v2_sparse_classes_36k_train_032604 | 3,919 | no_license | [
{
"docstring": "Create the UDPipe tool object.",
"name": "__init__",
"signature": "def __init__(self, model)"
},
{
"docstring": "Return absolute path to the model file to be loaded.",
"name": "model_path",
"signature": "def model_path(self)"
},
{
"docstring": "Tag (+lemmatize, fi... | 4 | stack_v2_sparse_classes_30k_train_011203 | Implement the Python class `UDPipe` described below.
Class description:
Wrapper for UDPipe (more pythonic than ufal.udpipe).
Method signatures and docstrings:
- def __init__(self, model): Create the UDPipe tool object.
- def model_path(self): Return absolute path to the model file to be loaded.
- def tag_parse_tree(s... | Implement the Python class `UDPipe` described below.
Class description:
Wrapper for UDPipe (more pythonic than ufal.udpipe).
Method signatures and docstrings:
- def __init__(self, model): Create the UDPipe tool object.
- def model_path(self): Return absolute path to the model file to be loaded.
- def tag_parse_tree(s... | 91c554a11943dbf7cb259b803821ea4762756b15 | <|skeleton|>
class UDPipe:
"""Wrapper for UDPipe (more pythonic than ufal.udpipe)."""
def __init__(self, model):
"""Create the UDPipe tool object."""
<|body_0|>
def model_path(self):
"""Return absolute path to the model file to be loaded."""
<|body_1|>
def tag_parse_tr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UDPipe:
"""Wrapper for UDPipe (more pythonic than ufal.udpipe)."""
def __init__(self, model):
"""Create the UDPipe tool object."""
self.model = model
path = self.model_path()
self.tool = Model.load(path)
if not self.tool:
raise IOError("Cannot load mode... | the_stack_v2_python_sparse | udapi/tool/udpipe.py | dan-zeman/udapi-python | train | 1 |
14dd151a0494de19546dc8c6a3aa2a485bc0609f | [
"tweet = line.split(',')[1].lower()\ntweet = re.sub('[^a-z 0-9]', '', tweet)\nyield ('chars', len(tweet))",
"tweet_total = 0\nchar_total = 0\nfor i in values:\n tweet_total += 1\n char_total += i\nyield ('average_tweet_length:', char_total / float(tweet_total))"
] | <|body_start_0|>
tweet = line.split(',')[1].lower()
tweet = re.sub('[^a-z 0-9]', '', tweet)
yield ('chars', len(tweet))
<|end_body_0|>
<|body_start_1|>
tweet_total = 0
char_total = 0
for i in values:
tweet_total += 1
char_total += i
yield ... | MRCharAverageCount | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MRCharAverageCount:
def mapper(self, _, line):
"""Parse tweet from csv, remove non-alphanumeric characters, and return total number of characters per tweet in k/v pair"""
<|body_0|>
def reducer(self, key, values):
"""aggregate total character count across all tweets,... | stack_v2_sparse_classes_36k_train_032605 | 1,180 | no_license | [
{
"docstring": "Parse tweet from csv, remove non-alphanumeric characters, and return total number of characters per tweet in k/v pair",
"name": "mapper",
"signature": "def mapper(self, _, line)"
},
{
"docstring": "aggregate total character count across all tweets, total number of tweets, and div... | 2 | stack_v2_sparse_classes_30k_train_007116 | Implement the Python class `MRCharAverageCount` described below.
Class description:
Implement the MRCharAverageCount class.
Method signatures and docstrings:
- def mapper(self, _, line): Parse tweet from csv, remove non-alphanumeric characters, and return total number of characters per tweet in k/v pair
- def reducer... | Implement the Python class `MRCharAverageCount` described below.
Class description:
Implement the MRCharAverageCount class.
Method signatures and docstrings:
- def mapper(self, _, line): Parse tweet from csv, remove non-alphanumeric characters, and return total number of characters per tweet in k/v pair
- def reducer... | a0706171ec7d502eb85397862b1daf9912ac15a5 | <|skeleton|>
class MRCharAverageCount:
def mapper(self, _, line):
"""Parse tweet from csv, remove non-alphanumeric characters, and return total number of characters per tweet in k/v pair"""
<|body_0|>
def reducer(self, key, values):
"""aggregate total character count across all tweets,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MRCharAverageCount:
def mapper(self, _, line):
"""Parse tweet from csv, remove non-alphanumeric characters, and return total number of characters per tweet in k/v pair"""
tweet = line.split(',')[1].lower()
tweet = re.sub('[^a-z 0-9]', '', tweet)
yield ('chars', len(tweet))
... | the_stack_v2_python_sparse | character_count.py | nickhamlin/MIDS-W205_A4 | train | 0 | |
9e6114ae1c4cbebd1924f31457e2f698ee74b065 | [
"mad = signals.sub(signals.median(axis=1), axis=0).abs().median(axis=1)\nself.thresholds = mad * self.n_mad\nspikes[spikes.le(self.thresholds, axis=0)] = 0\nreturn spikes",
"spikes = super().calculate(signals)\ntry:\n return self._mad_filter_spikes(signals - self.baseline, spikes)\nexcept AttributeError:\n ... | <|body_start_0|>
mad = signals.sub(signals.median(axis=1), axis=0).abs().median(axis=1)
self.thresholds = mad * self.n_mad
spikes[spikes.le(self.thresholds, axis=0)] = 0
return spikes
<|end_body_0|>
<|body_start_1|>
spikes = super().calculate(signals)
try:
re... | Mixin that adds an additional spike filtering step following inference, by discarding spikes with amplitude less than some threshold number of median absolute deviations from the original trace. Since we override the calculate method, this should be positioned first in the inheritance list when subclassing. Derived cla... | MADMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MADMixin:
"""Mixin that adds an additional spike filtering step following inference, by discarding spikes with amplitude less than some threshold number of median absolute deviations from the original trace. Since we override the calculate method, this should be positioned first in the inheritanc... | stack_v2_sparse_classes_36k_train_032606 | 8,181 | no_license | [
{
"docstring": "Do MAD filtering",
"name": "_mad_filter_spikes",
"signature": "def _mad_filter_spikes(self, signals, spikes)"
},
{
"docstring": "Calculates spikes and applies MAD filtering, if the n_mad attribute exists",
"name": "calculate",
"signature": "def calculate(self, signals)"
... | 2 | stack_v2_sparse_classes_30k_train_016173 | Implement the Python class `MADMixin` described below.
Class description:
Mixin that adds an additional spike filtering step following inference, by discarding spikes with amplitude less than some threshold number of median absolute deviations from the original trace. Since we override the calculate method, this shoul... | Implement the Python class `MADMixin` described below.
Class description:
Mixin that adds an additional spike filtering step following inference, by discarding spikes with amplitude less than some threshold number of median absolute deviations from the original trace. Since we override the calculate method, this shoul... | a04e357905cacc1efd75ec96ffcb6e293bb71ab9 | <|skeleton|>
class MADMixin:
"""Mixin that adds an additional spike filtering step following inference, by discarding spikes with amplitude less than some threshold number of median absolute deviations from the original trace. Since we override the calculate method, this should be positioned first in the inheritanc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MADMixin:
"""Mixin that adds an additional spike filtering step following inference, by discarding spikes with amplitude less than some threshold number of median absolute deviations from the original trace. Since we override the calculate method, this should be positioned first in the inheritance list when s... | the_stack_v2_python_sparse | lab3/lab3/signal/spikes.py | james-priestley/ca1_novelty_analysis | train | 0 |
9e3b840c54734cffbcb4fa7481f0ee433f2b74f0 | [
"super(BinaryFocalLoss, self).__init__(name=name)\nself.gamma = gamma\nself.alpha = alpha",
"y_true = tf.cast(y_true, tf.float32)\nepsilon = K.epsilon()\ny_pred = K.clip(y_pred, epsilon, 1.0 - epsilon)\np_t = tf.where(K.equal(y_true, 1), y_pred, 1 - y_pred)\nalpha_factor = K.ones_like(y_true) * self.alpha\nalpha_... | <|body_start_0|>
super(BinaryFocalLoss, self).__init__(name=name)
self.gamma = gamma
self.alpha = alpha
<|end_body_0|>
<|body_start_1|>
y_true = tf.cast(y_true, tf.float32)
epsilon = K.epsilon()
y_pred = K.clip(y_pred, epsilon, 1.0 - epsilon)
p_t = tf.where(K.equ... | Implementation of simple binary focal loss. | BinaryFocalLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinaryFocalLoss:
"""Implementation of simple binary focal loss."""
def __init__(self, name=None, gamma=2.0, alpha=0.25):
""":param name: displayed name for loss function :param gamma: gamma constant used in focal loss. gamma > 0 reduces the relative loss for well-classified examples ... | stack_v2_sparse_classes_36k_train_032607 | 3,619 | permissive | [
{
"docstring": ":param name: displayed name for loss function :param gamma: gamma constant used in focal loss. gamma > 0 reduces the relative loss for well-classified examples (p>0.5) putting more focus on hard misclassified example :param alpha: alpha constant used in focal loss equation. scalar factor to redu... | 2 | stack_v2_sparse_classes_30k_train_000482 | Implement the Python class `BinaryFocalLoss` described below.
Class description:
Implementation of simple binary focal loss.
Method signatures and docstrings:
- def __init__(self, name=None, gamma=2.0, alpha=0.25): :param name: displayed name for loss function :param gamma: gamma constant used in focal loss. gamma > ... | Implement the Python class `BinaryFocalLoss` described below.
Class description:
Implementation of simple binary focal loss.
Method signatures and docstrings:
- def __init__(self, name=None, gamma=2.0, alpha=0.25): :param name: displayed name for loss function :param gamma: gamma constant used in focal loss. gamma > ... | 391b4d84c9994e9abda64c6e48f2eac6b374b052 | <|skeleton|>
class BinaryFocalLoss:
"""Implementation of simple binary focal loss."""
def __init__(self, name=None, gamma=2.0, alpha=0.25):
""":param name: displayed name for loss function :param gamma: gamma constant used in focal loss. gamma > 0 reduces the relative loss for well-classified examples ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BinaryFocalLoss:
"""Implementation of simple binary focal loss."""
def __init__(self, name=None, gamma=2.0, alpha=0.25):
""":param name: displayed name for loss function :param gamma: gamma constant used in focal loss. gamma > 0 reduces the relative loss for well-classified examples (p>0.5) putti... | the_stack_v2_python_sparse | losses/focal_loss.py | Barchid/Indoor_Segmentation | train | 2 |
b317920e0921b5cc8e78bd74714dde79cd8a7871 | [
"self.teacher_model = teacher_model\nif 'args' in kwargs:\n assert isinstance(kwargs['args'], DistillerTrainingArguments), '`args` should be an instance of `DistillerTrainingArguments`.'\nelse:\n kwargs['args'] = DistillerTrainingArguments('tmp')\nsuper().__init__(**kwargs)",
"student_outputs = model(**inpu... | <|body_start_0|>
self.teacher_model = teacher_model
if 'args' in kwargs:
assert isinstance(kwargs['args'], DistillerTrainingArguments), '`args` should be an instance of `DistillerTrainingArguments`.'
else:
kwargs['args'] = DistillerTrainingArguments('tmp')
super()... | Hugging Face distillation-based trainer. | HfDistillerTrainer | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LGPL-2.1-or-later",
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HfDistillerTrainer:
"""Hugging Face distillation-based trainer."""
def __init__(self, teacher_model: torch.nn.Module, **kwargs) -> None:
"""Initialize Hugging Face distillation-based trainer. Args: teacher_model: Pre-trained teacher model."""
<|body_0|>
def compute_loss(... | stack_v2_sparse_classes_36k_train_032608 | 4,544 | permissive | [
{
"docstring": "Initialize Hugging Face distillation-based trainer. Args: teacher_model: Pre-trained teacher model.",
"name": "__init__",
"signature": "def __init__(self, teacher_model: torch.nn.Module, **kwargs) -> None"
},
{
"docstring": "Override the computation of the loss function. The loss... | 2 | stack_v2_sparse_classes_30k_train_004937 | Implement the Python class `HfDistillerTrainer` described below.
Class description:
Hugging Face distillation-based trainer.
Method signatures and docstrings:
- def __init__(self, teacher_model: torch.nn.Module, **kwargs) -> None: Initialize Hugging Face distillation-based trainer. Args: teacher_model: Pre-trained te... | Implement the Python class `HfDistillerTrainer` described below.
Class description:
Hugging Face distillation-based trainer.
Method signatures and docstrings:
- def __init__(self, teacher_model: torch.nn.Module, **kwargs) -> None: Initialize Hugging Face distillation-based trainer. Args: teacher_model: Pre-trained te... | 95d6e19a1523a701b3fbc249dd1a7d1e7ba44aee | <|skeleton|>
class HfDistillerTrainer:
"""Hugging Face distillation-based trainer."""
def __init__(self, teacher_model: torch.nn.Module, **kwargs) -> None:
"""Initialize Hugging Face distillation-based trainer. Args: teacher_model: Pre-trained teacher model."""
<|body_0|>
def compute_loss(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HfDistillerTrainer:
"""Hugging Face distillation-based trainer."""
def __init__(self, teacher_model: torch.nn.Module, **kwargs) -> None:
"""Initialize Hugging Face distillation-based trainer. Args: teacher_model: Pre-trained teacher model."""
self.teacher_model = teacher_model
if ... | the_stack_v2_python_sparse | archai/trainers/nlp/hf_trainer.py | microsoft/archai | train | 439 |
6d0946232c0bbb3988daacfd5ddc13314dba2110 | [
"self.scipy = scipy\nself.data = data\nself.mu = mu\nself.sigma = sigma\nself.log = log\nself.info = info\nself.epsilon = epsilon",
"if self.data is None:\n output = gaussian(x, scipy=self.scipy, data=self.data, mu=self.mu[idx], sigma=self.sigma[idx], log=self.log, info=self.info, epsilon=self.epsilon)\nelse:\... | <|body_start_0|>
self.scipy = scipy
self.data = data
self.mu = mu
self.sigma = sigma
self.log = log
self.info = info
self.epsilon = epsilon
<|end_body_0|>
<|body_start_1|>
if self.data is None:
output = gaussian(x, scipy=self.scipy, data=self.... | GaussianDistribution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianDistribution:
def __init__(self, scipy=False, data=None, mu=None, sigma=None, log=False, info=False, epsilon=1e-08):
"""Class for passing values through a Gaussian distribution, uses gaussian function. made this so I could use gaussian as a method For this class, training occurs ... | stack_v2_sparse_classes_36k_train_032609 | 47,457 | no_license | [
{
"docstring": "Class for passing values through a Gaussian distribution, uses gaussian function. made this so I could use gaussian as a method For this class, training occurs inside forward *Unimodal and univariate* Inputs: scipy (bool): if True use scipy's pdf functions, use custom is False see: https://docs.... | 2 | stack_v2_sparse_classes_30k_train_002955 | Implement the Python class `GaussianDistribution` described below.
Class description:
Implement the GaussianDistribution class.
Method signatures and docstrings:
- def __init__(self, scipy=False, data=None, mu=None, sigma=None, log=False, info=False, epsilon=1e-08): Class for passing values through a Gaussian distrib... | Implement the Python class `GaussianDistribution` described below.
Class description:
Implement the GaussianDistribution class.
Method signatures and docstrings:
- def __init__(self, scipy=False, data=None, mu=None, sigma=None, log=False, info=False, epsilon=1e-08): Class for passing values through a Gaussian distrib... | ad713e4eb15a2d9573622bace528fc86e19a6545 | <|skeleton|>
class GaussianDistribution:
def __init__(self, scipy=False, data=None, mu=None, sigma=None, log=False, info=False, epsilon=1e-08):
"""Class for passing values through a Gaussian distribution, uses gaussian function. made this so I could use gaussian as a method For this class, training occurs ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GaussianDistribution:
def __init__(self, scipy=False, data=None, mu=None, sigma=None, log=False, info=False, epsilon=1e-08):
"""Class for passing values through a Gaussian distribution, uses gaussian function. made this so I could use gaussian as a method For this class, training occurs inside forward... | the_stack_v2_python_sparse | manipulation/plating/GMM-Placing/gmm_placing/gaussian.py | HARPLab/gastronomy | train | 6 | |
98f2ffbe51cd6e89bee11590e48d3e9af4c650f2 | [
"super(TriGNN, self).__init__()\nself.gnn = GNNRaw()\ndim_in = 3 * dim\nself.mlp = MLP(dim_in, dim_in, dim_in * 2)\nself.linear = nn.Linear(dim, dim, bias=False)\nself.tanh = nn.Tanh()",
"x.data = F.normalize(x.data)\ny.data = F.normalize(y.data)\nx = self.tanh(self.linear(x))\ny = self.tanh(self.linear(y))\nx.da... | <|body_start_0|>
super(TriGNN, self).__init__()
self.gnn = GNNRaw()
dim_in = 3 * dim
self.mlp = MLP(dim_in, dim_in, dim_in * 2)
self.linear = nn.Linear(dim, dim, bias=False)
self.tanh = nn.Tanh()
<|end_body_0|>
<|body_start_1|>
x.data = F.normalize(x.data)
... | A graph neural network to compute the neighborhood embeddings. | TriGNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TriGNN:
"""A graph neural network to compute the neighborhood embeddings."""
def __init__(self, dim: int) -> None:
"""Args: dim: dimension of user embeddings"""
<|body_0|>
def forward(self, x: Tensor, y: Tensor, i: list, j: list, edges: list) -> tuple:
"""Args: x... | stack_v2_sparse_classes_36k_train_032610 | 2,891 | no_license | [
{
"docstring": "Args: dim: dimension of user embeddings",
"name": "__init__",
"signature": "def __init__(self, dim: int) -> None"
},
{
"docstring": "Args: x/y: user embeddings of the source/target network i/j: indices of users in the source/target network edges: indices of matched and unmatched ... | 2 | stack_v2_sparse_classes_30k_train_007628 | Implement the Python class `TriGNN` described below.
Class description:
A graph neural network to compute the neighborhood embeddings.
Method signatures and docstrings:
- def __init__(self, dim: int) -> None: Args: dim: dimension of user embeddings
- def forward(self, x: Tensor, y: Tensor, i: list, j: list, edges: li... | Implement the Python class `TriGNN` described below.
Class description:
A graph neural network to compute the neighborhood embeddings.
Method signatures and docstrings:
- def __init__(self, dim: int) -> None: Args: dim: dimension of user embeddings
- def forward(self, x: Tensor, y: Tensor, i: list, j: list, edges: li... | 28ba3c97969ef8f1c5f9912b9e0c48c11b972ea3 | <|skeleton|>
class TriGNN:
"""A graph neural network to compute the neighborhood embeddings."""
def __init__(self, dim: int) -> None:
"""Args: dim: dimension of user embeddings"""
<|body_0|>
def forward(self, x: Tensor, y: Tensor, i: list, j: list, edges: list) -> tuple:
"""Args: x... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TriGNN:
"""A graph neural network to compute the neighborhood embeddings."""
def __init__(self, dim: int) -> None:
"""Args: dim: dimension of user embeddings"""
super(TriGNN, self).__init__()
self.gnn = GNNRaw()
dim_in = 3 * dim
self.mlp = MLP(dim_in, dim_in, dim_i... | the_stack_v2_python_sparse | models/gnn.py | Xiexiaqing/INFUNE | train | 0 |
f5852c6002000b09254755af4f99c0e40c45bf9e | [
"super(TcpQuery, self).__init__()\nself._request_mbap = TcpMbap()\nself._response_mbap = TcpMbap()",
"if TcpQuery._last_transaction_id < 65535:\n TcpQuery._last_transaction_id += 1\nelse:\n TcpQuery._last_transaction_id = 0\nreturn TcpQuery._last_transaction_id",
"if slave < 0 or slave > 255:\n raise I... | <|body_start_0|>
super(TcpQuery, self).__init__()
self._request_mbap = TcpMbap()
self._response_mbap = TcpMbap()
<|end_body_0|>
<|body_start_1|>
if TcpQuery._last_transaction_id < 65535:
TcpQuery._last_transaction_id += 1
else:
TcpQuery._last_transaction_... | Subclass of a Query. Adds the Modbus TCP specific part of the protocol | TcpQuery | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TcpQuery:
"""Subclass of a Query. Adds the Modbus TCP specific part of the protocol"""
def __init__(self):
"""Constructor"""
<|body_0|>
def _get_transaction_id(self):
"""returns an identifier for the query"""
<|body_1|>
def build_request(self, pdu, s... | stack_v2_sparse_classes_36k_train_032611 | 14,499 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "returns an identifier for the query",
"name": "_get_transaction_id",
"signature": "def _get_transaction_id(self)"
},
{
"docstring": "Add the Modbus TCP part to the request",
... | 6 | stack_v2_sparse_classes_30k_train_000268 | Implement the Python class `TcpQuery` described below.
Class description:
Subclass of a Query. Adds the Modbus TCP specific part of the protocol
Method signatures and docstrings:
- def __init__(self): Constructor
- def _get_transaction_id(self): returns an identifier for the query
- def build_request(self, pdu, slave... | Implement the Python class `TcpQuery` described below.
Class description:
Subclass of a Query. Adds the Modbus TCP specific part of the protocol
Method signatures and docstrings:
- def __init__(self): Constructor
- def _get_transaction_id(self): returns an identifier for the query
- def build_request(self, pdu, slave... | a5aeb1238b26c1af55cf3a82787ed347dff1fb86 | <|skeleton|>
class TcpQuery:
"""Subclass of a Query. Adds the Modbus TCP specific part of the protocol"""
def __init__(self):
"""Constructor"""
<|body_0|>
def _get_transaction_id(self):
"""returns an identifier for the query"""
<|body_1|>
def build_request(self, pdu, s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TcpQuery:
"""Subclass of a Query. Adds the Modbus TCP specific part of the protocol"""
def __init__(self):
"""Constructor"""
super(TcpQuery, self).__init__()
self._request_mbap = TcpMbap()
self._response_mbap = TcpMbap()
def _get_transaction_id(self):
"""retur... | the_stack_v2_python_sparse | external/modbus_tk/modbus_tk/modbus_tcp.py | intel/intel-device-resource-mgt-lib | train | 2 |
784d90a9cc1908df689c7c84034d91e920952acc | [
"for i in range(256):\n self.assertEqual(binary_search(i, list(range(256))), i)\nself.assertEqual(binary_search(-1, list(range(256))), -1)\nself.assertEqual(binary_search(-411, list(range(256))), -1)\nself.assertEqual(binary_search(256, list(range(256))), -1)\nself.assertEqual(binary_search(411, list(range(256))... | <|body_start_0|>
for i in range(256):
self.assertEqual(binary_search(i, list(range(256))), i)
self.assertEqual(binary_search(-1, list(range(256))), -1)
self.assertEqual(binary_search(-411, list(range(256))), -1)
self.assertEqual(binary_search(256, list(range(256))), -1)
... | Test the implementation of binary search | TestBinarySearch | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestBinarySearch:
"""Test the implementation of binary search"""
def test_power_2(self):
"""Test with a list of power of 2 length First check all items in the list can be found, then check we fail high and low properly"""
<|body_0|>
def test_non_power_2(self):
""... | stack_v2_sparse_classes_36k_train_032612 | 2,127 | no_license | [
{
"docstring": "Test with a list of power of 2 length First check all items in the list can be found, then check we fail high and low properly",
"name": "test_power_2",
"signature": "def test_power_2(self)"
},
{
"docstring": "Test a list of non power of 2 length First check all items in the list... | 3 | stack_v2_sparse_classes_30k_test_000931 | Implement the Python class `TestBinarySearch` described below.
Class description:
Test the implementation of binary search
Method signatures and docstrings:
- def test_power_2(self): Test with a list of power of 2 length First check all items in the list can be found, then check we fail high and low properly
- def te... | Implement the Python class `TestBinarySearch` described below.
Class description:
Test the implementation of binary search
Method signatures and docstrings:
- def test_power_2(self): Test with a list of power of 2 length First check all items in the list can be found, then check we fail high and low properly
- def te... | 8539db2ba32b80b56461c145fbf62f7c1f6a238d | <|skeleton|>
class TestBinarySearch:
"""Test the implementation of binary search"""
def test_power_2(self):
"""Test with a list of power of 2 length First check all items in the list can be found, then check we fail high and low properly"""
<|body_0|>
def test_non_power_2(self):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestBinarySearch:
"""Test the implementation of binary search"""
def test_power_2(self):
"""Test with a list of power of 2 length First check all items in the list can be found, then check we fail high and low properly"""
for i in range(256):
self.assertEqual(binary_search(i, ... | the_stack_v2_python_sparse | python/binary_search.py | tompko/praxis | train | 1 |
682e5ea63d7aa03f56d1af981ea9021334128ff9 | [
"sign = 1 if x >= 0 else -1\nx *= sign\ny = 0\nwhile x != 0:\n remain = x % 10\n x = (x - remain) // 10\n y = y * 10 + remain\ny *= sign\nif y < -2147483648 or y > 2147483647:\n return 0\nelse:\n return y",
"if x < 0:\n return -self.reverse(-x)\nresult = 0\nwhile x:\n result = result * 10 + x... | <|body_start_0|>
sign = 1 if x >= 0 else -1
x *= sign
y = 0
while x != 0:
remain = x % 10
x = (x - remain) // 10
y = y * 10 + remain
y *= sign
if y < -2147483648 or y > 2147483647:
return 0
else:
return y... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverse1(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def reverse2(self, x):
""":type x: int :rtype: int"""
<|body_1|>
def reverse3(self, x):
""":type x: int :rtype: int"""
<|body_2|>
def reverse(self, x):
... | stack_v2_sparse_classes_36k_train_032613 | 1,760 | no_license | [
{
"docstring": ":type x: int :rtype: int",
"name": "reverse1",
"signature": "def reverse1(self, x)"
},
{
"docstring": ":type x: int :rtype: int",
"name": "reverse2",
"signature": "def reverse2(self, x)"
},
{
"docstring": ":type x: int :rtype: int",
"name": "reverse3",
"si... | 4 | stack_v2_sparse_classes_30k_train_014366 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse1(self, x): :type x: int :rtype: int
- def reverse2(self, x): :type x: int :rtype: int
- def reverse3(self, x): :type x: int :rtype: int
- def reverse(self, x): :type ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse1(self, x): :type x: int :rtype: int
- def reverse2(self, x): :type x: int :rtype: int
- def reverse3(self, x): :type x: int :rtype: int
- def reverse(self, x): :type ... | 4a1747b6497305f3821612d9c358a6795b1690da | <|skeleton|>
class Solution:
def reverse1(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def reverse2(self, x):
""":type x: int :rtype: int"""
<|body_1|>
def reverse3(self, x):
""":type x: int :rtype: int"""
<|body_2|>
def reverse(self, x):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverse1(self, x):
""":type x: int :rtype: int"""
sign = 1 if x >= 0 else -1
x *= sign
y = 0
while x != 0:
remain = x % 10
x = (x - remain) // 10
y = y * 10 + remain
y *= sign
if y < -2147483648 or y > 21... | the_stack_v2_python_sparse | Math/q007_reverse_integer.py | sevenhe716/LeetCode | train | 0 | |
a9995776d2d94e499ec914ccb7a1b9ae8ed56014 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn SimulationAutomation()",
"from .email_identity import EmailIdentity\nfrom .entity import Entity\nfrom .simulation_automation_run import SimulationAutomationRun\nfrom .simulation_automation_status import SimulationAutomationStatus\nfrom... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return SimulationAutomation()
<|end_body_0|>
<|body_start_1|>
from .email_identity import EmailIdentity
from .entity import Entity
from .simulation_automation_run import SimulationAutom... | SimulationAutomation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimulationAutomation:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SimulationAutomation:
"""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 ... | stack_v2_sparse_classes_36k_train_032614 | 5,474 | 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: SimulationAutomation",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminato... | 3 | stack_v2_sparse_classes_30k_test_000541 | Implement the Python class `SimulationAutomation` described below.
Class description:
Implement the SimulationAutomation class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SimulationAutomation: Creates a new instance of the appropriate class based o... | Implement the Python class `SimulationAutomation` described below.
Class description:
Implement the SimulationAutomation class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SimulationAutomation: Creates a new instance of the appropriate class based o... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class SimulationAutomation:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SimulationAutomation:
"""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 ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimulationAutomation:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SimulationAutomation:
"""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... | the_stack_v2_python_sparse | msgraph/generated/models/simulation_automation.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
3eb2255890133f2270e237a79c9b48c007b02c12 | [
"file_pattern = self.storage_root + '*.plx'\nself.possible_filenames = self.filter_files(glob.glob(file_pattern))\nself.possible_filesizes = np.array([os.stat(fname).st_size for fname in self.possible_filenames])\nsuper(PlexonSerialDIORowByte, self).init()",
"if hasattr(self, '_data_files'):\n return self._dat... | <|body_start_0|>
file_pattern = self.storage_root + '*.plx'
self.possible_filenames = self.filter_files(glob.glob(file_pattern))
self.possible_filesizes = np.array([os.stat(fname).st_size for fname in self.possible_filenames])
super(PlexonSerialDIORowByte, self).init()
<|end_body_0|>
<|... | PlexonSerialDIORowByte | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlexonSerialDIORowByte:
def init(self):
"""Find all the plx files created in the last 24 h before calling the parents init method"""
<|body_0|>
def data_files(self):
"""Calculates the plexon file that's most likely associated with the current task based on the time a... | stack_v2_sparse_classes_36k_train_032615 | 14,583 | permissive | [
{
"docstring": "Find all the plx files created in the last 24 h before calling the parents init method",
"name": "init",
"signature": "def init(self)"
},
{
"docstring": "Calculates the plexon file that's most likely associated with the current task based on the time at which the task ended and t... | 2 | stack_v2_sparse_classes_30k_train_004097 | Implement the Python class `PlexonSerialDIORowByte` described below.
Class description:
Implement the PlexonSerialDIORowByte class.
Method signatures and docstrings:
- def init(self): Find all the plx files created in the last 24 h before calling the parents init method
- def data_files(self): Calculates the plexon f... | Implement the Python class `PlexonSerialDIORowByte` described below.
Class description:
Implement the PlexonSerialDIORowByte class.
Method signatures and docstrings:
- def init(self): Find all the plx files created in the last 24 h before calling the parents init method
- def data_files(self): Calculates the plexon f... | a0e296aa663b49e767c9ebb274defb54b301eb12 | <|skeleton|>
class PlexonSerialDIORowByte:
def init(self):
"""Find all the plx files created in the last 24 h before calling the parents init method"""
<|body_0|>
def data_files(self):
"""Calculates the plexon file that's most likely associated with the current task based on the time a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlexonSerialDIORowByte:
def init(self):
"""Find all the plx files created in the last 24 h before calling the parents init method"""
file_pattern = self.storage_root + '*.plx'
self.possible_filenames = self.filter_files(glob.glob(file_pattern))
self.possible_filesizes = np.arra... | the_stack_v2_python_sparse | features/arduino_features.py | carmenalab/brain-python-interface | train | 9 | |
438ef2c50743635b3725a5ed8daa5de0416b99e2 | [
"self.main_window = main_window\nself.AddObserver('LeftButtonPressEvent', self.onLeftButtonDown)\nself.last_picked_actor = None\nself.silhouette = silhouette\nself.silhouette_actor = silhouette_actor",
"click_pos = self.GetInteractor().GetEventPosition()\npicker = vtk.vtkPropPicker()\npicker.Pick(click_pos[0], cl... | <|body_start_0|>
self.main_window = main_window
self.AddObserver('LeftButtonPressEvent', self.onLeftButtonDown)
self.last_picked_actor = None
self.silhouette = silhouette
self.silhouette_actor = silhouette_actor
<|end_body_0|>
<|body_start_1|>
click_pos = self.GetInterac... | Class use to highlight a selected component and generate an event when a component is selected | MouseInteractorHighLightActor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MouseInteractorHighLightActor:
"""Class use to highlight a selected component and generate an event when a component is selected"""
def __init__(self, silhouette, silhouette_actor, main_window):
"""Constructor :param silhouette: the silhouette object :param silhouette_actor: the silh... | stack_v2_sparse_classes_36k_train_032616 | 18,665 | permissive | [
{
"docstring": "Constructor :param silhouette: the silhouette object :param silhouette_actor: the silhouette actor :param main_window: the main_window to call events",
"name": "__init__",
"signature": "def __init__(self, silhouette, silhouette_actor, main_window)"
},
{
"docstring": "Method call ... | 2 | stack_v2_sparse_classes_30k_train_008820 | Implement the Python class `MouseInteractorHighLightActor` described below.
Class description:
Class use to highlight a selected component and generate an event when a component is selected
Method signatures and docstrings:
- def __init__(self, silhouette, silhouette_actor, main_window): Constructor :param silhouette... | Implement the Python class `MouseInteractorHighLightActor` described below.
Class description:
Class use to highlight a selected component and generate an event when a component is selected
Method signatures and docstrings:
- def __init__(self, silhouette, silhouette_actor, main_window): Constructor :param silhouette... | db7186d548bb9eea83ef2455946f7fd31245c26c | <|skeleton|>
class MouseInteractorHighLightActor:
"""Class use to highlight a selected component and generate an event when a component is selected"""
def __init__(self, silhouette, silhouette_actor, main_window):
"""Constructor :param silhouette: the silhouette object :param silhouette_actor: the silh... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MouseInteractorHighLightActor:
"""Class use to highlight a selected component and generate an event when a component is selected"""
def __init__(self, silhouette, silhouette_actor, main_window):
"""Constructor :param silhouette: the silhouette object :param silhouette_actor: the silhouette actor ... | the_stack_v2_python_sparse | Sources/visualizer/vtkUtils.py | Jean-Baptiste-HUYGHE/PRD | train | 1 |
851771d7e7af23442ab74d91e229c24a15d28579 | [
"self.callbacks = callbacks\nif serializer is None:\n serializer = rpc_serializer.NoOpSerializer()\nself.serializer = serializer\nsuper(RpcDispatcher, self).__init__()",
"new_kwargs = dict()\nfor argname, arg in six.iteritems(kwargs):\n new_kwargs[argname] = self.serializer.deserialize_entity(context, arg)\... | <|body_start_0|>
self.callbacks = callbacks
if serializer is None:
serializer = rpc_serializer.NoOpSerializer()
self.serializer = serializer
super(RpcDispatcher, self).__init__()
<|end_body_0|>
<|body_start_1|>
new_kwargs = dict()
for argname, arg in six.iter... | Dispatch rpc messages according to the requested API version. This class can be used as the top level 'manager' for a service. It contains a list of underlying managers that have an API_VERSION attribute. | RpcDispatcher | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RpcDispatcher:
"""Dispatch rpc messages according to the requested API version. This class can be used as the top level 'manager' for a service. It contains a list of underlying managers that have an API_VERSION attribute."""
def __init__(self, callbacks, serializer=None):
"""Initial... | stack_v2_sparse_classes_36k_train_032617 | 7,022 | permissive | [
{
"docstring": "Initialize the rpc dispatcher. :param callbacks: List of proxy objects that are an instance of a class with rpc methods exposed. Each proxy object should have an RPC_API_VERSION attribute. :param serializer: The Serializer object that will be used to deserialize arguments before the method call ... | 3 | stack_v2_sparse_classes_30k_train_009244 | Implement the Python class `RpcDispatcher` described below.
Class description:
Dispatch rpc messages according to the requested API version. This class can be used as the top level 'manager' for a service. It contains a list of underlying managers that have an API_VERSION attribute.
Method signatures and docstrings:
... | Implement the Python class `RpcDispatcher` described below.
Class description:
Dispatch rpc messages according to the requested API version. This class can be used as the top level 'manager' for a service. It contains a list of underlying managers that have an API_VERSION attribute.
Method signatures and docstrings:
... | d2fabf40119267164b9e765e59e3f99cd61fdcef | <|skeleton|>
class RpcDispatcher:
"""Dispatch rpc messages according to the requested API version. This class can be used as the top level 'manager' for a service. It contains a list of underlying managers that have an API_VERSION attribute."""
def __init__(self, callbacks, serializer=None):
"""Initial... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RpcDispatcher:
"""Dispatch rpc messages according to the requested API version. This class can be used as the top level 'manager' for a service. It contains a list of underlying managers that have an API_VERSION attribute."""
def __init__(self, callbacks, serializer=None):
"""Initialize the rpc d... | the_stack_v2_python_sparse | cloudbaseinit/openstack/common/rpc/dispatcher.py | pellaeon/bsd-cloudinit | train | 75 |
1b23460795c1da28038770775c591b628b91979e | [
"cls = self.__class__\nsetattr(cls.Meta, 'model', model)\nif hasattr(cls.Meta, 'list_serializer_class'):\n setattr(cls.Meta.list_serializer_class.Meta, 'model', model)\nsetattr(model, name, cls)",
"class NestedSerializer(ModelSerializer):\n\n class Meta:\n model = relation_info.related_model\n ... | <|body_start_0|>
cls = self.__class__
setattr(cls.Meta, 'model', model)
if hasattr(cls.Meta, 'list_serializer_class'):
setattr(cls.Meta.list_serializer_class.Meta, 'model', model)
setattr(model, name, cls)
<|end_body_0|>
<|body_start_1|>
class NestedSerializer(ModelS... | Mixin to add django's REST serializer as 'serializer' fiels. | ModelSerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelSerializer:
"""Mixin to add django's REST serializer as 'serializer' fiels."""
def contribute_to_class(self, model, name):
"""Setup "dynamically" model class for this serializer."""
<|body_0|>
def build_nested_field(self, field_name, relation_info, nested_depth):
... | stack_v2_sparse_classes_36k_train_032618 | 2,929 | permissive | [
{
"docstring": "Setup \"dynamically\" model class for this serializer.",
"name": "contribute_to_class",
"signature": "def contribute_to_class(self, model, name)"
},
{
"docstring": "Create nested fields for forward and reverse relationships.",
"name": "build_nested_field",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_003351 | Implement the Python class `ModelSerializer` described below.
Class description:
Mixin to add django's REST serializer as 'serializer' fiels.
Method signatures and docstrings:
- def contribute_to_class(self, model, name): Setup "dynamically" model class for this serializer.
- def build_nested_field(self, field_name, ... | Implement the Python class `ModelSerializer` described below.
Class description:
Mixin to add django's REST serializer as 'serializer' fiels.
Method signatures and docstrings:
- def contribute_to_class(self, model, name): Setup "dynamically" model class for this serializer.
- def build_nested_field(self, field_name, ... | 84c4fa10aefbd792a956cef3d727623ca78cb5fd | <|skeleton|>
class ModelSerializer:
"""Mixin to add django's REST serializer as 'serializer' fiels."""
def contribute_to_class(self, model, name):
"""Setup "dynamically" model class for this serializer."""
<|body_0|>
def build_nested_field(self, field_name, relation_info, nested_depth):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModelSerializer:
"""Mixin to add django's REST serializer as 'serializer' fiels."""
def contribute_to_class(self, model, name):
"""Setup "dynamically" model class for this serializer."""
cls = self.__class__
setattr(cls.Meta, 'model', model)
if hasattr(cls.Meta, 'list_seri... | the_stack_v2_python_sparse | market/core/serializers.py | katomaso/django-market | train | 0 |
0adff9aea85896ee03378eef1259a05bcb69a4c6 | [
"if target_python is None:\n target_python = TargetPython()\nif specifier is None:\n specifier = specifiers.SpecifierSet()\nsupported_tags = target_python.get_sorted_tags()\nreturn cls(project_name=project_name, supported_tags=supported_tags, specifier=specifier, prefer_binary=prefer_binary, allow_all_prerele... | <|body_start_0|>
if target_python is None:
target_python = TargetPython()
if specifier is None:
specifier = specifiers.SpecifierSet()
supported_tags = target_python.get_sorted_tags()
return cls(project_name=project_name, supported_tags=supported_tags, specifier=sp... | Responsible for filtering and sorting candidates for installation based on what tags are valid. | CandidateEvaluator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CandidateEvaluator:
"""Responsible for filtering and sorting candidates for installation based on what tags are valid."""
def create(cls, project_name: str, target_python: Optional[TargetPython]=None, prefer_binary: bool=False, allow_all_prereleases: bool=False, specifier: Optional[specifier... | stack_v2_sparse_classes_36k_train_032619 | 37,889 | permissive | [
{
"docstring": "Create a CandidateEvaluator object. :param target_python: The target Python interpreter to use when checking compatibility. If None (the default), a TargetPython object will be constructed from the running Python. :param specifier: An optional object implementing `filter` (e.g. `packaging.specif... | 6 | null | Implement the Python class `CandidateEvaluator` described below.
Class description:
Responsible for filtering and sorting candidates for installation based on what tags are valid.
Method signatures and docstrings:
- def create(cls, project_name: str, target_python: Optional[TargetPython]=None, prefer_binary: bool=Fal... | Implement the Python class `CandidateEvaluator` described below.
Class description:
Responsible for filtering and sorting candidates for installation based on what tags are valid.
Method signatures and docstrings:
- def create(cls, project_name: str, target_python: Optional[TargetPython]=None, prefer_binary: bool=Fal... | 0778c1c153da7da457b56df55fb77cbba08dfb0c | <|skeleton|>
class CandidateEvaluator:
"""Responsible for filtering and sorting candidates for installation based on what tags are valid."""
def create(cls, project_name: str, target_python: Optional[TargetPython]=None, prefer_binary: bool=False, allow_all_prereleases: bool=False, specifier: Optional[specifier... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CandidateEvaluator:
"""Responsible for filtering and sorting candidates for installation based on what tags are valid."""
def create(cls, project_name: str, target_python: Optional[TargetPython]=None, prefer_binary: bool=False, allow_all_prereleases: bool=False, specifier: Optional[specifiers.BaseSpecifi... | the_stack_v2_python_sparse | src/pip/_internal/index/package_finder.py | pypa/pip | train | 8,612 |
73d298e6b681db79257d3e689633c4c0b079a06f | [
"res = []\n\ndef transform(node):\n if not node:\n res.append('#')\n else:\n res.append(str(node.val))\n transform(node.left)\n transform(node.right)\ntransform(root)\nreturn ','.join(res)",
"res = iter(data.split(','))\n\ndef transform():\n val = next(res)\n if val == '#':... | <|body_start_0|>
res = []
def transform(node):
if not node:
res.append('#')
else:
res.append(str(node.val))
transform(node.left)
transform(node.right)
transform(root)
return ','.join(res)
<|end_body_... | 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_36k_train_032620 | 1,006 | 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_006092 | 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:... | c5e4f540e08492ea27ce17119b03b2528b780a92 | <|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_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
res = []
def transform(node):
if not node:
res.append('#')
else:
res.append(str(node.val))
transform(node... | the_stack_v2_python_sparse | Week_03/serialize_and_deserialize_binary_tree.py | SZ-Edward/algorithm011-class02 | train | 0 | |
e8e05023d5d3a4d7d689422fe3aae4b55299e097 | [
"json_obj = {'IP_LIST_OUTPUT': {'RESPONSE': {'DATETIME': 'sometime', 'IP_SET': {'IP': ['1.1.1.1']}}}}\nmocker.patch.object(Qualysv2, 'format_and_validate_response', return_value=json_obj)\ndummy_response = requests.Response()\nassert handle_general_result(dummy_response, 'qualys-ip-list') == {'DATETIME': 'sometime'... | <|body_start_0|>
json_obj = {'IP_LIST_OUTPUT': {'RESPONSE': {'DATETIME': 'sometime', 'IP_SET': {'IP': ['1.1.1.1']}}}}
mocker.patch.object(Qualysv2, 'format_and_validate_response', return_value=json_obj)
dummy_response = requests.Response()
assert handle_general_result(dummy_response, 'qu... | TestHandleGeneralResult | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestHandleGeneralResult:
def test_handle_general_result_path_exists(self, mocker):
"""Given - response in json format - path to a specific field When - the json object is well formed - the path is correct Then - return the path requested"""
<|body_0|>
def test_handle_general... | stack_v2_sparse_classes_36k_train_032621 | 44,285 | permissive | [
{
"docstring": "Given - response in json format - path to a specific field When - the json object is well formed - the path is correct Then - return the path requested",
"name": "test_handle_general_result_path_exists",
"signature": "def test_handle_general_result_path_exists(self, mocker)"
},
{
... | 5 | stack_v2_sparse_classes_30k_train_000725 | Implement the Python class `TestHandleGeneralResult` described below.
Class description:
Implement the TestHandleGeneralResult class.
Method signatures and docstrings:
- def test_handle_general_result_path_exists(self, mocker): Given - response in json format - path to a specific field When - the json object is well ... | Implement the Python class `TestHandleGeneralResult` described below.
Class description:
Implement the TestHandleGeneralResult class.
Method signatures and docstrings:
- def test_handle_general_result_path_exists(self, mocker): Given - response in json format - path to a specific field When - the json object is well ... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class TestHandleGeneralResult:
def test_handle_general_result_path_exists(self, mocker):
"""Given - response in json format - path to a specific field When - the json object is well formed - the path is correct Then - return the path requested"""
<|body_0|>
def test_handle_general... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestHandleGeneralResult:
def test_handle_general_result_path_exists(self, mocker):
"""Given - response in json format - path to a specific field When - the json object is well formed - the path is correct Then - return the path requested"""
json_obj = {'IP_LIST_OUTPUT': {'RESPONSE': {'DATETIME... | the_stack_v2_python_sparse | Packs/qualys/Integrations/Qualysv2/Qualysv2_test.py | demisto/content | train | 1,023 | |
487d8725374bfb0bd04c29b639f883de29abbb7c | [
"row_length = len(matrix)\nif row_length == 0:\n return\ncol_length = len(matrix[0])\nupdate_place = []\nfor i in range(row_length):\n for j in range(col_length):\n if matrix[i][j] == 0:\n update_place.append((i, j))\nfor row, col in update_place:\n for i in range(row_length):\n ma... | <|body_start_0|>
row_length = len(matrix)
if row_length == 0:
return
col_length = len(matrix[0])
update_place = []
for i in range(row_length):
for j in range(col_length):
if matrix[i][j] == 0:
update_place.append((i, j))... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def setZeroes(self, matrix: [[int]]) -> None:
"""Do not return anything, modify matrix in-place instead."""
<|body_0|>
def setZeroes_2(self, matrix: [[int]]) -> None:
"""Do not return anything, modify matrix in-place instead."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_032622 | 1,986 | permissive | [
{
"docstring": "Do not return anything, modify matrix in-place instead.",
"name": "setZeroes",
"signature": "def setZeroes(self, matrix: [[int]]) -> None"
},
{
"docstring": "Do not return anything, modify matrix in-place instead.",
"name": "setZeroes_2",
"signature": "def setZeroes_2(sel... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes(self, matrix: [[int]]) -> None: Do not return anything, modify matrix in-place instead.
- def setZeroes_2(self, matrix: [[int]]) -> None: Do not return anything, mo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes(self, matrix: [[int]]) -> None: Do not return anything, modify matrix in-place instead.
- def setZeroes_2(self, matrix: [[int]]) -> None: Do not return anything, mo... | 735e782742fab15bdb046eb6d5fc7b03502cc92d | <|skeleton|>
class Solution:
def setZeroes(self, matrix: [[int]]) -> None:
"""Do not return anything, modify matrix in-place instead."""
<|body_0|>
def setZeroes_2(self, matrix: [[int]]) -> None:
"""Do not return anything, modify matrix in-place instead."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def setZeroes(self, matrix: [[int]]) -> None:
"""Do not return anything, modify matrix in-place instead."""
row_length = len(matrix)
if row_length == 0:
return
col_length = len(matrix[0])
update_place = []
for i in range(row_length):
... | the_stack_v2_python_sparse | LeetCode/_0051_0100/_073_SetMatrixZeroes.py | BigEggStudy/LeetCode-Py | train | 1 | |
63f72e52d0fbf549698d1be1418c90b6965a86bb | [
"super().setUp()\nself.build_client = mock.MagicMock()\nself.Patch(android_build_client, 'AndroidBuildClient', return_value=self.build_client)\nself.Patch(auth, 'CreateCredentials', return_value=mock.MagicMock())\nself.RemoteImageLocalInstance = remote_image_local_instance.RemoteImageLocalInstance()\nself._fake_rem... | <|body_start_0|>
super().setUp()
self.build_client = mock.MagicMock()
self.Patch(android_build_client, 'AndroidBuildClient', return_value=self.build_client)
self.Patch(auth, 'CreateCredentials', return_value=mock.MagicMock())
self.RemoteImageLocalInstance = remote_image_local_ins... | Test remote_image_local_instance methods. | RemoteImageLocalInstanceTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RemoteImageLocalInstanceTest:
"""Test remote_image_local_instance methods."""
def setUp(self):
"""Initialize remote_image_local_instance."""
<|body_0|>
def testGetImageArtifactsPath(self, mock_proc):
"""Test get image artifacts path."""
<|body_1|>
de... | stack_v2_sparse_classes_36k_train_032623 | 7,664 | permissive | [
{
"docstring": "Initialize remote_image_local_instance.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test get image artifacts path.",
"name": "testGetImageArtifactsPath",
"signature": "def testGetImageArtifactsPath(self, mock_proc)"
},
{
"docstring": "Test... | 4 | null | Implement the Python class `RemoteImageLocalInstanceTest` described below.
Class description:
Test remote_image_local_instance methods.
Method signatures and docstrings:
- def setUp(self): Initialize remote_image_local_instance.
- def testGetImageArtifactsPath(self, mock_proc): Test get image artifacts path.
- def te... | Implement the Python class `RemoteImageLocalInstanceTest` described below.
Class description:
Test remote_image_local_instance methods.
Method signatures and docstrings:
- def setUp(self): Initialize remote_image_local_instance.
- def testGetImageArtifactsPath(self, mock_proc): Test get image artifacts path.
- def te... | 78a61ca023cbf1a0cecfef8b97df2b274ac3a988 | <|skeleton|>
class RemoteImageLocalInstanceTest:
"""Test remote_image_local_instance methods."""
def setUp(self):
"""Initialize remote_image_local_instance."""
<|body_0|>
def testGetImageArtifactsPath(self, mock_proc):
"""Test get image artifacts path."""
<|body_1|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RemoteImageLocalInstanceTest:
"""Test remote_image_local_instance methods."""
def setUp(self):
"""Initialize remote_image_local_instance."""
super().setUp()
self.build_client = mock.MagicMock()
self.Patch(android_build_client, 'AndroidBuildClient', return_value=self.build_... | the_stack_v2_python_sparse | tools/acloud/create/remote_image_local_instance_test.py | ZYHGOD-1/Aosp11 | train | 0 |
98f4e48be81494b54c105b6389fcce023ec898a4 | [
"self._type = type_\nself.query: Query = query\nself._client = client\nself._ttu = lifetime\nself._data: List[_Ps2ObjectT]\nself._index: int\nself._lock = asyncio.Lock()\nself._last_fetched = datetime.datetime.utcfromtimestamp(0)\nmax_age = datetime.datetime.utcnow() - self._last_fetched\nassert self._ttu < max_age... | <|body_start_0|>
self._type = type_
self.query: Query = query
self._client = client
self._ttu = lifetime
self._data: List[_Ps2ObjectT]
self._index: int
self._lock = asyncio.Lock()
self._last_fetched = datetime.datetime.utcfromtimestamp(0)
max_age =... | Base class for any proxy objects. The query object passed must specify the parent field name for all of its joins. This is necessary to allow parsing of the payload. Additionally, this currently does not support custom insertion fields. .. attribute:: query :type: auraxium.census.Query The API query used to populate th... | Proxy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Proxy:
"""Base class for any proxy objects. The query object passed must specify the parent field name for all of its joins. This is necessary to allow parsing of the payload. Additionally, this currently does not support custom insertion fields. .. attribute:: query :type: auraxium.census.Query ... | stack_v2_sparse_classes_36k_train_032624 | 6,687 | permissive | [
{
"docstring": "Initialise the proxy. Note that the lifetime argument may not exceed the UTC epoch seconds due to the way this value is initialised. :param type_: The object type represented by the proxy. :type type_: type[auraxium.base.Ps2Object] :param auraxium.census.Query query: The query used to retrieve t... | 3 | stack_v2_sparse_classes_30k_train_001626 | Implement the Python class `Proxy` described below.
Class description:
Base class for any proxy objects. The query object passed must specify the parent field name for all of its joins. This is necessary to allow parsing of the payload. Additionally, this currently does not support custom insertion fields. .. attribut... | Implement the Python class `Proxy` described below.
Class description:
Base class for any proxy objects. The query object passed must specify the parent field name for all of its joins. This is necessary to allow parsing of the payload. Additionally, this currently does not support custom insertion fields. .. attribut... | 23dcf927a199c8d7c917d89fe96b470a34cf4bba | <|skeleton|>
class Proxy:
"""Base class for any proxy objects. The query object passed must specify the parent field name for all of its joins. This is necessary to allow parsing of the payload. Additionally, this currently does not support custom insertion fields. .. attribute:: query :type: auraxium.census.Query ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Proxy:
"""Base class for any proxy objects. The query object passed must specify the parent field name for all of its joins. This is necessary to allow parsing of the payload. Additionally, this currently does not support custom insertion fields. .. attribute:: query :type: auraxium.census.Query The API query... | the_stack_v2_python_sparse | auraxium/_proxy.py | leonhard-s/auraxium | train | 29 |
0c47102e76757fba95a716bc39b718cb80ebf56b | [
"if not phone:\n raise ValueError('The given phone must be set')\nuser = self.model(phone=phone, **extra_fields)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"extra_fields.setdefault('is_staff', False)\nextra_fields.setdefault('is_superuser', False)\nreturn self._create_user(phone, pa... | <|body_start_0|>
if not phone:
raise ValueError('The given phone must be set')
user = self.model(phone=phone, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
<|body_start_1|>
extra_fields.setdefault('is_staff',... | CustomUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomUserManager:
def _create_user(self, phone, password, **extra_fields):
"""Create and save a User with the given email and password."""
<|body_0|>
def create_user(self, phone, password=None, **extra_fields):
"""Create and save a regular User with the given email ... | stack_v2_sparse_classes_36k_train_032625 | 3,142 | no_license | [
{
"docstring": "Create and save a User with the given email and password.",
"name": "_create_user",
"signature": "def _create_user(self, phone, password, **extra_fields)"
},
{
"docstring": "Create and save a regular User with the given email and password.",
"name": "create_user",
"signat... | 3 | stack_v2_sparse_classes_30k_train_004985 | Implement the Python class `CustomUserManager` described below.
Class description:
Implement the CustomUserManager class.
Method signatures and docstrings:
- def _create_user(self, phone, password, **extra_fields): Create and save a User with the given email and password.
- def create_user(self, phone, password=None,... | Implement the Python class `CustomUserManager` described below.
Class description:
Implement the CustomUserManager class.
Method signatures and docstrings:
- def _create_user(self, phone, password, **extra_fields): Create and save a User with the given email and password.
- def create_user(self, phone, password=None,... | abe910229da2d5be9a18c1e46fcf86f51f732c65 | <|skeleton|>
class CustomUserManager:
def _create_user(self, phone, password, **extra_fields):
"""Create and save a User with the given email and password."""
<|body_0|>
def create_user(self, phone, password=None, **extra_fields):
"""Create and save a regular User with the given email ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomUserManager:
def _create_user(self, phone, password, **extra_fields):
"""Create and save a User with the given email and password."""
if not phone:
raise ValueError('The given phone must be set')
user = self.model(phone=phone, **extra_fields)
user.set_password... | the_stack_v2_python_sparse | accounts/models.py | shams0910/uharvest-backend | train | 0 | |
f3e001f6f49f52fc47a65f8ad5139d4af4101f23 | [
"self.open(self.url)\nself.wait(2)\nself.input_value(args=self.search_input, text='自动化', context='搜索法律法规输入框')\nself.click(args=self.search_button, context='搜索按钮')\nself.wait(1)\nself.hover(args=self.search_input, context='搜索法律法规输入框')\nself.click(args=self.search_clear, context='清空按钮')\nself.input_value(args=self.se... | <|body_start_0|>
self.open(self.url)
self.wait(2)
self.input_value(args=self.search_input, text='自动化', context='搜索法律法规输入框')
self.click(args=self.search_button, context='搜索按钮')
self.wait(1)
self.hover(args=self.search_input, context='搜索法律法规输入框')
self.click(args=sel... | LowList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LowList:
def low_search_and_detail(self):
"""搜索法律法规和查看详情 :return:"""
<|body_0|>
def low_search_and_update(self):
"""搜索法律法规和编辑 :return:"""
<|body_1|>
def low_search_and_delete(self):
"""搜索法律法规和删除 :return:"""
<|body_2|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_36k_train_032626 | 5,189 | no_license | [
{
"docstring": "搜索法律法规和查看详情 :return:",
"name": "low_search_and_detail",
"signature": "def low_search_and_detail(self)"
},
{
"docstring": "搜索法律法规和编辑 :return:",
"name": "low_search_and_update",
"signature": "def low_search_and_update(self)"
},
{
"docstring": "搜索法律法规和删除 :return:",
... | 3 | stack_v2_sparse_classes_30k_train_000635 | Implement the Python class `LowList` described below.
Class description:
Implement the LowList class.
Method signatures and docstrings:
- def low_search_and_detail(self): 搜索法律法规和查看详情 :return:
- def low_search_and_update(self): 搜索法律法规和编辑 :return:
- def low_search_and_delete(self): 搜索法律法规和删除 :return: | Implement the Python class `LowList` described below.
Class description:
Implement the LowList class.
Method signatures and docstrings:
- def low_search_and_detail(self): 搜索法律法规和查看详情 :return:
- def low_search_and_update(self): 搜索法律法规和编辑 :return:
- def low_search_and_delete(self): 搜索法律法规和删除 :return:
<|skeleton|>
clas... | 1598890cc4b1ac44b5bf3ae9dd24145c49068b33 | <|skeleton|>
class LowList:
def low_search_and_detail(self):
"""搜索法律法规和查看详情 :return:"""
<|body_0|>
def low_search_and_update(self):
"""搜索法律法规和编辑 :return:"""
<|body_1|>
def low_search_and_delete(self):
"""搜索法律法规和删除 :return:"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LowList:
def low_search_and_detail(self):
"""搜索法律法规和查看详情 :return:"""
self.open(self.url)
self.wait(2)
self.input_value(args=self.search_input, text='自动化', context='搜索法律法规输入框')
self.click(args=self.search_button, context='搜索按钮')
self.wait(1)
self.hover(ar... | the_stack_v2_python_sparse | Lib/base/page_object/low/low_list.py | zhanpei10/skyline_lingang_ui | train | 0 | |
5dbc889ee969f27b6eb0448fb10647882657fe2f | [
"path = project.plugin_dir(plugin, make_dirs=False)\nsuper().__init__(plugin, str(path.parent.relative_to(project.root)))\nself.path = path",
"if not self.path.exists():\n self.remove_status = PluginLocationRemoveStatus.NOT_FOUND\n self.message = f'{self.plugin_descriptor} not found in {self.path.parent}'\n... | <|body_start_0|>
path = project.plugin_dir(plugin, make_dirs=False)
super().__init__(plugin, str(path.parent.relative_to(project.root)))
self.path = path
<|end_body_0|>
<|body_start_1|>
if not self.path.exists():
self.remove_status = PluginLocationRemoveStatus.NOT_FOUND
... | Handle removal of a plugin installation from `.meltano`. | InstallationRemoveManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstallationRemoveManager:
"""Handle removal of a plugin installation from `.meltano`."""
def __init__(self, plugin, project: Project):
"""Construct a InstallationRemoveManager instance."""
<|body_0|>
def remove(self):
"""Remove the plugin installation from `.mel... | stack_v2_sparse_classes_36k_train_032627 | 4,693 | permissive | [
{
"docstring": "Construct a InstallationRemoveManager instance.",
"name": "__init__",
"signature": "def __init__(self, plugin, project: Project)"
},
{
"docstring": "Remove the plugin installation from `.meltano`.",
"name": "remove",
"signature": "def remove(self)"
}
] | 2 | null | Implement the Python class `InstallationRemoveManager` described below.
Class description:
Handle removal of a plugin installation from `.meltano`.
Method signatures and docstrings:
- def __init__(self, plugin, project: Project): Construct a InstallationRemoveManager instance.
- def remove(self): Remove the plugin in... | Implement the Python class `InstallationRemoveManager` described below.
Class description:
Handle removal of a plugin installation from `.meltano`.
Method signatures and docstrings:
- def __init__(self, plugin, project: Project): Construct a InstallationRemoveManager instance.
- def remove(self): Remove the plugin in... | 332959c88e2f8d6dbdd7d91b56edadf8723abd2f | <|skeleton|>
class InstallationRemoveManager:
"""Handle removal of a plugin installation from `.meltano`."""
def __init__(self, plugin, project: Project):
"""Construct a InstallationRemoveManager instance."""
<|body_0|>
def remove(self):
"""Remove the plugin installation from `.mel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InstallationRemoveManager:
"""Handle removal of a plugin installation from `.meltano`."""
def __init__(self, plugin, project: Project):
"""Construct a InstallationRemoveManager instance."""
path = project.plugin_dir(plugin, make_dirs=False)
super().__init__(plugin, str(path.parent... | the_stack_v2_python_sparse | src/meltano/core/plugin_location_remove.py | forestlzj/meltano | train | 0 |
7fecd064d69a3d30af08fe173ca7eb6930b698a9 | [
"if filename is None:\n self.filename = DEFAULT_FILENAME\nelse:\n self.filename = filename\nself.settings = {}\nself.config_parser = configparser.ConfigParser()",
"if not os.path.isfile(self.filename):\n return\nself.config_parser.read(self.filename)\nif 'default' in self.config_parser.sections():\n c... | <|body_start_0|>
if filename is None:
self.filename = DEFAULT_FILENAME
else:
self.filename = filename
self.settings = {}
self.config_parser = configparser.ConfigParser()
<|end_body_0|>
<|body_start_1|>
if not os.path.isfile(self.filename):
ret... | Class representing a user config file The config file format should look like: [default] circuit_drawer = mpl circuit_mpl_style = default | UserConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserConfig:
"""Class representing a user config file The config file format should look like: [default] circuit_drawer = mpl circuit_mpl_style = default"""
def __init__(self, filename=None):
"""Create a UserConfig Args: filename (str): The path to the user config file. If one isn't s... | stack_v2_sparse_classes_36k_train_032628 | 3,452 | permissive | [
{
"docstring": "Create a UserConfig Args: filename (str): The path to the user config file. If one isn't specified ~/.qiskit/settings.conf is used.",
"name": "__init__",
"signature": "def __init__(self, filename=None)"
},
{
"docstring": "Read config file and parse the contents into the settings ... | 2 | stack_v2_sparse_classes_30k_train_006153 | Implement the Python class `UserConfig` described below.
Class description:
Class representing a user config file The config file format should look like: [default] circuit_drawer = mpl circuit_mpl_style = default
Method signatures and docstrings:
- def __init__(self, filename=None): Create a UserConfig Args: filenam... | Implement the Python class `UserConfig` described below.
Class description:
Class representing a user config file The config file format should look like: [default] circuit_drawer = mpl circuit_mpl_style = default
Method signatures and docstrings:
- def __init__(self, filename=None): Create a UserConfig Args: filenam... | abf6c23d4ab6c63f9c01c7434fb46321e6a69200 | <|skeleton|>
class UserConfig:
"""Class representing a user config file The config file format should look like: [default] circuit_drawer = mpl circuit_mpl_style = default"""
def __init__(self, filename=None):
"""Create a UserConfig Args: filename (str): The path to the user config file. If one isn't s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserConfig:
"""Class representing a user config file The config file format should look like: [default] circuit_drawer = mpl circuit_mpl_style = default"""
def __init__(self, filename=None):
"""Create a UserConfig Args: filename (str): The path to the user config file. If one isn't specified ~/.q... | the_stack_v2_python_sparse | qiskit/user_config.py | indian-institute-of-science-qc/qiskit-aakash | train | 37 |
5cb1a65ccee4c54377a7f9807db036cb8486e8dc | [
"if 'n_drop' in args:\n self.n_drop = args['n_drop']\nelse:\n self.n_drop = 10\nsuper(MarginSamplingDropout, self).__init__(X, Y, unlabeled_x, net, handler, nclasses, args)",
"probs = self.predict_prob_dropout(self.unlabeled_x, self.n_drop)\nprobs_sorted, idxs = probs.sort(descending=True)\nU = probs_sorted... | <|body_start_0|>
if 'n_drop' in args:
self.n_drop = args['n_drop']
else:
self.n_drop = 10
super(MarginSamplingDropout, self).__init__(X, Y, unlabeled_x, net, handler, nclasses, args)
<|end_body_0|>
<|body_start_1|>
probs = self.predict_prob_dropout(self.unlabeled... | Implements the Margin Sampling Strategy with dropout a active learning strategy similar to Least Confidence Sampling Strategy with dropout. While least confidence only takes into consideration the maximum probability, margin sampling considers the difference between the confidence of first and the second most probable ... | MarginSamplingDropout | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MarginSamplingDropout:
"""Implements the Margin Sampling Strategy with dropout a active learning strategy similar to Least Confidence Sampling Strategy with dropout. While least confidence only takes into consideration the maximum probability, margin sampling considers the difference between the ... | stack_v2_sparse_classes_36k_train_032629 | 3,247 | permissive | [
{
"docstring": "Constructor method",
"name": "__init__",
"signature": "def __init__(self, X, Y, unlabeled_x, net, handler, nclasses, args={})"
},
{
"docstring": "Select next set of points Parameters ---------- budget: int Number of indexes to be returned for next set Returns ---------- U_idx: li... | 2 | stack_v2_sparse_classes_30k_train_016121 | Implement the Python class `MarginSamplingDropout` described below.
Class description:
Implements the Margin Sampling Strategy with dropout a active learning strategy similar to Least Confidence Sampling Strategy with dropout. While least confidence only takes into consideration the maximum probability, margin samplin... | Implement the Python class `MarginSamplingDropout` described below.
Class description:
Implements the Margin Sampling Strategy with dropout a active learning strategy similar to Least Confidence Sampling Strategy with dropout. While least confidence only takes into consideration the maximum probability, margin samplin... | c8c3489920a24537a849eb8446efc9c2e19ab193 | <|skeleton|>
class MarginSamplingDropout:
"""Implements the Margin Sampling Strategy with dropout a active learning strategy similar to Least Confidence Sampling Strategy with dropout. While least confidence only takes into consideration the maximum probability, margin sampling considers the difference between the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MarginSamplingDropout:
"""Implements the Margin Sampling Strategy with dropout a active learning strategy similar to Least Confidence Sampling Strategy with dropout. While least confidence only takes into consideration the maximum probability, margin sampling considers the difference between the confidence of... | the_stack_v2_python_sparse | distil/active_learning_strategies/margin_sampling_dropout.py | chipsh/distil | train | 1 |
b7344d986efccd29dea4086d92f2298c174e1360 | [
"_1 = ListNode(3)\n_2 = ListNode(2)\n_3 = ListNode(0)\n_4 = ListNode(-4)\n_1.next = _2\n_2.next = _3\n_3.next = _4\n_4.next = _2\ns = Solution()\nself.assertTrue(s.hasCycle(_1))",
"l = [-21, 10, 17, 8, 4, 26, 5, 35, 33, -7, -16, 27, -12, 6, 29, -12, 5, 9, 20, 14, 14, 2, 13, -24, 21, 23, -21, 5]\nn = len(l)\nhead ... | <|body_start_0|>
_1 = ListNode(3)
_2 = ListNode(2)
_3 = ListNode(0)
_4 = ListNode(-4)
_1.next = _2
_2.next = _3
_3.next = _4
_4.next = _2
s = Solution()
self.assertTrue(s.hasCycle(_1))
<|end_body_0|>
<|body_start_1|>
l = [-21, 10, ... | Test | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test:
def test1(self):
"""head = [3,2,0,-4], pos = 1 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始) 如果 pos 是 -1,则在该链表中没有环"""
<|body_0|>
def test2(self):
"""[-21,10,17,8,4,26,5,35,33,-7,-16,27,-12,6,29,-12,5,9,20,14,14,2,13,-24,21,23,-21,5] -1"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_032630 | 1,711 | no_license | [
{
"docstring": "head = [3,2,0,-4], pos = 1 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始) 如果 pos 是 -1,则在该链表中没有环",
"name": "test1",
"signature": "def test1(self)"
},
{
"docstring": "[-21,10,17,8,4,26,5,35,33,-7,-16,27,-12,6,29,-12,5,9,20,14,14,2,13,-24,21,23,-21,5] -1",
"name": "test2",
... | 2 | stack_v2_sparse_classes_30k_train_020406 | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def test1(self): head = [3,2,0,-4], pos = 1 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始) 如果 pos 是 -1,则在该链表中没有环
- def test2(self): [-21,10,17,8,4,26,5,35,33,-7,-16,27,-12,6,29,-12,5,9... | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def test1(self): head = [3,2,0,-4], pos = 1 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始) 如果 pos 是 -1,则在该链表中没有环
- def test2(self): [-21,10,17,8,4,26,5,35,33,-7,-16,27,-12,6,29,-12,5,9... | 248b620791611001ebb471dcf8284437264b2f20 | <|skeleton|>
class Test:
def test1(self):
"""head = [3,2,0,-4], pos = 1 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始) 如果 pos 是 -1,则在该链表中没有环"""
<|body_0|>
def test2(self):
"""[-21,10,17,8,4,26,5,35,33,-7,-16,27,-12,6,29,-12,5,9,20,14,14,2,13,-24,21,23,-21,5] -1"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test:
def test1(self):
"""head = [3,2,0,-4], pos = 1 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始) 如果 pos 是 -1,则在该链表中没有环"""
_1 = ListNode(3)
_2 = ListNode(2)
_3 = ListNode(0)
_4 = ListNode(-4)
_1.next = _2
_2.next = _3
_3.next = _4
_4.... | the_stack_v2_python_sparse | 141_linked_list_cycle/_2.py | chxj1992/leetcode-exercise | train | 0 | |
8016ab8ec88e7fd8e3b377e204d83b4949469fb6 | [
"self.server_is_running = server_is_running(port, hostname)\nself.viz = Visdom(port=port) if self.server_is_running else None\nself.env = env_name\nself.plots = {}\nself.plots_ic = defaultdict(int)",
"if not self.server_is_running:\n return\nif x is None:\n x = self.plots_ic[var_name]\n self.plots_ic[var... | <|body_start_0|>
self.server_is_running = server_is_running(port, hostname)
self.viz = Visdom(port=port) if self.server_is_running else None
self.env = env_name
self.plots = {}
self.plots_ic = defaultdict(int)
<|end_body_0|>
<|body_start_1|>
if not self.server_is_running... | VisdomPlotter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VisdomPlotter:
def __init__(self, env_name='main', port=8097, hostname='localhost'):
"""Params: * env_name : str * port : int * hostname : str"""
<|body_0|>
def line_plot(self, var_name, split_name, title_name, x, y, x_label='Epochs'):
"""Params: * var_name : variabl... | stack_v2_sparse_classes_36k_train_032631 | 33,326 | no_license | [
{
"docstring": "Params: * env_name : str * port : int * hostname : str",
"name": "__init__",
"signature": "def __init__(self, env_name='main', port=8097, hostname='localhost')"
},
{
"docstring": "Params: * var_name : variable name (e.g. loss, acc) * split_name : split name (e.g. train, val) * ti... | 5 | stack_v2_sparse_classes_30k_test_000059 | Implement the Python class `VisdomPlotter` described below.
Class description:
Implement the VisdomPlotter class.
Method signatures and docstrings:
- def __init__(self, env_name='main', port=8097, hostname='localhost'): Params: * env_name : str * port : int * hostname : str
- def line_plot(self, var_name, split_name,... | Implement the Python class `VisdomPlotter` described below.
Class description:
Implement the VisdomPlotter class.
Method signatures and docstrings:
- def __init__(self, env_name='main', port=8097, hostname='localhost'): Params: * env_name : str * port : int * hostname : str
- def line_plot(self, var_name, split_name,... | 0eebc122396583eccb05fc2fd9a595cbb554b0de | <|skeleton|>
class VisdomPlotter:
def __init__(self, env_name='main', port=8097, hostname='localhost'):
"""Params: * env_name : str * port : int * hostname : str"""
<|body_0|>
def line_plot(self, var_name, split_name, title_name, x, y, x_label='Epochs'):
"""Params: * var_name : variabl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VisdomPlotter:
def __init__(self, env_name='main', port=8097, hostname='localhost'):
"""Params: * env_name : str * port : int * hostname : str"""
self.server_is_running = server_is_running(port, hostname)
self.viz = Visdom(port=port) if self.server_is_running else None
self.env... | the_stack_v2_python_sparse | apop/utils.py | thbeucher/ML_pytorch | train | 0 | |
d0a44249d8338ed71c802a632991d2db04d4d016 | [
"super(Critic, self).__init__()\nself.state_dim = state_dim\nself.action_dim = action_dim\nself.fcs1 = nn.Linear(state_dim, 256)\nself.fcs1.weight.data = fanin_init(self.fcs1.weight.data.size())\nself.fcs2 = nn.Linear(256, 128)\nself.fcs2.weight.data = fanin_init(self.fcs2.weight.data.size())\nself.fca1 = nn.Linear... | <|body_start_0|>
super(Critic, self).__init__()
self.state_dim = state_dim
self.action_dim = action_dim
self.fcs1 = nn.Linear(state_dim, 256)
self.fcs1.weight.data = fanin_init(self.fcs1.weight.data.size())
self.fcs2 = nn.Linear(256, 128)
self.fcs2.weight.data = f... | Critic | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Critic:
def __init__(self, state_dim, action_dim):
"""构建一个critic模型 Args: state_dim: 状态的特征的数量 (int) action_dim: 行为作为输入的特征的数量 (int)"""
<|body_0|>
def forward(self, state, action):
"""前向运算,根据状态和行为的特征得到Critic给出的价值(近似函数) Args: state 状态的特征表示 torch Tensor [n, state_dim] act... | stack_v2_sparse_classes_36k_train_032632 | 4,355 | permissive | [
{
"docstring": "构建一个critic模型 Args: state_dim: 状态的特征的数量 (int) action_dim: 行为作为输入的特征的数量 (int)",
"name": "__init__",
"signature": "def __init__(self, state_dim, action_dim)"
},
{
"docstring": "前向运算,根据状态和行为的特征得到Critic给出的价值(近似函数) Args: state 状态的特征表示 torch Tensor [n, state_dim] action 行为的特征表示 torch Te... | 2 | stack_v2_sparse_classes_30k_train_008917 | Implement the Python class `Critic` described below.
Class description:
Implement the Critic class.
Method signatures and docstrings:
- def __init__(self, state_dim, action_dim): 构建一个critic模型 Args: state_dim: 状态的特征的数量 (int) action_dim: 行为作为输入的特征的数量 (int)
- def forward(self, state, action): 前向运算,根据状态和行为的特征得到Critic给出的价... | Implement the Python class `Critic` described below.
Class description:
Implement the Critic class.
Method signatures and docstrings:
- def __init__(self, state_dim, action_dim): 构建一个critic模型 Args: state_dim: 状态的特征的数量 (int) action_dim: 行为作为输入的特征的数量 (int)
- def forward(self, state, action): 前向运算,根据状态和行为的特征得到Critic给出的价... | 59fdf29e7feb73048b9ddf3b4755b55f0459efcb | <|skeleton|>
class Critic:
def __init__(self, state_dim, action_dim):
"""构建一个critic模型 Args: state_dim: 状态的特征的数量 (int) action_dim: 行为作为输入的特征的数量 (int)"""
<|body_0|>
def forward(self, state, action):
"""前向运算,根据状态和行为的特征得到Critic给出的价值(近似函数) Args: state 状态的特征表示 torch Tensor [n, state_dim] act... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Critic:
def __init__(self, state_dim, action_dim):
"""构建一个critic模型 Args: state_dim: 状态的特征的数量 (int) action_dim: 行为作为输入的特征的数量 (int)"""
super(Critic, self).__init__()
self.state_dim = state_dim
self.action_dim = action_dim
self.fcs1 = nn.Linear(state_dim, 256)
self... | the_stack_v2_python_sparse | DDPG/approximator.py | WoShiDongZhiWu/reinforcement-learning-algorithm | train | 1 | |
c7ab036e7d928189048cbd35300c7eddde959387 | [
"if not root:\n return '^$'\nelse:\n return '^' + str(root.val) + self.serialize(root.left) + self.serialize(root.right) + '$'",
"if data == '^$':\n return None\nelse:\n p1 = data[1:].index('^') + 1\n cnt, p2 = (1, p1 + 1)\n while cnt > 0:\n if data[p2] == '^':\n cnt += 1\n ... | <|body_start_0|>
if not root:
return '^$'
else:
return '^' + str(root.val) + self.serialize(root.left) + self.serialize(root.right) + '$'
<|end_body_0|>
<|body_start_1|>
if data == '^$':
return None
else:
p1 = data[1:].index('^') + 1
... | 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_36k_train_032633 | 1,265 | 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_014836 | 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:... | 0d2e7f9b26e34c9b5964484563c597c3da296d15 | <|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_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return '^$'
else:
return '^' + str(root.val) + self.serialize(root.left) + self.serialize(root.right) + '$'
def deserialize(self, data):... | the_stack_v2_python_sparse | 297SerializeAndDeserializeBinaryTree.py | yanlinf/LeetCode | train | 0 | |
aab6ed463dfd489e94c415b92d379a2b94517267 | [
"try:\n self.sqlhandler = None\n if 'UID' not in self.request.cookies:\n self.write('error')\n return\n if not utils.isUIDValid(self):\n self.write('no uid')\n return\n self.classId = self.get_argument('classId')\n self.courseName = self.get_argument('courseName')\n sel... | <|body_start_0|>
try:
self.sqlhandler = None
if 'UID' not in self.request.cookies:
self.write('error')
return
if not utils.isUIDValid(self):
self.write('no uid')
return
self.classId = self.get_argumen... | AdmModifyClassRequestHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdmModifyClassRequestHandler:
def post(self):
"""添加班级信息"""
<|body_0|>
def setClass(self):
"""将班级信息写入数据库"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
self.sqlhandler = None
if 'UID' not in self.request.cookies:
... | stack_v2_sparse_classes_36k_train_032634 | 2,060 | no_license | [
{
"docstring": "添加班级信息",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "将班级信息写入数据库",
"name": "setClass",
"signature": "def setClass(self)"
}
] | 2 | null | Implement the Python class `AdmModifyClassRequestHandler` described below.
Class description:
Implement the AdmModifyClassRequestHandler class.
Method signatures and docstrings:
- def post(self): 添加班级信息
- def setClass(self): 将班级信息写入数据库 | Implement the Python class `AdmModifyClassRequestHandler` described below.
Class description:
Implement the AdmModifyClassRequestHandler class.
Method signatures and docstrings:
- def post(self): 添加班级信息
- def setClass(self): 将班级信息写入数据库
<|skeleton|>
class AdmModifyClassRequestHandler:
def post(self):
"""... | b28eb4163b02bd0a931653b94851592f2654b199 | <|skeleton|>
class AdmModifyClassRequestHandler:
def post(self):
"""添加班级信息"""
<|body_0|>
def setClass(self):
"""将班级信息写入数据库"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdmModifyClassRequestHandler:
def post(self):
"""添加班级信息"""
try:
self.sqlhandler = None
if 'UID' not in self.request.cookies:
self.write('error')
return
if not utils.isUIDValid(self):
self.write('no uid')
... | the_stack_v2_python_sparse | server/admin/python/AdmModifyClassRequestHandler.py | lyh-ADT/edu-app | train | 1 | |
98dd2b184bbfe2fcf26fa4d033ee2db1c859827f | [
"print('SnipcartHook:GET: Incoming get')\nprint(request.data)\ndata = {'body': 'ok'}\nreturn Response(data)",
"print('SnipcartHook:POST: Incoming post')\nprint(request.data['eventName'])\ntry:\n if request.data['eventName'] == 'order.completed':\n payment_gateway = 'snipcart'\n user = None\n ... | <|body_start_0|>
print('SnipcartHook:GET: Incoming get')
print(request.data)
data = {'body': 'ok'}
return Response(data)
<|end_body_0|>
<|body_start_1|>
print('SnipcartHook:POST: Incoming post')
print(request.data['eventName'])
try:
if request.data['e... | * Requires token authentication. | SnipcartHook | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnipcartHook:
"""* Requires token authentication."""
def get(self, request, format=None):
"""Docs"""
<|body_0|>
def post(self, request, format=None):
"""Docs"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
print('SnipcartHook:GET: Incoming get')... | stack_v2_sparse_classes_36k_train_032635 | 5,024 | no_license | [
{
"docstring": "Docs",
"name": "get",
"signature": "def get(self, request, format=None)"
},
{
"docstring": "Docs",
"name": "post",
"signature": "def post(self, request, format=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014920 | Implement the Python class `SnipcartHook` described below.
Class description:
* Requires token authentication.
Method signatures and docstrings:
- def get(self, request, format=None): Docs
- def post(self, request, format=None): Docs | Implement the Python class `SnipcartHook` described below.
Class description:
* Requires token authentication.
Method signatures and docstrings:
- def get(self, request, format=None): Docs
- def post(self, request, format=None): Docs
<|skeleton|>
class SnipcartHook:
"""* Requires token authentication."""
de... | d1ba4723c0ee8774ed70b8a1d163d10b3dcef28e | <|skeleton|>
class SnipcartHook:
"""* Requires token authentication."""
def get(self, request, format=None):
"""Docs"""
<|body_0|>
def post(self, request, format=None):
"""Docs"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SnipcartHook:
"""* Requires token authentication."""
def get(self, request, format=None):
"""Docs"""
print('SnipcartHook:GET: Incoming get')
print(request.data)
data = {'body': 'ok'}
return Response(data)
def post(self, request, format=None):
"""Docs""... | the_stack_v2_python_sparse | meshhairline/app.py | LogicalAddress/meshhairline | train | 0 |
2d9fba639fd15308a0d651a9bb2ec33924b7bcf7 | [
"score_map = {}\nfor i, s in items:\n self._insert_score(i, s, score_map)\nres = [[k, sum(v) // len(v)] for k, v in score_map.items()]\nreturn sorted(res, key=lambda x: x[0])",
"if i not in score_map:\n score_map[i] = [s]\nelif len(score_map[i]) < 5:\n heapq.heappush(score_map[i], s)\nelif score_map[i][0... | <|body_start_0|>
score_map = {}
for i, s in items:
self._insert_score(i, s, score_map)
res = [[k, sum(v) // len(v)] for k, v in score_map.items()]
return sorted(res, key=lambda x: x[0])
<|end_body_0|>
<|body_start_1|>
if i not in score_map:
score_map[i] =... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def highFive(self, items: List[List[int]]) -> List[List[int]]:
"""Hash table. Running time: O(nlogn) where n is the length of items."""
<|body_0|>
def _insert_score(self, i, s, score_map):
"""Heap. Running time: O(logn) where n is the length of score_map[i]... | stack_v2_sparse_classes_36k_train_032636 | 772 | permissive | [
{
"docstring": "Hash table. Running time: O(nlogn) where n is the length of items.",
"name": "highFive",
"signature": "def highFive(self, items: List[List[int]]) -> List[List[int]]"
},
{
"docstring": "Heap. Running time: O(logn) where n is the length of score_map[i].",
"name": "_insert_score... | 2 | stack_v2_sparse_classes_30k_train_020869 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def highFive(self, items: List[List[int]]) -> List[List[int]]: Hash table. Running time: O(nlogn) where n is the length of items.
- def _insert_score(self, i, s, score_map): Heap... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def highFive(self, items: List[List[int]]) -> List[List[int]]: Hash table. Running time: O(nlogn) where n is the length of items.
- def _insert_score(self, i, s, score_map): Heap... | 4a508a982b125a3a90ea893ae70863df7c99cc70 | <|skeleton|>
class Solution:
def highFive(self, items: List[List[int]]) -> List[List[int]]:
"""Hash table. Running time: O(nlogn) where n is the length of items."""
<|body_0|>
def _insert_score(self, i, s, score_map):
"""Heap. Running time: O(logn) where n is the length of score_map[i]... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def highFive(self, items: List[List[int]]) -> List[List[int]]:
"""Hash table. Running time: O(nlogn) where n is the length of items."""
score_map = {}
for i, s in items:
self._insert_score(i, s, score_map)
res = [[k, sum(v) // len(v)] for k, v in score_map... | the_stack_v2_python_sparse | solutions/1086_high_five.py | YiqunPeng/leetcode_pro | train | 0 | |
c19eee4511b5b8227560c25f2f92cebe410c278b | [
"user_db = User.get_by('token', token)\nif not user_db:\n raise ValueError('Sorry, your token is either invalid or expired.')\nreturn token",
"user_db = User.get_by('email', email)\nif not user_db:\n raise ValueError('This email is not in our database.')\nreturn email",
"user_db = User.get_by('email', ema... | <|body_start_0|>
user_db = User.get_by('token', token)
if not user_db:
raise ValueError('Sorry, your token is either invalid or expired.')
return token
<|end_body_0|>
<|body_start_1|>
user_db = User.get_by('email', email)
if not user_db:
raise ValueError(... | Defines how to create validators for user properties. For detailed description see BaseValidator | UserValidator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserValidator:
"""Defines how to create validators for user properties. For detailed description see BaseValidator"""
def token(cls, token):
"""Validates if given token is in datastore"""
<|body_0|>
def existing_email(cls, email):
"""Validates if given email is i... | stack_v2_sparse_classes_36k_train_032637 | 5,408 | permissive | [
{
"docstring": "Validates if given token is in datastore",
"name": "token",
"signature": "def token(cls, token)"
},
{
"docstring": "Validates if given email is in datastore",
"name": "existing_email",
"signature": "def existing_email(cls, email)"
},
{
"docstring": "Validates if g... | 4 | stack_v2_sparse_classes_30k_train_003616 | Implement the Python class `UserValidator` described below.
Class description:
Defines how to create validators for user properties. For detailed description see BaseValidator
Method signatures and docstrings:
- def token(cls, token): Validates if given token is in datastore
- def existing_email(cls, email): Validate... | Implement the Python class `UserValidator` described below.
Class description:
Defines how to create validators for user properties. For detailed description see BaseValidator
Method signatures and docstrings:
- def token(cls, token): Validates if given token is in datastore
- def existing_email(cls, email): Validate... | a82de1321abab504a0be85497587fa90d75fa62d | <|skeleton|>
class UserValidator:
"""Defines how to create validators for user properties. For detailed description see BaseValidator"""
def token(cls, token):
"""Validates if given token is in datastore"""
<|body_0|>
def existing_email(cls, email):
"""Validates if given email is i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserValidator:
"""Defines how to create validators for user properties. For detailed description see BaseValidator"""
def token(cls, token):
"""Validates if given token is in datastore"""
user_db = User.get_by('token', token)
if not user_db:
raise ValueError('Sorry, yo... | the_stack_v2_python_sparse | main/model/user.py | jajberni/pcse_web | train | 3 |
b66e4b55e67bb7998cd7bc882caaf58a9e15e8dd | [
"envelopes.sort(key=lambda x: (x[0], -x[1]))\ndoll = [0] * len(envelopes)\nmaxLen = 0\nfor envelope in envelopes:\n i = bisect_left(doll, envelope[1], 0, maxLen)\n doll[i] = envelope[1]\n if i == maxLen:\n maxLen += 1\nreturn maxLen",
"n = len(envelopes)\nif n < 1:\n return 0\nenvelopes.sort()\... | <|body_start_0|>
envelopes.sort(key=lambda x: (x[0], -x[1]))
doll = [0] * len(envelopes)
maxLen = 0
for envelope in envelopes:
i = bisect_left(doll, envelope[1], 0, maxLen)
doll[i] = envelope[1]
if i == maxLen:
maxLen += 1
retur... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxEnvelopes(self, envelopes):
""":type envelopes: List[List[int]] :rtype: int"""
<|body_0|>
def maxEnvelopes2(self, envelopes):
""":type envelopes: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
envelopes.... | stack_v2_sparse_classes_36k_train_032638 | 2,260 | no_license | [
{
"docstring": ":type envelopes: List[List[int]] :rtype: int",
"name": "maxEnvelopes",
"signature": "def maxEnvelopes(self, envelopes)"
},
{
"docstring": ":type envelopes: List[List[int]] :rtype: int",
"name": "maxEnvelopes2",
"signature": "def maxEnvelopes2(self, envelopes)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009489 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxEnvelopes(self, envelopes): :type envelopes: List[List[int]] :rtype: int
- def maxEnvelopes2(self, envelopes): :type envelopes: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxEnvelopes(self, envelopes): :type envelopes: List[List[int]] :rtype: int
- def maxEnvelopes2(self, envelopes): :type envelopes: List[List[int]] :rtype: int
<|skeleton|>
c... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Solution:
def maxEnvelopes(self, envelopes):
""":type envelopes: List[List[int]] :rtype: int"""
<|body_0|>
def maxEnvelopes2(self, envelopes):
""":type envelopes: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxEnvelopes(self, envelopes):
""":type envelopes: List[List[int]] :rtype: int"""
envelopes.sort(key=lambda x: (x[0], -x[1]))
doll = [0] * len(envelopes)
maxLen = 0
for envelope in envelopes:
i = bisect_left(doll, envelope[1], 0, maxLen)
... | the_stack_v2_python_sparse | code354RussianDollEnvelopes.py | cybelewang/leetcode-python | train | 0 | |
26785751065b87146ccd135f98b0c68a1ef80a91 | [
"url = '/api/v1.2/graph-connections/%d/gremlin-query' % graph_id\ncode, res = Request().request(method='post', path=url, json=body, types='hubble')\nreturn (code, res)",
"url = '/api/v1.2/graph-connections/%d/gremlin-query/async-task' % graph_id\ncode, res = Request().request(method='post', path=url, json=body, t... | <|body_start_0|>
url = '/api/v1.2/graph-connections/%d/gremlin-query' % graph_id
code, res = Request().request(method='post', path=url, json=body, types='hubble')
return (code, res)
<|end_body_0|>
<|body_start_1|>
url = '/api/v1.2/graph-connections/%d/gremlin-query/async-task' % graph_i... | 执行gremlin语句或任务 | Gremlin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Gremlin:
"""执行gremlin语句或任务"""
def gremlin_query(body, graph_id, auth=None):
"""执行GREMLIN查询 :param body: :param auth: :param graph_id: :return:"""
<|body_0|>
def gremlin_task(body, graph_id, auth=None):
"""执行GREMLIN任务 :param body: :param auth: :param graph_id: :re... | stack_v2_sparse_classes_36k_train_032639 | 26,078 | no_license | [
{
"docstring": "执行GREMLIN查询 :param body: :param auth: :param graph_id: :return:",
"name": "gremlin_query",
"signature": "def gremlin_query(body, graph_id, auth=None)"
},
{
"docstring": "执行GREMLIN任务 :param body: :param auth: :param graph_id: :return:",
"name": "gremlin_task",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_004476 | Implement the Python class `Gremlin` described below.
Class description:
执行gremlin语句或任务
Method signatures and docstrings:
- def gremlin_query(body, graph_id, auth=None): 执行GREMLIN查询 :param body: :param auth: :param graph_id: :return:
- def gremlin_task(body, graph_id, auth=None): 执行GREMLIN任务 :param body: :param auth:... | Implement the Python class `Gremlin` described below.
Class description:
执行gremlin语句或任务
Method signatures and docstrings:
- def gremlin_query(body, graph_id, auth=None): 执行GREMLIN查询 :param body: :param auth: :param graph_id: :return:
- def gremlin_task(body, graph_id, auth=None): 执行GREMLIN任务 :param body: :param auth:... | 89e5b34ab925bcc0bbc4ad63302e96c62a420399 | <|skeleton|>
class Gremlin:
"""执行gremlin语句或任务"""
def gremlin_query(body, graph_id, auth=None):
"""执行GREMLIN查询 :param body: :param auth: :param graph_id: :return:"""
<|body_0|>
def gremlin_task(body, graph_id, auth=None):
"""执行GREMLIN任务 :param body: :param auth: :param graph_id: :re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Gremlin:
"""执行gremlin语句或任务"""
def gremlin_query(body, graph_id, auth=None):
"""执行GREMLIN查询 :param body: :param auth: :param graph_id: :return:"""
url = '/api/v1.2/graph-connections/%d/gremlin-query' % graph_id
code, res = Request().request(method='post', path=url, json=body, types... | the_stack_v2_python_sparse | src/common/hubble_api.py | hugegraph/hugegraph-test | train | 1 |
bba765f632d586624cb3a7f9df1fb4dba3297e9b | [
"super(TempMediaMixin, self).setup_test_environment()\nself.__original_media_root = settings.MEDIA_ROOT\nself.__original_file_storage = settings.DEFAULT_FILE_STORAGE\nself.__temp_media = tempfile.mkdtemp()\nprint(\"Using temporary media root '{}'...\".format(self.__temp_media))\nsettings.MEDIA_ROOT = self.__temp_me... | <|body_start_0|>
super(TempMediaMixin, self).setup_test_environment()
self.__original_media_root = settings.MEDIA_ROOT
self.__original_file_storage = settings.DEFAULT_FILE_STORAGE
self.__temp_media = tempfile.mkdtemp()
print("Using temporary media root '{}'...".format(self.__temp... | Mixin to create MEDIA_ROOT in temp and tear down when complete. | TempMediaMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TempMediaMixin:
"""Mixin to create MEDIA_ROOT in temp and tear down when complete."""
def setup_test_environment(self):
"""Create temp directory and update MEDIA_ROOT and default storage."""
<|body_0|>
def teardown_test_environment(self):
"""Delete temp storage."... | stack_v2_sparse_classes_36k_train_032640 | 1,412 | permissive | [
{
"docstring": "Create temp directory and update MEDIA_ROOT and default storage.",
"name": "setup_test_environment",
"signature": "def setup_test_environment(self)"
},
{
"docstring": "Delete temp storage.",
"name": "teardown_test_environment",
"signature": "def teardown_test_environment(... | 2 | null | Implement the Python class `TempMediaMixin` described below.
Class description:
Mixin to create MEDIA_ROOT in temp and tear down when complete.
Method signatures and docstrings:
- def setup_test_environment(self): Create temp directory and update MEDIA_ROOT and default storage.
- def teardown_test_environment(self): ... | Implement the Python class `TempMediaMixin` described below.
Class description:
Mixin to create MEDIA_ROOT in temp and tear down when complete.
Method signatures and docstrings:
- def setup_test_environment(self): Create temp directory and update MEDIA_ROOT and default storage.
- def teardown_test_environment(self): ... | 9baa530f2f3405322f74ccc145641148f253341b | <|skeleton|>
class TempMediaMixin:
"""Mixin to create MEDIA_ROOT in temp and tear down when complete."""
def setup_test_environment(self):
"""Create temp directory and update MEDIA_ROOT and default storage."""
<|body_0|>
def teardown_test_environment(self):
"""Delete temp storage."... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TempMediaMixin:
"""Mixin to create MEDIA_ROOT in temp and tear down when complete."""
def setup_test_environment(self):
"""Create temp directory and update MEDIA_ROOT and default storage."""
super(TempMediaMixin, self).setup_test_environment()
self.__original_media_root = settings... | the_stack_v2_python_sparse | palvelutori/testrunner.py | City-of-Turku/munpalvelut_backend | train | 0 |
49fd90d458f875467cb13a2bde9413bd17bc4d73 | [
"self._latent_encoder = LatentEncoder(latent_encoder_output_sizes, num_latents)\nself._decoder = Decoder(decoder_output_sizes)\nself._use_deterministic_path = use_deterministic_path\nif use_deterministic_path:\n self._deterministic_encoder = DeterministicEncoder(deterministic_encoder_output_sizes, attention)",
... | <|body_start_0|>
self._latent_encoder = LatentEncoder(latent_encoder_output_sizes, num_latents)
self._decoder = Decoder(decoder_output_sizes)
self._use_deterministic_path = use_deterministic_path
if use_deterministic_path:
self._deterministic_encoder = DeterministicEncoder(de... | The (A)NP model. | LatentModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LatentModel:
"""The (A)NP model."""
def __init__(self, latent_encoder_output_sizes, num_latents, decoder_output_sizes, use_deterministic_path=True, deterministic_encoder_output_sizes=None, attention=None):
"""Initialises the model. Args: latent_encoder_output_sizes: An iterable conta... | stack_v2_sparse_classes_36k_train_032641 | 15,798 | permissive | [
{
"docstring": "Initialises the model. Args: latent_encoder_output_sizes: An iterable containing the sizes of hidden layers of the latent encoder. num_latents: The latent dimensionality. decoder_output_sizes: An iterable containing the sizes of hidden layers of the decoder. The last element should correspond to... | 2 | stack_v2_sparse_classes_30k_train_002243 | Implement the Python class `LatentModel` described below.
Class description:
The (A)NP model.
Method signatures and docstrings:
- def __init__(self, latent_encoder_output_sizes, num_latents, decoder_output_sizes, use_deterministic_path=True, deterministic_encoder_output_sizes=None, attention=None): Initialises the mo... | Implement the Python class `LatentModel` described below.
Class description:
The (A)NP model.
Method signatures and docstrings:
- def __init__(self, latent_encoder_output_sizes, num_latents, decoder_output_sizes, use_deterministic_path=True, deterministic_encoder_output_sizes=None, attention=None): Initialises the mo... | ddd3e586b01ba3a7f8b3721582aca7403649400e | <|skeleton|>
class LatentModel:
"""The (A)NP model."""
def __init__(self, latent_encoder_output_sizes, num_latents, decoder_output_sizes, use_deterministic_path=True, deterministic_encoder_output_sizes=None, attention=None):
"""Initialises the model. Args: latent_encoder_output_sizes: An iterable conta... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LatentModel:
"""The (A)NP model."""
def __init__(self, latent_encoder_output_sizes, num_latents, decoder_output_sizes, use_deterministic_path=True, deterministic_encoder_output_sizes=None, attention=None):
"""Initialises the model. Args: latent_encoder_output_sizes: An iterable containing the siz... | the_stack_v2_python_sparse | backup/model.py | jsikyoon/ASNP-RMR | train | 8 |
f81d317919cf1ab1a2ae8e6daa0ed67ef221d2d2 | [
"func_name = sys._getframe().f_code.co_name\nad_plan_info = self.get_request_data(func_name)\nexpect_errmsg = self.get_expect_result(func_name)\n'添加策略(不播放广告)'\nad_plan_info['playType'] = 1\nres = self.get_result(func_name, var_params=ad_plan_info)\nactual_errmsg = res[0].json()['errmsg']\nself.assertIn(actual_errms... | <|body_start_0|>
func_name = sys._getframe().f_code.co_name
ad_plan_info = self.get_request_data(func_name)
expect_errmsg = self.get_expect_result(func_name)
'添加策略(不播放广告)'
ad_plan_info['playType'] = 1
res = self.get_result(func_name, var_params=ad_plan_info)
actua... | StrategyManagementOfVideoEditionAdvertising | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StrategyManagementOfVideoEditionAdvertising:
def test_urine_v2_adPlanInfo_saveAdPlan(self):
"""添加视频广告策略 :return:"""
<|body_0|>
def test_urine_v2_adPlanInfo_adPlanList(self):
"""查询策略列表 :return:"""
<|body_1|>
def test_urine_v2_adPlanInfo_canBeDelete(self):... | stack_v2_sparse_classes_36k_train_032642 | 3,341 | no_license | [
{
"docstring": "添加视频广告策略 :return:",
"name": "test_urine_v2_adPlanInfo_saveAdPlan",
"signature": "def test_urine_v2_adPlanInfo_saveAdPlan(self)"
},
{
"docstring": "查询策略列表 :return:",
"name": "test_urine_v2_adPlanInfo_adPlanList",
"signature": "def test_urine_v2_adPlanInfo_adPlanList(self)"... | 4 | null | Implement the Python class `StrategyManagementOfVideoEditionAdvertising` described below.
Class description:
Implement the StrategyManagementOfVideoEditionAdvertising class.
Method signatures and docstrings:
- def test_urine_v2_adPlanInfo_saveAdPlan(self): 添加视频广告策略 :return:
- def test_urine_v2_adPlanInfo_adPlanList(s... | Implement the Python class `StrategyManagementOfVideoEditionAdvertising` described below.
Class description:
Implement the StrategyManagementOfVideoEditionAdvertising class.
Method signatures and docstrings:
- def test_urine_v2_adPlanInfo_saveAdPlan(self): 添加视频广告策略 :return:
- def test_urine_v2_adPlanInfo_adPlanList(s... | 6837a07ff200b610e7ba799a52543493848b6026 | <|skeleton|>
class StrategyManagementOfVideoEditionAdvertising:
def test_urine_v2_adPlanInfo_saveAdPlan(self):
"""添加视频广告策略 :return:"""
<|body_0|>
def test_urine_v2_adPlanInfo_adPlanList(self):
"""查询策略列表 :return:"""
<|body_1|>
def test_urine_v2_adPlanInfo_canBeDelete(self):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StrategyManagementOfVideoEditionAdvertising:
def test_urine_v2_adPlanInfo_saveAdPlan(self):
"""添加视频广告策略 :return:"""
func_name = sys._getframe().f_code.co_name
ad_plan_info = self.get_request_data(func_name)
expect_errmsg = self.get_expect_result(func_name)
'添加策略(不播放广告)'... | the_stack_v2_python_sparse | run/operation_management/test_strategy_management_of_video_edition_advertising.py | liwei123a/APITestFrame | train | 0 | |
d998425f5fe1e80a3dea29e8a37bd3d399940772 | [
"if not default_data is None and (not isinstance(default_data, (list, dict))):\n raise TypeError('Default data should be a dict or a list')\nself._filepath = filepath\nself._hold_for = hold_for\nself._check_every = check_every\nself._default_data = default_data\nself._data: JsonSuppored = DataNotLoaded()\nself._... | <|body_start_0|>
if not default_data is None and (not isinstance(default_data, (list, dict))):
raise TypeError('Default data should be a dict or a list')
self._filepath = filepath
self._hold_for = hold_for
self._check_every = check_every
self._default_data = default_d... | The bot uses a couple of json files that store data. Storing this data always in memory can be bad, especially at night for example, when usually no one uses the bot. When accessing json data files using this object, the data will be loaded to memory and will stay in memory for X seconds. If the data isn't accessed ano... | DynamicData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DynamicData:
"""The bot uses a couple of json files that store data. Storing this data always in memory can be bad, especially at night for example, when usually no one uses the bot. When accessing json data files using this object, the data will be loaded to memory and will stay in memory for X ... | stack_v2_sparse_classes_36k_train_032643 | 4,802 | no_license | [
{
"docstring": "Creates a dynamic data instance. When calling the constructor, the file is not actually read. `hold_for` is the number of seconds that the data will be stored in the memory before moving it to the local storage. By default, the data will be stored in the memory for 15 seconds. `check_every` dete... | 6 | stack_v2_sparse_classes_30k_train_006160 | Implement the Python class `DynamicData` described below.
Class description:
The bot uses a couple of json files that store data. Storing this data always in memory can be bad, especially at night for example, when usually no one uses the bot. When accessing json data files using this object, the data will be loaded t... | Implement the Python class `DynamicData` described below.
Class description:
The bot uses a couple of json files that store data. Storing this data always in memory can be bad, especially at night for example, when usually no one uses the bot. When accessing json data files using this object, the data will be loaded t... | 3c4029e82efa709ec24d8f893d63bd1cad2d77d6 | <|skeleton|>
class DynamicData:
"""The bot uses a couple of json files that store data. Storing this data always in memory can be bad, especially at night for example, when usually no one uses the bot. When accessing json data files using this object, the data will be loaded to memory and will stay in memory for X ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DynamicData:
"""The bot uses a couple of json files that store data. Storing this data always in memory can be bad, especially at night for example, when usually no one uses the bot. When accessing json data files using this object, the data will be loaded to memory and will stay in memory for X seconds. If t... | the_stack_v2_python_sparse | gadi/data.py | RealA10N/gadi | train | 0 |
a75c33816dc918279b40a897b2ee13d17c1177e0 | [
"self.words = words\nself.memo = {}\nself.indices = collections.defaultdict(list)\nfor i, x in enumerate(words):\n self.indices[x].append(i)",
"min_dist = len(self.words)\nindices1, indices2 = (self.indices[word1], self.indices[word2])\ni, j = (0, 0)\nwhile i < len(indices1) and j < len(indices2):\n min_dis... | <|body_start_0|>
self.words = words
self.memo = {}
self.indices = collections.defaultdict(list)
for i, x in enumerate(words):
self.indices[x].append(i)
<|end_body_0|>
<|body_start_1|>
min_dist = len(self.words)
indices1, indices2 = (self.indices[word1], self.... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.words = words
self.memo ... | stack_v2_sparse_classes_36k_train_032644 | 959 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortest(self, word1, word2)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013530 | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int
<|skeleton|>
class WordDistance:
... | 24aaca7585c59255a86474c1f8088bd5b81ebf51 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
self.words = words
self.memo = {}
self.indices = collections.defaultdict(list)
for i, x in enumerate(words):
self.indices[x].append(i)
def shortest(self, word1, word2):
""":ty... | the_stack_v2_python_sparse | Design/244. Shortest Word Distance II.py | burnmg/LC_algorithms_practice | train | 0 | |
6d6a172d2c448439d52eff39bafe0238b3987da4 | [
"refs = MetricModel.objects.filter(project_id=project_id).order_by('-updated')\ndata = [i.to_json() for i in refs]\nperm_can_use = request.GET.get('perm_can_use')\nif perm_can_use == '1':\n perm_can_use = True\nelse:\n perm_can_use = False\nperm = bcs_perm.Metric(request, project_id, bcs_perm.NO_RES)\ndata = ... | <|body_start_0|>
refs = MetricModel.objects.filter(project_id=project_id).order_by('-updated')
data = [i.to_json() for i in refs]
perm_can_use = request.GET.get('perm_can_use')
if perm_can_use == '1':
perm_can_use = True
else:
perm_can_use = False
... | metric列表 | Metric | [
"BSD-3-Clause",
"LicenseRef-scancode-unicode",
"ICU",
"LicenseRef-scancode-unknown-license-reference",
"Artistic-2.0",
"Zlib",
"LicenseRef-scancode-openssl",
"NAIST-2003",
"ISC",
"NTP",
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Metric:
"""metric列表"""
def list(self, request, project_id):
"""获取metric列表"""
<|body_0|>
def create(self, request, project_id):
"""创建metric"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
refs = MetricModel.objects.filter(project_id=project_id).o... | stack_v2_sparse_classes_36k_train_032645 | 10,522 | permissive | [
{
"docstring": "获取metric列表",
"name": "list",
"signature": "def list(self, request, project_id)"
},
{
"docstring": "创建metric",
"name": "create",
"signature": "def create(self, request, project_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008808 | Implement the Python class `Metric` described below.
Class description:
metric列表
Method signatures and docstrings:
- def list(self, request, project_id): 获取metric列表
- def create(self, request, project_id): 创建metric | Implement the Python class `Metric` described below.
Class description:
metric列表
Method signatures and docstrings:
- def list(self, request, project_id): 获取metric列表
- def create(self, request, project_id): 创建metric
<|skeleton|>
class Metric:
"""metric列表"""
def list(self, request, project_id):
"""获取m... | 96373cda9d87038aceb0b4858ce89e7873c8e149 | <|skeleton|>
class Metric:
"""metric列表"""
def list(self, request, project_id):
"""获取metric列表"""
<|body_0|>
def create(self, request, project_id):
"""创建metric"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Metric:
"""metric列表"""
def list(self, request, project_id):
"""获取metric列表"""
refs = MetricModel.objects.filter(project_id=project_id).order_by('-updated')
data = [i.to_json() for i in refs]
perm_can_use = request.GET.get('perm_can_use')
if perm_can_use == '1':
... | the_stack_v2_python_sparse | bcs-app/backend/apps/metric/views.py | freyzheng/bk-bcs-saas | train | 0 |
f6f070f1e5f36adfa535bed4212806218ebceca8 | [
"try:\n if max_last_time is None:\n raise MissingParameter('missing parameter max_last_time')\n url = base64.urlsafe_b64decode(b64url.encode('utf-8'))\n proxy = ProxyPool.instance().get(url, float(max_last_time))\n if proxy is None:\n response = {'success': False, 'error': 'no proxy avaiab... | <|body_start_0|>
try:
if max_last_time is None:
raise MissingParameter('missing parameter max_last_time')
url = base64.urlsafe_b64decode(b64url.encode('utf-8'))
proxy = ProxyPool.instance().get(url, float(max_last_time))
if proxy is None:
... | ProxyHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProxyHandler:
def get(self, b64url, max_last_time):
""":rtype proxy: {'http', 'http://8.8.8.8:8000'}"""
<|body_0|>
def post(self, b64url, useless):
""":param proxy: e.g. 'http://8.8.8.8:8000' :param status: 'success' or 'fail'"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_032646 | 5,572 | no_license | [
{
"docstring": ":rtype proxy: {'http', 'http://8.8.8.8:8000'}",
"name": "get",
"signature": "def get(self, b64url, max_last_time)"
},
{
"docstring": ":param proxy: e.g. 'http://8.8.8.8:8000' :param status: 'success' or 'fail'",
"name": "post",
"signature": "def post(self, b64url, useless... | 2 | null | Implement the Python class `ProxyHandler` described below.
Class description:
Implement the ProxyHandler class.
Method signatures and docstrings:
- def get(self, b64url, max_last_time): :rtype proxy: {'http', 'http://8.8.8.8:8000'}
- def post(self, b64url, useless): :param proxy: e.g. 'http://8.8.8.8:8000' :param sta... | Implement the Python class `ProxyHandler` described below.
Class description:
Implement the ProxyHandler class.
Method signatures and docstrings:
- def get(self, b64url, max_last_time): :rtype proxy: {'http', 'http://8.8.8.8:8000'}
- def post(self, b64url, useless): :param proxy: e.g. 'http://8.8.8.8:8000' :param sta... | 6f7205b00f1a105f4505cf4ee571f2c53762dc3e | <|skeleton|>
class ProxyHandler:
def get(self, b64url, max_last_time):
""":rtype proxy: {'http', 'http://8.8.8.8:8000'}"""
<|body_0|>
def post(self, b64url, useless):
""":param proxy: e.g. 'http://8.8.8.8:8000' :param status: 'success' or 'fail'"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProxyHandler:
def get(self, b64url, max_last_time):
""":rtype proxy: {'http', 'http://8.8.8.8:8000'}"""
try:
if max_last_time is None:
raise MissingParameter('missing parameter max_last_time')
url = base64.urlsafe_b64decode(b64url.encode('utf-8'))
... | the_stack_v2_python_sparse | crawlerservice/handler.py | Justinyj/ruyiwebcrawl | train | 0 | |
8cd1dde7a87bb9a255643fe12094d9cd4b2afa1c | [
"DocketGenerator.__init__(self)\nself.n_stimuli = n_stimuli\nself.n_reference = np.int32(n_reference)\nself.n_select = np.int32(n_select)\nself.is_ranked = True\nif max_unique_query is None:\n max_unique_query = n_stimuli\nelse:\n max_unique_query = np.minimum(max_unique_query, n_stimuli)\nself.max_unique_que... | <|body_start_0|>
DocketGenerator.__init__(self)
self.n_stimuli = n_stimuli
self.n_reference = np.int32(n_reference)
self.n_select = np.int32(n_select)
self.is_ranked = True
if max_unique_query is None:
max_unique_query = n_stimuli
else:
max... | A trial generator that uses approximate information gain. | ActiveRank | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActiveRank:
"""A trial generator that uses approximate information gain."""
def __init__(self, n_stimuli, n_reference=2, n_select=1, max_unique_query=None, n_candidate=1000, batch_size=128):
"""Initialize. Arguments: n_stimuli: A scalar indicating the total number of unique stimuli. ... | stack_v2_sparse_classes_36k_train_032647 | 15,132 | permissive | [
{
"docstring": "Initialize. Arguments: n_stimuli: A scalar indicating the total number of unique stimuli. n_reference (optional): An integer indicating the number of references for each trial. n_select (optional): An integer indicating the number of selections an agent must make. max_unique_query (optional): A ... | 4 | stack_v2_sparse_classes_30k_train_017430 | Implement the Python class `ActiveRank` described below.
Class description:
A trial generator that uses approximate information gain.
Method signatures and docstrings:
- def __init__(self, n_stimuli, n_reference=2, n_select=1, max_unique_query=None, n_candidate=1000, batch_size=128): Initialize. Arguments: n_stimuli:... | Implement the Python class `ActiveRank` described below.
Class description:
A trial generator that uses approximate information gain.
Method signatures and docstrings:
- def __init__(self, n_stimuli, n_reference=2, n_select=1, max_unique_query=None, n_candidate=1000, batch_size=128): Initialize. Arguments: n_stimuli:... | 4f05348cf43d2d53ff9cc6dee633de385df883e3 | <|skeleton|>
class ActiveRank:
"""A trial generator that uses approximate information gain."""
def __init__(self, n_stimuli, n_reference=2, n_select=1, max_unique_query=None, n_candidate=1000, batch_size=128):
"""Initialize. Arguments: n_stimuli: A scalar indicating the total number of unique stimuli. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActiveRank:
"""A trial generator that uses approximate information gain."""
def __init__(self, n_stimuli, n_reference=2, n_select=1, max_unique_query=None, n_candidate=1000, batch_size=128):
"""Initialize. Arguments: n_stimuli: A scalar indicating the total number of unique stimuli. n_reference (... | the_stack_v2_python_sparse | psiz/generators/similarity/rank/active_rank.py | asuiconlab/psiz | train | 0 |
e0e51d08ab022c7939580c37b0a1c132d5988a7f | [
"accepted_filter_labels_and_vals = {'active': 'False', 'deleted': 'True', 'all': 'All'}\naccepted_filters = []\nfor label, val in accepted_filter_labels_and_vals.items():\n args = {self.key: val}\n accepted_filters.append(GridColumnFilter(label, args))\nreturn accepted_filters",
"if column_filter == 'All':\... | <|body_start_0|>
accepted_filter_labels_and_vals = {'active': 'False', 'deleted': 'True', 'all': 'All'}
accepted_filters = []
for label, val in accepted_filter_labels_and_vals.items():
args = {self.key: val}
accepted_filters.append(GridColumnFilter(label, args))
r... | Column that tracks and filters for items with deleted attribute. | DeletedColumn | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeletedColumn:
"""Column that tracks and filters for items with deleted attribute."""
def get_accepted_filters(self):
"""Returns a list of accepted filters for this column."""
<|body_0|>
def filter(self, trans, user, query, column_filter):
"""Modify query to filt... | stack_v2_sparse_classes_36k_train_032648 | 38,546 | permissive | [
{
"docstring": "Returns a list of accepted filters for this column.",
"name": "get_accepted_filters",
"signature": "def get_accepted_filters(self)"
},
{
"docstring": "Modify query to filter self.model_class by state.",
"name": "filter",
"signature": "def filter(self, trans, user, query, ... | 2 | null | Implement the Python class `DeletedColumn` described below.
Class description:
Column that tracks and filters for items with deleted attribute.
Method signatures and docstrings:
- def get_accepted_filters(self): Returns a list of accepted filters for this column.
- def filter(self, trans, user, query, column_filter):... | Implement the Python class `DeletedColumn` described below.
Class description:
Column that tracks and filters for items with deleted attribute.
Method signatures and docstrings:
- def get_accepted_filters(self): Returns a list of accepted filters for this column.
- def filter(self, trans, user, query, column_filter):... | e9edd90c95f0d12da19f45d4d11b374f87149550 | <|skeleton|>
class DeletedColumn:
"""Column that tracks and filters for items with deleted attribute."""
def get_accepted_filters(self):
"""Returns a list of accepted filters for this column."""
<|body_0|>
def filter(self, trans, user, query, column_filter):
"""Modify query to filt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeletedColumn:
"""Column that tracks and filters for items with deleted attribute."""
def get_accepted_filters(self):
"""Returns a list of accepted filters for this column."""
accepted_filter_labels_and_vals = {'active': 'False', 'deleted': 'True', 'all': 'All'}
accepted_filters =... | the_stack_v2_python_sparse | galaxy/coralsnp_reports/lib/galaxy/webapps/coralsnp_reports/framework/grids.py | gregvonkuster/galaxy_tools | train | 4 |
0ddf629e462e6c0c541431709afac395813c010b | [
"path = []\nif root is None:\n return path\nstack = []\nstack.append(root)\nwhile stack:\n root = stack.pop()\n path.append(root.val)\n if root.right is not None:\n stack.append(root.right)\n if root.left is not None:\n stack.append(root.left)\nreturn path",
"path = []\nif root is Non... | <|body_start_0|>
path = []
if root is None:
return path
stack = []
stack.append(root)
while stack:
root = stack.pop()
path.append(root.val)
if root.right is not None:
stack.append(root.right)
if root.left... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def preorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def postorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
def inorderTraversal(self, root):
""":type root: Tree... | stack_v2_sparse_classes_36k_train_032649 | 3,018 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "preorderTraversal",
"signature": "def preorderTraversal(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "postorderTraversal",
"signature": "def postorderTraversal(self, root)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_021248 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def preorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def postorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def inorderTraversal(self... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def preorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def postorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def inorderTraversal(self... | 813235789ce422a3bab198317aafc46fbc61625e | <|skeleton|>
class Solution:
def preorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def postorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
def inorderTraversal(self, root):
""":type root: Tree... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def preorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
path = []
if root is None:
return path
stack = []
stack.append(root)
while stack:
root = stack.pop()
path.append(root.val)
i... | the_stack_v2_python_sparse | binary_tree_traversals_using_stack/solution.py | kimmyoo/python_leetcode | train | 1 | |
40873b9e0ffaadb6451f553b15a061d4381f80da | [
"operationSuccess = True\nif not isinstance(persistentDataContainer, dict):\n raise Exceptions.IncorrectTypeException(persistentDataContainer, 'persistentDataContainer', (dict,))\npersistentDataBranches = persistentDataContainer.get(self._branchesKey, dict())\nif not isinstance(persistentDataBranches, dict):\n ... | <|body_start_0|>
operationSuccess = True
if not isinstance(persistentDataContainer, dict):
raise Exceptions.IncorrectTypeException(persistentDataContainer, 'persistentDataContainer', (dict,))
persistentDataBranches = persistentDataContainer.get(self._branchesKey, dict())
if n... | A class for handling persistent data. This version will allow you to directly input the persistent data container when using the load method, and get the persistent data container as the return value when using the save method. | PersistentBranchedDirect | [
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PersistentBranchedDirect:
"""A class for handling persistent data. This version will allow you to directly input the persistent data container when using the load method, and get the persistent data container as the return value when using the save method."""
def Load(self, persistentDataCon... | stack_v2_sparse_classes_36k_train_032650 | 34,547 | permissive | [
{
"docstring": "Load persistent data from a persistent data container. :param persistentDataContainer: The persistent data container dictionary. :type persistentDataContainer: dict :return: True if this completed without incident, False if not. :rtype: bool",
"name": "Load",
"signature": "def Load(self,... | 2 | stack_v2_sparse_classes_30k_train_009328 | Implement the Python class `PersistentBranchedDirect` described below.
Class description:
A class for handling persistent data. This version will allow you to directly input the persistent data container when using the load method, and get the persistent data container as the return value when using the save method.
... | Implement the Python class `PersistentBranchedDirect` described below.
Class description:
A class for handling persistent data. This version will allow you to directly input the persistent data container when using the load method, and get the persistent data container as the return value when using the save method.
... | 2d85e6d4428f01294d2d34f1807287b753f7490c | <|skeleton|>
class PersistentBranchedDirect:
"""A class for handling persistent data. This version will allow you to directly input the persistent data container when using the load method, and get the persistent data container as the return value when using the save method."""
def Load(self, persistentDataCon... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PersistentBranchedDirect:
"""A class for handling persistent data. This version will allow you to directly input the persistent data container when using the load method, and get the persistent data container as the return value when using the save method."""
def Load(self, persistentDataContainer: dict)... | the_stack_v2_python_sparse | Python/NeonOcean.S4.Main/NeonOcean/S4/Main/Data/PersistenceBranched.py | NeonOcean/S4.Main | train | 1 |
b1e4ed4478ff182dfe54a677c76f41ebe36c829e | [
"status = ErrorCode.SUCCESS\ntry:\n data = DotDict(json_decode(self.request.body))\n content = data.get('content', '')\n mobiles = data.get('mobiles', None)\n logging.info('[UWEB] Announcement request: %s', data)\nexcept Exception as e:\n status = ErrorCode.ILLEGAL_DATA_FORMAT\n self.write_ret(sta... | <|body_start_0|>
status = ErrorCode.SUCCESS
try:
data = DotDict(json_decode(self.request.body))
content = data.get('content', '')
mobiles = data.get('mobiles', None)
logging.info('[UWEB] Announcement request: %s', data)
except Exception as e:
... | Record the announcement info. :url /announcement | AnnouncementHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnnouncementHandler:
"""Record the announcement info. :url /announcement"""
def post(self):
"""Insert new items."""
<|body_0|>
def delete(self):
"""Delete announcement."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
status = ErrorCode.SUCCESS
... | stack_v2_sparse_classes_36k_train_032651 | 4,433 | no_license | [
{
"docstring": "Insert new items.",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Delete announcement.",
"name": "delete",
"signature": "def delete(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008908 | Implement the Python class `AnnouncementHandler` described below.
Class description:
Record the announcement info. :url /announcement
Method signatures and docstrings:
- def post(self): Insert new items.
- def delete(self): Delete announcement. | Implement the Python class `AnnouncementHandler` described below.
Class description:
Record the announcement info. :url /announcement
Method signatures and docstrings:
- def post(self): Insert new items.
- def delete(self): Delete announcement.
<|skeleton|>
class AnnouncementHandler:
"""Record the announcement i... | 3b095a325581b1fc48497c234f0ad55e928586a1 | <|skeleton|>
class AnnouncementHandler:
"""Record the announcement info. :url /announcement"""
def post(self):
"""Insert new items."""
<|body_0|>
def delete(self):
"""Delete announcement."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnnouncementHandler:
"""Record the announcement info. :url /announcement"""
def post(self):
"""Insert new items."""
status = ErrorCode.SUCCESS
try:
data = DotDict(json_decode(self.request.body))
content = data.get('content', '')
mobiles = data.g... | the_stack_v2_python_sparse | apps/uweb/handlers/announcement.py | jcsy521/ydws | train | 0 |
7e7e44d69fba30084174a0f87524e7f731b27a51 | [
"self.policy_manager = PolicyManager(self.project, self.kb)\nif policies is not None:\n for policy in policies:\n self.policy_manager.register_policy(policy, policy.name)",
"if functions is None:\n functions = self.policy_manager.fast_cfg.functions.values()\nfor function in functions:\n self.polic... | <|body_start_0|>
self.policy_manager = PolicyManager(self.project, self.kb)
if policies is not None:
for policy in policies:
self.policy_manager.register_policy(policy, policy.name)
<|end_body_0|>
<|body_start_1|>
if functions is None:
functions = self.po... | An angr analysis that performs policy checks with a given set of policies against the binary program. | StaticPolice | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StaticPolice:
"""An angr analysis that performs policy checks with a given set of policies against the binary program."""
def __init__(self, policies=None):
"""Constructor. :param iterable policies: A collection of policies to be registered with the policy manager."""
<|body_... | stack_v2_sparse_classes_36k_train_032652 | 1,151 | permissive | [
{
"docstring": "Constructor. :param iterable policies: A collection of policies to be registered with the policy manager.",
"name": "__init__",
"signature": "def __init__(self, policies=None)"
},
{
"docstring": "Enforce the policy. :param iterable functions: A collection of functions to enforce ... | 2 | null | Implement the Python class `StaticPolice` described below.
Class description:
An angr analysis that performs policy checks with a given set of policies against the binary program.
Method signatures and docstrings:
- def __init__(self, policies=None): Constructor. :param iterable policies: A collection of policies to ... | Implement the Python class `StaticPolice` described below.
Class description:
An angr analysis that performs policy checks with a given set of policies against the binary program.
Method signatures and docstrings:
- def __init__(self, policies=None): Constructor. :param iterable policies: A collection of policies to ... | 964dc80c758e25c698c2cbcc454ef5954c5fa0a0 | <|skeleton|>
class StaticPolice:
"""An angr analysis that performs policy checks with a given set of policies against the binary program."""
def __init__(self, policies=None):
"""Constructor. :param iterable policies: A collection of policies to be registered with the policy manager."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StaticPolice:
"""An angr analysis that performs policy checks with a given set of policies against the binary program."""
def __init__(self, policies=None):
"""Constructor. :param iterable policies: A collection of policies to be registered with the policy manager."""
self.policy_manager ... | the_stack_v2_python_sparse | exercises/slide_104/static-police/staticpolice/staticpolice.py | Ruide/angr-dev | train | 0 |
d3299d1b5c13e2bae71d289ebce32b7e784afa75 | [
"self.items = items\nself.name = name\nself.optional = optional",
"if dictionary is None:\n return None\nitems = None\nif dictionary.get('items') != None:\n items = list()\n for structure in dictionary.get('items'):\n items.append(cohesity_management_sdk.models.pod_info_pod_spec_volume_info_key_to... | <|body_start_0|>
self.items = items
self.name = name
self.optional = optional
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
items = None
if dictionary.get('items') != None:
items = list()
for structure in dictionar... | Implementation of the 'PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection_ConfigMapProjection' model. TODO: type description here. Attributes: items (list of PodInfo_PodSpec_VolumeInfo_KeyToPath): TODO: Type description here. name (string): TODO: Type description here. optional (bool): TODO: Type description here. | PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection_ConfigMapProjection | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection_ConfigMapProjection:
"""Implementation of the 'PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection_ConfigMapProjection' model. TODO: type description here. Attributes: items (list of PodInfo_PodSpec_VolumeInfo_KeyToPath): TODO: Type descript... | stack_v2_sparse_classes_36k_train_032653 | 2,250 | permissive | [
{
"docstring": "Constructor for the PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection_ConfigMapProjection class",
"name": "__init__",
"signature": "def __init__(self, items=None, name=None, optional=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionar... | 2 | stack_v2_sparse_classes_30k_val_001049 | Implement the Python class `PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection_ConfigMapProjection` described below.
Class description:
Implementation of the 'PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection_ConfigMapProjection' model. TODO: type description here. Attributes: items (list of PodInfo_PodSpec_Vol... | Implement the Python class `PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection_ConfigMapProjection` described below.
Class description:
Implementation of the 'PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection_ConfigMapProjection' model. TODO: type description here. Attributes: items (list of PodInfo_PodSpec_Vol... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection_ConfigMapProjection:
"""Implementation of the 'PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection_ConfigMapProjection' model. TODO: type description here. Attributes: items (list of PodInfo_PodSpec_VolumeInfo_KeyToPath): TODO: Type descript... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection_ConfigMapProjection:
"""Implementation of the 'PodInfo_PodSpec_VolumeInfo_Projected_VolumeProjection_ConfigMapProjection' model. TODO: type description here. Attributes: items (list of PodInfo_PodSpec_VolumeInfo_KeyToPath): TODO: Type description here. nam... | the_stack_v2_python_sparse | cohesity_management_sdk/models/pod_info_pod_spec_volume_info_projected_volume_projection_config_map_projection.py | cohesity/management-sdk-python | train | 24 |
b27f1f10acf417ecefcf5ea630d4425b912945a1 | [
"super(Pose3DLoss, self).__init__()\nself.weight_3d = weight_3d\nself.weight_2d = weight_2d\nself.criterion_2dpose = nn.MSELoss(reduction=reduction)\nself.criterion_3dpose = nn.L1Loss(reduction=reduction)\nself.criterion_smoothl1 = nn.SmoothL1Loss(reduction=reduction, delta=1.0)\nself.criterion_vertices = nn.L1Loss... | <|body_start_0|>
super(Pose3DLoss, self).__init__()
self.weight_3d = weight_3d
self.weight_2d = weight_2d
self.criterion_2dpose = nn.MSELoss(reduction=reduction)
self.criterion_3dpose = nn.L1Loss(reduction=reduction)
self.criterion_smoothl1 = nn.SmoothL1Loss(reduction=red... | Pose3DLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pose3DLoss:
def __init__(self, weight_3d=1.0, weight_2d=0.0, reduction='none'):
"""KeyPointMSELoss layer Args: weight_3d (float): weight of 3d loss weight_2d (float): weight of 2d loss reduction (bool): whether use reduction to loss"""
<|body_0|>
def forward(self, pred3d, pr... | stack_v2_sparse_classes_36k_train_032654 | 7,960 | permissive | [
{
"docstring": "KeyPointMSELoss layer Args: weight_3d (float): weight of 3d loss weight_2d (float): weight of 2d loss reduction (bool): whether use reduction to loss",
"name": "__init__",
"signature": "def __init__(self, weight_3d=1.0, weight_2d=0.0, reduction='none')"
},
{
"docstring": "mpjpe: ... | 2 | null | Implement the Python class `Pose3DLoss` described below.
Class description:
Implement the Pose3DLoss class.
Method signatures and docstrings:
- def __init__(self, weight_3d=1.0, weight_2d=0.0, reduction='none'): KeyPointMSELoss layer Args: weight_3d (float): weight of 3d loss weight_2d (float): weight of 2d loss redu... | Implement the Python class `Pose3DLoss` described below.
Class description:
Implement the Pose3DLoss class.
Method signatures and docstrings:
- def __init__(self, weight_3d=1.0, weight_2d=0.0, reduction='none'): KeyPointMSELoss layer Args: weight_3d (float): weight of 3d loss weight_2d (float): weight of 2d loss redu... | bd83b98342b0a6bc8d8dcd5936233aeda1e32167 | <|skeleton|>
class Pose3DLoss:
def __init__(self, weight_3d=1.0, weight_2d=0.0, reduction='none'):
"""KeyPointMSELoss layer Args: weight_3d (float): weight of 3d loss weight_2d (float): weight of 2d loss reduction (bool): whether use reduction to loss"""
<|body_0|>
def forward(self, pred3d, pr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Pose3DLoss:
def __init__(self, weight_3d=1.0, weight_2d=0.0, reduction='none'):
"""KeyPointMSELoss layer Args: weight_3d (float): weight of 3d loss weight_2d (float): weight of 2d loss reduction (bool): whether use reduction to loss"""
super(Pose3DLoss, self).__init__()
self.weight_3d ... | the_stack_v2_python_sparse | ppdet/modeling/losses/pose3d_loss.py | PaddlePaddle/PaddleDetection | train | 12,523 | |
7bd87f386cc2cd3f38d1b8a78386c0c119b0db3c | [
"self.name = name\nself.account = account\nself.balance = Decimal(0)",
"if self.balance >= 0 and amount >= 0:\n self.balance = self.balance + Decimal(amount)\nelse:\n raise ValueError('balance and amount must be positive')",
"if amount <= self.balance:\n self.balance -= Decimal(amount)\nelse:\n rais... | <|body_start_0|>
self.name = name
self.account = account
self.balance = Decimal(0)
<|end_body_0|>
<|body_start_1|>
if self.balance >= 0 and amount >= 0:
self.balance = self.balance + Decimal(amount)
else:
raise ValueError('balance and amount must be posit... | A class that represents a customer (python docs follows Numpy/Scipy format) ... Attributes ---------- name: str customer name account: str customer's account balance: decimal.Decimal customer's balance Methods ------- deposit(amount) a customer deposits money withdraw(amount) a customer withdraw money | Customer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Customer:
"""A class that represents a customer (python docs follows Numpy/Scipy format) ... Attributes ---------- name: str customer name account: str customer's account balance: decimal.Decimal customer's balance Methods ------- deposit(amount) a customer deposits money withdraw(amount) a custo... | stack_v2_sparse_classes_36k_train_032655 | 1,891 | no_license | [
{
"docstring": "Parameters ---------- name: str customer name account: str customer's account balance: decimal.Decimal customer's balance",
"name": "__init__",
"signature": "def __init__(self, name, account)"
},
{
"docstring": "Deposit money Parameters ---------- amount: float amount of money th... | 3 | stack_v2_sparse_classes_30k_train_020093 | Implement the Python class `Customer` described below.
Class description:
A class that represents a customer (python docs follows Numpy/Scipy format) ... Attributes ---------- name: str customer name account: str customer's account balance: decimal.Decimal customer's balance Methods ------- deposit(amount) a customer ... | Implement the Python class `Customer` described below.
Class description:
A class that represents a customer (python docs follows Numpy/Scipy format) ... Attributes ---------- name: str customer name account: str customer's account balance: decimal.Decimal customer's balance Methods ------- deposit(amount) a customer ... | 11ef8a7885d1e5a1f16788a934f3bb8d62a01dc2 | <|skeleton|>
class Customer:
"""A class that represents a customer (python docs follows Numpy/Scipy format) ... Attributes ---------- name: str customer name account: str customer's account balance: decimal.Decimal customer's balance Methods ------- deposit(amount) a customer deposits money withdraw(amount) a custo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Customer:
"""A class that represents a customer (python docs follows Numpy/Scipy format) ... Attributes ---------- name: str customer name account: str customer's account balance: decimal.Decimal customer's balance Methods ------- deposit(amount) a customer deposits money withdraw(amount) a customer withdraw ... | the_stack_v2_python_sparse | exam/1/python-ci-gitlab/cathay/sample/customer.py | daniel-qa/Python | train | 0 |
6abb9954fd5c530cb8957d0d0c02931b9d0d2555 | [
"if old is not None:\n old.on_trait_change(self.active_editor_dirt, 'dirty', remove=True)\nif new is not None:\n new.on_trait_change(self.active_editor_dirt, 'dirty')\n self.active_editor_dirt(dirty=new.dirty)",
"if dirty:\n self.enabled = True\nelse:\n self.enabled = False",
"active_editor = sel... | <|body_start_0|>
if old is not None:
old.on_trait_change(self.active_editor_dirt, 'dirty', remove=True)
if new is not None:
new.on_trait_change(self.active_editor_dirt, 'dirty')
self.active_editor_dirt(dirty=new.dirty)
<|end_body_0|>
<|body_start_1|>
if dirty... | Defines an action that save the contents of the current editor. | SaveAction | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SaveAction:
"""Defines an action that save the contents of the current editor."""
def _active_editor_changed_for_window(self, obj, name, old, new):
"""Sets up static event handlers for change in the clean state of the active editor"""
<|body_0|>
def active_editor_dirt(se... | stack_v2_sparse_classes_36k_train_032656 | 4,322 | permissive | [
{
"docstring": "Sets up static event handlers for change in the clean state of the active editor",
"name": "_active_editor_changed_for_window",
"signature": "def _active_editor_changed_for_window(self, obj, name, old, new)"
},
{
"docstring": "Enables the action if the active editor is dirty.",
... | 3 | null | Implement the Python class `SaveAction` described below.
Class description:
Defines an action that save the contents of the current editor.
Method signatures and docstrings:
- def _active_editor_changed_for_window(self, obj, name, old, new): Sets up static event handlers for change in the clean state of the active ed... | Implement the Python class `SaveAction` described below.
Class description:
Defines an action that save the contents of the current editor.
Method signatures and docstrings:
- def _active_editor_changed_for_window(self, obj, name, old, new): Sets up static event handlers for change in the clean state of the active ed... | e8fc0b2d6b9b08e60389fc4714a5cf51f628b57f | <|skeleton|>
class SaveAction:
"""Defines an action that save the contents of the current editor."""
def _active_editor_changed_for_window(self, obj, name, old, new):
"""Sets up static event handlers for change in the clean state of the active editor"""
<|body_0|>
def active_editor_dirt(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SaveAction:
"""Defines an action that save the contents of the current editor."""
def _active_editor_changed_for_window(self, obj, name, old, new):
"""Sets up static event handlers for change in the clean state of the active editor"""
if old is not None:
old.on_trait_change(se... | the_stack_v2_python_sparse | puddle/resource/action/save_action.py | rwl/puddle | train | 2 |
a1e560d2aa4d86bef82fc586f46d544207a43c57 | [
"self.k = k\nself.nums = nums\nself.heap = heapify(self.nums)\nwhile len(self.nums) > k:\n heappop(self.nums)",
"if len(self.nums) < self.k:\n heappush(self.nums, val)\nelse:\n heappushpop(self.nums, val)\nreturn self.nums[0]"
] | <|body_start_0|>
self.k = k
self.nums = nums
self.heap = heapify(self.nums)
while len(self.nums) > k:
heappop(self.nums)
<|end_body_0|>
<|body_start_1|>
if len(self.nums) < self.k:
heappush(self.nums, val)
else:
heappushpop(self.nums, ... | KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.k = k
self.nums = nums
self.heap = he... | stack_v2_sparse_classes_36k_train_032657 | 1,461 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | null | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, nu... | 1c584f4ca4cda7a3fb3148801a1ff4c73befed24 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
self.k = k
self.nums = nums
self.heap = heapify(self.nums)
while len(self.nums) > k:
heappop(self.nums)
def add(self, val):
""":type val: int :rtype: int"""
... | the_stack_v2_python_sparse | Heaps/KthLargest.py | kqg13/LeetCode | train | 0 | |
062b6078e945baae00d4ce62faddc05d7feb7ad0 | [
"gtk.VBox.__init__(self)\nself.controller = controller\nself.config = controller.config\nself.set_spacing(8)\nself.set_border_width(8)\nself.labelName = gtk.Label()\nself.labelName.set_alignment(0.0, 0.5)\nself.labelDescription = gtk.Label()\nself.labelDescription.set_alignment(0.0, 0.5)\nself.labelAuthor = gtk.Lab... | <|body_start_0|>
gtk.VBox.__init__(self)
self.controller = controller
self.config = controller.config
self.set_spacing(8)
self.set_border_width(8)
self.labelName = gtk.Label()
self.labelName.set_alignment(0.0, 0.5)
self.labelDescription = gtk.Label()
... | This class represents the conversation layout config | ConversationLayoutTab | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConversationLayoutTab:
"""This class represents the conversation layout config"""
def __init__(self, controller):
"""Constructor"""
<|body_0|>
def updateInfosFrame(self):
"""Updates the htmltextview preview."""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_36k_train_032658 | 25,236 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, controller)"
},
{
"docstring": "Updates the htmltextview preview.",
"name": "updateInfosFrame",
"signature": "def updateInfosFrame(self)"
}
] | 2 | null | Implement the Python class `ConversationLayoutTab` described below.
Class description:
This class represents the conversation layout config
Method signatures and docstrings:
- def __init__(self, controller): Constructor
- def updateInfosFrame(self): Updates the htmltextview preview. | Implement the Python class `ConversationLayoutTab` described below.
Class description:
This class represents the conversation layout config
Method signatures and docstrings:
- def __init__(self, controller): Constructor
- def updateInfosFrame(self): Updates the htmltextview preview.
<|skeleton|>
class ConversationLa... | 1a99c1788f0eb9f1e5d8c2ced3892d00cd9449ad | <|skeleton|>
class ConversationLayoutTab:
"""This class represents the conversation layout config"""
def __init__(self, controller):
"""Constructor"""
<|body_0|>
def updateInfosFrame(self):
"""Updates the htmltextview preview."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConversationLayoutTab:
"""This class represents the conversation layout config"""
def __init__(self, controller):
"""Constructor"""
gtk.VBox.__init__(self)
self.controller = controller
self.config = controller.config
self.set_spacing(8)
self.set_border_widt... | the_stack_v2_python_sparse | emesene/rev1286-1505/left-trunk-1505/PreferenceWindow.py | joliebig/featurehouse_fstmerge_examples | train | 3 |
bbab6ed2284f420c0b1e85218b76b3b8863bd97d | [
"NonlinearProblem.__init__(self)\nself.type = 'snes'\nself.bcs = bcs\nself.state = state\nalpha = state['alpha']\nV = alpha.function_space()\nalpha_v = TestFunction(V)\ndalpha = TrialFunction(V)\nself.energy = energy\nself.F = derivative(energy, alpha, alpha_v)\nself.J = derivative(self.F, alpha, dalpha)\nself.lb =... | <|body_start_0|>
NonlinearProblem.__init__(self)
self.type = 'snes'
self.bcs = bcs
self.state = state
alpha = state['alpha']
V = alpha.function_space()
alpha_v = TestFunction(V)
dalpha = TrialFunction(V)
self.energy = energy
self.F = deriva... | Class for the damage problem with an NonlinearVariationalProblem. | DamageProblemSNES | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DamageProblemSNES:
"""Class for the damage problem with an NonlinearVariationalProblem."""
def __init__(self, energy, state, bcs=None):
"""Initialises the damage problem. Arguments: * energy * state * boundary conditions"""
<|body_0|>
def update_lower_bound(self):
... | stack_v2_sparse_classes_36k_train_032659 | 13,772 | permissive | [
{
"docstring": "Initialises the damage problem. Arguments: * energy * state * boundary conditions",
"name": "__init__",
"signature": "def __init__(self, energy, state, bcs=None)"
},
{
"docstring": "Update lower bound.",
"name": "update_lower_bound",
"signature": "def update_lower_bound(s... | 2 | stack_v2_sparse_classes_30k_train_016928 | Implement the Python class `DamageProblemSNES` described below.
Class description:
Class for the damage problem with an NonlinearVariationalProblem.
Method signatures and docstrings:
- def __init__(self, energy, state, bcs=None): Initialises the damage problem. Arguments: * energy * state * boundary conditions
- def ... | Implement the Python class `DamageProblemSNES` described below.
Class description:
Class for the damage problem with an NonlinearVariationalProblem.
Method signatures and docstrings:
- def __init__(self, energy, state, bcs=None): Initialises the damage problem. Arguments: * energy * state * boundary conditions
- def ... | 9a82bf40742a9b16122b7a476ad8aec65fe22539 | <|skeleton|>
class DamageProblemSNES:
"""Class for the damage problem with an NonlinearVariationalProblem."""
def __init__(self, energy, state, bcs=None):
"""Initialises the damage problem. Arguments: * energy * state * boundary conditions"""
<|body_0|>
def update_lower_bound(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DamageProblemSNES:
"""Class for the damage problem with an NonlinearVariationalProblem."""
def __init__(self, energy, state, bcs=None):
"""Initialises the damage problem. Arguments: * energy * state * boundary conditions"""
NonlinearProblem.__init__(self)
self.type = 'snes'
... | the_stack_v2_python_sparse | src/solvers.py | kumiori/stability-bifurcation | train | 1 |
0e7a0fb6d3bae406de8ccf2e614514c9c2fff34b | [
"cur_obj = self\nfor key in list_of_keys:\n cur_obj = cur_obj.get(key)\n if not cur_obj:\n break\nreturn cur_obj",
"inv_map = {}\nfor k, v in self.items():\n if sys.version_info < (3, 0):\n acceptable_v_instance = isinstance(v, (str, int, float, long))\n else:\n acceptable_v_insta... | <|body_start_0|>
cur_obj = self
for key in list_of_keys:
cur_obj = cur_obj.get(key)
if not cur_obj:
break
return cur_obj
<|end_body_0|>
<|body_start_1|>
inv_map = {}
for k, v in self.items():
if sys.version_info < (3, 0):
... | This class expands on the dictionary class by adding the gettree class method. | adv_dict | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class adv_dict:
"""This class expands on the dictionary class by adding the gettree class method."""
def get_tree(self, list_of_keys):
"""gettree will extract the value from a nested tree INPUT list_of_keys: a list of keys ie. ['key1', 'key2'] USAGE >>> # Access the value for key2 within t... | stack_v2_sparse_classes_36k_train_032660 | 22,796 | permissive | [
{
"docstring": "gettree will extract the value from a nested tree INPUT list_of_keys: a list of keys ie. ['key1', 'key2'] USAGE >>> # Access the value for key2 within the nested dictionary >>> adv_dict({'key1': {'key2': 'value'}}).gettree(['key1', 'key2']) 'value'",
"name": "get_tree",
"signature": "def... | 2 | stack_v2_sparse_classes_30k_train_007849 | Implement the Python class `adv_dict` described below.
Class description:
This class expands on the dictionary class by adding the gettree class method.
Method signatures and docstrings:
- def get_tree(self, list_of_keys): gettree will extract the value from a nested tree INPUT list_of_keys: a list of keys ie. ['key1... | Implement the Python class `adv_dict` described below.
Class description:
This class expands on the dictionary class by adding the gettree class method.
Method signatures and docstrings:
- def get_tree(self, list_of_keys): gettree will extract the value from a nested tree INPUT list_of_keys: a list of keys ie. ['key1... | b4cc546485bddbbe26de6a80b629350314db6422 | <|skeleton|>
class adv_dict:
"""This class expands on the dictionary class by adding the gettree class method."""
def get_tree(self, list_of_keys):
"""gettree will extract the value from a nested tree INPUT list_of_keys: a list of keys ie. ['key1', 'key2'] USAGE >>> # Access the value for key2 within t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class adv_dict:
"""This class expands on the dictionary class by adding the gettree class method."""
def get_tree(self, list_of_keys):
"""gettree will extract the value from a nested tree INPUT list_of_keys: a list of keys ie. ['key1', 'key2'] USAGE >>> # Access the value for key2 within the nested dic... | the_stack_v2_python_sparse | genemethods/cgecore/utility.py | OLC-LOC-Bioinformatics/genemethods | train | 1 |
1a46db908b47d7c6395d88b40c228d52ec521b2d | [
"kw = super(EventCreateView, self).get_form_kwargs()\nkw.update({'organization': self.request.user.organization})\nreturn kw",
"self.object = event = form.save(commit=False)\ndiscussion = Discussion.objects.create_discussion('EV')\nevent.discussion = discussion\nevent.owner = self.request.user\nevent.organization... | <|body_start_0|>
kw = super(EventCreateView, self).get_form_kwargs()
kw.update({'organization': self.request.user.organization})
return kw
<|end_body_0|>
<|body_start_1|>
self.object = event = form.save(commit=False)
discussion = Discussion.objects.create_discussion('EV')
... | A logged in user can create a event. Events are used to manage information about events. Events can either manage events that an organization are hosting or events that an organization is reporting on. Ex: Hosting = A townhall discussion hosted by an organization Ex: Reporting = A press conference at city hall covered ... | EventCreateView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventCreateView:
"""A logged in user can create a event. Events are used to manage information about events. Events can either manage events that an organization are hosting or events that an organization is reporting on. Ex: Hosting = A townhall discussion hosted by an organization Ex: Reporting... | stack_v2_sparse_classes_36k_train_032661 | 12,378 | permissive | [
{
"docstring": "Pass user organization to the form.",
"name": "get_form_kwargs",
"signature": "def get_form_kwargs(self)"
},
{
"docstring": "Save -- but first adding owner and organization.",
"name": "form_valid",
"signature": "def form_valid(self, form)"
}
] | 2 | null | Implement the Python class `EventCreateView` described below.
Class description:
A logged in user can create a event. Events are used to manage information about events. Events can either manage events that an organization are hosting or events that an organization is reporting on. Ex: Hosting = A townhall discussion ... | Implement the Python class `EventCreateView` described below.
Class description:
A logged in user can create a event. Events are used to manage information about events. Events can either manage events that an organization are hosting or events that an organization is reporting on. Ex: Hosting = A townhall discussion ... | dc6bc79d450f7e2bdf59cfbcd306d05a736e4db9 | <|skeleton|>
class EventCreateView:
"""A logged in user can create a event. Events are used to manage information about events. Events can either manage events that an organization are hosting or events that an organization is reporting on. Ex: Hosting = A townhall discussion hosted by an organization Ex: Reporting... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EventCreateView:
"""A logged in user can create a event. Events are used to manage information about events. Events can either manage events that an organization are hosting or events that an organization is reporting on. Ex: Hosting = A townhall discussion hosted by an organization Ex: Reporting = A press co... | the_stack_v2_python_sparse | project/editorial/views/events.py | ProjectFacet/facet | train | 25 |
6d0ffaf536049eee8a3c32159452af0db355174c | [
"self.__screen = screen\nself.__msg = TextboxReflowed(40, 'Select the device on the list to be configured:')\nself.__list = Listbox(5, scroll=1, returnExit=1)\nself.__buttonsBar = ButtonBar(self.__screen, [('OK', 'ok'), ('Back', 'back')])\nself.__devices = Network.getAvailableInterfaces(False)",
"self.__grid = Gr... | <|body_start_0|>
self.__screen = screen
self.__msg = TextboxReflowed(40, 'Select the device on the list to be configured:')
self.__list = Listbox(5, scroll=1, returnExit=1)
self.__buttonsBar = ButtonBar(self.__screen, [('OK', 'ok'), ('Back', 'back')])
self.__devices = Network.get... | Represents the network interface list screen | ListNetInterfaces | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListNetInterfaces:
"""Represents the network interface list screen"""
def __init__(self, screen):
"""Constructor @type screen: SnackScreen @param screen: SnackScreen instance"""
<|body_0|>
def __show(self):
"""Shows screen once @rtype: integer @returns: status of... | stack_v2_sparse_classes_36k_train_032662 | 3,951 | no_license | [
{
"docstring": "Constructor @type screen: SnackScreen @param screen: SnackScreen instance",
"name": "__init__",
"signature": "def __init__(self, screen)"
},
{
"docstring": "Shows screen once @rtype: integer @returns: status of operation",
"name": "__show",
"signature": "def __show(self)"... | 5 | stack_v2_sparse_classes_30k_train_013835 | Implement the Python class `ListNetInterfaces` described below.
Class description:
Represents the network interface list screen
Method signatures and docstrings:
- def __init__(self, screen): Constructor @type screen: SnackScreen @param screen: SnackScreen instance
- def __show(self): Shows screen once @rtype: intege... | Implement the Python class `ListNetInterfaces` described below.
Class description:
Represents the network interface list screen
Method signatures and docstrings:
- def __init__(self, screen): Constructor @type screen: SnackScreen @param screen: SnackScreen instance
- def __show(self): Shows screen once @rtype: intege... | 1c738fd5e6ee3f8fd4f47acf2207038f20868212 | <|skeleton|>
class ListNetInterfaces:
"""Represents the network interface list screen"""
def __init__(self, screen):
"""Constructor @type screen: SnackScreen @param screen: SnackScreen instance"""
<|body_0|>
def __show(self):
"""Shows screen once @rtype: integer @returns: status of... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ListNetInterfaces:
"""Represents the network interface list screen"""
def __init__(self, screen):
"""Constructor @type screen: SnackScreen @param screen: SnackScreen instance"""
self.__screen = screen
self.__msg = TextboxReflowed(40, 'Select the device on the list to be configured... | the_stack_v2_python_sparse | zfrobisher-installer/src/ui/networkcfg/listnetinterfaces.py | fedosu85nce/work | train | 2 |
a77697d586d356c501383e036e00184de2b9f570 | [
"key, data = symmetric_encrypt([1, 2, 3 + 2j])\nbase64.decodestring(key)\nbase64.decodestring(data)\nself.failUnlessEqual(symmetric_decrypt(key, data), [1, 2, 3 + 2j])",
"key, data = symmetric_encrypt(1)\nself.failUnlessRaises(ValueError, symmetric_decrypt, key, 'abcd')\nself.failUnlessRaises(ValueError, symmetri... | <|body_start_0|>
key, data = symmetric_encrypt([1, 2, 3 + 2j])
base64.decodestring(key)
base64.decodestring(data)
self.failUnlessEqual(symmetric_decrypt(key, data), [1, 2, 3 + 2j])
<|end_body_0|>
<|body_start_1|>
key, data = symmetric_encrypt(1)
self.failUnlessRaises(Val... | TestCardEncryption | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCardEncryption:
def testEncryption(self):
"""Test that the symmetric object encryption can encrypt and decrypt arbitrary python objects."""
<|body_0|>
def testDecryptionFailed(self):
"""Test that attempting to decrypt invalid data raises ValueError"""
<|b... | stack_v2_sparse_classes_36k_train_032663 | 3,039 | permissive | [
{
"docstring": "Test that the symmetric object encryption can encrypt and decrypt arbitrary python objects.",
"name": "testEncryption",
"signature": "def testEncryption(self)"
},
{
"docstring": "Test that attempting to decrypt invalid data raises ValueError",
"name": "testDecryptionFailed",
... | 2 | stack_v2_sparse_classes_30k_train_002595 | Implement the Python class `TestCardEncryption` described below.
Class description:
Implement the TestCardEncryption class.
Method signatures and docstrings:
- def testEncryption(self): Test that the symmetric object encryption can encrypt and decrypt arbitrary python objects.
- def testDecryptionFailed(self): Test t... | Implement the Python class `TestCardEncryption` described below.
Class description:
Implement the TestCardEncryption class.
Method signatures and docstrings:
- def testEncryption(self): Test that the symmetric object encryption can encrypt and decrypt arbitrary python objects.
- def testDecryptionFailed(self): Test t... | 0c4143021c16f7ae7b6f60da0f3f9ab37ff9eaad | <|skeleton|>
class TestCardEncryption:
def testEncryption(self):
"""Test that the symmetric object encryption can encrypt and decrypt arbitrary python objects."""
<|body_0|>
def testDecryptionFailed(self):
"""Test that attempting to decrypt invalid data raises ValueError"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestCardEncryption:
def testEncryption(self):
"""Test that the symmetric object encryption can encrypt and decrypt arbitrary python objects."""
key, data = symmetric_encrypt([1, 2, 3 + 2j])
base64.decodestring(key)
base64.decodestring(data)
self.failUnlessEqual(symmetri... | the_stack_v2_python_sparse | mauveinternet/ordering/tests.py | lordmauve/django-mauveinternet | train | 0 | |
22af5ebcea32d8d858a31947481f1d5e109e5280 | [
"super().__init__()\nself._registry = {}\nel = gremlin.event_handler.EventListener()\nel.joystick_event.connect(self._joystick_cb)",
"release_evt = physical_event.clone()\nrelease_evt.is_pressed = False\nif release_evt not in self._registry:\n self._registry[release_evt] = []\nself._registry[release_evt].appen... | <|body_start_0|>
super().__init__()
self._registry = {}
el = gremlin.event_handler.EventListener()
el.joystick_event.connect(self._joystick_cb)
<|end_body_0|>
<|body_start_1|>
release_evt = physical_event.clone()
release_evt.is_pressed = False
if release_evt not ... | Runs specified callback on release of an input. | OnReleaseExecutor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OnReleaseExecutor:
"""Runs specified callback on release of an input."""
def __init__(self):
"""Creates a new instance."""
<|body_0|>
def register(self, callback, physical_event):
"""Register a callback to run for a particular event. :param callback the function ... | stack_v2_sparse_classes_36k_train_032664 | 2,935 | no_license | [
{
"docstring": "Creates a new instance.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Register a callback to run for a particular event. :param callback the function to run when the specified input is released :param physical_event the event describing the event on w... | 3 | stack_v2_sparse_classes_30k_train_008617 | Implement the Python class `OnReleaseExecutor` described below.
Class description:
Runs specified callback on release of an input.
Method signatures and docstrings:
- def __init__(self): Creates a new instance.
- def register(self, callback, physical_event): Register a callback to run for a particular event. :param c... | Implement the Python class `OnReleaseExecutor` described below.
Class description:
Runs specified callback on release of an input.
Method signatures and docstrings:
- def __init__(self): Creates a new instance.
- def register(self, callback, physical_event): Register a callback to run for a particular event. :param c... | 4788dd811f42b2654bdb00bb9f9e51f63a26abf0 | <|skeleton|>
class OnReleaseExecutor:
"""Runs specified callback on release of an input."""
def __init__(self):
"""Creates a new instance."""
<|body_0|>
def register(self, callback, physical_event):
"""Register a callback to run for a particular event. :param callback the function ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OnReleaseExecutor:
"""Runs specified callback on release of an input."""
def __init__(self):
"""Creates a new instance."""
super().__init__()
self._registry = {}
el = gremlin.event_handler.EventListener()
el.joystick_event.connect(self._joystick_cb)
def regist... | the_stack_v2_python_sparse | temporary_mode_switch.py | WhiteMagic/JoystickGremlinModules | train | 5 |
f3a4d41e75f6def5ca56c1e955dc41618d7087d8 | [
"SuperbiasRaftTableAnalysisTask.__init__(self, **kwargs)\nself._mask_file_dict = {}\nself._sbias_file_dict = {}\nself._sbias_arrays = None\nself._sbias_images = None",
"self.safe_update(**kwargs)\nself._mask_file_dict = {}\nself._sbias_file_dict = {}\nif butler is not None:\n self.log.warn('Ignoring butler')\n... | <|body_start_0|>
SuperbiasRaftTableAnalysisTask.__init__(self, **kwargs)
self._mask_file_dict = {}
self._sbias_file_dict = {}
self._sbias_arrays = None
self._sbias_images = None
<|end_body_0|>
<|body_start_1|>
self.safe_update(**kwargs)
self._mask_file_dict = {}
... | Analyze the outliers in Superbias frames for a raft | SuperbiasRaftTask | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SuperbiasRaftTask:
"""Analyze the outliers in Superbias frames for a raft"""
def __init__(self, **kwargs):
"""C'tor Parameters ---------- kwargs Used to override configruation"""
<|body_0|>
def extract(self, butler, data, **kwargs):
"""Extract the outliers in the... | stack_v2_sparse_classes_36k_train_032665 | 15,893 | permissive | [
{
"docstring": "C'tor Parameters ---------- kwargs Used to override configruation",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Extract the outliers in the superbias frames for the raft Parameters ---------- butler : `Butler` The data butler data : `dict` D... | 4 | stack_v2_sparse_classes_30k_train_007228 | Implement the Python class `SuperbiasRaftTask` described below.
Class description:
Analyze the outliers in Superbias frames for a raft
Method signatures and docstrings:
- def __init__(self, **kwargs): C'tor Parameters ---------- kwargs Used to override configruation
- def extract(self, butler, data, **kwargs): Extrac... | Implement the Python class `SuperbiasRaftTask` described below.
Class description:
Analyze the outliers in Superbias frames for a raft
Method signatures and docstrings:
- def __init__(self, **kwargs): C'tor Parameters ---------- kwargs Used to override configruation
- def extract(self, butler, data, **kwargs): Extrac... | 28418284fdaf2b2fb0afbeccd4324f7ad3e676c8 | <|skeleton|>
class SuperbiasRaftTask:
"""Analyze the outliers in Superbias frames for a raft"""
def __init__(self, **kwargs):
"""C'tor Parameters ---------- kwargs Used to override configruation"""
<|body_0|>
def extract(self, butler, data, **kwargs):
"""Extract the outliers in the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SuperbiasRaftTask:
"""Analyze the outliers in Superbias frames for a raft"""
def __init__(self, **kwargs):
"""C'tor Parameters ---------- kwargs Used to override configruation"""
SuperbiasRaftTableAnalysisTask.__init__(self, **kwargs)
self._mask_file_dict = {}
self._sbias_... | the_stack_v2_python_sparse | python/lsst/eo_utils/bias/superbias.py | lsst-camera-dh/EO-utilities | train | 2 |
094209d58c1bab6774689f50f184c901534bf2bd | [
"super().__init__(ui_cfg)\nself.colors = {label.name: np.array(label.color) for label in labels if not label.hasInstances}\nself.colors.update({drivable.name: np.array(drivable.color) for drivable in drivables})\nself.colors.update({lane.name: np.array(lane.color) for lane in lane_categories})",
"if label.categor... | <|body_start_0|>
super().__init__(ui_cfg)
self.colors = {label.name: np.array(label.color) for label in labels if not label.hasInstances}
self.colors.update({drivable.name: np.array(drivable.color) for drivable in drivables})
self.colors.update({lane.name: np.array(lane.color) for lane i... | Basic class for viewing BDD100K labels. | LabelViewerBDD100K | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LabelViewerBDD100K:
"""Basic class for viewing BDD100K labels."""
def __init__(self, ui_cfg: UIConfig) -> None:
"""Initializer."""
<|body_0|>
def _get_label_color(self, label: Label) -> NDArrayF64:
"""Get color by category and id."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k_train_032666 | 5,193 | permissive | [
{
"docstring": "Initializer.",
"name": "__init__",
"signature": "def __init__(self, ui_cfg: UIConfig) -> None"
},
{
"docstring": "Get color by category and id.",
"name": "_get_label_color",
"signature": "def _get_label_color(self, label: Label) -> NDArrayF64"
}
] | 2 | stack_v2_sparse_classes_30k_train_012398 | Implement the Python class `LabelViewerBDD100K` described below.
Class description:
Basic class for viewing BDD100K labels.
Method signatures and docstrings:
- def __init__(self, ui_cfg: UIConfig) -> None: Initializer.
- def _get_label_color(self, label: Label) -> NDArrayF64: Get color by category and id. | Implement the Python class `LabelViewerBDD100K` described below.
Class description:
Basic class for viewing BDD100K labels.
Method signatures and docstrings:
- def __init__(self, ui_cfg: UIConfig) -> None: Initializer.
- def _get_label_color(self, label: Label) -> NDArrayF64: Get color by category and id.
<|skeleton... | a4bfa9dc0c79abe90b2c06d20e84b79fbd9f2e38 | <|skeleton|>
class LabelViewerBDD100K:
"""Basic class for viewing BDD100K labels."""
def __init__(self, ui_cfg: UIConfig) -> None:
"""Initializer."""
<|body_0|>
def _get_label_color(self, label: Label) -> NDArrayF64:
"""Get color by category and id."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LabelViewerBDD100K:
"""Basic class for viewing BDD100K labels."""
def __init__(self, ui_cfg: UIConfig) -> None:
"""Initializer."""
super().__init__(ui_cfg)
self.colors = {label.name: np.array(label.color) for label in labels if not label.hasInstances}
self.colors.update({d... | the_stack_v2_python_sparse | bdd100k/vis/viewer.py | navcul3108/bdd100k | train | 0 |
c14a9c2931a77babbafc7e38cf444e26f0d050ff | [
"self.k = k\nheapq.heapify(nums)\nself.heap = nums\nwhile len(self.heap) > k:\n heapq.heappop(self.heap)",
"if len(self.heap) < self.k:\n heapq.heappush(self.heap, val)\nelse:\n heapq.heappushpop(self.heap, val)\nreturn self.heap[0]"
] | <|body_start_0|>
self.k = k
heapq.heapify(nums)
self.heap = nums
while len(self.heap) > k:
heapq.heappop(self.heap)
<|end_body_0|>
<|body_start_1|>
if len(self.heap) < self.k:
heapq.heappush(self.heap, val)
else:
heapq.heappushpop(self... | KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.k = k
heapq.heapify(nums)
self.heap =... | stack_v2_sparse_classes_36k_train_032667 | 3,840 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | null | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, nu... | 5195b032d8000a3d888e2d4068984011bebd3b84 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
self.k = k
heapq.heapify(nums)
self.heap = nums
while len(self.heap) > k:
heapq.heappop(self.heap)
def add(self, val):
""":type val: int :rtype: int"""
if ... | the_stack_v2_python_sparse | leetcode_python/Heap/kth_largest_element_in_a_stream.py | ChillOrb/CS_basics | train | 1 | |
de56eabe2967d6f078fd6a5a396c1a68fb8d9956 | [
"Thread.__init__(self)\nself.global_var = global_var\nself.daemon = True",
"while True:\n time.sleep(2)\n if self.global_var['sequence']:\n if queue_manager.nb_seq_in_queue() != 0:\n queue_manager.set_current_thread()\n time.sleep(2)\n queue_manager.current_thread.sta... | <|body_start_0|>
Thread.__init__(self)
self.global_var = global_var
self.daemon = True
<|end_body_0|>
<|body_start_1|>
while True:
time.sleep(2)
if self.global_var['sequence']:
if queue_manager.nb_seq_in_queue() != 0:
queue_man... | Class daemon thread to manage Queue | SequenceManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequenceManager:
"""Class daemon thread to manage Queue"""
def __init__(self, global_var):
"""Constructor of SequenceManager :param global_var: global var of API"""
<|body_0|>
def run(self):
"""callback function of the thread this function manage the queue of the... | stack_v2_sparse_classes_36k_train_032668 | 1,008 | no_license | [
{
"docstring": "Constructor of SequenceManager :param global_var: global var of API",
"name": "__init__",
"signature": "def __init__(self, global_var)"
},
{
"docstring": "callback function of the thread this function manage the queue of the API :return: end of daemon thread",
"name": "run",
... | 2 | stack_v2_sparse_classes_30k_train_012770 | Implement the Python class `SequenceManager` described below.
Class description:
Class daemon thread to manage Queue
Method signatures and docstrings:
- def __init__(self, global_var): Constructor of SequenceManager :param global_var: global var of API
- def run(self): callback function of the thread this function ma... | Implement the Python class `SequenceManager` described below.
Class description:
Class daemon thread to manage Queue
Method signatures and docstrings:
- def __init__(self, global_var): Constructor of SequenceManager :param global_var: global var of API
- def run(self): callback function of the thread this function ma... | de1408317d5071b7e0c6b2fea6f281660115d728 | <|skeleton|>
class SequenceManager:
"""Class daemon thread to manage Queue"""
def __init__(self, global_var):
"""Constructor of SequenceManager :param global_var: global var of API"""
<|body_0|>
def run(self):
"""callback function of the thread this function manage the queue of the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SequenceManager:
"""Class daemon thread to manage Queue"""
def __init__(self, global_var):
"""Constructor of SequenceManager :param global_var: global var of API"""
Thread.__init__(self)
self.global_var = global_var
self.daemon = True
def run(self):
"""callbac... | the_stack_v2_python_sparse | api/package/sequence/sequence_manager.py | HE-Arc/Extrusion---web-interface | train | 4 |
8ccad1b60dc0c9188f77fd4ed71223e7cebd2f6a | [
"product = get_object_or_404(Product, id=id)\nform = ProductForm(instance=product)\nreturn render(request, 'product/add-product.html', {'form': form, 'func': 'Update', 'product': product})",
"product = get_object_or_404(Product, id=id)\nform = ProductForm(request.POST, instance=product)\nhas_images = ProductImage... | <|body_start_0|>
product = get_object_or_404(Product, id=id)
form = ProductForm(instance=product)
return render(request, 'product/add-product.html', {'form': form, 'func': 'Update', 'product': product})
<|end_body_0|>
<|body_start_1|>
product = get_object_or_404(Product, id=id)
... | Class based view for Updating new product. | ProductUpdateView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductUpdateView:
"""Class based view for Updating new product."""
def get(self, request, id):
"""Return Update new product form."""
<|body_0|>
def post(self, request, id):
"""Update product and redirect to product list."""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_032669 | 3,759 | no_license | [
{
"docstring": "Return Update new product form.",
"name": "get",
"signature": "def get(self, request, id)"
},
{
"docstring": "Update product and redirect to product list.",
"name": "post",
"signature": "def post(self, request, id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021167 | Implement the Python class `ProductUpdateView` described below.
Class description:
Class based view for Updating new product.
Method signatures and docstrings:
- def get(self, request, id): Return Update new product form.
- def post(self, request, id): Update product and redirect to product list. | Implement the Python class `ProductUpdateView` described below.
Class description:
Class based view for Updating new product.
Method signatures and docstrings:
- def get(self, request, id): Return Update new product form.
- def post(self, request, id): Update product and redirect to product list.
<|skeleton|>
class ... | 93c3106ab90fb9aed85658f93f51686ba4734091 | <|skeleton|>
class ProductUpdateView:
"""Class based view for Updating new product."""
def get(self, request, id):
"""Return Update new product form."""
<|body_0|>
def post(self, request, id):
"""Update product and redirect to product list."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProductUpdateView:
"""Class based view for Updating new product."""
def get(self, request, id):
"""Return Update new product form."""
product = get_object_or_404(Product, id=id)
form = ProductForm(instance=product)
return render(request, 'product/add-product.html', {'form'... | the_stack_v2_python_sparse | product/views/product_views.py | saadali5997/tms | train | 0 |
3c4f7cc9f1c85f714a73560c37b8b5a14bccfd7d | [
"params = {'phone': phone, 'message': message}\nif extension is not None:\n params['extension'] = extension\nif predelay is not None:\n params['predelay'] = predelay\nif postdelay is not None:\n params['postdelay'] = postdelay\nif digits is not None:\n params['digits'] = str(int(digits))\nresponse = sel... | <|body_start_0|>
params = {'phone': phone, 'message': message}
if extension is not None:
params['extension'] = extension
if predelay is not None:
params['predelay'] = predelay
if postdelay is not None:
params['postdelay'] = postdelay
if digits ... | Verify | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Verify:
def call(self, phone, extension=None, predelay=None, postdelay=None, message='The PIN is <pin>', digits=None):
"""Return a (PIN, txid) tuple from the response for a call API call."""
<|body_0|>
def status(self, txid):
"""Return the response for a status API c... | stack_v2_sparse_classes_36k_train_032670 | 1,681 | permissive | [
{
"docstring": "Return a (PIN, txid) tuple from the response for a call API call.",
"name": "call",
"signature": "def call(self, phone, extension=None, predelay=None, postdelay=None, message='The PIN is <pin>', digits=None)"
},
{
"docstring": "Return the response for a status API call.",
"na... | 3 | null | Implement the Python class `Verify` described below.
Class description:
Implement the Verify class.
Method signatures and docstrings:
- def call(self, phone, extension=None, predelay=None, postdelay=None, message='The PIN is <pin>', digits=None): Return a (PIN, txid) tuple from the response for a call API call.
- def... | Implement the Python class `Verify` described below.
Class description:
Implement the Verify class.
Method signatures and docstrings:
- def call(self, phone, extension=None, predelay=None, postdelay=None, message='The PIN is <pin>', digits=None): Return a (PIN, txid) tuple from the response for a call API call.
- def... | 718d15ca36c57231bb89df0aebc53d0210db400c | <|skeleton|>
class Verify:
def call(self, phone, extension=None, predelay=None, postdelay=None, message='The PIN is <pin>', digits=None):
"""Return a (PIN, txid) tuple from the response for a call API call."""
<|body_0|>
def status(self, txid):
"""Return the response for a status API c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Verify:
def call(self, phone, extension=None, predelay=None, postdelay=None, message='The PIN is <pin>', digits=None):
"""Return a (PIN, txid) tuple from the response for a call API call."""
params = {'phone': phone, 'message': message}
if extension is not None:
params['ext... | the_stack_v2_python_sparse | plugins/duo_auth/vendor/duo_client_python/duo_client/verify.py | rapid7/insightconnect-plugins | train | 61 | |
974aaf0bc1a3ac8bdf6a1863da1241bd8823d0c8 | [
"if isinstance(inf_rules, dict):\n inf_rules = [inf_rules]\nelif not isinstance(inf_rules, tuple):\n inf_rules = list(inf_rules)\nelif not isinstance(inf_rules, list):\n raise TypeError(f'inf_rules must be a dict or a collection of dict, not {type(inf_rules)}')\nself.commutative = commutative\nself.inf_rul... | <|body_start_0|>
if isinstance(inf_rules, dict):
inf_rules = [inf_rules]
elif not isinstance(inf_rules, tuple):
inf_rules = list(inf_rules)
elif not isinstance(inf_rules, list):
raise TypeError(f'inf_rules must be a dict or a collection of dict, not {type(inf_... | Type inference rule for a set of operations. TODO: Move TypeRule to registry.py | TypeRule | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TypeRule:
"""Type inference rule for a set of operations. TODO: Move TypeRule to registry.py"""
def __init__(self, inf_rules, commutative=False):
"""Parameters ---------- inf_rules : a dictionary or a collection of dictionaries The inference rules for the operation class Each item sh... | stack_v2_sparse_classes_36k_train_032671 | 10,492 | permissive | [
{
"docstring": "Parameters ---------- inf_rules : a dictionary or a collection of dictionaries The inference rules for the operation class Each item should be (input types, lambda function)",
"name": "__init__",
"signature": "def __init__(self, inf_rules, commutative=False)"
},
{
"docstring": "C... | 2 | stack_v2_sparse_classes_30k_test_000533 | Implement the Python class `TypeRule` described below.
Class description:
Type inference rule for a set of operations. TODO: Move TypeRule to registry.py
Method signatures and docstrings:
- def __init__(self, inf_rules, commutative=False): Parameters ---------- inf_rules : a dictionary or a collection of dictionaries... | Implement the Python class `TypeRule` described below.
Class description:
Type inference rule for a set of operations. TODO: Move TypeRule to registry.py
Method signatures and docstrings:
- def __init__(self, inf_rules, commutative=False): Parameters ---------- inf_rules : a dictionary or a collection of dictionaries... | b794409e68e326cafa6c3eaec2e3560ff066e129 | <|skeleton|>
class TypeRule:
"""Type inference rule for a set of operations. TODO: Move TypeRule to registry.py"""
def __init__(self, inf_rules, commutative=False):
"""Parameters ---------- inf_rules : a dictionary or a collection of dictionaries The inference rules for the operation class Each item sh... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TypeRule:
"""Type inference rule for a set of operations. TODO: Move TypeRule to registry.py"""
def __init__(self, inf_rules, commutative=False):
"""Parameters ---------- inf_rules : a dictionary or a collection of dictionaries The inference rules for the operation class Each item should be (inpu... | the_stack_v2_python_sparse | heterocl/types.py | cornell-zhang/heterocl | train | 312 |
3170646c3dc3f1c06a465a3d427cab169e89de74 | [
"if mibs_location:\n self.src_directories = mibs_location\nif type(self.src_directories) != list:\n self.src_directories = [self.src_directories]\nfor d in self.src_directories:\n if not os.path.exists(str(d)):\n msg = 'No mibs directory {} found test_SnmpHelper.'.format(str(d))\n raise Excep... | <|body_start_0|>
if mibs_location:
self.src_directories = mibs_location
if type(self.src_directories) != list:
self.src_directories = [self.src_directories]
for d in self.src_directories:
if not os.path.exists(str(d)):
msg = 'No mibs directory ... | Unit test for the SnmpMibs class to be run as a standalone module DEBUG: BFT_DEBUG=y shows the compiled dictionary BFT_DEBUG=yy VERY verbose, shows the compiled dictionary and mibs/oid details | SnmpMibsUnitTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnmpMibsUnitTest:
"""Unit test for the SnmpMibs class to be run as a standalone module DEBUG: BFT_DEBUG=y shows the compiled dictionary BFT_DEBUG=yy VERY verbose, shows the compiled dictionary and mibs/oid details"""
def __init__(self, mibs_location=None, files=None, mibs=None, err_mibs=None... | stack_v2_sparse_classes_36k_train_032672 | 18,780 | permissive | [
{
"docstring": "Takes: mibs_location: where the .mib files are located (can be a list of dirs) files: the name of the .mib/.txt files (without the extension) mibs: e.g. sysDescr, sysObjectID, etc err_mibs: wrong mibs (just for testing that the compiler rejects invalid mibs)",
"name": "__init__",
"signat... | 2 | stack_v2_sparse_classes_30k_train_005350 | Implement the Python class `SnmpMibsUnitTest` described below.
Class description:
Unit test for the SnmpMibs class to be run as a standalone module DEBUG: BFT_DEBUG=y shows the compiled dictionary BFT_DEBUG=yy VERY verbose, shows the compiled dictionary and mibs/oid details
Method signatures and docstrings:
- def __i... | Implement the Python class `SnmpMibsUnitTest` described below.
Class description:
Unit test for the SnmpMibs class to be run as a standalone module DEBUG: BFT_DEBUG=y shows the compiled dictionary BFT_DEBUG=yy VERY verbose, shows the compiled dictionary and mibs/oid details
Method signatures and docstrings:
- def __i... | 100521fde1fb67536682cafecc2f91a6e2e8a6f8 | <|skeleton|>
class SnmpMibsUnitTest:
"""Unit test for the SnmpMibs class to be run as a standalone module DEBUG: BFT_DEBUG=y shows the compiled dictionary BFT_DEBUG=yy VERY verbose, shows the compiled dictionary and mibs/oid details"""
def __init__(self, mibs_location=None, files=None, mibs=None, err_mibs=None... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SnmpMibsUnitTest:
"""Unit test for the SnmpMibs class to be run as a standalone module DEBUG: BFT_DEBUG=y shows the compiled dictionary BFT_DEBUG=yy VERY verbose, shows the compiled dictionary and mibs/oid details"""
def __init__(self, mibs_location=None, files=None, mibs=None, err_mibs=None):
""... | the_stack_v2_python_sparse | boardfarm/lib/SnmpHelper.py | mattsm/boardfarm | train | 45 |
93363cb133ae6e253c3de699b676f4cd58f3335f | [
"serialized_enrollments_map = {}\nfor course_run in mmtrack.get_all_enrolled_course_runs():\n course_title = course_run.course.title\n if course_title not in serialized_enrollments_map or serialized_enrollments_map[course_title]['payment_status'] == cls.UNPAID_STATUS:\n serialized_enrollments_map[cours... | <|body_start_0|>
serialized_enrollments_map = {}
for course_run in mmtrack.get_all_enrolled_course_runs():
course_title = course_run.course.title
if course_title not in serialized_enrollments_map or serialized_enrollments_map[course_title]['payment_status'] == cls.UNPAID_STATUS:
... | Provides functions for serializing a ProgramEnrollment for the ES index | UserProgramSearchSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserProgramSearchSerializer:
"""Provides functions for serializing a ProgramEnrollment for the ES index"""
def serialize_enrollments(cls, mmtrack):
"""Serializes a user's enrollment data for search results in such a way that enrollments in multiple runs of a single course will result... | stack_v2_sparse_classes_36k_train_032673 | 3,363 | no_license | [
{
"docstring": "Serializes a user's enrollment data for search results in such a way that enrollments in multiple runs of a single course will result in just one serialization. Args: mmtrack (MMTrack): An MMTrack object Returns: list: Serialized course enrollments",
"name": "serialize_enrollments",
"sig... | 4 | stack_v2_sparse_classes_30k_train_008188 | Implement the Python class `UserProgramSearchSerializer` described below.
Class description:
Provides functions for serializing a ProgramEnrollment for the ES index
Method signatures and docstrings:
- def serialize_enrollments(cls, mmtrack): Serializes a user's enrollment data for search results in such a way that en... | Implement the Python class `UserProgramSearchSerializer` described below.
Class description:
Provides functions for serializing a ProgramEnrollment for the ES index
Method signatures and docstrings:
- def serialize_enrollments(cls, mmtrack): Serializes a user's enrollment data for search results in such a way that en... | 3c13f5b3c738338ab950450b2dc2519f40f9f7bb | <|skeleton|>
class UserProgramSearchSerializer:
"""Provides functions for serializing a ProgramEnrollment for the ES index"""
def serialize_enrollments(cls, mmtrack):
"""Serializes a user's enrollment data for search results in such a way that enrollments in multiple runs of a single course will result... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserProgramSearchSerializer:
"""Provides functions for serializing a ProgramEnrollment for the ES index"""
def serialize_enrollments(cls, mmtrack):
"""Serializes a user's enrollment data for search results in such a way that enrollments in multiple runs of a single course will result in just one ... | the_stack_v2_python_sparse | dashboard/serializers.py | Excel-Chart/micromasters | train | 0 |
fee0295b795b17fad2a7b8699dfa34dd1503edc4 | [
"if len(argv) > 1:\n return False\nif not stdin.isatty():\n cls.buf_in = unicode(stdin.read()).strip()\n return len(cls.buf_in) > 0\nreturn False",
"args = {'name': '', 'signature': ''}\nexp = compile(AUTHORITY_REGEXPR, UNICODE)\nmatches = exp.match(cls.buf_in)\nif matches is None:\n args.update({'nam... | <|body_start_0|>
if len(argv) > 1:
return False
if not stdin.isatty():
cls.buf_in = unicode(stdin.read()).strip()
return len(cls.buf_in) > 0
return False
<|end_body_0|>
<|body_start_1|>
args = {'name': '', 'signature': ''}
exp = compile(AUTHOR... | Standard stream data wrapper. Arguments: buf_in (str): Input buffer used to store piped stdin. | StreamData | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StreamData:
"""Standard stream data wrapper. Arguments: buf_in (str): Input buffer used to store piped stdin."""
def read(cls):
"""Check if authority is piped. Returns: bool: True if data is piped, otherwise False."""
<|body_0|>
def parse(cls):
"""Parse input buf... | stack_v2_sparse_classes_36k_train_032674 | 2,651 | permissive | [
{
"docstring": "Check if authority is piped. Returns: bool: True if data is piped, otherwise False.",
"name": "read",
"signature": "def read(cls)"
},
{
"docstring": "Parse input buffer. Returns: dict: Dictionary with arguments.",
"name": "parse",
"signature": "def parse(cls)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012935 | Implement the Python class `StreamData` described below.
Class description:
Standard stream data wrapper. Arguments: buf_in (str): Input buffer used to store piped stdin.
Method signatures and docstrings:
- def read(cls): Check if authority is piped. Returns: bool: True if data is piped, otherwise False.
- def parse(... | Implement the Python class `StreamData` described below.
Class description:
Standard stream data wrapper. Arguments: buf_in (str): Input buffer used to store piped stdin.
Method signatures and docstrings:
- def read(cls): Check if authority is piped. Returns: bool: True if data is piped, otherwise False.
- def parse(... | 19950a7da374f6691ec525e4e8539e0d98faabeb | <|skeleton|>
class StreamData:
"""Standard stream data wrapper. Arguments: buf_in (str): Input buffer used to store piped stdin."""
def read(cls):
"""Check if authority is piped. Returns: bool: True if data is piped, otherwise False."""
<|body_0|>
def parse(cls):
"""Parse input buf... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StreamData:
"""Standard stream data wrapper. Arguments: buf_in (str): Input buffer used to store piped stdin."""
def read(cls):
"""Check if authority is piped. Returns: bool: True if data is piped, otherwise False."""
if len(argv) > 1:
return False
if not stdin.isatty(... | the_stack_v2_python_sparse | unlocker/stream.py | lexndru/unlocker | train | 4 |
46eaf4e96daee8278f60a59014c442029ea451a6 | [
"dic = {}\ni = 0\nwhile head:\n dic[i] = head.val\n head = head.next\n i += 1\nreturn dic[i // 2]",
"slow = fast = head\nwhile fast and fast.next:\n slow = slow.next\n fast = fast.next.next\nreturn slow"
] | <|body_start_0|>
dic = {}
i = 0
while head:
dic[i] = head.val
head = head.next
i += 1
return dic[i // 2]
<|end_body_0|>
<|body_start_1|>
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def middleNode(self, head):
"""time O(n) space O(n) :type head: ListNode :rtype: ListNode"""
<|body_0|>
def middleNode_slow_fast(self, head):
"""When traversing the list with a pointer slow, make another pointer fast that traverses twice as fast. When fast ... | stack_v2_sparse_classes_36k_train_032675 | 972 | no_license | [
{
"docstring": "time O(n) space O(n) :type head: ListNode :rtype: ListNode",
"name": "middleNode",
"signature": "def middleNode(self, head)"
},
{
"docstring": "When traversing the list with a pointer slow, make another pointer fast that traverses twice as fast. When fast reaches the end of the l... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def middleNode(self, head): time O(n) space O(n) :type head: ListNode :rtype: ListNode
- def middleNode_slow_fast(self, head): When traversing the list with a pointer slow, make ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def middleNode(self, head): time O(n) space O(n) :type head: ListNode :rtype: ListNode
- def middleNode_slow_fast(self, head): When traversing the list with a pointer slow, make ... | 85f71621c54f6b0029f3a2746f022f89dd7419d9 | <|skeleton|>
class Solution:
def middleNode(self, head):
"""time O(n) space O(n) :type head: ListNode :rtype: ListNode"""
<|body_0|>
def middleNode_slow_fast(self, head):
"""When traversing the list with a pointer slow, make another pointer fast that traverses twice as fast. When fast ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def middleNode(self, head):
"""time O(n) space O(n) :type head: ListNode :rtype: ListNode"""
dic = {}
i = 0
while head:
dic[i] = head.val
head = head.next
i += 1
return dic[i // 2]
def middleNode_slow_fast(self, head):
... | the_stack_v2_python_sparse | LeetCode/LinkedList/876_middle_of_the_linked_list.py | XyK0907/for_work | train | 0 | |
779e6839dc10c3c81f54eb477406e822a2a8eb44 | [
"super().__init__(logger=logger, config=config, timezone=timezone, max_length=max_length)\nself.user_dic = user_dic or config.get('janome_userdic') if config else None\nif self.user_dic:\n self.tokenizer = Tokenizer(self.user_dic, udic_enc='utf8')\nelse:\n self.tokenizer = Tokenizer()",
"if self.validate(te... | <|body_start_0|>
super().__init__(logger=logger, config=config, timezone=timezone, max_length=max_length)
self.user_dic = user_dic or config.get('janome_userdic') if config else None
if self.user_dic:
self.tokenizer = Tokenizer(self.user_dic, udic_enc='utf8')
else:
... | Tagger using Janome Attributes ---------- config : minette.Config Configuration timezone : pytz.timezone Timezone logger : logging.Logger Logger | JanomeTagger | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JanomeTagger:
"""Tagger using Janome Attributes ---------- config : minette.Config Configuration timezone : pytz.timezone Timezone logger : logging.Logger Logger"""
def __init__(self, config=None, timezone=None, logger=None, *, max_length=Tagger.MAX_LENGTH, user_dic=None, **kwargs):
... | stack_v2_sparse_classes_36k_train_032676 | 3,694 | permissive | [
{
"docstring": "Parameters ---------- config : Config, default None Configuration timezone : timezone, default None Timezone logger : Logger, default None Logger max_length : int, default 1000 Max length of the text to parse user_dic : str, default None Path to user dictionary (MeCab IPADIC format)",
"name"... | 2 | stack_v2_sparse_classes_30k_train_018368 | Implement the Python class `JanomeTagger` described below.
Class description:
Tagger using Janome Attributes ---------- config : minette.Config Configuration timezone : pytz.timezone Timezone logger : logging.Logger Logger
Method signatures and docstrings:
- def __init__(self, config=None, timezone=None, logger=None,... | Implement the Python class `JanomeTagger` described below.
Class description:
Tagger using Janome Attributes ---------- config : minette.Config Configuration timezone : pytz.timezone Timezone logger : logging.Logger Logger
Method signatures and docstrings:
- def __init__(self, config=None, timezone=None, logger=None,... | dd8cd7d244b6e6e4133c8e73d637ded8a8c6846f | <|skeleton|>
class JanomeTagger:
"""Tagger using Janome Attributes ---------- config : minette.Config Configuration timezone : pytz.timezone Timezone logger : logging.Logger Logger"""
def __init__(self, config=None, timezone=None, logger=None, *, max_length=Tagger.MAX_LENGTH, user_dic=None, **kwargs):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JanomeTagger:
"""Tagger using Janome Attributes ---------- config : minette.Config Configuration timezone : pytz.timezone Timezone logger : logging.Logger Logger"""
def __init__(self, config=None, timezone=None, logger=None, *, max_length=Tagger.MAX_LENGTH, user_dic=None, **kwargs):
"""Parameters... | the_stack_v2_python_sparse | minette/tagger/janometagger.py | uezo/minette-python | train | 33 |
4f4f0ecc79e175706a982bf3f9a2faa91673e885 | [
"ENFORCER.enforce_call(action='identity:check_system_grant_for_group', build_target=_build_enforcement_target)\nPROVIDERS.assignment_api.check_system_grant_for_group(group_id, role_id)\nreturn (None, http_client.NO_CONTENT)",
"ENFORCER.enforce_call(action='identity:create_system_grant_for_group', build_target=_bu... | <|body_start_0|>
ENFORCER.enforce_call(action='identity:check_system_grant_for_group', build_target=_build_enforcement_target)
PROVIDERS.assignment_api.check_system_grant_for_group(group_id, role_id)
return (None, http_client.NO_CONTENT)
<|end_body_0|>
<|body_start_1|>
ENFORCER.enforce_... | SystemGroupsRolestResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SystemGroupsRolestResource:
def get(self, group_id, role_id):
"""Check if a group has a specific role on the system. GET/HEAD /system/groups/{group_id}/roles/{role_id}"""
<|body_0|>
def put(self, group_id, role_id):
"""Grant a role to a group on the system. PUT /syst... | stack_v2_sparse_classes_36k_train_032677 | 7,288 | permissive | [
{
"docstring": "Check if a group has a specific role on the system. GET/HEAD /system/groups/{group_id}/roles/{role_id}",
"name": "get",
"signature": "def get(self, group_id, role_id)"
},
{
"docstring": "Grant a role to a group on the system. PUT /system/groups/{group_id}/roles/{role_id}",
"n... | 3 | null | Implement the Python class `SystemGroupsRolestResource` described below.
Class description:
Implement the SystemGroupsRolestResource class.
Method signatures and docstrings:
- def get(self, group_id, role_id): Check if a group has a specific role on the system. GET/HEAD /system/groups/{group_id}/roles/{role_id}
- def... | Implement the Python class `SystemGroupsRolestResource` described below.
Class description:
Implement the SystemGroupsRolestResource class.
Method signatures and docstrings:
- def get(self, group_id, role_id): Check if a group has a specific role on the system. GET/HEAD /system/groups/{group_id}/roles/{role_id}
- def... | 03a0a8146a78682ede9eca12a5a7fdacde2035c8 | <|skeleton|>
class SystemGroupsRolestResource:
def get(self, group_id, role_id):
"""Check if a group has a specific role on the system. GET/HEAD /system/groups/{group_id}/roles/{role_id}"""
<|body_0|>
def put(self, group_id, role_id):
"""Grant a role to a group on the system. PUT /syst... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SystemGroupsRolestResource:
def get(self, group_id, role_id):
"""Check if a group has a specific role on the system. GET/HEAD /system/groups/{group_id}/roles/{role_id}"""
ENFORCER.enforce_call(action='identity:check_system_grant_for_group', build_target=_build_enforcement_target)
PROVI... | the_stack_v2_python_sparse | keystone/api/system.py | sapcc/keystone | train | 0 | |
6b7176396db26a99ad6ff5884c402513ca499dca | [
"s = ''\nq = deque([root])\nwhile len(q):\n n = q.popleft()\n if n is None:\n s += Codec.NULL + Codec.DELIM\n else:\n s += str(n.val) + Codec.DELIM\n q.append(n.left)\n q.append(n.right)\nreturn s[:-1]",
"nodes = data.split(Codec.DELIM)\ncreate_node = lambda s: TreeNode(int(s)... | <|body_start_0|>
s = ''
q = deque([root])
while len(q):
n = q.popleft()
if n is None:
s += Codec.NULL + Codec.DELIM
else:
s += str(n.val) + Codec.DELIM
q.append(n.left)
q.append(n.right)
r... | 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_36k_train_032678 | 1,411 | 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_013491 | 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:... | 8a6954928acb0961ec3b65d7b7882305c0e617cf | <|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_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
s = ''
q = deque([root])
while len(q):
n = q.popleft()
if n is None:
s += Codec.NULL + Codec.DELIM
else:
... | the_stack_v2_python_sparse | serialize_deserialize_btree/main.py | yinxx/leetcode | train | 0 | |
c8662e83a299110f57651367a4dfd8da645f5382 | [
"average = 0\nfor node in list_num:\n average += node.value\nreturn round(average / list_num.size, 2)",
"media = self.compute_mean(list_num)\nstd_dev = 0\nfor node in list_num:\n std_dev += (node.value - media) ** 2\nreturn round(math.sqrt(std_dev / (list_num.size - 1)), 2)"
] | <|body_start_0|>
average = 0
for node in list_num:
average += node.value
return round(average / list_num.size, 2)
<|end_body_0|>
<|body_start_1|>
media = self.compute_mean(list_num)
std_dev = 0
for node in list_num:
std_dev += (node.value - media)... | ComputeStatiscs | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComputeStatiscs:
def compute_mean(self, list_num):
"""Compute the average of the passed number list."""
<|body_0|>
def compute_std_dev(self, list_num):
"""Compute the standard deviation of of the passed number list."""
<|body_1|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_36k_train_032679 | 643 | no_license | [
{
"docstring": "Compute the average of the passed number list.",
"name": "compute_mean",
"signature": "def compute_mean(self, list_num)"
},
{
"docstring": "Compute the standard deviation of of the passed number list.",
"name": "compute_std_dev",
"signature": "def compute_std_dev(self, li... | 2 | stack_v2_sparse_classes_30k_train_006179 | Implement the Python class `ComputeStatiscs` described below.
Class description:
Implement the ComputeStatiscs class.
Method signatures and docstrings:
- def compute_mean(self, list_num): Compute the average of the passed number list.
- def compute_std_dev(self, list_num): Compute the standard deviation of of the pas... | Implement the Python class `ComputeStatiscs` described below.
Class description:
Implement the ComputeStatiscs class.
Method signatures and docstrings:
- def compute_mean(self, list_num): Compute the average of the passed number list.
- def compute_std_dev(self, list_num): Compute the standard deviation of of the pas... | 740bf0b701ebf8c2dfc056b5b4fd39c1e73a3fe2 | <|skeleton|>
class ComputeStatiscs:
def compute_mean(self, list_num):
"""Compute the average of the passed number list."""
<|body_0|>
def compute_std_dev(self, list_num):
"""Compute the standard deviation of of the passed number list."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ComputeStatiscs:
def compute_mean(self, list_num):
"""Compute the average of the passed number list."""
average = 0
for node in list_num:
average += node.value
return round(average / list_num.size, 2)
def compute_std_dev(self, list_num):
"""Compute the ... | the_stack_v2_python_sparse | Programa1/Code/compute_statistics.py | Sergio2409/PSP-Programs | train | 0 | |
b3218b1f63512719bf13a8f67966abd43290d8ef | [
"if model._meta.app_label in Chemicals_APP:\n return self.using\nreturn None",
"if model._meta.app_label in Chemicals_APP:\n return self.using\nreturn None",
"if obj1._meta.app_label in Chemicals_APP or obj2._meta.app_label in Chemicals_APP:\n return True\nreturn None",
"if app_label in Chemicals_APP... | <|body_start_0|>
if model._meta.app_label in Chemicals_APP:
return self.using
return None
<|end_body_0|>
<|body_start_1|>
if model._meta.app_label in Chemicals_APP:
return self.using
return None
<|end_body_1|>
<|body_start_2|>
if obj1._meta.app_label in ... | A router to control all database operations on models in the auth application. | ChemicalsRouter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChemicalsRouter:
"""A router to control all database operations on models in the auth application."""
def db_for_read(self, model, **hints):
"""Attempts to read auth models go to auth_db."""
<|body_0|>
def db_for_write(self, model, **hints):
"""Attempts to write ... | stack_v2_sparse_classes_36k_train_032680 | 3,768 | no_license | [
{
"docstring": "Attempts to read auth models go to auth_db.",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "Attempts to write auth models go to auth_db.",
"name": "db_for_write",
"signature": "def db_for_write(self, model, **hints)"
},
... | 4 | null | Implement the Python class `ChemicalsRouter` described below.
Class description:
A router to control all database operations on models in the auth application.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read auth models go to auth_db.
- def db_for_write(self, model, **hints... | Implement the Python class `ChemicalsRouter` described below.
Class description:
A router to control all database operations on models in the auth application.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read auth models go to auth_db.
- def db_for_write(self, model, **hints... | 23d31fbeddcd303a7dc90ac9cfbe2c762d61c61e | <|skeleton|>
class ChemicalsRouter:
"""A router to control all database operations on models in the auth application."""
def db_for_read(self, model, **hints):
"""Attempts to read auth models go to auth_db."""
<|body_0|>
def db_for_write(self, model, **hints):
"""Attempts to write ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChemicalsRouter:
"""A router to control all database operations on models in the auth application."""
def db_for_read(self, model, **hints):
"""Attempts to read auth models go to auth_db."""
if model._meta.app_label in Chemicals_APP:
return self.using
return None
... | the_stack_v2_python_sparse | ultratech_fare/settings/routers.py | KONASANI-0143/Dev | train | 0 |
2908fbce074f74864e6eb5ccc7583ff65c3eda16 | [
"obj = cls()\ncrawler.signals.connect(obj.spider_error, signal=signals.spider_error)\nreturn obj",
"if 'errors' not in spider.state:\n spider.state['errors'] = []\nspider.state['errors'].append({'exception': failure, 'sender': response})"
] | <|body_start_0|>
obj = cls()
crawler.signals.connect(obj.spider_error, signal=signals.spider_error)
return obj
<|end_body_0|>
<|body_start_1|>
if 'errors' not in spider.state:
spider.state['errors'] = []
spider.state['errors'].append({'exception': failure, 'sender': ... | ErrorHandler | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ErrorHandler:
def from_crawler(cls, crawler, client=None, dsn=None):
"""Hook in the signal for errors."""
<|body_0|>
def spider_error(self, failure, response, spider, signal=None, sender=None, *args, **kwargs):
"""Register the error in the spider and continue."""
... | stack_v2_sparse_classes_36k_train_032681 | 1,511 | permissive | [
{
"docstring": "Hook in the signal for errors.",
"name": "from_crawler",
"signature": "def from_crawler(cls, crawler, client=None, dsn=None)"
},
{
"docstring": "Register the error in the spider and continue.",
"name": "spider_error",
"signature": "def spider_error(self, failure, response... | 2 | stack_v2_sparse_classes_30k_train_017963 | Implement the Python class `ErrorHandler` described below.
Class description:
Implement the ErrorHandler class.
Method signatures and docstrings:
- def from_crawler(cls, crawler, client=None, dsn=None): Hook in the signal for errors.
- def spider_error(self, failure, response, spider, signal=None, sender=None, *args,... | Implement the Python class `ErrorHandler` described below.
Class description:
Implement the ErrorHandler class.
Method signatures and docstrings:
- def from_crawler(cls, crawler, client=None, dsn=None): Hook in the signal for errors.
- def spider_error(self, failure, response, spider, signal=None, sender=None, *args,... | e645cc3dbfe74141c00f8e42e6fbc603e878af36 | <|skeleton|>
class ErrorHandler:
def from_crawler(cls, crawler, client=None, dsn=None):
"""Hook in the signal for errors."""
<|body_0|>
def spider_error(self, failure, response, spider, signal=None, sender=None, *args, **kwargs):
"""Register the error in the spider and continue."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ErrorHandler:
def from_crawler(cls, crawler, client=None, dsn=None):
"""Hook in the signal for errors."""
obj = cls()
crawler.signals.connect(obj.spider_error, signal=signals.spider_error)
return obj
def spider_error(self, failure, response, spider, signal=None, sender=Non... | the_stack_v2_python_sparse | hepcrawl/extensions.py | inspirehep/hepcrawl | train | 21 | |
8f330957446a85a0c05289337b71e98d81e52cdd | [
"self.words = words\nself.dictionary = defaultdict(list)\nfor index, word in enumerate(self.words):\n self.dictionary[word].append(index)",
"shortest_distance = sys.maxint\nfor index1, index2 in product(self.dictionary[word1], self.dictionary[word2]):\n if abs(index1 - index2) < shortest_distance:\n ... | <|body_start_0|>
self.words = words
self.dictionary = defaultdict(list)
for index, word in enumerate(self.words):
self.dictionary[word].append(index)
<|end_body_0|>
<|body_start_1|>
shortest_distance = sys.maxint
for index1, index2 in product(self.dictionary[word1], ... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
"""Adds a word into the data structure. :type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_032682 | 1,065 | no_license | [
{
"docstring": "initialize your data structure here. :type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": "Adds a word into the data structure. :type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortes... | 2 | stack_v2_sparse_classes_30k_train_000236 | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): initialize your data structure here. :type words: List[str]
- def shortest(self, word1, word2): Adds a word into the data structure. :type word... | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): initialize your data structure here. :type words: List[str]
- def shortest(self, word1, word2): Adds a word into the data structure. :type word... | 09355094c85496cc42f8cb3241da43e0ece1e45a | <|skeleton|>
class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
"""Adds a word into the data structure. :type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
self.words = words
self.dictionary = defaultdict(list)
for index, word in enumerate(self.words):
self.dictionary[word].append(index)
def shortest(self, wo... | the_stack_v2_python_sparse | Rakesh/hash-table/shortest distance problem II.py | rakeshsukla53/interview-preparation | train | 9 | |
30ad0e88b37828a3c7d63c14c612bd6ffafd530e | [
"single_name = namegen.fantasy_name()\nself.assertEqual(type(single_name), str)\nfluid_name = namegen.fantasy_name(style='fluid')\nself.assertEqual(type(fluid_name), str)\nthree_names = namegen.fantasy_name(num=3)\nself.assertEqual(type(three_names), list)\nself.assertEqual(len(three_names), 3)\nsingle_list = nameg... | <|body_start_0|>
single_name = namegen.fantasy_name()
self.assertEqual(type(single_name), str)
fluid_name = namegen.fantasy_name(style='fluid')
self.assertEqual(type(fluid_name), str)
three_names = namegen.fantasy_name(num=3)
self.assertEqual(type(three_names), list)
... | TestNameGenerator | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"CC-BY-SA-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestNameGenerator:
def test_fantasy_name(self):
"""Verify output types and lengths. fantasy_name() - str fantasy_name(style="fluid") - str fantasy_name(num=3) - list of length 3 fantasy_name(return_list=True) - list of length 1 raises KeyError on missing style or ValueError on num"""
... | stack_v2_sparse_classes_36k_train_032683 | 4,914 | permissive | [
{
"docstring": "Verify output types and lengths. fantasy_name() - str fantasy_name(style=\"fluid\") - str fantasy_name(num=3) - list of length 3 fantasy_name(return_list=True) - list of length 1 raises KeyError on missing style or ValueError on num",
"name": "test_fantasy_name",
"signature": "def test_f... | 5 | null | Implement the Python class `TestNameGenerator` described below.
Class description:
Implement the TestNameGenerator class.
Method signatures and docstrings:
- def test_fantasy_name(self): Verify output types and lengths. fantasy_name() - str fantasy_name(style="fluid") - str fantasy_name(num=3) - list of length 3 fant... | Implement the Python class `TestNameGenerator` described below.
Class description:
Implement the TestNameGenerator class.
Method signatures and docstrings:
- def test_fantasy_name(self): Verify output types and lengths. fantasy_name() - str fantasy_name(style="fluid") - str fantasy_name(num=3) - list of length 3 fant... | b3ca58b5c1325a3bf57051dfe23560a08d2947b7 | <|skeleton|>
class TestNameGenerator:
def test_fantasy_name(self):
"""Verify output types and lengths. fantasy_name() - str fantasy_name(style="fluid") - str fantasy_name(num=3) - list of length 3 fantasy_name(return_list=True) - list of length 1 raises KeyError on missing style or ValueError on num"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestNameGenerator:
def test_fantasy_name(self):
"""Verify output types and lengths. fantasy_name() - str fantasy_name(style="fluid") - str fantasy_name(num=3) - list of length 3 fantasy_name(return_list=True) - list of length 1 raises KeyError on missing style or ValueError on num"""
single_na... | the_stack_v2_python_sparse | evennia/contrib/utils/name_generator/tests.py | evennia/evennia | train | 1,781 | |
7e754ea0140a80f577f992b5116bae74d427068a | [
"self.__final, self.__toktype = (final, toktype)\nself.__transitions = transitions\nself.__pushback = pushback",
"if len(input) != 1:\n return (self.ERROR, False, self.ERROR, len(input) - 1)\nsuccessor = None\nif input in self.__transitions:\n successor = self.__transitions.get(input)\nelse:\n for s in s... | <|body_start_0|>
self.__final, self.__toktype = (final, toktype)
self.__transitions = transitions
self.__pushback = pushback
<|end_body_0|>
<|body_start_1|>
if len(input) != 1:
return (self.ERROR, False, self.ERROR, len(input) - 1)
successor = None
if input i... | Class representing the states of a Finite State Automata. Instance Variables: transitions: dictionary (string:integer) final: boolean toktype: Object pushback: integer State object consist of four properties: an a-list of accepted input strings and numeric identifiers for the succeeding states, a flag indicating if the... | State | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class State:
"""Class representing the states of a Finite State Automata. Instance Variables: transitions: dictionary (string:integer) final: boolean toktype: Object pushback: integer State object consist of four properties: an a-list of accepted input strings and numeric identifiers for the succeeding... | stack_v2_sparse_classes_36k_train_032684 | 8,174 | permissive | [
{
"docstring": "Constructor - create a State object. @params: transitions - lookup table of inputs and states final - final/non-final state flag (default false) toktype - type of token recognized on accept (default None) pushback - number of chars to push back after accept (default 0) Initializes the instance v... | 2 | stack_v2_sparse_classes_30k_train_007576 | Implement the Python class `State` described below.
Class description:
Class representing the states of a Finite State Automata. Instance Variables: transitions: dictionary (string:integer) final: boolean toktype: Object pushback: integer State object consist of four properties: an a-list of accepted input strings and... | Implement the Python class `State` described below.
Class description:
Class representing the states of a Finite State Automata. Instance Variables: transitions: dictionary (string:integer) final: boolean toktype: Object pushback: integer State object consist of four properties: an a-list of accepted input strings and... | 6812491740485ec9b6180bb2f2e49acfae53cf18 | <|skeleton|>
class State:
"""Class representing the states of a Finite State Automata. Instance Variables: transitions: dictionary (string:integer) final: boolean toktype: Object pushback: integer State object consist of four properties: an a-list of accepted input strings and numeric identifiers for the succeeding... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class State:
"""Class representing the states of a Finite State Automata. Instance Variables: transitions: dictionary (string:integer) final: boolean toktype: Object pushback: integer State object consist of four properties: an a-list of accepted input strings and numeric identifiers for the succeeding states, a fl... | the_stack_v2_python_sparse | src/StateMachine.py | Schol-R-LEA/Suntiger-Algol | train | 1 |
98fb9ccdc599f7b6772fc99195a969a9fcc10e93 | [
"self.logger = logging.getLogger(__name__)\nself.handler = QtHandler()\nself.handler.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))\nself.logger.addHandler(self.handler)\nself.logger.setLevel(logging.DEBUG)\nself.outHandlerGui = QTextBrowser()",
"self.handler.messageWritten.connect(self.outHandlerG... | <|body_start_0|>
self.logger = logging.getLogger(__name__)
self.handler = QtHandler()
self.handler.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
self.logger.addHandler(self.handler)
self.logger.setLevel(logging.DEBUG)
self.outHandlerGui = QTextBrowser()
<|... | SasviewLoggerTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SasviewLoggerTest:
def setUp(self):
"""Prepare the logger"""
<|body_0|>
def testQtHandler(self):
"""Test redirection of all levels of logging"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.logger = logging.getLogger(__name__)
self.hand... | stack_v2_sparse_classes_36k_train_032685 | 1,484 | permissive | [
{
"docstring": "Prepare the logger",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test redirection of all levels of logging",
"name": "testQtHandler",
"signature": "def testQtHandler(self)"
}
] | 2 | null | Implement the Python class `SasviewLoggerTest` described below.
Class description:
Implement the SasviewLoggerTest class.
Method signatures and docstrings:
- def setUp(self): Prepare the logger
- def testQtHandler(self): Test redirection of all levels of logging | Implement the Python class `SasviewLoggerTest` described below.
Class description:
Implement the SasviewLoggerTest class.
Method signatures and docstrings:
- def setUp(self): Prepare the logger
- def testQtHandler(self): Test redirection of all levels of logging
<|skeleton|>
class SasviewLoggerTest:
def setUp(s... | 7dd9811caddb73c8ef93fa35c91d76bbad7220c6 | <|skeleton|>
class SasviewLoggerTest:
def setUp(self):
"""Prepare the logger"""
<|body_0|>
def testQtHandler(self):
"""Test redirection of all levels of logging"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SasviewLoggerTest:
def setUp(self):
"""Prepare the logger"""
self.logger = logging.getLogger(__name__)
self.handler = QtHandler()
self.handler.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
self.logger.addHandler(self.handler)
self.logger.setLevel... | the_stack_v2_python_sparse | src/sas/qtgui/Utilities/UnitTesting/SasviewLoggerTest.py | PBenderLux/sasview | train | 0 | |
18e68949cd0b4be287d389250bfaa5aa7cfa1753 | [
"nums = set(nums)\nres = 0\nfor n in nums:\n if n - 1 in nums:\n continue\n m = n + 1\n while m in nums:\n m += 1\n res = max(res, m - n)\nreturn res",
"import collections\ndict_ = {}\nres = 0\nfor num in nums:\n if num not in dict_.keys():\n left = dict_.get(num - 1) if dict_.... | <|body_start_0|>
nums = set(nums)
res = 0
for n in nums:
if n - 1 in nums:
continue
m = n + 1
while m in nums:
m += 1
res = max(res, m - n)
return res
<|end_body_0|>
<|body_start_1|>
import collectio... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestConsecutive(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def longestConsecutive2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
nums = set(nums)
res =... | stack_v2_sparse_classes_36k_train_032686 | 1,330 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "longestConsecutive",
"signature": "def longestConsecutive(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "longestConsecutive2",
"signature": "def longestConsecutive2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009598 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestConsecutive(self, nums): :type nums: List[int] :rtype: int
- def longestConsecutive2(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 longestConsecutive(self, nums): :type nums: List[int] :rtype: int
- def longestConsecutive2(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
... | 29113d64155b152017fa0a98e6038323d1e8b8eb | <|skeleton|>
class Solution:
def longestConsecutive(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def longestConsecutive2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestConsecutive(self, nums):
""":type nums: List[int] :rtype: int"""
nums = set(nums)
res = 0
for n in nums:
if n - 1 in nums:
continue
m = n + 1
while m in nums:
m += 1
res = max(r... | the_stack_v2_python_sparse | August_18/128. Longest Consecutive Sequence.py | insigh/Leetcode | train | 0 | |
109a7f4b043dc9bb993cd3ba83c004b66adc1b9c | [
"plugin = NeighbourSelection()\nsites = [{'projection_x_coordinate': 10000.0, 'projection_y_coordinate': 10000.0}, {'projection_x_coordinate': 100000.0, 'projection_y_coordinate': 50000.0}]\nx_points = np.array([site['projection_x_coordinate'] for site in sites])\ny_points = np.array([site['projection_y_coordinate'... | <|body_start_0|>
plugin = NeighbourSelection()
sites = [{'projection_x_coordinate': 10000.0, 'projection_y_coordinate': 10000.0}, {'projection_x_coordinate': 100000.0, 'projection_y_coordinate': 50000.0}]
x_points = np.array([site['projection_x_coordinate'] for site in sites])
y_points =... | Test the function that removes sites falling outside the model domain from the site list. | Test_check_sites_are_within_domain | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_check_sites_are_within_domain:
"""Test the function that removes sites falling outside the model domain from the site list."""
def test_all_valid(self):
"""Test case in which all sites are valid and fall within domain."""
<|body_0|>
def test_some_invalid(self):
... | stack_v2_sparse_classes_36k_train_032687 | 40,371 | permissive | [
{
"docstring": "Test case in which all sites are valid and fall within domain.",
"name": "test_all_valid",
"signature": "def test_all_valid(self)"
},
{
"docstring": "Test case with some sites falling outside the regional domain.",
"name": "test_some_invalid",
"signature": "def test_some_... | 4 | null | Implement the Python class `Test_check_sites_are_within_domain` described below.
Class description:
Test the function that removes sites falling outside the model domain from the site list.
Method signatures and docstrings:
- def test_all_valid(self): Test case in which all sites are valid and fall within domain.
- d... | Implement the Python class `Test_check_sites_are_within_domain` described below.
Class description:
Test the function that removes sites falling outside the model domain from the site list.
Method signatures and docstrings:
- def test_all_valid(self): Test case in which all sites are valid and fall within domain.
- d... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_check_sites_are_within_domain:
"""Test the function that removes sites falling outside the model domain from the site list."""
def test_all_valid(self):
"""Test case in which all sites are valid and fall within domain."""
<|body_0|>
def test_some_invalid(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_check_sites_are_within_domain:
"""Test the function that removes sites falling outside the model domain from the site list."""
def test_all_valid(self):
"""Test case in which all sites are valid and fall within domain."""
plugin = NeighbourSelection()
sites = [{'projection_x_... | the_stack_v2_python_sparse | improver_tests/spotdata/test_NeighbourSelection.py | metoppv/improver | train | 101 |
d77ad6bf461c93196744e599479e1c95c6e2d95d | [
"grpc_obj = GrpcService(self.request)\nresp = await grpc_obj.get_redis_info()\nreturn ResponseMsg(data=resp)",
"json_data = await self.request.json()\nhost = json_data.get('host')\nport = json_data.get('port')\ntoken = json_data.get('token')\ngrpc_obj = GrpcService(self.request)\nresp = await grpc_obj.put_redis_i... | <|body_start_0|>
grpc_obj = GrpcService(self.request)
resp = await grpc_obj.get_redis_info()
return ResponseMsg(data=resp)
<|end_body_0|>
<|body_start_1|>
json_data = await self.request.json()
host = json_data.get('host')
port = json_data.get('port')
token = json... | redis | RedisListController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RedisListController:
"""redis"""
async def get(self):
"""获取 配置的 redis 信息 :return: @id->int redis uuid @host->string redis host @port->string redis port @token->string redis password @status->bool redis is ok? @delay_time->int delay time"""
<|body_0|>
async def post(self)... | stack_v2_sparse_classes_36k_train_032688 | 5,386 | no_license | [
{
"docstring": "获取 配置的 redis 信息 :return: @id->int redis uuid @host->string redis host @port->string redis port @token->string redis password @status->bool redis is ok? @delay_time->int delay time",
"name": "get",
"signature": "async def get(self)"
},
{
"docstring": "注册 配置的redis信息 @host->string r... | 2 | stack_v2_sparse_classes_30k_train_014104 | Implement the Python class `RedisListController` described below.
Class description:
redis
Method signatures and docstrings:
- async def get(self): 获取 配置的 redis 信息 :return: @id->int redis uuid @host->string redis host @port->string redis port @token->string redis password @status->bool redis is ok? @delay_time->int d... | Implement the Python class `RedisListController` described below.
Class description:
redis
Method signatures and docstrings:
- async def get(self): 获取 配置的 redis 信息 :return: @id->int redis uuid @host->string redis host @port->string redis port @token->string redis password @status->bool redis is ok? @delay_time->int d... | c6fdd48dae3bc98f9c41c603bef20d10c15476d7 | <|skeleton|>
class RedisListController:
"""redis"""
async def get(self):
"""获取 配置的 redis 信息 :return: @id->int redis uuid @host->string redis host @port->string redis port @token->string redis password @status->bool redis is ok? @delay_time->int delay time"""
<|body_0|>
async def post(self)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RedisListController:
"""redis"""
async def get(self):
"""获取 配置的 redis 信息 :return: @id->int redis uuid @host->string redis host @port->string redis port @token->string redis password @status->bool redis is ok? @delay_time->int delay time"""
grpc_obj = GrpcService(self.request)
resp... | the_stack_v2_python_sparse | api/redis_controller.py | Fosity/rpc_web | train | 0 |
12514db172636e7e48d6636cbd8c60466aa551c6 | [
"hold = 10 ** 4 + 1\nret = 0\nfor p in prices:\n ret = max(ret, p - hold)\n hold = min(p, hold)\nreturn ret",
"n = len(prices)\nif n <= 1:\n return 0\nbuy = prices[0]\nsell = prices[1]\nprofit = sell - buy\nfor i in range(1, n):\n if prices[i] < buy and i < n - 1:\n buy = prices[i]\n sel... | <|body_start_0|>
hold = 10 ** 4 + 1
ret = 0
for p in prices:
ret = max(ret, p - hold)
hold = min(p, hold)
return ret
<|end_body_0|>
<|body_start_1|>
n = len(prices)
if n <= 1:
return 0
buy = prices[0]
sell = prices[1]
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""2022-09-22 1 <= prices.length <= 10^5 0 <= prices[i] <= 10^4"""
<|body_0|>
def maxProfit2(self, prices: List[int]) -> int:
"""2021/8/22 211 / 211 test cases passed. Status: Accepted Runtime: 920 ms Memory Us... | stack_v2_sparse_classes_36k_train_032689 | 1,684 | permissive | [
{
"docstring": "2022-09-22 1 <= prices.length <= 10^5 0 <= prices[i] <= 10^4",
"name": "maxProfit",
"signature": "def maxProfit(self, prices: List[int]) -> int"
},
{
"docstring": "2021/8/22 211 / 211 test cases passed. Status: Accepted Runtime: 920 ms Memory Usage: 25.2 MB :param prices: :return... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices: List[int]) -> int: 2022-09-22 1 <= prices.length <= 10^5 0 <= prices[i] <= 10^4
- def maxProfit2(self, prices: List[int]) -> int: 2021/8/22 211 / 211 ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices: List[int]) -> int: 2022-09-22 1 <= prices.length <= 10^5 0 <= prices[i] <= 10^4
- def maxProfit2(self, prices: List[int]) -> int: 2021/8/22 211 / 211 ... | 4dd1e54d8d08f7e6590bc76abd08ecaacaf775e5 | <|skeleton|>
class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""2022-09-22 1 <= prices.length <= 10^5 0 <= prices[i] <= 10^4"""
<|body_0|>
def maxProfit2(self, prices: List[int]) -> int:
"""2021/8/22 211 / 211 test cases passed. Status: Accepted Runtime: 920 ms Memory Us... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""2022-09-22 1 <= prices.length <= 10^5 0 <= prices[i] <= 10^4"""
hold = 10 ** 4 + 1
ret = 0
for p in prices:
ret = max(ret, p - hold)
hold = min(p, hold)
return ret
def maxProfit2(se... | the_stack_v2_python_sparse | src/121-BestTimetoBuyandSellStock.py | Jiezhi/myleetcode | train | 1 | |
6fe55898669052487986d125bd80a546a24b2284 | [
"request_cls = OAuth2Request\nif isinstance(request, request_cls):\n return request\nif not request:\n request = flask_req\ntry:\n if request.headers['Content-Type'] != 'application/json':\n return self.create_authorization_request(request)\nexcept Exception:\n return self.create_oauth2_request(r... | <|body_start_0|>
request_cls = OAuth2Request
if isinstance(request, request_cls):
return request
if not request:
request = flask_req
try:
if request.headers['Content-Type'] != 'application/json':
return self.create_authorization_request... | BrightHive Authorization Server. Overrides the base Authlib AuthorizationServer class to provide a custom method for passing the OAuth 2.0 grant type as a field in the JSON request body, but still maintains the ability to handle the grant type as a query parameter. | BrightHiveAuthorizationServer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BrightHiveAuthorizationServer:
"""BrightHive Authorization Server. Overrides the base Authlib AuthorizationServer class to provide a custom method for passing the OAuth 2.0 grant type as a field in the JSON request body, but still maintains the ability to handle the grant type as a query paramete... | stack_v2_sparse_classes_36k_train_032690 | 2,589 | permissive | [
{
"docstring": "Build the OAuth2Request object from the JSON request body. Args: request (obj): The request object to parse for the necessary elements to build the OAuth2Request. Returns: (obj): The OAuth2Request object.",
"name": "create_oauth2_request_from_json",
"signature": "def create_oauth2_reques... | 2 | stack_v2_sparse_classes_30k_train_000299 | Implement the Python class `BrightHiveAuthorizationServer` described below.
Class description:
BrightHive Authorization Server. Overrides the base Authlib AuthorizationServer class to provide a custom method for passing the OAuth 2.0 grant type as a field in the JSON request body, but still maintains the ability to ha... | Implement the Python class `BrightHiveAuthorizationServer` described below.
Class description:
BrightHive Authorization Server. Overrides the base Authlib AuthorizationServer class to provide a custom method for passing the OAuth 2.0 grant type as a field in the JSON request body, but still maintains the ability to ha... | df10801de5a78b6a12c1d747f9da4b79506c45e5 | <|skeleton|>
class BrightHiveAuthorizationServer:
"""BrightHive Authorization Server. Overrides the base Authlib AuthorizationServer class to provide a custom method for passing the OAuth 2.0 grant type as a field in the JSON request body, but still maintains the ability to handle the grant type as a query paramete... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BrightHiveAuthorizationServer:
"""BrightHive Authorization Server. Overrides the base Authlib AuthorizationServer class to provide a custom method for passing the OAuth 2.0 grant type as a field in the JSON request body, but still maintains the ability to handle the grant type as a query parameter."""
de... | the_stack_v2_python_sparse | authserver/oauth2/rfc6749/authorization_server.py | TimothyJAndrus/authserver | train | 0 |
878c394dd3151d43e1ad4daec379caa83549e92f | [
"self.bg_file = bg_file\nself.ref_file = ref_file\nself.var_file = var_file\nself.region = region\nself.sample = sample\nself.gt_replace = gt_replace\nself.min_insert = min_insert\nself.max_insert = max_insert\nself.annotated_vars = None\nself.name = '%s:%d-%d' % tuple(self.region)",
"vcf_file = vcf.Reader(filena... | <|body_start_0|>
self.bg_file = bg_file
self.ref_file = ref_file
self.var_file = var_file
self.region = region
self.sample = sample
self.gt_replace = gt_replace
self.min_insert = min_insert
self.max_insert = max_insert
self.annotated_vars = None
... | This is one run of the program - I can thread these | PcmpTask | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PcmpTask:
"""This is one run of the program - I can thread these"""
def __init__(self, bg_file, ref_file, var_file, region=None, sample=None, gt_replace=False, min_insert=200, max_insert=1000):
"""Main runner On a BioGraph file and a Reference genotype the variants in var_file"""
... | stack_v2_sparse_classes_36k_train_032691 | 21,838 | permissive | [
{
"docstring": "Main runner On a BioGraph file and a Reference genotype the variants in var_file",
"name": "__init__",
"signature": "def __init__(self, bg_file, ref_file, var_file, region=None, sample=None, gt_replace=False, min_insert=200, max_insert=1000)"
},
{
"docstring": "Given a traced var... | 3 | stack_v2_sparse_classes_30k_train_009817 | Implement the Python class `PcmpTask` described below.
Class description:
This is one run of the program - I can thread these
Method signatures and docstrings:
- def __init__(self, bg_file, ref_file, var_file, region=None, sample=None, gt_replace=False, min_insert=200, max_insert=1000): Main runner On a BioGraph file... | Implement the Python class `PcmpTask` described below.
Class description:
This is one run of the program - I can thread these
Method signatures and docstrings:
- def __init__(self, bg_file, ref_file, var_file, region=None, sample=None, gt_replace=False, min_insert=200, max_insert=1000): Main runner On a BioGraph file... | 5f40198e95b0626ae143e021ec97884de634e61d | <|skeleton|>
class PcmpTask:
"""This is one run of the program - I can thread these"""
def __init__(self, bg_file, ref_file, var_file, region=None, sample=None, gt_replace=False, min_insert=200, max_insert=1000):
"""Main runner On a BioGraph file and a Reference genotype the variants in var_file"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PcmpTask:
"""This is one run of the program - I can thread these"""
def __init__(self, bg_file, ref_file, var_file, region=None, sample=None, gt_replace=False, min_insert=200, max_insert=1000):
"""Main runner On a BioGraph file and a Reference genotype the variants in var_file"""
self.bg_... | the_stack_v2_python_sparse | python/biograph/internal/vPCMP.py | spiralgenetics/biograph | train | 21 |
b3ea86eaca1c68187c9325ab5dd59af7ec26c478 | [
"if isinstance(key, int):\n return Packet(key)\nif key not in Packet._member_map_:\n extend_enum(Packet, key, default)\nreturn Packet[key]",
"if not (isinstance(value, int) and 0 <= value <= 127):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nif 5 <= value <= 15:\n extend_enum(cl... | <|body_start_0|>
if isinstance(key, int):
return Packet(key)
if key not in Packet._member_map_:
extend_enum(Packet, key, default)
return Packet[key]
<|end_body_0|>
<|body_start_1|>
if not (isinstance(value, int) and 0 <= value <= 127):
raise ValueErro... | [Packet] HIP Packet Types | Packet | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Packet:
"""[Packet] HIP Packet Types"""
def get(key, default=-1):
"""Backport support for original codes."""
<|body_0|>
def _missing_(cls, value):
"""Lookup function used when value is not found."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
i... | stack_v2_sparse_classes_36k_train_032692 | 2,001 | permissive | [
{
"docstring": "Backport support for original codes.",
"name": "get",
"signature": "def get(key, default=-1)"
},
{
"docstring": "Lookup function used when value is not found.",
"name": "_missing_",
"signature": "def _missing_(cls, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015632 | Implement the Python class `Packet` described below.
Class description:
[Packet] HIP Packet Types
Method signatures and docstrings:
- def get(key, default=-1): Backport support for original codes.
- def _missing_(cls, value): Lookup function used when value is not found. | Implement the Python class `Packet` described below.
Class description:
[Packet] HIP Packet Types
Method signatures and docstrings:
- def get(key, default=-1): Backport support for original codes.
- def _missing_(cls, value): Lookup function used when value is not found.
<|skeleton|>
class Packet:
"""[Packet] HI... | 71363d7948003fec88cedcf5bc80b6befa2ba244 | <|skeleton|>
class Packet:
"""[Packet] HIP Packet Types"""
def get(key, default=-1):
"""Backport support for original codes."""
<|body_0|>
def _missing_(cls, value):
"""Lookup function used when value is not found."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Packet:
"""[Packet] HIP Packet Types"""
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Packet(key)
if key not in Packet._member_map_:
extend_enum(Packet, key, default)
return Packet[key]
def... | the_stack_v2_python_sparse | pcapkit/const/hip/packet.py | hiok2000/PyPCAPKit | train | 0 |
87dc32e08cb5cba627981e0a53461cd06a49ad69 | [
"newMessage = ''\nnumWords = random.randint(1, 7)\nwordlist = OTPLocalizer.ChatGarblerDefault\nfor i in range(1, numWords + 1):\n wordIndex = random.randint(0, len(wordlist) - 1)\n newMessage = newMessage + wordlist[wordIndex]\n if i < numWords:\n newMessage = newMessage + ' '\nreturn newMessage",
... | <|body_start_0|>
newMessage = ''
numWords = random.randint(1, 7)
wordlist = OTPLocalizer.ChatGarblerDefault
for i in range(1, numWords + 1):
wordIndex = random.randint(0, len(wordlist) - 1)
newMessage = newMessage + wordlist[wordIndex]
if i < numWords:... | ChatGarbler class: contains methods to convert chat messages to animal sounds | ChatGarbler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChatGarbler:
"""ChatGarbler class: contains methods to convert chat messages to animal sounds"""
def garble(self, avatar, message):
"""garble(self, Avatar, string) Replace a chat message with a series of animal sounds based on the toon's animal type Algorithm completely disregards or... | stack_v2_sparse_classes_36k_train_032693 | 1,639 | no_license | [
{
"docstring": "garble(self, Avatar, string) Replace a chat message with a series of animal sounds based on the toon's animal type Algorithm completely disregards original message to prohibit any sort of meaningful communication",
"name": "garble",
"signature": "def garble(self, avatar, message)"
},
... | 2 | null | Implement the Python class `ChatGarbler` described below.
Class description:
ChatGarbler class: contains methods to convert chat messages to animal sounds
Method signatures and docstrings:
- def garble(self, avatar, message): garble(self, Avatar, string) Replace a chat message with a series of animal sounds based on ... | Implement the Python class `ChatGarbler` described below.
Class description:
ChatGarbler class: contains methods to convert chat messages to animal sounds
Method signatures and docstrings:
- def garble(self, avatar, message): garble(self, Avatar, string) Replace a chat message with a series of animal sounds based on ... | 0e7bfc1fe29fd595df0b982e40f94c30befb1ec7 | <|skeleton|>
class ChatGarbler:
"""ChatGarbler class: contains methods to convert chat messages to animal sounds"""
def garble(self, avatar, message):
"""garble(self, Avatar, string) Replace a chat message with a series of animal sounds based on the toon's animal type Algorithm completely disregards or... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChatGarbler:
"""ChatGarbler class: contains methods to convert chat messages to animal sounds"""
def garble(self, avatar, message):
"""garble(self, Avatar, string) Replace a chat message with a series of animal sounds based on the toon's animal type Algorithm completely disregards original messag... | the_stack_v2_python_sparse | otp/src/chat/ChatGarbler.py | satire6/Anesidora | train | 89 |
6cd7f0726f60c3f5dfba853a1056dab3c1f5fc09 | [
"super().__init__()\nself.self_attn = self_attn\nself.feed_forward = feed_forward\nself.norm1 = LayerNorm(size, epsilon=1e-12)\nself.norm2 = LayerNorm(size, epsilon=1e-12)\nself.dropout = nn.Dropout(dropout_rate)\nself.size = size\nself.normalize_before = normalize_before\nself.concat_after = concat_after\nself.con... | <|body_start_0|>
super().__init__()
self.self_attn = self_attn
self.feed_forward = feed_forward
self.norm1 = LayerNorm(size, epsilon=1e-12)
self.norm2 = LayerNorm(size, epsilon=1e-12)
self.dropout = nn.Dropout(dropout_rate)
self.size = size
self.normalize_... | Encoder layer module. | TransformerEncoderLayer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerEncoderLayer:
"""Encoder layer module."""
def __init__(self, size: int, self_attn: nn.Layer, feed_forward: nn.Layer, dropout_rate: float, normalize_before: bool=True, concat_after: bool=False):
"""Construct an EncoderLayer object. Args: size (int): Input dimension. self_at... | stack_v2_sparse_classes_36k_train_032694 | 16,607 | permissive | [
{
"docstring": "Construct an EncoderLayer object. Args: size (int): Input dimension. self_attn (nn.Layer): Self-attention module instance. `MultiHeadedAttention`, `RelPositionMultiHeadedAttention` or `RoPERelPositionMultiHeadedAttention` instance can be used as the argument. feed_forward (nn.Layer): Feed-forwar... | 2 | null | Implement the Python class `TransformerEncoderLayer` described below.
Class description:
Encoder layer module.
Method signatures and docstrings:
- def __init__(self, size: int, self_attn: nn.Layer, feed_forward: nn.Layer, dropout_rate: float, normalize_before: bool=True, concat_after: bool=False): Construct an Encode... | Implement the Python class `TransformerEncoderLayer` described below.
Class description:
Encoder layer module.
Method signatures and docstrings:
- def __init__(self, size: int, self_attn: nn.Layer, feed_forward: nn.Layer, dropout_rate: float, normalize_before: bool=True, concat_after: bool=False): Construct an Encode... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class TransformerEncoderLayer:
"""Encoder layer module."""
def __init__(self, size: int, self_attn: nn.Layer, feed_forward: nn.Layer, dropout_rate: float, normalize_before: bool=True, concat_after: bool=False):
"""Construct an EncoderLayer object. Args: size (int): Input dimension. self_at... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransformerEncoderLayer:
"""Encoder layer module."""
def __init__(self, size: int, self_attn: nn.Layer, feed_forward: nn.Layer, dropout_rate: float, normalize_before: bool=True, concat_after: bool=False):
"""Construct an EncoderLayer object. Args: size (int): Input dimension. self_attn (nn.Layer)... | the_stack_v2_python_sparse | paddlespeech/s2t/modules/encoder_layer.py | anniyanvr/DeepSpeech-1 | train | 0 |
9ec7386869f80904a786dcc1aa9712d2676e36ec | [
"self.res_path = res_path\nself.lmtzr = nltk.stem.wordnet.WordNetLemmatizer()\nself.in_helper = imagenet_helper.ImageNetHelper(res_path)\nwith open(os.path.join(res_path, 'visualization', 'common_colors.p')) as f:\n self.common_colors_set = set(cPickle.load(f))",
"word = word.lower().strip().replace(' ', '_')\... | <|body_start_0|>
self.res_path = res_path
self.lmtzr = nltk.stem.wordnet.WordNetLemmatizer()
self.in_helper = imagenet_helper.ImageNetHelper(res_path)
with open(os.path.join(res_path, 'visualization', 'common_colors.p')) as f:
self.common_colors_set = set(cPickle.load(f))
<|e... | WordNetMapper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordNetMapper:
def __init__(self, res_path):
"""Initializer. Args: res_path: A string representing path to the resource files."""
<|body_0|>
def map_word(self, word, pos=wordnet.NOUN):
"""Maps a word to the most frequent WordNet synset. The mapping is based on NLTK W... | stack_v2_sparse_classes_36k_train_032695 | 4,435 | permissive | [
{
"docstring": "Initializer. Args: res_path: A string representing path to the resource files.",
"name": "__init__",
"signature": "def __init__(self, res_path)"
},
{
"docstring": "Maps a word to the most frequent WordNet synset. The mapping is based on NLTK WordNet interface result, WordNet lemm... | 2 | stack_v2_sparse_classes_30k_train_016119 | Implement the Python class `WordNetMapper` described below.
Class description:
Implement the WordNetMapper class.
Method signatures and docstrings:
- def __init__(self, res_path): Initializer. Args: res_path: A string representing path to the resource files.
- def map_word(self, word, pos=wordnet.NOUN): Maps a word t... | Implement the Python class `WordNetMapper` described below.
Class description:
Implement the WordNetMapper class.
Method signatures and docstrings:
- def __init__(self, res_path): Initializer. Args: res_path: A string representing path to the resource files.
- def map_word(self, word, pos=wordnet.NOUN): Maps a word t... | ac3c0e93adf35015d7f6cfc8c6cf2e6ec45cdeae | <|skeleton|>
class WordNetMapper:
def __init__(self, res_path):
"""Initializer. Args: res_path: A string representing path to the resource files."""
<|body_0|>
def map_word(self, word, pos=wordnet.NOUN):
"""Maps a word to the most frequent WordNet synset. The mapping is based on NLTK W... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordNetMapper:
def __init__(self, res_path):
"""Initializer. Args: res_path: A string representing path to the resource files."""
self.res_path = res_path
self.lmtzr = nltk.stem.wordnet.WordNetLemmatizer()
self.in_helper = imagenet_helper.ImageNetHelper(res_path)
with o... | the_stack_v2_python_sparse | server/canonicalization/wordnet_mapper.py | hotpxl/canonicalization-server | train | 3 | |
4a964ba2300c1f05a1d8f2b3ae964515ebf8d0e3 | [
"result = []\n\ndef preorder(root):\n if not root:\n return\n size = len(root.children)\n result.append(str(root.val))\n result.append(str(size))\n for c in root.children:\n preorder(c)\npreorder(root)\nreturn ','.join(result)",
"if not data:\n return None\nqueue = collections.dequ... | <|body_start_0|>
result = []
def preorder(root):
if not root:
return
size = len(root.children)
result.append(str(root.val))
result.append(str(size))
for c in root.children:
preorder(c)
preorder(root)
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_032696 | 1,290 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root: 'Node') -> str"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def des... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | d953abe2c9680f636563e76287d2f907e90ced63 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
result = []
def preorder(root):
if not root:
return
size = len(root.children)
result.append(str(root.val))
... | the_stack_v2_python_sparse | python_leetcode_2020/Python_Leetcode_2020/428_serialize_deserialize_n-ary.py | xiangcao/Leetcode | train | 0 | |
255f571c4530efdbc9813bb6fb6ef9da1a9c2e83 | [
"coleccion_objeto = Coleccion()\nimage_objeto = Image()\nimage_objeto.image_File = SimpleUploadedFile(name='black.png', content=open('../../black.png', 'rb').read(), content_type='image/png')\nimage_objeto.fk_Coleccion = coleccion_objeto\nself.assertEqual(image_objeto.load_image_function().format, 'PNG')",
"colec... | <|body_start_0|>
coleccion_objeto = Coleccion()
image_objeto = Image()
image_objeto.image_File = SimpleUploadedFile(name='black.png', content=open('../../black.png', 'rb').read(), content_type='image/png')
image_objeto.fk_Coleccion = coleccion_objeto
self.assertEqual(image_objeto... | TestImagenes | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestImagenes:
def test_format(self):
"""Función que evalua si el formato de una imagen se conserva @return: resultado de prueba comparando si la imagen es formato png"""
<|body_0|>
def test_add_photo(self):
"""Función que evalua si la base de datos guarda satisfactor... | stack_v2_sparse_classes_36k_train_032697 | 3,082 | no_license | [
{
"docstring": "Función que evalua si el formato de una imagen se conserva @return: resultado de prueba comparando si la imagen es formato png",
"name": "test_format",
"signature": "def test_format(self)"
},
{
"docstring": "Función que evalua si la base de datos guarda satisfactoriamente la imag... | 5 | stack_v2_sparse_classes_30k_val_000847 | Implement the Python class `TestImagenes` described below.
Class description:
Implement the TestImagenes class.
Method signatures and docstrings:
- def test_format(self): Función que evalua si el formato de una imagen se conserva @return: resultado de prueba comparando si la imagen es formato png
- def test_add_photo... | Implement the Python class `TestImagenes` described below.
Class description:
Implement the TestImagenes class.
Method signatures and docstrings:
- def test_format(self): Función que evalua si el formato de una imagen se conserva @return: resultado de prueba comparando si la imagen es formato png
- def test_add_photo... | 586fe5d322581fc5a01a31504d76c4966f0207c2 | <|skeleton|>
class TestImagenes:
def test_format(self):
"""Función que evalua si el formato de una imagen se conserva @return: resultado de prueba comparando si la imagen es formato png"""
<|body_0|>
def test_add_photo(self):
"""Función que evalua si la base de datos guarda satisfactor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestImagenes:
def test_format(self):
"""Función que evalua si el formato de una imagen se conserva @return: resultado de prueba comparando si la imagen es formato png"""
coleccion_objeto = Coleccion()
image_objeto = Image()
image_objeto.image_File = SimpleUploadedFile(name='bla... | the_stack_v2_python_sparse | WebProject/CellSegmentation/ImageApp/test.py | joseant12/CellSegmentationProject | train | 0 | |
ab094ceb257d161cbeee1c069f3265ec8229ef9f | [
"print(validated_data)\nu = User.objects.create(**validated_data)\nu.set_password(validated_data['password'])\nu.save()\nreturn u",
"instance.first_name = validated_data.get('first_name', instance.first_name)\ninstance.middle_name = validated_data.get('middle_name', instance.middle_name)\ninstance.last_name = val... | <|body_start_0|>
print(validated_data)
u = User.objects.create(**validated_data)
u.set_password(validated_data['password'])
u.save()
return u
<|end_body_0|>
<|body_start_1|>
instance.first_name = validated_data.get('first_name', instance.first_name)
instance.midd... | Serializer for User Model | UserDetailSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserDetailSerializer:
"""Serializer for User Model"""
def create(self, validated_data):
"""Create and return a new `User` instance given the validated data."""
<|body_0|>
def update(self, instance, validated_data):
"""Update and return an existing `User` instance... | stack_v2_sparse_classes_36k_train_032698 | 3,455 | no_license | [
{
"docstring": "Create and return a new `User` instance given the validated data.",
"name": "create",
"signature": "def create(self, validated_data)"
},
{
"docstring": "Update and return an existing `User` instance, given the validated data",
"name": "update",
"signature": "def update(se... | 2 | stack_v2_sparse_classes_30k_train_000272 | Implement the Python class `UserDetailSerializer` described below.
Class description:
Serializer for User Model
Method signatures and docstrings:
- def create(self, validated_data): Create and return a new `User` instance given the validated data.
- def update(self, instance, validated_data): Update and return an exi... | Implement the Python class `UserDetailSerializer` described below.
Class description:
Serializer for User Model
Method signatures and docstrings:
- def create(self, validated_data): Create and return a new `User` instance given the validated data.
- def update(self, instance, validated_data): Update and return an exi... | 31c745ec4345b6c2d00e1d33f53f5585defa57d1 | <|skeleton|>
class UserDetailSerializer:
"""Serializer for User Model"""
def create(self, validated_data):
"""Create and return a new `User` instance given the validated data."""
<|body_0|>
def update(self, instance, validated_data):
"""Update and return an existing `User` instance... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserDetailSerializer:
"""Serializer for User Model"""
def create(self, validated_data):
"""Create and return a new `User` instance given the validated data."""
print(validated_data)
u = User.objects.create(**validated_data)
u.set_password(validated_data['password'])
... | the_stack_v2_python_sparse | user/serializers.py | pranavkneeraj/PMS | train | 0 |
ae5cbd882c78ebb5413b5c645474fa006abb3c63 | [
"super(MEGNet, self).__init__()\ntry:\n from torch_geometric.nn import Set2Set\nexcept ModuleNotFoundError:\n raise ImportError('MEGNet model requires torch_geometric to be installed')\nif mode not in ['classification', 'regression']:\n raise ValueError(\"mode must be either 'classification' or 'regression... | <|body_start_0|>
super(MEGNet, self).__init__()
try:
from torch_geometric.nn import Set2Set
except ModuleNotFoundError:
raise ImportError('MEGNet model requires torch_geometric to be installed')
if mode not in ['classification', 'regression']:
raise Va... | MatErials Graph Network A model for predicting crystal and molecular properties using GraphNetworks. Example ------- >>> import numpy as np >>> from torch_geometric.data import Batch >>> from deepchem.feat import GraphData >>> n_nodes, n_node_features = 5, 10 >>> n_edges, n_edge_attrs = 5, 2 >>> n_global_features = 4 >... | MEGNet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MEGNet:
"""MatErials Graph Network A model for predicting crystal and molecular properties using GraphNetworks. Example ------- >>> import numpy as np >>> from torch_geometric.data import Batch >>> from deepchem.feat import GraphData >>> n_nodes, n_node_features = 5, 10 >>> n_edges, n_edge_attrs ... | stack_v2_sparse_classes_36k_train_032699 | 11,170 | permissive | [
{
"docstring": "Parameters ---------- n_node_features: int Number of features in a node n_edge_features: int Number of features in a edge n_global_features: int Number of global features n_blocks: int Number of GraphNetworks block to use in update is_undirected: bool, optional (default True) True when the graph... | 2 | stack_v2_sparse_classes_30k_train_017534 | Implement the Python class `MEGNet` described below.
Class description:
MatErials Graph Network A model for predicting crystal and molecular properties using GraphNetworks. Example ------- >>> import numpy as np >>> from torch_geometric.data import Batch >>> from deepchem.feat import GraphData >>> n_nodes, n_node_feat... | Implement the Python class `MEGNet` described below.
Class description:
MatErials Graph Network A model for predicting crystal and molecular properties using GraphNetworks. Example ------- >>> import numpy as np >>> from torch_geometric.data import Batch >>> from deepchem.feat import GraphData >>> n_nodes, n_node_feat... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class MEGNet:
"""MatErials Graph Network A model for predicting crystal and molecular properties using GraphNetworks. Example ------- >>> import numpy as np >>> from torch_geometric.data import Batch >>> from deepchem.feat import GraphData >>> n_nodes, n_node_features = 5, 10 >>> n_edges, n_edge_attrs ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MEGNet:
"""MatErials Graph Network A model for predicting crystal and molecular properties using GraphNetworks. Example ------- >>> import numpy as np >>> from torch_geometric.data import Batch >>> from deepchem.feat import GraphData >>> n_nodes, n_node_features = 5, 10 >>> n_edges, n_edge_attrs = 5, 2 >>> n_... | the_stack_v2_python_sparse | deepchem/models/torch_models/megnet.py | deepchem/deepchem | train | 4,876 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.