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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fe0d5bdea9e7abdf781783893fd99c1acef4ac1d | [
"super(GMM, self).__init__()\nself.num_comp = num_comp\nself.noise_dims = noise_dims\nself.means = Parameter(torch.randn(num_comp, noise_dims))",
"batch_size = noise.size(0)\nnum_samples = noise.size(1)\ncomp_ind = Variable(torch.LongTensor(npr.choice(self.num_comp, size=batch_size * num_samples)))\nif torch.cuda... | <|body_start_0|>
super(GMM, self).__init__()
self.num_comp = num_comp
self.noise_dims = noise_dims
self.means = Parameter(torch.randn(num_comp, noise_dims))
<|end_body_0|>
<|body_start_1|>
batch_size = noise.size(0)
num_samples = noise.size(1)
comp_ind = Variable... | GMM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GMM:
def __init__(self, noise_dims, num_comp):
"""noise_dims = Number of noise dimensions num_comp = Number of noise components"""
<|body_0|>
def forward(self, input, noise, target_size):
"""noise: batch_size x num_samples x noise_dim"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k_train_009900 | 10,873 | no_license | [
{
"docstring": "noise_dims = Number of noise dimensions num_comp = Number of noise components",
"name": "__init__",
"signature": "def __init__(self, noise_dims, num_comp)"
},
{
"docstring": "noise: batch_size x num_samples x noise_dim",
"name": "forward",
"signature": "def forward(self, ... | 2 | stack_v2_sparse_classes_30k_train_018764 | Implement the Python class `GMM` described below.
Class description:
Implement the GMM class.
Method signatures and docstrings:
- def __init__(self, noise_dims, num_comp): noise_dims = Number of noise dimensions num_comp = Number of noise components
- def forward(self, input, noise, target_size): noise: batch_size x ... | Implement the Python class `GMM` described below.
Class description:
Implement the GMM class.
Method signatures and docstrings:
- def __init__(self, noise_dims, num_comp): noise_dims = Number of noise dimensions num_comp = Number of noise components
- def forward(self, input, noise, target_size): noise: batch_size x ... | ca6f291761d7559b957575c030f06ca6ae0017d2 | <|skeleton|>
class GMM:
def __init__(self, noise_dims, num_comp):
"""noise_dims = Number of noise dimensions num_comp = Number of noise components"""
<|body_0|>
def forward(self, input, noise, target_size):
"""noise: batch_size x num_samples x noise_dim"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GMM:
def __init__(self, noise_dims, num_comp):
"""noise_dims = Number of noise dimensions num_comp = Number of noise components"""
super(GMM, self).__init__()
self.num_comp = num_comp
self.noise_dims = noise_dims
self.means = Parameter(torch.randn(num_comp, noise_dims))... | the_stack_v2_python_sparse | prednet/stochastic/models/models.py | yaminibansal/pytorchprednet | train | 0 | |
d978676738ed1f4974790da615d016fce2b1a497 | [
"if n == 0:\n return list()\nreturn [self.gen_triangle_level(i) for i in range(1, n + 1, 1)]",
"if i == 1:\n return list([1])\nt = self.gen_triangle_level(i - 1)\nm = len(t) + 1\nreturn [1 if j == 0 or j == m - 1 else t[j - 1] + t[j] for j in range(0, m, 1)]"
] | <|body_start_0|>
if n == 0:
return list()
return [self.gen_triangle_level(i) for i in range(1, n + 1, 1)]
<|end_body_0|>
<|body_start_1|>
if i == 1:
return list([1])
t = self.gen_triangle_level(i - 1)
m = len(t) + 1
return [1 if j == 0 or j == m -... | Pythonic iteration over all Pascal triangle depths and node values. Implements memoization algorithm (top-down dynamic programming). Time complexity: O(n ** m) - Iterate over all triangle depths and values Space complexity: O(n ** m) - Store all intermediate triangle values | Solution | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Pythonic iteration over all Pascal triangle depths and node values. Implements memoization algorithm (top-down dynamic programming). Time complexity: O(n ** m) - Iterate over all triangle depths and values Space complexity: O(n ** m) - Store all intermediate triangle values"""
d... | stack_v2_sparse_classes_36k_train_009901 | 3,716 | permissive | [
{
"docstring": "Creates Pascal triangle to specified depth \"n\". :param int n: max depth of target Pascal triangle :return: array of all triangle levels to max depth \"n\" (inclusive) :rtype: list[list[int]]",
"name": "create_pascal_triangle",
"signature": "def create_pascal_triangle(self, n)"
},
{... | 2 | stack_v2_sparse_classes_30k_test_000857 | Implement the Python class `Solution` described below.
Class description:
Pythonic iteration over all Pascal triangle depths and node values. Implements memoization algorithm (top-down dynamic programming). Time complexity: O(n ** m) - Iterate over all triangle depths and values Space complexity: O(n ** m) - Store all... | Implement the Python class `Solution` described below.
Class description:
Pythonic iteration over all Pascal triangle depths and node values. Implements memoization algorithm (top-down dynamic programming). Time complexity: O(n ** m) - Iterate over all triangle depths and values Space complexity: O(n ** m) - Store all... | 69f90877c5466927e8b081c4268cbcda074813ec | <|skeleton|>
class Solution:
"""Pythonic iteration over all Pascal triangle depths and node values. Implements memoization algorithm (top-down dynamic programming). Time complexity: O(n ** m) - Iterate over all triangle depths and values Space complexity: O(n ** m) - Store all intermediate triangle values"""
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""Pythonic iteration over all Pascal triangle depths and node values. Implements memoization algorithm (top-down dynamic programming). Time complexity: O(n ** m) - Iterate over all triangle depths and values Space complexity: O(n ** m) - Store all intermediate triangle values"""
def create_pas... | the_stack_v2_python_sparse | 0118_pascals_triangle/python_source.py | arthurdysart/LeetCode | train | 0 |
ee0411dcb2a7aeb73dc1f3e9180b96a59e186241 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('esaracin', 'esaracin')\ndataset = repo['esaracin.boston_shootings'].find()\ndf_shootings = pd.DataFrame(list(dataset))\ncrime_types = df_shootings['INCIDENT_TYPE_DESCRIPTION'].unique()\npolice_districts ... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('esaracin', 'esaracin')
dataset = repo['esaracin.boston_shootings'].find()
df_shootings = pd.DataFrame(list(dataset))
crime_types = df_shoo... | build_shooting_set | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class build_shooting_set:
def execute(trial=False):
"""Retrieves our data sets from Boston Open Data using specific URLs. Creates the necessary pymongo collections within our repo database."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
... | stack_v2_sparse_classes_36k_train_009902 | 4,275 | no_license | [
{
"docstring": "Retrieves our data sets from Boston Open Data using specific URLs. Creates the necessary pymongo collections within our repo database.",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Creates the provenance document describing the merging of data oc... | 2 | stack_v2_sparse_classes_30k_train_008817 | Implement the Python class `build_shooting_set` described below.
Class description:
Implement the build_shooting_set class.
Method signatures and docstrings:
- def execute(trial=False): Retrieves our data sets from Boston Open Data using specific URLs. Creates the necessary pymongo collections within our repo databas... | Implement the Python class `build_shooting_set` described below.
Class description:
Implement the build_shooting_set class.
Method signatures and docstrings:
- def execute(trial=False): Retrieves our data sets from Boston Open Data using specific URLs. Creates the necessary pymongo collections within our repo databas... | 97e72731ffadbeae57d7a332decd58706e7c08de | <|skeleton|>
class build_shooting_set:
def execute(trial=False):
"""Retrieves our data sets from Boston Open Data using specific URLs. Creates the necessary pymongo collections within our repo database."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class build_shooting_set:
def execute(trial=False):
"""Retrieves our data sets from Boston Open Data using specific URLs. Creates the necessary pymongo collections within our repo database."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
... | the_stack_v2_python_sparse | esaracin/build_shooting_set.py | ROODAY/course-2017-fal-proj | train | 3 | |
192a806b70368b1b1553a42ec01b0d83d5c9cd8e | [
"result = collections.defaultdict(list)\nqueue = [(root, 0, 0)]\nminx, max = (0, 0)\nwhile queue:\n nextqueue = []\n while queue:\n node, x, y = queue.pop()\n minx = min(x, minx)\n maxx = max(x, maxx)\n result[x].append((y, node.val))\n if node.left:\n nextqueue.a... | <|body_start_0|>
result = collections.defaultdict(list)
queue = [(root, 0, 0)]
minx, max = (0, 0)
while queue:
nextqueue = []
while queue:
node, x, y = queue.pop()
minx = min(x, minx)
maxx = max(x, maxx)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def verticalTraversal(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_0|>
def verticalTraversal(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = co... | stack_v2_sparse_classes_36k_train_009903 | 1,964 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[List[int]]",
"name": "verticalTraversal",
"signature": "def verticalTraversal(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[List[int]]",
"name": "verticalTraversal",
"signature": "def verticalTraversal(self, root)"
}... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def verticalTraversal(self, root): :type root: TreeNode :rtype: List[List[int]]
- def verticalTraversal(self, root): :type root: TreeNode :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def verticalTraversal(self, root): :type root: TreeNode :rtype: List[List[int]]
- def verticalTraversal(self, root): :type root: TreeNode :rtype: List[List[int]]
<|skeleton|>
cl... | d953abe2c9680f636563e76287d2f907e90ced63 | <|skeleton|>
class Solution:
def verticalTraversal(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_0|>
def verticalTraversal(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def verticalTraversal(self, root):
""":type root: TreeNode :rtype: List[List[int]]"""
result = collections.defaultdict(list)
queue = [(root, 0, 0)]
minx, max = (0, 0)
while queue:
nextqueue = []
while queue:
node, x, y =... | the_stack_v2_python_sparse | python_leetcode_2020/Python_Leetcode_2020/987_vertical_order_traversal_binary_tree.py | xiangcao/Leetcode | train | 0 | |
c1186443007106adf8bd6295902d5f13a075f874 | [
"dp = [[0] * len(grid[0]) for _ in range(len(grid))]\nfor r in range(len(grid)):\n for w in range(len(grid[0])):\n if r > 0:\n if w > 0:\n dp[r][w] = min(dp[r - 1][w], dp[r][w - 1]) + grid[r][w]\n else:\n dp[r][w] = dp[r - 1][w] + grid[r][w]\n eli... | <|body_start_0|>
dp = [[0] * len(grid[0]) for _ in range(len(grid))]
for r in range(len(grid)):
for w in range(len(grid[0])):
if r > 0:
if w > 0:
dp[r][w] = min(dp[r - 1][w], dp[r][w - 1]) + grid[r][w]
else:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _minPathSum(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_0|>
def minPathSum(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dp = [[0] * len(grid[0]) for _ in ... | stack_v2_sparse_classes_36k_train_009904 | 2,305 | permissive | [
{
"docstring": ":type grid: List[List[int]] :rtype: int",
"name": "_minPathSum",
"signature": "def _minPathSum(self, grid)"
},
{
"docstring": ":type grid: List[List[int]] :rtype: int",
"name": "minPathSum",
"signature": "def minPathSum(self, grid)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _minPathSum(self, grid): :type grid: List[List[int]] :rtype: int
- def minPathSum(self, grid): :type grid: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _minPathSum(self, grid): :type grid: List[List[int]] :rtype: int
- def minPathSum(self, grid): :type grid: List[List[int]] :rtype: int
<|skeleton|>
class Solution:
def ... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _minPathSum(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_0|>
def minPathSum(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def _minPathSum(self, grid):
""":type grid: List[List[int]] :rtype: int"""
dp = [[0] * len(grid[0]) for _ in range(len(grid))]
for r in range(len(grid)):
for w in range(len(grid[0])):
if r > 0:
if w > 0:
... | the_stack_v2_python_sparse | 64.minimum-path-sum.py | windard/leeeeee | train | 0 | |
e0f8954cac756eec29f1296797de34f8e8f65155 | [
"self.variable = variable\nvalue = str(ServerVar(variable))\ntry:\n value = float(value)\nexcept:\n pass\nself.default = value",
"if not addon in self:\n return\nsuper(_RegisteredAddons, self).remove(addon)\nif not self:\n del VariableBackups[self.variable]"
] | <|body_start_0|>
self.variable = variable
value = str(ServerVar(variable))
try:
value = float(value)
except:
pass
self.default = value
<|end_body_0|>
<|body_start_1|>
if not addon in self:
return
super(_RegisteredAddons, self).... | Class used to register addons to the variable and store its default value | _RegisteredAddons | [
"Artistic-1.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _RegisteredAddons:
"""Class used to register addons to the variable and store its default value"""
def __init__(self, variable):
"""Stores the variable, its default value, and addons that register for the variable"""
<|body_0|>
def remove(self, addon):
"""Unregis... | stack_v2_sparse_classes_36k_train_009905 | 2,938 | permissive | [
{
"docstring": "Stores the variable, its default value, and addons that register for the variable",
"name": "__init__",
"signature": "def __init__(self, variable)"
},
{
"docstring": "Unregisters an addon for the variable and removes the variable from the dictionary if it is no longer registered"... | 2 | stack_v2_sparse_classes_30k_train_016176 | Implement the Python class `_RegisteredAddons` described below.
Class description:
Class used to register addons to the variable and store its default value
Method signatures and docstrings:
- def __init__(self, variable): Stores the variable, its default value, and addons that register for the variable
- def remove(... | Implement the Python class `_RegisteredAddons` described below.
Class description:
Class used to register addons to the variable and store its default value
Method signatures and docstrings:
- def __init__(self, variable): Stores the variable, its default value, and addons that register for the variable
- def remove(... | ebf4624626266f552189a32612b8d09cd5b4c5a3 | <|skeleton|>
class _RegisteredAddons:
"""Class used to register addons to the variable and store its default value"""
def __init__(self, variable):
"""Stores the variable, its default value, and addons that register for the variable"""
<|body_0|>
def remove(self, addon):
"""Unregis... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _RegisteredAddons:
"""Class used to register addons to the variable and store its default value"""
def __init__(self, variable):
"""Stores the variable, its default value, and addons that register for the variable"""
self.variable = variable
value = str(ServerVar(variable))
... | the_stack_v2_python_sparse | cstrike/addons/eventscripts/gungame51/modules/backups.py | GunGame-Dev-Team/GunGame51 | train | 0 |
1be7690b54b5cdd754c9e1a6455449796c7e406c | [
"super(NormalizedPacConv2d, self).__init__(in_channels, out_channels, kernel_size, stride=1, padding=padding, dilation=1, bias=bias, kernel_type=kernel_type, smooth_kernel_type='none', normalize_kernel=False, shared_filters=shared_filters, filler='uniform', native_impl=False)\nself.weight_normalization = torch.nn.p... | <|body_start_0|>
super(NormalizedPacConv2d, self).__init__(in_channels, out_channels, kernel_size, stride=1, padding=padding, dilation=1, bias=bias, kernel_type=kernel_type, smooth_kernel_type='none', normalize_kernel=False, shared_filters=shared_filters, filler='uniform', native_impl=False)
self.weight... | Implements a pixel-adaptive convolution with advanced normalization. | NormalizedPacConv2d | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NormalizedPacConv2d:
"""Implements a pixel-adaptive convolution with advanced normalization."""
def __init__(self, in_channels, out_channels, kernel_size, padding=0, bias=True, kernel_type='gaussian', shared_filters=False):
"""Initializes PAC with advanced normalization. Args: in_cha... | stack_v2_sparse_classes_36k_train_009906 | 7,401 | permissive | [
{
"docstring": "Initializes PAC with advanced normalization. Args: in_channels: Number of input channels. out_channels: Number of output channels. kernel_size: Filter size of used kernel. padding: Number of zero padding elements applied at all borders. bias: Usage of bias term. kernel_type: Type of kernel funct... | 2 | stack_v2_sparse_classes_30k_train_002564 | Implement the Python class `NormalizedPacConv2d` described below.
Class description:
Implements a pixel-adaptive convolution with advanced normalization.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, kernel_size, padding=0, bias=True, kernel_type='gaussian', shared_filters=False): ... | Implement the Python class `NormalizedPacConv2d` described below.
Class description:
Implements a pixel-adaptive convolution with advanced normalization.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, kernel_size, padding=0, bias=True, kernel_type='gaussian', shared_filters=False): ... | 04a8676f5eb96c41ec6b1125c6bcad430218ef30 | <|skeleton|>
class NormalizedPacConv2d:
"""Implements a pixel-adaptive convolution with advanced normalization."""
def __init__(self, in_channels, out_channels, kernel_size, padding=0, bias=True, kernel_type='gaussian', shared_filters=False):
"""Initializes PAC with advanced normalization. Args: in_cha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NormalizedPacConv2d:
"""Implements a pixel-adaptive convolution with advanced normalization."""
def __init__(self, in_channels, out_channels, kernel_size, padding=0, bias=True, kernel_type='gaussian', shared_filters=False):
"""Initializes PAC with advanced normalization. Args: in_channels: Number... | the_stack_v2_python_sparse | src/probabilistic_pac.py | visinf/ppac_refinement | train | 81 |
abeca593c173d61be194e3c86acaca8b8cb70c21 | [
"discriminator = getattr(ctx.dialog, 'discriminator', None)\nif discriminator:\n if not entities.Entity.ByKeys(discriminator):\n raise ue.Exception('csweb_err_classtilesmall_discriminator')",
"def _add_subclass_config(config, plugin_configs):\n \"\"\"\n The function checks if the class of ... | <|body_start_0|>
discriminator = getattr(ctx.dialog, 'discriminator', None)
if discriminator:
if not entities.Entity.ByKeys(discriminator):
raise ue.Exception('csweb_err_classtilesmall_discriminator')
<|end_body_0|>
<|body_start_1|>
def _add_subclass_config(config, p... | PlugIn to manage plugins with the id ``class-tile_small`` | WebUIPluginCallbackClassTileSmall | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WebUIPluginCallbackClassTileSmall:
"""PlugIn to manage plugins with the id ``class-tile_small``"""
def check_values(cls, ctx):
"""Check if the discriminator is a valid regular expression."""
<|body_0|>
def adapt_config(cls, plugin_configs):
"""This callback allow... | stack_v2_sparse_classes_36k_train_009907 | 8,936 | no_license | [
{
"docstring": "Check if the discriminator is a valid regular expression.",
"name": "check_values",
"signature": "def check_values(cls, ctx)"
},
{
"docstring": "This callback allows you to manipulate the plugin_config list after the configuration has been read from the database.",
"name": "a... | 2 | null | Implement the Python class `WebUIPluginCallbackClassTileSmall` described below.
Class description:
PlugIn to manage plugins with the id ``class-tile_small``
Method signatures and docstrings:
- def check_values(cls, ctx): Check if the discriminator is a valid regular expression.
- def adapt_config(cls, plugin_configs)... | Implement the Python class `WebUIPluginCallbackClassTileSmall` described below.
Class description:
PlugIn to manage plugins with the id ``class-tile_small``
Method signatures and docstrings:
- def check_values(cls, ctx): Check if the discriminator is a valid regular expression.
- def adapt_config(cls, plugin_configs)... | 6bc932c67bc8d93b873838ae6d9fb8d33c72234d | <|skeleton|>
class WebUIPluginCallbackClassTileSmall:
"""PlugIn to manage plugins with the id ``class-tile_small``"""
def check_values(cls, ctx):
"""Check if the discriminator is a valid regular expression."""
<|body_0|>
def adapt_config(cls, plugin_configs):
"""This callback allow... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WebUIPluginCallbackClassTileSmall:
"""PlugIn to manage plugins with the id ``class-tile_small``"""
def check_values(cls, ctx):
"""Check if the discriminator is a valid regular expression."""
discriminator = getattr(ctx.dialog, 'discriminator', None)
if discriminator:
i... | the_stack_v2_python_sparse | site-packages/cs.web-15.3.0.6-py2.7.egg/cs/web/components/plugin_config.py | prachipainuly-rbei/devops-poc | train | 0 |
793e9053b218a4c4ece4d609e02a50cd685bfa1b | [
"super(PositionalEncoding, self).__init__()\nself.d_model = d_model\nself.xscale = math.sqrt(self.d_model)\nself.dropout = nn.Dropout(p=dropout)\nself.pe = None\nself.extend_pe(torch.tensor(0.0).expand(1, max_len))",
"if self.pe is not None:\n if self.pe.size(1) >= x.size(1):\n if self.pe.dtype != x.dty... | <|body_start_0|>
super(PositionalEncoding, self).__init__()
self.d_model = d_model
self.xscale = math.sqrt(self.d_model)
self.dropout = nn.Dropout(p=dropout)
self.pe = None
self.extend_pe(torch.tensor(0.0).expand(1, max_len))
<|end_body_0|>
<|body_start_1|>
if se... | Positional encoding. Args: d_model: Embedding dimension. dropout: Dropout rate. max_len: Maximum input length. | PositionalEncoding | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PositionalEncoding:
"""Positional encoding. Args: d_model: Embedding dimension. dropout: Dropout rate. max_len: Maximum input length."""
def __init__(self, d_model: int, dropout: float=0.1, max_len: int=5000) -> None:
"""Construct an PositionalEncoding object."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_009908 | 33,189 | permissive | [
{
"docstring": "Construct an PositionalEncoding object.",
"name": "__init__",
"signature": "def __init__(self, d_model: int, dropout: float=0.1, max_len: int=5000) -> None"
},
{
"docstring": "Reset the positional encodings.",
"name": "extend_pe",
"signature": "def extend_pe(self, x: Tens... | 3 | stack_v2_sparse_classes_30k_test_000475 | Implement the Python class `PositionalEncoding` described below.
Class description:
Positional encoding. Args: d_model: Embedding dimension. dropout: Dropout rate. max_len: Maximum input length.
Method signatures and docstrings:
- def __init__(self, d_model: int, dropout: float=0.1, max_len: int=5000) -> None: Constr... | Implement the Python class `PositionalEncoding` described below.
Class description:
Positional encoding. Args: d_model: Embedding dimension. dropout: Dropout rate. max_len: Maximum input length.
Method signatures and docstrings:
- def __init__(self, d_model: int, dropout: float=0.1, max_len: int=5000) -> None: Constr... | 2dda31e14039a79b77c89bcd3bb96d52cbf60c8a | <|skeleton|>
class PositionalEncoding:
"""Positional encoding. Args: d_model: Embedding dimension. dropout: Dropout rate. max_len: Maximum input length."""
def __init__(self, d_model: int, dropout: float=0.1, max_len: int=5000) -> None:
"""Construct an PositionalEncoding object."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PositionalEncoding:
"""Positional encoding. Args: d_model: Embedding dimension. dropout: Dropout rate. max_len: Maximum input length."""
def __init__(self, d_model: int, dropout: float=0.1, max_len: int=5000) -> None:
"""Construct an PositionalEncoding object."""
super(PositionalEncoding,... | the_stack_v2_python_sparse | snowfall/models/transformer.py | csukuangfj/snowfall | train | 0 |
5d4408c1875d87f2f2c3223dbfceb0d0a6af17ed | [
"self.product_code = product_code\nself.description = description\nself.market_price = market_price\nself.rental_price = rental_price",
"output_dict = {}\noutput_dict['productCode'] = self.product_code\noutput_dict['description'] = self.description\noutput_dict['marketPrice'] = self.market_price\noutput_dict['ren... | <|body_start_0|>
self.product_code = product_code
self.description = description
self.market_price = market_price
self.rental_price = rental_price
<|end_body_0|>
<|body_start_1|>
output_dict = {}
output_dict['productCode'] = self.product_code
output_dict['descrip... | Inventory class | Inventory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Inventory:
"""Inventory class"""
def __init__(self, product_code, description, market_price, rental_price):
"""class construction"""
<|body_0|>
def return_as_dictionary(self):
"""function to return an inventory dictionary"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_009909 | 809 | no_license | [
{
"docstring": "class construction",
"name": "__init__",
"signature": "def __init__(self, product_code, description, market_price, rental_price)"
},
{
"docstring": "function to return an inventory dictionary",
"name": "return_as_dictionary",
"signature": "def return_as_dictionary(self)"
... | 2 | null | Implement the Python class `Inventory` described below.
Class description:
Inventory class
Method signatures and docstrings:
- def __init__(self, product_code, description, market_price, rental_price): class construction
- def return_as_dictionary(self): function to return an inventory dictionary | Implement the Python class `Inventory` described below.
Class description:
Inventory class
Method signatures and docstrings:
- def __init__(self, product_code, description, market_price, rental_price): class construction
- def return_as_dictionary(self): function to return an inventory dictionary
<|skeleton|>
class ... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class Inventory:
"""Inventory class"""
def __init__(self, product_code, description, market_price, rental_price):
"""class construction"""
<|body_0|>
def return_as_dictionary(self):
"""function to return an inventory dictionary"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Inventory:
"""Inventory class"""
def __init__(self, product_code, description, market_price, rental_price):
"""class construction"""
self.product_code = product_code
self.description = description
self.market_price = market_price
self.rental_price = rental_price
... | the_stack_v2_python_sparse | students/ethan_nguyen/Lesson01/assignment/inventory_management/inventory_class.py | JavaRod/SP_Python220B_2019 | train | 1 |
566e75892cc5937b60491c88610c7514f6d89ccd | [
"self.f = f\nself.gp = GP(X_init, Y_init, l, sigma_f)\nmin, max = bounds\nX_s = np.linspace(min, max, ac_samples)\nself.X_s = np.sort(X_s).reshape(-1, 1)\nself.xsi = xsi\nself.minimize = minimize",
"mu, sigma = self.gp.predict(self.X_s)\nif self.minimize is True:\n optimize = np.amin(self.gp.Y)\n imp = opti... | <|body_start_0|>
self.f = f
self.gp = GP(X_init, Y_init, l, sigma_f)
min, max = bounds
X_s = np.linspace(min, max, ac_samples)
self.X_s = np.sort(X_s).reshape(-1, 1)
self.xsi = xsi
self.minimize = minimize
<|end_body_0|>
<|body_start_1|>
mu, sigma = self.... | Performs Bayesian optimization on a noiseless 1D Gaussian process | BayesianOptimization | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BayesianOptimization:
"""Performs Bayesian optimization on a noiseless 1D Gaussian process"""
def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):
"""Class constructor Args: f: is the black-box function to be optimized X_init: is a numpy... | stack_v2_sparse_classes_36k_train_009910 | 3,572 | no_license | [
{
"docstring": "Class constructor Args: f: is the black-box function to be optimized X_init: is a numpy.ndarray of shape (t, 1) representing the inputs already sampled with the black-box function Y_init: is a numpy.ndarray of shape (t, 1) representing the outputs of the black-box function for each input in X_in... | 3 | null | Implement the Python class `BayesianOptimization` described below.
Class description:
Performs Bayesian optimization on a noiseless 1D Gaussian process
Method signatures and docstrings:
- def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True): Class constructor Args: f: is ... | Implement the Python class `BayesianOptimization` described below.
Class description:
Performs Bayesian optimization on a noiseless 1D Gaussian process
Method signatures and docstrings:
- def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True): Class constructor Args: f: is ... | 8ad4c2594ff78b345dbd92e9d54d2a143ac4071a | <|skeleton|>
class BayesianOptimization:
"""Performs Bayesian optimization on a noiseless 1D Gaussian process"""
def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):
"""Class constructor Args: f: is the black-box function to be optimized X_init: is a numpy... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BayesianOptimization:
"""Performs Bayesian optimization on a noiseless 1D Gaussian process"""
def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):
"""Class constructor Args: f: is the black-box function to be optimized X_init: is a numpy.ndarray of s... | the_stack_v2_python_sparse | unsupervised_learning/0x03-hyperparameter_tuning/5-bayes_opt.py | jorgezafra94/holbertonschool-machine_learning | train | 1 |
d3efd2f8f3d27bbd4b365d9cebbf902a3482248c | [
"super(InstanceGroupNetworkMigration, self).__init__()\nself.instance_group = self.build_instance_group()\nself.instance_group_migration_handler = self.build_instance_group_handler()",
"instance_group_helper = InstanceGroupHelper(self.compute, self.project, self.instance_group_name, self.region, self.zone, self.n... | <|body_start_0|>
super(InstanceGroupNetworkMigration, self).__init__()
self.instance_group = self.build_instance_group()
self.instance_group_migration_handler = self.build_instance_group_handler()
<|end_body_0|>
<|body_start_1|>
instance_group_helper = InstanceGroupHelper(self.compute, ... | InstanceGroupNetworkMigration | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstanceGroupNetworkMigration:
def __init__(self, compute, project, network_name, subnetwork_name, preserve_external_ip, zone, region, instance_group_name):
"""Initialize a InstanceNetworkMigration object Args: compute: google compute engine API project: project id network_name: target n... | stack_v2_sparse_classes_36k_train_009911 | 5,430 | permissive | [
{
"docstring": "Initialize a InstanceNetworkMigration object Args: compute: google compute engine API project: project id network_name: target network subnetwork_name: target subnetwork preserve_external_ip: whether to preserve instances' external IPs zone: zone of a zonal instance group region: region of regio... | 5 | stack_v2_sparse_classes_30k_train_020462 | Implement the Python class `InstanceGroupNetworkMigration` described below.
Class description:
Implement the InstanceGroupNetworkMigration class.
Method signatures and docstrings:
- def __init__(self, compute, project, network_name, subnetwork_name, preserve_external_ip, zone, region, instance_group_name): Initialize... | Implement the Python class `InstanceGroupNetworkMigration` described below.
Class description:
Implement the InstanceGroupNetworkMigration class.
Method signatures and docstrings:
- def __init__(self, compute, project, network_name, subnetwork_name, preserve_external_ip, zone, region, instance_group_name): Initialize... | 1132e44d696ab9da4d1079ebc3d32ed4382cdc28 | <|skeleton|>
class InstanceGroupNetworkMigration:
def __init__(self, compute, project, network_name, subnetwork_name, preserve_external_ip, zone, region, instance_group_name):
"""Initialize a InstanceNetworkMigration object Args: compute: google compute engine API project: project id network_name: target n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InstanceGroupNetworkMigration:
def __init__(self, compute, project, network_name, subnetwork_name, preserve_external_ip, zone, region, instance_group_name):
"""Initialize a InstanceNetworkMigration object Args: compute: google compute engine API project: project id network_name: target network subnetw... | the_stack_v2_python_sparse | vm_network_migration/handlers/instance_group_migration/instance_group_network_migration.py | googleinterns/vm-network-migration | train | 1 | |
b50876a373beea5b55bfe702cfb558dd9b2d6665 | [
"self.session = session\nself.summary_placeholders = {}\nself.summary_ops = {}\nself.train_summary_writer = tf.summary.FileWriter(os.path.join(log_path, 'train'), self.session.graph)\nself.test_summary_writer = tf.summary.FileWriter(os.path.join(log_path, 'test'))",
"summary_writer = self.train_summary_writer if ... | <|body_start_0|>
self.session = session
self.summary_placeholders = {}
self.summary_ops = {}
self.train_summary_writer = tf.summary.FileWriter(os.path.join(log_path, 'train'), self.session.graph)
self.test_summary_writer = tf.summary.FileWriter(os.path.join(log_path, 'test'))
<|e... | TensorLogger object helps to log the training/testing progress in Tensorboard | TensorLogger | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TensorLogger:
"""TensorLogger object helps to log the training/testing progress in Tensorboard"""
def __init__(self, log_path, session):
""":param str log_path: path where we keep the logs :param tf.Session session: tensorflow session"""
<|body_0|>
def log_scalars(self, ... | stack_v2_sparse_classes_36k_train_009912 | 2,167 | no_license | [
{
"docstring": ":param str log_path: path where we keep the logs :param tf.Session session: tensorflow session",
"name": "__init__",
"signature": "def __init__(self, log_path, session)"
},
{
"docstring": "Logs the scalars of decoded string in Tensorboard :param int step: the step of the summary ... | 2 | stack_v2_sparse_classes_30k_train_017142 | Implement the Python class `TensorLogger` described below.
Class description:
TensorLogger object helps to log the training/testing progress in Tensorboard
Method signatures and docstrings:
- def __init__(self, log_path, session): :param str log_path: path where we keep the logs :param tf.Session session: tensorflow ... | Implement the Python class `TensorLogger` described below.
Class description:
TensorLogger object helps to log the training/testing progress in Tensorboard
Method signatures and docstrings:
- def __init__(self, log_path, session): :param str log_path: path where we keep the logs :param tf.Session session: tensorflow ... | 6793d8f471038b2401df2376aa7a8d97b440927a | <|skeleton|>
class TensorLogger:
"""TensorLogger object helps to log the training/testing progress in Tensorboard"""
def __init__(self, log_path, session):
""":param str log_path: path where we keep the logs :param tf.Session session: tensorflow session"""
<|body_0|>
def log_scalars(self, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TensorLogger:
"""TensorLogger object helps to log the training/testing progress in Tensorboard"""
def __init__(self, log_path, session):
""":param str log_path: path where we keep the logs :param tf.Session session: tensorflow session"""
self.session = session
self.summary_placeho... | the_stack_v2_python_sparse | object_detection/utils/tensor_logger.py | zvadaadam/traffic-object-detection | train | 0 |
d53123f8286514231614dc17e6d3e1e9956f4de2 | [
"print(validated_data)\nquiz = Quiz.objects.create(**validated_data)\nreturn quiz\n'\\n answers_data = validated_data.pop(\"answers\")\\n question = Question.objects.create(**validated_data)\\n for answer in answers_data:\\n answer = Answer.objects.create(question=question, **answer... | <|body_start_0|>
print(validated_data)
quiz = Quiz.objects.create(**validated_data)
return quiz
'\n answers_data = validated_data.pop("answers")\n question = Question.objects.create(**validated_data)\n for answer in answers_data:\n answer = Answer.objects... | QuizSerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuizSerializer:
def create(self, validated_data, *args, **kwargs):
"""we can override the create method"""
<|body_0|>
def update(self, instance, validated_data):
"""update or put the exsiting value"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pri... | stack_v2_sparse_classes_36k_train_009913 | 2,460 | permissive | [
{
"docstring": "we can override the create method",
"name": "create",
"signature": "def create(self, validated_data, *args, **kwargs)"
},
{
"docstring": "update or put the exsiting value",
"name": "update",
"signature": "def update(self, instance, validated_data)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001111 | Implement the Python class `QuizSerializer` described below.
Class description:
Implement the QuizSerializer class.
Method signatures and docstrings:
- def create(self, validated_data, *args, **kwargs): we can override the create method
- def update(self, instance, validated_data): update or put the exsiting value | Implement the Python class `QuizSerializer` described below.
Class description:
Implement the QuizSerializer class.
Method signatures and docstrings:
- def create(self, validated_data, *args, **kwargs): we can override the create method
- def update(self, instance, validated_data): update or put the exsiting value
<... | bebeff8d055ea769773cd1c749f42408aa83f5b9 | <|skeleton|>
class QuizSerializer:
def create(self, validated_data, *args, **kwargs):
"""we can override the create method"""
<|body_0|>
def update(self, instance, validated_data):
"""update or put the exsiting value"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuizSerializer:
def create(self, validated_data, *args, **kwargs):
"""we can override the create method"""
print(validated_data)
quiz = Quiz.objects.create(**validated_data)
return quiz
'\n answers_data = validated_data.pop("answers")\n question = Questio... | the_stack_v2_python_sparse | backend/quiz/api/serializers/quizes.py | mahmoud-batman/quizz-app | train | 0 | |
2a57ab619fea5c93fb191973a9c9a32edb6bfdb9 | [
"query = 'sqlite3 {0} \"update {1} set '.format(db, table)\ni = 0\nfor column in columns:\n query += \"{0} = '{1}', \".format(column, values[i])\n i += 1\nquery = query.strip().strip(',')\nquery += ' where '\ni = 0\nfor column in where_columns:\n query += \"{0} = '{1}' and \".format(column, where_values[i]... | <|body_start_0|>
query = 'sqlite3 {0} "update {1} set '.format(db, table)
i = 0
for column in columns:
query += "{0} = '{1}', ".format(column, values[i])
i += 1
query = query.strip().strip(',')
query += ' where '
i = 0
for column in where_c... | Sqlite | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sqlite:
def generate_update_query(db, table, columns, values, where_columns, where_values):
"""description: forms the <update> query from given parameters db = path to db on the device table = table on which the update will be performed columns = list of the columns to be updated values ... | stack_v2_sparse_classes_36k_train_009914 | 20,926 | permissive | [
{
"docstring": "description: forms the <update> query from given parameters db = path to db on the device table = table on which the update will be performed columns = list of the columns to be updated values = list of values to be used for update where_columns = list of columns to be used for identifying the e... | 2 | null | Implement the Python class `Sqlite` described below.
Class description:
Implement the Sqlite class.
Method signatures and docstrings:
- def generate_update_query(db, table, columns, values, where_columns, where_values): description: forms the <update> query from given parameters db = path to db on the device table = ... | Implement the Python class `Sqlite` described below.
Class description:
Implement the Sqlite class.
Method signatures and docstrings:
- def generate_update_query(db, table, columns, values, where_columns, where_values): description: forms the <update> query from given parameters db = path to db on the device table = ... | 7bf09f20f117fc74d02b7635305ce664b65cdcba | <|skeleton|>
class Sqlite:
def generate_update_query(db, table, columns, values, where_columns, where_values):
"""description: forms the <update> query from given parameters db = path to db on the device table = table on which the update will be performed columns = list of the columns to be updated values ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Sqlite:
def generate_update_query(db, table, columns, values, where_columns, where_values):
"""description: forms the <update> query from given parameters db = path to db on the device table = table on which the update will be performed columns = list of the columns to be updated values = list of valu... | the_stack_v2_python_sparse | acs_test_suites/OTC/libs/testlib/scripts/android/adb/adb_utils.py | intel/test-framework-and-suites-for-android | train | 9 | |
17b08756a0fd45fe379484af9ec8d98b7a266698 | [
"self.lenses_list = lenses_list\nself.sources_list = sources_list\nself.global_dict = global_dict\nself.observation_dict = observation_dict\nself.set_up_global()\nself.set_up_observation()",
"self.z_s = self.global_dict['z_s']\nself.z_l = self.global_dict['z_l']\nself.D_s = Planck15.angular_diameter_distance(z=se... | <|body_start_0|>
self.lenses_list = lenses_list
self.sources_list = sources_list
self.global_dict = global_dict
self.observation_dict = observation_dict
self.set_up_global()
self.set_up_observation()
<|end_body_0|>
<|body_start_1|>
self.z_s = self.global_dict['z_... | LensingSim | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LensingSim:
def __init__(self, lenses_list=[{}], sources_list=[{}], global_dict={}, observation_dict={}):
"""Class for simulation of strong lensing images"""
<|body_0|>
def set_up_global(self):
"""Set some global variables so don't need to recompute each time"""
... | stack_v2_sparse_classes_36k_train_009915 | 5,119 | permissive | [
{
"docstring": "Class for simulation of strong lensing images",
"name": "__init__",
"signature": "def __init__(self, lenses_list=[{}], sources_list=[{}], global_dict={}, observation_dict={})"
},
{
"docstring": "Set some global variables so don't need to recompute each time",
"name": "set_up_... | 4 | stack_v2_sparse_classes_30k_train_000072 | Implement the Python class `LensingSim` described below.
Class description:
Implement the LensingSim class.
Method signatures and docstrings:
- def __init__(self, lenses_list=[{}], sources_list=[{}], global_dict={}, observation_dict={}): Class for simulation of strong lensing images
- def set_up_global(self): Set som... | Implement the Python class `LensingSim` described below.
Class description:
Implement the LensingSim class.
Method signatures and docstrings:
- def __init__(self, lenses_list=[{}], sources_list=[{}], global_dict={}, observation_dict={}): Class for simulation of strong lensing images
- def set_up_global(self): Set som... | 8f432b58cecdafd70054fa63f285f3f284fa0720 | <|skeleton|>
class LensingSim:
def __init__(self, lenses_list=[{}], sources_list=[{}], global_dict={}, observation_dict={}):
"""Class for simulation of strong lensing images"""
<|body_0|>
def set_up_global(self):
"""Set some global variables so don't need to recompute each time"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LensingSim:
def __init__(self, lenses_list=[{}], sources_list=[{}], global_dict={}, observation_dict={}):
"""Class for simulation of strong lensing images"""
self.lenses_list = lenses_list
self.sources_list = sources_list
self.global_dict = global_dict
self.observation_... | the_stack_v2_python_sparse | simulation/lensing_sim.py | smsharma/mining-for-substructure-lens | train | 25 | |
b01d28fdd8776473a9c8d1921a1cf8108feef178 | [
"m = 300\nctx.save_for_backward(k)\nk = k.double()\nanswer = (m / 2 - 1) * torch.log(k) - torch.log(sp.special.ive(m / 2 - 1, k)).cuda() - k - m / 2 * np.log(2 * np.pi)\nanswer = answer.float()\nreturn answer",
"k, = ctx.saved_tensors\nm = 300\nk = k.double()\nx = -(sp.special.ive(m / 2, k) / sp.special.ive(m / 2... | <|body_start_0|>
m = 300
ctx.save_for_backward(k)
k = k.double()
answer = (m / 2 - 1) * torch.log(k) - torch.log(sp.special.ive(m / 2 - 1, k)).cuda() - k - m / 2 * np.log(2 * np.pi)
answer = answer.float()
return answer
<|end_body_0|>
<|body_start_1|>
k, = ctx.sa... | The exponentially scaled modified Bessel function of the first kind | Logcmk | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Logcmk:
"""The exponentially scaled modified Bessel function of the first kind"""
def forward(ctx, k):
"""In the forward pass we receive a Tensor containing the input and return a Tensor containing the output. ctx is a context object that can be used to stash information for backward... | stack_v2_sparse_classes_36k_train_009916 | 10,462 | permissive | [
{
"docstring": "In the forward pass we receive a Tensor containing the input and return a Tensor containing the output. ctx is a context object that can be used to stash information for backward computation. You can cache arbitrary objects for use in the backward pass using the ctx.save_for_backward method.",
... | 2 | null | Implement the Python class `Logcmk` described below.
Class description:
The exponentially scaled modified Bessel function of the first kind
Method signatures and docstrings:
- def forward(ctx, k): In the forward pass we receive a Tensor containing the input and return a Tensor containing the output. ctx is a context ... | Implement the Python class `Logcmk` described below.
Class description:
The exponentially scaled modified Bessel function of the first kind
Method signatures and docstrings:
- def forward(ctx, k): In the forward pass we receive a Tensor containing the input and return a Tensor containing the output. ctx is a context ... | 99cba1030ed8c012a453bc7715830fc99fb980dc | <|skeleton|>
class Logcmk:
"""The exponentially scaled modified Bessel function of the first kind"""
def forward(ctx, k):
"""In the forward pass we receive a Tensor containing the input and return a Tensor containing the output. ctx is a context object that can be used to stash information for backward... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Logcmk:
"""The exponentially scaled modified Bessel function of the first kind"""
def forward(ctx, k):
"""In the forward pass we receive a Tensor containing the input and return a Tensor containing the output. ctx is a context object that can be used to stash information for backward computation.... | the_stack_v2_python_sparse | models/loss/vonmises.py | jamesoneill12/LayerFusion | train | 2 |
f5a18acda7f0176407a365ce9ef37dcf50b06033 | [
"try:\n tasks = request.args.get('tasks') if request.args.get('tasks') else None\n as_file = strtobool(request.args.get('as_file')) if request.args.get('as_file') else True\n tasks_json = ProjectService.get_project_tasks(int(project_id), tasks)\n if as_file:\n tasks_json = str(tasks_json).encode(... | <|body_start_0|>
try:
tasks = request.args.get('tasks') if request.args.get('tasks') else None
as_file = strtobool(request.args.get('as_file')) if request.args.get('as_file') else True
tasks_json = ProjectService.get_project_tasks(int(project_id), tasks)
if as_fil... | TasksQueriesJsonAPI | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TasksQueriesJsonAPI:
def get(self, project_id):
"""Get all tasks for a project as JSON --- tags: - tasks produces: - application/json parameters: - name: project_id in: path description: Project ID the task is associated with required: true type: integer default: 1 - in: query name: task... | stack_v2_sparse_classes_36k_train_009917 | 16,428 | permissive | [
{
"docstring": "Get all tasks for a project as JSON --- tags: - tasks produces: - application/json parameters: - name: project_id in: path description: Project ID the task is associated with required: true type: integer default: 1 - in: query name: tasks type: string description: List of tasks; leave blank to r... | 2 | null | Implement the Python class `TasksQueriesJsonAPI` described below.
Class description:
Implement the TasksQueriesJsonAPI class.
Method signatures and docstrings:
- def get(self, project_id): Get all tasks for a project as JSON --- tags: - tasks produces: - application/json parameters: - name: project_id in: path descri... | Implement the Python class `TasksQueriesJsonAPI` described below.
Class description:
Implement the TasksQueriesJsonAPI class.
Method signatures and docstrings:
- def get(self, project_id): Get all tasks for a project as JSON --- tags: - tasks produces: - application/json parameters: - name: project_id in: path descri... | 45bf3937c74902226096aee5b49e7abea62df524 | <|skeleton|>
class TasksQueriesJsonAPI:
def get(self, project_id):
"""Get all tasks for a project as JSON --- tags: - tasks produces: - application/json parameters: - name: project_id in: path description: Project ID the task is associated with required: true type: integer default: 1 - in: query name: task... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TasksQueriesJsonAPI:
def get(self, project_id):
"""Get all tasks for a project as JSON --- tags: - tasks produces: - application/json parameters: - name: project_id in: path description: Project ID the task is associated with required: true type: integer default: 1 - in: query name: tasks type: string... | the_stack_v2_python_sparse | backend/api/tasks/resources.py | hotosm/tasking-manager | train | 526 | |
3ae4f1019bf71f99c7df2bae6d1341af33d0dd11 | [
"if root == None:\n return []\nqueue = collections.deque()\nqueue.append(root)\nans = []\nwhile queue:\n root = queue.popleft()\n if not root:\n ans.append(None)\n else:\n ans.append(root.val)\n queue.append(root.left)\n queue.append(root.right)\nreturn ans",
"if data == []... | <|body_start_0|>
if root == None:
return []
queue = collections.deque()
queue.append(root)
ans = []
while queue:
root = queue.popleft()
if not root:
ans.append(None)
else:
ans.append(root.val)
... | 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_009918 | 3,342 | 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 | null | 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:... | 692bf0e5aab402d55463274e99ab4d0ed56ce64c | <|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 root == None:
return []
queue = collections.deque()
queue.append(root)
ans = []
while queue:
root = queue.popleft()
... | the_stack_v2_python_sparse | 297-serialize_and_deserialize_bin_tree.py | WweiL/LeetCode | train | 0 | |
bfcb32b1b13f914bf5c07adfdf5124d167a8b091 | [
"self.combine_mode = combine_mode\nsuper().__init__(name, parent, hyperparameter_config, spatial_scale)\npass",
"new_block = gn.genes.ConvBlockGene('conv block', parent=self)\nself.children.append(new_block)\npass",
"if len(self.children) > 1 and self.hyperparam('spatial_mode') == 1:\n self.children[1].set(p... | <|body_start_0|>
self.combine_mode = combine_mode
super().__init__(name, parent, hyperparameter_config, spatial_scale)
pass
<|end_body_0|>
<|body_start_1|>
new_block = gn.genes.ConvBlockGene('conv block', parent=self)
self.children.append(new_block)
pass
<|end_body_1|>
... | A Gene for a module with parallel convolution block paths at multiple spatial scales. | SpatialPyramidGene | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpatialPyramidGene:
"""A Gene for a module with parallel convolution block paths at multiple spatial scales."""
def __init__(self, combine_mode: str='add', name: str='spatial_pyramid', parent: Optional[gn.genes.ScaleGene]=None, hyperparameter_config: Optional[mt.HyperparameterConfig]=None, s... | stack_v2_sparse_classes_36k_train_009919 | 9,428 | no_license | [
{
"docstring": "Constructor. Args: combine_mode (str): Combination mode for the output of the multiscale feature maps. Must be 'add', for a residual connection, or 'merge' for a merge connection. name (str): This gene's name. parent (Optional[gn.ScaleGene]): Parent gene. hyperparameter_config (Optional[mt.Hyper... | 5 | stack_v2_sparse_classes_30k_val_000917 | Implement the Python class `SpatialPyramidGene` described below.
Class description:
A Gene for a module with parallel convolution block paths at multiple spatial scales.
Method signatures and docstrings:
- def __init__(self, combine_mode: str='add', name: str='spatial_pyramid', parent: Optional[gn.genes.ScaleGene]=No... | Implement the Python class `SpatialPyramidGene` described below.
Class description:
A Gene for a module with parallel convolution block paths at multiple spatial scales.
Method signatures and docstrings:
- def __init__(self, combine_mode: str='add', name: str='spatial_pyramid', parent: Optional[gn.genes.ScaleGene]=No... | 6b78dc5e1e793a206ae3f4860d3a9ac887e663e5 | <|skeleton|>
class SpatialPyramidGene:
"""A Gene for a module with parallel convolution block paths at multiple spatial scales."""
def __init__(self, combine_mode: str='add', name: str='spatial_pyramid', parent: Optional[gn.genes.ScaleGene]=None, hyperparameter_config: Optional[mt.HyperparameterConfig]=None, s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpatialPyramidGene:
"""A Gene for a module with parallel convolution block paths at multiple spatial scales."""
def __init__(self, combine_mode: str='add', name: str='spatial_pyramid', parent: Optional[gn.genes.ScaleGene]=None, hyperparameter_config: Optional[mt.HyperparameterConfig]=None, spatial_scale:... | the_stack_v2_python_sparse | example2/src/_private/SpatialPyramidGene.py | leapmanlab/examples | train | 1 |
dac31e70d66fc6b3a588c2d56cfe7e2ac707b4ed | [
"AbstractModule.__init__(self, scripts=scripts, styles=styles)\nself.button_label = button_label\nself.label = label\nself.default_value = default_value",
"params = {'button_label': self.button_label}\nif self.label is not None:\n params.update({'label': self.label})\nif self.default_value is not None:\n pa... | <|body_start_0|>
AbstractModule.__init__(self, scripts=scripts, styles=styles)
self.button_label = button_label
self.label = label
self.default_value = default_value
<|end_body_0|>
<|body_start_1|>
params = {'button_label': self.button_label}
if self.label is not None:
... | Input Button module | AbstractInputButtonModule | [
"NIST-Software",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbstractInputButtonModule:
"""Input Button module"""
def __init__(self, scripts=list(), styles=list(), button_label='Send', label=None, default_value=None):
"""Initialize the module Args: scripts: styles: button_label: label: default_value:"""
<|body_0|>
def _render_modu... | stack_v2_sparse_classes_36k_train_009920 | 1,253 | permissive | [
{
"docstring": "Initialize the module Args: scripts: styles: button_label: label: default_value:",
"name": "__init__",
"signature": "def __init__(self, scripts=list(), styles=list(), button_label='Send', label=None, default_value=None)"
},
{
"docstring": "Return the module rendering Args: reques... | 2 | stack_v2_sparse_classes_30k_train_017461 | Implement the Python class `AbstractInputButtonModule` described below.
Class description:
Input Button module
Method signatures and docstrings:
- def __init__(self, scripts=list(), styles=list(), button_label='Send', label=None, default_value=None): Initialize the module Args: scripts: styles: button_label: label: d... | Implement the Python class `AbstractInputButtonModule` described below.
Class description:
Input Button module
Method signatures and docstrings:
- def __init__(self, scripts=list(), styles=list(), button_label='Send', label=None, default_value=None): Initialize the module Args: scripts: styles: button_label: label: d... | cef5e0f040c87e5fb224c59f90c314a6944e4d6b | <|skeleton|>
class AbstractInputButtonModule:
"""Input Button module"""
def __init__(self, scripts=list(), styles=list(), button_label='Send', label=None, default_value=None):
"""Initialize the module Args: scripts: styles: button_label: label: default_value:"""
<|body_0|>
def _render_modu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AbstractInputButtonModule:
"""Input Button module"""
def __init__(self, scripts=list(), styles=list(), button_label='Send', label=None, default_value=None):
"""Initialize the module Args: scripts: styles: button_label: label: default_value:"""
AbstractModule.__init__(self, scripts=scripts... | the_stack_v2_python_sparse | core_parser_app/tools/modules/views/builtin/input_button_module.py | usnistgov/core_parser_app | train | 0 |
d156937663b12c26df506b5478f43845b6c1ddd2 | [
"if self.raw_content is not None and self.normalized_content is None:\n return False\nreturn self.has_usual_file_name_extension",
"try:\n data = json.loads(self.raw_content.decode())\n return normalize_data(data)\nexcept (TypeError, ValueError):\n return None"
] | <|body_start_0|>
if self.raw_content is not None and self.normalized_content is None:
return False
return self.has_usual_file_name_extension
<|end_body_0|>
<|body_start_1|>
try:
data = json.loads(self.raw_content.decode())
return normalize_data(data)
... | A JSON file. | JsonFile | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JsonFile:
"""A JSON file."""
def matches_file_type(self) -> bool:
"""Whether the current instance is a static file of this type."""
<|body_0|>
def normalized_content(self) -> Union[bytes, None]:
"""The content of this static file normalized for this file type."""... | stack_v2_sparse_classes_36k_train_009921 | 927 | permissive | [
{
"docstring": "Whether the current instance is a static file of this type.",
"name": "matches_file_type",
"signature": "def matches_file_type(self) -> bool"
},
{
"docstring": "The content of this static file normalized for this file type.",
"name": "normalized_content",
"signature": "de... | 2 | null | Implement the Python class `JsonFile` described below.
Class description:
A JSON file.
Method signatures and docstrings:
- def matches_file_type(self) -> bool: Whether the current instance is a static file of this type.
- def normalized_content(self) -> Union[bytes, None]: The content of this static file normalized f... | Implement the Python class `JsonFile` described below.
Class description:
A JSON file.
Method signatures and docstrings:
- def matches_file_type(self) -> bool: Whether the current instance is a static file of this type.
- def normalized_content(self) -> Union[bytes, None]: The content of this static file normalized f... | d53433de80a10c02ca1a71c0fa47d371739a4859 | <|skeleton|>
class JsonFile:
"""A JSON file."""
def matches_file_type(self) -> bool:
"""Whether the current instance is a static file of this type."""
<|body_0|>
def normalized_content(self) -> Union[bytes, None]:
"""The content of this static file normalized for this file type."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JsonFile:
"""A JSON file."""
def matches_file_type(self) -> bool:
"""Whether the current instance is a static file of this type."""
if self.raw_content is not None and self.normalized_content is None:
return False
return self.has_usual_file_name_extension
def norm... | the_stack_v2_python_sparse | files/json_file.py | wichmannpas/VersionInferrer | train | 5 |
3d33c400deaf2760f9ba2154c6d194977b7d2eac | [
"self.Wz = np.random.normal(size=(i + h, h))\nself.Wr = np.random.normal(size=(i + h, h))\nself.Wh = np.random.normal(size=(i + h, h))\nself.Wy = np.random.normal(size=(h, o))\nself.bz = np.zeros((1, h))\nself.br = np.zeros((1, h))\nself.bh = np.zeros((1, h))\nself.by = np.zeros((1, o))",
"h_x = np.concatenate((h... | <|body_start_0|>
self.Wz = np.random.normal(size=(i + h, h))
self.Wr = np.random.normal(size=(i + h, h))
self.Wh = np.random.normal(size=(i + h, h))
self.Wy = np.random.normal(size=(h, o))
self.bz = np.zeros((1, h))
self.br = np.zeros((1, h))
self.bh = np.zeros((1... | [summary] | GRUCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GRUCell:
"""[summary]"""
def __init__(self, i, h, o):
"""[summary] Args: i ([type]): [description] h ([type]): [description] o ([type]): [description]"""
<|body_0|>
def forward(self, h_prev, x_t):
"""[summary] Args: h_prev ([type]): [description] x_t ([type]): [d... | stack_v2_sparse_classes_36k_train_009922 | 1,669 | no_license | [
{
"docstring": "[summary] Args: i ([type]): [description] h ([type]): [description] o ([type]): [description]",
"name": "__init__",
"signature": "def __init__(self, i, h, o)"
},
{
"docstring": "[summary] Args: h_prev ([type]): [description] x_t ([type]): [description] Returns: [type]: [descripti... | 2 | null | Implement the Python class `GRUCell` described below.
Class description:
[summary]
Method signatures and docstrings:
- def __init__(self, i, h, o): [summary] Args: i ([type]): [description] h ([type]): [description] o ([type]): [description]
- def forward(self, h_prev, x_t): [summary] Args: h_prev ([type]): [descript... | Implement the Python class `GRUCell` described below.
Class description:
[summary]
Method signatures and docstrings:
- def __init__(self, i, h, o): [summary] Args: i ([type]): [description] h ([type]): [description] o ([type]): [description]
- def forward(self, h_prev, x_t): [summary] Args: h_prev ([type]): [descript... | 5f86dee95f4d1c32014d0d74a368f342ff3ce6f7 | <|skeleton|>
class GRUCell:
"""[summary]"""
def __init__(self, i, h, o):
"""[summary] Args: i ([type]): [description] h ([type]): [description] o ([type]): [description]"""
<|body_0|>
def forward(self, h_prev, x_t):
"""[summary] Args: h_prev ([type]): [description] x_t ([type]): [d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GRUCell:
"""[summary]"""
def __init__(self, i, h, o):
"""[summary] Args: i ([type]): [description] h ([type]): [description] o ([type]): [description]"""
self.Wz = np.random.normal(size=(i + h, h))
self.Wr = np.random.normal(size=(i + h, h))
self.Wh = np.random.normal(size... | the_stack_v2_python_sparse | supervised_learning/0x0D-RNNs/2-gru_cell.py | d1sd41n/holbertonschool-machine_learning | train | 0 |
5a6cc692df3673b87d7e413000aa34bd74a54ad5 | [
"super().__init__()\nlogger.debug('Create PaddleCLSConnectionHandler to process the cls request')\nself._inputs = OrderedDict()\nself._outputs = OrderedDict()\nself.cls_engine = cls_engine\nself.executor = self.cls_engine.executor\nself._conf = self.executor._conf\nself._label_list = self.executor._label_list\nself... | <|body_start_0|>
super().__init__()
logger.debug('Create PaddleCLSConnectionHandler to process the cls request')
self._inputs = OrderedDict()
self._outputs = OrderedDict()
self.cls_engine = cls_engine
self.executor = self.cls_engine.executor
self._conf = self.exec... | PaddleCLSConnectionHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PaddleCLSConnectionHandler:
def __init__(self, cls_engine):
"""The PaddleSpeech CLS Server Connection Handler This connection process every cls server request Args: cls_engine (CLSEngine): The CLS engine"""
<|body_0|>
def run(self, audio_data):
"""engine run Args: au... | stack_v2_sparse_classes_36k_train_009923 | 7,010 | permissive | [
{
"docstring": "The PaddleSpeech CLS Server Connection Handler This connection process every cls server request Args: cls_engine (CLSEngine): The CLS engine",
"name": "__init__",
"signature": "def __init__(self, cls_engine)"
},
{
"docstring": "engine run Args: audio_data (bytes): base64.b64decod... | 3 | stack_v2_sparse_classes_30k_train_005273 | Implement the Python class `PaddleCLSConnectionHandler` described below.
Class description:
Implement the PaddleCLSConnectionHandler class.
Method signatures and docstrings:
- def __init__(self, cls_engine): The PaddleSpeech CLS Server Connection Handler This connection process every cls server request Args: cls_engi... | Implement the Python class `PaddleCLSConnectionHandler` described below.
Class description:
Implement the PaddleCLSConnectionHandler class.
Method signatures and docstrings:
- def __init__(self, cls_engine): The PaddleSpeech CLS Server Connection Handler This connection process every cls server request Args: cls_engi... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class PaddleCLSConnectionHandler:
def __init__(self, cls_engine):
"""The PaddleSpeech CLS Server Connection Handler This connection process every cls server request Args: cls_engine (CLSEngine): The CLS engine"""
<|body_0|>
def run(self, audio_data):
"""engine run Args: au... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PaddleCLSConnectionHandler:
def __init__(self, cls_engine):
"""The PaddleSpeech CLS Server Connection Handler This connection process every cls server request Args: cls_engine (CLSEngine): The CLS engine"""
super().__init__()
logger.debug('Create PaddleCLSConnectionHandler to process t... | the_stack_v2_python_sparse | paddlespeech/server/engine/cls/paddleinference/cls_engine.py | anniyanvr/DeepSpeech-1 | train | 0 | |
eb3c0f2cc282e00e0f28d20572ebcf4bb300bd44 | [
"super().__init__(hass, logger, ble_device.address, bluetooth.BluetoothScanningMode.ACTIVE, connectable)\nself.ble_device = ble_device\nself.device = device\nself.data: dict[str, Any] = {}\nself.device_name = device_name\nself.base_unique_id = base_unique_id\nself.model = model\nself._ready_event = asyncio.Event()"... | <|body_start_0|>
super().__init__(hass, logger, ble_device.address, bluetooth.BluetoothScanningMode.ACTIVE, connectable)
self.ble_device = ble_device
self.device = device
self.data: dict[str, Any] = {}
self.device_name = device_name
self.base_unique_id = base_unique_id
... | Class to manage fetching switchbot data. | SwitchbotDataUpdateCoordinator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SwitchbotDataUpdateCoordinator:
"""Class to manage fetching switchbot data."""
def __init__(self, hass: HomeAssistant, logger: logging.Logger, ble_device: BLEDevice, device: switchbot.SwitchbotDevice, base_unique_id: str, device_name: str, connectable: bool, model: str) -> None:
"""I... | stack_v2_sparse_classes_36k_train_009924 | 2,867 | permissive | [
{
"docstring": "Initialize global switchbot data updater.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, logger: logging.Logger, ble_device: BLEDevice, device: switchbot.SwitchbotDevice, base_unique_id: str, device_name: str, connectable: bool, model: str) -> None"
},
{
... | 3 | null | Implement the Python class `SwitchbotDataUpdateCoordinator` described below.
Class description:
Class to manage fetching switchbot data.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, logger: logging.Logger, ble_device: BLEDevice, device: switchbot.SwitchbotDevice, base_unique_id: str, de... | Implement the Python class `SwitchbotDataUpdateCoordinator` described below.
Class description:
Class to manage fetching switchbot data.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, logger: logging.Logger, ble_device: BLEDevice, device: switchbot.SwitchbotDevice, base_unique_id: str, de... | dcf68d768e4f628d038f1fdd6e40bad713fbc222 | <|skeleton|>
class SwitchbotDataUpdateCoordinator:
"""Class to manage fetching switchbot data."""
def __init__(self, hass: HomeAssistant, logger: logging.Logger, ble_device: BLEDevice, device: switchbot.SwitchbotDevice, base_unique_id: str, device_name: str, connectable: bool, model: str) -> None:
"""I... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SwitchbotDataUpdateCoordinator:
"""Class to manage fetching switchbot data."""
def __init__(self, hass: HomeAssistant, logger: logging.Logger, ble_device: BLEDevice, device: switchbot.SwitchbotDevice, base_unique_id: str, device_name: str, connectable: bool, model: str) -> None:
"""Initialize glo... | the_stack_v2_python_sparse | homeassistant/components/switchbot/coordinator.py | Adminiuga/home-assistant | train | 5 |
e52f61ccf821fec7130dfa09cb9073306f4bacb5 | [
"self.units = 32 if units is None else units\nself.num_layers = num_layers\nself.activation = activation\nself.dropout_layer = custom_layers.ConcreteDropout\nself.build_layers(input_shape, output_shape)",
"inputs, outputs = self.build_input(input_shape)\nfor power in range(1, self.num_layers):\n outputs = self... | <|body_start_0|>
self.units = 32 if units is None else units
self.num_layers = num_layers
self.activation = activation
self.dropout_layer = custom_layers.ConcreteDropout
self.build_layers(input_shape, output_shape)
<|end_body_0|>
<|body_start_1|>
inputs, outputs = self.b... | Extends keras.models.Model object. Implementation of stacked GRU topology for multivariate time series. :param input_shape: Shape of input example. :type input_shape: tuple :param output_shape: Shape of output consistent with loss function. :type output_shape: tuple :param units: Number of hidden units for each layer. ... | StackedGRU | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StackedGRU:
"""Extends keras.models.Model object. Implementation of stacked GRU topology for multivariate time series. :param input_shape: Shape of input example. :type input_shape: tuple :param output_shape: Shape of output consistent with loss function. :type output_shape: tuple :param units: N... | stack_v2_sparse_classes_36k_train_009925 | 7,749 | no_license | [
{
"docstring": "Initialize attributes.",
"name": "__init__",
"signature": "def __init__(self, input_shape, output_shape, units=32, num_layers=1, activation='relu')"
},
{
"docstring": "Build layers of the network. :param input_shape: Length and dimensionality of time series. :type input_shape: tu... | 5 | stack_v2_sparse_classes_30k_train_013201 | Implement the Python class `StackedGRU` described below.
Class description:
Extends keras.models.Model object. Implementation of stacked GRU topology for multivariate time series. :param input_shape: Shape of input example. :type input_shape: tuple :param output_shape: Shape of output consistent with loss function. :t... | Implement the Python class `StackedGRU` described below.
Class description:
Extends keras.models.Model object. Implementation of stacked GRU topology for multivariate time series. :param input_shape: Shape of input example. :type input_shape: tuple :param output_shape: Shape of output consistent with loss function. :t... | b6943406fa4a094b7dbe7fe7c5378f0116749f56 | <|skeleton|>
class StackedGRU:
"""Extends keras.models.Model object. Implementation of stacked GRU topology for multivariate time series. :param input_shape: Shape of input example. :type input_shape: tuple :param output_shape: Shape of output consistent with loss function. :type output_shape: tuple :param units: N... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StackedGRU:
"""Extends keras.models.Model object. Implementation of stacked GRU topology for multivariate time series. :param input_shape: Shape of input example. :type input_shape: tuple :param output_shape: Shape of output consistent with loss function. :type output_shape: tuple :param units: Number of hidd... | the_stack_v2_python_sparse | hybrid4cast/cnn/models.py | Aspriter/Hybrid4Cast | train | 1 |
cc7468515370e4a4845ed45bba1746e7a3b83941 | [
"super().__init__()\nself.config = params\ntry:\n self.my_device = self.config['my_device']\nexcept:\n self.my_device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n'\\n NV uses padding = \"same\" to preserve the input and output size of conv.\\n We can do the same as follows:... | <|body_start_0|>
super().__init__()
self.config = params
try:
self.my_device = self.config['my_device']
except:
self.my_device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
'\n NV uses padding = "same" to preserve the input and ou... | Implement the architecture from Nielsen and Voigt (2018) | NVCNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NVCNN:
"""Implement the architecture from Nielsen and Voigt (2018)"""
def __init__(self, params):
"""Params are: vocab_size: the number of dimensions in the 1-hot encoding lr: learning rate filter_number: number of filters (in NV, 1-512) filter_len: length of filters (in NV, 1-48) nu... | stack_v2_sparse_classes_36k_train_009926 | 34,560 | no_license | [
{
"docstring": "Params are: vocab_size: the number of dimensions in the 1-hot encoding lr: learning rate filter_number: number of filters (in NV, 1-512) filter_len: length of filters (in NV, 1-48) num_dense_nodes: size of dense layer after filters input_len: length of input (batch_size, vocab_size, input_len) n... | 2 | stack_v2_sparse_classes_30k_train_010025 | Implement the Python class `NVCNN` described below.
Class description:
Implement the architecture from Nielsen and Voigt (2018)
Method signatures and docstrings:
- def __init__(self, params): Params are: vocab_size: the number of dimensions in the 1-hot encoding lr: learning rate filter_number: number of filters (in ... | Implement the Python class `NVCNN` described below.
Class description:
Implement the architecture from Nielsen and Voigt (2018)
Method signatures and docstrings:
- def __init__(self, params): Params are: vocab_size: the number of dimensions in the 1-hot encoding lr: learning rate filter_number: number of filters (in ... | b850f7c91e16e3dacca4d3b6377c77502960dd19 | <|skeleton|>
class NVCNN:
"""Implement the architecture from Nielsen and Voigt (2018)"""
def __init__(self, params):
"""Params are: vocab_size: the number of dimensions in the 1-hot encoding lr: learning rate filter_number: number of filters (in NV, 1-512) filter_len: length of filters (in NV, 1-48) nu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NVCNN:
"""Implement the architecture from Nielsen and Voigt (2018)"""
def __init__(self, params):
"""Params are: vocab_size: the number of dimensions in the 1-hot encoding lr: learning rate filter_number: number of filters (in NV, 1-512) filter_len: length of filters (in NV, 1-48) num_dense_nodes... | the_stack_v2_python_sparse | common/mytorch.py | altLabs/attrib | train | 1 |
595ac2335a12fea6bebd10d78e7365622c61beb4 | [
"if not value:\n return []\nreturn [v.strip() for v in value.split() if v != '']",
"super().validate(value)\ntry:\n for email in value:\n validate_email(email)\nexcept ValidationError:\n raise ValidationError(self.message, code=self.code)"
] | <|body_start_0|>
if not value:
return []
return [v.strip() for v in value.split() if v != '']
<|end_body_0|>
<|body_start_1|>
super().validate(value)
try:
for email in value:
validate_email(email)
except ValidationError:
raise ... | MultiEmailField | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiEmailField:
def to_python(self, value):
"""Normalize data to a list of strings."""
<|body_0|>
def validate(self, value):
"""Check if value consists only of valid emails."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not value:
... | stack_v2_sparse_classes_36k_train_009927 | 1,497 | permissive | [
{
"docstring": "Normalize data to a list of strings.",
"name": "to_python",
"signature": "def to_python(self, value)"
},
{
"docstring": "Check if value consists only of valid emails.",
"name": "validate",
"signature": "def validate(self, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011101 | Implement the Python class `MultiEmailField` described below.
Class description:
Implement the MultiEmailField class.
Method signatures and docstrings:
- def to_python(self, value): Normalize data to a list of strings.
- def validate(self, value): Check if value consists only of valid emails. | Implement the Python class `MultiEmailField` described below.
Class description:
Implement the MultiEmailField class.
Method signatures and docstrings:
- def to_python(self, value): Normalize data to a list of strings.
- def validate(self, value): Check if value consists only of valid emails.
<|skeleton|>
class Mult... | de532aee33b03f9b580404dbf273713b12bd6275 | <|skeleton|>
class MultiEmailField:
def to_python(self, value):
"""Normalize data to a list of strings."""
<|body_0|>
def validate(self, value):
"""Check if value consists only of valid emails."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiEmailField:
def to_python(self, value):
"""Normalize data to a list of strings."""
if not value:
return []
return [v.strip() for v in value.split() if v != '']
def validate(self, value):
"""Check if value consists only of valid emails."""
super().v... | the_stack_v2_python_sparse | src/easydmp/invitation/forms.py | hmpf/easydmp | train | 8 | |
c7fd7be7562f1485033aec56b3526a91f60cfe9d | [
"try:\n o = FileComment.objects.get(pk=pk)\nexcept FileComment.DoesNotExist:\n return api_error(status.HTTP_400_BAD_REQUEST, 'Wrong comment id')\ntry:\n avatar_size = int(request.GET.get('avatar_size', AVATAR_DEFAULT_SIZE))\nexcept ValueError:\n avatar_size = AVATAR_DEFAULT_SIZE\ncomment = o.to_dict()\n... | <|body_start_0|>
try:
o = FileComment.objects.get(pk=pk)
except FileComment.DoesNotExist:
return api_error(status.HTTP_400_BAD_REQUEST, 'Wrong comment id')
try:
avatar_size = int(request.GET.get('avatar_size', AVATAR_DEFAULT_SIZE))
except ValueError:
... | FileCommentView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileCommentView:
def get(self, request, repo_id, pk, format=None):
"""Get a comment."""
<|body_0|>
def delete(self, request, repo_id, pk, format=None):
"""Delete a comment, only comment author or repo owner can perform this op."""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_36k_train_009928 | 2,197 | permissive | [
{
"docstring": "Get a comment.",
"name": "get",
"signature": "def get(self, request, repo_id, pk, format=None)"
},
{
"docstring": "Delete a comment, only comment author or repo owner can perform this op.",
"name": "delete",
"signature": "def delete(self, request, repo_id, pk, format=None... | 2 | null | Implement the Python class `FileCommentView` described below.
Class description:
Implement the FileCommentView class.
Method signatures and docstrings:
- def get(self, request, repo_id, pk, format=None): Get a comment.
- def delete(self, request, repo_id, pk, format=None): Delete a comment, only comment author or rep... | Implement the Python class `FileCommentView` described below.
Class description:
Implement the FileCommentView class.
Method signatures and docstrings:
- def get(self, request, repo_id, pk, format=None): Get a comment.
- def delete(self, request, repo_id, pk, format=None): Delete a comment, only comment author or rep... | 13b3ed26a04248211ef91ca70dccc617be27a3c3 | <|skeleton|>
class FileCommentView:
def get(self, request, repo_id, pk, format=None):
"""Get a comment."""
<|body_0|>
def delete(self, request, repo_id, pk, format=None):
"""Delete a comment, only comment author or repo owner can perform this op."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileCommentView:
def get(self, request, repo_id, pk, format=None):
"""Get a comment."""
try:
o = FileComment.objects.get(pk=pk)
except FileComment.DoesNotExist:
return api_error(status.HTTP_400_BAD_REQUEST, 'Wrong comment id')
try:
avatar_siz... | the_stack_v2_python_sparse | fhs/usr/share/python/syncwerk/restapi/restapi/api2/endpoints/file_comment.py | syncwerk/syncwerk-server-restapi | train | 0 | |
de7fb2c5e0719a9fc330fe052c0d84a9e807c467 | [
"self.counts = pd.read_csv(counts, index_col=0, engine='c')\nself.meta = pd.read_csv(meta, index_col=0, engine='c')\nself.group_by = group_by",
"groups = self.meta[self.group_by].unique()\nif gene not in self.counts.index:\n return None\nres = {}\nfor group in groups:\n idx = self.meta.loc[self.meta[self.gr... | <|body_start_0|>
self.counts = pd.read_csv(counts, index_col=0, engine='c')
self.meta = pd.read_csv(meta, index_col=0, engine='c')
self.group_by = group_by
<|end_body_0|>
<|body_start_1|>
groups = self.meta[self.group_by].unique()
if gene not in self.counts.index:
re... | read gene expression and meta info | GeneExpression | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeneExpression:
"""read gene expression and meta info"""
def __init__(self, counts: str, meta: str, group_by='res.0.6'):
"""read data :param counts: :param meta: :param group_by:"""
<|body_0|>
def get_gene_exp(self, gene):
"""get gene expression :param gene: :par... | stack_v2_sparse_classes_36k_train_009929 | 18,577 | no_license | [
{
"docstring": "read data :param counts: :param meta: :param group_by:",
"name": "__init__",
"signature": "def __init__(self, counts: str, meta: str, group_by='res.0.6')"
},
{
"docstring": "get gene expression :param gene: :param group: :return:",
"name": "get_gene_exp",
"signature": "de... | 3 | stack_v2_sparse_classes_30k_train_001939 | Implement the Python class `GeneExpression` described below.
Class description:
read gene expression and meta info
Method signatures and docstrings:
- def __init__(self, counts: str, meta: str, group_by='res.0.6'): read data :param counts: :param meta: :param group_by:
- def get_gene_exp(self, gene): get gene express... | Implement the Python class `GeneExpression` described below.
Class description:
read gene expression and meta info
Method signatures and docstrings:
- def __init__(self, counts: str, meta: str, group_by='res.0.6'): read data :param counts: :param meta: :param group_by:
- def get_gene_exp(self, gene): get gene express... | e81713687f9e14d39f9e1d531c7fe1db14cab7a4 | <|skeleton|>
class GeneExpression:
"""read gene expression and meta info"""
def __init__(self, counts: str, meta: str, group_by='res.0.6'):
"""read data :param counts: :param meta: :param group_by:"""
<|body_0|>
def get_gene_exp(self, gene):
"""get gene expression :param gene: :par... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GeneExpression:
"""read gene expression and meta info"""
def __init__(self, counts: str, meta: str, group_by='res.0.6'):
"""read data :param counts: :param meta: :param group_by:"""
self.counts = pd.read_csv(counts, index_col=0, engine='c')
self.meta = pd.read_csv(meta, index_col=... | the_stack_v2_python_sparse | bak/4_gene_signature/make_line_plot_of_module.py | Chenmengpin/inferCC | train | 0 |
439a37d3e02980619da9eebb12f230f283609193 | [
"nums.sort()\nmin_diff = float('inf')\nmin_sum = None\nfor i in range(len(nums) - 2):\n j = i + 1\n k = len(nums) - 1\n while j < k:\n cur_sum = nums[i] + nums[j] + nums[k]\n diff = abs(target - cur_sum)\n if diff < min_diff:\n min_diff = diff\n min_sum = cur_sum\... | <|body_start_0|>
nums.sort()
min_diff = float('inf')
min_sum = None
for i in range(len(nums) - 2):
j = i + 1
k = len(nums) - 1
while j < k:
cur_sum = nums[i] + nums[j] + nums[k]
diff = abs(target - cur_sum)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
"""08/19/2021 12:26 Time Complexity: O(n^2) Space Complexity: O(1)"""
<|body_0|>
def threeSumClosest(self, nums: List[int], target: int) -> int:
"""10/21/2022 20:30 Time Complexity: O(n^2*logn)... | stack_v2_sparse_classes_36k_train_009930 | 2,723 | no_license | [
{
"docstring": "08/19/2021 12:26 Time Complexity: O(n^2) Space Complexity: O(1)",
"name": "threeSumClosest",
"signature": "def threeSumClosest(self, nums: List[int], target: int) -> int"
},
{
"docstring": "10/21/2022 20:30 Time Complexity: O(n^2*logn) Space Complexity: O(1)",
"name": "threeS... | 2 | stack_v2_sparse_classes_30k_train_015715 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSumClosest(self, nums: List[int], target: int) -> int: 08/19/2021 12:26 Time Complexity: O(n^2) Space Complexity: O(1)
- def threeSumClosest(self, nums: List[int], targe... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSumClosest(self, nums: List[int], target: int) -> int: 08/19/2021 12:26 Time Complexity: O(n^2) Space Complexity: O(1)
- def threeSumClosest(self, nums: List[int], targe... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
"""08/19/2021 12:26 Time Complexity: O(n^2) Space Complexity: O(1)"""
<|body_0|>
def threeSumClosest(self, nums: List[int], target: int) -> int:
"""10/21/2022 20:30 Time Complexity: O(n^2*logn)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
"""08/19/2021 12:26 Time Complexity: O(n^2) Space Complexity: O(1)"""
nums.sort()
min_diff = float('inf')
min_sum = None
for i in range(len(nums) - 2):
j = i + 1
k = len(nu... | the_stack_v2_python_sparse | leetcode/solved/16_3Sum_Closest/solution.py | sungminoh/algorithms | train | 0 | |
0b772ae26adb72fcc8fa72cc959cb9e9a6826d8f | [
"post_body = {'service_id': service_id, 'region': region_id, 'publicurl': kwargs.get('publicurl'), 'adminurl': kwargs.get('adminurl'), 'internalurl': kwargs.get('internalurl')}\npost_body = json.dumps({'endpoint': post_body})\nresp, body = self.post('/endpoints', post_body)\nself.expected_success(200, resp.status)\... | <|body_start_0|>
post_body = {'service_id': service_id, 'region': region_id, 'publicurl': kwargs.get('publicurl'), 'adminurl': kwargs.get('adminurl'), 'internalurl': kwargs.get('internalurl')}
post_body = json.dumps({'endpoint': post_body})
resp, body = self.post('/endpoints', post_body)
... | EndpointsClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EndpointsClient:
def create_endpoint(self, service_id, region_id, **kwargs):
"""Create an endpoint for service."""
<|body_0|>
def list_endpoints(self):
"""List Endpoints - Returns Endpoints."""
<|body_1|>
def delete_endpoint(self, endpoint_id):
"... | stack_v2_sparse_classes_36k_train_009931 | 1,870 | permissive | [
{
"docstring": "Create an endpoint for service.",
"name": "create_endpoint",
"signature": "def create_endpoint(self, service_id, region_id, **kwargs)"
},
{
"docstring": "List Endpoints - Returns Endpoints.",
"name": "list_endpoints",
"signature": "def list_endpoints(self)"
},
{
"... | 3 | stack_v2_sparse_classes_30k_test_001115 | Implement the Python class `EndpointsClient` described below.
Class description:
Implement the EndpointsClient class.
Method signatures and docstrings:
- def create_endpoint(self, service_id, region_id, **kwargs): Create an endpoint for service.
- def list_endpoints(self): List Endpoints - Returns Endpoints.
- def de... | Implement the Python class `EndpointsClient` described below.
Class description:
Implement the EndpointsClient class.
Method signatures and docstrings:
- def create_endpoint(self, service_id, region_id, **kwargs): Create an endpoint for service.
- def list_endpoints(self): List Endpoints - Returns Endpoints.
- def de... | 78c71b3bc74144ee5d2a77707d7f195b96ad09b4 | <|skeleton|>
class EndpointsClient:
def create_endpoint(self, service_id, region_id, **kwargs):
"""Create an endpoint for service."""
<|body_0|>
def list_endpoints(self):
"""List Endpoints - Returns Endpoints."""
<|body_1|>
def delete_endpoint(self, endpoint_id):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EndpointsClient:
def create_endpoint(self, service_id, region_id, **kwargs):
"""Create an endpoint for service."""
post_body = {'service_id': service_id, 'region': region_id, 'publicurl': kwargs.get('publicurl'), 'adminurl': kwargs.get('adminurl'), 'internalurl': kwargs.get('internalurl')}
... | the_stack_v2_python_sparse | tempest/services/identity/v2/json/endpoints_client.py | microsoft/LIS-Tempest | train | 1 | |
a0d465e69f3bc97209e2bc3e56f12378e27eacf9 | [
"self.model_type = model_type\nself.batch_size = batch_size\nself.save_dir = save_dir\nif model_type == 'resnet':\n m = models.resnet152(pretrained=True)\n self.features = nn.Sequential(*[mod for n, mod in m._modules.items() if n not in ['avgpool', 'fc']])\nelif model_type == 'densenet':\n m = models.dense... | <|body_start_0|>
self.model_type = model_type
self.batch_size = batch_size
self.save_dir = save_dir
if model_type == 'resnet':
m = models.resnet152(pretrained=True)
self.features = nn.Sequential(*[mod for n, mod in m._modules.items() if n not in ['avgpool', 'fc']]... | Image Featurizer. | ImgFeaturizer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImgFeaturizer:
"""Image Featurizer."""
def __init__(self, model_type, batch_size, save_dir):
"""Initialize ImgFeatureizer. Args ---- batch_size : int, batch size for data loader. save_dir : string, path to directory for saving img features."""
<|body_0|>
def transform(se... | stack_v2_sparse_classes_36k_train_009932 | 2,563 | no_license | [
{
"docstring": "Initialize ImgFeatureizer. Args ---- batch_size : int, batch size for data loader. save_dir : string, path to directory for saving img features.",
"name": "__init__",
"signature": "def __init__(self, model_type, batch_size, save_dir)"
},
{
"docstring": "Transform imgs to features... | 2 | stack_v2_sparse_classes_30k_train_005841 | Implement the Python class `ImgFeaturizer` described below.
Class description:
Image Featurizer.
Method signatures and docstrings:
- def __init__(self, model_type, batch_size, save_dir): Initialize ImgFeatureizer. Args ---- batch_size : int, batch size for data loader. save_dir : string, path to directory for saving ... | Implement the Python class `ImgFeaturizer` described below.
Class description:
Image Featurizer.
Method signatures and docstrings:
- def __init__(self, model_type, batch_size, save_dir): Initialize ImgFeatureizer. Args ---- batch_size : int, batch size for data loader. save_dir : string, path to directory for saving ... | fbfa1766dbc52cbf39036abe1a44f9315fad4a5c | <|skeleton|>
class ImgFeaturizer:
"""Image Featurizer."""
def __init__(self, model_type, batch_size, save_dir):
"""Initialize ImgFeatureizer. Args ---- batch_size : int, batch size for data loader. save_dir : string, path to directory for saving img features."""
<|body_0|>
def transform(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImgFeaturizer:
"""Image Featurizer."""
def __init__(self, model_type, batch_size, save_dir):
"""Initialize ImgFeatureizer. Args ---- batch_size : int, batch size for data loader. save_dir : string, path to directory for saving img features."""
self.model_type = model_type
self.bat... | the_stack_v2_python_sparse | preprocessing/img_featurizer.py | estebandito22/MC-BERT | train | 0 |
a2e473a33161d2eda5bd4828e935c763f80655eb | [
"self.metadata_fields = []\nrecord_count = len(hdf5_file[self.time_field])\nobj_paths = []\nhdf5_file.visit(obj_paths.append)\nfor obj_path in obj_paths:\n obj = hdf5_file[obj_path]\n if isinstance(obj, h5py.Dataset):\n if obj_path not in self.state_vector_fields and obj_path != self.time_field and (le... | <|body_start_0|>
self.metadata_fields = []
record_count = len(hdf5_file[self.time_field])
obj_paths = []
hdf5_file.visit(obj_paths.append)
for obj_path in obj_paths:
obj = hdf5_file[obj_path]
if isinstance(obj, h5py.Dataset):
if obj_path no... | _HDF5Reader | [
"LicenseRef-scancode-proprietary-license",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"Python-2.0",
"LicenseRef-scancode-secret-labs-2011"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _HDF5Reader:
def _discover_metadata_fields(self, hdf5_file):
"""Recurse through all objects in a file and treat any dataset with the same number of records as a valid metadata field path, excluding datasets that are already specified for state values. Parameters ---------- hdf5_file : :c... | stack_v2_sparse_classes_36k_train_009933 | 9,184 | permissive | [
{
"docstring": "Recurse through all objects in a file and treat any dataset with the same number of records as a valid metadata field path, excluding datasets that are already specified for state values. Parameters ---------- hdf5_file : :class:`h5py.File` The HDF5 file to walk through",
"name": "_discover_... | 3 | stack_v2_sparse_classes_30k_train_007249 | Implement the Python class `_HDF5Reader` described below.
Class description:
Implement the _HDF5Reader class.
Method signatures and docstrings:
- def _discover_metadata_fields(self, hdf5_file): Recurse through all objects in a file and treat any dataset with the same number of records as a valid metadata field path, ... | Implement the Python class `_HDF5Reader` described below.
Class description:
Implement the _HDF5Reader class.
Method signatures and docstrings:
- def _discover_metadata_fields(self, hdf5_file): Recurse through all objects in a file and treat any dataset with the same number of records as a valid metadata field path, ... | f24090cc919b3b590b84f965a3884ed1293d181d | <|skeleton|>
class _HDF5Reader:
def _discover_metadata_fields(self, hdf5_file):
"""Recurse through all objects in a file and treat any dataset with the same number of records as a valid metadata field path, excluding datasets that are already specified for state values. Parameters ---------- hdf5_file : :c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _HDF5Reader:
def _discover_metadata_fields(self, hdf5_file):
"""Recurse through all objects in a file and treat any dataset with the same number of records as a valid metadata field path, excluding datasets that are already specified for state values. Parameters ---------- hdf5_file : :class:`h5py.Fil... | the_stack_v2_python_sparse | stonesoup/reader/hdf5.py | dstl/Stone-Soup | train | 315 | |
335cc1d3bc8a545f6243680c932316d2ffb2c25e | [
"self.comm = driver.comm\nself.model = driver.model\nself.driver = driver\nself._iteration = 0\nself._x_dict = None\nself._funcs = None\nself._sens = None\nself.write_designs = write_designs\nif write_designs:\n self._design_folder = os.path.join(os.getcwd(), 'design')\n if not os.path.exists(self._design_fol... | <|body_start_0|>
self.comm = driver.comm
self.model = driver.model
self.driver = driver
self._iteration = 0
self._x_dict = None
self._funcs = None
self._sens = None
self.write_designs = write_designs
if write_designs:
self._design_folde... | Manages the pyoptsparse opimization problems with funtofem drivers as well as oneway coupled tacs drivers Requires only a pre-built funtofem model and driver, coupled or oneway-coupled Performs a gatekeeper feature to prevent double-running the forward analysis | OptimizationManager | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptimizationManager:
"""Manages the pyoptsparse opimization problems with funtofem drivers as well as oneway coupled tacs drivers Requires only a pre-built funtofem model and driver, coupled or oneway-coupled Performs a gatekeeper feature to prevent double-running the forward analysis"""
def... | stack_v2_sparse_classes_36k_train_009934 | 6,156 | permissive | [
{
"docstring": "Constructs the optimization manager class using a funtofem model and driver Parameters -------------- driver : any driver coupled or oneway coupled, must have solve_forward and solve_adjoint methods",
"name": "__init__",
"signature": "def __init__(self, driver, write_designs: bool=True, ... | 6 | stack_v2_sparse_classes_30k_train_006372 | Implement the Python class `OptimizationManager` described below.
Class description:
Manages the pyoptsparse opimization problems with funtofem drivers as well as oneway coupled tacs drivers Requires only a pre-built funtofem model and driver, coupled or oneway-coupled Performs a gatekeeper feature to prevent double-r... | Implement the Python class `OptimizationManager` described below.
Class description:
Manages the pyoptsparse opimization problems with funtofem drivers as well as oneway coupled tacs drivers Requires only a pre-built funtofem model and driver, coupled or oneway-coupled Performs a gatekeeper feature to prevent double-r... | 4c11b61397100f9d8b455f7d20cf3b507a15c1e9 | <|skeleton|>
class OptimizationManager:
"""Manages the pyoptsparse opimization problems with funtofem drivers as well as oneway coupled tacs drivers Requires only a pre-built funtofem model and driver, coupled or oneway-coupled Performs a gatekeeper feature to prevent double-running the forward analysis"""
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OptimizationManager:
"""Manages the pyoptsparse opimization problems with funtofem drivers as well as oneway coupled tacs drivers Requires only a pre-built funtofem model and driver, coupled or oneway-coupled Performs a gatekeeper feature to prevent double-running the forward analysis"""
def __init__(sel... | the_stack_v2_python_sparse | funtofem/optimization/optimization_manager.py | gjkennedy/funtofem | train | 0 |
ed41bfc5515008d62eee2b4e11ec55f39c8710c4 | [
"form = ServerForm()\nlist_server = Server.objects.all()\noutput = {'form': form, 'list_server': list_server}\nreturn render(request, self.template_name, output)",
"form = ServerForm(request.POST)\nif form.is_valid():\n form.save()\n return HttpResponseRedirect('/')\noutput = {'form': form, 'messages': 'Rev... | <|body_start_0|>
form = ServerForm()
list_server = Server.objects.all()
output = {'form': form, 'list_server': list_server}
return render(request, self.template_name, output)
<|end_body_0|>
<|body_start_1|>
form = ServerForm(request.POST)
if form.is_valid():
... | Clase para crear un servidor | ServerNewView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServerNewView:
"""Clase para crear un servidor"""
def get(self, request, *args, **kwargs):
"""Método get"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Método post"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
form = ServerForm()
... | stack_v2_sparse_classes_36k_train_009935 | 22,221 | no_license | [
{
"docstring": "Método get",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Método post",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_val_001082 | Implement the Python class `ServerNewView` described below.
Class description:
Clase para crear un servidor
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Método get
- def post(self, request, *args, **kwargs): Método post | Implement the Python class `ServerNewView` described below.
Class description:
Clase para crear un servidor
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Método get
- def post(self, request, *args, **kwargs): Método post
<|skeleton|>
class ServerNewView:
"""Clase para crear un serv... | e28e2d968372609ad396c42fb572a00c2410a117 | <|skeleton|>
class ServerNewView:
"""Clase para crear un servidor"""
def get(self, request, *args, **kwargs):
"""Método get"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Método post"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ServerNewView:
"""Clase para crear un servidor"""
def get(self, request, *args, **kwargs):
"""Método get"""
form = ServerForm()
list_server = Server.objects.all()
output = {'form': form, 'list_server': list_server}
return render(request, self.template_name, output)... | the_stack_v2_python_sparse | list/views.py | damaos/server_list2 | train | 0 |
3667aa5cec6bbab2d040f4484ac3839be9397ce7 | [
"super(DGCNNCls, self).__init__()\nself.cfg = cfg\nself.k = cfg.get('k')\nself.emb_dims = cfg.get('emb_dims')\nself.dropout = cfg.get('dropout', 0.5)\nself.bn1 = nn.BatchNorm2d(64)\nself.bn2 = nn.BatchNorm2d(64)\nself.bn3 = nn.BatchNorm2d(128)\nself.bn4 = nn.BatchNorm2d(256)\nself.bn5 = nn.BatchNorm1d(self.emb_dims... | <|body_start_0|>
super(DGCNNCls, self).__init__()
self.cfg = cfg
self.k = cfg.get('k')
self.emb_dims = cfg.get('emb_dims')
self.dropout = cfg.get('dropout', 0.5)
self.bn1 = nn.BatchNorm2d(64)
self.bn2 = nn.BatchNorm2d(64)
self.bn3 = nn.BatchNorm2d(128)
... | DGCNNCls | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DGCNNCls:
def __init__(self, cfg, output_channels=40):
"""Author: shi.xian dgcnn classification network Args: k (int): [Num of nearest neighbors] emb_dims (int): [Dimension of embeddings] dropout (List[int], optional): [layers to apply dropout]"""
<|body_0|>
def forward(self... | stack_v2_sparse_classes_36k_train_009936 | 4,296 | permissive | [
{
"docstring": "Author: shi.xian dgcnn classification network Args: k (int): [Num of nearest neighbors] emb_dims (int): [Dimension of embeddings] dropout (List[int], optional): [layers to apply dropout]",
"name": "__init__",
"signature": "def __init__(self, cfg, output_channels=40)"
},
{
"docstr... | 2 | stack_v2_sparse_classes_30k_train_007735 | Implement the Python class `DGCNNCls` described below.
Class description:
Implement the DGCNNCls class.
Method signatures and docstrings:
- def __init__(self, cfg, output_channels=40): Author: shi.xian dgcnn classification network Args: k (int): [Num of nearest neighbors] emb_dims (int): [Dimension of embeddings] dro... | Implement the Python class `DGCNNCls` described below.
Class description:
Implement the DGCNNCls class.
Method signatures and docstrings:
- def __init__(self, cfg, output_channels=40): Author: shi.xian dgcnn classification network Args: k (int): [Num of nearest neighbors] emb_dims (int): [Dimension of embeddings] dro... | 9987806185a4e1619bc15ceecb8a1755e764ff68 | <|skeleton|>
class DGCNNCls:
def __init__(self, cfg, output_channels=40):
"""Author: shi.xian dgcnn classification network Args: k (int): [Num of nearest neighbors] emb_dims (int): [Dimension of embeddings] dropout (List[int], optional): [layers to apply dropout]"""
<|body_0|>
def forward(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DGCNNCls:
def __init__(self, cfg, output_channels=40):
"""Author: shi.xian dgcnn classification network Args: k (int): [Num of nearest neighbors] emb_dims (int): [Dimension of embeddings] dropout (List[int], optional): [layers to apply dropout]"""
super(DGCNNCls, self).__init__()
self.... | the_stack_v2_python_sparse | gorilla3d/nn/models/dgcnn/dgcnn_cls.py | SijanNeupane49/gorilla-3d | train | 0 | |
d39e17a393aa6fdc344046ef8159f4dd631d9f2d | [
"if status == 'CANCELLED' and (not cancel_reason):\n raise ILLError('You have to provide a cancel reason when cancelling a request')\nif cancel_reason and (not status == 'CANCELLED'):\n raise ILLError('If you select a cancel reason you need to select \"Cancelled\" in the state')",
"Document = current_app_il... | <|body_start_0|>
if status == 'CANCELLED' and (not cancel_reason):
raise ILLError('You have to provide a cancel reason when cancelling a request')
if cancel_reason and (not status == 'CANCELLED'):
raise ILLError('If you select a cancel reason you need to select "Cancelled" in the... | Ill record validator. | IllValidator | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IllValidator:
"""Ill record validator."""
def validate_cancel(self, status, cancel_reason):
"""Validate decline is correct."""
<|body_0|>
def ensure_document_exists(self, document_pid):
"""Ensure document exists or raise."""
<|body_1|>
def ensure_pat... | stack_v2_sparse_classes_36k_train_009937 | 13,301 | permissive | [
{
"docstring": "Validate decline is correct.",
"name": "validate_cancel",
"signature": "def validate_cancel(self, status, cancel_reason)"
},
{
"docstring": "Ensure document exists or raise.",
"name": "ensure_document_exists",
"signature": "def ensure_document_exists(self, document_pid)"
... | 5 | stack_v2_sparse_classes_30k_train_018700 | Implement the Python class `IllValidator` described below.
Class description:
Ill record validator.
Method signatures and docstrings:
- def validate_cancel(self, status, cancel_reason): Validate decline is correct.
- def ensure_document_exists(self, document_pid): Ensure document exists or raise.
- def ensure_patron_... | Implement the Python class `IllValidator` described below.
Class description:
Ill record validator.
Method signatures and docstrings:
- def validate_cancel(self, status, cancel_reason): Validate decline is correct.
- def ensure_document_exists(self, document_pid): Ensure document exists or raise.
- def ensure_patron_... | 1c36526e85510100c5f64059518d1b716d87ac10 | <|skeleton|>
class IllValidator:
"""Ill record validator."""
def validate_cancel(self, status, cancel_reason):
"""Validate decline is correct."""
<|body_0|>
def ensure_document_exists(self, document_pid):
"""Ensure document exists or raise."""
<|body_1|>
def ensure_pat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IllValidator:
"""Ill record validator."""
def validate_cancel(self, status, cancel_reason):
"""Validate decline is correct."""
if status == 'CANCELLED' and (not cancel_reason):
raise ILLError('You have to provide a cancel reason when cancelling a request')
if cancel_re... | the_stack_v2_python_sparse | invenio_app_ils/ill/api.py | inveniosoftware/invenio-app-ils | train | 64 |
1519d9153d90ba4c14bc16d7d896605384114721 | [
"res = {}\nres['retcode'] = e.code\nres['retmsg'] = e.message\nres.update(e.ext)\nreturn res",
"res = {}\nres['retcode'] = BaseError.SUCCESS\nres['retmsg'] = BaseError.get_message(res['retcode'])\nres['retdata'] = data if data is not None else {}\nreturn res"
] | <|body_start_0|>
res = {}
res['retcode'] = e.code
res['retmsg'] = e.message
res.update(e.ext)
return res
<|end_body_0|>
<|body_start_1|>
res = {}
res['retcode'] = BaseError.SUCCESS
res['retmsg'] = BaseError.get_message(res['retcode'])
res['retdata... | 响应 | ResponseBuilder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResponseBuilder:
"""响应"""
def build_error(handler, e):
"""返回错误 Args: handler: torndb.web.RequestHandler object e: An instance of UFOException Returns: A json string"""
<|body_0|>
def build_success(handler, data=None):
"""返回成功 Args: handler: torndb.web.RequestHand... | stack_v2_sparse_classes_36k_train_009938 | 1,250 | no_license | [
{
"docstring": "返回错误 Args: handler: torndb.web.RequestHandler object e: An instance of UFOException Returns: A json string",
"name": "build_error",
"signature": "def build_error(handler, e)"
},
{
"docstring": "返回成功 Args: handler: torndb.web.RequestHandler object data: data returned by processor ... | 2 | stack_v2_sparse_classes_30k_train_019598 | Implement the Python class `ResponseBuilder` described below.
Class description:
响应
Method signatures and docstrings:
- def build_error(handler, e): 返回错误 Args: handler: torndb.web.RequestHandler object e: An instance of UFOException Returns: A json string
- def build_success(handler, data=None): 返回成功 Args: handler: t... | Implement the Python class `ResponseBuilder` described below.
Class description:
响应
Method signatures and docstrings:
- def build_error(handler, e): 返回错误 Args: handler: torndb.web.RequestHandler object e: An instance of UFOException Returns: A json string
- def build_success(handler, data=None): 返回成功 Args: handler: t... | d520316d773ee14e7db25d2da56e4a19e52f8821 | <|skeleton|>
class ResponseBuilder:
"""响应"""
def build_error(handler, e):
"""返回错误 Args: handler: torndb.web.RequestHandler object e: An instance of UFOException Returns: A json string"""
<|body_0|>
def build_success(handler, data=None):
"""返回成功 Args: handler: torndb.web.RequestHand... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResponseBuilder:
"""响应"""
def build_error(handler, e):
"""返回错误 Args: handler: torndb.web.RequestHandler object e: An instance of UFOException Returns: A json string"""
res = {}
res['retcode'] = e.code
res['retmsg'] = e.message
res.update(e.ext)
return res
... | the_stack_v2_python_sparse | utils/protocol_utils.py | zikkinbun/s2s | train | 0 |
eb0acf0cd12c4616c27329221ee9b286456240bd | [
"morning_weather = self._parse_weather_info('Утро')\nday_weather = self._parse_weather_info('День')\nevening_weather = self._parse_weather_info('Вечер')\nnight_weather = self._parse_weather_info('Ночь')\nreturn 'Погода в Новосибирске сегодня такая\\n{0}{1}{2}{3}'.format(morning_weather, day_weather, evening_weather... | <|body_start_0|>
morning_weather = self._parse_weather_info('Утро')
day_weather = self._parse_weather_info('День')
evening_weather = self._parse_weather_info('Вечер')
night_weather = self._parse_weather_info('Ночь')
return 'Погода в Новосибирске сегодня такая\n{0}{1}{2}{3}'.forma... | Класс, работающий с парсингом погоды | WeatherManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WeatherManager:
"""Класс, работающий с парсингом погоды"""
def get_weather_info(self):
"""Метод позволяет спарсить погоду сайта Яндекс Подсказки: # following-sibling - следующий элемент в DOM на том же уровне # ancestor:: - поиск предка"""
<|body_0|>
def _parse_weather_i... | stack_v2_sparse_classes_36k_train_009939 | 4,756 | no_license | [
{
"docstring": "Метод позволяет спарсить погоду сайта Яндекс Подсказки: # following-sibling - следующий элемент в DOM на том же уровне # ancestor:: - поиск предка",
"name": "get_weather_info",
"signature": "def get_weather_info(self)"
},
{
"docstring": "Вспомогательный метод, парсит погоду",
... | 3 | stack_v2_sparse_classes_30k_test_000134 | Implement the Python class `WeatherManager` described below.
Class description:
Класс, работающий с парсингом погоды
Method signatures and docstrings:
- def get_weather_info(self): Метод позволяет спарсить погоду сайта Яндекс Подсказки: # following-sibling - следующий элемент в DOM на том же уровне # ancestor:: - пои... | Implement the Python class `WeatherManager` described below.
Class description:
Класс, работающий с парсингом погоды
Method signatures and docstrings:
- def get_weather_info(self): Метод позволяет спарсить погоду сайта Яндекс Подсказки: # following-sibling - следующий элемент в DOM на том же уровне # ancestor:: - пои... | 13ca8263a927b7a8533c97227cf51e7b223843c5 | <|skeleton|>
class WeatherManager:
"""Класс, работающий с парсингом погоды"""
def get_weather_info(self):
"""Метод позволяет спарсить погоду сайта Яндекс Подсказки: # following-sibling - следующий элемент в DOM на том же уровне # ancestor:: - поиск предка"""
<|body_0|>
def _parse_weather_i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WeatherManager:
"""Класс, работающий с парсингом погоды"""
def get_weather_info(self):
"""Метод позволяет спарсить погоду сайта Яндекс Подсказки: # following-sibling - следующий элемент в DOM на том же уровне # ancestor:: - поиск предка"""
morning_weather = self._parse_weather_info('Утро'... | the_stack_v2_python_sparse | bot_skills.py | KobanBanan/TelegramBot | train | 0 |
f6ae82440e44f59504edf5f3797ea1269b00cd32 | [
"super().__init__(ui_obj=ui_obj, vertex=vertex, scale_factor=scale_factor, movable=movable, r=r)\nself.selected_pen = GUI_settings.pen_selected_2\nself.selected_brush = GUI_settings.brush_selected_2\nself.unselected_pen = GUI_settings.pen_atom_pos\nself.unselected_brush = GUI_settings.brush_atom_pos\nself.hidden_pe... | <|body_start_0|>
super().__init__(ui_obj=ui_obj, vertex=vertex, scale_factor=scale_factor, movable=movable, r=r)
self.selected_pen = GUI_settings.pen_selected_2
self.selected_brush = GUI_settings.brush_selected_2
self.unselected_pen = GUI_settings.pen_atom_pos
self.unselected_bru... | InteractivePosColumn | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InteractivePosColumn:
def __init__(self, ui_obj=None, vertex=None, scale_factor=1, movable=True, r=16):
"""Initialize a positional interactive column. Inherits GUI_custom_components.InteractiveColumn. Is used to highlight atomic positions."""
<|body_0|>
def set_style(self):
... | stack_v2_sparse_classes_36k_train_009940 | 26,668 | no_license | [
{
"docstring": "Initialize a positional interactive column. Inherits GUI_custom_components.InteractiveColumn. Is used to highlight atomic positions.",
"name": "__init__",
"signature": "def __init__(self, ui_obj=None, vertex=None, scale_factor=1, movable=True, r=16)"
},
{
"docstring": "Set the ap... | 2 | stack_v2_sparse_classes_30k_train_017765 | Implement the Python class `InteractivePosColumn` described below.
Class description:
Implement the InteractivePosColumn class.
Method signatures and docstrings:
- def __init__(self, ui_obj=None, vertex=None, scale_factor=1, movable=True, r=16): Initialize a positional interactive column. Inherits GUI_custom_componen... | Implement the Python class `InteractivePosColumn` described below.
Class description:
Implement the InteractivePosColumn class.
Method signatures and docstrings:
- def __init__(self, ui_obj=None, vertex=None, scale_factor=1, movable=True, r=16): Initialize a positional interactive column. Inherits GUI_custom_componen... | 7fed6e5121180981ce67b1397ddd5ef54246e5eb | <|skeleton|>
class InteractivePosColumn:
def __init__(self, ui_obj=None, vertex=None, scale_factor=1, movable=True, r=16):
"""Initialize a positional interactive column. Inherits GUI_custom_components.InteractiveColumn. Is used to highlight atomic positions."""
<|body_0|>
def set_style(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InteractivePosColumn:
def __init__(self, ui_obj=None, vertex=None, scale_factor=1, movable=True, r=16):
"""Initialize a positional interactive column. Inherits GUI_custom_components.InteractiveColumn. Is used to highlight atomic positions."""
super().__init__(ui_obj=ui_obj, vertex=vertex, scal... | the_stack_v2_python_sparse | GUI_custom_components.py | Haawk666/AutomAl_6000_thesis_version | train | 0 | |
1ca0a1d443090ea4db5dd85cbaa70a35275c74c6 | [
"self.freq = 100\nself.zero_rpm = 2500\nself.hover_rpm = 2600\nself.full_rpm = 2800\nprint('Controlling rpm between', self.zero_rpm, ' and ', self.full_rpm)\nself.sub = rospy.Subscriber('/phoenix/imu', Imu, self.imu_callback)\nself.pub = rospy.Publisher('/phoenix/cmd_motor', MotorMessage)\nr = rospy.Rate(self.freq)... | <|body_start_0|>
self.freq = 100
self.zero_rpm = 2500
self.hover_rpm = 2600
self.full_rpm = 2800
print('Controlling rpm between', self.zero_rpm, ' and ', self.full_rpm)
self.sub = rospy.Subscriber('/phoenix/imu', Imu, self.imu_callback)
self.pub = rospy.Publisher(... | ControllerNode | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ControllerNode:
def __init__(self):
"""Initialize a new controller instance."""
<|body_0|>
def imu_callback(self, imu_msg):
"""React on new imu measurements."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.freq = 100
self.zero_rpm = 250... | stack_v2_sparse_classes_36k_train_009941 | 3,455 | no_license | [
{
"docstring": "Initialize a new controller instance.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "React on new imu measurements.",
"name": "imu_callback",
"signature": "def imu_callback(self, imu_msg)"
}
] | 2 | null | Implement the Python class `ControllerNode` described below.
Class description:
Implement the ControllerNode class.
Method signatures and docstrings:
- def __init__(self): Initialize a new controller instance.
- def imu_callback(self, imu_msg): React on new imu measurements. | Implement the Python class `ControllerNode` described below.
Class description:
Implement the ControllerNode class.
Method signatures and docstrings:
- def __init__(self): Initialize a new controller instance.
- def imu_callback(self, imu_msg): React on new imu measurements.
<|skeleton|>
class ControllerNode:
d... | 301121da01382c1d0acb9af20d7b269ba177f820 | <|skeleton|>
class ControllerNode:
def __init__(self):
"""Initialize a new controller instance."""
<|body_0|>
def imu_callback(self, imu_msg):
"""React on new imu measurements."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ControllerNode:
def __init__(self):
"""Initialize a new controller instance."""
self.freq = 100
self.zero_rpm = 2500
self.hover_rpm = 2600
self.full_rpm = 2800
print('Controlling rpm between', self.zero_rpm, ' and ', self.full_rpm)
self.sub = rospy.Subsc... | the_stack_v2_python_sparse | phx_simulator/src/controller_node.py | tum-phoenix/phx_quadrocopter_ros | train | 2 | |
85f82fd233c92a6959977eda259030bfddc12bc5 | [
"if isinstance(levels, int):\n levels = np.arange(levels)\nself.est = estimator\nself.levels = levels\nself.tmpshape = None",
"levels = self.levels\nexpanded_levels = levels[None, :]\nsamples = self.est.forward(x)\ntmp = samples * expanded_levels\nself.tmpshape = tmp.shape\nreturn tmp.sum(axis=-1)",
"levels ... | <|body_start_0|>
if isinstance(levels, int):
levels = np.arange(levels)
self.est = estimator
self.levels = levels
self.tmpshape = None
<|end_body_0|>
<|body_start_1|>
levels = self.levels
expanded_levels = levels[None, :]
samples = self.est.forward(x)... | An encoder that embds a continuous encoder, which encourages values to cluster at discrete states. | DiscreteEncoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiscreteEncoder:
"""An encoder that embds a continuous encoder, which encourages values to cluster at discrete states."""
def __init__(self, estimator, levels):
"""Create a new DiscreteEncoder. Parameters ---------- estimator : an initialized estimator for example GumbelSoftmax() lev... | stack_v2_sparse_classes_36k_train_009942 | 7,697 | permissive | [
{
"docstring": "Create a new DiscreteEncoder. Parameters ---------- estimator : an initialized estimator for example GumbelSoftmax() levels : int or numpy.ndarray if int, self-generates arange(levels) else, expected to be K discrete, non-overlapping integer states",
"name": "__init__",
"signature": "def... | 4 | stack_v2_sparse_classes_30k_train_006265 | Implement the Python class `DiscreteEncoder` described below.
Class description:
An encoder that embds a continuous encoder, which encourages values to cluster at discrete states.
Method signatures and docstrings:
- def __init__(self, estimator, levels): Create a new DiscreteEncoder. Parameters ---------- estimator :... | Implement the Python class `DiscreteEncoder` described below.
Class description:
An encoder that embds a continuous encoder, which encourages values to cluster at discrete states.
Method signatures and docstrings:
- def __init__(self, estimator, levels): Create a new DiscreteEncoder. Parameters ---------- estimator :... | af89c94d500a274eda664188ddb97fcae30c6ac5 | <|skeleton|>
class DiscreteEncoder:
"""An encoder that embds a continuous encoder, which encourages values to cluster at discrete states."""
def __init__(self, estimator, levels):
"""Create a new DiscreteEncoder. Parameters ---------- estimator : an initialized estimator for example GumbelSoftmax() lev... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DiscreteEncoder:
"""An encoder that embds a continuous encoder, which encourages values to cluster at discrete states."""
def __init__(self, estimator, levels):
"""Create a new DiscreteEncoder. Parameters ---------- estimator : an initialized estimator for example GumbelSoftmax() levels : int or ... | the_stack_v2_python_sparse | prysm/x/optym/activation.py | brandondube/prysm | train | 192 |
4c53c4d7c9e361fa992b3742fe9c247df8d9524a | [
"new_x = 0\nold_x = x\nif x < 0:\n return False\nelif x % 10 == x:\n return True\nelse:\n while x > 0:\n rem = x % 10\n new_x = new_x * 10 + rem\n x = x // 10\n if new_x == old_x:\n return True\n else:\n return False",
"if x < 0:\n return False\nelif x % 10 == ... | <|body_start_0|>
new_x = 0
old_x = x
if x < 0:
return False
elif x % 10 == x:
return True
else:
while x > 0:
rem = x % 10
new_x = new_x * 10 + rem
x = x // 10
if new_x == old_x:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindrome_2(self, x):
""":type x: int :rtype: bool"""
<|body_0|>
def isPalindrome(self, x):
""":type x: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
new_x = 0
old_x = x
if x < 0:
retur... | stack_v2_sparse_classes_36k_train_009943 | 1,267 | no_license | [
{
"docstring": ":type x: int :rtype: bool",
"name": "isPalindrome_2",
"signature": "def isPalindrome_2(self, x)"
},
{
"docstring": ":type x: int :rtype: bool",
"name": "isPalindrome",
"signature": "def isPalindrome(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013592 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome_2(self, x): :type x: int :rtype: bool
- def isPalindrome(self, x): :type x: int :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome_2(self, x): :type x: int :rtype: bool
- def isPalindrome(self, x): :type x: int :rtype: bool
<|skeleton|>
class Solution:
def isPalindrome_2(self, x):
... | ec48cbde4356208afac226d41752daffe674be2c | <|skeleton|>
class Solution:
def isPalindrome_2(self, x):
""":type x: int :rtype: bool"""
<|body_0|>
def isPalindrome(self, x):
""":type x: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isPalindrome_2(self, x):
""":type x: int :rtype: bool"""
new_x = 0
old_x = x
if x < 0:
return False
elif x % 10 == x:
return True
else:
while x > 0:
rem = x % 10
new_x = new_x * 10... | the_stack_v2_python_sparse | B2BSWE/Primitives/isPalindromeNum.py | librar127/PythonDS | train | 0 | |
2c2769b489ded5ac59eebdcc91e96b3b5b63a23d | [
"result_expiration_sec_default = values.get('result_expiration_sec_default', DEFAULT_RESULT_EXPIRATION_SEC_DEFAULT)\nresult_expiration_sec_limit = values.get('result_expiration_sec_limit', DEFAULT_RESULT_EXPIRATION_SEC_LIMIT)\nif result_expiration_sec_default > result_expiration_sec_limit:\n raise ValueError(f'r... | <|body_start_0|>
result_expiration_sec_default = values.get('result_expiration_sec_default', DEFAULT_RESULT_EXPIRATION_SEC_DEFAULT)
result_expiration_sec_limit = values.get('result_expiration_sec_limit', DEFAULT_RESULT_EXPIRATION_SEC_LIMIT)
if result_expiration_sec_default > result_expiration_se... | Configuration for the API service | APIServiceConfig | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class APIServiceConfig:
"""Configuration for the API service"""
def check_result_expiration_sec(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""Validate that result_expiration_sec_default does not exceed result_expiration_sec_limit"""
<|body_0|>
def check_max_graph_age_sec(... | stack_v2_sparse_classes_36k_train_009944 | 5,558 | permissive | [
{
"docstring": "Validate that result_expiration_sec_default does not exceed result_expiration_sec_limit",
"name": "check_result_expiration_sec",
"signature": "def check_result_expiration_sec(cls, values: Dict[str, Any]) -> Dict[str, Any]"
},
{
"docstring": "Validate that max_graph_age_sec_defaul... | 3 | null | Implement the Python class `APIServiceConfig` described below.
Class description:
Configuration for the API service
Method signatures and docstrings:
- def check_result_expiration_sec(cls, values: Dict[str, Any]) -> Dict[str, Any]: Validate that result_expiration_sec_default does not exceed result_expiration_sec_limi... | Implement the Python class `APIServiceConfig` described below.
Class description:
Configuration for the API service
Method signatures and docstrings:
- def check_result_expiration_sec(cls, values: Dict[str, Any]) -> Dict[str, Any]: Validate that result_expiration_sec_default does not exceed result_expiration_sec_limi... | eb7d5d18f3d177973c4105c21be9d251250ca8d6 | <|skeleton|>
class APIServiceConfig:
"""Configuration for the API service"""
def check_result_expiration_sec(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""Validate that result_expiration_sec_default does not exceed result_expiration_sec_limit"""
<|body_0|>
def check_max_graph_age_sec(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class APIServiceConfig:
"""Configuration for the API service"""
def check_result_expiration_sec(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""Validate that result_expiration_sec_default does not exceed result_expiration_sec_limit"""
result_expiration_sec_default = values.get('result_expira... | the_stack_v2_python_sparse | altimeter/qj/config.py | tableau/altimeter | train | 75 |
26ab3f6f7388a720d81be8da784acd5299f98d9b | [
"if line == 'ping':\n self.sendLine('pong')\nelse:\n log('lineReceived', line)\n message = Message.create_message(line)\n self.factory.network.peers.add_message(message)",
"remote_ip = self.transport.getPeer().host\nif not self.factory.network.peers.assert_ip(remote_ip):\n self.transport.loseConnec... | <|body_start_0|>
if line == 'ping':
self.sendLine('pong')
else:
log('lineReceived', line)
message = Message.create_message(line)
self.factory.network.peers.add_message(message)
<|end_body_0|>
<|body_start_1|>
remote_ip = self.transport.getPeer().h... | ProfileServerProtocol | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileServerProtocol:
def lineReceived(self, line):
"""incomming connection from other peer"""
<|body_0|>
def connectionMade(self):
"""a peer has connect to us"""
<|body_1|>
def connectionLost(self, reason):
"""called when transfer complete"""
... | stack_v2_sparse_classes_36k_train_009945 | 4,415 | no_license | [
{
"docstring": "incomming connection from other peer",
"name": "lineReceived",
"signature": "def lineReceived(self, line)"
},
{
"docstring": "a peer has connect to us",
"name": "connectionMade",
"signature": "def connectionMade(self)"
},
{
"docstring": "called when transfer compl... | 3 | null | Implement the Python class `ProfileServerProtocol` described below.
Class description:
Implement the ProfileServerProtocol class.
Method signatures and docstrings:
- def lineReceived(self, line): incomming connection from other peer
- def connectionMade(self): a peer has connect to us
- def connectionLost(self, reaso... | Implement the Python class `ProfileServerProtocol` described below.
Class description:
Implement the ProfileServerProtocol class.
Method signatures and docstrings:
- def lineReceived(self, line): incomming connection from other peer
- def connectionMade(self): a peer has connect to us
- def connectionLost(self, reaso... | 12c2face0ed3398f3733595190abcecb372796e7 | <|skeleton|>
class ProfileServerProtocol:
def lineReceived(self, line):
"""incomming connection from other peer"""
<|body_0|>
def connectionMade(self):
"""a peer has connect to us"""
<|body_1|>
def connectionLost(self, reason):
"""called when transfer complete"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProfileServerProtocol:
def lineReceived(self, line):
"""incomming connection from other peer"""
if line == 'ping':
self.sendLine('pong')
else:
log('lineReceived', line)
message = Message.create_message(line)
self.factory.network.peers.add... | the_stack_v2_python_sparse | trunk/contrib/profile/network/server_protocol.py | BackupTheBerlios/solipsis-svn | train | 1 | |
d6fbedb83b39047f310b7935ea33ca436583fe7c | [
"self.driver.get(self.url_ + '/')\ntitle_present = EC.text_to_be_present_in_element((By.XPATH, '//*[@id=\"main-nav\"]/div/div[1]/a'), 'Data Commons')\nWebDriverWait(self.driver, self.TIMEOUT_SEC).until(title_present)\nhero_msg = self.driver.find_elements_by_class_name('lead')[0]\nself.assertTrue(hero_msg.text.start... | <|body_start_0|>
self.driver.get(self.url_ + '/')
title_present = EC.text_to_be_present_in_element((By.XPATH, '//*[@id="main-nav"]/div/div[1]/a'), 'Data Commons')
WebDriverWait(self.driver, self.TIMEOUT_SEC).until(title_present)
hero_msg = self.driver.find_elements_by_class_name('lead')[... | Tests for Homepage. | TestPlaceLanding | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestPlaceLanding:
"""Tests for Homepage."""
def test_homepage_en(self):
"""Test homepage in EN."""
<|body_0|>
def test_homepage_it(self):
"""Test homepage in IT."""
<|body_1|>
def test_hero_all_langs(self):
"""Test hero message translation in... | stack_v2_sparse_classes_36k_train_009946 | 5,887 | permissive | [
{
"docstring": "Test homepage in EN.",
"name": "test_homepage_en",
"signature": "def test_homepage_en(self)"
},
{
"docstring": "Test homepage in IT.",
"name": "test_homepage_it",
"signature": "def test_homepage_it(self)"
},
{
"docstring": "Test hero message translation in *all* l... | 3 | stack_v2_sparse_classes_30k_train_009585 | Implement the Python class `TestPlaceLanding` described below.
Class description:
Tests for Homepage.
Method signatures and docstrings:
- def test_homepage_en(self): Test homepage in EN.
- def test_homepage_it(self): Test homepage in IT.
- def test_hero_all_langs(self): Test hero message translation in *all* language... | Implement the Python class `TestPlaceLanding` described below.
Class description:
Tests for Homepage.
Method signatures and docstrings:
- def test_homepage_en(self): Test homepage in EN.
- def test_homepage_it(self): Test homepage in IT.
- def test_hero_all_langs(self): Test hero message translation in *all* language... | 928625749a74dd9de473170b5683f62a4bbdbd15 | <|skeleton|>
class TestPlaceLanding:
"""Tests for Homepage."""
def test_homepage_en(self):
"""Test homepage in EN."""
<|body_0|>
def test_homepage_it(self):
"""Test homepage in IT."""
<|body_1|>
def test_hero_all_langs(self):
"""Test hero message translation in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestPlaceLanding:
"""Tests for Homepage."""
def test_homepage_en(self):
"""Test homepage in EN."""
self.driver.get(self.url_ + '/')
title_present = EC.text_to_be_present_in_element((By.XPATH, '//*[@id="main-nav"]/div/div[1]/a'), 'Data Commons')
WebDriverWait(self.driver, s... | the_stack_v2_python_sparse | server/webdriver_tests/homepage_test.py | localsite/website | train | 0 |
0ad3d46b1c840031470142e972aa704b87e9360f | [
"re = MonthTicketConfig(userLogin).createMonthTicketConfig(send_data['parkName'], send_data['ticketTypeName'], send_data['renewMethod'], send_data['validTo'])\nresult = re\nAssertions().assert_in_text(result, expect['createMonthTicketConfigMsg'])",
"re = MonthTicketBill(userLogin).openMonthTicketBill(send_data['c... | <|body_start_0|>
re = MonthTicketConfig(userLogin).createMonthTicketConfig(send_data['parkName'], send_data['ticketTypeName'], send_data['renewMethod'], send_data['validTo'])
result = re
Assertions().assert_in_text(result, expect['createMonthTicketConfigMsg'])
<|end_body_0|>
<|body_start_1|>
... | TestCheckVIPCarRecord | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCheckVIPCarRecord:
def test_createMonthTicketConfig(self, userLogin, send_data, expect):
"""创建自定义月票类型"""
<|body_0|>
def test_openMonthTicketBill(self, userLogin, send_data, expect):
"""用自定义月票类型开通月票"""
<|body_1|>
def test_checkMonthTicketListRecord(se... | stack_v2_sparse_classes_36k_train_009947 | 1,918 | no_license | [
{
"docstring": "创建自定义月票类型",
"name": "test_createMonthTicketConfig",
"signature": "def test_createMonthTicketConfig(self, userLogin, send_data, expect)"
},
{
"docstring": "用自定义月票类型开通月票",
"name": "test_openMonthTicketBill",
"signature": "def test_openMonthTicketBill(self, userLogin, send_d... | 3 | null | Implement the Python class `TestCheckVIPCarRecord` described below.
Class description:
Implement the TestCheckVIPCarRecord class.
Method signatures and docstrings:
- def test_createMonthTicketConfig(self, userLogin, send_data, expect): 创建自定义月票类型
- def test_openMonthTicketBill(self, userLogin, send_data, expect): 用自定义... | Implement the Python class `TestCheckVIPCarRecord` described below.
Class description:
Implement the TestCheckVIPCarRecord class.
Method signatures and docstrings:
- def test_createMonthTicketConfig(self, userLogin, send_data, expect): 创建自定义月票类型
- def test_openMonthTicketBill(self, userLogin, send_data, expect): 用自定义... | 34c368c109867da26d9256bca85f872b0fac2ea7 | <|skeleton|>
class TestCheckVIPCarRecord:
def test_createMonthTicketConfig(self, userLogin, send_data, expect):
"""创建自定义月票类型"""
<|body_0|>
def test_openMonthTicketBill(self, userLogin, send_data, expect):
"""用自定义月票类型开通月票"""
<|body_1|>
def test_checkMonthTicketListRecord(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestCheckVIPCarRecord:
def test_createMonthTicketConfig(self, userLogin, send_data, expect):
"""创建自定义月票类型"""
re = MonthTicketConfig(userLogin).createMonthTicketConfig(send_data['parkName'], send_data['ticketTypeName'], send_data['renewMethod'], send_data['validTo'])
result = re
... | the_stack_v2_python_sparse | test_suite/centerMonitorRoom/carInOutHandle/test_checkVIPCarRecord.py | oyebino/pomp_api | train | 1 | |
89eda3da74e5dbc3b50d3c619fe0c0e9db991f61 | [
"self.month = month\nself.net = net\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\nmonth = dictionary.get('month')\nnet = dictionary.get('net')\nfor key in cls._names.values():\n if key in dictionary:\n del dictionary[key]\nreturn cls(month, net, dictiona... | <|body_start_0|>
self.month = month
self.net = net
self.additional_properties = additional_properties
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
month = dictionary.get('month')
net = dictionary.get('net')
for key in cls._names.... | Implementation of the 'NetMonthly' model. TODO: type model description here. Attributes: month (long|int): Timestamp for the first day of this month net (float): Total income during the given month, across all income streams | NetMonthly | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetMonthly:
"""Implementation of the 'NetMonthly' model. TODO: type model description here. Attributes: month (long|int): Timestamp for the first day of this month net (float): Total income during the given month, across all income streams"""
def __init__(self, month=None, net=None, addition... | stack_v2_sparse_classes_36k_train_009948 | 1,874 | permissive | [
{
"docstring": "Constructor for the NetMonthly class",
"name": "__init__",
"signature": "def __init__(self, month=None, net=None, additional_properties={})"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the ob... | 2 | stack_v2_sparse_classes_30k_train_020676 | Implement the Python class `NetMonthly` described below.
Class description:
Implementation of the 'NetMonthly' model. TODO: type model description here. Attributes: month (long|int): Timestamp for the first day of this month net (float): Total income during the given month, across all income streams
Method signatures... | Implement the Python class `NetMonthly` described below.
Class description:
Implementation of the 'NetMonthly' model. TODO: type model description here. Attributes: month (long|int): Timestamp for the first day of this month net (float): Total income during the given month, across all income streams
Method signatures... | b2ab1ded435db75c78d42261f5e4acd2a3061487 | <|skeleton|>
class NetMonthly:
"""Implementation of the 'NetMonthly' model. TODO: type model description here. Attributes: month (long|int): Timestamp for the first day of this month net (float): Total income during the given month, across all income streams"""
def __init__(self, month=None, net=None, addition... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NetMonthly:
"""Implementation of the 'NetMonthly' model. TODO: type model description here. Attributes: month (long|int): Timestamp for the first day of this month net (float): Total income during the given month, across all income streams"""
def __init__(self, month=None, net=None, additional_properties... | the_stack_v2_python_sparse | finicityapi/models/net_monthly.py | monarchmoney/finicity-python | train | 0 |
443f5ddf5ef4a27803bc4e521401554eab237717 | [
"user_attribute = is_user_attribute('facebook_id')\nif user_attribute:\n user = self.user_authenticate(facebook_id, facebook_email)\nelse:\n user = self.profile_authenticate(facebook_id, facebook_email)\nreturn user",
"user_model = get_user_model()\nif facebook_id or facebook_email:\n auth_conditions = [... | <|body_start_0|>
user_attribute = is_user_attribute('facebook_id')
if user_attribute:
user = self.user_authenticate(facebook_id, facebook_email)
else:
user = self.profile_authenticate(facebook_id, facebook_email)
return user
<|end_body_0|>
<|body_start_1|>
... | Django Facebook authentication backend This backend hides the difference between authenticating with - a django 1.5 custom user model - profile models, which were used prior to 1.5 **Example usage** >>> FacebookBackend().authenticate(facebook_id=myid) | FacebookBackend | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FacebookBackend:
"""Django Facebook authentication backend This backend hides the difference between authenticating with - a django 1.5 custom user model - profile models, which were used prior to 1.5 **Example usage** >>> FacebookBackend().authenticate(facebook_id=myid)"""
def authenticate(... | stack_v2_sparse_classes_36k_train_009949 | 5,121 | permissive | [
{
"docstring": "Route to either the user or profile table depending on which type of user customization we are using (profile was used in Django < 1.5, user is the new way in 1.5 and up)",
"name": "authenticate",
"signature": "def authenticate(self, facebook_id=None, facebook_email=None)"
},
{
"... | 3 | stack_v2_sparse_classes_30k_train_018270 | Implement the Python class `FacebookBackend` described below.
Class description:
Django Facebook authentication backend This backend hides the difference between authenticating with - a django 1.5 custom user model - profile models, which were used prior to 1.5 **Example usage** >>> FacebookBackend().authenticate(face... | Implement the Python class `FacebookBackend` described below.
Class description:
Django Facebook authentication backend This backend hides the difference between authenticating with - a django 1.5 custom user model - profile models, which were used prior to 1.5 **Example usage** >>> FacebookBackend().authenticate(face... | 89ddaae491a5110bb707567df41479f650f22f81 | <|skeleton|>
class FacebookBackend:
"""Django Facebook authentication backend This backend hides the difference between authenticating with - a django 1.5 custom user model - profile models, which were used prior to 1.5 **Example usage** >>> FacebookBackend().authenticate(facebook_id=myid)"""
def authenticate(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FacebookBackend:
"""Django Facebook authentication backend This backend hides the difference between authenticating with - a django 1.5 custom user model - profile models, which were used prior to 1.5 **Example usage** >>> FacebookBackend().authenticate(facebook_id=myid)"""
def authenticate(self, faceboo... | the_stack_v2_python_sparse | django_facebook/auth_backends.py | RebelTat/Django-facebook | train | 1 |
3a246305936b631fc4b4a3ad21aa16d5defee301 | [
"ans = collections.defaultdict(list)\nfor s in strs:\n ans[tuple(sorted(s))].append(s)\nreturn ans.values()",
"ans = collections.defaultdict(list)\nfor s in strs:\n count = [0] * 26\n for c in s:\n count[ord(c) - ord('a')] += 1\n ans[tuple(count)].append(s)\nreturn ans.values()"
] | <|body_start_0|>
ans = collections.defaultdict(list)
for s in strs:
ans[tuple(sorted(s))].append(s)
return ans.values()
<|end_body_0|>
<|body_start_1|>
ans = collections.defaultdict(list)
for s in strs:
count = [0] * 26
for c in s:
... | OfficialSolution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OfficialSolution:
def group_anagrams(self, strs: List[str]) -> List[List[str]]:
"""排序数组分类。"""
<|body_0|>
def group_anagrams_2(self, strs: List[str]) -> List[List[str]]:
"""按计数分类。"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ans = collections.defa... | stack_v2_sparse_classes_36k_train_009950 | 3,871 | no_license | [
{
"docstring": "排序数组分类。",
"name": "group_anagrams",
"signature": "def group_anagrams(self, strs: List[str]) -> List[List[str]]"
},
{
"docstring": "按计数分类。",
"name": "group_anagrams_2",
"signature": "def group_anagrams_2(self, strs: List[str]) -> List[List[str]]"
}
] | 2 | null | Implement the Python class `OfficialSolution` described below.
Class description:
Implement the OfficialSolution class.
Method signatures and docstrings:
- def group_anagrams(self, strs: List[str]) -> List[List[str]]: 排序数组分类。
- def group_anagrams_2(self, strs: List[str]) -> List[List[str]]: 按计数分类。 | Implement the Python class `OfficialSolution` described below.
Class description:
Implement the OfficialSolution class.
Method signatures and docstrings:
- def group_anagrams(self, strs: List[str]) -> List[List[str]]: 排序数组分类。
- def group_anagrams_2(self, strs: List[str]) -> List[List[str]]: 按计数分类。
<|skeleton|>
class... | 6932d69353b94ec824dd0ddc86a92453f6673232 | <|skeleton|>
class OfficialSolution:
def group_anagrams(self, strs: List[str]) -> List[List[str]]:
"""排序数组分类。"""
<|body_0|>
def group_anagrams_2(self, strs: List[str]) -> List[List[str]]:
"""按计数分类。"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OfficialSolution:
def group_anagrams(self, strs: List[str]) -> List[List[str]]:
"""排序数组分类。"""
ans = collections.defaultdict(list)
for s in strs:
ans[tuple(sorted(s))].append(s)
return ans.values()
def group_anagrams_2(self, strs: List[str]) -> List[List[str]]:
... | the_stack_v2_python_sparse | 0049_group-anagrams.py | Nigirimeshi/leetcode | train | 0 | |
d7f12b771436b89ff37c54d1e3920954087cad8c | [
"self.__cookie = {'token': token}\nself.__info = USER_INFO()\nself._Init_Info()",
"while True:\n try:\n html = REQUESTS().Get(url=API().Aggregate_Score.geturl(), cookies=self.__cookie)\n data = html.json()\n self.__info.User_Id = data['data']['userId']\n break\n except TypeError:... | <|body_start_0|>
self.__cookie = {'token': token}
self.__info = USER_INFO()
self._Init_Info()
<|end_body_0|>
<|body_start_1|>
while True:
try:
html = REQUESTS().Get(url=API().Aggregate_Score.geturl(), cookies=self.__cookie)
data = html.json()
... | 获取信息类 | GET_INFO | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GET_INFO:
"""获取信息类"""
def __init__(self, token: str):
"""GET_INFO(token: str) 初始化 :param token: 令牌"""
<|body_0|>
def _Init_Info(self) -> None:
"""_Init_Info() -> None 初始化用户id :return: None"""
<|body_1|>
def Get_Aggregate_Score(self) -> None:
... | stack_v2_sparse_classes_36k_train_009951 | 4,181 | permissive | [
{
"docstring": "GET_INFO(token: str) 初始化 :param token: 令牌",
"name": "__init__",
"signature": "def __init__(self, token: str)"
},
{
"docstring": "_Init_Info() -> None 初始化用户id :return: None",
"name": "_Init_Info",
"signature": "def _Init_Info(self) -> None"
},
{
"docstring": "Get_A... | 6 | null | Implement the Python class `GET_INFO` described below.
Class description:
获取信息类
Method signatures and docstrings:
- def __init__(self, token: str): GET_INFO(token: str) 初始化 :param token: 令牌
- def _Init_Info(self) -> None: _Init_Info() -> None 初始化用户id :return: None
- def Get_Aggregate_Score(self) -> None: Get_Aggregat... | Implement the Python class `GET_INFO` described below.
Class description:
获取信息类
Method signatures and docstrings:
- def __init__(self, token: str): GET_INFO(token: str) 初始化 :param token: 令牌
- def _Init_Info(self) -> None: _Init_Info() -> None 初始化用户id :return: None
- def Get_Aggregate_Score(self) -> None: Get_Aggregat... | 9e2a023917b86460fb02984aed9fe638c3d38dd4 | <|skeleton|>
class GET_INFO:
"""获取信息类"""
def __init__(self, token: str):
"""GET_INFO(token: str) 初始化 :param token: 令牌"""
<|body_0|>
def _Init_Info(self) -> None:
"""_Init_Info() -> None 初始化用户id :return: None"""
<|body_1|>
def Get_Aggregate_Score(self) -> None:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GET_INFO:
"""获取信息类"""
def __init__(self, token: str):
"""GET_INFO(token: str) 初始化 :param token: 令牌"""
self.__cookie = {'token': token}
self.__info = USER_INFO()
self._Init_Info()
def _Init_Info(self) -> None:
"""_Init_Info() -> None 初始化用户id :return: None"""
... | the_stack_v2_python_sparse | inside/Info/Get_Info.py | lifansama/learning-power | train | 1 |
f96aa4c0e277164cf14f5fe0921b287dbb594526 | [
"if not email:\n raise ValueError('User must have an email address')\nemail = self.normalize_email(email)\nuser = self.model(email=email, name=name, surname=surname)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(email, name, surname, password)\nuser.is_superuse... | <|body_start_0|>
if not email:
raise ValueError('User must have an email address')
email = self.normalize_email(email)
user = self.model(email=email, name=name, surname=surname)
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
... | Manager to create some functions for User model | UserProfileManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserProfileManager:
"""Manager to create some functions for User model"""
def create_user(self, email, name, surname, password=None):
"""Create a new user profile"""
<|body_0|>
def create_superuser(self, email, name, surname, password):
"""Create and save a new s... | stack_v2_sparse_classes_36k_train_009952 | 4,215 | no_license | [
{
"docstring": "Create a new user profile",
"name": "create_user",
"signature": "def create_user(self, email, name, surname, password=None)"
},
{
"docstring": "Create and save a new superuser with given details",
"name": "create_superuser",
"signature": "def create_superuser(self, email,... | 2 | stack_v2_sparse_classes_30k_train_003494 | Implement the Python class `UserProfileManager` described below.
Class description:
Manager to create some functions for User model
Method signatures and docstrings:
- def create_user(self, email, name, surname, password=None): Create a new user profile
- def create_superuser(self, email, name, surname, password): Cr... | Implement the Python class `UserProfileManager` described below.
Class description:
Manager to create some functions for User model
Method signatures and docstrings:
- def create_user(self, email, name, surname, password=None): Create a new user profile
- def create_superuser(self, email, name, surname, password): Cr... | bbcdb06cb1eed37f45557d927581e17dec801baf | <|skeleton|>
class UserProfileManager:
"""Manager to create some functions for User model"""
def create_user(self, email, name, surname, password=None):
"""Create a new user profile"""
<|body_0|>
def create_superuser(self, email, name, surname, password):
"""Create and save a new s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserProfileManager:
"""Manager to create some functions for User model"""
def create_user(self, email, name, surname, password=None):
"""Create a new user profile"""
if not email:
raise ValueError('User must have an email address')
email = self.normalize_email(email)
... | the_stack_v2_python_sparse | api/models.py | HashimovH/wallet-backend-api-demo | train | 0 |
acdeb0ae8076e8448f8140d5ec45e7c45216eeee | [
"req_body = cli.make_body(managementAddress=management_address, localUsername=local_username, localPassword=local_password, remoteUsername=remote_username, remotePassword=remote_password, connectionType=connection_type)\nresp = cli.post(cls().resource_class, **req_body)\nresp.raise_if_err()\nreturn cls.get(cli, res... | <|body_start_0|>
req_body = cli.make_body(managementAddress=management_address, localUsername=local_username, localPassword=local_password, remoteUsername=remote_username, remotePassword=remote_password, connectionType=connection_type)
resp = cli.post(cls().resource_class, **req_body)
resp.raise... | UnityRemoteSystem | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnityRemoteSystem:
def create(cls, cli, management_address, local_username=None, local_password=None, remote_username=None, remote_password=None, connection_type=None):
"""Configures a remote system for remote replication. :param cls: this class. :param cli: the rest client. :param manag... | stack_v2_sparse_classes_36k_train_009953 | 3,443 | permissive | [
{
"docstring": "Configures a remote system for remote replication. :param cls: this class. :param cli: the rest client. :param management_address: the management IP address of the remote system. :param local_username: administrative username of local system. :param local_password: administrative password of loc... | 3 | stack_v2_sparse_classes_30k_train_002211 | Implement the Python class `UnityRemoteSystem` described below.
Class description:
Implement the UnityRemoteSystem class.
Method signatures and docstrings:
- def create(cls, cli, management_address, local_username=None, local_password=None, remote_username=None, remote_password=None, connection_type=None): Configures... | Implement the Python class `UnityRemoteSystem` described below.
Class description:
Implement the UnityRemoteSystem class.
Method signatures and docstrings:
- def create(cls, cli, management_address, local_username=None, local_password=None, remote_username=None, remote_password=None, connection_type=None): Configures... | ccfccba0bceda34c0d5dc8105c95731036f4e955 | <|skeleton|>
class UnityRemoteSystem:
def create(cls, cli, management_address, local_username=None, local_password=None, remote_username=None, remote_password=None, connection_type=None):
"""Configures a remote system for remote replication. :param cls: this class. :param cli: the rest client. :param manag... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnityRemoteSystem:
def create(cls, cli, management_address, local_username=None, local_password=None, remote_username=None, remote_password=None, connection_type=None):
"""Configures a remote system for remote replication. :param cls: this class. :param cli: the rest client. :param management_address:... | the_stack_v2_python_sparse | storops/unity/resource/remote_system.py | emc-openstack/storops | train | 61 | |
571307be1e1d20222afe3cbe4527af5fcb38f445 | [
"try:\n return Member.objects.get(pk=pk)\nexcept Member.DoesNotExist:\n raise Http404",
"if pk is not None:\n member = self.get_member(int(pk))\nelse:\n member = None\nself.check_object_permissions(request, member)\nsecurity = SecuritySavings.get_members_securities(member=member)\nserializer = Securit... | <|body_start_0|>
try:
return Member.objects.get(pk=pk)
except Member.DoesNotExist:
raise Http404
<|end_body_0|>
<|body_start_1|>
if pk is not None:
member = self.get_member(int(pk))
else:
member = None
self.check_object_permissions... | LoanSecuritySavingsView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoanSecuritySavingsView:
def get_member(self, pk):
"""Get a member."""
<|body_0|>
def get(self, request, pk, format=None):
"""List Securities in form of savings --- serializer: loans.serializers.SecuritySavingsSerializer"""
<|body_1|>
def post(self, requ... | stack_v2_sparse_classes_36k_train_009954 | 13,511 | no_license | [
{
"docstring": "Get a member.",
"name": "get_member",
"signature": "def get_member(self, pk)"
},
{
"docstring": "List Securities in form of savings --- serializer: loans.serializers.SecuritySavingsSerializer",
"name": "get",
"signature": "def get(self, request, pk, format=None)"
},
{... | 3 | stack_v2_sparse_classes_30k_train_003181 | Implement the Python class `LoanSecuritySavingsView` described below.
Class description:
Implement the LoanSecuritySavingsView class.
Method signatures and docstrings:
- def get_member(self, pk): Get a member.
- def get(self, request, pk, format=None): List Securities in form of savings --- serializer: loans.serializ... | Implement the Python class `LoanSecuritySavingsView` described below.
Class description:
Implement the LoanSecuritySavingsView class.
Method signatures and docstrings:
- def get_member(self, pk): Get a member.
- def get(self, request, pk, format=None): List Securities in form of savings --- serializer: loans.serializ... | c5ac11e40a628c93c3865363e97b4f255a104ca8 | <|skeleton|>
class LoanSecuritySavingsView:
def get_member(self, pk):
"""Get a member."""
<|body_0|>
def get(self, request, pk, format=None):
"""List Securities in form of savings --- serializer: loans.serializers.SecuritySavingsSerializer"""
<|body_1|>
def post(self, requ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoanSecuritySavingsView:
def get_member(self, pk):
"""Get a member."""
try:
return Member.objects.get(pk=pk)
except Member.DoesNotExist:
raise Http404
def get(self, request, pk, format=None):
"""List Securities in form of savings --- serializer: loa... | the_stack_v2_python_sparse | loans/views.py | lubegamark/gosacco | train | 2 | |
95c30e8261c9ab99b9146d46209704d9556ecd03 | [
"self.r = radius\nself.x = x_center\nself.y = y_center",
"nr = math.sqrt(random.random()) * self.r\nalpha = random.random() * 2 * 3.141592653\nnewx = self.x + nr * math.cos(alpha)\nnewy = self.y + nr * math.sin(alpha)\nreturn [newx, newy]"
] | <|body_start_0|>
self.r = radius
self.x = x_center
self.y = y_center
<|end_body_0|>
<|body_start_1|>
nr = math.sqrt(random.random()) * self.r
alpha = random.random() * 2 * 3.141592653
newx = self.x + nr * math.cos(alpha)
newy = self.y + nr * math.sin(alpha)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, radius, x_center, y_center):
""":type radius: float :type x_center: float :type y_center: float"""
<|body_0|>
def randPoint(self):
""":rtype: List[float]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.r = radius
... | stack_v2_sparse_classes_36k_train_009955 | 1,839 | no_license | [
{
"docstring": ":type radius: float :type x_center: float :type y_center: float",
"name": "__init__",
"signature": "def __init__(self, radius, x_center, y_center)"
},
{
"docstring": ":rtype: List[float]",
"name": "randPoint",
"signature": "def randPoint(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000775 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, radius, x_center, y_center): :type radius: float :type x_center: float :type y_center: float
- def randPoint(self): :rtype: List[float] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, radius, x_center, y_center): :type radius: float :type x_center: float :type y_center: float
- def randPoint(self): :rtype: List[float]
<|skeleton|>
class Sol... | 035ef08434fa1ca781a6fb2f9eed3538b7d20c02 | <|skeleton|>
class Solution:
def __init__(self, radius, x_center, y_center):
""":type radius: float :type x_center: float :type y_center: float"""
<|body_0|>
def randPoint(self):
""":rtype: List[float]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, radius, x_center, y_center):
""":type radius: float :type x_center: float :type y_center: float"""
self.r = radius
self.x = x_center
self.y = y_center
def randPoint(self):
""":rtype: List[float]"""
nr = math.sqrt(random.random()... | the_stack_v2_python_sparse | leetcode_python/Math/generate-random-point-in-a-circle.py | yennanliu/CS_basics | train | 64 | |
23954de07b288e1b78c7bed27199f41cd6e69c3f | [
"http = self.get_auth_http_client()\nbody = urllib_parse.urlencode({'redirect_uri': redirect_uri, 'code': code, 'client_id': self.settings[self._OAUTH_SETTINGS_KEY]['key'], 'client_secret': self.settings[self._OAUTH_SETTINGS_KEY]['secret'], 'grant_type': 'authorization_code'})\nhttp.fetch(self._OAUTH_ACCESS_TOKEN_U... | <|body_start_0|>
http = self.get_auth_http_client()
body = urllib_parse.urlencode({'redirect_uri': redirect_uri, 'code': code, 'client_id': self.settings[self._OAUTH_SETTINGS_KEY]['key'], 'client_secret': self.settings[self._OAUTH_SETTINGS_KEY]['secret'], 'grant_type': 'authorization_code'})
htt... | Google authentication using OAuth2. In order to use, register your application with Google and copy the relevant parameters to your application settings. * Go to the Google Dev Console at http://console.developers.google.com * Select a project, or create a new one. * In the sidebar on the left, select APIs & Auth. * In... | GoogleOAuth2Mixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoogleOAuth2Mixin:
"""Google authentication using OAuth2. In order to use, register your application with Google and copy the relevant parameters to your application settings. * Go to the Google Dev Console at http://console.developers.google.com * Select a project, or create a new one. * In the ... | stack_v2_sparse_classes_36k_train_009956 | 47,702 | permissive | [
{
"docstring": "Handles the login for the Google user, returning an access token. The result is a dictionary containing an ``access_token`` field ([among others](https://developers.google.com/identity/protocols/OAuth2WebServer#handlingtheresponse)). Unlike other ``get_authenticated_user`` methods in this packag... | 2 | stack_v2_sparse_classes_30k_train_004208 | Implement the Python class `GoogleOAuth2Mixin` described below.
Class description:
Google authentication using OAuth2. In order to use, register your application with Google and copy the relevant parameters to your application settings. * Go to the Google Dev Console at http://console.developers.google.com * Select a ... | Implement the Python class `GoogleOAuth2Mixin` described below.
Class description:
Google authentication using OAuth2. In order to use, register your application with Google and copy the relevant parameters to your application settings. * Go to the Google Dev Console at http://console.developers.google.com * Select a ... | f5042e35b945aded77b23470ead62d7eacefde92 | <|skeleton|>
class GoogleOAuth2Mixin:
"""Google authentication using OAuth2. In order to use, register your application with Google and copy the relevant parameters to your application settings. * Go to the Google Dev Console at http://console.developers.google.com * Select a project, or create a new one. * In the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GoogleOAuth2Mixin:
"""Google authentication using OAuth2. In order to use, register your application with Google and copy the relevant parameters to your application settings. * Go to the Google Dev Console at http://console.developers.google.com * Select a project, or create a new one. * In the sidebar on th... | the_stack_v2_python_sparse | contrib/python/tornado/tornado-4/tornado/auth.py | catboost/catboost | train | 8,012 |
221d3c789e5e6580f94d2daabddf663f1d249883 | [
"Component.__init__(self, name, ReduceTensor, config)\nself.key_inputs = self.stream_keys['inputs']\nself.key_outputs = self.stream_keys['outputs']\nself.num_inputs_dims = self.config['num_inputs_dims']\nself.input_size = self.globals['input_size']\nself.dim = self.config['reduction_dim']\nself.keepdim = self.confi... | <|body_start_0|>
Component.__init__(self, name, ReduceTensor, config)
self.key_inputs = self.stream_keys['inputs']
self.key_outputs = self.stream_keys['outputs']
self.num_inputs_dims = self.config['num_inputs_dims']
self.input_size = self.globals['input_size']
self.dim = ... | Class responsible for reducing tensor using indicated reduction method along a given dimension. | ReduceTensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReduceTensor:
"""Class responsible for reducing tensor using indicated reduction method along a given dimension."""
def __init__(self, name, config):
"""Initializes object. :param name: Name of the component loaded from the configuration file. :type name: str :param config: Dictionar... | stack_v2_sparse_classes_36k_train_009957 | 4,905 | permissive | [
{
"docstring": "Initializes object. :param name: Name of the component loaded from the configuration file. :type name: str :param config: Dictionary of parameters (read from the configuration ``.yaml`` file). :type config: :py:class:`ptp.configuration.ConfigInterface`",
"name": "__init__",
"signature": ... | 4 | stack_v2_sparse_classes_30k_train_014873 | Implement the Python class `ReduceTensor` described below.
Class description:
Class responsible for reducing tensor using indicated reduction method along a given dimension.
Method signatures and docstrings:
- def __init__(self, name, config): Initializes object. :param name: Name of the component loaded from the con... | Implement the Python class `ReduceTensor` described below.
Class description:
Class responsible for reducing tensor using indicated reduction method along a given dimension.
Method signatures and docstrings:
- def __init__(self, name, config): Initializes object. :param name: Name of the component loaded from the con... | 9cb17271666061cb19fe24197ecd5e4c8d32c5da | <|skeleton|>
class ReduceTensor:
"""Class responsible for reducing tensor using indicated reduction method along a given dimension."""
def __init__(self, name, config):
"""Initializes object. :param name: Name of the component loaded from the configuration file. :type name: str :param config: Dictionar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReduceTensor:
"""Class responsible for reducing tensor using indicated reduction method along a given dimension."""
def __init__(self, name, config):
"""Initializes object. :param name: Name of the component loaded from the configuration file. :type name: str :param config: Dictionary of paramete... | the_stack_v2_python_sparse | ptp/components/transforms/reduce_tensor.py | ConnectionMaster/pytorchpipe | train | 1 |
e6d24767d4558091ea1840e522e53448065babce | [
"self.egseProtocol = UTIL.SYS.s_configuration.EGSE_PROTOCOL\nself.connected = False\nself.ccsPort = UTIL.SYS.s_configuration.CCS_SERVER_PORT\nself.connected2 = False\nself.ccsPort2 = UTIL.SYS.s_configuration.CCS_SERVER_PORT2\nself.egseAck1 = ENABLE_ACK\nself.egseAck2 = ENABLE_ACK",
"LOG_INFO('EGSE interface serve... | <|body_start_0|>
self.egseProtocol = UTIL.SYS.s_configuration.EGSE_PROTOCOL
self.connected = False
self.ccsPort = UTIL.SYS.s_configuration.CCS_SERVER_PORT
self.connected2 = False
self.ccsPort2 = UTIL.SYS.s_configuration.CCS_SERVER_PORT2
self.egseAck1 = ENABLE_ACK
... | Server Configuration (on SCOE side) | ServerConfiguration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServerConfiguration:
"""Server Configuration (on SCOE side)"""
def __init__(self):
"""Initialise the connection relevant informations"""
<|body_0|>
def dump(self):
"""Dumps the status of the server configuration attributes"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_009958 | 5,792 | permissive | [
{
"docstring": "Initialise the connection relevant informations",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Dumps the status of the server configuration attributes",
"name": "dump",
"signature": "def dump(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000241 | Implement the Python class `ServerConfiguration` described below.
Class description:
Server Configuration (on SCOE side)
Method signatures and docstrings:
- def __init__(self): Initialise the connection relevant informations
- def dump(self): Dumps the status of the server configuration attributes | Implement the Python class `ServerConfiguration` described below.
Class description:
Server Configuration (on SCOE side)
Method signatures and docstrings:
- def __init__(self): Initialise the connection relevant informations
- def dump(self): Dumps the status of the server configuration attributes
<|skeleton|>
class... | c94415e9d85519f345fc56938198ac2537c0c6d0 | <|skeleton|>
class ServerConfiguration:
"""Server Configuration (on SCOE side)"""
def __init__(self):
"""Initialise the connection relevant informations"""
<|body_0|>
def dump(self):
"""Dumps the status of the server configuration attributes"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ServerConfiguration:
"""Server Configuration (on SCOE side)"""
def __init__(self):
"""Initialise the connection relevant informations"""
self.egseProtocol = UTIL.SYS.s_configuration.EGSE_PROTOCOL
self.connected = False
self.ccsPort = UTIL.SYS.s_configuration.CCS_SERVER_POR... | the_stack_v2_python_sparse | EGSE/IF.py | khawatkom/SpacePyLibrary | train | 1 |
dceaf6a4c30e56ee41c9defd0a6ee7d9f0c8782a | [
"try:\n gcal = Calendar.from_ical(base64.b64decode(raw))\nexcept ValueError:\n gcal = Calendar.from_ical(raw)\nif not gcal:\n raise ParserError('Not a valid iCalendar data received')\nreturn self.parse_ical(gcal)",
"result = []\nfor component in gcal.walk():\n if component.name == 'VEVENT':\n d... | <|body_start_0|>
try:
gcal = Calendar.from_ical(base64.b64decode(raw))
except ValueError:
gcal = Calendar.from_ical(raw)
if not gcal:
raise ParserError('Not a valid iCalendar data received')
return self.parse_ical(gcal)
<|end_body_0|>
<|body_start_1|>... | Standard Notifications Parser based on ICal notifications. Reference: https://tools.ietf.org/html/draft-gunter-calext-maintenance-notifications-00 | ICal | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ICal:
"""Standard Notifications Parser based on ICal notifications. Reference: https://tools.ietf.org/html/draft-gunter-calext-maintenance-notifications-00"""
def parser_hook(self, raw: bytes):
"""Execute parsing."""
<|body_0|>
def parse_ical(gcal: Calendar) -> List[Dict... | stack_v2_sparse_classes_36k_train_009959 | 9,015 | permissive | [
{
"docstring": "Execute parsing.",
"name": "parser_hook",
"signature": "def parser_hook(self, raw: bytes)"
},
{
"docstring": "Standard ICalendar parsing.",
"name": "parse_ical",
"signature": "def parse_ical(gcal: Calendar) -> List[Dict]"
}
] | 2 | null | Implement the Python class `ICal` described below.
Class description:
Standard Notifications Parser based on ICal notifications. Reference: https://tools.ietf.org/html/draft-gunter-calext-maintenance-notifications-00
Method signatures and docstrings:
- def parser_hook(self, raw: bytes): Execute parsing.
- def parse_i... | Implement the Python class `ICal` described below.
Class description:
Standard Notifications Parser based on ICal notifications. Reference: https://tools.ietf.org/html/draft-gunter-calext-maintenance-notifications-00
Method signatures and docstrings:
- def parser_hook(self, raw: bytes): Execute parsing.
- def parse_i... | 2f89d326a1dea49de24b47448549d1715dee189c | <|skeleton|>
class ICal:
"""Standard Notifications Parser based on ICal notifications. Reference: https://tools.ietf.org/html/draft-gunter-calext-maintenance-notifications-00"""
def parser_hook(self, raw: bytes):
"""Execute parsing."""
<|body_0|>
def parse_ical(gcal: Calendar) -> List[Dict... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ICal:
"""Standard Notifications Parser based on ICal notifications. Reference: https://tools.ietf.org/html/draft-gunter-calext-maintenance-notifications-00"""
def parser_hook(self, raw: bytes):
"""Execute parsing."""
try:
gcal = Calendar.from_ical(base64.b64decode(raw))
... | the_stack_v2_python_sparse | circuit_maintenance_parser/parser.py | NickCostadura/circuit-maintenance-parser | train | 0 |
c0c2b71b8e222b7d45bfff8bbdc6624c6eeeefc4 | [
"if type(dm) is not int:\n raise TypeError('dm must be int representing dimensionality of model')\nif type(h) is not int:\n raise TypeError('h must be int representing number of heads')\nsuper(MultiHeadAttention, self).__init__()\nself.h = h\nself.dm = dm\nself.depth = dm // h\nself.Wq = tf.keras.layers.Dense... | <|body_start_0|>
if type(dm) is not int:
raise TypeError('dm must be int representing dimensionality of model')
if type(h) is not int:
raise TypeError('h must be int representing number of heads')
super(MultiHeadAttention, self).__init__()
self.h = h
self.... | Class to perform multi-head attention class constructor: def __init__(self, dm, h) public instance attribute: h: number of heads dm: the dimensionality of the model depth: the depth of each attention head Wq: a Dense layer with dm units, used to generate the query matrix Wk: a Dense layer with dm units, used to generat... | MultiHeadAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadAttention:
"""Class to perform multi-head attention class constructor: def __init__(self, dm, h) public instance attribute: h: number of heads dm: the dimensionality of the model depth: the depth of each attention head Wq: a Dense layer with dm units, used to generate the query matrix Wk... | stack_v2_sparse_classes_36k_train_009960 | 28,983 | no_license | [
{
"docstring": "Class constructor parameters: dm [int]: represents the dimensionality of the model h [int]: represents the number of heads sets the public instance attributes: h: number of heads dm: the dimensionality of the model depth: the depth of each attention head Wq: a Dense layer with dm units, used to ... | 3 | null | Implement the Python class `MultiHeadAttention` described below.
Class description:
Class to perform multi-head attention class constructor: def __init__(self, dm, h) public instance attribute: h: number of heads dm: the dimensionality of the model depth: the depth of each attention head Wq: a Dense layer with dm unit... | Implement the Python class `MultiHeadAttention` described below.
Class description:
Class to perform multi-head attention class constructor: def __init__(self, dm, h) public instance attribute: h: number of heads dm: the dimensionality of the model depth: the depth of each attention head Wq: a Dense layer with dm unit... | 8834b201ca84937365e4dcc0fac978656cdf5293 | <|skeleton|>
class MultiHeadAttention:
"""Class to perform multi-head attention class constructor: def __init__(self, dm, h) public instance attribute: h: number of heads dm: the dimensionality of the model depth: the depth of each attention head Wq: a Dense layer with dm units, used to generate the query matrix Wk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiHeadAttention:
"""Class to perform multi-head attention class constructor: def __init__(self, dm, h) public instance attribute: h: number of heads dm: the dimensionality of the model depth: the depth of each attention head Wq: a Dense layer with dm units, used to generate the query matrix Wk: a Dense lay... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/5-transformer.py | ejonakodra/holbertonschool-machine_learning-1 | train | 0 |
4dd207e78d5e1c5609d67152f7dd00c34dcc3ef6 | [
"len_objecttypes = float(Objecttype.published.count())\nself.cache_metatypes = {}\nfor cat in metatypes:\n if len_objecttypes:\n self.cache_metatypes[cat.pk] = cat.objecttypes_published().count() / len_objecttypes\n else:\n self.cache_metatypes[cat.pk] = 0.0",
"metatypes = Metatype.objects.all... | <|body_start_0|>
len_objecttypes = float(Objecttype.published.count())
self.cache_metatypes = {}
for cat in metatypes:
if len_objecttypes:
self.cache_metatypes[cat.pk] = cat.objecttypes_published().count() / len_objecttypes
else:
self.cache... | Sitemap for metatypes | MetatypeSitemap | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetatypeSitemap:
"""Sitemap for metatypes"""
def cache(self, metatypes):
"""Cache categorie's objecttypes percent on total objecttypes"""
<|body_0|>
def items(self):
"""Return all metatypes with coeff"""
<|body_1|>
def lastmod(self, obj):
"""... | stack_v2_sparse_classes_36k_train_009961 | 3,528 | permissive | [
{
"docstring": "Cache categorie's objecttypes percent on total objecttypes",
"name": "cache",
"signature": "def cache(self, metatypes)"
},
{
"docstring": "Return all metatypes with coeff",
"name": "items",
"signature": "def items(self)"
},
{
"docstring": "Return last modification... | 4 | stack_v2_sparse_classes_30k_train_007627 | Implement the Python class `MetatypeSitemap` described below.
Class description:
Sitemap for metatypes
Method signatures and docstrings:
- def cache(self, metatypes): Cache categorie's objecttypes percent on total objecttypes
- def items(self): Return all metatypes with coeff
- def lastmod(self, obj): Return last mod... | Implement the Python class `MetatypeSitemap` described below.
Class description:
Sitemap for metatypes
Method signatures and docstrings:
- def cache(self, metatypes): Cache categorie's objecttypes percent on total objecttypes
- def items(self): Return all metatypes with coeff
- def lastmod(self, obj): Return last mod... | 727eeefe475bb2fd1cf819bdab496f4369d1c991 | <|skeleton|>
class MetatypeSitemap:
"""Sitemap for metatypes"""
def cache(self, metatypes):
"""Cache categorie's objecttypes percent on total objecttypes"""
<|body_0|>
def items(self):
"""Return all metatypes with coeff"""
<|body_1|>
def lastmod(self, obj):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MetatypeSitemap:
"""Sitemap for metatypes"""
def cache(self, metatypes):
"""Cache categorie's objecttypes percent on total objecttypes"""
len_objecttypes = float(Objecttype.published.count())
self.cache_metatypes = {}
for cat in metatypes:
if len_objecttypes:
... | the_stack_v2_python_sparse | gstudio/sitemaps.py | suruchi/django-gstudio | train | 0 |
44feb77608e233d1888ec65e7559e8311142c0c9 | [
"import da.commit_message\nexample_message = textwrap.dedent('\\n c000|p0000|j0000000|Development Automation Bootstrap\\n\\n ---\\n work_summary: Development Automation Bootstrap\\n\\n work_notes: We have a basic skeleton build-system in place and\\n avail... | <|body_start_0|>
import da.commit_message
example_message = textwrap.dedent('\n c000|p0000|j0000000|Development Automation Bootstrap\n\n ---\n work_summary: Development Automation Bootstrap\n\n work_notes: We have a basic skeleton build-system in place and\n ... | Specify the da.commit_message.parse() function. | SpecifyParse | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpecifyParse:
"""Specify the da.commit_message.parse() function."""
def it_parses_well_formed_commit_messages(self):
"""The parse() function parses a well formed commit message."""
<|body_0|>
def it_fails_gracefully_with_a_malformed_commit_message(self):
"""It fa... | stack_v2_sparse_classes_36k_train_009962 | 5,816 | permissive | [
{
"docstring": "The parse() function parses a well formed commit message.",
"name": "it_parses_well_formed_commit_messages",
"signature": "def it_parses_well_formed_commit_messages(self)"
},
{
"docstring": "It fails gracefully when given malformed commit message.",
"name": "it_fails_graceful... | 2 | null | Implement the Python class `SpecifyParse` described below.
Class description:
Specify the da.commit_message.parse() function.
Method signatures and docstrings:
- def it_parses_well_formed_commit_messages(self): The parse() function parses a well formed commit message.
- def it_fails_gracefully_with_a_malformed_commit... | Implement the Python class `SpecifyParse` described below.
Class description:
Specify the da.commit_message.parse() function.
Method signatures and docstrings:
- def it_parses_well_formed_commit_messages(self): The parse() function parses a well formed commit message.
- def it_fails_gracefully_with_a_malformed_commit... | 04a13be2792323e3f9fdb83fd236a8e9cfe6aa2d | <|skeleton|>
class SpecifyParse:
"""Specify the da.commit_message.parse() function."""
def it_parses_well_formed_commit_messages(self):
"""The parse() function parses a well formed commit message."""
<|body_0|>
def it_fails_gracefully_with_a_malformed_commit_message(self):
"""It fa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpecifyParse:
"""Specify the da.commit_message.parse() function."""
def it_parses_well_formed_commit_messages(self):
"""The parse() function parses a well formed commit message."""
import da.commit_message
example_message = textwrap.dedent('\n c000|p0000|j0000000|Developmen... | the_stack_v2_python_sparse | a3_src/h70_internal/da/spec/spec_commit_message.py | wtpayne/hiai | train | 5 |
9827f2c266d245838a42a58f95f3892cb4e371e9 | [
"log = logging.getLogger(__name__)\napp = cls.objects.order_by('-created_at').first()\nif app and settings.DEBUG:\n log.debug(f'PagerDuty Access Token:{app.access_token}')\nsession = None\nif app:\n session = APISession(app.access_token, auth_type='oauth2')\nreturn session",
"session = cls.client()\nif not ... | <|body_start_0|>
log = logging.getLogger(__name__)
app = cls.objects.order_by('-created_at').first()
if app and settings.DEBUG:
log.debug(f'PagerDuty Access Token:{app.access_token}')
session = None
if app:
session = APISession(app.access_token, auth_type=... | Used to store Pager Duty OAuth client / app details after successfull completion of the OAuth process. | PagerDutyApp | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PagerDutyApp:
"""Used to store Pager Duty OAuth client / app details after successfull completion of the OAuth process."""
def client(cls):
"""Returns a client instance ready for use. :returns: The APISession instance for pager duty. If the OAuth app is not yet set up then None will ... | stack_v2_sparse_classes_36k_train_009963 | 15,122 | permissive | [
{
"docstring": "Returns a client instance ready for use. :returns: The APISession instance for pager duty. If the OAuth app is not yet set up then None will be returned.",
"name": "client",
"signature": "def client(cls)"
},
{
"docstring": "Return the primary and secondary on call contacts. :retu... | 2 | stack_v2_sparse_classes_30k_train_006002 | Implement the Python class `PagerDutyApp` described below.
Class description:
Used to store Pager Duty OAuth client / app details after successfull completion of the OAuth process.
Method signatures and docstrings:
- def client(cls): Returns a client instance ready for use. :returns: The APISession instance for pager... | Implement the Python class `PagerDutyApp` described below.
Class description:
Used to store Pager Duty OAuth client / app details after successfull completion of the OAuth process.
Method signatures and docstrings:
- def client(cls): Returns a client instance ready for use. :returns: The APISession instance for pager... | 0fc00331851db8a37803a95acf8dde83ddbf8be8 | <|skeleton|>
class PagerDutyApp:
"""Used to store Pager Duty OAuth client / app details after successfull completion of the OAuth process."""
def client(cls):
"""Returns a client instance ready for use. :returns: The APISession instance for pager duty. If the OAuth app is not yet set up then None will ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PagerDutyApp:
"""Used to store Pager Duty OAuth client / app details after successfull completion of the OAuth process."""
def client(cls):
"""Returns a client instance ready for use. :returns: The APISession instance for pager duty. If the OAuth app is not yet set up then None will be returned."... | the_stack_v2_python_sparse | zenslackchat/models.py | oisinmulvihill/django-zenslackchat | train | 0 |
aa2b6242b321e05ae453e47163902c67659395ce | [
"self.xml_dir = xml_dir\nself.images_dir = images_dir\nassert os.path.exists(xml_dir), 'XML file not exist'\nassert os.path.exists(images_dir), 'Images path not exist'",
"if width == 0 or height == 0:\n width = img.shape(0)\n height = img.shape(1)\ntransform = A.Compose([A.Resize(width, height, always_apply... | <|body_start_0|>
self.xml_dir = xml_dir
self.images_dir = images_dir
assert os.path.exists(xml_dir), 'XML file not exist'
assert os.path.exists(images_dir), 'Images path not exist'
<|end_body_0|>
<|body_start_1|>
if width == 0 or height == 0:
width = img.shape(0)
... | KPImageAug | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KPImageAug:
def __init__(self, xml_dir: str=None, images_dir: str=None):
"""A wrapper class on albumentations package to work on cvat segmentation format easily Args: xml_dir: XML cvat path of Images and Annotations images_dir: Images Directory"""
<|body_0|>
def augment_imag... | stack_v2_sparse_classes_36k_train_009964 | 5,420 | permissive | [
{
"docstring": "A wrapper class on albumentations package to work on cvat segmentation format easily Args: xml_dir: XML cvat path of Images and Annotations images_dir: Images Directory",
"name": "__init__",
"signature": "def __init__(self, xml_dir: str=None, images_dir: str=None)"
},
{
"docstrin... | 3 | stack_v2_sparse_classes_30k_train_008995 | Implement the Python class `KPImageAug` described below.
Class description:
Implement the KPImageAug class.
Method signatures and docstrings:
- def __init__(self, xml_dir: str=None, images_dir: str=None): A wrapper class on albumentations package to work on cvat segmentation format easily Args: xml_dir: XML cvat path... | Implement the Python class `KPImageAug` described below.
Class description:
Implement the KPImageAug class.
Method signatures and docstrings:
- def __init__(self, xml_dir: str=None, images_dir: str=None): A wrapper class on albumentations package to work on cvat segmentation format easily Args: xml_dir: XML cvat path... | 8301e63815f0a8bdf34a2bde52aad40a74b9dd74 | <|skeleton|>
class KPImageAug:
def __init__(self, xml_dir: str=None, images_dir: str=None):
"""A wrapper class on albumentations package to work on cvat segmentation format easily Args: xml_dir: XML cvat path of Images and Annotations images_dir: Images Directory"""
<|body_0|>
def augment_imag... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KPImageAug:
def __init__(self, xml_dir: str=None, images_dir: str=None):
"""A wrapper class on albumentations package to work on cvat segmentation format easily Args: xml_dir: XML cvat path of Images and Annotations images_dir: Images Directory"""
self.xml_dir = xml_dir
self.images_dir... | the_stack_v2_python_sparse | preimutils/keypoint_detection/cvat/img_aug.py | mrl-amrl/preimutils | train | 10 | |
6372f28bf35b473b31e1aa871ad3e425ae330971 | [
"data, status_code = self._rest_get('/quota/' + str(quota_id))\nif status_code == 200:\n return data['quota']\nelif status_code == 404:\n raise ZoeAPIException('quota \"{}\" not found'.format(quota_id))\nelse:\n raise ZoeAPIException('error retrieving quota {}: {}'.format(quota_id, data))",
"data, status... | <|body_start_0|>
data, status_code = self._rest_get('/quota/' + str(quota_id))
if status_code == 200:
return data['quota']
elif status_code == 404:
raise ZoeAPIException('quota "{}" not found'.format(quota_id))
else:
raise ZoeAPIException('error retrie... | The quota API class. | ZoeQuotaAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZoeQuotaAPI:
"""The quota API class."""
def get(self, quota_id: int) -> dict:
"""Retrieve a quota by its ID. :param quota_id: the service to query :return: :type quota_id: int :rtype: dict"""
<|body_0|>
def delete(self, quota_id: int) -> None:
"""Delete a quota. ... | stack_v2_sparse_classes_36k_train_009965 | 2,826 | permissive | [
{
"docstring": "Retrieve a quota by its ID. :param quota_id: the service to query :return: :type quota_id: int :rtype: dict",
"name": "get",
"signature": "def get(self, quota_id: int) -> dict"
},
{
"docstring": "Delete a quota. :param quota_id: :return: :type quota_id: int :rtype: dict",
"na... | 5 | stack_v2_sparse_classes_30k_test_000715 | Implement the Python class `ZoeQuotaAPI` described below.
Class description:
The quota API class.
Method signatures and docstrings:
- def get(self, quota_id: int) -> dict: Retrieve a quota by its ID. :param quota_id: the service to query :return: :type quota_id: int :rtype: dict
- def delete(self, quota_id: int) -> N... | Implement the Python class `ZoeQuotaAPI` described below.
Class description:
The quota API class.
Method signatures and docstrings:
- def get(self, quota_id: int) -> dict: Retrieve a quota by its ID. :param quota_id: the service to query :return: :type quota_id: int :rtype: dict
- def delete(self, quota_id: int) -> N... | c8e0c908af1954a8b41d0f6de23d08589564f0ab | <|skeleton|>
class ZoeQuotaAPI:
"""The quota API class."""
def get(self, quota_id: int) -> dict:
"""Retrieve a quota by its ID. :param quota_id: the service to query :return: :type quota_id: int :rtype: dict"""
<|body_0|>
def delete(self, quota_id: int) -> None:
"""Delete a quota. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZoeQuotaAPI:
"""The quota API class."""
def get(self, quota_id: int) -> dict:
"""Retrieve a quota by its ID. :param quota_id: the service to query :return: :type quota_id: int :rtype: dict"""
data, status_code = self._rest_get('/quota/' + str(quota_id))
if status_code == 200:
... | the_stack_v2_python_sparse | zoe_cmd/api_lib/quota.py | DistributedSystemsGroup/zoe | train | 60 |
0798982cc7b7658ac3fdfdbfc0335e1c775d65b4 | [
"threading.Thread.__init__(self)\nself.service_class_name = service_class_name\nself.message = message\nself.spot_master_dispatcher = spot_master_dispatcher",
"try:\n constructor = globals()[self.service_class_name]\n instance = constructor(spot_master_table_name=self.spot_master_dispatcher.spot_master_tabl... | <|body_start_0|>
threading.Thread.__init__(self)
self.service_class_name = service_class_name
self.message = message
self.spot_master_dispatcher = spot_master_dispatcher
<|end_body_0|>
<|body_start_1|>
try:
constructor = globals()[self.service_class_name]
... | Launch and run a Master microservice based on the service_class_name | SpotMasterMicrosvcLauncher | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpotMasterMicrosvcLauncher:
"""Launch and run a Master microservice based on the service_class_name"""
def __init__(self, service_class_name, message, spot_master_dispatcher):
""":param service_class_name: Service Class Name from the message attribute service_class_name :param messag... | stack_v2_sparse_classes_36k_train_009966 | 7,141 | no_license | [
{
"docstring": ":param service_class_name: Service Class Name from the message attribute service_class_name :param message: raw json of SpotMasterMessage instance :param spot_master_dispatcher: spot master dispatcher instance - contains various attributes necessary to launch the microservice",
"name": "__in... | 2 | stack_v2_sparse_classes_30k_train_008962 | Implement the Python class `SpotMasterMicrosvcLauncher` described below.
Class description:
Launch and run a Master microservice based on the service_class_name
Method signatures and docstrings:
- def __init__(self, service_class_name, message, spot_master_dispatcher): :param service_class_name: Service Class Name fr... | Implement the Python class `SpotMasterMicrosvcLauncher` described below.
Class description:
Launch and run a Master microservice based on the service_class_name
Method signatures and docstrings:
- def __init__(self, service_class_name, message, spot_master_dispatcher): :param service_class_name: Service Class Name fr... | f6db8f9f65bd231f3589865ac2eb1bcb45c9d837 | <|skeleton|>
class SpotMasterMicrosvcLauncher:
"""Launch and run a Master microservice based on the service_class_name"""
def __init__(self, service_class_name, message, spot_master_dispatcher):
""":param service_class_name: Service Class Name from the message attribute service_class_name :param messag... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpotMasterMicrosvcLauncher:
"""Launch and run a Master microservice based on the service_class_name"""
def __init__(self, service_class_name, message, spot_master_dispatcher):
""":param service_class_name: Service Class Name from the message attribute service_class_name :param message: raw json o... | the_stack_v2_python_sparse | src/awsspotbatch/microsvc/master/spotmasterdispatcher.py | petezybrick/awsspotbatch | train | 1 |
3717b6d79da8580f017c2c91375b795d6161e9e6 | [
"self.content = []\nif not content is None:\n self.append(content)\nself.attr = kwargs",
"if isinstance(content, str):\n self.content.append(TextEntry(content))\nelse:\n self.content.append(content)",
"file_out.write(cur_ind + '<{}'.format(self.tag))\nfor key, val in self.attr.items():\n file_out.wr... | <|body_start_0|>
self.content = []
if not content is None:
self.append(content)
self.attr = kwargs
<|end_body_0|>
<|body_start_1|>
if isinstance(content, str):
self.content.append(TextEntry(content))
else:
self.content.append(content)
<|end_bo... | An element represents one level of html tag, which can contain more nested elements | Element | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Element:
"""An element represents one level of html tag, which can contain more nested elements"""
def __init__(self, content=None, **kwargs):
"""Optional content is the next element nested under this one"""
<|body_0|>
def append(self, content):
"""Content to be ... | stack_v2_sparse_classes_36k_train_009967 | 4,165 | no_license | [
{
"docstring": "Optional content is the next element nested under this one",
"name": "__init__",
"signature": "def __init__(self, content=None, **kwargs)"
},
{
"docstring": "Content to be appended is either an Element or a string, which will be used to append a new TextElement",
"name": "app... | 3 | stack_v2_sparse_classes_30k_train_004698 | Implement the Python class `Element` described below.
Class description:
An element represents one level of html tag, which can contain more nested elements
Method signatures and docstrings:
- def __init__(self, content=None, **kwargs): Optional content is the next element nested under this one
- def append(self, con... | Implement the Python class `Element` described below.
Class description:
An element represents one level of html tag, which can contain more nested elements
Method signatures and docstrings:
- def __init__(self, content=None, **kwargs): Optional content is the next element nested under this one
- def append(self, con... | e298b1151dab639659d8dfa56f47bcb43dd3438f | <|skeleton|>
class Element:
"""An element represents one level of html tag, which can contain more nested elements"""
def __init__(self, content=None, **kwargs):
"""Optional content is the next element nested under this one"""
<|body_0|>
def append(self, content):
"""Content to be ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Element:
"""An element represents one level of html tag, which can contain more nested elements"""
def __init__(self, content=None, **kwargs):
"""Optional content is the next element nested under this one"""
self.content = []
if not content is None:
self.append(content... | the_stack_v2_python_sparse | students/RoyC/Lesson07/html_render.py | UWPCE-PythonCert-ClassRepos/Self_Paced-Online | train | 13 |
70a665c306b3d51e3dd7d62a19cfb0058a1bb917 | [
"benzyl_path = os.path.join(os.path.dirname(os.path.dirname(rmgpy.__file__)), 'examples', 'arkane', 'species', 'Benzyl')\narkane = Arkane(input_file=os.path.join(benzyl_path, 'input.py'), output_directory=benzyl_path)\narkane.plot = False\narkane.execute()\nwith open(os.path.join(benzyl_path, 'output.py'), 'r') as ... | <|body_start_0|>
benzyl_path = os.path.join(os.path.dirname(os.path.dirname(rmgpy.__file__)), 'examples', 'arkane', 'species', 'Benzyl')
arkane = Arkane(input_file=os.path.join(benzyl_path, 'input.py'), output_directory=benzyl_path)
arkane.plot = False
arkane.execute()
with open(... | Contains functional tests for Arkane's output module. | OutputTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OutputTest:
"""Contains functional tests for Arkane's output module."""
def test_prettify(self):
"""Test that the prettify function works for an Arkane job"""
<|body_0|>
def tearDownClass(cls):
"""A function that is run ONCE after all unit tests in this class."""... | stack_v2_sparse_classes_36k_train_009968 | 8,033 | permissive | [
{
"docstring": "Test that the prettify function works for an Arkane job",
"name": "test_prettify",
"signature": "def test_prettify(self)"
},
{
"docstring": "A function that is run ONCE after all unit tests in this class.",
"name": "tearDownClass",
"signature": "def tearDownClass(cls)"
... | 2 | null | Implement the Python class `OutputTest` described below.
Class description:
Contains functional tests for Arkane's output module.
Method signatures and docstrings:
- def test_prettify(self): Test that the prettify function works for an Arkane job
- def tearDownClass(cls): A function that is run ONCE after all unit te... | Implement the Python class `OutputTest` described below.
Class description:
Contains functional tests for Arkane's output module.
Method signatures and docstrings:
- def test_prettify(self): Test that the prettify function works for an Arkane job
- def tearDownClass(cls): A function that is run ONCE after all unit te... | 349a4af759cf8877197772cd7eaca1e51d46eff5 | <|skeleton|>
class OutputTest:
"""Contains functional tests for Arkane's output module."""
def test_prettify(self):
"""Test that the prettify function works for an Arkane job"""
<|body_0|>
def tearDownClass(cls):
"""A function that is run ONCE after all unit tests in this class."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OutputTest:
"""Contains functional tests for Arkane's output module."""
def test_prettify(self):
"""Test that the prettify function works for an Arkane job"""
benzyl_path = os.path.join(os.path.dirname(os.path.dirname(rmgpy.__file__)), 'examples', 'arkane', 'species', 'Benzyl')
ar... | the_stack_v2_python_sparse | arkane/outputTest.py | CanePan-cc/CanePanWorkshop | train | 2 |
028d80b24867f09946d11df436e66ed39985cbb7 | [
"super(DiceLossV1, self).__init__()\nself.smooth = smooth\nif weight is not None:\n weight = torch.tensor(weight).float()\nself.weight = weight",
"num_classes = logits.shape[1]\ngt = gt.long()\nif num_classes == 1:\n gt_1_hot = torch.eye(num_classes + 1)[gt.squeeze(1)]\n gt_1_hot = gt_1_hot.permute(0, 3,... | <|body_start_0|>
super(DiceLossV1, self).__init__()
self.smooth = smooth
if weight is not None:
weight = torch.tensor(weight).float()
self.weight = weight
<|end_body_0|>
<|body_start_1|>
num_classes = logits.shape[1]
gt = gt.long()
if num_classes == 1... | different from normal dice loss for image with no positive mask, only calculate dice for background for positive image, only calculate positive pixel | DiceLossV1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiceLossV1:
"""different from normal dice loss for image with no positive mask, only calculate dice for background for positive image, only calculate positive pixel"""
def __init__(self, smooth=1e-07, weight=None):
"""Diceloss for segmentation :param smooth: smooth value for fraction... | stack_v2_sparse_classes_36k_train_009969 | 12,362 | no_license | [
{
"docstring": "Diceloss for segmentation :param smooth: smooth value for fraction :param weight: class weight",
"name": "__init__",
"signature": "def __init__(self, smooth=1e-07, weight=None)"
},
{
"docstring": "code from https://github.com/kevinzakka/pytorch-goodies/blob/master/losses.py Note ... | 2 | stack_v2_sparse_classes_30k_train_000114 | Implement the Python class `DiceLossV1` described below.
Class description:
different from normal dice loss for image with no positive mask, only calculate dice for background for positive image, only calculate positive pixel
Method signatures and docstrings:
- def __init__(self, smooth=1e-07, weight=None): Diceloss ... | Implement the Python class `DiceLossV1` described below.
Class description:
different from normal dice loss for image with no positive mask, only calculate dice for background for positive image, only calculate positive pixel
Method signatures and docstrings:
- def __init__(self, smooth=1e-07, weight=None): Diceloss ... | 8e6f42e3a0cbc87c66b148fb61fcb44af287619e | <|skeleton|>
class DiceLossV1:
"""different from normal dice loss for image with no positive mask, only calculate dice for background for positive image, only calculate positive pixel"""
def __init__(self, smooth=1e-07, weight=None):
"""Diceloss for segmentation :param smooth: smooth value for fraction... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DiceLossV1:
"""different from normal dice loss for image with no positive mask, only calculate dice for background for positive image, only calculate positive pixel"""
def __init__(self, smooth=1e-07, weight=None):
"""Diceloss for segmentation :param smooth: smooth value for fraction :param weigh... | the_stack_v2_python_sparse | lib/loss/loss.py | yangsenwxy/colonoscopy_tissue_screen_and_segmentation | train | 0 |
69dc22baa6e75bca504755e69f3fc4f537c0362a | [
"indices = VectorQuantization.apply(inputs, codebook, labels, num_classes, activate_class_partitioning, shared_keys, training)\nindices_flatten = indices.view(-1)\nctx.save_for_backward(indices_flatten, codebook)\nctx.mark_non_differentiable(indices_flatten)\ncodes_flatten = torch.index_select(codebook, dim=0, inde... | <|body_start_0|>
indices = VectorQuantization.apply(inputs, codebook, labels, num_classes, activate_class_partitioning, shared_keys, training)
indices_flatten = indices.view(-1)
ctx.save_for_backward(indices_flatten, codebook)
ctx.mark_non_differentiable(indices_flatten)
codes_fl... | This class defines the forward method for vector quantization. As VQ is not differentiable, it approximates the gradient of the VQ as in https://arxiv.org/abs/1711.00937. | VectorQuantizationStraightThrough | [
"Apache-2.0",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-permissive",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VectorQuantizationStraightThrough:
"""This class defines the forward method for vector quantization. As VQ is not differentiable, it approximates the gradient of the VQ as in https://arxiv.org/abs/1711.00937."""
def forward(ctx, inputs, codebook, labels=None, num_classes=10, activate_class_p... | stack_v2_sparse_classes_36k_train_009970 | 19,449 | permissive | [
{
"docstring": "Applies VQ to vectors `input` with `codebook` as VQ dictionary and estimates gradients with a Straight-Through (id) approximation of the quantization steps. Arguments --------- inputs : torch.Tensor Hidden representations to quantize. Expected shape is `torch.Size([B, W, H, C])`. codebook : torc... | 2 | null | Implement the Python class `VectorQuantizationStraightThrough` described below.
Class description:
This class defines the forward method for vector quantization. As VQ is not differentiable, it approximates the gradient of the VQ as in https://arxiv.org/abs/1711.00937.
Method signatures and docstrings:
- def forward(... | Implement the Python class `VectorQuantizationStraightThrough` described below.
Class description:
This class defines the forward method for vector quantization. As VQ is not differentiable, it approximates the gradient of the VQ as in https://arxiv.org/abs/1711.00937.
Method signatures and docstrings:
- def forward(... | 92acc188d3a0f634de58463b6676e70df83ef808 | <|skeleton|>
class VectorQuantizationStraightThrough:
"""This class defines the forward method for vector quantization. As VQ is not differentiable, it approximates the gradient of the VQ as in https://arxiv.org/abs/1711.00937."""
def forward(ctx, inputs, codebook, labels=None, num_classes=10, activate_class_p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VectorQuantizationStraightThrough:
"""This class defines the forward method for vector quantization. As VQ is not differentiable, it approximates the gradient of the VQ as in https://arxiv.org/abs/1711.00937."""
def forward(ctx, inputs, codebook, labels=None, num_classes=10, activate_class_partitioning=T... | the_stack_v2_python_sparse | PyTorch/dev/perf/speechbrain-tdnn/speechbrain/lobes/models/PIQ.py | Ascend/ModelZoo-PyTorch | train | 23 |
d9bf4a4d995e547f97c3ef55cf5049b6a7f9024e | [
"if not cls.ALERT_PROCESSOR:\n cls.ALERT_PROCESSOR = AlertProcessor()\nreturn cls.ALERT_PROCESSOR",
"output_config = load_config(include={'outputs.json'})['outputs']\nself.config = resources.merge_required_outputs(output_config, env['STREAMALERT_PREFIX'])\nself.alerts_table = AlertTable(env['ALERTS_TABLE'])",
... | <|body_start_0|>
if not cls.ALERT_PROCESSOR:
cls.ALERT_PROCESSOR = AlertProcessor()
return cls.ALERT_PROCESSOR
<|end_body_0|>
<|body_start_1|>
output_config = load_config(include={'outputs.json'})['outputs']
self.config = resources.merge_required_outputs(output_config, env['... | Orchestrates delivery of alerts to the appropriate dispatchers. | AlertProcessor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlertProcessor:
"""Orchestrates delivery of alerts to the appropriate dispatchers."""
def get_instance(cls):
"""Get an instance of the AlertProcessor, using a cached version if possible."""
<|body_0|>
def __init__(self):
"""Initialization logic that can be cached... | stack_v2_sparse_classes_36k_train_009971 | 6,845 | permissive | [
{
"docstring": "Get an instance of the AlertProcessor, using a cached version if possible.",
"name": "get_instance",
"signature": "def get_instance(cls)"
},
{
"docstring": "Initialization logic that can be cached across invocations",
"name": "__init__",
"signature": "def __init__(self)"
... | 6 | stack_v2_sparse_classes_30k_train_015542 | Implement the Python class `AlertProcessor` described below.
Class description:
Orchestrates delivery of alerts to the appropriate dispatchers.
Method signatures and docstrings:
- def get_instance(cls): Get an instance of the AlertProcessor, using a cached version if possible.
- def __init__(self): Initialization log... | Implement the Python class `AlertProcessor` described below.
Class description:
Orchestrates delivery of alerts to the appropriate dispatchers.
Method signatures and docstrings:
- def get_instance(cls): Get an instance of the AlertProcessor, using a cached version if possible.
- def __init__(self): Initialization log... | 75ba140d2e1aa6e903313d88326920adcb8bff45 | <|skeleton|>
class AlertProcessor:
"""Orchestrates delivery of alerts to the appropriate dispatchers."""
def get_instance(cls):
"""Get an instance of the AlertProcessor, using a cached version if possible."""
<|body_0|>
def __init__(self):
"""Initialization logic that can be cached... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlertProcessor:
"""Orchestrates delivery of alerts to the appropriate dispatchers."""
def get_instance(cls):
"""Get an instance of the AlertProcessor, using a cached version if possible."""
if not cls.ALERT_PROCESSOR:
cls.ALERT_PROCESSOR = AlertProcessor()
return cls.A... | the_stack_v2_python_sparse | streamalert/alert_processor/main.py | avmi/streamalert | train | 0 |
6936c171df3d01a2b3947f1bd5d2ffb196fd11f2 | [
"self.n = n\nself.identity = identity_element_func\nself.binary = binary_operation_func\nn2 = 1\nwhile n2 < n:\n n2 <<= 1\nself.n2 = n2\nself.tree = [identity_element_func() for _ in range(n2 << 1)]",
"index += self.n2\nself.tree[index] = self.binary(self.tree[index], x)\nwhile index > 1:\n x = self.binary(... | <|body_start_0|>
self.n = n
self.identity = identity_element_func
self.binary = binary_operation_func
n2 = 1
while n2 < n:
n2 <<= 1
self.n2 = n2
self.tree = [identity_element_func() for _ in range(n2 << 1)]
<|end_body_0|>
<|body_start_1|>
inde... | Segment tree Store value as object type and optional function for binary operarion get function return a value by binary operarion result update function update tree's a value Attributes ---------- n : int Number of elements identity element_func : func identity_element for initialization if operator is * and identiry ... | segtree | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class segtree:
"""Segment tree Store value as object type and optional function for binary operarion get function return a value by binary operarion result update function update tree's a value Attributes ---------- n : int Number of elements identity element_func : func identity_element for initializa... | stack_v2_sparse_classes_36k_train_009972 | 4,132 | permissive | [
{
"docstring": "Constructer(Initialize parameter in this class) Parameters ---------- n : int Number of elements identity_element_func : func identity element for initialization if operator is * and identiry element is e, e * A = A and A * e = A binary_operation_func : func function for binary operation x and y... | 3 | stack_v2_sparse_classes_30k_train_013405 | Implement the Python class `segtree` described below.
Class description:
Segment tree Store value as object type and optional function for binary operarion get function return a value by binary operarion result update function update tree's a value Attributes ---------- n : int Number of elements identity element_func... | Implement the Python class `segtree` described below.
Class description:
Segment tree Store value as object type and optional function for binary operarion get function return a value by binary operarion result update function update tree's a value Attributes ---------- n : int Number of elements identity element_func... | 79a16474a8f21310e0fb47e536d527dd5dc6d655 | <|skeleton|>
class segtree:
"""Segment tree Store value as object type and optional function for binary operarion get function return a value by binary operarion result update function update tree's a value Attributes ---------- n : int Number of elements identity element_func : func identity_element for initializa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class segtree:
"""Segment tree Store value as object type and optional function for binary operarion get function return a value by binary operarion result update function update tree's a value Attributes ---------- n : int Number of elements identity element_func : func identity_element for initialization if opera... | the_stack_v2_python_sparse | src/data/403.py | NULLCT/LOMC | train | 0 |
0d60d5bccbadc9c6509b8ea9425bfc022c3a4a1f | [
"self.name = name\nself.status = ''\nself.ready = False\nself.restart_count = 0\nself.image = ''",
"if status.running:\n self.status = 'Running'\nelif status.terminated:\n self.status = 'Terminated ({})'.format(status.terminated.reason)\nelif status.waiting:\n self.status = 'Waiting ({})'.format(status.w... | <|body_start_0|>
self.name = name
self.status = ''
self.ready = False
self.restart_count = 0
self.image = ''
<|end_body_0|>
<|body_start_1|>
if status.running:
self.status = 'Running'
elif status.terminated:
self.status = 'Terminated ({})'... | Container class. | Container | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Container:
"""Container class."""
def __init__(self, name=''):
"""Init the container."""
<|body_0|>
def set_status(self, status):
"""Generate status for container."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.name = name
self.sta... | stack_v2_sparse_classes_36k_train_009973 | 4,373 | no_license | [
{
"docstring": "Init the container.",
"name": "__init__",
"signature": "def __init__(self, name='')"
},
{
"docstring": "Generate status for container.",
"name": "set_status",
"signature": "def set_status(self, status)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007330 | Implement the Python class `Container` described below.
Class description:
Container class.
Method signatures and docstrings:
- def __init__(self, name=''): Init the container.
- def set_status(self, status): Generate status for container. | Implement the Python class `Container` described below.
Class description:
Container class.
Method signatures and docstrings:
- def __init__(self, name=''): Init the container.
- def set_status(self, status): Generate status for container.
<|skeleton|>
class Container:
"""Container class."""
def __init__(se... | 190b7b8ca15a545ec83424bc2367dab954780f32 | <|skeleton|>
class Container:
"""Container class."""
def __init__(self, name=''):
"""Init the container."""
<|body_0|>
def set_status(self, status):
"""Generate status for container."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Container:
"""Container class."""
def __init__(self, name=''):
"""Init the container."""
self.name = name
self.status = ''
self.ready = False
self.restart_count = 0
self.image = ''
def set_status(self, status):
"""Generate status for container.... | the_stack_v2_python_sparse | src/onaptests/steps/cloud/resources.py | onap/testsuite-pythonsdk-tests | train | 1 |
0101cb4e170a8d168a24134fee231c0d44274d44 | [
"LOG.debug('Plumbing VIP for amphora id: %s', amphora.get(constants.ID))\nsession = db_apis.get_session()\nwith session.begin():\n db_amp = self.amphora_repo.get(session, id=amphora.get(constants.ID))\n db_subnet = self.network_driver.get_subnet(subnet[constants.ID])\n db_lb = self.loadbalancer_repo.get(se... | <|body_start_0|>
LOG.debug('Plumbing VIP for amphora id: %s', amphora.get(constants.ID))
session = db_apis.get_session()
with session.begin():
db_amp = self.amphora_repo.get(session, id=amphora.get(constants.ID))
db_subnet = self.network_driver.get_subnet(subnet[constants... | Task to plumb a VIP. | PlugVIPAmphora | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlugVIPAmphora:
"""Task to plumb a VIP."""
def execute(self, loadbalancer, amphora, subnet):
"""Plumb a vip to an amphora."""
<|body_0|>
def revert(self, result, loadbalancer, amphora, subnet, *args, **kwargs):
"""Handle a failure to plumb a vip."""
<|bod... | stack_v2_sparse_classes_36k_train_009974 | 44,034 | permissive | [
{
"docstring": "Plumb a vip to an amphora.",
"name": "execute",
"signature": "def execute(self, loadbalancer, amphora, subnet)"
},
{
"docstring": "Handle a failure to plumb a vip.",
"name": "revert",
"signature": "def revert(self, result, loadbalancer, amphora, subnet, *args, **kwargs)"
... | 2 | stack_v2_sparse_classes_30k_val_000685 | Implement the Python class `PlugVIPAmphora` described below.
Class description:
Task to plumb a VIP.
Method signatures and docstrings:
- def execute(self, loadbalancer, amphora, subnet): Plumb a vip to an amphora.
- def revert(self, result, loadbalancer, amphora, subnet, *args, **kwargs): Handle a failure to plumb a ... | Implement the Python class `PlugVIPAmphora` described below.
Class description:
Task to plumb a VIP.
Method signatures and docstrings:
- def execute(self, loadbalancer, amphora, subnet): Plumb a vip to an amphora.
- def revert(self, result, loadbalancer, amphora, subnet, *args, **kwargs): Handle a failure to plumb a ... | 0426285a41464a5015494584f109eed35a0d44db | <|skeleton|>
class PlugVIPAmphora:
"""Task to plumb a VIP."""
def execute(self, loadbalancer, amphora, subnet):
"""Plumb a vip to an amphora."""
<|body_0|>
def revert(self, result, loadbalancer, amphora, subnet, *args, **kwargs):
"""Handle a failure to plumb a vip."""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlugVIPAmphora:
"""Task to plumb a VIP."""
def execute(self, loadbalancer, amphora, subnet):
"""Plumb a vip to an amphora."""
LOG.debug('Plumbing VIP for amphora id: %s', amphora.get(constants.ID))
session = db_apis.get_session()
with session.begin():
db_amp = ... | the_stack_v2_python_sparse | octavia/controller/worker/v2/tasks/network_tasks.py | openstack/octavia | train | 147 |
0e3fdb47bce1e24332eb643301a35c77c4367d22 | [
"import bisect as bi\n\nclass Wrapper(object):\n\n def __getitem__(self, i):\n return isBadVersion(i)\ni = bi.bisect(Wrapper(), False, 1, n + 1)\nreturn i",
"s = 1\ne = n\nwhile s < e:\n m = s + (e - s) / 2\n if isBadVersion(m):\n e = m\n else:\n s = m + 1\nreturn s"
] | <|body_start_0|>
import bisect as bi
class Wrapper(object):
def __getitem__(self, i):
return isBadVersion(i)
i = bi.bisect(Wrapper(), False, 1, n + 1)
return i
<|end_body_0|>
<|body_start_1|>
s = 1
e = n
while s < e:
m = ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def firstBadVersion(self, n):
""":type n: int :rtype: int [) s: 含 e: 不含"""
<|body_0|>
def firstBadVersion2(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
import bisect as bi
class Wrapper(obj... | stack_v2_sparse_classes_36k_train_009975 | 2,267 | no_license | [
{
"docstring": ":type n: int :rtype: int [) s: 含 e: 不含",
"name": "firstBadVersion",
"signature": "def firstBadVersion(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "firstBadVersion2",
"signature": "def firstBadVersion2(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstBadVersion(self, n): :type n: int :rtype: int [) s: 含 e: 不含
- def firstBadVersion2(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstBadVersion(self, n): :type n: int :rtype: int [) s: 含 e: 不含
- def firstBadVersion2(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def firstBadVers... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def firstBadVersion(self, n):
""":type n: int :rtype: int [) s: 含 e: 不含"""
<|body_0|>
def firstBadVersion2(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def firstBadVersion(self, n):
""":type n: int :rtype: int [) s: 含 e: 不含"""
import bisect as bi
class Wrapper(object):
def __getitem__(self, i):
return isBadVersion(i)
i = bi.bisect(Wrapper(), False, 1, n + 1)
return i
def fir... | the_stack_v2_python_sparse | binary_search_tree/278_First_Bad_Version.py | vsdrun/lc_public | train | 6 | |
361355f6b2717ad5cc4565576590bbcf3bf88a70 | [
"self._inputs = self.build_inputs()\nmoving_image = self._inputs['moving_image']\nfixed_image = self._inputs['fixed_image']\ncontrol_points = self.config['backbone'].pop('control_points', False)\nbackbone_inputs = self.concat_images(moving_image, fixed_image)\nbackbone = REGISTRY.build_backbone(config=self.config['... | <|body_start_0|>
self._inputs = self.build_inputs()
moving_image = self._inputs['moving_image']
fixed_image = self._inputs['fixed_image']
control_points = self.config['backbone'].pop('control_points', False)
backbone_inputs = self.concat_images(moving_image, fixed_image)
... | A registration model predicts DVF. DDF is calculated based on DVF. | DVFModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DVFModel:
"""A registration model predicts DVF. DDF is calculated based on DVF."""
def build_model(self):
"""Build the model to be saved as self._model."""
<|body_0|>
def build_loss(self):
"""Build losses according to configs."""
<|body_1|>
def postp... | stack_v2_sparse_classes_36k_train_009976 | 21,008 | permissive | [
{
"docstring": "Build the model to be saved as self._model.",
"name": "build_model",
"signature": "def build_model(self)"
},
{
"docstring": "Build losses according to configs.",
"name": "build_loss",
"signature": "def build_loss(self)"
},
{
"docstring": "Return a dict used for sa... | 3 | null | Implement the Python class `DVFModel` described below.
Class description:
A registration model predicts DVF. DDF is calculated based on DVF.
Method signatures and docstrings:
- def build_model(self): Build the model to be saved as self._model.
- def build_loss(self): Build losses according to configs.
- def postproce... | Implement the Python class `DVFModel` described below.
Class description:
A registration model predicts DVF. DDF is calculated based on DVF.
Method signatures and docstrings:
- def build_model(self): Build the model to be saved as self._model.
- def build_loss(self): Build losses according to configs.
- def postproce... | 650a2f1a88ad3c6932be305d6a98a36e26feedc6 | <|skeleton|>
class DVFModel:
"""A registration model predicts DVF. DDF is calculated based on DVF."""
def build_model(self):
"""Build the model to be saved as self._model."""
<|body_0|>
def build_loss(self):
"""Build losses according to configs."""
<|body_1|>
def postp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DVFModel:
"""A registration model predicts DVF. DDF is calculated based on DVF."""
def build_model(self):
"""Build the model to be saved as self._model."""
self._inputs = self.build_inputs()
moving_image = self._inputs['moving_image']
fixed_image = self._inputs['fixed_imag... | the_stack_v2_python_sparse | deepreg/model/network.py | DeepRegNet/DeepReg | train | 509 |
e683268bd87d377b3ad90bda0f2d8103faab0f81 | [
"rewards = [0 for _ in range(10001)]\nfor num in nums:\n rewards[num] += num\ncur, prev = (0, 0)\nfor reward in rewards:\n nxt = max(cur, prev + reward)\n prev = cur\n cur = nxt\nreturn cur",
"counter = defaultdict(int)\nfor n in nums:\n counter[n] += 1\nF = [0 for _ in range(10000 + 3)]\nfor i in ... | <|body_start_0|>
rewards = [0 for _ in range(10001)]
for num in nums:
rewards[num] += num
cur, prev = (0, 0)
for reward in rewards:
nxt = max(cur, prev + reward)
prev = cur
cur = nxt
return cur
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
"""reduce to house rob problem whether to pick the number or not F[n] = max F[n-1] if not pick n F[n-2] + reward if pick n"""
<|body_0|>
def deleteAndEarn_dp(self, nums: List[int]) -> int:
"""reduce to house ... | stack_v2_sparse_classes_36k_train_009977 | 3,136 | no_license | [
{
"docstring": "reduce to house rob problem whether to pick the number or not F[n] = max F[n-1] if not pick n F[n-2] + reward if pick n",
"name": "deleteAndEarn",
"signature": "def deleteAndEarn(self, nums: List[int]) -> int"
},
{
"docstring": "reduce to house rob problem whether to pick the num... | 3 | stack_v2_sparse_classes_30k_train_007948 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteAndEarn(self, nums: List[int]) -> int: reduce to house rob problem whether to pick the number or not F[n] = max F[n-1] if not pick n F[n-2] + reward if pick n
- def del... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteAndEarn(self, nums: List[int]) -> int: reduce to house rob problem whether to pick the number or not F[n] = max F[n-1] if not pick n F[n-2] + reward if pick n
- def del... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
"""reduce to house rob problem whether to pick the number or not F[n] = max F[n-1] if not pick n F[n-2] + reward if pick n"""
<|body_0|>
def deleteAndEarn_dp(self, nums: List[int]) -> int:
"""reduce to house ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
"""reduce to house rob problem whether to pick the number or not F[n] = max F[n-1] if not pick n F[n-2] + reward if pick n"""
rewards = [0 for _ in range(10001)]
for num in nums:
rewards[num] += num
cur, pre... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetCode/740 Delete and Earn.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
29e577143f74ccf159ca861cdf558c13a122f57f | [
"self.id = targetid\nself.ra = ra\nself.dec = dec\nself.glon = glon\nself.glat = glat\nself.fuv_tot_exptime = fuv_tot_exptime\nself.nuv_tot_exptime = nuv_tot_exptime\nself.fuv_timerange_start = fuv_timerange_start\nself.fuv_timerange_end = fuv_timerange_end\nself.nuv_timerange_start = nuv_timerange_start\nself.nuv_... | <|body_start_0|>
self.id = targetid
self.ra = ra
self.dec = dec
self.glon = glon
self.glat = glat
self.fuv_tot_exptime = fuv_tot_exptime
self.nuv_tot_exptime = nuv_tot_exptime
self.fuv_timerange_start = fuv_timerange_start
self.fuv_timerange_end = ... | This class defines a single target within gPhoton/gTool. It keeps track of the target identifier, coordinates, locations of gPhoton output files, location of diagnostic plots, lightcurve parameters, aperture sizes, etc. | gTarget | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class gTarget:
"""This class defines a single target within gPhoton/gTool. It keeps track of the target identifier, coordinates, locations of gPhoton output files, location of diagnostic plots, lightcurve parameters, aperture sizes, etc."""
def __init__(self, targetid, ra, dec, glon, glat, fuv_tot... | stack_v2_sparse_classes_36k_train_009978 | 17,361 | no_license | [
{
"docstring": ":param targetid: ID/name of the target. :type targetid: str :param ra: Right Ascension of the target in degrees. :type ra: numpy.float64 :param dec: Declination of the target in degrees. :type dec: numpy.float64 :param glon: Galactic longitude of the target in degrees. :type glon: numpy.float64 ... | 2 | stack_v2_sparse_classes_30k_train_016206 | Implement the Python class `gTarget` described below.
Class description:
This class defines a single target within gPhoton/gTool. It keeps track of the target identifier, coordinates, locations of gPhoton output files, location of diagnostic plots, lightcurve parameters, aperture sizes, etc.
Method signatures and doc... | Implement the Python class `gTarget` described below.
Class description:
This class defines a single target within gPhoton/gTool. It keeps track of the target identifier, coordinates, locations of gPhoton output files, location of diagnostic plots, lightcurve parameters, aperture sizes, etc.
Method signatures and doc... | ccd8de1dc5cdab8869cddbdcac4685047c435fa2 | <|skeleton|>
class gTarget:
"""This class defines a single target within gPhoton/gTool. It keeps track of the target identifier, coordinates, locations of gPhoton output files, location of diagnostic plots, lightcurve parameters, aperture sizes, etc."""
def __init__(self, targetid, ra, dec, glon, glat, fuv_tot... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class gTarget:
"""This class defines a single target within gPhoton/gTool. It keeps track of the target identifier, coordinates, locations of gPhoton output files, location of diagnostic plots, lightcurve parameters, aperture sizes, etc."""
def __init__(self, targetid, ra, dec, glon, glat, fuv_tot_exptime=None... | the_stack_v2_python_sparse | gPhoton/analysis/gtool_input.py | parejkoj/gPhoton | train | 0 |
944850bd92fcccc2d48f01d6748c1e9cd1598b4c | [
"super().__init__(name=name)\nif len(output_channels) != 6:\n raise ValueError(f'Given `output_channels` must have length 6 but has length {len(output_channels)}.')\nself._output_channels = output_channels\nself._normalize_fn = normalize_fn\nself._temporal_kernel_size = temporal_kernel_size\nif self_gating_fn is... | <|body_start_0|>
super().__init__(name=name)
if len(output_channels) != 6:
raise ValueError(f'Given `output_channels` must have length 6 but has length {len(output_channels)}.')
self._output_channels = output_channels
self._normalize_fn = normalize_fn
self._temporal_k... | A 3D Inception v1 block. This allows use of separable 3D convolutions and self-gating, as described in: Rethinking Spatiotemporal Feature Learning For Video Understanding. Saining Xie, Chen Sun, Jonathan Huang, Zhuowen Tu and Kevin Murphy. https://arxiv.org/abs/1712.04851. | InceptionBlockV13D | [
"LicenseRef-scancode-proprietary-license",
"CC-BY-NC-4.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InceptionBlockV13D:
"""A 3D Inception v1 block. This allows use of separable 3D convolutions and self-gating, as described in: Rethinking Spatiotemporal Feature Learning For Video Understanding. Saining Xie, Chen Sun, Jonathan Huang, Zhuowen Tu and Kevin Murphy. https://arxiv.org/abs/1712.04851."... | stack_v2_sparse_classes_36k_train_009979 | 18,025 | permissive | [
{
"docstring": "Initializes the InceptionBlockV13D module. Args: output_channels: The size of the output channels of each block, ordered as [Conv2d_0a_1x1, Conv2d_0a_1x1, Conv2d_0b_3x3, Conv2d_0a_1x1, Conv2d_0b_3x3, Conv2d_0b_1x1] normalize_fn: Function used for normalization. temporal_kernel_size: The size of ... | 2 | null | Implement the Python class `InceptionBlockV13D` described below.
Class description:
A 3D Inception v1 block. This allows use of separable 3D convolutions and self-gating, as described in: Rethinking Spatiotemporal Feature Learning For Video Understanding. Saining Xie, Chen Sun, Jonathan Huang, Zhuowen Tu and Kevin Mur... | Implement the Python class `InceptionBlockV13D` described below.
Class description:
A 3D Inception v1 block. This allows use of separable 3D convolutions and self-gating, as described in: Rethinking Spatiotemporal Feature Learning For Video Understanding. Saining Xie, Chen Sun, Jonathan Huang, Zhuowen Tu and Kevin Mur... | a6ef8053380d6aa19aaae14b93f013ae9762d057 | <|skeleton|>
class InceptionBlockV13D:
"""A 3D Inception v1 block. This allows use of separable 3D convolutions and self-gating, as described in: Rethinking Spatiotemporal Feature Learning For Video Understanding. Saining Xie, Chen Sun, Jonathan Huang, Zhuowen Tu and Kevin Murphy. https://arxiv.org/abs/1712.04851."... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InceptionBlockV13D:
"""A 3D Inception v1 block. This allows use of separable 3D convolutions and self-gating, as described in: Rethinking Spatiotemporal Feature Learning For Video Understanding. Saining Xie, Chen Sun, Jonathan Huang, Zhuowen Tu and Kevin Murphy. https://arxiv.org/abs/1712.04851."""
def _... | the_stack_v2_python_sparse | mmv/models/s3d.py | sethuramanio/deepmind-research | train | 1 |
4edcb2410cb51abcc3350056649d5119ba099873 | [
"with FileAccess._game_lock:\n with open(os.path.join(os.path.dirname(__file__), '..', 'test_data', filename), 'r') as file:\n return function(file)",
"with FileAccess._game_lock:\n with open(os.path.join(os.path.dirname(__file__), '..', 'test_data', filename), 'w') as file:\n return function(... | <|body_start_0|>
with FileAccess._game_lock:
with open(os.path.join(os.path.dirname(__file__), '..', 'test_data', filename), 'r') as file:
return function(file)
<|end_body_0|>
<|body_start_1|>
with FileAccess._game_lock:
with open(os.path.join(os.path.dirname(__f... | Handles access of the data to prevent files from being accessed while already in use | FileAccess | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileAccess:
"""Handles access of the data to prevent files from being accessed while already in use"""
def read_game_table(function, filename):
"""Executes the passed in function after thread obtains the lock and prevents other threads from reading or writing simultaneously to the ga... | stack_v2_sparse_classes_36k_train_009980 | 4,980 | no_license | [
{
"docstring": "Executes the passed in function after thread obtains the lock and prevents other threads from reading or writing simultaneously to the game table @precondition none @return the return value of the passed in function @param function The service attempting to read from the game table @param filena... | 6 | stack_v2_sparse_classes_30k_train_001976 | Implement the Python class `FileAccess` described below.
Class description:
Handles access of the data to prevent files from being accessed while already in use
Method signatures and docstrings:
- def read_game_table(function, filename): Executes the passed in function after thread obtains the lock and prevents other... | Implement the Python class `FileAccess` described below.
Class description:
Handles access of the data to prevent files from being accessed while already in use
Method signatures and docstrings:
- def read_game_table(function, filename): Executes the passed in function after thread obtains the lock and prevents other... | 7f3a4377ff2d3d81835aafad06c654a95f059353 | <|skeleton|>
class FileAccess:
"""Handles access of the data to prevent files from being accessed while already in use"""
def read_game_table(function, filename):
"""Executes the passed in function after thread obtains the lock and prevents other threads from reading or writing simultaneously to the ga... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileAccess:
"""Handles access of the data to prevent files from being accessed while already in use"""
def read_game_table(function, filename):
"""Executes the passed in function after thread obtains the lock and prevents other threads from reading or writing simultaneously to the game table @pre... | the_stack_v2_python_sparse | code/SteamScoutServer/src/dataupdates/fileaccess.py | TheMichaelJiles/SteamScout | train | 0 |
a140d78df4e8066e3849e6fab5f0402a8a7f3bc1 | [
"self.alarms = alarms\nself.mrn = mrn\nself.csn = csn\nself.adt = adt\nself.alarms_dfs = self._get_alarms_dfs()",
"alarms: Set[str] = set()\nalarm_name_column = ALARMS_FILES['columns'][3]\nfor alarms_df in self.alarms_dfs:\n alarms = alarms.union(set(alarms_df[alarm_name_column].astype('str').str.upper()))\nre... | <|body_start_0|>
self.alarms = alarms
self.mrn = mrn
self.csn = csn
self.adt = adt
self.alarms_dfs = self._get_alarms_dfs()
<|end_body_0|>
<|body_start_1|>
alarms: Set[str] = set()
alarm_name_column = ALARMS_FILES['columns'][3]
for alarms_df in self.alarm... | Implementation of the Reader for Bedmaster Alarms data. | BedmasterAlarmsReader | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BedmasterAlarmsReader:
"""Implementation of the Reader for Bedmaster Alarms data."""
def __init__(self, alarms: str, mrn: str, csn: str, adt: str):
"""Init Bedmaster Alarms Reader. :param alarms: Absolute path of Bedmaster alarms directory. :param mrn: MRN of the patient. :param csn:... | stack_v2_sparse_classes_36k_train_009981 | 37,163 | permissive | [
{
"docstring": "Init Bedmaster Alarms Reader. :param alarms: Absolute path of Bedmaster alarms directory. :param mrn: MRN of the patient. :param csn: CSN of the patient visit. :param adt: Path to adt table.",
"name": "__init__",
"signature": "def __init__(self, alarms: str, mrn: str, csn: str, adt: str)... | 5 | stack_v2_sparse_classes_30k_train_021166 | Implement the Python class `BedmasterAlarmsReader` described below.
Class description:
Implementation of the Reader for Bedmaster Alarms data.
Method signatures and docstrings:
- def __init__(self, alarms: str, mrn: str, csn: str, adt: str): Init Bedmaster Alarms Reader. :param alarms: Absolute path of Bedmaster alar... | Implement the Python class `BedmasterAlarmsReader` described below.
Class description:
Implementation of the Reader for Bedmaster Alarms data.
Method signatures and docstrings:
- def __init__(self, alarms: str, mrn: str, csn: str, adt: str): Init Bedmaster Alarms Reader. :param alarms: Absolute path of Bedmaster alar... | 0e25886083ccefc6cbb6250605c58f018f70a2e9 | <|skeleton|>
class BedmasterAlarmsReader:
"""Implementation of the Reader for Bedmaster Alarms data."""
def __init__(self, alarms: str, mrn: str, csn: str, adt: str):
"""Init Bedmaster Alarms Reader. :param alarms: Absolute path of Bedmaster alarms directory. :param mrn: MRN of the patient. :param csn:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BedmasterAlarmsReader:
"""Implementation of the Reader for Bedmaster Alarms data."""
def __init__(self, alarms: str, mrn: str, csn: str, adt: str):
"""Init Bedmaster Alarms Reader. :param alarms: Absolute path of Bedmaster alarms directory. :param mrn: MRN of the patient. :param csn: CSN of the p... | the_stack_v2_python_sparse | tensorize/bedmaster/readers.py | mit-ccrg/ml4c3-mirror | train | 0 |
d000f4b62633eb9546b67ae1cf8cdcbb42cb1e3a | [
"self._grid = grid\nsoil_props = {'sand': (0.694, 0.0726), 'loamy sand': (0.553, 0.0869), 'sandy loam': (0.378, 0.1466), 'loam': (0.252, 0.1115), 'silt loam': (0.234, 0.2076), 'sandy clay loam': (0.319, 0.2808), 'clay loam': (0.242, 0.2589), 'silty clay loam': (0.177, 0.3256), 'sandy clay': (0.223, 0.2917), 'silty ... | <|body_start_0|>
self._grid = grid
soil_props = {'sand': (0.694, 0.0726), 'loamy sand': (0.553, 0.0869), 'sandy loam': (0.378, 0.1466), 'loam': (0.252, 0.1115), 'silt loam': (0.234, 0.2076), 'sandy clay loam': (0.319, 0.2808), 'clay loam': (0.242, 0.2589), 'silty clay loam': (0.177, 0.3256), 'sandy clay... | Infiltrate surface water into a soil following the Green-Ampt method. This code is based on an overland flow model by Francis Rengers and colleagues, after Julien et al., 1995. The infiltration scheme follows the Green and Ampt equation. It was implemented in Landlab by DEJH, March '16. Please cite Rengers et al., 2016... | SoilInfiltrationGreenAmpt | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SoilInfiltrationGreenAmpt:
"""Infiltrate surface water into a soil following the Green-Ampt method. This code is based on an overland flow model by Francis Rengers and colleagues, after Julien et al., 1995. The infiltration scheme follows the Green and Ampt equation. It was implemented in Landlab... | stack_v2_sparse_classes_36k_train_009982 | 13,125 | permissive | [
{
"docstring": "Initialize the kinematic wave approximation overland flow component.",
"name": "__init__",
"signature": "def __init__(self, grid, hydraulic_conductivity=0.005, soil_bulk_density=1590.0, rock_density=2650.0, initial_soil_moisture_content=0.15, soil_type='sandy loam', volume_fraction_coars... | 2 | stack_v2_sparse_classes_30k_test_000907 | Implement the Python class `SoilInfiltrationGreenAmpt` described below.
Class description:
Infiltrate surface water into a soil following the Green-Ampt method. This code is based on an overland flow model by Francis Rengers and colleagues, after Julien et al., 1995. The infiltration scheme follows the Green and Ampt ... | Implement the Python class `SoilInfiltrationGreenAmpt` described below.
Class description:
Infiltrate surface water into a soil following the Green-Ampt method. This code is based on an overland flow model by Francis Rengers and colleagues, after Julien et al., 1995. The infiltration scheme follows the Green and Ampt ... | 8c8613f8b8653906c1497f6557dd2a0bc555a79a | <|skeleton|>
class SoilInfiltrationGreenAmpt:
"""Infiltrate surface water into a soil following the Green-Ampt method. This code is based on an overland flow model by Francis Rengers and colleagues, after Julien et al., 1995. The infiltration scheme follows the Green and Ampt equation. It was implemented in Landlab... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SoilInfiltrationGreenAmpt:
"""Infiltrate surface water into a soil following the Green-Ampt method. This code is based on an overland flow model by Francis Rengers and colleagues, after Julien et al., 1995. The infiltration scheme follows the Green and Ampt equation. It was implemented in Landlab by DEJH, Mar... | the_stack_v2_python_sparse | landlab/components/soil_moisture/infiltrate_soil_green_ampt.py | RondaStrauch/landlab | train | 2 |
fdf55cd227fb358c37e18c97d4cab1b69ca87593 | [
"if chainlen > 10 or chainlen < 1:\n print('Chain length must be between 1 and 10, inclusive')\n sys.exit(0)\nself.mcd = Mdict()\noldnames = []\nself.chainlen = chainlen\nfor l in source:\n l = l.strip()\n oldnames.append(l)\n s = ' ' * chainlen + l\n for n in range(0, len(l)):\n self.mcd.a... | <|body_start_0|>
if chainlen > 10 or chainlen < 1:
print('Chain length must be between 1 and 10, inclusive')
sys.exit(0)
self.mcd = Mdict()
oldnames = []
self.chainlen = chainlen
for l in source:
l = l.strip()
oldnames.append(l)
... | A name from a Markov chain | MName | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MName:
"""A name from a Markov chain"""
def __init__(self, source, chainlen=2):
"""Building the dictionary"""
<|body_0|>
def New(self):
"""New name from the Markov chain"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if chainlen > 10 or chainle... | stack_v2_sparse_classes_36k_train_009983 | 8,017 | permissive | [
{
"docstring": "Building the dictionary",
"name": "__init__",
"signature": "def __init__(self, source, chainlen=2)"
},
{
"docstring": "New name from the Markov chain",
"name": "New",
"signature": "def New(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004117 | Implement the Python class `MName` described below.
Class description:
A name from a Markov chain
Method signatures and docstrings:
- def __init__(self, source, chainlen=2): Building the dictionary
- def New(self): New name from the Markov chain | Implement the Python class `MName` described below.
Class description:
A name from a Markov chain
Method signatures and docstrings:
- def __init__(self, source, chainlen=2): Building the dictionary
- def New(self): New name from the Markov chain
<|skeleton|>
class MName:
"""A name from a Markov chain"""
def... | 525aeb53217166d2ce83e4e91a3b8c1b102f0dcb | <|skeleton|>
class MName:
"""A name from a Markov chain"""
def __init__(self, source, chainlen=2):
"""Building the dictionary"""
<|body_0|>
def New(self):
"""New name from the Markov chain"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MName:
"""A name from a Markov chain"""
def __init__(self, source, chainlen=2):
"""Building the dictionary"""
if chainlen > 10 or chainlen < 1:
print('Chain length must be between 1 and 10, inclusive')
sys.exit(0)
self.mcd = Mdict()
oldnames = []
... | the_stack_v2_python_sparse | plot_gen.py | TheNicGard/DungeonStar | train | 3 |
6b7cc16a7991104e38d1c1e741130c2a632399ac | [
"self.trie = collections.defaultdict(list)\nself.length, self.ans = (len(words[0]), [])\nfor word in words:\n prefix = ''\n for letter in word:\n prefix += letter\n self.trie[prefix].append(word)\nfor word in words:\n self.dfs([word])\nreturn self.ans",
"if len(square) == self.length:\n ... | <|body_start_0|>
self.trie = collections.defaultdict(list)
self.length, self.ans = (len(words[0]), [])
for word in words:
prefix = ''
for letter in word:
prefix += letter
self.trie[prefix].append(word)
for word in words:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wordSquares(self, words):
""":type words: List[str] :rtype: List[List[str]]"""
<|body_0|>
def dfs(self, square):
""":type square: [[str]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.trie = collections.defaultdict(list)
... | stack_v2_sparse_classes_36k_train_009984 | 985 | no_license | [
{
"docstring": ":type words: List[str] :rtype: List[List[str]]",
"name": "wordSquares",
"signature": "def wordSquares(self, words)"
},
{
"docstring": ":type square: [[str]]",
"name": "dfs",
"signature": "def dfs(self, square)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006294 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordSquares(self, words): :type words: List[str] :rtype: List[List[str]]
- def dfs(self, square): :type square: [[str]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordSquares(self, words): :type words: List[str] :rtype: List[List[str]]
- def dfs(self, square): :type square: [[str]]
<|skeleton|>
class Solution:
def wordSquares(sel... | cc6245c9519d2a249aa469eefc003e340bdbfa7c | <|skeleton|>
class Solution:
def wordSquares(self, words):
""":type words: List[str] :rtype: List[List[str]]"""
<|body_0|>
def dfs(self, square):
""":type square: [[str]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def wordSquares(self, words):
""":type words: List[str] :rtype: List[List[str]]"""
self.trie = collections.defaultdict(list)
self.length, self.ans = (len(words[0]), [])
for word in words:
prefix = ''
for letter in word:
prefix +... | the_stack_v2_python_sparse | search/hardOnes/word_square.py | LQXshane/leetcode | train | 0 | |
63e6a5cc67f9859e3beab288bb97f617f2f9630b | [
"SampleQsubProcess.__init__(self, config, process_name=process_name, **kwargs)\nextension = ''\nr1_fname = self.sample_key + '_R1.fastq' + extension\nr2_fname = self.sample_key + '_R2.fastq' + extension\nself.r1_path = os.path.join(self.output_dir, r1_fname)\nself.r2_path = os.path.join(self.output_dir, r2_fname)",... | <|body_start_0|>
SampleQsubProcess.__init__(self, config, process_name=process_name, **kwargs)
extension = ''
r1_fname = self.sample_key + '_R1.fastq' + extension
r2_fname = self.sample_key + '_R2.fastq' + extension
self.r1_path = os.path.join(self.output_dir, r1_fname)
s... | Manage and stores info for the Zcat process. This is the process that decompresses and moves fastq files from storage to the processing directories. | Zcat | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Zcat:
"""Manage and stores info for the Zcat process. This is the process that decompresses and moves fastq files from storage to the processing directories."""
def __init__(self, config, process_name='zcat', **kwargs):
"""Initializes the zcat process object."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_009985 | 7,917 | no_license | [
{
"docstring": "Initializes the zcat process object.",
"name": "__init__",
"signature": "def __init__(self, config, process_name='zcat', **kwargs)"
},
{
"docstring": "Fills the qsub file from a template. Since not all information is archived in the parent object, the function also gets additiona... | 4 | stack_v2_sparse_classes_30k_train_011876 | Implement the Python class `Zcat` described below.
Class description:
Manage and stores info for the Zcat process. This is the process that decompresses and moves fastq files from storage to the processing directories.
Method signatures and docstrings:
- def __init__(self, config, process_name='zcat', **kwargs): Init... | Implement the Python class `Zcat` described below.
Class description:
Manage and stores info for the Zcat process. This is the process that decompresses and moves fastq files from storage to the processing directories.
Method signatures and docstrings:
- def __init__(self, config, process_name='zcat', **kwargs): Init... | d05f7849139d6396a7a2d3905b76cd64dcbc96dc | <|skeleton|>
class Zcat:
"""Manage and stores info for the Zcat process. This is the process that decompresses and moves fastq files from storage to the processing directories."""
def __init__(self, config, process_name='zcat', **kwargs):
"""Initializes the zcat process object."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Zcat:
"""Manage and stores info for the Zcat process. This is the process that decompresses and moves fastq files from storage to the processing directories."""
def __init__(self, config, process_name='zcat', **kwargs):
"""Initializes the zcat process object."""
SampleQsubProcess.__init__... | the_stack_v2_python_sparse | pipeline/processes/zcat/models.py | billyziege/pipeline_project | train | 0 |
265946f67b70ea6c96ed04389c31650606dacc63 | [
"l, r, size = (0, 0, len(nums))\nwhile r < size:\n if nums[r] != 0:\n nums[l], nums[r] = (nums[r], nums[l])\n l += 1\n r += 1\nprint(nums)",
"size, l = (len(nums), 0)\nfor i in range(0, size):\n if nums[i] != 0:\n nums[l] = nums[i]\n l += 1\nfor i in range(l, size):\n nums[... | <|body_start_0|>
l, r, size = (0, 0, len(nums))
while r < size:
if nums[r] != 0:
nums[l], nums[r] = (nums[r], nums[l])
l += 1
r += 1
print(nums)
<|end_body_0|>
<|body_start_1|>
size, l = (len(nums), 0)
for i in range(0, siz... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def moveZeroes1(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k_train_009986 | 802 | no_license | [
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "moveZeroes",
"signature": "def moveZeroes(self, nums: List[int]) -> None"
},
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "moveZeroes1",
"signature": "def moveZeroes1(self,... | 2 | stack_v2_sparse_classes_30k_train_014766 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def moveZeroes(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead.
- def moveZeroes1(self, nums: List[int]) -> None: Do not return anything, mod... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def moveZeroes(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead.
- def moveZeroes1(self, nums: List[int]) -> None: Do not return anything, mod... | d74389704de4ce519a22061191b626b7204d4dbc | <|skeleton|>
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def moveZeroes1(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
l, r, size = (0, 0, len(nums))
while r < size:
if nums[r] != 0:
nums[l], nums[r] = (nums[r], nums[l])
l += 1
r +=... | the_stack_v2_python_sparse | 01_array/easy_283_moveZeroes.py | MrLW/algorithm | train | 0 | |
2f86dc0783c7165661c461a1fea1fb2376e9e55f | [
"Parametre.__init__(self, 'trouver', 'find')\nself.schema = '<ident_salle>'\nself.aide_courte = 'cherche une route'\nself.aide_longue = \"Cette commande demande au système de chercher le chemin le plus court entre deux salles : la salle d'origine est celle où vous vous trouvez actuellement. La salle de destination ... | <|body_start_0|>
Parametre.__init__(self, 'trouver', 'find')
self.schema = '<ident_salle>'
self.aide_courte = 'cherche une route'
self.aide_longue = "Cette commande demande au système de chercher le chemin le plus court entre deux salles : la salle d'origine est celle où vous vous trouve... | Commande 'route trouver' | PrmTrouver | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmTrouver:
"""Commande 'route trouver'"""
def __init__(self):
"""Constructeur du paramètre."""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Méthode d'interprétation de commande."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
P... | stack_v2_sparse_classes_36k_train_009987 | 3,108 | permissive | [
{
"docstring": "Constructeur du paramètre.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Méthode d'interprétation de commande.",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000038 | Implement the Python class `PrmTrouver` described below.
Class description:
Commande 'route trouver'
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre.
- def interpreter(self, personnage, dic_masques): Méthode d'interprétation de commande. | Implement the Python class `PrmTrouver` described below.
Class description:
Commande 'route trouver'
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre.
- def interpreter(self, personnage, dic_masques): Méthode d'interprétation de commande.
<|skeleton|>
class PrmTrouver:
"""Command... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmTrouver:
"""Commande 'route trouver'"""
def __init__(self):
"""Constructeur du paramètre."""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Méthode d'interprétation de commande."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrmTrouver:
"""Commande 'route trouver'"""
def __init__(self):
"""Constructeur du paramètre."""
Parametre.__init__(self, 'trouver', 'find')
self.schema = '<ident_salle>'
self.aide_courte = 'cherche une route'
self.aide_longue = "Cette commande demande au système de... | the_stack_v2_python_sparse | src/secondaires/route/commandes/route/trouver.py | vincent-lg/tsunami | train | 5 |
f34d04c6577fd8f9c685ef6b5d38dbaca3bc1c7c | [
"coreIOManager = slicer.app.coreIOManager()\nfileType = coreIOManager.fileType(fileUri)\nfileSuccessfullyLoaded = slicer.util.loadNodeFromFile(fileUri, fileType)\nslicer.app.processEvents()\nif not fileSuccessfullyLoaded:\n errStr = \"Could not load '%s'!\" % fileUri\n print(errStr)\nelse:\n slicer.app.lay... | <|body_start_0|>
coreIOManager = slicer.app.coreIOManager()
fileType = coreIOManager.fileType(fileUri)
fileSuccessfullyLoaded = slicer.util.loadNodeFromFile(fileUri, fileType)
slicer.app.processEvents()
if not fileSuccessfullyLoaded:
errStr = "Could not load '%s'!" % ... | SlicerUtils | [
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SlicerUtils:
def loadNodeFromFile(fileUri):
"""Load a given file as a node into Slicer, first by calling on slicer.app.coreIOManager.fileType to determine the file's type, then by calling on slicer.util.loadNodeFromFile. @param fileUri: The file to load. @type fileUri: string"""
... | stack_v2_sparse_classes_36k_train_009988 | 9,290 | permissive | [
{
"docstring": "Load a given file as a node into Slicer, first by calling on slicer.app.coreIOManager.fileType to determine the file's type, then by calling on slicer.util.loadNodeFromFile. @param fileUri: The file to load. @type fileUri: string",
"name": "loadNodeFromFile",
"signature": "def loadNodeFr... | 4 | stack_v2_sparse_classes_30k_train_002126 | Implement the Python class `SlicerUtils` described below.
Class description:
Implement the SlicerUtils class.
Method signatures and docstrings:
- def loadNodeFromFile(fileUri): Load a given file as a node into Slicer, first by calling on slicer.app.coreIOManager.fileType to determine the file's type, then by calling ... | Implement the Python class `SlicerUtils` described below.
Class description:
Implement the SlicerUtils class.
Method signatures and docstrings:
- def loadNodeFromFile(fileUri): Load a given file as a node into Slicer, first by calling on slicer.app.coreIOManager.fileType to determine the file's type, then by calling ... | 06867037842e2a074ae5ed3b0bdf4bf016a231a5 | <|skeleton|>
class SlicerUtils:
def loadNodeFromFile(fileUri):
"""Load a given file as a node into Slicer, first by calling on slicer.app.coreIOManager.fileType to determine the file's type, then by calling on slicer.util.loadNodeFromFile. @param fileUri: The file to load. @type fileUri: string"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SlicerUtils:
def loadNodeFromFile(fileUri):
"""Load a given file as a node into Slicer, first by calling on slicer.app.coreIOManager.fileType to determine the file's type, then by calling on slicer.util.loadNodeFromFile. @param fileUri: The file to load. @type fileUri: string"""
coreIOManager ... | the_stack_v2_python_sparse | XNATSlicer/XnatSlicerLib/utils/SlicerUtils.py | NrgXnat/XNATSlicer | train | 4 | |
177f4a5ab7e755ad2681cc79cb9b73d99b7ef244 | [
"logger.info('Connecting to Redis on {host}:{port}...'.format(host=self.host, port=self.port))\nsuper(RedisSubscriber, self).connect()\nlogger.info('Successfully connected to Redis')\nself.pubsub = self.client.pubsub()\nself.pubsub.subscribe(self.channel)\nlogger.info('Subscribed to [{channel}] Redis channel'.forma... | <|body_start_0|>
logger.info('Connecting to Redis on {host}:{port}...'.format(host=self.host, port=self.port))
super(RedisSubscriber, self).connect()
logger.info('Successfully connected to Redis')
self.pubsub = self.client.pubsub()
self.pubsub.subscribe(self.channel)
logg... | Subscriber using Redis SUB | RedisSubscriber | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RedisSubscriber:
"""Subscriber using Redis SUB"""
def connect(self):
"""Connects to Redis"""
<|body_0|>
def listen(self):
"""Listen for messages"""
<|body_1|>
def exit(self):
"""Closes the connection"""
<|body_2|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_36k_train_009989 | 3,622 | permissive | [
{
"docstring": "Connects to Redis",
"name": "connect",
"signature": "def connect(self)"
},
{
"docstring": "Listen for messages",
"name": "listen",
"signature": "def listen(self)"
},
{
"docstring": "Closes the connection",
"name": "exit",
"signature": "def exit(self)"
}
... | 3 | stack_v2_sparse_classes_30k_val_001108 | Implement the Python class `RedisSubscriber` described below.
Class description:
Subscriber using Redis SUB
Method signatures and docstrings:
- def connect(self): Connects to Redis
- def listen(self): Listen for messages
- def exit(self): Closes the connection | Implement the Python class `RedisSubscriber` described below.
Class description:
Subscriber using Redis SUB
Method signatures and docstrings:
- def connect(self): Connects to Redis
- def listen(self): Listen for messages
- def exit(self): Closes the connection
<|skeleton|>
class RedisSubscriber:
"""Subscriber us... | b9fbd08bbe162c8890c2a2124674371170c319ef | <|skeleton|>
class RedisSubscriber:
"""Subscriber using Redis SUB"""
def connect(self):
"""Connects to Redis"""
<|body_0|>
def listen(self):
"""Listen for messages"""
<|body_1|>
def exit(self):
"""Closes the connection"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RedisSubscriber:
"""Subscriber using Redis SUB"""
def connect(self):
"""Connects to Redis"""
logger.info('Connecting to Redis on {host}:{port}...'.format(host=self.host, port=self.port))
super(RedisSubscriber, self).connect()
logger.info('Successfully connected to Redis')
... | the_stack_v2_python_sparse | mease/backends/redis.py | florianpaquet/mease | train | 2 |
ced5f55568d1bf3a6451b0bca5176f21a02b01c1 | [
"amount = -1\nwhile amount <= 0:\n amount = float(input(f'Enter {budget_category.value} budget: '))\n if amount <= 0:\n print('Budget amount must be greater than 0! Please enter again!')\nreturn Budget(budget_category, amount)",
"manager = BudgetManager()\nfor category in list(BudgetCategory):\n b... | <|body_start_0|>
amount = -1
while amount <= 0:
amount = float(input(f'Enter {budget_category.value} budget: '))
if amount <= 0:
print('Budget amount must be greater than 0! Please enter again!')
return Budget(budget_category, amount)
<|end_body_0|>
<|bod... | An utility class that helps create Budget and BudgetManager. | BudgetCreator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BudgetCreator:
"""An utility class that helps create Budget and BudgetManager."""
def create_budget(budget_category: BudgetCategory) -> Budget:
"""Creates and returns a budget from user input for the given budget category. :param budget_category: a string :return: a Budget"""
... | stack_v2_sparse_classes_36k_train_009990 | 5,756 | no_license | [
{
"docstring": "Creates and returns a budget from user input for the given budget category. :param budget_category: a string :return: a Budget",
"name": "create_budget",
"signature": "def create_budget(budget_category: BudgetCategory) -> Budget"
},
{
"docstring": "Prompts the user for the amount... | 4 | stack_v2_sparse_classes_30k_train_021331 | Implement the Python class `BudgetCreator` described below.
Class description:
An utility class that helps create Budget and BudgetManager.
Method signatures and docstrings:
- def create_budget(budget_category: BudgetCategory) -> Budget: Creates and returns a budget from user input for the given budget category. :par... | Implement the Python class `BudgetCreator` described below.
Class description:
An utility class that helps create Budget and BudgetManager.
Method signatures and docstrings:
- def create_budget(budget_category: BudgetCategory) -> Budget: Creates and returns a budget from user input for the given budget category. :par... | e86956c69006f96221349fe9bd4925ad2255601e | <|skeleton|>
class BudgetCreator:
"""An utility class that helps create Budget and BudgetManager."""
def create_budget(budget_category: BudgetCategory) -> Budget:
"""Creates and returns a budget from user input for the given budget category. :param budget_category: a string :return: a Budget"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BudgetCreator:
"""An utility class that helps create Budget and BudgetManager."""
def create_budget(budget_category: BudgetCategory) -> Budget:
"""Creates and returns a budget from user input for the given budget category. :param budget_category: a string :return: a Budget"""
amount = -1
... | the_stack_v2_python_sparse | assignment-1-the-f-a-m-lizhiquan/budget.py | lizhiquan/learning-python | train | 0 |
f35c4eeab4ae0f5bc1bdcaa90e18314256783d17 | [
"self.fmap_shape = None\nself.indices = None\nself.indices_list = None",
"df['idx'] = range(len(df))\nembedding_2d = df[['x', 'y']].values\nN = len(df)\nsize1 = int(np.ceil(np.sqrt(N)))\nsize2 = int(np.ceil(N / size1))\ngrid_size = (size1, size2)\ngrid = np.dstack(np.meshgrid(np.linspace(0, 1, size2), np.linspace... | <|body_start_0|>
self.fmap_shape = None
self.indices = None
self.indices_list = None
<|end_body_0|>
<|body_start_1|>
df['idx'] = range(len(df))
embedding_2d = df[['x', 'y']].values
N = len(df)
size1 = int(np.ceil(np.sqrt(N)))
size2 = int(np.ceil(N / size1... | Scatter2Grid | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Scatter2Grid:
def __init__(self):
"""assign x,y coords to gird numpy array"""
<|body_0|>
def fit(self, df, split_channels=True, channel_col='Channels', channel_order=[]):
"""parameters ------------------ df: dataframe with x, y columns split_channels: bool, if True, ... | stack_v2_sparse_classes_36k_train_009991 | 7,104 | permissive | [
{
"docstring": "assign x,y coords to gird numpy array",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "parameters ------------------ df: dataframe with x, y columns split_channels: bool, if True, will apply split by group channel_col: column in df.columns, split to grou... | 3 | null | Implement the Python class `Scatter2Grid` described below.
Class description:
Implement the Scatter2Grid class.
Method signatures and docstrings:
- def __init__(self): assign x,y coords to gird numpy array
- def fit(self, df, split_channels=True, channel_col='Channels', channel_order=[]): parameters -----------------... | Implement the Python class `Scatter2Grid` described below.
Class description:
Implement the Scatter2Grid class.
Method signatures and docstrings:
- def __init__(self): assign x,y coords to gird numpy array
- def fit(self, df, split_channels=True, channel_col='Channels', channel_order=[]): parameters -----------------... | a46526eb1094b87ffa387e357de9313cff7ff7e3 | <|skeleton|>
class Scatter2Grid:
def __init__(self):
"""assign x,y coords to gird numpy array"""
<|body_0|>
def fit(self, df, split_channels=True, channel_col='Channels', channel_order=[]):
"""parameters ------------------ df: dataframe with x, y columns split_channels: bool, if True, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Scatter2Grid:
def __init__(self):
"""assign x,y coords to gird numpy array"""
self.fmap_shape = None
self.indices = None
self.indices_list = None
def fit(self, df, split_channels=True, channel_col='Channels', channel_order=[]):
"""parameters ------------------ df: ... | the_stack_v2_python_sparse | molmap/utils/matrixopt.py | shenwanxiang/bidd-molmap | train | 124 | |
581ec5db4a01dac41a9d66756a7b5da45b83e275 | [
"self.observation_payload = self._build_prolog(request)\nself._build_project(self.observation_payload, request)\nself._build_inst_schedule(instname, self.observation_payload, request)",
"exp_time = request.payload['exposure_time']\nexp_count = int(request.payload['exposure_counts'])\nfor filt in request.payload['... | <|body_start_0|>
self.observation_payload = self._build_prolog(request)
self._build_project(self.observation_payload, request)
self._build_inst_schedule(instname, self.observation_payload, request)
<|end_body_0|>
<|body_start_1|>
exp_time = request.payload['exposure_time']
exp_c... | An XML structure for LT IOO/IOI requests. | IOOIOIRequest | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IOOIOIRequest:
"""An XML structure for LT IOO/IOI requests."""
def __init__(self, instname, request):
"""Initialize IOO/IOI request. Parameters ---------- instname: str IO:O or IO:I. request: skyportal.models.FollowupRequest The request to add to the queue and the SkyPortal database.... | stack_v2_sparse_classes_36k_train_009992 | 27,052 | permissive | [
{
"docstring": "Initialize IOO/IOI request. Parameters ---------- instname: str IO:O or IO:I. request: skyportal.models.FollowupRequest The request to add to the queue and the SkyPortal database.",
"name": "__init__",
"signature": "def __init__(self, instname, request)"
},
{
"docstring": "Payloa... | 3 | null | Implement the Python class `IOOIOIRequest` described below.
Class description:
An XML structure for LT IOO/IOI requests.
Method signatures and docstrings:
- def __init__(self, instname, request): Initialize IOO/IOI request. Parameters ---------- instname: str IO:O or IO:I. request: skyportal.models.FollowupRequest Th... | Implement the Python class `IOOIOIRequest` described below.
Class description:
An XML structure for LT IOO/IOI requests.
Method signatures and docstrings:
- def __init__(self, instname, request): Initialize IOO/IOI request. Parameters ---------- instname: str IO:O or IO:I. request: skyportal.models.FollowupRequest Th... | 161d3532ba3ba059446addcdac58ca96f39e9636 | <|skeleton|>
class IOOIOIRequest:
"""An XML structure for LT IOO/IOI requests."""
def __init__(self, instname, request):
"""Initialize IOO/IOI request. Parameters ---------- instname: str IO:O or IO:I. request: skyportal.models.FollowupRequest The request to add to the queue and the SkyPortal database.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IOOIOIRequest:
"""An XML structure for LT IOO/IOI requests."""
def __init__(self, instname, request):
"""Initialize IOO/IOI request. Parameters ---------- instname: str IO:O or IO:I. request: skyportal.models.FollowupRequest The request to add to the queue and the SkyPortal database."""
s... | the_stack_v2_python_sparse | skyportal/facility_apis/lt.py | skyportal/skyportal | train | 80 |
7de5a7daa0c87564e6f5a853165ff86046fdf91c | [
"self.uk_1 = u_init\nself._is_angle = is_angle\nrc = 1.0 / (2.0 * np.pi * f_cutoff)\nself.alpha = dt / (rc + dt)\nself.u_init = u_init\nself.r_lim = r_cutoff * dt",
"if np.isfinite(value):\n if not self._is_angle:\n uk = self.uk_1 + self.alpha * (value - self.uk_1)\n uk = self._rate_limit(uk)\n ... | <|body_start_0|>
self.uk_1 = u_init
self._is_angle = is_angle
rc = 1.0 / (2.0 * np.pi * f_cutoff)
self.alpha = dt / (rc + dt)
self.u_init = u_init
self.r_lim = r_cutoff * dt
<|end_body_0|>
<|body_start_1|>
if np.isfinite(value):
if not self._is_angle:... | An RC low-pass filter for smoothing the command output that also includes a rate limitng funciton. | RateLimitedLowPass | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RateLimitedLowPass:
"""An RC low-pass filter for smoothing the command output that also includes a rate limitng funciton."""
def __init__(self, dt, f_cutoff, r_cutoff=1.0, u_init=0.0, is_angle=False):
"""Constructor Arguments: dt: filter sample time in seconds f_cutoff: rolloff frequ... | stack_v2_sparse_classes_36k_train_009993 | 5,482 | permissive | [
{
"docstring": "Constructor Arguments: dt: filter sample time in seconds f_cutoff: rolloff frequency in Hz r_cutoff: maximum rate of the signal in (signal/s) u_init: initial value is_angle: bool, defaults false, if true then wrap the signal between -pi and pi Returns: object",
"name": "__init__",
"signa... | 4 | null | Implement the Python class `RateLimitedLowPass` described below.
Class description:
An RC low-pass filter for smoothing the command output that also includes a rate limitng funciton.
Method signatures and docstrings:
- def __init__(self, dt, f_cutoff, r_cutoff=1.0, u_init=0.0, is_angle=False): Constructor Arguments: ... | Implement the Python class `RateLimitedLowPass` described below.
Class description:
An RC low-pass filter for smoothing the command output that also includes a rate limitng funciton.
Method signatures and docstrings:
- def __init__(self, dt, f_cutoff, r_cutoff=1.0, u_init=0.0, is_angle=False): Constructor Arguments: ... | 6827886916e36432ce1d806f0a78edef6c9270d9 | <|skeleton|>
class RateLimitedLowPass:
"""An RC low-pass filter for smoothing the command output that also includes a rate limitng funciton."""
def __init__(self, dt, f_cutoff, r_cutoff=1.0, u_init=0.0, is_angle=False):
"""Constructor Arguments: dt: filter sample time in seconds f_cutoff: rolloff frequ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RateLimitedLowPass:
"""An RC low-pass filter for smoothing the command output that also includes a rate limitng funciton."""
def __init__(self, dt, f_cutoff, r_cutoff=1.0, u_init=0.0, is_angle=False):
"""Constructor Arguments: dt: filter sample time in seconds f_cutoff: rolloff frequency in Hz r_... | the_stack_v2_python_sparse | pybots/src/filters/dynamical_filters.py | aivian/robots | train | 0 |
b9c4b621f0538dd39643839b00a5a003e146f007 | [
"self._clear_others = clear_others\nself._to_update = env_vars_to_update\nself._to_remove = env_vars_to_remove",
"del metadata\nif self._clear_others:\n config.env_vars.clear()\nelif self._to_remove:\n for env_var in self._to_remove:\n if env_var in config.env_vars:\n del config.env_vars[e... | <|body_start_0|>
self._clear_others = clear_others
self._to_update = env_vars_to_update
self._to_remove = env_vars_to_remove
<|end_body_0|>
<|body_start_1|>
del metadata
if self._clear_others:
config.env_vars.clear()
elif self._to_remove:
for env_... | Represents the user-intent to modify environment variables. | EnvVarChanges | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnvVarChanges:
"""Represents the user-intent to modify environment variables."""
def __init__(self, env_vars_to_update=None, env_vars_to_remove=None, clear_others=False):
"""Initialize a new EnvVarChanges object. Args: env_vars_to_update: {str, str}, Update env var names and values. ... | stack_v2_sparse_classes_36k_train_009994 | 3,547 | permissive | [
{
"docstring": "Initialize a new EnvVarChanges object. Args: env_vars_to_update: {str, str}, Update env var names and values. env_vars_to_remove: [str], List of env vars to remove. clear_others: bool, If true, clear all non-updated env vars.",
"name": "__init__",
"signature": "def __init__(self, env_var... | 2 | null | Implement the Python class `EnvVarChanges` described below.
Class description:
Represents the user-intent to modify environment variables.
Method signatures and docstrings:
- def __init__(self, env_vars_to_update=None, env_vars_to_remove=None, clear_others=False): Initialize a new EnvVarChanges object. Args: env_vars... | Implement the Python class `EnvVarChanges` described below.
Class description:
Represents the user-intent to modify environment variables.
Method signatures and docstrings:
- def __init__(self, env_vars_to_update=None, env_vars_to_remove=None, clear_others=False): Initialize a new EnvVarChanges object. Args: env_vars... | 1f9b424c40a87b46656fc9f5e2e9c81895c7e614 | <|skeleton|>
class EnvVarChanges:
"""Represents the user-intent to modify environment variables."""
def __init__(self, env_vars_to_update=None, env_vars_to_remove=None, clear_others=False):
"""Initialize a new EnvVarChanges object. Args: env_vars_to_update: {str, str}, Update env var names and values. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EnvVarChanges:
"""Represents the user-intent to modify environment variables."""
def __init__(self, env_vars_to_update=None, env_vars_to_remove=None, clear_others=False):
"""Initialize a new EnvVarChanges object. Args: env_vars_to_update: {str, str}, Update env var names and values. env_vars_to_r... | the_stack_v2_python_sparse | google-cloud-sdk/lib/googlecloudsdk/command_lib/serverless/config_changes.py | twistedpair/google-cloud-sdk | train | 58 |
d2882d003ac8bca512f6f624b2db5319224f5e3a | [
"self.ip = ip\nself.port = port\nself.token = token\nself.service = 'shcifco/dataapi'\nself.domain = 'http://' + ':'.join([self.ip, self.port])",
"url = '/'.join([self.domain, self.service, path])\nparams['token'] = self.token\nr = requests.get(url=url, params=params)\nif r.status_code != HTTP_OK:\n print(u'ht... | <|body_start_0|>
self.ip = ip
self.port = port
self.token = token
self.service = 'shcifco/dataapi'
self.domain = 'http://' + ':'.join([self.ip, self.port])
<|end_body_0|>
<|body_start_1|>
url = '/'.join([self.domain, self.service, path])
params['token'] = self.to... | 数据接口 | ShcifcoApi | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShcifcoApi:
"""数据接口"""
def __init__(self, ip, port, token):
"""Constructor"""
<|body_0|>
def getData(self, path, params):
"""下载数据"""
<|body_1|>
def getLastTick(self, symbol):
"""获取最新Tick"""
<|body_2|>
def getLastPrice(self, symbo... | stack_v2_sparse_classes_36k_train_009995 | 4,262 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, ip, port, token)"
},
{
"docstring": "下载数据",
"name": "getData",
"signature": "def getData(self, path, params)"
},
{
"docstring": "获取最新Tick",
"name": "getLastTick",
"signature": "def getLastT... | 6 | null | Implement the Python class `ShcifcoApi` described below.
Class description:
数据接口
Method signatures and docstrings:
- def __init__(self, ip, port, token): Constructor
- def getData(self, path, params): 下载数据
- def getLastTick(self, symbol): 获取最新Tick
- def getLastPrice(self, symbol): 获取最新成交价
- def getLastBar(self, symbo... | Implement the Python class `ShcifcoApi` described below.
Class description:
数据接口
Method signatures and docstrings:
- def __init__(self, ip, port, token): Constructor
- def getData(self, path, params): 下载数据
- def getLastTick(self, symbol): 获取最新Tick
- def getLastPrice(self, symbol): 获取最新成交价
- def getLastBar(self, symbo... | 75f95a00e7eb569cb7cc530ea55d6646ba4595c1 | <|skeleton|>
class ShcifcoApi:
"""数据接口"""
def __init__(self, ip, port, token):
"""Constructor"""
<|body_0|>
def getData(self, path, params):
"""下载数据"""
<|body_1|>
def getLastTick(self, symbol):
"""获取最新Tick"""
<|body_2|>
def getLastPrice(self, symbo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShcifcoApi:
"""数据接口"""
def __init__(self, ip, port, token):
"""Constructor"""
self.ip = ip
self.port = port
self.token = token
self.service = 'shcifco/dataapi'
self.domain = 'http://' + ':'.join([self.ip, self.port])
def getData(self, path, params):
... | the_stack_v2_python_sparse | vnpy/data/shcifco/vnshcifco.py | KilimanjaroFreeman/vnpy | train | 3 |
deec239cac777d1686d93df93e23797d6e50395c | [
"super(MenuPointer, self).__init__(image=MenuPointer.image, x=x, y=y, dx=0, dy=0)\nself.game = game\nself.selection = 0\nself.num_options = len(self.game.options) - 1\nself.menu = menu\nself.counter = 15",
"if self.counter > 0:\n self.counter -= 1\nif self.counter == 0:\n if self.num_options > 0:\n i... | <|body_start_0|>
super(MenuPointer, self).__init__(image=MenuPointer.image, x=x, y=y, dx=0, dy=0)
self.game = game
self.selection = 0
self.num_options = len(self.game.options) - 1
self.menu = menu
self.counter = 15
<|end_body_0|>
<|body_start_1|>
if self.counter ... | Pointer for highlighting and making selections on the game menus | MenuPointer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MenuPointer:
"""Pointer for highlighting and making selections on the game menus"""
def __init__(self, game, x, y, menu):
"""Initialize the sprite."""
<|body_0|>
def update(self):
"""Move the pointer up and down through the options list If the user hits enter pro... | stack_v2_sparse_classes_36k_train_009996 | 3,711 | no_license | [
{
"docstring": "Initialize the sprite.",
"name": "__init__",
"signature": "def __init__(self, game, x, y, menu)"
},
{
"docstring": "Move the pointer up and down through the options list If the user hits enter proceed with the selected option",
"name": "update",
"signature": "def update(s... | 4 | stack_v2_sparse_classes_30k_train_016880 | Implement the Python class `MenuPointer` described below.
Class description:
Pointer for highlighting and making selections on the game menus
Method signatures and docstrings:
- def __init__(self, game, x, y, menu): Initialize the sprite.
- def update(self): Move the pointer up and down through the options list If th... | Implement the Python class `MenuPointer` described below.
Class description:
Pointer for highlighting and making selections on the game menus
Method signatures and docstrings:
- def __init__(self, game, x, y, menu): Initialize the sprite.
- def update(self): Move the pointer up and down through the options list If th... | aab3e28ef659b9a62060940e752b22679b344fdf | <|skeleton|>
class MenuPointer:
"""Pointer for highlighting and making selections on the game menus"""
def __init__(self, game, x, y, menu):
"""Initialize the sprite."""
<|body_0|>
def update(self):
"""Move the pointer up and down through the options list If the user hits enter pro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MenuPointer:
"""Pointer for highlighting and making selections on the game menus"""
def __init__(self, game, x, y, menu):
"""Initialize the sprite."""
super(MenuPointer, self).__init__(image=MenuPointer.image, x=x, y=y, dx=0, dy=0)
self.game = game
self.selection = 0
... | the_stack_v2_python_sparse | bin/menuPointer.py | noelano/Portal | train | 0 |
19325c56955871b2a34775b00cfc9cb6ef9afce2 | [
"length = len(nums)\nif not length:\n return 0\nindex = 0\nearlier = None\nwhile index < length:\n if index == 0:\n earlier = nums[index]\n index += 1\n elif nums[index] == earlier:\n for i in range(index + 1, length):\n nums[i - 1] = nums[i]\n nums.pop()\n len... | <|body_start_0|>
length = len(nums)
if not length:
return 0
index = 0
earlier = None
while index < length:
if index == 0:
earlier = nums[index]
index += 1
elif nums[index] == earlier:
for i in ran... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeDuplicates_me(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def removeDuplicates(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
length = len(nums)
if no... | stack_v2_sparse_classes_36k_train_009997 | 1,248 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "removeDuplicates_me",
"signature": "def removeDuplicates_me(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "removeDuplicates",
"signature": "def removeDuplicates(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006807 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicates_me(self, nums): :type nums: List[int] :rtype: int
- def removeDuplicates(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 removeDuplicates_me(self, nums): :type nums: List[int] :rtype: int
- def removeDuplicates(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
de... | cefa2f08667de4d2973274de3ff29a31a7d25eda | <|skeleton|>
class Solution:
def removeDuplicates_me(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def removeDuplicates(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 removeDuplicates_me(self, nums):
""":type nums: List[int] :rtype: int"""
length = len(nums)
if not length:
return 0
index = 0
earlier = None
while index < length:
if index == 0:
earlier = nums[index]
... | the_stack_v2_python_sparse | play/first/26_Remove_Duplicates_from_Sorted_Array.py | zhangruochi/leetcode | train | 14 | |
aaa8806b1754ef891aab5cc7f520e1109a7e4b7a | [
"equipment_qs = Equipment.search(**search_info)\nequipment_qs.order_by('-create_time')\nreturn Splitor(current_page, equipment_qs)",
"for logistics in logistics_list:\n for logisticsitem in logistics.items:\n equipment_qs = Equipment.search(logistics_item=logisticsitem)\n logisticsitem.equipment_... | <|body_start_0|>
equipment_qs = Equipment.search(**search_info)
equipment_qs.order_by('-create_time')
return Splitor(current_page, equipment_qs)
<|end_body_0|>
<|body_start_1|>
for logistics in logistics_list:
for logisticsitem in logistics.items:
equipment_q... | EquipmentServer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EquipmentServer:
def search(cls, current_page, **search_info):
"""查询设备列表"""
<|body_0|>
def hung_code_bylogistics(cls, logistics_list):
"""根据物流详情挂载设备"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
equipment_qs = Equipment.search(**search_info)
... | stack_v2_sparse_classes_36k_train_009998 | 1,568 | no_license | [
{
"docstring": "查询设备列表",
"name": "search",
"signature": "def search(cls, current_page, **search_info)"
},
{
"docstring": "根据物流详情挂载设备",
"name": "hung_code_bylogistics",
"signature": "def hung_code_bylogistics(cls, logistics_list)"
}
] | 2 | null | Implement the Python class `EquipmentServer` described below.
Class description:
Implement the EquipmentServer class.
Method signatures and docstrings:
- def search(cls, current_page, **search_info): 查询设备列表
- def hung_code_bylogistics(cls, logistics_list): 根据物流详情挂载设备 | Implement the Python class `EquipmentServer` described below.
Class description:
Implement the EquipmentServer class.
Method signatures and docstrings:
- def search(cls, current_page, **search_info): 查询设备列表
- def hung_code_bylogistics(cls, logistics_list): 根据物流详情挂载设备
<|skeleton|>
class EquipmentServer:
def sear... | c22e772bc24381f7f57e1d6e41ae0289e7f11e57 | <|skeleton|>
class EquipmentServer:
def search(cls, current_page, **search_info):
"""查询设备列表"""
<|body_0|>
def hung_code_bylogistics(cls, logistics_list):
"""根据物流详情挂载设备"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EquipmentServer:
def search(cls, current_page, **search_info):
"""查询设备列表"""
equipment_qs = Equipment.search(**search_info)
equipment_qs.order_by('-create_time')
return Splitor(current_page, equipment_qs)
def hung_code_bylogistics(cls, logistics_list):
"""根据物流详情挂载设备... | the_stack_v2_python_sparse | codes/crm-be/tuoen/abs/service/equipment/manager.py | MaseraTiGo/Maserati_Go | train | 0 | |
85be6638fbe1047c8329aba0fa1aea4135867951 | [
"Controller.__init__(self, params)\nself.E_k = 0\nself.e_k_1 = 0",
"self.kp = params.kp\nself.ki = params.ki\nself.kd = params.kd",
"x_g, y_g = (state.goal.x, state.goal.y)\nx_r, y_r, theta = state.pose\ne_k = math.atan2(y_g - y_r, x_g - x_r) - theta\ne_k = math.atan2(math.sin(e_k), math.cos(e_k))\nself.E_k += ... | <|body_start_0|>
Controller.__init__(self, params)
self.E_k = 0
self.e_k_1 = 0
<|end_body_0|>
<|body_start_1|>
self.kp = params.kp
self.ki = params.ki
self.kd = params.kd
<|end_body_1|>
<|body_start_2|>
x_g, y_g = (state.goal.x, state.goal.y)
x_r, y_r, t... | Example of PID implementation for goal-seek | GoToGoal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoToGoal:
"""Example of PID implementation for goal-seek"""
def __init__(self, params):
"""init @params:"""
<|body_0|>
def set_parameters(self, params):
"""Set the PID Values @params: (float) kp, ki, kd"""
<|body_1|>
def execute(self, state, dt):
... | stack_v2_sparse_classes_36k_train_009999 | 1,591 | no_license | [
{
"docstring": "init @params:",
"name": "__init__",
"signature": "def __init__(self, params)"
},
{
"docstring": "Set the PID Values @params: (float) kp, ki, kd",
"name": "set_parameters",
"signature": "def set_parameters(self, params)"
},
{
"docstring": "Executes the controller b... | 3 | stack_v2_sparse_classes_30k_train_007666 | Implement the Python class `GoToGoal` described below.
Class description:
Example of PID implementation for goal-seek
Method signatures and docstrings:
- def __init__(self, params): init @params:
- def set_parameters(self, params): Set the PID Values @params: (float) kp, ki, kd
- def execute(self, state, dt): Execute... | Implement the Python class `GoToGoal` described below.
Class description:
Example of PID implementation for goal-seek
Method signatures and docstrings:
- def __init__(self, params): init @params:
- def set_parameters(self, params): Set the PID Values @params: (float) kp, ki, kd
- def execute(self, state, dt): Execute... | 4b2c92086d48cb7297793998714eded968674df0 | <|skeleton|>
class GoToGoal:
"""Example of PID implementation for goal-seek"""
def __init__(self, params):
"""init @params:"""
<|body_0|>
def set_parameters(self, params):
"""Set the PID Values @params: (float) kp, ki, kd"""
<|body_1|>
def execute(self, state, dt):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GoToGoal:
"""Example of PID implementation for goal-seek"""
def __init__(self, params):
"""init @params:"""
Controller.__init__(self, params)
self.E_k = 0
self.e_k_1 = 0
def set_parameters(self, params):
"""Set the PID Values @params: (float) kp, ki, kd"""
... | the_stack_v2_python_sparse | controllers/gotogoal.py | jamesclyeh/pysimiam | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.