blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d3c783e522474a2909db83b3b734cc9b4b2c54f2 | [
"self.fragments = {}\nself.rootFragments = []\nself.nextTxnId = 0",
"resumeFragment = TxnFragment(txn, resumeId=linkId)\nresumeKey = ResumeKey(linkId)\nresumeFragments = self.fragments.get(resumeKey, None)\nif not resumeFragments:\n resumeFragments = []\n self.fragments.update({resumeKey: resumeFragments})\... | <|body_start_0|>
self.fragments = {}
self.rootFragments = []
self.nextTxnId = 0
<|end_body_0|>
<|body_start_1|>
resumeFragment = TxnFragment(txn, resumeId=linkId)
resumeKey = ResumeKey(linkId)
resumeFragments = self.fragments.get(resumeKey, None)
if not resumeFra... | A collection of suspending and resuming transaction fragemnts | TxnFragments | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TxnFragments:
"""A collection of suspending and resuming transaction fragemnts"""
def __init__(self):
"""Constructs an instance of transaction fragment collection"""
<|body_0|>
def addResumeFragment(self, linkId, txn):
"""Adds a resuming transaction fragment to t... | stack_v2_sparse_classes_75kplus_train_006000 | 4,916 | permissive | [
{
"docstring": "Constructs an instance of transaction fragment collection",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Adds a resuming transaction fragment to the collection. Resuming fragments lookup for the previous suspended fragement to form a link :param linkId... | 5 | stack_v2_sparse_classes_30k_train_029248 | Implement the Python class `TxnFragments` described below.
Class description:
A collection of suspending and resuming transaction fragemnts
Method signatures and docstrings:
- def __init__(self): Constructs an instance of transaction fragment collection
- def addResumeFragment(self, linkId, txn): Adds a resuming tran... | Implement the Python class `TxnFragments` described below.
Class description:
A collection of suspending and resuming transaction fragemnts
Method signatures and docstrings:
- def __init__(self): Constructs an instance of transaction fragment collection
- def addResumeFragment(self, linkId, txn): Adds a resuming tran... | d6b67e98d4b640c98499a373425f1f009e5b9061 | <|skeleton|>
class TxnFragments:
"""A collection of suspending and resuming transaction fragemnts"""
def __init__(self):
"""Constructs an instance of transaction fragment collection"""
<|body_0|>
def addResumeFragment(self, linkId, txn):
"""Adds a resuming transaction fragment to t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TxnFragments:
"""A collection of suspending and resuming transaction fragemnts"""
def __init__(self):
"""Constructs an instance of transaction fragment collection"""
self.fragments = {}
self.rootFragments = []
self.nextTxnId = 0
def addResumeFragment(self, linkId, txn... | the_stack_v2_python_sparse | scripts/lib/xpedite/txn/fragments.py | dendisuhubdy/Xpedite | train | 1 |
de657f6e41f4b3a2951491b151a73910da459499 | [
"lo, hi = (max(nums), sum(nums))\nwhile lo < hi:\n mid = lo + (hi - lo) // 2\n cnt = 0\n curr = 0\n for num in nums:\n if curr + num <= mid:\n curr += num\n else:\n cnt += 1\n curr = num\n if cnt >= m:\n lo = mid + 1\n else:\n hi = mid\n... | <|body_start_0|>
lo, hi = (max(nums), sum(nums))
while lo < hi:
mid = lo + (hi - lo) // 2
cnt = 0
curr = 0
for num in nums:
if curr + num <= mid:
curr += num
else:
cnt += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def splitArray1(self, nums: List[int], m: int) -> int:
"""binary search"""
<|body_0|>
def splitArray2(self, nums: List[int], m: int) -> int:
"""dynamic programming: define dp[i][j] as minimum largest subarray sum for splitting nums[0..j] in i parts time: O(... | stack_v2_sparse_classes_75kplus_train_006001 | 2,009 | no_license | [
{
"docstring": "binary search",
"name": "splitArray1",
"signature": "def splitArray1(self, nums: List[int], m: int) -> int"
},
{
"docstring": "dynamic programming: define dp[i][j] as minimum largest subarray sum for splitting nums[0..j] in i parts time: O(MN^2) space: O(MN)",
"name": "splitA... | 2 | stack_v2_sparse_classes_30k_train_020576 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def splitArray1(self, nums: List[int], m: int) -> int: binary search
- def splitArray2(self, nums: List[int], m: int) -> int: dynamic programming: define dp[i][j] as minimum larg... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def splitArray1(self, nums: List[int], m: int) -> int: binary search
- def splitArray2(self, nums: List[int], m: int) -> int: dynamic programming: define dp[i][j] as minimum larg... | 6ff1941ff213a843013100ac7033e2d4f90fbd6a | <|skeleton|>
class Solution:
def splitArray1(self, nums: List[int], m: int) -> int:
"""binary search"""
<|body_0|>
def splitArray2(self, nums: List[int], m: int) -> int:
"""dynamic programming: define dp[i][j] as minimum largest subarray sum for splitting nums[0..j] in i parts time: O(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def splitArray1(self, nums: List[int], m: int) -> int:
"""binary search"""
lo, hi = (max(nums), sum(nums))
while lo < hi:
mid = lo + (hi - lo) // 2
cnt = 0
curr = 0
for num in nums:
if curr + num <= mid:
... | the_stack_v2_python_sparse | Leetcode 0410. Split Array Largest Sum.py | Chaoran-sjsu/leetcode | train | 0 | |
5214ef7af28235be78ecae59458aded32c00b3ee | [
"super().__init__()\nself.keys = []\nself.freq = {}",
"if key is not None and item is not None:\n if len(self.keys) >= BaseCaching.MAX_ITEMS and key not in self.keys:\n lfu = self.keys.pop(self.keys.index(self.find_lessFreq()))\n del self.freq[lfu]\n del self.cache_data[lfu]\n print... | <|body_start_0|>
super().__init__()
self.keys = []
self.freq = {}
<|end_body_0|>
<|body_start_1|>
if key is not None and item is not None:
if len(self.keys) >= BaseCaching.MAX_ITEMS and key not in self.keys:
lfu = self.keys.pop(self.keys.index(self.find_lessF... | manage the cache | LFUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LFUCache:
"""manage the cache"""
def __init__(self):
"""auto call function"""
<|body_0|>
def put(self, key, item):
"""add an item in the cache using Least-frequently used"""
<|body_1|>
def get(self, key):
"""Get an item by key using LFU"""
... | stack_v2_sparse_classes_75kplus_train_006002 | 1,623 | no_license | [
{
"docstring": "auto call function",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "add an item in the cache using Least-frequently used",
"name": "put",
"signature": "def put(self, key, item)"
},
{
"docstring": "Get an item by key using LFU",
"name"... | 4 | stack_v2_sparse_classes_30k_train_049555 | Implement the Python class `LFUCache` described below.
Class description:
manage the cache
Method signatures and docstrings:
- def __init__(self): auto call function
- def put(self, key, item): add an item in the cache using Least-frequently used
- def get(self, key): Get an item by key using LFU
- def find_lessFreq(... | Implement the Python class `LFUCache` described below.
Class description:
manage the cache
Method signatures and docstrings:
- def __init__(self): auto call function
- def put(self, key, item): add an item in the cache using Least-frequently used
- def get(self, key): Get an item by key using LFU
- def find_lessFreq(... | 251d28c9b555096c61a7112ada43dc65576d03c5 | <|skeleton|>
class LFUCache:
"""manage the cache"""
def __init__(self):
"""auto call function"""
<|body_0|>
def put(self, key, item):
"""add an item in the cache using Least-frequently used"""
<|body_1|>
def get(self, key):
"""Get an item by key using LFU"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LFUCache:
"""manage the cache"""
def __init__(self):
"""auto call function"""
super().__init__()
self.keys = []
self.freq = {}
def put(self, key, item):
"""add an item in the cache using Least-frequently used"""
if key is not None and item is not None:... | the_stack_v2_python_sparse | 0x03-caching/100-lfu_cache.py | dgquintero/holbertonschool-web_back_end | train | 0 |
0000676cc93b8e397479fab7fc4b243e12d0a16a | [
"if type(data) is not np.ndarray or len(data.shape) != 2:\n raise TypeError('data must be a 2D numpy.ndarray')\nd, n = data.shape\nif n < 2:\n raise ValueError('data must contain multiple data points')\nmean = np.mean(data, axis=1, keepdims=True)\nself.mean = mean\ncov = np.matmul(data - mean, data.T - mean.T... | <|body_start_0|>
if type(data) is not np.ndarray or len(data.shape) != 2:
raise TypeError('data must be a 2D numpy.ndarray')
d, n = data.shape
if n < 2:
raise ValueError('data must contain multiple data points')
mean = np.mean(data, axis=1, keepdims=True)
... | Class that represents Multivariate Normal Distribution class constructor: def __init__(self, data) public instance variables: mean [numpy.ndarray of shape (d, 1)]: contains the mean of data cov [numpy.ndarray of shape (d, d)]: contains the covariance matrix of data public instance method: def pdf(self, x): calculates t... | MultiNormal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiNormal:
"""Class that represents Multivariate Normal Distribution class constructor: def __init__(self, data) public instance variables: mean [numpy.ndarray of shape (d, 1)]: contains the mean of data cov [numpy.ndarray of shape (d, d)]: contains the covariance matrix of data public instance... | stack_v2_sparse_classes_75kplus_train_006003 | 2,274 | no_license | [
{
"docstring": "Class constructor parameters: data [numpy.ndarray of shape (d, n)]: contains the data set d: number of dimensions in each data point n: number of data points",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "Calculates the PDF at a data point parame... | 2 | stack_v2_sparse_classes_30k_train_003122 | Implement the Python class `MultiNormal` described below.
Class description:
Class that represents Multivariate Normal Distribution class constructor: def __init__(self, data) public instance variables: mean [numpy.ndarray of shape (d, 1)]: contains the mean of data cov [numpy.ndarray of shape (d, d)]: contains the co... | Implement the Python class `MultiNormal` described below.
Class description:
Class that represents Multivariate Normal Distribution class constructor: def __init__(self, data) public instance variables: mean [numpy.ndarray of shape (d, 1)]: contains the mean of data cov [numpy.ndarray of shape (d, d)]: contains the co... | 8834b201ca84937365e4dcc0fac978656cdf5293 | <|skeleton|>
class MultiNormal:
"""Class that represents Multivariate Normal Distribution class constructor: def __init__(self, data) public instance variables: mean [numpy.ndarray of shape (d, 1)]: contains the mean of data cov [numpy.ndarray of shape (d, d)]: contains the covariance matrix of data public instance... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiNormal:
"""Class that represents Multivariate Normal Distribution class constructor: def __init__(self, data) public instance variables: mean [numpy.ndarray of shape (d, 1)]: contains the mean of data cov [numpy.ndarray of shape (d, d)]: contains the covariance matrix of data public instance method: def ... | the_stack_v2_python_sparse | math/0x06-multivariate_prob/multinormal.py | ejonakodra/holbertonschool-machine_learning-1 | train | 0 |
3d2e01c99ec4c3a8cd5f88d4ced9016fa5dd17d9 | [
"for fea in [pay_date, finish_date]:\n df[fea] = pd.to_datetime(df[fea])\ndf[f'{finish_date}_af_proc'] = df[finish_date]\nidx = (df[pay_date] < ref_date) & pd.isnull(df[finish_date])\ndf.loc[idx, f'{finish_date}_af_proc'] = ref_date\ndf['ovd_days'] = (df[f'{finish_date}_af_proc'] - df[pay_date]).dt.days\nreturn ... | <|body_start_0|>
for fea in [pay_date, finish_date]:
df[fea] = pd.to_datetime(df[fea])
df[f'{finish_date}_af_proc'] = df[finish_date]
idx = (df[pay_date] < ref_date) & pd.isnull(df[finish_date])
df.loc[idx, f'{finish_date}_af_proc'] = ref_date
df['ovd_days'] = (df[f'{... | get ovd information | GetOvdInform | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetOvdInform:
"""get ovd information"""
def _calc_ovd_days(self, df, pay_date, finish_date, ref_date):
"""repay = _calc_ovd_days(repay, pay_date='PAYDATE', finish_date='FINISHDATE', ref_date=pd.to_datetime((dt.datetime.now()).strftime("%Y-%m-%d"))- dt.timedelta(days=0))"""
<|... | stack_v2_sparse_classes_75kplus_train_006004 | 32,015 | no_license | [
{
"docstring": "repay = _calc_ovd_days(repay, pay_date='PAYDATE', finish_date='FINISHDATE', ref_date=pd.to_datetime((dt.datetime.now()).strftime(\"%Y-%m-%d\"))- dt.timedelta(days=0))",
"name": "_calc_ovd_days",
"signature": "def _calc_ovd_days(self, df, pay_date, finish_date, ref_date)"
},
{
"do... | 3 | stack_v2_sparse_classes_30k_test_000569 | Implement the Python class `GetOvdInform` described below.
Class description:
get ovd information
Method signatures and docstrings:
- def _calc_ovd_days(self, df, pay_date, finish_date, ref_date): repay = _calc_ovd_days(repay, pay_date='PAYDATE', finish_date='FINISHDATE', ref_date=pd.to_datetime((dt.datetime.now()).s... | Implement the Python class `GetOvdInform` described below.
Class description:
get ovd information
Method signatures and docstrings:
- def _calc_ovd_days(self, df, pay_date, finish_date, ref_date): repay = _calc_ovd_days(repay, pay_date='PAYDATE', finish_date='FINISHDATE', ref_date=pd.to_datetime((dt.datetime.now()).s... | 2b6812fcd8a7414e606cc3f5964b171503683144 | <|skeleton|>
class GetOvdInform:
"""get ovd information"""
def _calc_ovd_days(self, df, pay_date, finish_date, ref_date):
"""repay = _calc_ovd_days(repay, pay_date='PAYDATE', finish_date='FINISHDATE', ref_date=pd.to_datetime((dt.datetime.now()).strftime("%Y-%m-%d"))- dt.timedelta(days=0))"""
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GetOvdInform:
"""get ovd information"""
def _calc_ovd_days(self, df, pay_date, finish_date, ref_date):
"""repay = _calc_ovd_days(repay, pay_date='PAYDATE', finish_date='FINISHDATE', ref_date=pd.to_datetime((dt.datetime.now()).strftime("%Y-%m-%d"))- dt.timedelta(days=0))"""
for fea in [pay... | the_stack_v2_python_sparse | model_tools/model_tools/gentools/advtools.py | yanghaitian1/risk_control | train | 3 |
6467bd2586116182eb4e4444fba33e0c7cac87cc | [
"super(SleepModule, self).__init__(eventid)\nif seconds is not None:\n self.seconds = seconds",
"if self.seconds is None:\n self.seconds = 60\ntime.sleep(self.seconds)",
"parser = argparse.ArgumentParser(prog=self.__class__.command_name, description=inspect.getdoc(self.__class__))\nparser.add_argument('-s... | <|body_start_0|>
super(SleepModule, self).__init__(eventid)
if seconds is not None:
self.seconds = seconds
<|end_body_0|>
<|body_start_1|>
if self.seconds is None:
self.seconds = 60
time.sleep(self.seconds)
<|end_body_1|>
<|body_start_2|>
parser = argpar... | sleep -- Sleep for a number of seconds. | SleepModule | [
"LicenseRef-scancode-warranty-disclaimer",
"CC0-1.0",
"Python-2.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SleepModule:
"""sleep -- Sleep for a number of seconds."""
def __init__(self, eventid, seconds=None):
"""Instantiate a SleepModule class with an event ID."""
<|body_0|>
def execute(self):
"""Sleep for the specified number of seconds and return. The default is 60 ... | stack_v2_sparse_classes_75kplus_train_006005 | 1,885 | permissive | [
{
"docstring": "Instantiate a SleepModule class with an event ID.",
"name": "__init__",
"signature": "def __init__(self, eventid, seconds=None)"
},
{
"docstring": "Sleep for the specified number of seconds and return. The default is 60 seconds.",
"name": "execute",
"signature": "def exec... | 3 | null | Implement the Python class `SleepModule` described below.
Class description:
sleep -- Sleep for a number of seconds.
Method signatures and docstrings:
- def __init__(self, eventid, seconds=None): Instantiate a SleepModule class with an event ID.
- def execute(self): Sleep for the specified number of seconds and retur... | Implement the Python class `SleepModule` described below.
Class description:
sleep -- Sleep for a number of seconds.
Method signatures and docstrings:
- def __init__(self, eventid, seconds=None): Instantiate a SleepModule class with an event ID.
- def execute(self): Sleep for the specified number of seconds and retur... | 8094736e43cc8043044344116b064917d5560c5a | <|skeleton|>
class SleepModule:
"""sleep -- Sleep for a number of seconds."""
def __init__(self, eventid, seconds=None):
"""Instantiate a SleepModule class with an event ID."""
<|body_0|>
def execute(self):
"""Sleep for the specified number of seconds and return. The default is 60 ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SleepModule:
"""sleep -- Sleep for a number of seconds."""
def __init__(self, eventid, seconds=None):
"""Instantiate a SleepModule class with an event ID."""
super(SleepModule, self).__init__(eventid)
if seconds is not None:
self.seconds = seconds
def execute(self... | the_stack_v2_python_sparse | shakemap/coremods/sleep.py | GeoscienceAustralia/shakemap | train | 1 |
103261cc468986a50d33c722268da8b594e15a42 | [
"x_dict = [{} for x in range(9)]\ny_dict = [{} for y in range(9)]\nbox_dict = [{} for box in range(9)]\nfor i in range(9):\n for j in range(9):\n try:\n num = int(board[i][j])\n box_index = i // 3 * 3 + j // 3\n x_dict[i][num] = x_dict[i].get(num, 0) + 1\n if x_... | <|body_start_0|>
x_dict = [{} for x in range(9)]
y_dict = [{} for y in range(9)]
box_dict = [{} for box in range(9)]
for i in range(9):
for j in range(9):
try:
num = int(board[i][j])
box_index = i // 3 * 3 + j // 3
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isValidSudoku(self, board):
""":type board: List[List[str]] :rtype: bool"""
<|body_0|>
def isValidSudoku1(self, board):
""":type board: List[List[str]] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
x_dict = [{} for x in ... | stack_v2_sparse_classes_75kplus_train_006006 | 1,886 | no_license | [
{
"docstring": ":type board: List[List[str]] :rtype: bool",
"name": "isValidSudoku",
"signature": "def isValidSudoku(self, board)"
},
{
"docstring": ":type board: List[List[str]] :rtype: bool",
"name": "isValidSudoku1",
"signature": "def isValidSudoku1(self, board)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000320 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValidSudoku(self, board): :type board: List[List[str]] :rtype: bool
- def isValidSudoku1(self, board): :type board: List[List[str]] :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValidSudoku(self, board): :type board: List[List[str]] :rtype: bool
- def isValidSudoku1(self, board): :type board: List[List[str]] :rtype: bool
<|skeleton|>
class Solutio... | b8ec1350e904665f1375c29a53f443ecf262d723 | <|skeleton|>
class Solution:
def isValidSudoku(self, board):
""":type board: List[List[str]] :rtype: bool"""
<|body_0|>
def isValidSudoku1(self, board):
""":type board: List[List[str]] :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isValidSudoku(self, board):
""":type board: List[List[str]] :rtype: bool"""
x_dict = [{} for x in range(9)]
y_dict = [{} for y in range(9)]
box_dict = [{} for box in range(9)]
for i in range(9):
for j in range(9):
try:
... | the_stack_v2_python_sparse | leetcode/036有效的数独.py | ShawDa/Coding | train | 0 | |
d1ce8e77935501fe84c118ad30fb58b84de1177d | [
"super(Conv1d, self).__init__()\nif kernel_size % 2 == 0:\n padding = kernel_size // 2 * dilation\n self.shift = True\nelse:\n padding = (kernel_size - 1) // 2 * dilation\n self.shift = False\nself.conv = nn.Conv1d(hidden_size, hidden_size, kernel_size, padding=padding, dilation=dilation)",
"if self.s... | <|body_start_0|>
super(Conv1d, self).__init__()
if kernel_size % 2 == 0:
padding = kernel_size // 2 * dilation
self.shift = True
else:
padding = (kernel_size - 1) // 2 * dilation
self.shift = False
self.conv = nn.Conv1d(hidden_size, hidden_... | 1D convolution layer. | Conv1d | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Conv1d:
"""1D convolution layer."""
def __init__(self, hidden_size, kernel_size, dilation=1):
"""Initialization. Args: hidden_size: dimension of input embeddings kernel_size: convolution kernel size dilation: the spacing between the kernel points"""
<|body_0|>
def forwar... | stack_v2_sparse_classes_75kplus_train_006007 | 8,877 | permissive | [
{
"docstring": "Initialization. Args: hidden_size: dimension of input embeddings kernel_size: convolution kernel size dilation: the spacing between the kernel points",
"name": "__init__",
"signature": "def __init__(self, hidden_size, kernel_size, dilation=1)"
},
{
"docstring": "Compute convoluti... | 2 | null | Implement the Python class `Conv1d` described below.
Class description:
1D convolution layer.
Method signatures and docstrings:
- def __init__(self, hidden_size, kernel_size, dilation=1): Initialization. Args: hidden_size: dimension of input embeddings kernel_size: convolution kernel size dilation: the spacing betwee... | Implement the Python class `Conv1d` described below.
Class description:
1D convolution layer.
Method signatures and docstrings:
- def __init__(self, hidden_size, kernel_size, dilation=1): Initialization. Args: hidden_size: dimension of input embeddings kernel_size: convolution kernel size dilation: the spacing betwee... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class Conv1d:
"""1D convolution layer."""
def __init__(self, hidden_size, kernel_size, dilation=1):
"""Initialization. Args: hidden_size: dimension of input embeddings kernel_size: convolution kernel size dilation: the spacing between the kernel points"""
<|body_0|>
def forwar... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Conv1d:
"""1D convolution layer."""
def __init__(self, hidden_size, kernel_size, dilation=1):
"""Initialization. Args: hidden_size: dimension of input embeddings kernel_size: convolution kernel size dilation: the spacing between the kernel points"""
super(Conv1d, self).__init__()
... | the_stack_v2_python_sparse | structformer/layers.py | Jimmy-INL/google-research | train | 1 |
03db52a047d3856a481e5c4e32d2a680f5b21c9d | [
"nums.sort()\nhalf = len(nums[::2]) - 1\nnums[::2], nums[1::2] = (nums[half::-1], nums[:half:-1])",
"nums.sort()\nhalf = len(nums[::2])\nnums[::2], nums[1::2] = (nums[:half][::-1], nums[half:][::-1])"
] | <|body_start_0|>
nums.sort()
half = len(nums[::2]) - 1
nums[::2], nums[1::2] = (nums[half::-1], nums[:half:-1])
<|end_body_0|>
<|body_start_1|>
nums.sort()
half = len(nums[::2])
nums[::2], nums[1::2] = (nums[:half][::-1], nums[half:][::-1])
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wiggleSort(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. nums: [1, 5, 1, 1, 6, 4] sort: [1, 1, 1, 4, 5, 6] nums[half::-1] => [1, 1, 1] nums[:half:-1] => [6, 5, 4] beats 96.09%"""
<|body_0|>
def wiggleSo... | stack_v2_sparse_classes_75kplus_train_006008 | 912 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. nums: [1, 5, 1, 1, 6, 4] sort: [1, 1, 1, 4, 5, 6] nums[half::-1] => [1, 1, 1] nums[:half:-1] => [6, 5, 4] beats 96.09%",
"name": "wiggleSort",
"signature": "def wiggleSort(self, nums)"
},
{
"... | 2 | stack_v2_sparse_classes_30k_train_002879 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wiggleSort(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. nums: [1, 5, 1, 1, 6, 4] sort: [1, 1, 1, 4, 5, 6] nums[half::... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wiggleSort(self, nums): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. nums: [1, 5, 1, 1, 6, 4] sort: [1, 1, 1, 4, 5, 6] nums[half::... | 7e0e917c15d3e35f49da3a00ef395bd5ff180d79 | <|skeleton|>
class Solution:
def wiggleSort(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. nums: [1, 5, 1, 1, 6, 4] sort: [1, 1, 1, 4, 5, 6] nums[half::-1] => [1, 1, 1] nums[:half:-1] => [6, 5, 4] beats 96.09%"""
<|body_0|>
def wiggleSo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def wiggleSort(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. nums: [1, 5, 1, 1, 6, 4] sort: [1, 1, 1, 4, 5, 6] nums[half::-1] => [1, 1, 1] nums[:half:-1] => [6, 5, 4] beats 96.09%"""
nums.sort()
half = len(nums[::2]) ... | the_stack_v2_python_sparse | LeetCode/324_wiggle_sort_ii.py | yao23/Machine_Learning_Playground | train | 12 | |
9f77000fba4809829eb5dd4e313488b10c14cf5f | [
"self.organisms = 0\nself.hyperparameters = hyperparameters\nself.grid_dim = self.hyperparameters['grid_dim']\nself.mutation_prob = self.hyperparameters['mutation_prob']\nself.replication_prob = self.hyperparameters['replication_prob']\nself.grid_range = list(range(self.grid_dim))\nself.grid = [None for _ in range(... | <|body_start_0|>
self.organisms = 0
self.hyperparameters = hyperparameters
self.grid_dim = self.hyperparameters['grid_dim']
self.mutation_prob = self.hyperparameters['mutation_prob']
self.replication_prob = self.hyperparameters['replication_prob']
self.grid_range = list(r... | 1-Dimensional grid containing replicators -- the medium with which replication occurs | ReplicationGrid | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReplicationGrid:
"""1-Dimensional grid containing replicators -- the medium with which replication occurs"""
def __init__(self, hyperparameters):
"""Initialize grid parameters :param hyperparameters: (dict) dictionary of hyperparameters"""
<|body_0|>
def step(self):
... | stack_v2_sparse_classes_75kplus_train_006009 | 8,990 | permissive | [
{
"docstring": "Initialize grid parameters :param hyperparameters: (dict) dictionary of hyperparameters",
"name": "__init__",
"signature": "def __init__(self, hyperparameters)"
},
{
"docstring": "Replicator's interaction with environment including replication, creation, and death :return: (list(... | 4 | stack_v2_sparse_classes_30k_train_034909 | Implement the Python class `ReplicationGrid` described below.
Class description:
1-Dimensional grid containing replicators -- the medium with which replication occurs
Method signatures and docstrings:
- def __init__(self, hyperparameters): Initialize grid parameters :param hyperparameters: (dict) dictionary of hyperp... | Implement the Python class `ReplicationGrid` described below.
Class description:
1-Dimensional grid containing replicators -- the medium with which replication occurs
Method signatures and docstrings:
- def __init__(self, hyperparameters): Initialize grid parameters :param hyperparameters: (dict) dictionary of hyperp... | 1a6f8225378b59423a97b439b56710bbed2754e9 | <|skeleton|>
class ReplicationGrid:
"""1-Dimensional grid containing replicators -- the medium with which replication occurs"""
def __init__(self, hyperparameters):
"""Initialize grid parameters :param hyperparameters: (dict) dictionary of hyperparameters"""
<|body_0|>
def step(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReplicationGrid:
"""1-Dimensional grid containing replicators -- the medium with which replication occurs"""
def __init__(self, hyperparameters):
"""Initialize grid parameters :param hyperparameters: (dict) dictionary of hyperparameters"""
self.organisms = 0
self.hyperparameters =... | the_stack_v2_python_sparse | evo_replicators/evolutionary_replicator.py | SamuelSchmidgall/EvolutionarySelfReplication | train | 14 |
e4d75d2769f74d1f9ba4b03f8459536e8890a1dc | [
"self.x = x\nself.coef = coef\nself.kernelEval = kernelEval",
"if y.ndim == 1:\n keval = pairwise_distances(self.x, y.reshape(1, -1), self.kernelEval).squeeze()\n return keval.dot(self.coef)\nelif y.ndim == 2:\n keval = pairwise_distances(self.x, y, self.kernelEval)\n return keval.T.dot(self.coef)\nel... | <|body_start_0|>
self.x = x
self.coef = coef
self.kernelEval = kernelEval
<|end_body_0|>
<|body_start_1|>
if y.ndim == 1:
keval = pairwise_distances(self.x, y.reshape(1, -1), self.kernelEval).squeeze()
return keval.dot(self.coef)
elif y.ndim == 2:
... | KernelSpan | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KernelSpan:
def __init__(self, x, coef, kernelEval):
""":type x: 2d array :param x: data points, each row is a data point :type coef: 1d array :param coef: expansion loadings :param kernelEval: :return:"""
<|body_0|>
def __call__(self, y):
"""Evaluation of the kernel... | stack_v2_sparse_classes_75kplus_train_006010 | 12,141 | no_license | [
{
"docstring": ":type x: 2d array :param x: data points, each row is a data point :type coef: 1d array :param coef: expansion loadings :param kernelEval: :return:",
"name": "__init__",
"signature": "def __init__(self, x, coef, kernelEval)"
},
{
"docstring": "Evaluation of the kernel span at one ... | 2 | null | Implement the Python class `KernelSpan` described below.
Class description:
Implement the KernelSpan class.
Method signatures and docstrings:
- def __init__(self, x, coef, kernelEval): :type x: 2d array :param x: data points, each row is a data point :type coef: 1d array :param coef: expansion loadings :param kernelE... | Implement the Python class `KernelSpan` described below.
Class description:
Implement the KernelSpan class.
Method signatures and docstrings:
- def __init__(self, x, coef, kernelEval): :type x: 2d array :param x: data points, each row is a data point :type coef: 1d array :param coef: expansion loadings :param kernelE... | 066595d8b4d96b8ad6b3fe48ef941412b355ca67 | <|skeleton|>
class KernelSpan:
def __init__(self, x, coef, kernelEval):
""":type x: 2d array :param x: data points, each row is a data point :type coef: 1d array :param coef: expansion loadings :param kernelEval: :return:"""
<|body_0|>
def __call__(self, y):
"""Evaluation of the kernel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KernelSpan:
def __init__(self, x, coef, kernelEval):
""":type x: 2d array :param x: data points, each row is a data point :type coef: 1d array :param coef: expansion loadings :param kernelEval: :return:"""
self.x = x
self.coef = coef
self.kernelEval = kernelEval
def __call... | the_stack_v2_python_sparse | okgtreg/Kernel.py | pancodia/OKGTreg | train | 0 | |
669e3e0aefdd316cde52ab54baf39da693c12c54 | [
"self.k = k\nself.heap = nums\nheapq.heapify(self.heap)\nreduce = len(nums) - k\nwhile reduce > 0:\n heapq.heappop(self.heap)\n reduce -= 1",
"heapq.heappush(self.heap, val)\nif len(self.heap) > self.k:\n heapq.heappop(self.heap)\nreturn self.heap[0]"
] | <|body_start_0|>
self.k = k
self.heap = nums
heapq.heapify(self.heap)
reduce = len(nums) - k
while reduce > 0:
heapq.heappop(self.heap)
reduce -= 1
<|end_body_0|>
<|body_start_1|>
heapq.heappush(self.heap, val)
if len(self.heap) > self.k:
... | KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.k = k
self.heap = nums
heapq.heapify(... | stack_v2_sparse_classes_75kplus_train_006011 | 875 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_044518 | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, nu... | 85128e7d26157b3c36eb43868269de42ea2fcb98 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
self.k = k
self.heap = nums
heapq.heapify(self.heap)
reduce = len(nums) - k
while reduce > 0:
heapq.heappop(self.heap)
reduce -= 1
def add(self, val):
... | the_stack_v2_python_sparse | src/KthLargest.py | jsdiuf/leetcode | train | 1 | |
1e9cd14c126d3471fd52137100977ed7cb0854cb | [
"func_name = sys._getframe().f_code.co_name\nres = self.get_result(func_name)\nexpect_result = self.get_expect_result(func_name)\nactivityInfo_list = res[0].json()['data']\nactual_result = res[0].json()['errmsg']\nself.assertIn(actual_result, expect_result)\nself.assertIsNotNone(activityInfo_list)\ngl.set_value('ac... | <|body_start_0|>
func_name = sys._getframe().f_code.co_name
res = self.get_result(func_name)
expect_result = self.get_expect_result(func_name)
activityInfo_list = res[0].json()['data']
actual_result = res[0].json()['errmsg']
self.assertIn(actual_result, expect_result)
... | OperationActivityConfiguration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OperationActivityConfiguration:
def test_urine_v2_activityInfo_list(self):
"""运营活动配置列表 :return:"""
<|body_0|>
def test_urine_v2_activityInfo_update(self):
"""更新运营活动配置信息 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
func_name = sys._getfra... | stack_v2_sparse_classes_75kplus_train_006012 | 1,847 | no_license | [
{
"docstring": "运营活动配置列表 :return:",
"name": "test_urine_v2_activityInfo_list",
"signature": "def test_urine_v2_activityInfo_list(self)"
},
{
"docstring": "更新运营活动配置信息 :return:",
"name": "test_urine_v2_activityInfo_update",
"signature": "def test_urine_v2_activityInfo_update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_val_002540 | Implement the Python class `OperationActivityConfiguration` described below.
Class description:
Implement the OperationActivityConfiguration class.
Method signatures and docstrings:
- def test_urine_v2_activityInfo_list(self): 运营活动配置列表 :return:
- def test_urine_v2_activityInfo_update(self): 更新运营活动配置信息 :return: | Implement the Python class `OperationActivityConfiguration` described below.
Class description:
Implement the OperationActivityConfiguration class.
Method signatures and docstrings:
- def test_urine_v2_activityInfo_list(self): 运营活动配置列表 :return:
- def test_urine_v2_activityInfo_update(self): 更新运营活动配置信息 :return:
<|ske... | 6837a07ff200b610e7ba799a52543493848b6026 | <|skeleton|>
class OperationActivityConfiguration:
def test_urine_v2_activityInfo_list(self):
"""运营活动配置列表 :return:"""
<|body_0|>
def test_urine_v2_activityInfo_update(self):
"""更新运营活动配置信息 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OperationActivityConfiguration:
def test_urine_v2_activityInfo_list(self):
"""运营活动配置列表 :return:"""
func_name = sys._getframe().f_code.co_name
res = self.get_result(func_name)
expect_result = self.get_expect_result(func_name)
activityInfo_list = res[0].json()['data']
... | the_stack_v2_python_sparse | run/operation_management/test_operation_activity_configuration.py | liwei123a/APITestFrame | train | 0 | |
6f226064f895be5a5f4d529f3959ccaca29a056a | [
"rmg_path = os.path.normpath(os.path.join(get_path(), '..'))\nself.settings1 = QMSettings(software='mopac', method='pm3', fileStore=os.path.join(rmg_path, 'testing', 'qm', 'QMfiles'), scratchDirectory=None, onlyCyclics=False, maxRadicalNumber=0)\nself.settings2 = QMSettings()",
"try:\n self.settings1.check_all... | <|body_start_0|>
rmg_path = os.path.normpath(os.path.join(get_path(), '..'))
self.settings1 = QMSettings(software='mopac', method='pm3', fileStore=os.path.join(rmg_path, 'testing', 'qm', 'QMfiles'), scratchDirectory=None, onlyCyclics=False, maxRadicalNumber=0)
self.settings2 = QMSettings()
<|end... | Contains unit tests for the QMSettings class. | TestQMSettings | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestQMSettings:
"""Contains unit tests for the QMSettings class."""
def setUp(self):
"""A function run before each unit test in this class."""
<|body_0|>
def test_check_all_set(self):
"""Test that check_all_set() works correctly."""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_75kplus_train_006013 | 14,056 | permissive | [
{
"docstring": "A function run before each unit test in this class.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test that check_all_set() works correctly.",
"name": "test_check_all_set",
"signature": "def test_check_all_set(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_049186 | Implement the Python class `TestQMSettings` described below.
Class description:
Contains unit tests for the QMSettings class.
Method signatures and docstrings:
- def setUp(self): A function run before each unit test in this class.
- def test_check_all_set(self): Test that check_all_set() works correctly. | Implement the Python class `TestQMSettings` described below.
Class description:
Contains unit tests for the QMSettings class.
Method signatures and docstrings:
- def setUp(self): A function run before each unit test in this class.
- def test_check_all_set(self): Test that check_all_set() works correctly.
<|skeleton|... | 349a4af759cf8877197772cd7eaca1e51d46eff5 | <|skeleton|>
class TestQMSettings:
"""Contains unit tests for the QMSettings class."""
def setUp(self):
"""A function run before each unit test in this class."""
<|body_0|>
def test_check_all_set(self):
"""Test that check_all_set() works correctly."""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestQMSettings:
"""Contains unit tests for the QMSettings class."""
def setUp(self):
"""A function run before each unit test in this class."""
rmg_path = os.path.normpath(os.path.join(get_path(), '..'))
self.settings1 = QMSettings(software='mopac', method='pm3', fileStore=os.path.... | the_stack_v2_python_sparse | rmgpy/qm/mainTest.py | CanePan-cc/CanePanWorkshop | train | 2 |
b622207880edde1bd21cc4df826718565a5dde89 | [
"try:\n post = PostService.get_post_by_id(post_id)\n post_schema = PostSchema()\n return render_template('post.html', title=post.title, post=post_schema.dump(post), current_connected_user=connected_user(get_jwt_identity()))\nexcept ResourceNotFound as e:\n return (render_template('404.html', title='Arti... | <|body_start_0|>
try:
post = PostService.get_post_by_id(post_id)
post_schema = PostSchema()
return render_template('post.html', title=post.title, post=post_schema.dump(post), current_connected_user=connected_user(get_jwt_identity()))
except ResourceNotFound as e:
... | Post | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Post:
def get(self, post_id):
"""Obtenir un post à partir de son id."""
<|body_0|>
def put(self, post_id):
"""Mettre à jour un post"""
<|body_1|>
def delete(self, post_id):
"""Supprimer un post"""
<|body_2|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_75kplus_train_006014 | 3,927 | no_license | [
{
"docstring": "Obtenir un post à partir de son id.",
"name": "get",
"signature": "def get(self, post_id)"
},
{
"docstring": "Mettre à jour un post",
"name": "put",
"signature": "def put(self, post_id)"
},
{
"docstring": "Supprimer un post",
"name": "delete",
"signature":... | 3 | stack_v2_sparse_classes_30k_val_001996 | Implement the Python class `Post` described below.
Class description:
Implement the Post class.
Method signatures and docstrings:
- def get(self, post_id): Obtenir un post à partir de son id.
- def put(self, post_id): Mettre à jour un post
- def delete(self, post_id): Supprimer un post | Implement the Python class `Post` described below.
Class description:
Implement the Post class.
Method signatures and docstrings:
- def get(self, post_id): Obtenir un post à partir de son id.
- def put(self, post_id): Mettre à jour un post
- def delete(self, post_id): Supprimer un post
<|skeleton|>
class Post:
... | dbeb9e603f8c24583dd6fd8b4e69ae488bc62591 | <|skeleton|>
class Post:
def get(self, post_id):
"""Obtenir un post à partir de son id."""
<|body_0|>
def put(self, post_id):
"""Mettre à jour un post"""
<|body_1|>
def delete(self, post_id):
"""Supprimer un post"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Post:
def get(self, post_id):
"""Obtenir un post à partir de son id."""
try:
post = PostService.get_post_by_id(post_id)
post_schema = PostSchema()
return render_template('post.html', title=post.title, post=post_schema.dump(post), current_connected_user=conne... | the_stack_v2_python_sparse | blog/controllers/post.py | buzzromain/projet-web-serveur | train | 0 | |
39f5b512d33125488d5908de524419f5972d1893 | [
"cuts.extend([0, n])\ncuts.sort()\n\n@lru_cache(None)\ndef f(i, j):\n if i + 1 >= j:\n return 0\n return cuts[j] - cuts[i] + min((f(i, k) + f(k, j) for k in range(i + 1, j)), default=0)\nreturn f(0, len(cuts) - 1)",
"cuts.extend([0, n])\ncuts.sort()\ndp = [[0 for _ in range(len(cuts))] for _ in range... | <|body_start_0|>
cuts.extend([0, n])
cuts.sort()
@lru_cache(None)
def f(i, j):
if i + 1 >= j:
return 0
return cuts[j] - cuts[i] + min((f(i, k) + f(k, j) for k in range(i + 1, j)), default=0)
return f(0, len(cuts) - 1)
<|end_body_0|>
<|bod... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minCost(self, n: int, cuts: List[int]) -> int:
"""Cutting a stick into len(cuts) pieces -> return min cuts"""
<|body_0|>
def minCost2(self, n: int, cuts: List[int]) -> int:
"""dp[i][j] means the min price of cutting all edges between i and j"""
... | stack_v2_sparse_classes_75kplus_train_006015 | 1,245 | no_license | [
{
"docstring": "Cutting a stick into len(cuts) pieces -> return min cuts",
"name": "minCost",
"signature": "def minCost(self, n: int, cuts: List[int]) -> int"
},
{
"docstring": "dp[i][j] means the min price of cutting all edges between i and j",
"name": "minCost2",
"signature": "def minC... | 2 | stack_v2_sparse_classes_30k_train_050203 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minCost(self, n: int, cuts: List[int]) -> int: Cutting a stick into len(cuts) pieces -> return min cuts
- def minCost2(self, n: int, cuts: List[int]) -> int: dp[i][j] means t... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minCost(self, n: int, cuts: List[int]) -> int: Cutting a stick into len(cuts) pieces -> return min cuts
- def minCost2(self, n: int, cuts: List[int]) -> int: dp[i][j] means t... | 19836799c0df23ed8a11d6a40d18abf9d00878d0 | <|skeleton|>
class Solution:
def minCost(self, n: int, cuts: List[int]) -> int:
"""Cutting a stick into len(cuts) pieces -> return min cuts"""
<|body_0|>
def minCost2(self, n: int, cuts: List[int]) -> int:
"""dp[i][j] means the min price of cutting all edges between i and j"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minCost(self, n: int, cuts: List[int]) -> int:
"""Cutting a stick into len(cuts) pieces -> return min cuts"""
cuts.extend([0, n])
cuts.sort()
@lru_cache(None)
def f(i, j):
if i + 1 >= j:
return 0
return cuts[j] - cu... | the_stack_v2_python_sparse | dp/dp_cut_sticks.py | kangli-bionic/algorithms-4 | train | 0 | |
e13753ac1c3350b142ae9cb99461e13c32b63912 | [
"n, sorts = (len(nums), sorted(nums))\nif nums == sorts:\n return 0\nl, r = (min((i for i in range(n) if nums[i] != sorts[i])), max((i for i in range(n) if nums[i] != sorts[i])))\nreturn r - l + 1",
"snums = sorted(nums)\ns = e = -1\nfor i in range(len(nums)):\n if nums[i] != snums[i]:\n if s == -1:\... | <|body_start_0|>
n, sorts = (len(nums), sorted(nums))
if nums == sorts:
return 0
l, r = (min((i for i in range(n) if nums[i] != sorts[i])), max((i for i in range(n) if nums[i] != sorts[i])))
return r - l + 1
<|end_body_0|>
<|body_start_1|>
snums = sorted(nums)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findUnsortedSubarray(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findUnsortedSubarray1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n, sorts = (len(nums), sor... | stack_v2_sparse_classes_75kplus_train_006016 | 1,323 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findUnsortedSubarray",
"signature": "def findUnsortedSubarray(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findUnsortedSubarray1",
"signature": "def findUnsortedSubarray1(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findUnsortedSubarray(self, nums): :type nums: List[int] :rtype: int
- def findUnsortedSubarray1(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 findUnsortedSubarray(self, nums): :type nums: List[int] :rtype: int
- def findUnsortedSubarray1(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
... | eaeeb9ad2d8cf2a60517cd86f42b30678b5ad2f8 | <|skeleton|>
class Solution:
def findUnsortedSubarray(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findUnsortedSubarray1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findUnsortedSubarray(self, nums):
""":type nums: List[int] :rtype: int"""
n, sorts = (len(nums), sorted(nums))
if nums == sorts:
return 0
l, r = (min((i for i in range(n) if nums[i] != sorts[i])), max((i for i in range(n) if nums[i] != sorts[i])))
... | the_stack_v2_python_sparse | Python/581. Shortest Unsorted Continuous Subarray.py | maiwen/LeetCode | train | 0 | |
ecd97a9935a567d3f0ea41b88f3747ded6a5ee4b | [
"table_name = os.environ.get('PAY_PAY_COUPON_INFO_DB')\nsuper().__init__(table_name)\nself._table = self._db.Table(table_name)",
"key = {'couponId': coupon_id}\ntry:\n item = self._get_item(key)\nexcept Exception as e:\n raise e\nreturn item",
"try:\n items = self._scan('deleted', '')\nexcept Exception... | <|body_start_0|>
table_name = os.environ.get('PAY_PAY_COUPON_INFO_DB')
super().__init__(table_name)
self._table = self._db.Table(table_name)
<|end_body_0|>
<|body_start_1|>
key = {'couponId': coupon_id}
try:
item = self._get_item(key)
except Exception as e:
... | SmartRegisterCouponInfo操作用クラス | SmartRegisterCouponInfo | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SmartRegisterCouponInfo:
"""SmartRegisterCouponInfo操作用クラス"""
def __init__(self):
"""初期化メソッド"""
<|body_0|>
def get_item(self, coupon_id):
"""データ取得 Parameters ---------- coupon_id : str クーポンID Returns ------- item : dict クーポン情報"""
<|body_1|>
def scan_n... | stack_v2_sparse_classes_75kplus_train_006017 | 1,189 | permissive | [
{
"docstring": "初期化メソッド",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "データ取得 Parameters ---------- coupon_id : str クーポンID Returns ------- item : dict クーポン情報",
"name": "get_item",
"signature": "def get_item(self, coupon_id)"
},
{
"docstring": "削除済みでないアイ... | 3 | stack_v2_sparse_classes_30k_train_023632 | Implement the Python class `SmartRegisterCouponInfo` described below.
Class description:
SmartRegisterCouponInfo操作用クラス
Method signatures and docstrings:
- def __init__(self): 初期化メソッド
- def get_item(self, coupon_id): データ取得 Parameters ---------- coupon_id : str クーポンID Returns ------- item : dict クーポン情報
- def scan_not_d... | Implement the Python class `SmartRegisterCouponInfo` described below.
Class description:
SmartRegisterCouponInfo操作用クラス
Method signatures and docstrings:
- def __init__(self): 初期化メソッド
- def get_item(self, coupon_id): データ取得 Parameters ---------- coupon_id : str クーポンID Returns ------- item : dict クーポン情報
- def scan_not_d... | 5667bc2d1db6d60950d8b9b6d6265e56b406ea1f | <|skeleton|>
class SmartRegisterCouponInfo:
"""SmartRegisterCouponInfo操作用クラス"""
def __init__(self):
"""初期化メソッド"""
<|body_0|>
def get_item(self, coupon_id):
"""データ取得 Parameters ---------- coupon_id : str クーポンID Returns ------- item : dict クーポン情報"""
<|body_1|>
def scan_n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SmartRegisterCouponInfo:
"""SmartRegisterCouponInfo操作用クラス"""
def __init__(self):
"""初期化メソッド"""
table_name = os.environ.get('PAY_PAY_COUPON_INFO_DB')
super().__init__(table_name)
self._table = self._db.Table(table_name)
def get_item(self, coupon_id):
"""データ取得 P... | the_stack_v2_python_sparse | backend/Layer/layer/smart_register/smart_register_coupon_info.py | tacck/line-api-use-case-smart-retail | train | 1 |
1f65b8d0a80d447c9885dfd5141ea2e44e3a1155 | [
"if _debug:\n ConfigArgumentParser._debug('__init__')\nArgumentParser.__init__(self, **kwargs)\nself.add_argument('--ini', help='device object configuration file', default=settings.ini)",
"if _debug:\n ConfigArgumentParser._debug('update_os_env')\nArgumentParser.update_os_env(self)\nsettings['ini'] = os.get... | <|body_start_0|>
if _debug:
ConfigArgumentParser._debug('__init__')
ArgumentParser.__init__(self, **kwargs)
self.add_argument('--ini', help='device object configuration file', default=settings.ini)
<|end_body_0|>
<|body_start_1|>
if _debug:
ConfigArgumentParser._... | ConfigArgumentParser extends the ArgumentParser with the functionality to read in an INI configuration file. --ini INI provide a separate INI file | ConfigArgumentParser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigArgumentParser:
"""ConfigArgumentParser extends the ArgumentParser with the functionality to read in an INI configuration file. --ini INI provide a separate INI file"""
def __init__(self, **kwargs):
"""Follow normal initialization and add BACpypes arguments."""
<|body_0... | stack_v2_sparse_classes_75kplus_train_006018 | 12,303 | permissive | [
{
"docstring": "Follow normal initialization and add BACpypes arguments.",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Update the settings with values from the environment, if provided.",
"name": "update_os_env",
"signature": "def update_os_env(self... | 3 | null | Implement the Python class `ConfigArgumentParser` described below.
Class description:
ConfigArgumentParser extends the ArgumentParser with the functionality to read in an INI configuration file. --ini INI provide a separate INI file
Method signatures and docstrings:
- def __init__(self, **kwargs): Follow normal initi... | Implement the Python class `ConfigArgumentParser` described below.
Class description:
ConfigArgumentParser extends the ArgumentParser with the functionality to read in an INI configuration file. --ini INI provide a separate INI file
Method signatures and docstrings:
- def __init__(self, **kwargs): Follow normal initi... | a5be2ad5ac69821c12299716b167dd52041b5342 | <|skeleton|>
class ConfigArgumentParser:
"""ConfigArgumentParser extends the ArgumentParser with the functionality to read in an INI configuration file. --ini INI provide a separate INI file"""
def __init__(self, **kwargs):
"""Follow normal initialization and add BACpypes arguments."""
<|body_0... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConfigArgumentParser:
"""ConfigArgumentParser extends the ArgumentParser with the functionality to read in an INI configuration file. --ini INI provide a separate INI file"""
def __init__(self, **kwargs):
"""Follow normal initialization and add BACpypes arguments."""
if _debug:
... | the_stack_v2_python_sparse | py27/bacpypes/consolelogging.py | JoelBender/bacpypes | train | 284 |
35e96d045ee297c35e3efe42b72f0e252e91dc6f | [
"voyages_file = open('csv_files/Voyages.csv', 'r')\nvoyages_reader = csv.DictReader(voyages_file)\nvoyages_list = []\nfor row in voyages_reader:\n voyage_id = row['voyage_id']\n flight_number_out = row['flight_num_out']\n flight_number_back = row['flight_num_back']\n departure_out = row['departure_out']... | <|body_start_0|>
voyages_file = open('csv_files/Voyages.csv', 'r')
voyages_reader = csv.DictReader(voyages_file)
voyages_list = []
for row in voyages_reader:
voyage_id = row['voyage_id']
flight_number_out = row['flight_num_out']
flight_number_back = ro... | VoyageIO | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VoyageIO:
def load_all_voyages(self):
"""Reads into the database. Returns a list of all voyages as instances"""
<|body_0|>
def store_voyage_changes(self, voyages_list):
"""Adds plane and staff to specific voyage"""
<|body_1|>
def store_new_voyage(self, n... | stack_v2_sparse_classes_75kplus_train_006019 | 2,379 | no_license | [
{
"docstring": "Reads into the database. Returns a list of all voyages as instances",
"name": "load_all_voyages",
"signature": "def load_all_voyages(self)"
},
{
"docstring": "Adds plane and staff to specific voyage",
"name": "store_voyage_changes",
"signature": "def store_voyage_changes(... | 4 | stack_v2_sparse_classes_30k_train_054131 | Implement the Python class `VoyageIO` described below.
Class description:
Implement the VoyageIO class.
Method signatures and docstrings:
- def load_all_voyages(self): Reads into the database. Returns a list of all voyages as instances
- def store_voyage_changes(self, voyages_list): Adds plane and staff to specific v... | Implement the Python class `VoyageIO` described below.
Class description:
Implement the VoyageIO class.
Method signatures and docstrings:
- def load_all_voyages(self): Reads into the database. Returns a list of all voyages as instances
- def store_voyage_changes(self, voyages_list): Adds plane and staff to specific v... | 5dbce2a3d1cdc8a0614252fb77685211b395c2df | <|skeleton|>
class VoyageIO:
def load_all_voyages(self):
"""Reads into the database. Returns a list of all voyages as instances"""
<|body_0|>
def store_voyage_changes(self, voyages_list):
"""Adds plane and staff to specific voyage"""
<|body_1|>
def store_new_voyage(self, n... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VoyageIO:
def load_all_voyages(self):
"""Reads into the database. Returns a list of all voyages as instances"""
voyages_file = open('csv_files/Voyages.csv', 'r')
voyages_reader = csv.DictReader(voyages_file)
voyages_list = []
for row in voyages_reader:
voyag... | the_stack_v2_python_sparse | DataLayer/VoyageIO.py | svana00/VLN1-NaN-Air | train | 0 | |
bdd3363c9dad88e8cdee6abf7b898b41e8f4c08a | [
"if not builder:\n raise ValueError('Builder is not specified')\nself.__builder = builder",
"assert component, 'Software component is not specified'\nassert containerOsh, 'Software component container is not specified'\nosh = self.__builder.buildSoftwareComponent(component)\nosh.setContainer(containerOsh)\nret... | <|body_start_0|>
if not builder:
raise ValueError('Builder is not specified')
self.__builder = builder
<|end_body_0|>
<|body_start_1|>
assert component, 'Software component is not specified'
assert containerOsh, 'Software component container is not specified'
osh = s... | SoftwareComponentReporter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SoftwareComponentReporter:
def __init__(self, builder):
"""@types: SoftwareComponentBuilder"""
<|body_0|>
def reportSoftwareComponent(self, component, containerOsh):
"""@types: SoftwareComponent, ObjectStateHolder -> ObjectStateHolder"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus_train_006020 | 17,185 | no_license | [
{
"docstring": "@types: SoftwareComponentBuilder",
"name": "__init__",
"signature": "def __init__(self, builder)"
},
{
"docstring": "@types: SoftwareComponent, ObjectStateHolder -> ObjectStateHolder",
"name": "reportSoftwareComponent",
"signature": "def reportSoftwareComponent(self, comp... | 2 | stack_v2_sparse_classes_30k_test_001675 | Implement the Python class `SoftwareComponentReporter` described below.
Class description:
Implement the SoftwareComponentReporter class.
Method signatures and docstrings:
- def __init__(self, builder): @types: SoftwareComponentBuilder
- def reportSoftwareComponent(self, component, containerOsh): @types: SoftwareComp... | Implement the Python class `SoftwareComponentReporter` described below.
Class description:
Implement the SoftwareComponentReporter class.
Method signatures and docstrings:
- def __init__(self, builder): @types: SoftwareComponentBuilder
- def reportSoftwareComponent(self, component, containerOsh): @types: SoftwareComp... | c431e809e8d0f82e1bca7e3429dd0245560b5680 | <|skeleton|>
class SoftwareComponentReporter:
def __init__(self, builder):
"""@types: SoftwareComponentBuilder"""
<|body_0|>
def reportSoftwareComponent(self, component, containerOsh):
"""@types: SoftwareComponent, ObjectStateHolder -> ObjectStateHolder"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SoftwareComponentReporter:
def __init__(self, builder):
"""@types: SoftwareComponentBuilder"""
if not builder:
raise ValueError('Builder is not specified')
self.__builder = builder
def reportSoftwareComponent(self, component, containerOsh):
"""@types: SoftwareC... | the_stack_v2_python_sparse | reference/ucmdb/discovery/sap_jee.py | madmonkyang/cda-record | train | 0 | |
656256fb8189a363ae884d547f42ee47acf4f06b | [
"matrix = copy.deepcopy(grid)\nxLength = len(grid)\nyLength = xLength and len(grid[0])\nfor i in range(1, xLength):\n matrix[i][0] += matrix[i - 1][0]\nfor i in range(1, yLength):\n matrix[0][i] += matrix[0][i - 1]\nfor i in range(1, xLength):\n for j in range(1, yLength):\n matrix[i][j] += min(matr... | <|body_start_0|>
matrix = copy.deepcopy(grid)
xLength = len(grid)
yLength = xLength and len(grid[0])
for i in range(1, xLength):
matrix[i][0] += matrix[i - 1][0]
for i in range(1, yLength):
matrix[0][i] += matrix[0][i - 1]
for i in range(1, xLength... | 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 minPathSum2(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
matrix = copy.deepcopy(grid)
... | stack_v2_sparse_classes_75kplus_train_006021 | 1,207 | 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": "minPathSum2",
"signature": "def minPathSum2(self, grid)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003316 | 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 minPathSum2(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 minPathSum2(self, grid): :type grid: List[List[int]] :rtype: int
<|skeleton|>
class Solution:
def ... | c8bf33af30569177c5276ffcd72a8d93ba4c402a | <|skeleton|>
class Solution:
def minPathSum(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_0|>
def minPathSum2(self, grid):
""":type grid: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minPathSum(self, grid):
""":type grid: List[List[int]] :rtype: int"""
matrix = copy.deepcopy(grid)
xLength = len(grid)
yLength = xLength and len(grid[0])
for i in range(1, xLength):
matrix[i][0] += matrix[i - 1][0]
for i in range(1, yLe... | the_stack_v2_python_sparse | 1-100/61-70/64-minimumPathSum/minimumPathSum.py | xuychen/Leetcode | train | 0 | |
261a326e10c4ad704f782c41b6e0ac30c80b17e9 | [
"super().__init__()\nself.view = view\nself.view.title = 'ROOT'\nself.view.expandable = True\nself._project = project\nself.update_children(progress_listener)",
"if progress_listener is None:\n progress_listener = DummyOpenProjectProgressListener()\nchildren = []\nprogress_listener.loading_root_resource_views(... | <|body_start_0|>
super().__init__()
self.view = view
self.view.title = 'ROOT'
self.view.expandable = True
self._project = project
self.update_children(progress_listener)
<|end_body_0|>
<|body_start_1|>
if progress_listener is None:
progress_listener =... | RootNode | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RootNode:
def __init__(self, project: Project, view: NodeView, progress_listener: OpenProjectProgressListener) -> None:
"""Raises: * CancelOpenProject"""
<|body_0|>
def update_children(self, progress_listener: Optional[OpenProjectProgressListener]=None) -> None:
"""R... | stack_v2_sparse_classes_75kplus_train_006022 | 33,790 | no_license | [
{
"docstring": "Raises: * CancelOpenProject",
"name": "__init__",
"signature": "def __init__(self, project: Project, view: NodeView, progress_listener: OpenProjectProgressListener) -> None"
},
{
"docstring": "Raises: * CancelOpenProject",
"name": "update_children",
"signature": "def upda... | 2 | null | Implement the Python class `RootNode` described below.
Class description:
Implement the RootNode class.
Method signatures and docstrings:
- def __init__(self, project: Project, view: NodeView, progress_listener: OpenProjectProgressListener) -> None: Raises: * CancelOpenProject
- def update_children(self, progress_lis... | Implement the Python class `RootNode` described below.
Class description:
Implement the RootNode class.
Method signatures and docstrings:
- def __init__(self, project: Project, view: NodeView, progress_listener: OpenProjectProgressListener) -> None: Raises: * CancelOpenProject
- def update_children(self, progress_lis... | cc23432b7b9212edbf29e8588345ee5d92150e52 | <|skeleton|>
class RootNode:
def __init__(self, project: Project, view: NodeView, progress_listener: OpenProjectProgressListener) -> None:
"""Raises: * CancelOpenProject"""
<|body_0|>
def update_children(self, progress_listener: Optional[OpenProjectProgressListener]=None) -> None:
"""R... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RootNode:
def __init__(self, project: Project, view: NodeView, progress_listener: OpenProjectProgressListener) -> None:
"""Raises: * CancelOpenProject"""
super().__init__()
self.view = view
self.view.title = 'ROOT'
self.view.expandable = True
self._project = pro... | the_stack_v2_python_sparse | src/crystal/browser/entitytree.py | davidfstr/Crystal-Web-Archiver | train | 29 | |
35614e2637393597b6eb728e13a561902b613e57 | [
"id = kwargs['designer']\nself.designer = get_object_or_404(Designer, id=id)\nreturn super(DesignerInventoryViewSet, self).dispatch(request, *args, **kwargs)",
"designer = self.designer\ntry:\n inventory = Inventory.objects.get(designer=designer)\n data = {'inventory': InventoryModelSerializer(inventory).da... | <|body_start_0|>
id = kwargs['designer']
self.designer = get_object_or_404(Designer, id=id)
return super(DesignerInventoryViewSet, self).dispatch(request, *args, **kwargs)
<|end_body_0|>
<|body_start_1|>
designer = self.designer
try:
inventory = Inventory.objects.get... | The viewset to CRUD and inventory from a specific designer | DesignerInventoryViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DesignerInventoryViewSet:
"""The viewset to CRUD and inventory from a specific designer"""
def dispatch(self, request, *args, **kwargs):
"""obtains the designer from the keyword 'designer' in the url"""
<|body_0|>
def list(self, request, *args, **kwargs):
"""List... | stack_v2_sparse_classes_75kplus_train_006023 | 4,916 | no_license | [
{
"docstring": "obtains the designer from the keyword 'designer' in the url",
"name": "dispatch",
"signature": "def dispatch(self, request, *args, **kwargs)"
},
{
"docstring": "Lists the inventorie of the designer",
"name": "list",
"signature": "def list(self, request, *args, **kwargs)"
... | 3 | stack_v2_sparse_classes_30k_train_024447 | Implement the Python class `DesignerInventoryViewSet` described below.
Class description:
The viewset to CRUD and inventory from a specific designer
Method signatures and docstrings:
- def dispatch(self, request, *args, **kwargs): obtains the designer from the keyword 'designer' in the url
- def list(self, request, *... | Implement the Python class `DesignerInventoryViewSet` described below.
Class description:
The viewset to CRUD and inventory from a specific designer
Method signatures and docstrings:
- def dispatch(self, request, *args, **kwargs): obtains the designer from the keyword 'designer' in the url
- def list(self, request, *... | bd037be8a814dce554e709d851c6a96e6a41ea78 | <|skeleton|>
class DesignerInventoryViewSet:
"""The viewset to CRUD and inventory from a specific designer"""
def dispatch(self, request, *args, **kwargs):
"""obtains the designer from the keyword 'designer' in the url"""
<|body_0|>
def list(self, request, *args, **kwargs):
"""List... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DesignerInventoryViewSet:
"""The viewset to CRUD and inventory from a specific designer"""
def dispatch(self, request, *args, **kwargs):
"""obtains the designer from the keyword 'designer' in the url"""
id = kwargs['designer']
self.designer = get_object_or_404(Designer, id=id)
... | the_stack_v2_python_sparse | users/views/designers.py | jpcano1/tShoes | train | 0 |
05de142a59139d1e65d95687788fd10cbe5e575d | [
"result = []\ncollection = mongo.get_conn()['main_otss']\ncategories = collection.find()\nif collection:\n for document in categories:\n document['_id'] = str(document['_id'])\n result.append(document)\nreturn Response({'otss': result}, status=200)",
"collection = mongo.get_conn()['main_otss']\nc... | <|body_start_0|>
result = []
collection = mongo.get_conn()['main_otss']
categories = collection.find()
if collection:
for document in categories:
document['_id'] = str(document['_id'])
result.append(document)
return Response({'otss': re... | OTSSView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OTSSView:
def get(self, _):
""":param _: Default to none. :return: OTSS category list. Response status 200."""
<|body_0|>
def post(self, request):
""":param request: Request entity, contains request payload. :return: Response message: "message": "OTSS category '{}' c... | stack_v2_sparse_classes_75kplus_train_006024 | 31,474 | no_license | [
{
"docstring": ":param _: Default to none. :return: OTSS category list. Response status 200.",
"name": "get",
"signature": "def get(self, _)"
},
{
"docstring": ":param request: Request entity, contains request payload. :return: Response message: \"message\": \"OTSS category '{}' created successf... | 4 | null | Implement the Python class `OTSSView` described below.
Class description:
Implement the OTSSView class.
Method signatures and docstrings:
- def get(self, _): :param _: Default to none. :return: OTSS category list. Response status 200.
- def post(self, request): :param request: Request entity, contains request payload... | Implement the Python class `OTSSView` described below.
Class description:
Implement the OTSSView class.
Method signatures and docstrings:
- def get(self, _): :param _: Default to none. :return: OTSS category list. Response status 200.
- def post(self, request): :param request: Request entity, contains request payload... | 1a1cf80999d02b830217a8cbd9200ed9b1332c88 | <|skeleton|>
class OTSSView:
def get(self, _):
""":param _: Default to none. :return: OTSS category list. Response status 200."""
<|body_0|>
def post(self, request):
""":param request: Request entity, contains request payload. :return: Response message: "message": "OTSS category '{}' c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OTSSView:
def get(self, _):
""":param _: Default to none. :return: OTSS category list. Response status 200."""
result = []
collection = mongo.get_conn()['main_otss']
categories = collection.find()
if collection:
for document in categories:
do... | the_stack_v2_python_sparse | backend/main/views.py | buldozzzer/inventorybase | train | 0 | |
b7b9efe57ce3cd746390e1de414961405bce4196 | [
"if hasattr(info.context, 'repo_cache_middleware_complete'):\n return next(root, info, **args)\nif info.operation.operation == 'mutation':\n try:\n self.flush_repo_cache(info.operation, info.variable_values)\n except UnknownRepo as e:\n logger.warning(f'Mutation {info.operation.name} not asso... | <|body_start_0|>
if hasattr(info.context, 'repo_cache_middleware_complete'):
return next(root, info, **args)
if info.operation.operation == 'mutation':
try:
self.flush_repo_cache(info.operation, info.variable_values)
except UnknownRepo as e:
... | RepositoryCacheMiddleware | [
"MIT",
"LicenseRef-scancode-dco-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RepositoryCacheMiddleware:
def resolve(self, next, root, info, **args):
"""This segment of the middleware attempts to capture specific mutations and use the info for given repositories to flush the corresponding cache input. For example, if you stop a Project container, this callback wil... | stack_v2_sparse_classes_75kplus_train_006025 | 4,223 | permissive | [
{
"docstring": "This segment of the middleware attempts to capture specific mutations and use the info for given repositories to flush the corresponding cache input. For example, if you stop a Project container, this callback will capture the owner and repository name, and then flush the Redis cache for that re... | 2 | stack_v2_sparse_classes_30k_train_045709 | Implement the Python class `RepositoryCacheMiddleware` described below.
Class description:
Implement the RepositoryCacheMiddleware class.
Method signatures and docstrings:
- def resolve(self, next, root, info, **args): This segment of the middleware attempts to capture specific mutations and use the info for given re... | Implement the Python class `RepositoryCacheMiddleware` described below.
Class description:
Implement the RepositoryCacheMiddleware class.
Method signatures and docstrings:
- def resolve(self, next, root, info, **args): This segment of the middleware attempts to capture specific mutations and use the info for given re... | 70fe6b39b87b1c56351f2b4c551b6f1693813e4f | <|skeleton|>
class RepositoryCacheMiddleware:
def resolve(self, next, root, info, **args):
"""This segment of the middleware attempts to capture specific mutations and use the info for given repositories to flush the corresponding cache input. For example, if you stop a Project container, this callback wil... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RepositoryCacheMiddleware:
def resolve(self, next, root, info, **args):
"""This segment of the middleware attempts to capture specific mutations and use the info for given repositories to flush the corresponding cache input. For example, if you stop a Project container, this callback will capture the ... | the_stack_v2_python_sparse | packages/gtmapi/lmsrvcore/middleware/cache.py | griffinmilsap/gigantum-client | train | 0 | |
3d6889709a3d7d30ebd44a12d15ca34a8120f45b | [
"num = len(self._instances)\nindex_groups = [set() for i in range(num)]\nfor i, instance in enumerate(self._instances):\n for j in range(i + 1, num):\n if fun(instance, self._instances[j]):\n index_groups[i].add(j)\n index_groups[j].add(i)\ngroups = graph_bfs(index_groups)\ngroups = ... | <|body_start_0|>
num = len(self._instances)
index_groups = [set() for i in range(num)]
for i, instance in enumerate(self._instances):
for j in range(i + 1, num):
if fun(instance, self._instances[j]):
index_groups[i].add(j)
index... | Collection of instance focusing on grouping sub-collection based on intersections. | Collection | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Collection:
"""Collection of instance focusing on grouping sub-collection based on intersections."""
def group(self, fun):
"""Group instances according to user defined criterion. Args: fun (function): with 2 arguments representing 2 instances (Element) and return bool. Returns: list:... | stack_v2_sparse_classes_75kplus_train_006026 | 9,233 | permissive | [
{
"docstring": "Group instances according to user defined criterion. Args: fun (function): with 2 arguments representing 2 instances (Element) and return bool. Returns: list: a list of grouped ``Collection`` instances. Examples 1:: # group instances intersected with each other fun = lambda a,b: a.bbox & b.bbox ... | 2 | stack_v2_sparse_classes_30k_train_032948 | Implement the Python class `Collection` described below.
Class description:
Collection of instance focusing on grouping sub-collection based on intersections.
Method signatures and docstrings:
- def group(self, fun): Group instances according to user defined criterion. Args: fun (function): with 2 arguments represent... | Implement the Python class `Collection` described below.
Class description:
Collection of instance focusing on grouping sub-collection based on intersections.
Method signatures and docstrings:
- def group(self, fun): Group instances according to user defined criterion. Args: fun (function): with 2 arguments represent... | 13cdbaa8acef8e1140e419ac488eb6f18d4ca6d5 | <|skeleton|>
class Collection:
"""Collection of instance focusing on grouping sub-collection based on intersections."""
def group(self, fun):
"""Group instances according to user defined criterion. Args: fun (function): with 2 arguments representing 2 instances (Element) and return bool. Returns: list:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Collection:
"""Collection of instance focusing on grouping sub-collection based on intersections."""
def group(self, fun):
"""Group instances according to user defined criterion. Args: fun (function): with 2 arguments representing 2 instances (Element) and return bool. Returns: list: a list of gr... | the_stack_v2_python_sparse | CustomPdf2Docx/common/Collection.py | ikdk5596/pdf_translate | train | 0 |
383125120f094cbdd3c29378d7d827eb3c4bbfc8 | [
"response = requests.get('https://favqs.com/api/quotes/', params={'filter': random.choice(CATEGORY)}, headers={'Authorization': 'Token token=' + ACCESS_KEY_QUOTES})\nquote_list_json = response.json()\nreturn [quote_list_json['quotes'][0]['body'], quote_list_json['quotes'][0]['author']]",
"response = requests.get(... | <|body_start_0|>
response = requests.get('https://favqs.com/api/quotes/', params={'filter': random.choice(CATEGORY)}, headers={'Authorization': 'Token token=' + ACCESS_KEY_QUOTES})
quote_list_json = response.json()
return [quote_list_json['quotes'][0]['body'], quote_list_json['quotes'][0]['autho... | Quotes | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Quotes:
def quotes_fav(self):
"""Fetches quotes from FavQuotes API from the category list returns a list of quote and author"""
<|body_0|>
def random_quote_fav(self):
"""Fetches quote of the Day returns a list of quote and author"""
<|body_1|>
def quotab... | stack_v2_sparse_classes_75kplus_train_006027 | 1,960 | permissive | [
{
"docstring": "Fetches quotes from FavQuotes API from the category list returns a list of quote and author",
"name": "quotes_fav",
"signature": "def quotes_fav(self)"
},
{
"docstring": "Fetches quote of the Day returns a list of quote and author",
"name": "random_quote_fav",
"signature"... | 4 | stack_v2_sparse_classes_30k_val_000644 | Implement the Python class `Quotes` described below.
Class description:
Implement the Quotes class.
Method signatures and docstrings:
- def quotes_fav(self): Fetches quotes from FavQuotes API from the category list returns a list of quote and author
- def random_quote_fav(self): Fetches quote of the Day returns a lis... | Implement the Python class `Quotes` described below.
Class description:
Implement the Quotes class.
Method signatures and docstrings:
- def quotes_fav(self): Fetches quotes from FavQuotes API from the category list returns a list of quote and author
- def random_quote_fav(self): Fetches quote of the Day returns a lis... | d87c6294043889d89a10b44811c7b240d4c1905d | <|skeleton|>
class Quotes:
def quotes_fav(self):
"""Fetches quotes from FavQuotes API from the category list returns a list of quote and author"""
<|body_0|>
def random_quote_fav(self):
"""Fetches quote of the Day returns a list of quote and author"""
<|body_1|>
def quotab... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Quotes:
def quotes_fav(self):
"""Fetches quotes from FavQuotes API from the category list returns a list of quote and author"""
response = requests.get('https://favqs.com/api/quotes/', params={'filter': random.choice(CATEGORY)}, headers={'Authorization': 'Token token=' + ACCESS_KEY_QUOTES})
... | the_stack_v2_python_sparse | Resources/quotes_fetch.py | JayP09/Inspiquote | train | 0 | |
c4523e521d2da59860514e3b1ed78be687e5de8e | [
"for l in lines:\n match = self.__regex_obj.match(l)\n if match:\n match_name = match.lastgroup\n match_groups = [x for x in match.groups() if x]\n self.__match_handlers[match_name](match_name, *match_groups)\n else:\n raise NullStateException(repr(l))",
"if regex_obj:\n se... | <|body_start_0|>
for l in lines:
match = self.__regex_obj.match(l)
if match:
match_name = match.lastgroup
match_groups = [x for x in match.groups() if x]
self.__match_handlers[match_name](match_name, *match_groups)
else:
... | Base class for building a finite state machine. The state machine is controled by two externally provided data structures. .. attribute:: regex_obj A compiled :mod:`regex <re>` pattern instance that contains one or more named groups (i.e. ``(?P<name>...)``) sub-patterns. .. attribute:: match_handlers A :class:`dict` th... | StateMachine | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StateMachine:
"""Base class for building a finite state machine. The state machine is controled by two externally provided data structures. .. attribute:: regex_obj A compiled :mod:`regex <re>` pattern instance that contains one or more named groups (i.e. ``(?P<name>...)``) sub-patterns. .. attri... | stack_v2_sparse_classes_75kplus_train_006028 | 2,585 | permissive | [
{
"docstring": "For each line of text in :data:`lines`, a regex match is performed and a state handler function is called to finalize processing of the string. :param lines: Input data consumed by state machine :type lines: list",
"name": "__call__",
"signature": "def __call__(self, lines)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_016966 | Implement the Python class `StateMachine` described below.
Class description:
Base class for building a finite state machine. The state machine is controled by two externally provided data structures. .. attribute:: regex_obj A compiled :mod:`regex <re>` pattern instance that contains one or more named groups (i.e. ``... | Implement the Python class `StateMachine` described below.
Class description:
Base class for building a finite state machine. The state machine is controled by two externally provided data structures. .. attribute:: regex_obj A compiled :mod:`regex <re>` pattern instance that contains one or more named groups (i.e. ``... | 36dd86b71c79c1f02ca07743b4bdea08527bafda | <|skeleton|>
class StateMachine:
"""Base class for building a finite state machine. The state machine is controled by two externally provided data structures. .. attribute:: regex_obj A compiled :mod:`regex <re>` pattern instance that contains one or more named groups (i.e. ``(?P<name>...)``) sub-patterns. .. attri... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StateMachine:
"""Base class for building a finite state machine. The state machine is controled by two externally provided data structures. .. attribute:: regex_obj A compiled :mod:`regex <re>` pattern instance that contains one or more named groups (i.e. ``(?P<name>...)``) sub-patterns. .. attribute:: match_... | the_stack_v2_python_sparse | mktoc/fsm.py | cmcginty/mktoc | train | 12 |
23ca73cee025fb7658d3524a431659ca6d9d41af | [
"result = find_angle(10, 10)\nself.assertEqual(result, '45°')\nreturn",
"result = find_angle(5, 5)\nself.assertEqual(result, '45°')\nreturn"
] | <|body_start_0|>
result = find_angle(10, 10)
self.assertEqual(result, '45°')
return
<|end_body_0|>
<|body_start_1|>
result = find_angle(5, 5)
self.assertEqual(result, '45°')
return
<|end_body_1|>
| Test angle MBC | TestFindAngle | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestFindAngle:
"""Test angle MBC"""
def test_hackerrank_sample1(self):
"""Verify provided test case."""
<|body_0|>
def test_hackerrank_sample2(self):
"""Verify provided test case."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = find_ang... | stack_v2_sparse_classes_75kplus_train_006029 | 564 | no_license | [
{
"docstring": "Verify provided test case.",
"name": "test_hackerrank_sample1",
"signature": "def test_hackerrank_sample1(self)"
},
{
"docstring": "Verify provided test case.",
"name": "test_hackerrank_sample2",
"signature": "def test_hackerrank_sample2(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002699 | Implement the Python class `TestFindAngle` described below.
Class description:
Test angle MBC
Method signatures and docstrings:
- def test_hackerrank_sample1(self): Verify provided test case.
- def test_hackerrank_sample2(self): Verify provided test case. | Implement the Python class `TestFindAngle` described below.
Class description:
Test angle MBC
Method signatures and docstrings:
- def test_hackerrank_sample1(self): Verify provided test case.
- def test_hackerrank_sample2(self): Verify provided test case.
<|skeleton|>
class TestFindAngle:
"""Test angle MBC"""
... | fcf3755b62fe0644af763875e3a00be962941a6d | <|skeleton|>
class TestFindAngle:
"""Test angle MBC"""
def test_hackerrank_sample1(self):
"""Verify provided test case."""
<|body_0|>
def test_hackerrank_sample2(self):
"""Verify provided test case."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestFindAngle:
"""Test angle MBC"""
def test_hackerrank_sample1(self):
"""Verify provided test case."""
result = find_angle(10, 10)
self.assertEqual(result, '45°')
return
def test_hackerrank_sample2(self):
"""Verify provided test case."""
result = find... | the_stack_v2_python_sparse | python3/find_angle/test_find_angle.py | ayazhemani/hackerrank-py | train | 0 |
952e448aff6e98000cc42eb7a9cfe4bd7e912942 | [
"project = Project.query.get(pid)\nuser = helpers.abort_if_unauthorized(project)\nhelpers.abort_if_project_member(user, pid)\nmembership = Membership.join_project(user.id, pid)\nreturn custom_response(200, data=ProjectMember().dump(membership))",
"project = Project.query.get(pid)\nuser = helpers.abort_if_unauthor... | <|body_start_0|>
project = Project.query.get(pid)
user = helpers.abort_if_unauthorized(project)
helpers.abort_if_project_member(user, pid)
membership = Membership.join_project(user.id, pid)
return custom_response(200, data=ProjectMember().dump(membership))
<|end_body_0|>
<|body_... | Mapped to: /api/project/<int:id>/membership/ | ProjectMembership | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectMembership:
"""Mapped to: /api/project/<int:id>/membership/"""
def post(self, pid):
"""Joins a public project for a given user (determined through JWT token)"""
<|body_0|>
def delete(self, pid):
"""Leaves a project for a given user (determined through JWT ... | stack_v2_sparse_classes_75kplus_train_006030 | 8,130 | no_license | [
{
"docstring": "Joins a public project for a given user (determined through JWT token)",
"name": "post",
"signature": "def post(self, pid)"
},
{
"docstring": "Leaves a project for a given user (determined through JWT token)",
"name": "delete",
"signature": "def delete(self, pid)"
}
] | 2 | stack_v2_sparse_classes_30k_train_040357 | Implement the Python class `ProjectMembership` described below.
Class description:
Mapped to: /api/project/<int:id>/membership/
Method signatures and docstrings:
- def post(self, pid): Joins a public project for a given user (determined through JWT token)
- def delete(self, pid): Leaves a project for a given user (de... | Implement the Python class `ProjectMembership` described below.
Class description:
Mapped to: /api/project/<int:id>/membership/
Method signatures and docstrings:
- def post(self, pid): Joins a public project for a given user (determined through JWT token)
- def delete(self, pid): Leaves a project for a given user (de... | 716fa5a6e905380cb206c57868e87556805f2b7f | <|skeleton|>
class ProjectMembership:
"""Mapped to: /api/project/<int:id>/membership/"""
def post(self, pid):
"""Joins a public project for a given user (determined through JWT token)"""
<|body_0|>
def delete(self, pid):
"""Leaves a project for a given user (determined through JWT ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProjectMembership:
"""Mapped to: /api/project/<int:id>/membership/"""
def post(self, pid):
"""Joins a public project for a given user (determined through JWT token)"""
project = Project.query.get(pid)
user = helpers.abort_if_unauthorized(project)
helpers.abort_if_project_m... | the_stack_v2_python_sparse | gabber/api/membership.py | joseplj/GabberAPI | train | 0 |
8f540844ba35df23b5dd0188d3d9d7fd9f0228b4 | [
"self.timeout = timeout\ntry:\n self.pre_snap = self.mapping.learn_ops(device=uut, abstract=abstract, steps=steps, timeout=self.timeout)\nexcept Exception as e:\n self.skipped('Cannot learn the feature', from_exception=e, goto=['next_tc'])\nfor stp in steps.details:\n if stp.result.name == 'skipped':\n ... | <|body_start_0|>
self.timeout = timeout
try:
self.pre_snap = self.mapping.learn_ops(device=uut, abstract=abstract, steps=steps, timeout=self.timeout)
except Exception as e:
self.skipped('Cannot learn the feature', from_exception=e, goto=['next_tc'])
for stp in ste... | Trigger class for ISSU action | TriggerIssu | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TriggerIssu:
"""Trigger class for ISSU action"""
def verify_prerequisite(self, uut, abstract, steps, timeout):
"""Learn Ops object and verify the requirements. If the requirements are not satisfied, then skip to the next testcase. Args: uut (`obj`): Device object. abstract (`obj`): A... | stack_v2_sparse_classes_75kplus_train_006031 | 20,969 | permissive | [
{
"docstring": "Learn Ops object and verify the requirements. If the requirements are not satisfied, then skip to the next testcase. Args: uut (`obj`): Device object. abstract (`obj`): Abstract object. steps (`step obj`): aetest step object timeout (`timeout obj`): Timeout Object Returns: None Raises: pyATS Res... | 5 | stack_v2_sparse_classes_30k_train_038173 | Implement the Python class `TriggerIssu` described below.
Class description:
Trigger class for ISSU action
Method signatures and docstrings:
- def verify_prerequisite(self, uut, abstract, steps, timeout): Learn Ops object and verify the requirements. If the requirements are not satisfied, then skip to the next testca... | Implement the Python class `TriggerIssu` described below.
Class description:
Trigger class for ISSU action
Method signatures and docstrings:
- def verify_prerequisite(self, uut, abstract, steps, timeout): Learn Ops object and verify the requirements. If the requirements are not satisfied, then skip to the next testca... | e42e51475cddcb10f5c7814d0fe892ac865742ba | <|skeleton|>
class TriggerIssu:
"""Trigger class for ISSU action"""
def verify_prerequisite(self, uut, abstract, steps, timeout):
"""Learn Ops object and verify the requirements. If the requirements are not satisfied, then skip to the next testcase. Args: uut (`obj`): Device object. abstract (`obj`): A... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TriggerIssu:
"""Trigger class for ISSU action"""
def verify_prerequisite(self, uut, abstract, steps, timeout):
"""Learn Ops object and verify the requirements. If the requirements are not satisfied, then skip to the next testcase. Args: uut (`obj`): Device object. abstract (`obj`): Abstract objec... | the_stack_v2_python_sparse | pkgs/sdk-pkg/src/genie/libs/sdk/triggers/ha/ha.py | CiscoTestAutomation/genielibs | train | 109 |
9cea73822853a0a1d73761413469a847fd3efd1f | [
"self.description = description\nself.domain = domain\nself.object_class = object_class\nself.principal_name = principal_name\nself.restricted = restricted\nself.roles = roles",
"if dictionary is None:\n return None\ndescription = dictionary.get('description')\ndomain = dictionary.get('domain')\nobject_class =... | <|body_start_0|>
self.description = description
self.domain = domain
self.object_class = object_class
self.principal_name = principal_name
self.restricted = restricted
self.roles = roles
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return No... | Implementation of the 'ActiveDirectoryPrincipalsAddParameters' model. Specifies the settings for adding new users and groups for Active Directory principals. These users and groups are added to the Cohesity Cluster. You cannot create users and groups in the default Cohesity domain called 'LOCAL' using this operation. A... | ActiveDirectoryPrincipalsAddParameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActiveDirectoryPrincipalsAddParameters:
"""Implementation of the 'ActiveDirectoryPrincipalsAddParameters' model. Specifies the settings for adding new users and groups for Active Directory principals. These users and groups are added to the Cohesity Cluster. You cannot create users and groups in ... | stack_v2_sparse_classes_75kplus_train_006032 | 4,214 | permissive | [
{
"docstring": "Constructor for the ActiveDirectoryPrincipalsAddParameters class",
"name": "__init__",
"signature": "def __init__(self, description=None, domain=None, object_class=None, principal_name=None, restricted=None, roles=None)"
},
{
"docstring": "Creates an instance of this model from a... | 2 | stack_v2_sparse_classes_30k_train_015943 | Implement the Python class `ActiveDirectoryPrincipalsAddParameters` described below.
Class description:
Implementation of the 'ActiveDirectoryPrincipalsAddParameters' model. Specifies the settings for adding new users and groups for Active Directory principals. These users and groups are added to the Cohesity Cluster.... | Implement the Python class `ActiveDirectoryPrincipalsAddParameters` described below.
Class description:
Implementation of the 'ActiveDirectoryPrincipalsAddParameters' model. Specifies the settings for adding new users and groups for Active Directory principals. These users and groups are added to the Cohesity Cluster.... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ActiveDirectoryPrincipalsAddParameters:
"""Implementation of the 'ActiveDirectoryPrincipalsAddParameters' model. Specifies the settings for adding new users and groups for Active Directory principals. These users and groups are added to the Cohesity Cluster. You cannot create users and groups in ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ActiveDirectoryPrincipalsAddParameters:
"""Implementation of the 'ActiveDirectoryPrincipalsAddParameters' model. Specifies the settings for adding new users and groups for Active Directory principals. These users and groups are added to the Cohesity Cluster. You cannot create users and groups in the default C... | the_stack_v2_python_sparse | cohesity_management_sdk/models/active_directory_principals_add_parameters.py | cohesity/management-sdk-python | train | 24 |
b9615ce8bc2be6d03eb7b42569210928da8d3a93 | [
"@functools.wraps(udf)\ndef wrapper() -> None:\n udf_args, udf_kwargs = self._prepare_udf_args(udf=udf, fp_config=fp_config)\n output = udf(*udf_args, **udf_kwargs)\n self.udf_output_receiver.ingest_udf_output(output, fp_config)\nreturn wrapper",
"args = ()\nkwargs = {**self.udf_arg_provider.provide_inpu... | <|body_start_0|>
@functools.wraps(udf)
def wrapper() -> None:
udf_args, udf_kwargs = self._prepare_udf_args(udf=udf, fp_config=fp_config)
output = udf(*udf_args, **udf_kwargs)
self.udf_output_receiver.ingest_udf_output(output, fp_config)
return wrapper
<|end_b... | Class that wraps a user provided function. | UDFWrapper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UDFWrapper:
"""Class that wraps a user provided function."""
def wrap(self, udf: Callable[..., T], fp_config: FeatureProcessorConfig) -> Callable[..., None]:
"""Wrap the provided UDF with the logic defined by the FeatureProcessorConfig. General functionality of the wrapper function i... | stack_v2_sparse_classes_75kplus_train_006033 | 3,203 | permissive | [
{
"docstring": "Wrap the provided UDF with the logic defined by the FeatureProcessorConfig. General functionality of the wrapper function includes but is not limited to loading data sources and ingesting output data to a Feature Group. Args: udf (Callable[..., T]): The feature_processor wrapped user function. f... | 2 | stack_v2_sparse_classes_30k_train_044171 | Implement the Python class `UDFWrapper` described below.
Class description:
Class that wraps a user provided function.
Method signatures and docstrings:
- def wrap(self, udf: Callable[..., T], fp_config: FeatureProcessorConfig) -> Callable[..., None]: Wrap the provided UDF with the logic defined by the FeatureProcess... | Implement the Python class `UDFWrapper` described below.
Class description:
Class that wraps a user provided function.
Method signatures and docstrings:
- def wrap(self, udf: Callable[..., T], fp_config: FeatureProcessorConfig) -> Callable[..., None]: Wrap the provided UDF with the logic defined by the FeatureProcess... | 8d5d7fd8ae1a917ed3e2b988d5e533bce244fd85 | <|skeleton|>
class UDFWrapper:
"""Class that wraps a user provided function."""
def wrap(self, udf: Callable[..., T], fp_config: FeatureProcessorConfig) -> Callable[..., None]:
"""Wrap the provided UDF with the logic defined by the FeatureProcessorConfig. General functionality of the wrapper function i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UDFWrapper:
"""Class that wraps a user provided function."""
def wrap(self, udf: Callable[..., T], fp_config: FeatureProcessorConfig) -> Callable[..., None]:
"""Wrap the provided UDF with the logic defined by the FeatureProcessorConfig. General functionality of the wrapper function includes but i... | the_stack_v2_python_sparse | src/sagemaker/feature_store/feature_processor/_udf_wrapper.py | aws/sagemaker-python-sdk | train | 2,050 |
73b5d26bfaf82db1ad8ceb3734dd735bc719ef4a | [
"if 'id' not in row:\n row['id'] = row['\\ufeffid']\nBOOLEAN_FIELDS = ['has_ordered_answers', 'publish']\nfor boolean_field in BOOLEAN_FIELDS:\n row[boolean_field] = True if row[boolean_field] == 'Yes' else False",
"self._m2m_updated = False\ntag_ids = []\ntags = row.get('tags')\nif tags:\n tags_split = ... | <|body_start_0|>
if 'id' not in row:
row['id'] = row['\ufeffid']
BOOLEAN_FIELDS = ['has_ordered_answers', 'publish']
for boolean_field in BOOLEAN_FIELDS:
row[boolean_field] = True if row[boolean_field] == 'Yes' else False
<|end_body_0|>
<|body_start_1|>
self._m2m... | QuestionResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionResource:
def before_import_row(self, row, **kwargs):
"""- Notion.so adds a BOM identifier before each line And setting from_encoding = 'utf-8-sig' in the QuestionAdmin does not work So we need to fix the 'id' column - Issue with BooleanFields because Notion exports Yes/No"""
... | stack_v2_sparse_classes_75kplus_train_006034 | 15,004 | no_license | [
{
"docstring": "- Notion.so adds a BOM identifier before each line And setting from_encoding = 'utf-8-sig' in the QuestionAdmin does not work So we need to fix the 'id' column - Issue with BooleanFields because Notion exports Yes/No",
"name": "before_import_row",
"signature": "def before_import_row(self... | 3 | stack_v2_sparse_classes_30k_train_018860 | Implement the Python class `QuestionResource` described below.
Class description:
Implement the QuestionResource class.
Method signatures and docstrings:
- def before_import_row(self, row, **kwargs): - Notion.so adds a BOM identifier before each line And setting from_encoding = 'utf-8-sig' in the QuestionAdmin does n... | Implement the Python class `QuestionResource` described below.
Class description:
Implement the QuestionResource class.
Method signatures and docstrings:
- def before_import_row(self, row, **kwargs): - Notion.so adds a BOM identifier before each line And setting from_encoding = 'utf-8-sig' in the QuestionAdmin does n... | 92695bf0416aa0a264d7160785d163f5a3afd555 | <|skeleton|>
class QuestionResource:
def before_import_row(self, row, **kwargs):
"""- Notion.so adds a BOM identifier before each line And setting from_encoding = 'utf-8-sig' in the QuestionAdmin does not work So we need to fix the 'id' column - Issue with BooleanFields because Notion exports Yes/No"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QuestionResource:
def before_import_row(self, row, **kwargs):
"""- Notion.so adds a BOM identifier before each line And setting from_encoding = 'utf-8-sig' in the QuestionAdmin does not work So we need to fix the 'id' column - Issue with BooleanFields because Notion exports Yes/No"""
if 'id' n... | the_stack_v2_python_sparse | api/admin.py | cedricboudinet/know-your-planet | train | 0 | |
e9ae4336674e6b012f9f2f3d5ccfed0d10133d3f | [
"self.connectivityBoundaries = None\nself.connectivityConnections = None\nself.hierarchyBoundaries = None\nself.dualHierarchyBoundaries = None\nself.hierarchyConnections = None\nself.dualHierarchyConnections = None\nself.contacts = None",
"self.connectivityBoundaries = Cluster.clusterBoundaries(contacts=contacts)... | <|body_start_0|>
self.connectivityBoundaries = None
self.connectivityConnections = None
self.hierarchyBoundaries = None
self.dualHierarchyBoundaries = None
self.hierarchyConnections = None
self.dualHierarchyConnections = None
self.contacts = None
<|end_body_0|>
<... | An instance of this class can contain up to six different clusterings of the same data (see below) Clusters can be formed in the following ways: 1) Clustering based on connectivity All boundaries that are linked to each other via connections (connectors) form a boundary cluster. In the same way, all connections that ar... | MultiCluster | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiCluster:
"""An instance of this class can contain up to six different clusterings of the same data (see below) Clusters can be formed in the following ways: 1) Clustering based on connectivity All boundaries that are linked to each other via connections (connectors) form a boundary cluster. ... | stack_v2_sparse_classes_75kplus_train_006035 | 15,116 | permissive | [
{
"docstring": "Initializes attributes",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Clusters boundaries and connections based on connectivity. Arguments: - contacts: (Contacts) specifies contacts between connections and boundaries - topology: if True calculates topo... | 4 | stack_v2_sparse_classes_30k_train_048735 | Implement the Python class `MultiCluster` described below.
Class description:
An instance of this class can contain up to six different clusterings of the same data (see below) Clusters can be formed in the following ways: 1) Clustering based on connectivity All boundaries that are linked to each other via connections... | Implement the Python class `MultiCluster` described below.
Class description:
An instance of this class can contain up to six different clusterings of the same data (see below) Clusters can be formed in the following ways: 1) Clustering based on connectivity All boundaries that are linked to each other via connections... | 1370bfedae2ad5e6cdd1dc08395eb9e95b4a8596 | <|skeleton|>
class MultiCluster:
"""An instance of this class can contain up to six different clusterings of the same data (see below) Clusters can be formed in the following ways: 1) Clustering based on connectivity All boundaries that are linked to each other via connections (connectors) form a boundary cluster. ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiCluster:
"""An instance of this class can contain up to six different clusterings of the same data (see below) Clusters can be formed in the following ways: 1) Clustering based on connectivity All boundaries that are linked to each other via connections (connectors) form a boundary cluster. In the same w... | the_stack_v2_python_sparse | code/pyto/scene/multi_cluster.py | anmartinezs/pyseg_system | train | 15 |
09626cca2436f5fcf2fa6e519316e06effa4f765 | [
"super(JoinCommand, self).__init__(game, data)\nself.__websocket = websocket\nself.__colors = ['blue', 'yellow', 'purple', 'red', 'black']",
"if self._game.getCurrPlayer() is None and len(self._game.getPlayers()) < 5:\n players = self._game.getPlayers()\n for player in players:\n self.__colors.remove... | <|body_start_0|>
super(JoinCommand, self).__init__(game, data)
self.__websocket = websocket
self.__colors = ['blue', 'yellow', 'purple', 'red', 'black']
<|end_body_0|>
<|body_start_1|>
if self._game.getCurrPlayer() is None and len(self._game.getPlayers()) < 5:
players = self... | Handle joining to game lobby | JoinCommand | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JoinCommand:
"""Handle joining to game lobby"""
def __init__(self, game, data, websocket):
"""Initialize attributes"""
<|body_0|>
def execute(self):
"""If game is not ongoing and we have less than 5 players, add new player and return updated player lobby, else re... | stack_v2_sparse_classes_75kplus_train_006036 | 1,711 | no_license | [
{
"docstring": "Initialize attributes",
"name": "__init__",
"signature": "def __init__(self, game, data, websocket)"
},
{
"docstring": "If game is not ongoing and we have less than 5 players, add new player and return updated player lobby, else return information that client can't join",
"na... | 2 | null | Implement the Python class `JoinCommand` described below.
Class description:
Handle joining to game lobby
Method signatures and docstrings:
- def __init__(self, game, data, websocket): Initialize attributes
- def execute(self): If game is not ongoing and we have less than 5 players, add new player and return updated ... | Implement the Python class `JoinCommand` described below.
Class description:
Handle joining to game lobby
Method signatures and docstrings:
- def __init__(self, game, data, websocket): Initialize attributes
- def execute(self): If game is not ongoing and we have less than 5 players, add new player and return updated ... | d4a2e0f54edd29cef8dbac8840f8b156efd34164 | <|skeleton|>
class JoinCommand:
"""Handle joining to game lobby"""
def __init__(self, game, data, websocket):
"""Initialize attributes"""
<|body_0|>
def execute(self):
"""If game is not ongoing and we have less than 5 players, add new player and return updated player lobby, else re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JoinCommand:
"""Handle joining to game lobby"""
def __init__(self, game, data, websocket):
"""Initialize attributes"""
super(JoinCommand, self).__init__(game, data)
self.__websocket = websocket
self.__colors = ['blue', 'yellow', 'purple', 'red', 'black']
def execute(s... | the_stack_v2_python_sparse | backend/command/JoinCommand.py | mateuszkochanek/carcassone-game | train | 1 |
f5a96f2a739e375fee562d8cc52d74dfc17ca1f5 | [
"logger.debug('Visiting %s', self.novel_url)\nsoup = self.get_soup(self.novel_url)\nself.novel_title = soup.select_one('.breadcrumb-item.active').text.strip()\nlogger.info('Novel title: %s', self.novel_title)\npossible_cover = soup.select_one('img.lazy[alt*=\"Thumbnail\"]')\nif possible_cover:\n self.novel_cover... | <|body_start_0|>
logger.debug('Visiting %s', self.novel_url)
soup = self.get_soup(self.novel_url)
self.novel_title = soup.select_one('.breadcrumb-item.active').text.strip()
logger.info('Novel title: %s', self.novel_title)
possible_cover = soup.select_one('img.lazy[alt*="Thumbnail... | WorldnovelonlineCrawler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorldnovelonlineCrawler:
def read_novel_info(self):
"""Get novel title, autor, cover etc"""
<|body_0|>
def download_chapter_body(self, chapter):
"""Download body of a single chapter and return as clean html format"""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_75kplus_train_006037 | 5,353 | permissive | [
{
"docstring": "Get novel title, autor, cover etc",
"name": "read_novel_info",
"signature": "def read_novel_info(self)"
},
{
"docstring": "Download body of a single chapter and return as clean html format",
"name": "download_chapter_body",
"signature": "def download_chapter_body(self, ch... | 2 | stack_v2_sparse_classes_30k_train_001347 | Implement the Python class `WorldnovelonlineCrawler` described below.
Class description:
Implement the WorldnovelonlineCrawler class.
Method signatures and docstrings:
- def read_novel_info(self): Get novel title, autor, cover etc
- def download_chapter_body(self, chapter): Download body of a single chapter and retur... | Implement the Python class `WorldnovelonlineCrawler` described below.
Class description:
Implement the WorldnovelonlineCrawler class.
Method signatures and docstrings:
- def read_novel_info(self): Get novel title, autor, cover etc
- def download_chapter_body(self, chapter): Download body of a single chapter and retur... | 451e816ab03c8466be90f6f0b3eaa52d799140ce | <|skeleton|>
class WorldnovelonlineCrawler:
def read_novel_info(self):
"""Get novel title, autor, cover etc"""
<|body_0|>
def download_chapter_body(self, chapter):
"""Download body of a single chapter and return as clean html format"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WorldnovelonlineCrawler:
def read_novel_info(self):
"""Get novel title, autor, cover etc"""
logger.debug('Visiting %s', self.novel_url)
soup = self.get_soup(self.novel_url)
self.novel_title = soup.select_one('.breadcrumb-item.active').text.strip()
logger.info('Novel tit... | the_stack_v2_python_sparse | lncrawl/sources/worldnovelonline.py | NNTin/lightnovel-crawler | train | 2 | |
da75dc4d4529accb0a160a28a858f60919b200d1 | [
"self.calibrator = CameraCalibrator()\nself.binarizer = Binarizer()\nself.warper = Warper()\nself.visualizer = Visualizer(self.warper)\nself.lane = Lane(image_size=frame_size)\nself.calibrator.loadParameters('./src/LaneLineDetector/calibration_coefficients.p')",
"undist = self.calibrator.undistort(frame)\nbinariz... | <|body_start_0|>
self.calibrator = CameraCalibrator()
self.binarizer = Binarizer()
self.warper = Warper()
self.visualizer = Visualizer(self.warper)
self.lane = Lane(image_size=frame_size)
self.calibrator.loadParameters('./src/LaneLineDetector/calibration_coefficients.p')
... | lane line Detector | LaneLineDetector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LaneLineDetector:
"""lane line Detector"""
def __init__(self, frame_size=(720, 1280)):
"""Initialize lane line detector"""
<|body_0|>
def process_frame(self, frame):
"""Process a video frame"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.c... | stack_v2_sparse_classes_75kplus_train_006038 | 1,174 | no_license | [
{
"docstring": "Initialize lane line detector",
"name": "__init__",
"signature": "def __init__(self, frame_size=(720, 1280))"
},
{
"docstring": "Process a video frame",
"name": "process_frame",
"signature": "def process_frame(self, frame)"
}
] | 2 | stack_v2_sparse_classes_30k_train_043925 | Implement the Python class `LaneLineDetector` described below.
Class description:
lane line Detector
Method signatures and docstrings:
- def __init__(self, frame_size=(720, 1280)): Initialize lane line detector
- def process_frame(self, frame): Process a video frame | Implement the Python class `LaneLineDetector` described below.
Class description:
lane line Detector
Method signatures and docstrings:
- def __init__(self, frame_size=(720, 1280)): Initialize lane line detector
- def process_frame(self, frame): Process a video frame
<|skeleton|>
class LaneLineDetector:
"""lane l... | c557975ad5e00fdbd4c483c1d3decf1d51b87c73 | <|skeleton|>
class LaneLineDetector:
"""lane line Detector"""
def __init__(self, frame_size=(720, 1280)):
"""Initialize lane line detector"""
<|body_0|>
def process_frame(self, frame):
"""Process a video frame"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LaneLineDetector:
"""lane line Detector"""
def __init__(self, frame_size=(720, 1280)):
"""Initialize lane line detector"""
self.calibrator = CameraCalibrator()
self.binarizer = Binarizer()
self.warper = Warper()
self.visualizer = Visualizer(self.warper)
sel... | the_stack_v2_python_sparse | src/LaneLineDetector/LaneLineDetector.py | thoomi/vehicle-detection | train | 5 |
88320bf04ef783974d8ea0e868ae1dcb52f252c4 | [
"self.params = prior\nchain = LikelihoodComputationChain(min=self.params[:, 1], max=self.params[:, 2])\nchain.params = self.params\nif like_func == 'n':\n chain.addLikelihoodModule(LikeModule(data, nbins, noise, div, model_name))\nelse:\n chain.addLikelihoodModule(ComplexLikeModule(data, nbins, noise, div))\n... | <|body_start_0|>
self.params = prior
chain = LikelihoodComputationChain(min=self.params[:, 1], max=self.params[:, 2])
chain.params = self.params
if like_func == 'n':
chain.addLikelihoodModule(LikeModule(data, nbins, noise, div, model_name))
else:
chain.add... | sampler & MPI sampler class | RunMCMC | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunMCMC:
"""sampler & MPI sampler class"""
def __init__(self, prior, data, nbins, model, noise=0.0, div=1.0, like_func='n'):
""":param prior: define the prior according to CosmoHammer format :param data: load your data :param nbins: number of k-modes in powerspectrum OR number of tri... | stack_v2_sparse_classes_75kplus_train_006039 | 5,165 | permissive | [
{
"docstring": ":param prior: define the prior according to CosmoHammer format :param data: load your data :param nbins: number of k-modes in powerspectrum OR number of triangle contributions in bispectrum (for covariance matrix) :param noise: system noise, e.g. SKA, MWA noise response (if any), default 0.0, :p... | 5 | stack_v2_sparse_classes_30k_train_020165 | Implement the Python class `RunMCMC` described below.
Class description:
sampler & MPI sampler class
Method signatures and docstrings:
- def __init__(self, prior, data, nbins, model, noise=0.0, div=1.0, like_func='n'): :param prior: define the prior according to CosmoHammer format :param data: load your data :param n... | Implement the Python class `RunMCMC` described below.
Class description:
sampler & MPI sampler class
Method signatures and docstrings:
- def __init__(self, prior, data, nbins, model, noise=0.0, div=1.0, like_func='n'): :param prior: define the prior according to CosmoHammer format :param data: load your data :param n... | 01df70553d2bd166f93c2044efb0050076f78fdb | <|skeleton|>
class RunMCMC:
"""sampler & MPI sampler class"""
def __init__(self, prior, data, nbins, model, noise=0.0, div=1.0, like_func='n'):
""":param prior: define the prior according to CosmoHammer format :param data: load your data :param nbins: number of k-modes in powerspectrum OR number of tri... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RunMCMC:
"""sampler & MPI sampler class"""
def __init__(self, prior, data, nbins, model, noise=0.0, div=1.0, like_func='n'):
""":param prior: define the prior according to CosmoHammer format :param data: load your data :param nbins: number of k-modes in powerspectrum OR number of triangle contrib... | the_stack_v2_python_sparse | EmuPBk/MCMC/sampler.py | himmng/EmuPBk | train | 2 |
bf83258315e2f2131319d3940a554ceee47b3074 | [
"self.mothed = mothed\nself.url = url\nself.data = data\nself.headers = headers",
"if self.mothed.lower() == 'get':\n try:\n res = self.s.get(url=self.url, params=self.data, headers=self.headers)\n except Exception as e:\n print('get请求发送错误{}'.format(e))\n else:\n return res.cookies\n... | <|body_start_0|>
self.mothed = mothed
self.url = url
self.data = data
self.headers = headers
<|end_body_0|>
<|body_start_1|>
if self.mothed.lower() == 'get':
try:
res = self.s.get(url=self.url, params=self.data, headers=self.headers)
excep... | 保存cookies信息的请求类 | HttpSession | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HttpSession:
"""保存cookies信息的请求类"""
def __init__(self, mothed, url, data, headers=None):
"""初始化数据 :param mothed: 请求方式 :param url: 请求地址 :param data: 请求参数 :param headers: 请求头"""
<|body_0|>
def request(self):
"""发送请求"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_75kplus_train_006040 | 3,874 | no_license | [
{
"docstring": "初始化数据 :param mothed: 请求方式 :param url: 请求地址 :param data: 请求参数 :param headers: 请求头",
"name": "__init__",
"signature": "def __init__(self, mothed, url, data, headers=None)"
},
{
"docstring": "发送请求",
"name": "request",
"signature": "def request(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_050959 | Implement the Python class `HttpSession` described below.
Class description:
保存cookies信息的请求类
Method signatures and docstrings:
- def __init__(self, mothed, url, data, headers=None): 初始化数据 :param mothed: 请求方式 :param url: 请求地址 :param data: 请求参数 :param headers: 请求头
- def request(self): 发送请求 | Implement the Python class `HttpSession` described below.
Class description:
保存cookies信息的请求类
Method signatures and docstrings:
- def __init__(self, mothed, url, data, headers=None): 初始化数据 :param mothed: 请求方式 :param url: 请求地址 :param data: 请求参数 :param headers: 请求头
- def request(self): 发送请求
<|skeleton|>
class HttpSessi... | 498fd0c5a6e66258e36efea0b31185097057d544 | <|skeleton|>
class HttpSession:
"""保存cookies信息的请求类"""
def __init__(self, mothed, url, data, headers=None):
"""初始化数据 :param mothed: 请求方式 :param url: 请求地址 :param data: 请求参数 :param headers: 请求头"""
<|body_0|>
def request(self):
"""发送请求"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HttpSession:
"""保存cookies信息的请求类"""
def __init__(self, mothed, url, data, headers=None):
"""初始化数据 :param mothed: 请求方式 :param url: 请求地址 :param data: 请求参数 :param headers: 请求头"""
self.mothed = mothed
self.url = url
self.data = data
self.headers = headers
def reque... | the_stack_v2_python_sparse | class21_api/common/myrequests.py | Joker-ice/python_21 | train | 0 |
e3d62106c02d59548f1d722e512d7b05d001b844 | [
"values = self.do_version_changes_for_db()\nvalues['initial_version'] = values['current_version']\ndb_fwcmp = self.dbapi.create_firmware_component(values)\nself._from_db_object(self._context, self, db_fwcmp)",
"updates = self.do_version_changes_for_db()\nup_fwcmp = self.dbapi.update_firmware_component(self.node_i... | <|body_start_0|>
values = self.do_version_changes_for_db()
values['initial_version'] = values['current_version']
db_fwcmp = self.dbapi.create_firmware_component(values)
self._from_db_object(self._context, self, db_fwcmp)
<|end_body_0|>
<|body_start_1|>
updates = self.do_version_... | FirmwareComponent | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FirmwareComponent:
def create(self, context=None):
"""Create a Firmware record in the DB. :param context: Security context. :raises: NodeNotFound if the node is not found. :raises: FirmwareComponentAlreadyExists if the record already exists."""
<|body_0|>
def save(self, cont... | stack_v2_sparse_classes_75kplus_train_006041 | 6,237 | permissive | [
{
"docstring": "Create a Firmware record in the DB. :param context: Security context. :raises: NodeNotFound if the node is not found. :raises: FirmwareComponentAlreadyExists if the record already exists.",
"name": "create",
"signature": "def create(self, context=None)"
},
{
"docstring": "Save up... | 3 | stack_v2_sparse_classes_30k_train_029683 | Implement the Python class `FirmwareComponent` described below.
Class description:
Implement the FirmwareComponent class.
Method signatures and docstrings:
- def create(self, context=None): Create a Firmware record in the DB. :param context: Security context. :raises: NodeNotFound if the node is not found. :raises: F... | Implement the Python class `FirmwareComponent` described below.
Class description:
Implement the FirmwareComponent class.
Method signatures and docstrings:
- def create(self, context=None): Create a Firmware record in the DB. :param context: Security context. :raises: NodeNotFound if the node is not found. :raises: F... | ab76ff12e1c3c2208455e917f1a40d4000b4e990 | <|skeleton|>
class FirmwareComponent:
def create(self, context=None):
"""Create a Firmware record in the DB. :param context: Security context. :raises: NodeNotFound if the node is not found. :raises: FirmwareComponentAlreadyExists if the record already exists."""
<|body_0|>
def save(self, cont... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FirmwareComponent:
def create(self, context=None):
"""Create a Firmware record in the DB. :param context: Security context. :raises: NodeNotFound if the node is not found. :raises: FirmwareComponentAlreadyExists if the record already exists."""
values = self.do_version_changes_for_db()
... | the_stack_v2_python_sparse | ironic/objects/firmware.py | openstack/ironic | train | 411 | |
ea95cbc9f7155276329779b065c7482863de34ca | [
"if User.objects.filter(email__iexact=self.cleaned_data['email']):\n raise forms.ValidationError(_('This email address is already in use. Please supply a different email address.'))\nreturn self.cleaned_data['email']",
"if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:\n if self.clea... | <|body_start_0|>
if User.objects.filter(email__iexact=self.cleaned_data['email']):
raise forms.ValidationError(_('This email address is already in use. Please supply a different email address.'))
return self.cleaned_data['email']
<|end_body_0|>
<|body_start_1|>
if 'password1' in sel... | RegistrationForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistrationForm:
def clean_email(self):
"""Validate that the supplied email address is unique for the site."""
<|body_0|>
def clean(self):
"""Verifiy that the values entered into the two password fields match. Note that an error here will end up in ``non_field_error... | stack_v2_sparse_classes_75kplus_train_006042 | 3,948 | no_license | [
{
"docstring": "Validate that the supplied email address is unique for the site.",
"name": "clean_email",
"signature": "def clean_email(self)"
},
{
"docstring": "Verifiy that the values entered into the two password fields match. Note that an error here will end up in ``non_field_errors()`` beca... | 2 | stack_v2_sparse_classes_30k_train_044532 | Implement the Python class `RegistrationForm` described below.
Class description:
Implement the RegistrationForm class.
Method signatures and docstrings:
- def clean_email(self): Validate that the supplied email address is unique for the site.
- def clean(self): Verifiy that the values entered into the two password f... | Implement the Python class `RegistrationForm` described below.
Class description:
Implement the RegistrationForm class.
Method signatures and docstrings:
- def clean_email(self): Validate that the supplied email address is unique for the site.
- def clean(self): Verifiy that the values entered into the two password f... | 3031a38a88a96d1ade8e2391cb455fa9921e7549 | <|skeleton|>
class RegistrationForm:
def clean_email(self):
"""Validate that the supplied email address is unique for the site."""
<|body_0|>
def clean(self):
"""Verifiy that the values entered into the two password fields match. Note that an error here will end up in ``non_field_error... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RegistrationForm:
def clean_email(self):
"""Validate that the supplied email address is unique for the site."""
if User.objects.filter(email__iexact=self.cleaned_data['email']):
raise forms.ValidationError(_('This email address is already in use. Please supply a different email add... | the_stack_v2_python_sparse | accaunt/forms.py | MaratFM/Djanym | train | 0 | |
937135a92632fb73ac5d0a1bb6b88ba0fc812868 | [
"for source, expected in self.valid_specifiers:\n result = _spec(parse_connection(source))\n frm = u'{0}: was {1}, expected {2}'\n msg = frm.format(source, result, expected)\n self.assertEqual(expected, result, msg)",
"for spec in self.invalid_specificers:\n try:\n parse_connection(spec)\n ... | <|body_start_0|>
for source, expected in self.valid_specifiers:
result = _spec(parse_connection(source))
frm = u'{0}: was {1}, expected {2}'
msg = frm.format(source, result, expected)
self.assertEqual(expected, result, msg)
<|end_body_0|>
<|body_start_1|>
... | Test that parsing connection strings work correctly. | TestParseConnection | [
"LicenseRef-scancode-python-cwi",
"LGPL-2.0-or-later",
"BSD-3-Clause",
"bzip2-1.0.6",
"LicenseRef-scancode-free-unknown",
"GPL-2.0-only",
"LicenseRef-scancode-other-copyleft",
"Sleepycat",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-lat... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestParseConnection:
"""Test that parsing connection strings work correctly."""
def test_valid(self):
"""Test parsing valid versions of connection strings."""
<|body_0|>
def test_invalid(self):
"""Test parsing invalid versions of connection strings. If the connec... | stack_v2_sparse_classes_75kplus_train_006043 | 6,015 | permissive | [
{
"docstring": "Test parsing valid versions of connection strings.",
"name": "test_valid",
"signature": "def test_valid(self)"
},
{
"docstring": "Test parsing invalid versions of connection strings. If the connection string is invalid, a FormatError should be thrown.",
"name": "test_invalid"... | 2 | stack_v2_sparse_classes_30k_train_054438 | Implement the Python class `TestParseConnection` described below.
Class description:
Test that parsing connection strings work correctly.
Method signatures and docstrings:
- def test_valid(self): Test parsing valid versions of connection strings.
- def test_invalid(self): Test parsing invalid versions of connection s... | Implement the Python class `TestParseConnection` described below.
Class description:
Test that parsing connection strings work correctly.
Method signatures and docstrings:
- def test_valid(self): Test parsing valid versions of connection strings.
- def test_invalid(self): Test parsing invalid versions of connection s... | 1e912fd87282be3b3bed48487e6beb0ecb1de339 | <|skeleton|>
class TestParseConnection:
"""Test that parsing connection strings work correctly."""
def test_valid(self):
"""Test parsing valid versions of connection strings."""
<|body_0|>
def test_invalid(self):
"""Test parsing invalid versions of connection strings. If the connec... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestParseConnection:
"""Test that parsing connection strings work correctly."""
def test_valid(self):
"""Test parsing valid versions of connection strings."""
for source, expected in self.valid_specifiers:
result = _spec(parse_connection(source))
frm = u'{0}: was {... | the_stack_v2_python_sparse | mysql-utilities-1.6.0/unit_tests/test_options.py | scavarda/mysql-dbcompare | train | 2 |
8860e7bbd4f50160588dd6d64b333f00cb10e9f5 | [
"with open(filename, 'r', encoding='utf-8') as file:\n sentiment = json.load(file)\n segments = []\n for sen in sentiment:\n segments.append(Interval(begin=sen['begin'], end=sen['end'], data=SentimentData(text=sen['text'], pos=sen['pos'], neg=sen['neg'], neu=sen['neu'])))\n return cls(filename=fi... | <|body_start_0|>
with open(filename, 'r', encoding='utf-8') as file:
sentiment = json.load(file)
segments = []
for sen in sentiment:
segments.append(Interval(begin=sen['begin'], end=sen['end'], data=SentimentData(text=sen['text'], pos=sen['pos'], neg=sen['neg'... | Class for storing sentiment scores of transcribed sentences. Stores sentiment scores as intervals in an interval tree. The scores are stored in the `data` attribute of each interval. | SentimentAnnotation | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SentimentAnnotation:
"""Class for storing sentiment scores of transcribed sentences. Stores sentiment scores as intervals in an interval tree. The scores are stored in the `data` attribute of each interval."""
def from_json(cls, filename: str, extra_filename: Optional[str]=None):
"""... | stack_v2_sparse_classes_75kplus_train_006044 | 34,060 | permissive | [
{
"docstring": "Load a sentiment annotation from a JSON file. Parameters ---------- filename: str Name of the JSON file from which the object should be loaded. Must have a .json ending.",
"name": "from_json",
"signature": "def from_json(cls, filename: str, extra_filename: Optional[str]=None)"
},
{
... | 2 | null | Implement the Python class `SentimentAnnotation` described below.
Class description:
Class for storing sentiment scores of transcribed sentences. Stores sentiment scores as intervals in an interval tree. The scores are stored in the `data` attribute of each interval.
Method signatures and docstrings:
- def from_json(... | Implement the Python class `SentimentAnnotation` described below.
Class description:
Class for storing sentiment scores of transcribed sentences. Stores sentiment scores as intervals in an interval tree. The scores are stored in the `data` attribute of each interval.
Method signatures and docstrings:
- def from_json(... | fe7cfdd3ff6c6d2bf1f1f7825faf8c17777b309b | <|skeleton|>
class SentimentAnnotation:
"""Class for storing sentiment scores of transcribed sentences. Stores sentiment scores as intervals in an interval tree. The scores are stored in the `data` attribute of each interval."""
def from_json(cls, filename: str, extra_filename: Optional[str]=None):
"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SentimentAnnotation:
"""Class for storing sentiment scores of transcribed sentences. Stores sentiment scores as intervals in an interval tree. The scores are stored in the `data` attribute of each interval."""
def from_json(cls, filename: str, extra_filename: Optional[str]=None):
"""Load a sentim... | the_stack_v2_python_sparse | mexca/data.py | mexca/mexca | train | 7 |
4786e4dea1ae7490d785e6dc512f42cc222285b8 | [
"super(pbs_sm, self).check()\nif 'WALLTIME' not in PAR:\n setattr(PAR, 'WALLTIME', 30.0)\nif 'MEMORY' not in PAR:\n setattr(PAR, 'MEMORY', 0)\nif 'NODESIZE' not in PAR:\n raise ParameterError(PAR, 'NODESIZE')\nif 'PBSARGS' not in PAR:\n setattr(PAR, 'PBSARGS', '')",
"unix.mkdir(PATH.OUTPUT)\nunix.cd(P... | <|body_start_0|>
super(pbs_sm, self).check()
if 'WALLTIME' not in PAR:
setattr(PAR, 'WALLTIME', 30.0)
if 'MEMORY' not in PAR:
setattr(PAR, 'MEMORY', 0)
if 'NODESIZE' not in PAR:
raise ParameterError(PAR, 'NODESIZE')
if 'PBSARGS' not in PAR:
... | An interface through which to submit workflows, run tasks in serial or parallel, and perform other system functions. By hiding environment details behind a python interface layer, these classes provide a consistent command set across different computing environments. Intermediate files are written to a global scratch p... | pbs_sm | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class pbs_sm:
"""An interface through which to submit workflows, run tasks in serial or parallel, and perform other system functions. By hiding environment details behind a python interface layer, these classes provide a consistent command set across different computing environments. Intermediate files... | stack_v2_sparse_classes_75kplus_train_006045 | 2,739 | permissive | [
{
"docstring": "Checks parameters and paths",
"name": "check",
"signature": "def check(self)"
},
{
"docstring": "Submits job",
"name": "submit",
"signature": "def submit(self, workflow)"
}
] | 2 | null | Implement the Python class `pbs_sm` described below.
Class description:
An interface through which to submit workflows, run tasks in serial or parallel, and perform other system functions. By hiding environment details behind a python interface layer, these classes provide a consistent command set across different com... | Implement the Python class `pbs_sm` described below.
Class description:
An interface through which to submit workflows, run tasks in serial or parallel, and perform other system functions. By hiding environment details behind a python interface layer, these classes provide a consistent command set across different com... | 47725866ac516767c9eb536f4a0e86c7c0b97482 | <|skeleton|>
class pbs_sm:
"""An interface through which to submit workflows, run tasks in serial or parallel, and perform other system functions. By hiding environment details behind a python interface layer, these classes provide a consistent command set across different computing environments. Intermediate files... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class pbs_sm:
"""An interface through which to submit workflows, run tasks in serial or parallel, and perform other system functions. By hiding environment details behind a python interface layer, these classes provide a consistent command set across different computing environments. Intermediate files are written ... | the_stack_v2_python_sparse | seisflows/system/pbs_sm.py | yanhuay/seisflows | train | 1 |
e77d4937a723b5a13132dbb3ecb6e9296ca9dc86 | [
"super().__init__()\nself.cost_class = cost_class\nself.cost_bbox = cost_bbox\nself.cost_giou = cost_giou\nassert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, 'all costs cant be 0'",
"bs, num_queries = outputs['pred_logits'].shape[:2]\nout_prob = outputs['pred_logits'].flatten(0, 1).softmax(-1)\nout_bbox ... | <|body_start_0|>
super().__init__()
self.cost_class = cost_class
self.cost_bbox = cost_bbox
self.cost_giou = cost_giou
assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, 'all costs cant be 0'
<|end_body_0|>
<|body_start_1|>
bs, num_queries = outputs['pred_logits... | This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions, while the others are un-matched (... | HungarianMatcher | [
"BSD-3-Clause",
"BSD-2-Clause",
"LicenseRef-scancode-secret-labs-2011",
"LicenseRef-scancode-generic-cla",
"BSL-1.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HungarianMatcher:
"""This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case, we do a 1-to-1 matching of the best pr... | stack_v2_sparse_classes_75kplus_train_006046 | 34,942 | permissive | [
{
"docstring": "Creates the matcher Params: cost_class: This is the relative weight of the classification error in the matching cost cost_bbox: This is the relative weight of the L1 error of the bounding box coordinates in the matching cost cost_giou: This is the relative weight of the giou loss of the bounding... | 2 | null | Implement the Python class `HungarianMatcher` described below.
Class description:
This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case,... | Implement the Python class `HungarianMatcher` described below.
Class description:
This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case,... | a6f7dd4707ac116c0f5fb5f44f42429f38d23ab4 | <|skeleton|>
class HungarianMatcher:
"""This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case, we do a 1-to-1 matching of the best pr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HungarianMatcher:
"""This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions, wh... | the_stack_v2_python_sparse | benchmarks/functional_autograd_benchmark/torchvision_models.py | pytorch/pytorch | train | 77,092 |
0e5b547ca093c89e0c5c65b00b444dcc81d6b077 | [
"api = python_otbr_api.OTBR(otbr_url, async_get_clientsession(self.hass), 10)\nif await api.get_active_dataset_tlvs() is None:\n allowed_channel = await get_allowed_channel(self.hass, otbr_url)\n thread_dataset_channel = None\n thread_dataset_tlv = await async_get_preferred_dataset(self.hass)\n if threa... | <|body_start_0|>
api = python_otbr_api.OTBR(otbr_url, async_get_clientsession(self.hass), 10)
if await api.get_active_dataset_tlvs() is None:
allowed_channel = await get_allowed_channel(self.hass, otbr_url)
thread_dataset_channel = None
thread_dataset_tlv = await asyn... | Handle a config flow for Open Thread Border Router. | OTBRConfigFlow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OTBRConfigFlow:
"""Handle a config flow for Open Thread Border Router."""
async def _connect_and_set_dataset(self, otbr_url: str) -> None:
"""Connect to the OTBR and create or apply a dataset if it doesn't have one."""
<|body_0|>
async def async_step_user(self, user_inpu... | stack_v2_sparse_classes_75kplus_train_006047 | 4,982 | permissive | [
{
"docstring": "Connect to the OTBR and create or apply a dataset if it doesn't have one.",
"name": "_connect_and_set_dataset",
"signature": "async def _connect_and_set_dataset(self, otbr_url: str) -> None"
},
{
"docstring": "Set up by user.",
"name": "async_step_user",
"signature": "asy... | 3 | stack_v2_sparse_classes_30k_val_000323 | Implement the Python class `OTBRConfigFlow` described below.
Class description:
Handle a config flow for Open Thread Border Router.
Method signatures and docstrings:
- async def _connect_and_set_dataset(self, otbr_url: str) -> None: Connect to the OTBR and create or apply a dataset if it doesn't have one.
- async def... | Implement the Python class `OTBRConfigFlow` described below.
Class description:
Handle a config flow for Open Thread Border Router.
Method signatures and docstrings:
- async def _connect_and_set_dataset(self, otbr_url: str) -> None: Connect to the OTBR and create or apply a dataset if it doesn't have one.
- async def... | 2e65b77b2b5c17919939481f327963abdfdc53f0 | <|skeleton|>
class OTBRConfigFlow:
"""Handle a config flow for Open Thread Border Router."""
async def _connect_and_set_dataset(self, otbr_url: str) -> None:
"""Connect to the OTBR and create or apply a dataset if it doesn't have one."""
<|body_0|>
async def async_step_user(self, user_inpu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OTBRConfigFlow:
"""Handle a config flow for Open Thread Border Router."""
async def _connect_and_set_dataset(self, otbr_url: str) -> None:
"""Connect to the OTBR and create or apply a dataset if it doesn't have one."""
api = python_otbr_api.OTBR(otbr_url, async_get_clientsession(self.hass... | the_stack_v2_python_sparse | homeassistant/components/otbr/config_flow.py | konnected-io/home-assistant | train | 24 |
fa7290313a58eae2c6fe61233ab168b1abf1fb46 | [
"tau_sorted = self._sort_tau_by_y(0)\nfor itr in range(self.n_nodes - 1):\n ind = int(tau_sorted[itr, 0])\n copula = Bivariate.select_copula(self.u_matrix[:, (0, ind)])\n name, theta = (copula.copula_type, copula.theta)\n new_edge = Edge(itr, 0, ind, name, theta)\n new_edge.tau = self.tau_matrix[0, i... | <|body_start_0|>
tau_sorted = self._sort_tau_by_y(0)
for itr in range(self.n_nodes - 1):
ind = int(tau_sorted[itr, 0])
copula = Bivariate.select_copula(self.u_matrix[:, (0, ind)])
name, theta = (copula.copula_type, copula.theta)
new_edge = Edge(itr, 0, ind... | Tree for a C-vine copula. | CenterTree | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CenterTree:
"""Tree for a C-vine copula."""
def _build_first_tree(self):
"""Build first level tree."""
<|body_0|>
def _build_kth_tree(self):
"""Build k-th level tree."""
<|body_1|>
def get_anchor(self):
"""Find anchor variable with highest su... | stack_v2_sparse_classes_75kplus_train_006048 | 22,020 | permissive | [
{
"docstring": "Build first level tree.",
"name": "_build_first_tree",
"signature": "def _build_first_tree(self)"
},
{
"docstring": "Build k-th level tree.",
"name": "_build_kth_tree",
"signature": "def _build_kth_tree(self)"
},
{
"docstring": "Find anchor variable with highest s... | 3 | null | Implement the Python class `CenterTree` described below.
Class description:
Tree for a C-vine copula.
Method signatures and docstrings:
- def _build_first_tree(self): Build first level tree.
- def _build_kth_tree(self): Build k-th level tree.
- def get_anchor(self): Find anchor variable with highest sum of dependence... | Implement the Python class `CenterTree` described below.
Class description:
Tree for a C-vine copula.
Method signatures and docstrings:
- def _build_first_tree(self): Build first level tree.
- def _build_kth_tree(self): Build k-th level tree.
- def get_anchor(self): Find anchor variable with highest sum of dependence... | 4de54e946ecb1e2bf831874e6a00a7d04d302804 | <|skeleton|>
class CenterTree:
"""Tree for a C-vine copula."""
def _build_first_tree(self):
"""Build first level tree."""
<|body_0|>
def _build_kth_tree(self):
"""Build k-th level tree."""
<|body_1|>
def get_anchor(self):
"""Find anchor variable with highest su... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CenterTree:
"""Tree for a C-vine copula."""
def _build_first_tree(self):
"""Build first level tree."""
tau_sorted = self._sort_tau_by_y(0)
for itr in range(self.n_nodes - 1):
ind = int(tau_sorted[itr, 0])
copula = Bivariate.select_copula(self.u_matrix[:, (0... | the_stack_v2_python_sparse | copulas/multivariate/tree.py | pvk-developer/Copulas | train | 0 |
e1e2074cd9c8f90baffffb2d96d4f32b5f4b0646 | [
"test_jobposting = JobPosting(title='Postdoctoral Researcher', description='Some description', link='http:/jobs.com/awesomejob', active=True)\ntest_jobposting.save()\nself.assertEqual(test_jobposting.pk, 1)",
"test_jobposting = JobPosting(title='Postdoctoral Researcher', description='Some description', link='http... | <|body_start_0|>
test_jobposting = JobPosting(title='Postdoctoral Researcher', description='Some description', link='http:/jobs.com/awesomejob', active=True)
test_jobposting.save()
self.assertEqual(test_jobposting.pk, 1)
<|end_body_0|>
<|body_start_1|>
test_jobposting = JobPosting(title... | Tests the model attributes of ::class:`JobPosting` objects contained in the ::mod:`personnel` app. | JobPostingModelTests | [
"CC0-1.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JobPostingModelTests:
"""Tests the model attributes of ::class:`JobPosting` objects contained in the ::mod:`personnel` app."""
def test_create_jobposting_minimal(self):
"""This is a test for creating a new ::class:`JobPosting` object, with only the minimum fields being entered"""
... | stack_v2_sparse_classes_75kplus_train_006049 | 5,452 | permissive | [
{
"docstring": "This is a test for creating a new ::class:`JobPosting` object, with only the minimum fields being entered",
"name": "test_create_jobposting_minimal",
"signature": "def test_create_jobposting_minimal(self)"
},
{
"docstring": "This is a test for creating a new ::class:`JobPosting` ... | 3 | stack_v2_sparse_classes_30k_train_014136 | Implement the Python class `JobPostingModelTests` described below.
Class description:
Tests the model attributes of ::class:`JobPosting` objects contained in the ::mod:`personnel` app.
Method signatures and docstrings:
- def test_create_jobposting_minimal(self): This is a test for creating a new ::class:`JobPosting` ... | Implement the Python class `JobPostingModelTests` described below.
Class description:
Tests the model attributes of ::class:`JobPosting` objects contained in the ::mod:`personnel` app.
Method signatures and docstrings:
- def test_create_jobposting_minimal(self): This is a test for creating a new ::class:`JobPosting` ... | d6f6c9c068bbf668c253e5943d9514947023e66d | <|skeleton|>
class JobPostingModelTests:
"""Tests the model attributes of ::class:`JobPosting` objects contained in the ::mod:`personnel` app."""
def test_create_jobposting_minimal(self):
"""This is a test for creating a new ::class:`JobPosting` object, with only the minimum fields being entered"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JobPostingModelTests:
"""Tests the model attributes of ::class:`JobPosting` objects contained in the ::mod:`personnel` app."""
def test_create_jobposting_minimal(self):
"""This is a test for creating a new ::class:`JobPosting` object, with only the minimum fields being entered"""
test_job... | the_stack_v2_python_sparse | personnel/tests.py | BridgesLab/Lab-Website | train | 0 |
55169e4fd536e744475f8442c4d55a4938ea1469 | [
"super(TripletLoss, self).__init__()\nif margin:\n self.parser = margin_ranking_loss_parser\n self.loss = nn.MarginRankingLoss(margin=margin, reduction=reduction)\nelse:\n self.parser = soft_margin_loss_parser\n self.loss = nn.SoftMarginLoss(reduction=reduction)",
"if mask is not None:\n pos_output... | <|body_start_0|>
super(TripletLoss, self).__init__()
if margin:
self.parser = margin_ranking_loss_parser
self.loss = nn.MarginRankingLoss(margin=margin, reduction=reduction)
else:
self.parser = soft_margin_loss_parser
self.loss = nn.SoftMarginLoss(... | TripletLoss is a pairwise ranking loss which is used in FaceNet at first, and implemented by PyTorch in module\\: torch.nn.MarginRankingLoss and torch.nn.SoftMarginLoss. This module is an integration of those losses as a standardize calling method with other losses implemented in this package. For the calculation, the ... | TripletLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TripletLoss:
"""TripletLoss is a pairwise ranking loss which is used in FaceNet at first, and implemented by PyTorch in module\\: torch.nn.MarginRankingLoss and torch.nn.SoftMarginLoss. This module is an integration of those losses as a standardize calling method with other losses implemented in ... | stack_v2_sparse_classes_75kplus_train_006050 | 9,218 | permissive | [
{
"docstring": "Initialize TripletLoss Args: margin (float, optional): size of margin. Defaults to 1.0. reduction (str, optional): method of reduction. Defaults to None.",
"name": "__init__",
"signature": "def __init__(self, margin: float=1.0, reduction: str=None)"
},
{
"docstring": "Forward cal... | 2 | stack_v2_sparse_classes_30k_test_001107 | Implement the Python class `TripletLoss` described below.
Class description:
TripletLoss is a pairwise ranking loss which is used in FaceNet at first, and implemented by PyTorch in module\\: torch.nn.MarginRankingLoss and torch.nn.SoftMarginLoss. This module is an integration of those losses as a standardize calling m... | Implement the Python class `TripletLoss` described below.
Class description:
TripletLoss is a pairwise ranking loss which is used in FaceNet at first, and implemented by PyTorch in module\\: torch.nn.MarginRankingLoss and torch.nn.SoftMarginLoss. This module is an integration of those losses as a standardize calling m... | 07a6a38c7eb44225f2b22f332081f697c3b92894 | <|skeleton|>
class TripletLoss:
"""TripletLoss is a pairwise ranking loss which is used in FaceNet at first, and implemented by PyTorch in module\\: torch.nn.MarginRankingLoss and torch.nn.SoftMarginLoss. This module is an integration of those losses as a standardize calling method with other losses implemented in ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TripletLoss:
"""TripletLoss is a pairwise ranking loss which is used in FaceNet at first, and implemented by PyTorch in module\\: torch.nn.MarginRankingLoss and torch.nn.SoftMarginLoss. This module is an integration of those losses as a standardize calling method with other losses implemented in this package.... | the_stack_v2_python_sparse | torecsys/losses/ltr/pairwise_ranking_loss.py | zwcdp/torecsys | train | 0 |
c0709c5c31e7f9d512437e0ac0fe066f69e96560 | [
"self.filters = filters\nself.kernel_size = kernel_size\nself.strides = [1] + list(strides) + [1]\nself.padding = padding\nself.l1 = l1_reg\nself.l2 = l2_reg\nself.use_bias = use_bias\nself.init_fn = init_fn",
"n_samples, (height, width, channels) = self._get_X_dims(X)\nW_shape, b_shape = self._weight_shapes(chan... | <|body_start_0|>
self.filters = filters
self.kernel_size = kernel_size
self.strides = [1] + list(strides) + [1]
self.padding = padding
self.l1 = l1_reg
self.l2 = l2_reg
self.use_bias = use_bias
self.init_fn = init_fn
<|end_body_0|>
<|body_start_1|>
... | A 2D convolution layer. This layer uses maximum likelihood or maximum *a-posteriori* inference to learn the convolutional kernels and biases, and so also returns complexity penalities (l1 or l2) for the weights and biases. Parameters ---------- filters : int the dimension of the output of this layer (i.e. the number of... | Conv2D | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Conv2D:
"""A 2D convolution layer. This layer uses maximum likelihood or maximum *a-posteriori* inference to learn the convolutional kernels and biases, and so also returns complexity penalities (l1 or l2) for the weights and biases. Parameters ---------- filters : int the dimension of the output... | stack_v2_sparse_classes_75kplus_train_006051 | 43,510 | permissive | [
{
"docstring": "Create and instance of a variational Conv2D layer.",
"name": "__init__",
"signature": "def __init__(self, filters, kernel_size, strides=(1, 1), padding='SAME', l1_reg=0.0, l2_reg=0.0, use_bias=True, init_fn='glorot_trunc')"
},
{
"docstring": "Build the graph of this layer.",
... | 3 | null | Implement the Python class `Conv2D` described below.
Class description:
A 2D convolution layer. This layer uses maximum likelihood or maximum *a-posteriori* inference to learn the convolutional kernels and biases, and so also returns complexity penalities (l1 or l2) for the weights and biases. Parameters ---------- fi... | Implement the Python class `Conv2D` described below.
Class description:
A 2D convolution layer. This layer uses maximum likelihood or maximum *a-posteriori* inference to learn the convolutional kernels and biases, and so also returns complexity penalities (l1 or l2) for the weights and biases. Parameters ---------- fi... | 53a3de23dce4d607ffec92be936e83d2dd7ebb3c | <|skeleton|>
class Conv2D:
"""A 2D convolution layer. This layer uses maximum likelihood or maximum *a-posteriori* inference to learn the convolutional kernels and biases, and so also returns complexity penalities (l1 or l2) for the weights and biases. Parameters ---------- filters : int the dimension of the output... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Conv2D:
"""A 2D convolution layer. This layer uses maximum likelihood or maximum *a-posteriori* inference to learn the convolutional kernels and biases, and so also returns complexity penalities (l1 or l2) for the weights and biases. Parameters ---------- filters : int the dimension of the output of this laye... | the_stack_v2_python_sparse | aboleth/layers.py | LaplaceKorea/aboleth | train | 0 |
b13c87c27a6a06a321f88da128ae6cfa4be208a0 | [
"if noun_tags == None:\n tool_factory = core.KBBenchmark.singleton().run_tools[run_name]\n pos_tagger = tool_factory.posTagger(document.language)\n noun_tags = pos_tagger.tagset()[nlp_tool_interface.KBPOSTaggerI.POSTagKey.NOUN]\nif adjective_tags == None:\n tool_factory = core.KBBenchmark.singleton().ru... | <|body_start_0|>
if noun_tags == None:
tool_factory = core.KBBenchmark.singleton().run_tools[run_name]
pos_tagger = tool_factory.posTagger(document.language)
noun_tags = pos_tagger.tagset()[nlp_tool_interface.KBPOSTaggerI.POSTagKey.NOUN]
if adjective_tags == None:
... | French pattern matching candidate extractor that filters useless adjectives. Candidate extractor providing only textual units that match the POS tag pattern C{N+A?}. When the adjective is not derived from a noun, only the modified noun is extracted. | FrenchRefinedNounPhraseExtractor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FrenchRefinedNounPhraseExtractor:
"""French pattern matching candidate extractor that filters useless adjectives. Candidate extractor providing only textual units that match the POS tag pattern C{N+A?}. When the adjective is not derived from a noun, only the modified noun is extracted."""
de... | stack_v2_sparse_classes_75kplus_train_006052 | 7,049 | no_license | [
{
"docstring": "Constructor. Args: name: The C{string} name of the component. run_name: The C{string} name of the run for which the component is affected to. shared: True if the component shares informations with equivalent components (same name). lazy_mode: True if the component load precomputed data. False, o... | 3 | stack_v2_sparse_classes_30k_train_045642 | Implement the Python class `FrenchRefinedNounPhraseExtractor` described below.
Class description:
French pattern matching candidate extractor that filters useless adjectives. Candidate extractor providing only textual units that match the POS tag pattern C{N+A?}. When the adjective is not derived from a noun, only the... | Implement the Python class `FrenchRefinedNounPhraseExtractor` described below.
Class description:
French pattern matching candidate extractor that filters useless adjectives. Candidate extractor providing only textual units that match the POS tag pattern C{N+A?}. When the adjective is not derived from a noun, only the... | a66cf98b11260d2b74cd990f36f5dcde192b0346 | <|skeleton|>
class FrenchRefinedNounPhraseExtractor:
"""French pattern matching candidate extractor that filters useless adjectives. Candidate extractor providing only textual units that match the POS tag pattern C{N+A?}. When the adjective is not derived from a noun, only the modified noun is extracted."""
de... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FrenchRefinedNounPhraseExtractor:
"""French pattern matching candidate extractor that filters useless adjectives. Candidate extractor providing only textual units that match the POS tag pattern C{N+A?}. When the adjective is not derived from a noun, only the modified noun is extracted."""
def __init__(se... | the_stack_v2_python_sparse | src/keybench/main/component/implementation/candidate_extractor/french_refined_noun_phrase_extractor.py | Archer-W/KeyBench | train | 0 |
6ecf94fd54dd808b92f0d82d8915328231df2146 | [
"super(Door, self).__init__('Door', EntityType.OTHER, '+', libtcod.white)\nself.closed = True\nself.locked = False\nself.blocks_sight = True\nself.blocks_move = True",
"if not self.closed:\n ui.Screens.msg.add_message('This door is already open.')\n return\nself.closed = False\nself.blocks_sight = False\nse... | <|body_start_0|>
super(Door, self).__init__('Door', EntityType.OTHER, '+', libtcod.white)
self.closed = True
self.locked = False
self.blocks_sight = True
self.blocks_move = True
<|end_body_0|>
<|body_start_1|>
if not self.closed:
ui.Screens.msg.add_message('T... | Door entity. Can be opened/closed and destroyed. May be locked, or opened by some other means. | Door | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Door:
"""Door entity. Can be opened/closed and destroyed. May be locked, or opened by some other means."""
def __init__(self):
"""Create door."""
<|body_0|>
def action_open(self):
"""Try and open the door."""
<|body_1|>
def action_close(self):
... | stack_v2_sparse_classes_75kplus_train_006053 | 1,994 | no_license | [
{
"docstring": "Create door.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Try and open the door.",
"name": "action_open",
"signature": "def action_open(self)"
},
{
"docstring": "Try and close the door.",
"name": "action_close",
"signature": "... | 5 | stack_v2_sparse_classes_30k_test_002986 | Implement the Python class `Door` described below.
Class description:
Door entity. Can be opened/closed and destroyed. May be locked, or opened by some other means.
Method signatures and docstrings:
- def __init__(self): Create door.
- def action_open(self): Try and open the door.
- def action_close(self): Try and cl... | Implement the Python class `Door` described below.
Class description:
Door entity. Can be opened/closed and destroyed. May be locked, or opened by some other means.
Method signatures and docstrings:
- def __init__(self): Create door.
- def action_open(self): Try and open the door.
- def action_close(self): Try and cl... | 115f6cc3d5bbdb7d2b456f02e122bb1d6894381e | <|skeleton|>
class Door:
"""Door entity. Can be opened/closed and destroyed. May be locked, or opened by some other means."""
def __init__(self):
"""Create door."""
<|body_0|>
def action_open(self):
"""Try and open the door."""
<|body_1|>
def action_close(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Door:
"""Door entity. Can be opened/closed and destroyed. May be locked, or opened by some other means."""
def __init__(self):
"""Create door."""
super(Door, self).__init__('Door', EntityType.OTHER, '+', libtcod.white)
self.closed = True
self.locked = False
self.bl... | the_stack_v2_python_sparse | entities/door.py | ajare/citadel | train | 0 |
81fae067fa86ad63ee8c7d711881972207f35d54 | [
"lat = '{:.2f}'.format(latlong['lat'])\nlng = '{:.2f}'.format(latlong['lng'])\nformat_lat = ''\nformat_lng = ''\nif lat[0] == '-':\n format_lat = lat[1:] + 'S'\nelse:\n format_lat = lat + 'N'\nif lng[0] == '-':\n format_lng = lng[1:] + 'W'\nelse:\n format_lng = lng + 'E'\nreturn '{} {}'.format(format_la... | <|body_start_0|>
lat = '{:.2f}'.format(latlong['lat'])
lng = '{:.2f}'.format(latlong['lng'])
format_lat = ''
format_lng = ''
if lat[0] == '-':
format_lat = lat[1:] + 'S'
else:
format_lat = lat + 'N'
if lng[0] == '-':
format_lng ... | latlong | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class latlong:
def _format_latlong(latlong: dict) -> str:
"""creates a formated string using a dictionary containing a latitude and longitutde"""
<|body_0|>
def get_latlongs(json_dict: dict) -> dict:
"""returns a dictionary with latlongs from a json dictionary"""
<... | stack_v2_sparse_classes_75kplus_train_006054 | 2,967 | no_license | [
{
"docstring": "creates a formated string using a dictionary containing a latitude and longitutde",
"name": "_format_latlong",
"signature": "def _format_latlong(latlong: dict) -> str"
},
{
"docstring": "returns a dictionary with latlongs from a json dictionary",
"name": "get_latlongs",
"... | 3 | null | Implement the Python class `latlong` described below.
Class description:
Implement the latlong class.
Method signatures and docstrings:
- def _format_latlong(latlong: dict) -> str: creates a formated string using a dictionary containing a latitude and longitutde
- def get_latlongs(json_dict: dict) -> dict: returns a ... | Implement the Python class `latlong` described below.
Class description:
Implement the latlong class.
Method signatures and docstrings:
- def _format_latlong(latlong: dict) -> str: creates a formated string using a dictionary containing a latitude and longitutde
- def get_latlongs(json_dict: dict) -> dict: returns a ... | 7a0ff602035e55e5ea9dc0260eca3ca917e83819 | <|skeleton|>
class latlong:
def _format_latlong(latlong: dict) -> str:
"""creates a formated string using a dictionary containing a latitude and longitutde"""
<|body_0|>
def get_latlongs(json_dict: dict) -> dict:
"""returns a dictionary with latlongs from a json dictionary"""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class latlong:
def _format_latlong(latlong: dict) -> str:
"""creates a formated string using a dictionary containing a latitude and longitutde"""
lat = '{:.2f}'.format(latlong['lat'])
lng = '{:.2f}'.format(latlong['lng'])
format_lat = ''
format_lng = ''
if lat[0] == '... | the_stack_v2_python_sparse | ICS 32/ICS 32 Project 3/classes.py | MohamedKharaev/UCI | train | 0 | |
d01a77e195e2981e09c6dd1b79c9c5317bdc7f94 | [
"self._m = matrix\nfor i in xrange(len(matrix)):\n left_sum = 0\n for j in xrange(len(matrix[0])):\n left_sum += matrix[i][j]\n top = 0 if i == 0 else matrix[i - 1][j]\n matrix[i][j] = left_sum + top",
"matrix = self._m\ntotal = matrix[row2][col2]\nleft = 0 if col1 == 0 else matrix[row2... | <|body_start_0|>
self._m = matrix
for i in xrange(len(matrix)):
left_sum = 0
for j in xrange(len(matrix[0])):
left_sum += matrix[i][j]
top = 0 if i == 0 else matrix[i - 1][j]
matrix[i][j] = left_sum + top
<|end_body_0|>
<|body_star... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_75kplus_train_006055 | 892 | no_license | [
{
"docstring": ":type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int",
"name": "sumRegion",
"signature": "def sumRegion(self, row1, col1, row2, col2)"
... | 2 | null | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | 6b607f4aae3a4603e61f2e2b7480fdfba1d9b947 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
self._m = matrix
for i in xrange(len(matrix)):
left_sum = 0
for j in xrange(len(matrix[0])):
left_sum += matrix[i][j]
top = 0 if i == 0 else matrix[i - 1][... | the_stack_v2_python_sparse | 0001-0500/0304.Range Sum Query 2D - Immutable.py | kaiwensun/leetcode | train | 69 | |
5b8a2569de01e7fc8270151c7035b46d129fda4b | [
"class GoAwayError(Exception):\n\n def __init__(self, name, reason):\n self.name = name\n self.reason = reason\n\nclass MyHandler(BaseHandler):\n \"\"\"\n Handler which raises a custom exception \n \"\"\"\n allowed_methods = ('GET',)\n\n def read(self, request):\n ... | <|body_start_0|>
class GoAwayError(Exception):
def __init__(self, name, reason):
self.name = name
self.reason = reason
class MyHandler(BaseHandler):
"""
Handler which raises a custom exception
"""
... | ErrorHandlerTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ErrorHandlerTest:
def test_customized_error_handler(self):
"""Throw a custom error from a handler method and catch (and format) it in an overridden error_handler method on the associated Resource object"""
<|body_0|>
def test_type_error(self):
"""Verify that type err... | stack_v2_sparse_classes_75kplus_train_006056 | 7,124 | permissive | [
{
"docstring": "Throw a custom error from a handler method and catch (and format) it in an overridden error_handler method on the associated Resource object",
"name": "test_customized_error_handler",
"signature": "def test_customized_error_handler(self)"
},
{
"docstring": "Verify that type error... | 3 | stack_v2_sparse_classes_30k_train_052207 | Implement the Python class `ErrorHandlerTest` described below.
Class description:
Implement the ErrorHandlerTest class.
Method signatures and docstrings:
- def test_customized_error_handler(self): Throw a custom error from a handler method and catch (and format) it in an overridden error_handler method on the associa... | Implement the Python class `ErrorHandlerTest` described below.
Class description:
Implement the ErrorHandlerTest class.
Method signatures and docstrings:
- def test_customized_error_handler(self): Throw a custom error from a handler method and catch (and format) it in an overridden error_handler method on the associa... | 1d4724e1d69fae2bb3bbb1bdd3640b253f3f63d3 | <|skeleton|>
class ErrorHandlerTest:
def test_customized_error_handler(self):
"""Throw a custom error from a handler method and catch (and format) it in an overridden error_handler method on the associated Resource object"""
<|body_0|>
def test_type_error(self):
"""Verify that type err... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ErrorHandlerTest:
def test_customized_error_handler(self):
"""Throw a custom error from a handler method and catch (and format) it in an overridden error_handler method on the associated Resource object"""
class GoAwayError(Exception):
def __init__(self, name, reason):
... | the_stack_v2_python_sparse | vendor-local/src/django-piston/piston/tests.py | rtucker-mozilla/minventory | train | 0 | |
3a14b1c867f2c14502bad08049a6b49735b4e163 | [
"super(ContainerLossFunction, self).__init__(scope=scope, **kwargs)\nif isinstance(loss_functions_spec, dict):\n weights_ = {}\n self.loss_functions = {}\n for i, (key, loss_fn_spec) in enumerate(loss_functions_spec.items()):\n if weights is None and 'weight' in loss_fn_spec:\n weights_[k... | <|body_start_0|>
super(ContainerLossFunction, self).__init__(scope=scope, **kwargs)
if isinstance(loss_functions_spec, dict):
weights_ = {}
self.loss_functions = {}
for i, (key, loss_fn_spec) in enumerate(loss_functions_spec.items()):
if weights is Non... | A loss function consisting of n sub-loss functions whose weighted sum is used as the total loss. | ContainerLossFunction | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContainerLossFunction:
"""A loss function consisting of n sub-loss functions whose weighted sum is used as the total loss."""
def __init__(self, loss_functions_spec, weights=None, scope='mixture-loss', **kwargs):
"""Args: loss_functions_spec (Union[Dict[str,dict],Tuple[dict]]): A spe... | stack_v2_sparse_classes_75kplus_train_006057 | 5,330 | permissive | [
{
"docstring": "Args: loss_functions_spec (Union[Dict[str,dict],Tuple[dict]]): A specification dict or tuple with values being the spec dicts for the single loss functions. The `loss` methods expect a dict input or a single tuple input (not as *args) in its first parameter. weights (Optional[List[float]]): If g... | 2 | stack_v2_sparse_classes_30k_train_024480 | Implement the Python class `ContainerLossFunction` described below.
Class description:
A loss function consisting of n sub-loss functions whose weighted sum is used as the total loss.
Method signatures and docstrings:
- def __init__(self, loss_functions_spec, weights=None, scope='mixture-loss', **kwargs): Args: loss_... | Implement the Python class `ContainerLossFunction` described below.
Class description:
A loss function consisting of n sub-loss functions whose weighted sum is used as the total loss.
Method signatures and docstrings:
- def __init__(self, loss_functions_spec, weights=None, scope='mixture-loss', **kwargs): Args: loss_... | a10f382e0681ba1f7aa8e83a8c1483afb8b825c1 | <|skeleton|>
class ContainerLossFunction:
"""A loss function consisting of n sub-loss functions whose weighted sum is used as the total loss."""
def __init__(self, loss_functions_spec, weights=None, scope='mixture-loss', **kwargs):
"""Args: loss_functions_spec (Union[Dict[str,dict],Tuple[dict]]): A spe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ContainerLossFunction:
"""A loss function consisting of n sub-loss functions whose weighted sum is used as the total loss."""
def __init__(self, loss_functions_spec, weights=None, scope='mixture-loss', **kwargs):
"""Args: loss_functions_spec (Union[Dict[str,dict],Tuple[dict]]): A specification di... | the_stack_v2_python_sparse | rlgraph/components/loss_functions/container_loss_function.py | jon-chuang/rlgraph | train | 0 |
4abc95d290571ed1dcf8283a99a7222228ea1810 | [
"super().__init__()\nself.intersection_temperature = intersection_temperature\nself.approximation_mode = approximation_mode",
"if self.intersection_temperature == 0:\n return hard_intersection(left, right)\nelse:\n return gumbel_intersection(left, right, self.intersection_temperature, self.approximation_mod... | <|body_start_0|>
super().__init__()
self.intersection_temperature = intersection_temperature
self.approximation_mode = approximation_mode
<|end_body_0|>
<|body_start_1|>
if self.intersection_temperature == 0:
return hard_intersection(left, right)
else:
re... | All for one Intersection operation as Layer/Module | Intersection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Intersection:
"""All for one Intersection operation as Layer/Module"""
def __init__(self, intersection_temperature: float=0.0, approximation_mode: Optional[str]=None) -> None:
"""Args: intersection_temperature: Gumbel's beta parameter, if non-zero performs the intersection operation ... | stack_v2_sparse_classes_75kplus_train_006058 | 2,590 | no_license | [
{
"docstring": "Args: intersection_temperature: Gumbel's beta parameter, if non-zero performs the intersection operation as described in `Improving Local Identifiability in Probabilistic Box Embeddings <https://arxiv.org/abs/2010.04831>`_ approximation_mode: Only for gumbel intersection, i.e. if intersection_te... | 2 | null | Implement the Python class `Intersection` described below.
Class description:
All for one Intersection operation as Layer/Module
Method signatures and docstrings:
- def __init__(self, intersection_temperature: float=0.0, approximation_mode: Optional[str]=None) -> None: Args: intersection_temperature: Gumbel's beta pa... | Implement the Python class `Intersection` described below.
Class description:
All for one Intersection operation as Layer/Module
Method signatures and docstrings:
- def __init__(self, intersection_temperature: float=0.0, approximation_mode: Optional[str]=None) -> None: Args: intersection_temperature: Gumbel's beta pa... | 874f1ee1302b93a8fb94e45a66707f5a6ea16628 | <|skeleton|>
class Intersection:
"""All for one Intersection operation as Layer/Module"""
def __init__(self, intersection_temperature: float=0.0, approximation_mode: Optional[str]=None) -> None:
"""Args: intersection_temperature: Gumbel's beta parameter, if non-zero performs the intersection operation ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Intersection:
"""All for one Intersection operation as Layer/Module"""
def __init__(self, intersection_temperature: float=0.0, approximation_mode: Optional[str]=None) -> None:
"""Args: intersection_temperature: Gumbel's beta parameter, if non-zero performs the intersection operation as described ... | the_stack_v2_python_sparse | box_embeddings/modules/intersection/intersection.py | amitgajbhiye/box-embeddings | train | 0 |
9a5dbc727fc9964b0caf645d871ee4f4fb224824 | [
"self.module_name = module_name\nself.mail_templates = mail_templates\nsuper(Logic, self).__init__(model=model, base_model=base_model, scope_logic=scope_logic)",
"current_status = record.status\nif current_status == 'pre-accepted':\n new_status = 'accepted'\nelif current_status == 'pre-rejected':\n new_stat... | <|body_start_0|>
self.module_name = module_name
self.mail_templates = mail_templates
super(Logic, self).__init__(model=model, base_model=base_model, scope_logic=scope_logic)
<|end_body_0|>
<|body_start_1|>
current_status = record.status
if current_status == 'pre-accepted':
... | Logic class for OrgAppRecord. | Logic | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Logic:
"""Logic class for OrgAppRecord."""
def __init__(self, model=org_app_model, base_model=SurveyRecord, scope_logic=None, module_name=None, mail_templates=None):
"""Defines the name, key_name and model for this entity."""
<|body_0|>
def processRecord(self, record):
... | stack_v2_sparse_classes_75kplus_train_006059 | 2,779 | permissive | [
{
"docstring": "Defines the name, key_name and model for this entity.",
"name": "__init__",
"signature": "def __init__(self, model=org_app_model, base_model=SurveyRecord, scope_logic=None, module_name=None, mail_templates=None)"
},
{
"docstring": "Processes an OrgAppRecord that is in the pre-acc... | 3 | stack_v2_sparse_classes_30k_train_039458 | Implement the Python class `Logic` described below.
Class description:
Logic class for OrgAppRecord.
Method signatures and docstrings:
- def __init__(self, model=org_app_model, base_model=SurveyRecord, scope_logic=None, module_name=None, mail_templates=None): Defines the name, key_name and model for this entity.
- de... | Implement the Python class `Logic` described below.
Class description:
Logic class for OrgAppRecord.
Method signatures and docstrings:
- def __init__(self, model=org_app_model, base_model=SurveyRecord, scope_logic=None, module_name=None, mail_templates=None): Defines the name, key_name and model for this entity.
- de... | 9bd45c168f8ddb5c0e6c04eacdcaeafd61908be7 | <|skeleton|>
class Logic:
"""Logic class for OrgAppRecord."""
def __init__(self, model=org_app_model, base_model=SurveyRecord, scope_logic=None, module_name=None, mail_templates=None):
"""Defines the name, key_name and model for this entity."""
<|body_0|>
def processRecord(self, record):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Logic:
"""Logic class for OrgAppRecord."""
def __init__(self, model=org_app_model, base_model=SurveyRecord, scope_logic=None, module_name=None, mail_templates=None):
"""Defines the name, key_name and model for this entity."""
self.module_name = module_name
self.mail_templates = ma... | the_stack_v2_python_sparse | app/soc/logic/models/org_app_record.py | pombredanne/Melange-1 | train | 0 |
eb0ca6ff14e7a26a45d19c5d529d6b7e0b94ac8d | [
"try:\n cls.db = mysql.connector.connect(host='sql10.freemysqlhosting.net', user='sql10404333', passwd='nBUhZ1gSar', db='sql10404333')\n cls.cursor = cls.db.cursor(buffered=True)\nexcept Exception as e:\n raise custom_exceptions.ErrorDeConexion(origen='data', msj=str(e), msj_adicional='Error conectando a l... | <|body_start_0|>
try:
cls.db = mysql.connector.connect(host='sql10.freemysqlhosting.net', user='sql10404333', passwd='nBUhZ1gSar', db='sql10404333')
cls.cursor = cls.db.cursor(buffered=True)
except Exception as e:
raise custom_exceptions.ErrorDeConexion(origen='data',... | Clase que representa la capa de negocio. Los métodos declarados aquí serán heredados por todas las clases de negocio. | Datos | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Datos:
"""Clase que representa la capa de negocio. Los métodos declarados aquí serán heredados por todas las clases de negocio."""
def abrir_conexion(cls):
"""Abre la conexión con el motor de BD, y setea como variables de clase a la BD y el Cursor."""
<|body_0|>
def cerr... | stack_v2_sparse_classes_75kplus_train_006060 | 2,596 | no_license | [
{
"docstring": "Abre la conexión con el motor de BD, y setea como variables de clase a la BD y el Cursor.",
"name": "abrir_conexion",
"signature": "def abrir_conexion(cls)"
},
{
"docstring": "Cierra la conexión con el motor de BD.",
"name": "cerrar_conexion",
"signature": "def cerrar_con... | 2 | null | Implement the Python class `Datos` described below.
Class description:
Clase que representa la capa de negocio. Los métodos declarados aquí serán heredados por todas las clases de negocio.
Method signatures and docstrings:
- def abrir_conexion(cls): Abre la conexión con el motor de BD, y setea como variables de clase... | Implement the Python class `Datos` described below.
Class description:
Clase que representa la capa de negocio. Los métodos declarados aquí serán heredados por todas las clases de negocio.
Method signatures and docstrings:
- def abrir_conexion(cls): Abre la conexión con el motor de BD, y setea como variables de clase... | 57ca674dba4dabd2526c450ba7210933240f19c5 | <|skeleton|>
class Datos:
"""Clase que representa la capa de negocio. Los métodos declarados aquí serán heredados por todas las clases de negocio."""
def abrir_conexion(cls):
"""Abre la conexión con el motor de BD, y setea como variables de clase a la BD y el Cursor."""
<|body_0|>
def cerr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Datos:
"""Clase que representa la capa de negocio. Los métodos declarados aquí serán heredados por todas las clases de negocio."""
def abrir_conexion(cls):
"""Abre la conexión con el motor de BD, y setea como variables de clase a la BD y el Cursor."""
try:
cls.db = mysql.conne... | the_stack_v2_python_sparse | data/data.py | JoaquinCardonaRuiz/proyecto-final | train | 0 |
27d6ed5f6e1d3ce63ac49e14fd773bd99d53701a | [
"self.positions = positions\nself.num_trials = num_trials\nself.position_value = 1000 / positions",
"cumu_ret = np.zeros(self.num_trials)\nfor trial in range(self.num_trials):\n outcome = 0\n for p in range(self.positions):\n random = np.random.rand()\n if random <= 0.51:\n outcome ... | <|body_start_0|>
self.positions = positions
self.num_trials = num_trials
self.position_value = 1000 / positions
<|end_body_0|>
<|body_start_1|>
cumu_ret = np.zeros(self.num_trials)
for trial in range(self.num_trials):
outcome = 0
for p in range(self.posit... | Create class investment | investment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class investment:
"""Create class investment"""
def __init__(self, positions, num_trials):
"""Constructing the class"""
<|body_0|>
def simulate(self):
"""Simulating outcome of investment"""
<|body_1|>
def output(positions, num_trials):
"""Creating ... | stack_v2_sparse_classes_75kplus_train_006061 | 1,647 | no_license | [
{
"docstring": "Constructing the class",
"name": "__init__",
"signature": "def __init__(self, positions, num_trials)"
},
{
"docstring": "Simulating outcome of investment",
"name": "simulate",
"signature": "def simulate(self)"
},
{
"docstring": "Creating graph and text file by run... | 3 | stack_v2_sparse_classes_30k_train_041801 | Implement the Python class `investment` described below.
Class description:
Create class investment
Method signatures and docstrings:
- def __init__(self, positions, num_trials): Constructing the class
- def simulate(self): Simulating outcome of investment
- def output(positions, num_trials): Creating graph and text ... | Implement the Python class `investment` described below.
Class description:
Create class investment
Method signatures and docstrings:
- def __init__(self, positions, num_trials): Constructing the class
- def simulate(self): Simulating outcome of investment
- def output(positions, num_trials): Creating graph and text ... | 5b904060e8bced7f91547ad7f7819773a7450a1e | <|skeleton|>
class investment:
"""Create class investment"""
def __init__(self, positions, num_trials):
"""Constructing the class"""
<|body_0|>
def simulate(self):
"""Simulating outcome of investment"""
<|body_1|>
def output(positions, num_trials):
"""Creating ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class investment:
"""Create class investment"""
def __init__(self, positions, num_trials):
"""Constructing the class"""
self.positions = positions
self.num_trials = num_trials
self.position_value = 1000 / positions
def simulate(self):
"""Simulating outcome of invest... | the_stack_v2_python_sparse | llq205/investment.py | ds-ga-1007/assignment8 | train | 1 |
8952ec55556ebe23d7241575e35ccdf2e12ee4f3 | [
"LOGGER.info('importing csv files for database function tests')\nimport_data('csv_files', 'product_file.csv', 'customer_file.csv', 'rentals_file.csv')\nLOGGER.info('csv files successfully imported')",
"LOGGER.info('testing show_available_products function')\nmy_dict = show_available_products()\nexpected_dict = {'... | <|body_start_0|>
LOGGER.info('importing csv files for database function tests')
import_data('csv_files', 'product_file.csv', 'customer_file.csv', 'rentals_file.csv')
LOGGER.info('csv files successfully imported')
<|end_body_0|>
<|body_start_1|>
LOGGER.info('testing show_available_produc... | tests for database.py functions | TestsDatabase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestsDatabase:
"""tests for database.py functions"""
def setUp(self):
"""importing csv files for tests"""
<|body_0|>
def test_show_available_products(self):
"""testing show_available_products function"""
<|body_1|>
def test_show_rentals(self):
... | stack_v2_sparse_classes_75kplus_train_006062 | 4,093 | no_license | [
{
"docstring": "importing csv files for tests",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "testing show_available_products function",
"name": "test_show_available_products",
"signature": "def test_show_available_products(self)"
},
{
"docstring": "testing s... | 4 | stack_v2_sparse_classes_30k_val_000521 | Implement the Python class `TestsDatabase` described below.
Class description:
tests for database.py functions
Method signatures and docstrings:
- def setUp(self): importing csv files for tests
- def test_show_available_products(self): testing show_available_products function
- def test_show_rentals(self): testing sh... | Implement the Python class `TestsDatabase` described below.
Class description:
tests for database.py functions
Method signatures and docstrings:
- def setUp(self): importing csv files for tests
- def test_show_available_products(self): testing show_available_products function
- def test_show_rentals(self): testing sh... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class TestsDatabase:
"""tests for database.py functions"""
def setUp(self):
"""importing csv files for tests"""
<|body_0|>
def test_show_available_products(self):
"""testing show_available_products function"""
<|body_1|>
def test_show_rentals(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestsDatabase:
"""tests for database.py functions"""
def setUp(self):
"""importing csv files for tests"""
LOGGER.info('importing csv files for database function tests')
import_data('csv_files', 'product_file.csv', 'customer_file.csv', 'rentals_file.csv')
LOGGER.info('csv f... | the_stack_v2_python_sparse | students/christopher_gantt/lesson09/assignment/2-Context Manager/test_database.py | JavaRod/SP_Python220B_2019 | train | 1 |
7e3714338d2a3d5d7224560dbd46a6e1ccd9e710 | [
"volume = self.create_volume(imageRef=self.image_ref)\nextend_size = volume['size'] * 2\nself.volumes_client.extend_volume(volume['id'], new_size=extend_size)\nwaiters.wait_for_volume_resource_status(self.volumes_client, volume['id'], 'available')\nvolume = self.volumes_client.show_volume(volume['id'])['volume']\ns... | <|body_start_0|>
volume = self.create_volume(imageRef=self.image_ref)
extend_size = volume['size'] * 2
self.volumes_client.extend_volume(volume['id'], new_size=extend_size)
waiters.wait_for_volume_resource_status(self.volumes_client, volume['id'], 'available')
volume = self.volum... | Test volume extend | VolumesExtendTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VolumesExtendTest:
"""Test volume extend"""
def test_volume_extend(self):
"""Test extend a volume"""
<|body_0|>
def test_volume_extend_when_volume_has_snapshot(self):
"""Test extending a volume which has a snapshot"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_006063 | 9,365 | permissive | [
{
"docstring": "Test extend a volume",
"name": "test_volume_extend",
"signature": "def test_volume_extend(self)"
},
{
"docstring": "Test extending a volume which has a snapshot",
"name": "test_volume_extend_when_volume_has_snapshot",
"signature": "def test_volume_extend_when_volume_has_s... | 2 | null | Implement the Python class `VolumesExtendTest` described below.
Class description:
Test volume extend
Method signatures and docstrings:
- def test_volume_extend(self): Test extend a volume
- def test_volume_extend_when_volume_has_snapshot(self): Test extending a volume which has a snapshot | Implement the Python class `VolumesExtendTest` described below.
Class description:
Test volume extend
Method signatures and docstrings:
- def test_volume_extend(self): Test extend a volume
- def test_volume_extend_when_volume_has_snapshot(self): Test extending a volume which has a snapshot
<|skeleton|>
class Volumes... | 3932a799e620a20d7abf7b89e21b520683a1809b | <|skeleton|>
class VolumesExtendTest:
"""Test volume extend"""
def test_volume_extend(self):
"""Test extend a volume"""
<|body_0|>
def test_volume_extend_when_volume_has_snapshot(self):
"""Test extending a volume which has a snapshot"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VolumesExtendTest:
"""Test volume extend"""
def test_volume_extend(self):
"""Test extend a volume"""
volume = self.create_volume(imageRef=self.image_ref)
extend_size = volume['size'] * 2
self.volumes_client.extend_volume(volume['id'], new_size=extend_size)
waiters.... | the_stack_v2_python_sparse | tempest/api/volume/test_volumes_extend.py | openstack/tempest | train | 270 |
730656fde1d4be9927ceea267a9accabcf6525e3 | [
"if cls.__instance is None:\n cls.__instance = object.__new__(cls)\nreturn cls.__instance",
"self.api_url = 'https://api.openweathermap.org'\nself.api_keys = list(os.environ['WEATHER_API_KEY'].split(' '))\nself.connection = requests.Session()",
"response = None\ntry:\n keys = iter(self.api_keys)\n key ... | <|body_start_0|>
if cls.__instance is None:
cls.__instance = object.__new__(cls)
return cls.__instance
<|end_body_0|>
<|body_start_1|>
self.api_url = 'https://api.openweathermap.org'
self.api_keys = list(os.environ['WEATHER_API_KEY'].split(' '))
self.connection = req... | HTTPClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HTTPClient:
def __new__(cls):
"""This method creates the only instance of the class(singleton pattern) :param cls: The class :return: The method returns the class instance"""
<|body_0|>
def __init__(self):
"""Class constructor, sets up the HTTP client object."""
... | stack_v2_sparse_classes_75kplus_train_006064 | 2,076 | permissive | [
{
"docstring": "This method creates the only instance of the class(singleton pattern) :param cls: The class :return: The method returns the class instance",
"name": "__new__",
"signature": "def __new__(cls)"
},
{
"docstring": "Class constructor, sets up the HTTP client object.",
"name": "__i... | 3 | stack_v2_sparse_classes_30k_train_023132 | Implement the Python class `HTTPClient` described below.
Class description:
Implement the HTTPClient class.
Method signatures and docstrings:
- def __new__(cls): This method creates the only instance of the class(singleton pattern) :param cls: The class :return: The method returns the class instance
- def __init__(se... | Implement the Python class `HTTPClient` described below.
Class description:
Implement the HTTPClient class.
Method signatures and docstrings:
- def __new__(cls): This method creates the only instance of the class(singleton pattern) :param cls: The class :return: The method returns the class instance
- def __init__(se... | fb9a384495a315eebab183f9f12a5dafefa67e51 | <|skeleton|>
class HTTPClient:
def __new__(cls):
"""This method creates the only instance of the class(singleton pattern) :param cls: The class :return: The method returns the class instance"""
<|body_0|>
def __init__(self):
"""Class constructor, sets up the HTTP client object."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HTTPClient:
def __new__(cls):
"""This method creates the only instance of the class(singleton pattern) :param cls: The class :return: The method returns the class instance"""
if cls.__instance is None:
cls.__instance = object.__new__(cls)
return cls.__instance
def __in... | the_stack_v2_python_sparse | app/HTTPClient.py | sgabriel190/weather-desktop-app | train | 0 | |
ff5d09adf24f7a4ed64dc118d733efcad3b80bad | [
"super().__init__(coordinator, automation.automation_id)\nself._attr_name = automation.name\nself._automation: NexiaAutomation = automation\nself._attr_extra_state_attributes = {ATTR_DESCRIPTION: automation.description}",
"await self._automation.activate()\n\nasync def refresh_callback(_):\n await self.coordin... | <|body_start_0|>
super().__init__(coordinator, automation.automation_id)
self._attr_name = automation.name
self._automation: NexiaAutomation = automation
self._attr_extra_state_attributes = {ATTR_DESCRIPTION: automation.description}
<|end_body_0|>
<|body_start_1|>
await self._au... | Provides Nexia automation support. | NexiaAutomationScene | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NexiaAutomationScene:
"""Provides Nexia automation support."""
def __init__(self, coordinator: NexiaDataUpdateCoordinator, automation: NexiaAutomation) -> None:
"""Initialize the automation scene."""
<|body_0|>
async def async_activate(self, **kwargs: Any) -> None:
... | stack_v2_sparse_classes_75kplus_train_006065 | 1,960 | permissive | [
{
"docstring": "Initialize the automation scene.",
"name": "__init__",
"signature": "def __init__(self, coordinator: NexiaDataUpdateCoordinator, automation: NexiaAutomation) -> None"
},
{
"docstring": "Activate an automation scene.",
"name": "async_activate",
"signature": "async def asyn... | 2 | stack_v2_sparse_classes_30k_train_052690 | Implement the Python class `NexiaAutomationScene` described below.
Class description:
Provides Nexia automation support.
Method signatures and docstrings:
- def __init__(self, coordinator: NexiaDataUpdateCoordinator, automation: NexiaAutomation) -> None: Initialize the automation scene.
- async def async_activate(sel... | Implement the Python class `NexiaAutomationScene` described below.
Class description:
Provides Nexia automation support.
Method signatures and docstrings:
- def __init__(self, coordinator: NexiaDataUpdateCoordinator, automation: NexiaAutomation) -> None: Initialize the automation scene.
- async def async_activate(sel... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class NexiaAutomationScene:
"""Provides Nexia automation support."""
def __init__(self, coordinator: NexiaDataUpdateCoordinator, automation: NexiaAutomation) -> None:
"""Initialize the automation scene."""
<|body_0|>
async def async_activate(self, **kwargs: Any) -> None:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NexiaAutomationScene:
"""Provides Nexia automation support."""
def __init__(self, coordinator: NexiaDataUpdateCoordinator, automation: NexiaAutomation) -> None:
"""Initialize the automation scene."""
super().__init__(coordinator, automation.automation_id)
self._attr_name = automat... | the_stack_v2_python_sparse | homeassistant/components/nexia/scene.py | home-assistant/core | train | 35,501 |
1337dc9ad5760e68818a73346502d3bb55026b15 | [
"if not 'atlas_flags' in self.extra_flags:\n self._log.info('SimFlags:: Loading ATLAS flags')\n if not 'ATLAS-' in self.SimLayout.get_Value():\n self._log.warning('Loading ATLAS flags, but SimLayout tag is not an ATLAS geometry')\n self.extra_flags.append('atlas_flags')\n self.import_JobPropertie... | <|body_start_0|>
if not 'atlas_flags' in self.extra_flags:
self._log.info('SimFlags:: Loading ATLAS flags')
if not 'ATLAS-' in self.SimLayout.get_Value():
self._log.warning('Loading ATLAS flags, but SimLayout tag is not an ATLAS geometry')
self.extra_flags.app... | Container for all the simulation flags. By default SimFlags contains a minimal set of simulation flags, but this set can be extended using the "load_*_flags()" methods. The extra_flags attribute records the app-specific flags which have been loaded. If the SimSkeleton hits the do_jobproperties phase and no extra flags ... | SimFlags | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimFlags:
"""Container for all the simulation flags. By default SimFlags contains a minimal set of simulation flags, but this set can be extended using the "load_*_flags()" methods. The extra_flags attribute records the app-specific flags which have been loaded. If the SimSkeleton hits the do_job... | stack_v2_sparse_classes_75kplus_train_006066 | 35,004 | permissive | [
{
"docstring": "Load extra config flags specific to ATLAS layouts.",
"name": "load_atlas_flags",
"signature": "def load_atlas_flags(self)"
},
{
"docstring": "Load extra config flags specific to cosmics simulation.",
"name": "load_cosmics_flags",
"signature": "def load_cosmics_flags(self)... | 5 | null | Implement the Python class `SimFlags` described below.
Class description:
Container for all the simulation flags. By default SimFlags contains a minimal set of simulation flags, but this set can be extended using the "load_*_flags()" methods. The extra_flags attribute records the app-specific flags which have been loa... | Implement the Python class `SimFlags` described below.
Class description:
Container for all the simulation flags. By default SimFlags contains a minimal set of simulation flags, but this set can be extended using the "load_*_flags()" methods. The extra_flags attribute records the app-specific flags which have been loa... | 354f92551294f7be678aebcd7b9d67d2c4448176 | <|skeleton|>
class SimFlags:
"""Container for all the simulation flags. By default SimFlags contains a minimal set of simulation flags, but this set can be extended using the "load_*_flags()" methods. The extra_flags attribute records the app-specific flags which have been loaded. If the SimSkeleton hits the do_job... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SimFlags:
"""Container for all the simulation flags. By default SimFlags contains a minimal set of simulation flags, but this set can be extended using the "load_*_flags()" methods. The extra_flags attribute records the app-specific flags which have been loaded. If the SimSkeleton hits the do_jobproperties ph... | the_stack_v2_python_sparse | Simulation/G4Atlas/G4AtlasApps/python/SimFlags.py | strigazi/athena | train | 0 |
965f1d6339bb5141077ffce23364bb82ab3b5900 | [
"self.has_value = False\nself.value = None\nself.event = threading.Event()\nself.exception = None\npromise_callback = PromiseCallback(self, callback, *args, **kwargs)\npromise_thread = threading.Thread(target=promise_callback)\npromise_thread.start()",
"try:\n self.value = callback(*args, **kwargs)\nexcept Exc... | <|body_start_0|>
self.has_value = False
self.value = None
self.event = threading.Event()
self.exception = None
promise_callback = PromiseCallback(self, callback, *args, **kwargs)
promise_thread = threading.Thread(target=promise_callback)
promise_thread.start()
<|e... | Class for promises to deliver a value in the future. A thread is started to run callback(args), that thread should return the value that it generates, or raise an expception. p.WaitAndGetValue() will block until a value is available. If an exception was raised, p.WaitAndGetValue() will re-raise the same exception. | Promise | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Promise:
"""Class for promises to deliver a value in the future. A thread is started to run callback(args), that thread should return the value that it generates, or raise an expception. p.WaitAndGetValue() will block until a value is available. If an exception was raised, p.WaitAndGetValue() wil... | stack_v2_sparse_classes_75kplus_train_006067 | 21,209 | permissive | [
{
"docstring": "Initialize the promise and immediately call the supplied function. Args: callback: Function that takes the args and returns the promise value. *args: Any arguments to the target function. **kwargs: Any keyword args for the target function.",
"name": "__init__",
"signature": "def __init__... | 3 | stack_v2_sparse_classes_30k_train_007458 | Implement the Python class `Promise` described below.
Class description:
Class for promises to deliver a value in the future. A thread is started to run callback(args), that thread should return the value that it generates, or raise an expception. p.WaitAndGetValue() will block until a value is available. If an except... | Implement the Python class `Promise` described below.
Class description:
Class for promises to deliver a value in the future. A thread is started to run callback(args), that thread should return the value that it generates, or raise an expception. p.WaitAndGetValue() will block until a value is available. If an except... | b5d4783f99461438ca9e6a477535617fadab6ba3 | <|skeleton|>
class Promise:
"""Class for promises to deliver a value in the future. A thread is started to run callback(args), that thread should return the value that it generates, or raise an expception. p.WaitAndGetValue() will block until a value is available. If an exception was raised, p.WaitAndGetValue() wil... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Promise:
"""Class for promises to deliver a value in the future. A thread is started to run callback(args), that thread should return the value that it generates, or raise an expception. p.WaitAndGetValue() will block until a value is available. If an exception was raised, p.WaitAndGetValue() will re-raise th... | the_stack_v2_python_sparse | appengine/monorail/framework/framework_helpers.py | xinghun61/infra | train | 2 |
a9231bfc4169bd7e798d65db5989f7d885d01dd6 | [
"u1, u2 = [m.user for m in Member.objects.active()[3:5]]\nself.assertEqual(Relationship.objects.filter(mentor=u1, mentee=u2).count(), 0)\nself.assertEqual(len(mail.outbox), 0)\nRelationship.objects.create(mentor=u1, mentee=u2)\nself.assertEqual(Relationship.objects.filter(mentor=u1, mentee=u2).count(), 1)\nself.ass... | <|body_start_0|>
u1, u2 = [m.user for m in Member.objects.active()[3:5]]
self.assertEqual(Relationship.objects.filter(mentor=u1, mentee=u2).count(), 0)
self.assertEqual(len(mail.outbox), 0)
Relationship.objects.create(mentor=u1, mentee=u2)
self.assertEqual(Relationship.objects.fi... | NewRelationshipTestCase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewRelationshipTestCase:
def test_email_sent_on_new_relationship(self):
"""Creating a new relationship should notify the members."""
<|body_0|>
def test_email_not_sent_on_new_inactive_relationship(self):
"""Creating a new inactive relationship should not notify the m... | stack_v2_sparse_classes_75kplus_train_006068 | 2,023 | permissive | [
{
"docstring": "Creating a new relationship should notify the members.",
"name": "test_email_sent_on_new_relationship",
"signature": "def test_email_sent_on_new_relationship(self)"
},
{
"docstring": "Creating a new inactive relationship should not notify the members.",
"name": "test_email_no... | 3 | null | Implement the Python class `NewRelationshipTestCase` described below.
Class description:
Implement the NewRelationshipTestCase class.
Method signatures and docstrings:
- def test_email_sent_on_new_relationship(self): Creating a new relationship should notify the members.
- def test_email_not_sent_on_new_inactive_rela... | Implement the Python class `NewRelationshipTestCase` described below.
Class description:
Implement the NewRelationshipTestCase class.
Method signatures and docstrings:
- def test_email_sent_on_new_relationship(self): Creating a new relationship should notify the members.
- def test_email_not_sent_on_new_inactive_rela... | 037215e088ead3e730099f156e216e9b7afe2857 | <|skeleton|>
class NewRelationshipTestCase:
def test_email_sent_on_new_relationship(self):
"""Creating a new relationship should notify the members."""
<|body_0|>
def test_email_not_sent_on_new_inactive_relationship(self):
"""Creating a new inactive relationship should not notify the m... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NewRelationshipTestCase:
def test_email_sent_on_new_relationship(self):
"""Creating a new relationship should notify the members."""
u1, u2 = [m.user for m in Member.objects.active()[3:5]]
self.assertEqual(Relationship.objects.filter(mentor=u1, mentee=u2).count(), 0)
self.asser... | the_stack_v2_python_sparse | edpcmentoring/autonag/tests.py | cuedpc/edpcmentoring | train | 1 | |
3b4ae1171eb34c1c4be575c33e6a218faa5f9be1 | [
"md5_obj = hashlib.md5()\nmd5_obj.update(text.encode('utf-8'))\nreturn md5_obj.hexdigest()",
"md5_obj = hashlib.md5()\ntry:\n with open(file, 'rb') as f:\n for data in f:\n md5_obj.update(data)\n return md5_obj.hexdigest()\nexcept FileNotFoundError as e:\n print(e)\n return False... | <|body_start_0|>
md5_obj = hashlib.md5()
md5_obj.update(text.encode('utf-8'))
return md5_obj.hexdigest()
<|end_body_0|>
<|body_start_1|>
md5_obj = hashlib.md5()
try:
with open(file, 'rb') as f:
for data in f:
md5_obj.update(data)
... | 获取传入对象的md5值 | GetMD5 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetMD5:
"""获取传入对象的md5值"""
def get_str_md5(text):
"""检测md5 :param text: 用户明文 :return: md5"""
<|body_0|>
def get_file_md5(file):
"""计算文件的md5 :param file: 文件 :return md5"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
md5_obj = hashlib.md5()
... | stack_v2_sparse_classes_75kplus_train_006069 | 912 | no_license | [
{
"docstring": "检测md5 :param text: 用户明文 :return: md5",
"name": "get_str_md5",
"signature": "def get_str_md5(text)"
},
{
"docstring": "计算文件的md5 :param file: 文件 :return md5",
"name": "get_file_md5",
"signature": "def get_file_md5(file)"
}
] | 2 | stack_v2_sparse_classes_30k_train_049775 | Implement the Python class `GetMD5` described below.
Class description:
获取传入对象的md5值
Method signatures and docstrings:
- def get_str_md5(text): 检测md5 :param text: 用户明文 :return: md5
- def get_file_md5(file): 计算文件的md5 :param file: 文件 :return md5 | Implement the Python class `GetMD5` described below.
Class description:
获取传入对象的md5值
Method signatures and docstrings:
- def get_str_md5(text): 检测md5 :param text: 用户明文 :return: md5
- def get_file_md5(file): 计算文件的md5 :param file: 文件 :return md5
<|skeleton|>
class GetMD5:
"""获取传入对象的md5值"""
def get_str_md5(text... | 7f984fbfcb7152a055d4bc67ca0a7d64a52ce125 | <|skeleton|>
class GetMD5:
"""获取传入对象的md5值"""
def get_str_md5(text):
"""检测md5 :param text: 用户明文 :return: md5"""
<|body_0|>
def get_file_md5(file):
"""计算文件的md5 :param file: 文件 :return md5"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GetMD5:
"""获取传入对象的md5值"""
def get_str_md5(text):
"""检测md5 :param text: 用户明文 :return: md5"""
md5_obj = hashlib.md5()
md5_obj.update(text.encode('utf-8'))
return md5_obj.hexdigest()
def get_file_md5(file):
"""计算文件的md5 :param file: 文件 :return md5"""
md5_o... | the_stack_v2_python_sparse | luffycity-s8/第三模块_面向对象_网络编程基础/网络编程基础/作业_FTP文件服务器/FTPProject/server/modules/get_md5.py | PAYNE1Z/python-learn | train | 2 |
dc3bc04babbd05cc7879e90a99281c58e54fba3d | [
"if id is None:\n Base.__nb_objects += 1\n self.id = Base.__nb_objects\nelif id <= 0:\n raise ValueError('id must be positive integer')\nelse:\n self.id = id\n Base.__nb_objects += 1",
"if list_dictionaries is None or list_dictionaries is []:\n return '[]'\nreturn json.dumps(list_dictionaries)",... | <|body_start_0|>
if id is None:
Base.__nb_objects += 1
self.id = Base.__nb_objects
elif id <= 0:
raise ValueError('id must be positive integer')
else:
self.id = id
Base.__nb_objects += 1
<|end_body_0|>
<|body_start_1|>
if list_... | This class will be the base of all other classes in project | Base | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Base:
"""This class will be the base of all other classes in project"""
def __init__(self, id=None):
"""Assign obj id"""
<|body_0|>
def to_json_string(list_dictionaries):
"""json string rep of for instances of dicts"""
<|body_1|>
def save_to_file(cls... | stack_v2_sparse_classes_75kplus_train_006070 | 2,141 | no_license | [
{
"docstring": "Assign obj id",
"name": "__init__",
"signature": "def __init__(self, id=None)"
},
{
"docstring": "json string rep of for instances of dicts",
"name": "to_json_string",
"signature": "def to_json_string(list_dictionaries)"
},
{
"docstring": "writes the JSON string r... | 6 | stack_v2_sparse_classes_30k_train_018076 | Implement the Python class `Base` described below.
Class description:
This class will be the base of all other classes in project
Method signatures and docstrings:
- def __init__(self, id=None): Assign obj id
- def to_json_string(list_dictionaries): json string rep of for instances of dicts
- def save_to_file(cls, li... | Implement the Python class `Base` described below.
Class description:
This class will be the base of all other classes in project
Method signatures and docstrings:
- def __init__(self, id=None): Assign obj id
- def to_json_string(list_dictionaries): json string rep of for instances of dicts
- def save_to_file(cls, li... | 75bedbbd249be2536da5a77f6337b14c8363f1b8 | <|skeleton|>
class Base:
"""This class will be the base of all other classes in project"""
def __init__(self, id=None):
"""Assign obj id"""
<|body_0|>
def to_json_string(list_dictionaries):
"""json string rep of for instances of dicts"""
<|body_1|>
def save_to_file(cls... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Base:
"""This class will be the base of all other classes in project"""
def __init__(self, id=None):
"""Assign obj id"""
if id is None:
Base.__nb_objects += 1
self.id = Base.__nb_objects
elif id <= 0:
raise ValueError('id must be positive intege... | the_stack_v2_python_sparse | 0x0C-python-almost_a_circle/models/base.py | Sainterman/holbertonschool-higher_level_programming | train | 0 |
190a49890250de840e025b583954fe8e892afc2c | [
"self.ascii_A = ord('A')\nself.ascii_threshold = 26\nself.ascii_error_message = 'The Vigenere Cipher only supports ASCII characters'",
"vigenere_queue = deque()\nshift_dir = 1\nif mode == 'dec':\n shift_dir = -1\nfor char in keyword:\n if char not in string.ascii_uppercase and char != ' ':\n return -... | <|body_start_0|>
self.ascii_A = ord('A')
self.ascii_threshold = 26
self.ascii_error_message = 'The Vigenere Cipher only supports ASCII characters'
<|end_body_0|>
<|body_start_1|>
vigenere_queue = deque()
shift_dir = 1
if mode == 'dec':
shift_dir = -1
... | A class which implements the vigenere Cipher. | VigenereCipher | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VigenereCipher:
"""A class which implements the vigenere Cipher."""
def __init__(self):
"""sets ascii limitations"""
<|body_0|>
def make_shift_queue(self, keyword, mode):
"""turns a keyword into a queue of shift values. mode determines whether the shift values ar... | stack_v2_sparse_classes_75kplus_train_006071 | 3,408 | permissive | [
{
"docstring": "sets ascii limitations",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "turns a keyword into a queue of shift values. mode determines whether the shift values are for encryption or decryption valid values are mode='enc' and mode='dec'",
"name": "make... | 5 | null | Implement the Python class `VigenereCipher` described below.
Class description:
A class which implements the vigenere Cipher.
Method signatures and docstrings:
- def __init__(self): sets ascii limitations
- def make_shift_queue(self, keyword, mode): turns a keyword into a queue of shift values. mode determines whethe... | Implement the Python class `VigenereCipher` described below.
Class description:
A class which implements the vigenere Cipher.
Method signatures and docstrings:
- def __init__(self): sets ascii limitations
- def make_shift_queue(self, keyword, mode): turns a keyword into a queue of shift values. mode determines whethe... | 83616f28e5e69aac40ed54247091a2f93f8f9464 | <|skeleton|>
class VigenereCipher:
"""A class which implements the vigenere Cipher."""
def __init__(self):
"""sets ascii limitations"""
<|body_0|>
def make_shift_queue(self, keyword, mode):
"""turns a keyword into a queue of shift values. mode determines whether the shift values ar... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VigenereCipher:
"""A class which implements the vigenere Cipher."""
def __init__(self):
"""sets ascii limitations"""
self.ascii_A = ord('A')
self.ascii_threshold = 26
self.ascii_error_message = 'The Vigenere Cipher only supports ASCII characters'
def make_shift_queue(... | the_stack_v2_python_sparse | modules/ciphers/vigenere.py | yoda-pa/yoda | train | 777 |
0d0662c43a5d9a7703fd6b09578c2a3ee47ea32e | [
"RelModelBase.__init__(self, classes, rel_classes, mode, num_gpus, require_overlap_det)\nassert depth_model in DEPTH_MODELS\nself.depth_model = depth_model\nself.pretrained_depth = pretrained_depth\nself.depth_pooling_dim = DEPTH_DIMS[self.depth_model]\nself.depth_channels = DEPTH_CHANNELS[self.depth_model]\nself.p... | <|body_start_0|>
RelModelBase.__init__(self, classes, rel_classes, mode, num_gpus, require_overlap_det)
assert depth_model in DEPTH_MODELS
self.depth_model = depth_model
self.pretrained_depth = pretrained_depth
self.depth_pooling_dim = DEPTH_DIMS[self.depth_model]
self.de... | Depth-Union relation detection model | RelModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelModel:
"""Depth-Union relation detection model"""
def __init__(self, classes, rel_classes, mode='sgdet', num_gpus=1, require_overlap_det=True, depth_model=None, pretrained_depth=False, **kwargs):
""":param classes: object classes :param rel_classes: relationship classes. None if w... | stack_v2_sparse_classes_75kplus_train_006072 | 6,300 | permissive | [
{
"docstring": ":param classes: object classes :param rel_classes: relationship classes. None if were not using rel mode :param mode: (sgcls, predcls, or sgdet) :param num_gpus: how many GPUS 2 use :param require_overlap_det: Whether two objects must intersect :param depth_model: provided architecture for depth... | 3 | stack_v2_sparse_classes_30k_test_000944 | Implement the Python class `RelModel` described below.
Class description:
Depth-Union relation detection model
Method signatures and docstrings:
- def __init__(self, classes, rel_classes, mode='sgdet', num_gpus=1, require_overlap_det=True, depth_model=None, pretrained_depth=False, **kwargs): :param classes: object cl... | Implement the Python class `RelModel` described below.
Class description:
Depth-Union relation detection model
Method signatures and docstrings:
- def __init__(self, classes, rel_classes, mode='sgdet', num_gpus=1, require_overlap_det=True, depth_model=None, pretrained_depth=False, **kwargs): :param classes: object cl... | 39fb0d493f44ac2daf4bbc8569a1c74e8828da5f | <|skeleton|>
class RelModel:
"""Depth-Union relation detection model"""
def __init__(self, classes, rel_classes, mode='sgdet', num_gpus=1, require_overlap_det=True, depth_model=None, pretrained_depth=False, **kwargs):
""":param classes: object classes :param rel_classes: relationship classes. None if w... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RelModel:
"""Depth-Union relation detection model"""
def __init__(self, classes, rel_classes, mode='sgdet', num_gpus=1, require_overlap_det=True, depth_model=None, pretrained_depth=False, **kwargs):
""":param classes: object classes :param rel_classes: relationship classes. None if were not using... | the_stack_v2_python_sparse | lib/shz_models/rel_model_depth_union.py | sharifza/Depth-VRD | train | 1 |
17b6c347cb58758616bbcdd2f3e840d2cb9a3780 | [
"api_calls = ApiCallParser.parse_stream(MATCHING_LOG_LINES)\nself.assertIsInstance(api_calls, collections.Iterable)\napi_calls = list(api_calls)\nself.assertEqual(len(api_calls), len(MATCHING_LOG_LINES))\nfor entity in api_calls:\n self.assertIsInstance(entity, ApiCall)",
"api_calls = ApiCallParser.parse_strea... | <|body_start_0|>
api_calls = ApiCallParser.parse_stream(MATCHING_LOG_LINES)
self.assertIsInstance(api_calls, collections.Iterable)
api_calls = list(api_calls)
self.assertEqual(len(api_calls), len(MATCHING_LOG_LINES))
for entity in api_calls:
self.assertIsInstance(enti... | TestApiCallParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestApiCallParser:
def test_that_we_get_expected_api_calls(self):
"""Test that when we give the parser lines that should match, they match"""
<|body_0|>
def test_that_we_do_not_see_unexpected_api_calls(self):
"""Test that when we give the parser lines that don't matc... | stack_v2_sparse_classes_75kplus_train_006073 | 6,036 | no_license | [
{
"docstring": "Test that when we give the parser lines that should match, they match",
"name": "test_that_we_get_expected_api_calls",
"signature": "def test_that_we_get_expected_api_calls(self)"
},
{
"docstring": "Test that when we give the parser lines that don't match, they don't match",
... | 3 | stack_v2_sparse_classes_30k_train_009140 | Implement the Python class `TestApiCallParser` described below.
Class description:
Implement the TestApiCallParser class.
Method signatures and docstrings:
- def test_that_we_get_expected_api_calls(self): Test that when we give the parser lines that should match, they match
- def test_that_we_do_not_see_unexpected_ap... | Implement the Python class `TestApiCallParser` described below.
Class description:
Implement the TestApiCallParser class.
Method signatures and docstrings:
- def test_that_we_get_expected_api_calls(self): Test that when we give the parser lines that should match, they match
- def test_that_we_do_not_see_unexpected_ap... | d673d2447fc87669aa3ea529b09450de0e6f0fb4 | <|skeleton|>
class TestApiCallParser:
def test_that_we_get_expected_api_calls(self):
"""Test that when we give the parser lines that should match, they match"""
<|body_0|>
def test_that_we_do_not_see_unexpected_api_calls(self):
"""Test that when we give the parser lines that don't matc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestApiCallParser:
def test_that_we_get_expected_api_calls(self):
"""Test that when we give the parser lines that should match, they match"""
api_calls = ApiCallParser.parse_stream(MATCHING_LOG_LINES)
self.assertIsInstance(api_calls, collections.Iterable)
api_calls = list(api_c... | the_stack_v2_python_sparse | src/lib/api_call/test_api_call_parser.py | topher200/assertion-context | train | 0 | |
0337cbc76e4210d9acafa4b17fbed99a4ed46489 | [
"super(CaptchaAuthenticationForm, self).__init__(*args, **kwargs)\nself.captcha_answer = request.session.get(CAPTCHA_SESSION_KEY)\nif getattr(request, 'limited', False):\n a, b = (random.randint(1, 9), random.randint(1, 9))\n if b > a:\n a, b = (b, a)\n opname, op = random.choice(OPERATORS.items())\... | <|body_start_0|>
super(CaptchaAuthenticationForm, self).__init__(*args, **kwargs)
self.captcha_answer = request.session.get(CAPTCHA_SESSION_KEY)
if getattr(request, 'limited', False):
a, b = (random.randint(1, 9), random.randint(1, 9))
if b > a:
a, b = (b,... | Login form with a simple math captcha. For use when there have been too many failed login attempts from a particular IP address or for a particular username. Simply locking users out in this case creates a potential Denial of Service vulnerability; a captcha allows a human to still log in but makes life more difficult ... | CaptchaAuthenticationForm | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CaptchaAuthenticationForm:
"""Login form with a simple math captcha. For use when there have been too many failed login attempts from a particular IP address or for a particular username. Simply locking users out in this case creates a potential Denial of Service vulnerability; a captcha allows a... | stack_v2_sparse_classes_75kplus_train_006074 | 6,418 | permissive | [
{
"docstring": "Initialize form, including captcha question and expected answer.",
"name": "__init__",
"signature": "def __init__(self, request=None, *args, **kwargs)"
},
{
"docstring": "Fail form validation if captcha answer is not the expected answer. If no expected captcha answer was previous... | 2 | null | Implement the Python class `CaptchaAuthenticationForm` described below.
Class description:
Login form with a simple math captcha. For use when there have been too many failed login attempts from a particular IP address or for a particular username. Simply locking users out in this case creates a potential Denial of Se... | Implement the Python class `CaptchaAuthenticationForm` described below.
Class description:
Login form with a simple math captcha. For use when there have been too many failed login attempts from a particular IP address or for a particular username. Simply locking users out in this case creates a potential Denial of Se... | ee54db2fe8ffbf2216d359b7a093b51f2574878e | <|skeleton|>
class CaptchaAuthenticationForm:
"""Login form with a simple math captcha. For use when there have been too many failed login attempts from a particular IP address or for a particular username. Simply locking users out in this case creates a potential Denial of Service vulnerability; a captcha allows a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CaptchaAuthenticationForm:
"""Login form with a simple math captcha. For use when there have been too many failed login attempts from a particular IP address or for a particular username. Simply locking users out in this case creates a potential Denial of Service vulnerability; a captcha allows a human to sti... | the_stack_v2_python_sparse | moztrap/view/users/forms.py | isakib/moztrap | train | 1 |
1f59b7a6e2196069acfdaaf289c699ea739fe9c3 | [
"super().__init__(**kwargs)\nself.prenet_dense = [tf.keras.layers.Dense(units=config.prenet_units, activation=ACT2FN[config.prenet_activation], name='dense_._{}'.format(i)) for i in range(config.n_prenet_layers)]\nself.dropout = tf.keras.layers.Dropout(rate=config.prenet_dropout_rate, name='dropout')",
"outputs =... | <|body_start_0|>
super().__init__(**kwargs)
self.prenet_dense = [tf.keras.layers.Dense(units=config.prenet_units, activation=ACT2FN[config.prenet_activation], name='dense_._{}'.format(i)) for i in range(config.n_prenet_layers)]
self.dropout = tf.keras.layers.Dropout(rate=config.prenet_dropout_ra... | Tacotron-2 prenet. | Prenet | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Prenet:
"""Tacotron-2 prenet."""
def __init__(self, config, **kwargs):
"""Init variables."""
<|body_0|>
def call(self, inputs, training=False):
"""Call logic."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__(**kwargs)
sel... | stack_v2_sparse_classes_75kplus_train_006075 | 28,579 | permissive | [
{
"docstring": "Init variables.",
"name": "__init__",
"signature": "def __init__(self, config, **kwargs)"
},
{
"docstring": "Call logic.",
"name": "call",
"signature": "def call(self, inputs, training=False)"
}
] | 2 | stack_v2_sparse_classes_30k_train_029708 | Implement the Python class `Prenet` described below.
Class description:
Tacotron-2 prenet.
Method signatures and docstrings:
- def __init__(self, config, **kwargs): Init variables.
- def call(self, inputs, training=False): Call logic. | Implement the Python class `Prenet` described below.
Class description:
Tacotron-2 prenet.
Method signatures and docstrings:
- def __init__(self, config, **kwargs): Init variables.
- def call(self, inputs, training=False): Call logic.
<|skeleton|>
class Prenet:
"""Tacotron-2 prenet."""
def __init__(self, co... | 7eb37838e21bd0b8c9da7e00c03245cdedfd6c80 | <|skeleton|>
class Prenet:
"""Tacotron-2 prenet."""
def __init__(self, config, **kwargs):
"""Init variables."""
<|body_0|>
def call(self, inputs, training=False):
"""Call logic."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Prenet:
"""Tacotron-2 prenet."""
def __init__(self, config, **kwargs):
"""Init variables."""
super().__init__(**kwargs)
self.prenet_dense = [tf.keras.layers.Dense(units=config.prenet_units, activation=ACT2FN[config.prenet_activation], name='dense_._{}'.format(i)) for i in range(co... | the_stack_v2_python_sparse | AMmodel/las_wrap.py | freefly518/TensorflowASR | train | 0 |
7d9e38377fe555c174368e49c7a81d74a2617207 | [
"print('Running cookiecutter project creation with package: ', cookiecutter_path)\nfor k, v in migration_data.items():\n print('Creating the cookiecutter repository subdirectory for: ', k)\n self.create_project(package_path=cookiecutter_path, context=v)",
"if not context:\n context = {}\ntry:\n cookie... | <|body_start_0|>
print('Running cookiecutter project creation with package: ', cookiecutter_path)
for k, v in migration_data.items():
print('Creating the cookiecutter repository subdirectory for: ', k)
self.create_project(package_path=cookiecutter_path, context=v)
<|end_body_0|>
... | Handle cookiecutter operations. | CookiecutterHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CookiecutterHandler:
"""Handle cookiecutter operations."""
def run(self, migration_data: Dict[str, Any], cookiecutter_path: str='https://github.com/2ndWatch/cookiecutter-tf-cloudendure') -> None:
"""Run the automation of cookiecutter."""
<|body_0|>
def create_project(sel... | stack_v2_sparse_classes_75kplus_train_006076 | 3,636 | permissive | [
{
"docstring": "Run the automation of cookiecutter.",
"name": "run",
"signature": "def run(self, migration_data: Dict[str, Any], cookiecutter_path: str='https://github.com/2ndWatch/cookiecutter-tf-cloudendure') -> None"
},
{
"docstring": "Create a cookiecutter project with the provided details. ... | 2 | null | Implement the Python class `CookiecutterHandler` described below.
Class description:
Handle cookiecutter operations.
Method signatures and docstrings:
- def run(self, migration_data: Dict[str, Any], cookiecutter_path: str='https://github.com/2ndWatch/cookiecutter-tf-cloudendure') -> None: Run the automation of cookie... | Implement the Python class `CookiecutterHandler` described below.
Class description:
Handle cookiecutter operations.
Method signatures and docstrings:
- def run(self, migration_data: Dict[str, Any], cookiecutter_path: str='https://github.com/2ndWatch/cookiecutter-tf-cloudendure') -> None: Run the automation of cookie... | f81d1be1422b7c19adedb06c584803eaaa811919 | <|skeleton|>
class CookiecutterHandler:
"""Handle cookiecutter operations."""
def run(self, migration_data: Dict[str, Any], cookiecutter_path: str='https://github.com/2ndWatch/cookiecutter-tf-cloudendure') -> None:
"""Run the automation of cookiecutter."""
<|body_0|>
def create_project(sel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CookiecutterHandler:
"""Handle cookiecutter operations."""
def run(self, migration_data: Dict[str, Any], cookiecutter_path: str='https://github.com/2ndWatch/cookiecutter-tf-cloudendure') -> None:
"""Run the automation of cookiecutter."""
print('Running cookiecutter project creation with p... | the_stack_v2_python_sparse | cloudendure/templates.py | 2ndWatch/cloudendure-python | train | 11 |
7e30f6a7fa98dbf955dc2db8afbf099d9bf3941d | [
"try:\n job_id = output.split(' ')[2]\n int(job_id)\n return job_id\nexcept (ValueError, IndexError) as e:\n self.log.error('Spawner unable to parse job ID from text: {}'.format(output))\n raise e",
"if self.job_status:\n job_info = xml.etree.ElementTree.fromstring(self.job_status).find(\".//job... | <|body_start_0|>
try:
job_id = output.split(' ')[2]
int(job_id)
return job_id
except (ValueError, IndexError) as e:
self.log.error('Spawner unable to parse job ID from text: {}'.format(output))
raise e
<|end_body_0|>
<|body_start_1|>
i... | GridengineSpawner | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GridengineSpawner:
def parse_job_id(self, output):
"""Parsing output of submit command to get job id. :param str output: Output of submit command, scheduler-specific. :return: Job id in queue. :rtype: str"""
<|body_0|>
def state_ispending(self):
"""Querying for "pend... | stack_v2_sparse_classes_75kplus_train_006077 | 43,287 | permissive | [
{
"docstring": "Parsing output of submit command to get job id. :param str output: Output of submit command, scheduler-specific. :return: Job id in queue. :rtype: str",
"name": "parse_job_id",
"signature": "def parse_job_id(self, output)"
},
{
"docstring": "Querying for \"pending\" status. :retu... | 4 | stack_v2_sparse_classes_30k_train_015283 | Implement the Python class `GridengineSpawner` described below.
Class description:
Implement the GridengineSpawner class.
Method signatures and docstrings:
- def parse_job_id(self, output): Parsing output of submit command to get job id. :param str output: Output of submit command, scheduler-specific. :return: Job id... | Implement the Python class `GridengineSpawner` described below.
Class description:
Implement the GridengineSpawner class.
Method signatures and docstrings:
- def parse_job_id(self, output): Parsing output of submit command to get job id. :param str output: Output of submit command, scheduler-specific. :return: Job id... | d07c43a396267d26f52b7b152a385f8a600ac2e8 | <|skeleton|>
class GridengineSpawner:
def parse_job_id(self, output):
"""Parsing output of submit command to get job id. :param str output: Output of submit command, scheduler-specific. :return: Job id in queue. :rtype: str"""
<|body_0|>
def state_ispending(self):
"""Querying for "pend... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GridengineSpawner:
def parse_job_id(self, output):
"""Parsing output of submit command to get job id. :param str output: Output of submit command, scheduler-specific. :return: Job id in queue. :rtype: str"""
try:
job_id = output.split(' ')[2]
int(job_id)
ret... | the_stack_v2_python_sparse | launcher/batchspawner.py | melissa-sa/melissa | train | 7 | |
cc202951f77e29e392934f9d7a89fd340d7fb205 | [
"if len(words) != len(coefs):\n return -1\nresult = sum([len(word) * coef for word, coef in zip(words, coefs)])\nreturn result",
"if len(words) != len(coefs):\n return -1\nresult = sum([len(word) * coefs[i] for i, word in enumerate(words)])\nreturn result"
] | <|body_start_0|>
if len(words) != len(coefs):
return -1
result = sum([len(word) * coef for word, coef in zip(words, coefs)])
return result
<|end_body_0|>
<|body_start_1|>
if len(words) != len(coefs):
return -1
result = sum([len(word) * coefs[i] for i, wor... | Has two static functions named: zip_evaluate and enumerate_evaluate. The goal of these functions is to compute the sum of the lengths of every words of a given list weighted by a list a coefs. The lists coefs and words have to be the same length. If this is not the case, the function should return -1. | Evaluator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Evaluator:
"""Has two static functions named: zip_evaluate and enumerate_evaluate. The goal of these functions is to compute the sum of the lengths of every words of a given list weighted by a list a coefs. The lists coefs and words have to be the same length. If this is not the case, the functio... | stack_v2_sparse_classes_75kplus_train_006078 | 3,095 | no_license | [
{
"docstring": "Compute the sum of the lengths of every words of a given list weighted by a list a coefs. The lists coefs and words have to be the same length. If this is not the case, the function should return -1. :param words: list of str :param coefs: list of float :return: int - result (or -1 in case of wr... | 2 | stack_v2_sparse_classes_30k_train_047138 | Implement the Python class `Evaluator` described below.
Class description:
Has two static functions named: zip_evaluate and enumerate_evaluate. The goal of these functions is to compute the sum of the lengths of every words of a given list weighted by a list a coefs. The lists coefs and words have to be the same lengt... | Implement the Python class `Evaluator` described below.
Class description:
Has two static functions named: zip_evaluate and enumerate_evaluate. The goal of these functions is to compute the sum of the lengths of every words of a given list weighted by a list a coefs. The lists coefs and words have to be the same lengt... | 6ef001c7ad538239d78c18f9c5b236dad8f9e415 | <|skeleton|>
class Evaluator:
"""Has two static functions named: zip_evaluate and enumerate_evaluate. The goal of these functions is to compute the sum of the lengths of every words of a given list weighted by a list a coefs. The lists coefs and words have to be the same length. If this is not the case, the functio... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Evaluator:
"""Has two static functions named: zip_evaluate and enumerate_evaluate. The goal of these functions is to compute the sum of the lengths of every words of a given list weighted by a list a coefs. The lists coefs and words have to be the same length. If this is not the case, the function should retu... | the_stack_v2_python_sparse | day01/ex04/eval.py | sky-183/42ai_python_bootcamp | train | 0 |
1624ecff9683ececb1823d0a95a379d234c66d99 | [
"info = Func().query(function_id)\nif info is None:\n return self.error_404('接口%s不存在' % function_id)\nreturn self.succeed('接口查询成功', info)",
"try:\n info = Request()\nexcept ValueError as e:\n return self.error_400(str(e))\nif Func().update(function_id, url=info.get_param('url'), coontent=info.get_param('... | <|body_start_0|>
info = Func().query(function_id)
if info is None:
return self.error_404('接口%s不存在' % function_id)
return self.succeed('接口查询成功', info)
<|end_body_0|>
<|body_start_1|>
try:
info = Request()
except ValueError as e:
return self.err... | Function | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Function:
def get(self, function_id):
""":param function_id: :return:"""
<|body_0|>
def put(self, function_id):
"""只允许更新urk地址和content :param function_id: :return:"""
<|body_1|>
def delete(self, function_id):
""":param function_id: :return:"""
... | stack_v2_sparse_classes_75kplus_train_006079 | 2,971 | permissive | [
{
"docstring": ":param function_id: :return:",
"name": "get",
"signature": "def get(self, function_id)"
},
{
"docstring": "只允许更新urk地址和content :param function_id: :return:",
"name": "put",
"signature": "def put(self, function_id)"
},
{
"docstring": ":param function_id: :return:",
... | 3 | null | Implement the Python class `Function` described below.
Class description:
Implement the Function class.
Method signatures and docstrings:
- def get(self, function_id): :param function_id: :return:
- def put(self, function_id): 只允许更新urk地址和content :param function_id: :return:
- def delete(self, function_id): :param fun... | Implement the Python class `Function` described below.
Class description:
Implement the Function class.
Method signatures and docstrings:
- def get(self, function_id): :param function_id: :return:
- def put(self, function_id): 只允许更新urk地址和content :param function_id: :return:
- def delete(self, function_id): :param fun... | 3252f47e6b3fca170b57819f8fdbdeb0f868654e | <|skeleton|>
class Function:
def get(self, function_id):
""":param function_id: :return:"""
<|body_0|>
def put(self, function_id):
"""只允许更新urk地址和content :param function_id: :return:"""
<|body_1|>
def delete(self, function_id):
""":param function_id: :return:"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Function:
def get(self, function_id):
""":param function_id: :return:"""
info = Func().query(function_id)
if info is None:
return self.error_404('接口%s不存在' % function_id)
return self.succeed('接口查询成功', info)
def put(self, function_id):
"""只允许更新urk地址和conte... | the_stack_v2_python_sparse | apps/controllers/v1/function.py | BruceWW/flask-basic | train | 1 | |
e4da5603a34dee978c7ef7ff2b4126e984a0e26f | [
"super(GenericGeometry, self).__init__(**kwargs)\nself._logger.debug('Method: Constructor')\nfor item in network._geometry:\n if item.name == name:\n raise Exception('A Geometry Object with the supplied name already exists')\nnetwork.set_pore_info(label=name, locations=pnums)\nnetwork.set_throat_info(labe... | <|body_start_0|>
super(GenericGeometry, self).__init__(**kwargs)
self._logger.debug('Method: Constructor')
for item in network._geometry:
if item.name == name:
raise Exception('A Geometry Object with the supplied name already exists')
network.set_pore_info(lab... | GenericGeometry - Base class to construct pore networks This class contains the interface definition for the construction of networks Parameters ---------- network : OpenPNM Network Object name : string A unique name to apply to the object. This name will also be used as a label to identify where this this geometry app... | GenericGeometry | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenericGeometry:
"""GenericGeometry - Base class to construct pore networks This class contains the interface definition for the construction of networks Parameters ---------- network : OpenPNM Network Object name : string A unique name to apply to the object. This name will also be used as a lab... | stack_v2_sparse_classes_75kplus_train_006080 | 6,847 | permissive | [
{
"docstring": "Initialize",
"name": "__init__",
"signature": "def __init__(self, network, name, pnums='all', tnums='all', **kwargs)"
},
{
"docstring": "This updates all properties using the selected methods Parameters ---------- prop_list : string or list of strings The names of the properties ... | 4 | null | Implement the Python class `GenericGeometry` described below.
Class description:
GenericGeometry - Base class to construct pore networks This class contains the interface definition for the construction of networks Parameters ---------- network : OpenPNM Network Object name : string A unique name to apply to the objec... | Implement the Python class `GenericGeometry` described below.
Class description:
GenericGeometry - Base class to construct pore networks This class contains the interface definition for the construction of networks Parameters ---------- network : OpenPNM Network Object name : string A unique name to apply to the objec... | 7dcb9bfa8fc37568d5567cf36d91877fe2c53915 | <|skeleton|>
class GenericGeometry:
"""GenericGeometry - Base class to construct pore networks This class contains the interface definition for the construction of networks Parameters ---------- network : OpenPNM Network Object name : string A unique name to apply to the object. This name will also be used as a lab... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GenericGeometry:
"""GenericGeometry - Base class to construct pore networks This class contains the interface definition for the construction of networks Parameters ---------- network : OpenPNM Network Object name : string A unique name to apply to the object. This name will also be used as a label to identif... | the_stack_v2_python_sparse | OpenPNM/Geometry/__GenericGeometry__.py | jhinebau/OpenPNM | train | 0 |
ef316b1346de0ca0cc18f92dc54f1d67019712ba | [
"if not emails:\n return []\nreturn [email.strip() for email in emails.split(',')]",
"super().validate(emails)\nfor email in emails:\n validate_email(email)"
] | <|body_start_0|>
if not emails:
return []
return [email.strip() for email in emails.split(',')]
<|end_body_0|>
<|body_start_1|>
super().validate(emails)
for email in emails:
validate_email(email)
<|end_body_1|>
| MultiEmailField | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiEmailField:
def to_python(self, emails: Optional[str]) -> List[str]:
"""Normalize data to a list of strings."""
<|body_0|>
def validate(self, emails: List[str]) -> None:
"""Check if value consists only of valid emails."""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_75kplus_train_006081 | 23,582 | permissive | [
{
"docstring": "Normalize data to a list of strings.",
"name": "to_python",
"signature": "def to_python(self, emails: Optional[str]) -> List[str]"
},
{
"docstring": "Check if value consists only of valid emails.",
"name": "validate",
"signature": "def validate(self, emails: List[str]) ->... | 2 | stack_v2_sparse_classes_30k_train_008318 | Implement the Python class `MultiEmailField` described below.
Class description:
Implement the MultiEmailField class.
Method signatures and docstrings:
- def to_python(self, emails: Optional[str]) -> List[str]: Normalize data to a list of strings.
- def validate(self, emails: List[str]) -> None: Check if value consis... | Implement the Python class `MultiEmailField` described below.
Class description:
Implement the MultiEmailField class.
Method signatures and docstrings:
- def to_python(self, emails: Optional[str]) -> List[str]: Normalize data to a list of strings.
- def validate(self, emails: List[str]) -> None: Check if value consis... | 965a25d91b6ee2db54038f5df855215fa25146b0 | <|skeleton|>
class MultiEmailField:
def to_python(self, emails: Optional[str]) -> List[str]:
"""Normalize data to a list of strings."""
<|body_0|>
def validate(self, emails: List[str]) -> None:
"""Check if value consists only of valid emails."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiEmailField:
def to_python(self, emails: Optional[str]) -> List[str]:
"""Normalize data to a list of strings."""
if not emails:
return []
return [email.strip() for email in emails.split(',')]
def validate(self, emails: List[str]) -> None:
"""Check if value ... | the_stack_v2_python_sparse | zerver/forms.py | zulip/zulip | train | 20,239 | |
bba310e00c1afdffef382cfdc4ce467497ec007c | [
"super(FeedbackLinearizedParkController, self).__init__(path, L, is_ned, is_flat)\nassert type(acceleration) is numpy.ndarray, 'acceleration must be numpy array'\nassert acceleration.shape[1] == 3, 'acceleration must be nx3'\nassert acceleration.shape == path.shape, 'path and acceleration must ... | <|body_start_0|>
super(FeedbackLinearizedParkController, self).__init__(path, L, is_ned, is_flat)
assert type(acceleration) is numpy.ndarray, 'acceleration must be numpy array'
assert acceleration.shape[1] == 3, 'acceleration must be nx3'
assert acceleration.shape == path.shap... | A class generalizing the park controller to accelerating trajectories The park controller is developed for linear trajectories (ie tracking a line from one point to another). Here we generalize that through the use of feedback linearization. A nominal acceleration is provided for every point along the trajectory and is... | FeedbackLinearizedParkController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeedbackLinearizedParkController:
"""A class generalizing the park controller to accelerating trajectories The park controller is developed for linear trajectories (ie tracking a line from one point to another). Here we generalize that through the use of feedback linearization. A nominal accelera... | stack_v2_sparse_classes_75kplus_train_006082 | 19,298 | permissive | [
{
"docstring": "Constructor Arguments: path: an nx3 numpy specifying positions along the path in 3-d space acceleration: an nx3 numpy array specifying the nominal acceleration at each point on the path L: the lookahead distance on the path. is_ned: optional flag indicating if the path is given in north, east, d... | 2 | stack_v2_sparse_classes_30k_train_041669 | Implement the Python class `FeedbackLinearizedParkController` described below.
Class description:
A class generalizing the park controller to accelerating trajectories The park controller is developed for linear trajectories (ie tracking a line from one point to another). Here we generalize that through the use of fee... | Implement the Python class `FeedbackLinearizedParkController` described below.
Class description:
A class generalizing the park controller to accelerating trajectories The park controller is developed for linear trajectories (ie tracking a line from one point to another). Here we generalize that through the use of fee... | 6827886916e36432ce1d806f0a78edef6c9270d9 | <|skeleton|>
class FeedbackLinearizedParkController:
"""A class generalizing the park controller to accelerating trajectories The park controller is developed for linear trajectories (ie tracking a line from one point to another). Here we generalize that through the use of feedback linearization. A nominal accelera... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FeedbackLinearizedParkController:
"""A class generalizing the park controller to accelerating trajectories The park controller is developed for linear trajectories (ie tracking a line from one point to another). Here we generalize that through the use of feedback linearization. A nominal acceleration is provi... | the_stack_v2_python_sparse | pybots/src/robot_control/path_following.py | aivian/robots | train | 0 |
945e3e23bd75205f80350df351a7c10d5f780a75 | [
"self.accu_matrix = [row[:] for row in matrix]\nfor row in self.accu_matrix:\n for idx in range(1, len(row)):\n row[idx] += row[idx - 1]",
"res = 0\nfor row in self.accu_matrix[row1:row2 + 1]:\n res += row[col2] - (row[col1 - 1] if col1 > 0 else 0)\nreturn res"
] | <|body_start_0|>
self.accu_matrix = [row[:] for row in matrix]
for row in self.accu_matrix:
for idx in range(1, len(row)):
row[idx] += row[idx - 1]
<|end_body_0|>
<|body_start_1|>
res = 0
for row in self.accu_matrix[row1:row2 + 1]:
res += row[col2... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_75kplus_train_006083 | 1,079 | no_license | [
{
"docstring": ":type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int",
"name": "sumRegion",
"signature": "def sumRegion(self, row1, col1, row2, col2)"
... | 2 | stack_v2_sparse_classes_30k_train_015787 | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | dbdb227e12f329e4ca064b338f1fbdca42f3a848 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
self.accu_matrix = [row[:] for row in matrix]
for row in self.accu_matrix:
for idx in range(1, len(row)):
row[idx] += row[idx - 1]
def sumRegion(self, row1, col1, row2, col2):
... | the_stack_v2_python_sparse | LC304.py | Qiao-Liang/LeetCode | train | 0 | |
2d17ee1671e7e266de124413c642172868f24098 | [
"mock_request.remote_addr = '10.10.10.10'\nmock_request.session = None\nmock_request.auth = mock.MagicMock(nonce='foononce123')\nmock_get_config.return_value = {'CSRF_SECRET': 'foosecret'}\n\nclass ProtectedForm(csrf.CSRFForm):\n \"\"\"A CSRF-protected form.\"\"\"\n something_sensitive = StringField('Somethin... | <|body_start_0|>
mock_request.remote_addr = '10.10.10.10'
mock_request.session = None
mock_request.auth = mock.MagicMock(nonce='foononce123')
mock_get_config.return_value = {'CSRF_SECRET': 'foosecret'}
class ProtectedForm(csrf.CSRFForm):
"""A CSRF-protected form."""
... | Test using the ``request.auth`` session ref in accounts v0.4.1. | TestCSRFFormWithNewSessionRef | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCSRFFormWithNewSessionRef:
"""Test using the ``request.auth`` session ref in accounts v0.4.1."""
def test_invalid_token(self, mock_get_config, mock_request):
"""An invalid CSRF token is passed in the form data."""
<|body_0|>
def test_valid_token(self, mock_get_config... | stack_v2_sparse_classes_75kplus_train_006084 | 6,313 | permissive | [
{
"docstring": "An invalid CSRF token is passed in the form data.",
"name": "test_invalid_token",
"signature": "def test_invalid_token(self, mock_get_config, mock_request)"
},
{
"docstring": "A valid CSRF token is passed in the form data.",
"name": "test_valid_token",
"signature": "def t... | 3 | stack_v2_sparse_classes_30k_train_014699 | Implement the Python class `TestCSRFFormWithNewSessionRef` described below.
Class description:
Test using the ``request.auth`` session ref in accounts v0.4.1.
Method signatures and docstrings:
- def test_invalid_token(self, mock_get_config, mock_request): An invalid CSRF token is passed in the form data.
- def test_v... | Implement the Python class `TestCSRFFormWithNewSessionRef` described below.
Class description:
Test using the ``request.auth`` session ref in accounts v0.4.1.
Method signatures and docstrings:
- def test_invalid_token(self, mock_get_config, mock_request): An invalid CSRF token is passed in the form data.
- def test_v... | d1d9810a2b2318665be45bcf91bb9b08d88e44f1 | <|skeleton|>
class TestCSRFFormWithNewSessionRef:
"""Test using the ``request.auth`` session ref in accounts v0.4.1."""
def test_invalid_token(self, mock_get_config, mock_request):
"""An invalid CSRF token is passed in the form data."""
<|body_0|>
def test_valid_token(self, mock_get_config... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestCSRFFormWithNewSessionRef:
"""Test using the ``request.auth`` session ref in accounts v0.4.1."""
def test_invalid_token(self, mock_get_config, mock_request):
"""An invalid CSRF token is passed in the form data."""
mock_request.remote_addr = '10.10.10.10'
mock_request.session =... | the_stack_v2_python_sparse | arxiv/forms/tests.py | arXiv/arxiv-base | train | 31 |
78831c3f27120e24f4da27d75f37b3c6f53641a2 | [
"super().__init__()\nself.discriminators = torch.nn.ModuleList()\nfor i in range(scales):\n params = copy.deepcopy(discriminator_params)\n if follow_official_norm:\n if i == 0:\n params['use_weight_norm'] = False\n params['use_spectral_norm'] = True\n else:\n par... | <|body_start_0|>
super().__init__()
self.discriminators = torch.nn.ModuleList()
for i in range(scales):
params = copy.deepcopy(discriminator_params)
if follow_official_norm:
if i == 0:
params['use_weight_norm'] = False
... | HiFi-GAN multi-scale discriminator module. | HiFiGANMultiScaleDiscriminator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HiFiGANMultiScaleDiscriminator:
"""HiFi-GAN multi-scale discriminator module."""
def __init__(self, scales: int=3, downsample_pooling: str='AvgPool1d', downsample_pooling_params: Dict[str, Any]={'kernel_size': 4, 'stride': 2, 'padding': 2}, discriminator_params: Dict[str, Any]={'in_channels'... | stack_v2_sparse_classes_75kplus_train_006085 | 31,567 | permissive | [
{
"docstring": "Initilize HiFiGAN multi-scale discriminator module. Args: scales (int): Number of multi-scales. downsample_pooling (str): Pooling module name for downsampling of the inputs. downsample_pooling_params (Dict[str, Any]): Parameters for the above pooling module. discriminator_params (Dict[str, Any])... | 2 | stack_v2_sparse_classes_30k_train_026466 | Implement the Python class `HiFiGANMultiScaleDiscriminator` described below.
Class description:
HiFi-GAN multi-scale discriminator module.
Method signatures and docstrings:
- def __init__(self, scales: int=3, downsample_pooling: str='AvgPool1d', downsample_pooling_params: Dict[str, Any]={'kernel_size': 4, 'stride': 2... | Implement the Python class `HiFiGANMultiScaleDiscriminator` described below.
Class description:
HiFi-GAN multi-scale discriminator module.
Method signatures and docstrings:
- def __init__(self, scales: int=3, downsample_pooling: str='AvgPool1d', downsample_pooling_params: Dict[str, Any]={'kernel_size': 4, 'stride': 2... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class HiFiGANMultiScaleDiscriminator:
"""HiFi-GAN multi-scale discriminator module."""
def __init__(self, scales: int=3, downsample_pooling: str='AvgPool1d', downsample_pooling_params: Dict[str, Any]={'kernel_size': 4, 'stride': 2, 'padding': 2}, discriminator_params: Dict[str, Any]={'in_channels'... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HiFiGANMultiScaleDiscriminator:
"""HiFi-GAN multi-scale discriminator module."""
def __init__(self, scales: int=3, downsample_pooling: str='AvgPool1d', downsample_pooling_params: Dict[str, Any]={'kernel_size': 4, 'stride': 2, 'padding': 2}, discriminator_params: Dict[str, Any]={'in_channels': 1, 'out_cha... | the_stack_v2_python_sparse | espnet2/gan_tts/hifigan/hifigan.py | espnet/espnet | train | 7,242 |
5473cd67a43aeac7ba032a27f3cbf8e0654f8f17 | [
"l, r = (0, len(A) - 1)\nwhile l < r:\n mid = int((l + r) / 2)\n if len(A) - 1 > mid > 0 and A[mid + 1] < A[mid] > A[mid - 1]:\n return mid\n elif A[mid] < A[mid + 1]:\n l = mid + 1\n elif A[mid] < A[mid - 1]:\n r = mid - 1\nreturn l",
"l, r = (0, len(A))\nwhile l < r:\n mid = ... | <|body_start_0|>
l, r = (0, len(A) - 1)
while l < r:
mid = int((l + r) / 2)
if len(A) - 1 > mid > 0 and A[mid + 1] < A[mid] > A[mid - 1]:
return mid
elif A[mid] < A[mid + 1]:
l = mid + 1
elif A[mid] < A[mid - 1]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def peakIndexInMountainArray(self, A):
""":type A: List[int] :rtype: int"""
<|body_0|>
def peakIndexInMountainArray2(self, A):
"""2020.02.23: Binary search."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
l, r = (0, len(A) - 1)
whi... | stack_v2_sparse_classes_75kplus_train_006086 | 2,067 | no_license | [
{
"docstring": ":type A: List[int] :rtype: int",
"name": "peakIndexInMountainArray",
"signature": "def peakIndexInMountainArray(self, A)"
},
{
"docstring": "2020.02.23: Binary search.",
"name": "peakIndexInMountainArray2",
"signature": "def peakIndexInMountainArray2(self, A)"
}
] | 2 | stack_v2_sparse_classes_30k_test_002528 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def peakIndexInMountainArray(self, A): :type A: List[int] :rtype: int
- def peakIndexInMountainArray2(self, A): 2020.02.23: Binary search. | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def peakIndexInMountainArray(self, A): :type A: List[int] :rtype: int
- def peakIndexInMountainArray2(self, A): 2020.02.23: Binary search.
<|skeleton|>
class Solution:
def ... | a5b02044ef39154b6a8d32eb57682f447e1632ba | <|skeleton|>
class Solution:
def peakIndexInMountainArray(self, A):
""":type A: List[int] :rtype: int"""
<|body_0|>
def peakIndexInMountainArray2(self, A):
"""2020.02.23: Binary search."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def peakIndexInMountainArray(self, A):
""":type A: List[int] :rtype: int"""
l, r = (0, len(A) - 1)
while l < r:
mid = int((l + r) / 2)
if len(A) - 1 > mid > 0 and A[mid + 1] < A[mid] > A[mid - 1]:
return mid
elif A[mid] < A[... | the_stack_v2_python_sparse | algo/binary_search/peak_index_in_a_mountain_array.py | xys234/coding-problems | train | 0 | |
fe679d5f56871253bef8e90afee1deaa87381d75 | [
"res = super(create_quick_purchase, self)._onchange_product_id()\nproduct = self.product_id\nif product:\n if product.purchase_line_warn != 'no-message':\n res = {'warning': {'title': _('Warning for %s') % product.name, 'message': product.purchase_line_warn_msg}}\nreturn res",
"warning = {}\ntitle = Fal... | <|body_start_0|>
res = super(create_quick_purchase, self)._onchange_product_id()
product = self.product_id
if product:
if product.purchase_line_warn != 'no-message':
res = {'warning': {'title': _('Warning for %s') % product.name, 'message': product.purchase_line_warn_... | create_quick_purchase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class create_quick_purchase:
def _onchange_product_id(self):
"""Surcharge du onchange des produits du wizard de création rapide d'achat, lorsqu'on sélectionne un produit on vérifie s'il dispose ou non d'un warning et on l'affiche si c'est le cas."""
<|body_0|>
def _onchange_partne... | stack_v2_sparse_classes_75kplus_train_006087 | 1,707 | no_license | [
{
"docstring": "Surcharge du onchange des produits du wizard de création rapide d'achat, lorsqu'on sélectionne un produit on vérifie s'il dispose ou non d'un warning et on l'affiche si c'est le cas.",
"name": "_onchange_product_id",
"signature": "def _onchange_product_id(self)"
},
{
"docstring":... | 2 | stack_v2_sparse_classes_30k_train_038757 | Implement the Python class `create_quick_purchase` described below.
Class description:
Implement the create_quick_purchase class.
Method signatures and docstrings:
- def _onchange_product_id(self): Surcharge du onchange des produits du wizard de création rapide d'achat, lorsqu'on sélectionne un produit on vérifie s'i... | Implement the Python class `create_quick_purchase` described below.
Class description:
Implement the create_quick_purchase class.
Method signatures and docstrings:
- def _onchange_product_id(self): Surcharge du onchange des produits du wizard de création rapide d'achat, lorsqu'on sélectionne un produit on vérifie s'i... | eb394e1f79ba1995da2dcd81adfdd511c22caff9 | <|skeleton|>
class create_quick_purchase:
def _onchange_product_id(self):
"""Surcharge du onchange des produits du wizard de création rapide d'achat, lorsqu'on sélectionne un produit on vérifie s'il dispose ou non d'un warning et on l'affiche si c'est le cas."""
<|body_0|>
def _onchange_partne... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class create_quick_purchase:
def _onchange_product_id(self):
"""Surcharge du onchange des produits du wizard de création rapide d'achat, lorsqu'on sélectionne un produit on vérifie s'il dispose ou non d'un warning et on l'affiche si c'est le cas."""
res = super(create_quick_purchase, self)._onchange... | the_stack_v2_python_sparse | OpenPROD/openprod-addons/warning/wizard/create_quick_purchase.py | kazacube-mziouadi/ceci | train | 0 | |
4375e2a1aeae290587b1884e656cf83b8cb82a82 | [
"if not root:\n return 0\nreturn 1 + self.countNodes(root.left) + self.countNodes(root.right)",
"if not root:\n return 0\nh = 0\nwhile root.left:\n h += 1\n root = root.left\nreturn 2 ** h - 1"
] | <|body_start_0|>
if not root:
return 0
return 1 + self.countNodes(root.left) + self.countNodes(root.right)
<|end_body_0|>
<|body_start_1|>
if not root:
return 0
h = 0
while root.left:
h += 1
root = root.left
return 2 ** h -... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countNodes(self, root) -> int:
"""完全二叉树: 除了最底层节点可能没填满外, 其余每层节点数都达到最大值, 并且最下面一层的节点都集中在该层最左边的若干位置。 若最底层为第 h 层,则该层包含 1~ 2h 个节点。"""
<|body_0|>
def countFullNodes(self, root):
"""满二叉树,既每层都是满的二叉树 他的节点个数为 2^h -1 个 (h为层数)"""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_75kplus_train_006088 | 1,095 | no_license | [
{
"docstring": "完全二叉树: 除了最底层节点可能没填满外, 其余每层节点数都达到最大值, 并且最下面一层的节点都集中在该层最左边的若干位置。 若最底层为第 h 层,则该层包含 1~ 2h 个节点。",
"name": "countNodes",
"signature": "def countNodes(self, root) -> int"
},
{
"docstring": "满二叉树,既每层都是满的二叉树 他的节点个数为 2^h -1 个 (h为层数)",
"name": "countFullNodes",
"signature": "def cou... | 2 | stack_v2_sparse_classes_30k_train_042091 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countNodes(self, root) -> int: 完全二叉树: 除了最底层节点可能没填满外, 其余每层节点数都达到最大值, 并且最下面一层的节点都集中在该层最左边的若干位置。 若最底层为第 h 层,则该层包含 1~ 2h 个节点。
- def countFullNodes(self, root): 满二叉树,既每层都是满的二叉树 他的... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countNodes(self, root) -> int: 完全二叉树: 除了最底层节点可能没填满外, 其余每层节点数都达到最大值, 并且最下面一层的节点都集中在该层最左边的若干位置。 若最底层为第 h 层,则该层包含 1~ 2h 个节点。
- def countFullNodes(self, root): 满二叉树,既每层都是满的二叉树 他的... | e0ad5e52829345dd2ce4bc578295336ca07b2662 | <|skeleton|>
class Solution:
def countNodes(self, root) -> int:
"""完全二叉树: 除了最底层节点可能没填满外, 其余每层节点数都达到最大值, 并且最下面一层的节点都集中在该层最左边的若干位置。 若最底层为第 h 层,则该层包含 1~ 2h 个节点。"""
<|body_0|>
def countFullNodes(self, root):
"""满二叉树,既每层都是满的二叉树 他的节点个数为 2^h -1 个 (h为层数)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def countNodes(self, root) -> int:
"""完全二叉树: 除了最底层节点可能没填满外, 其余每层节点数都达到最大值, 并且最下面一层的节点都集中在该层最左边的若干位置。 若最底层为第 h 层,则该层包含 1~ 2h 个节点。"""
if not root:
return 0
return 1 + self.countNodes(root.left) + self.countNodes(root.right)
def countFullNodes(self, root):
... | the_stack_v2_python_sparse | labuladong/二叉树/222.完全二叉树的节点个数.py | Ehco1996/leetcode | train | 7 | |
3253ad287bab368239a9832c558801a90279b4d0 | [
"num = 1\nsubnum = 0\nif filename is None:\n filename = cls.DEFAULT_FILE\nif os.path.exists(filename):\n with open(filename, 'r') as fin:\n line = fin.readline()\n mtch = re.search('(\\\\d+)\\\\s+(\\\\d+)', line)\n if mtch is not None:\n try:\n num = int(mtch.gro... | <|body_start_0|>
num = 1
subnum = 0
if filename is None:
filename = cls.DEFAULT_FILE
if os.path.exists(filename):
with open(filename, 'r') as fin:
line = fin.readline()
mtch = re.search('(\\d+)\\s+(\\d+)', line)
if m... | RunNumber | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunNumber:
def get_last(cls, filename=None):
"""Return the last run and subrun numbers as a tuple"""
<|body_0|>
def set_last(cls, number, subrun=0, filename=None):
"""Set the last run and subrun numbers"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_006089 | 4,402 | no_license | [
{
"docstring": "Return the last run and subrun numbers as a tuple",
"name": "get_last",
"signature": "def get_last(cls, filename=None)"
},
{
"docstring": "Set the last run and subrun numbers",
"name": "set_last",
"signature": "def set_last(cls, number, subrun=0, filename=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_025747 | Implement the Python class `RunNumber` described below.
Class description:
Implement the RunNumber class.
Method signatures and docstrings:
- def get_last(cls, filename=None): Return the last run and subrun numbers as a tuple
- def set_last(cls, number, subrun=0, filename=None): Set the last run and subrun numbers | Implement the Python class `RunNumber` described below.
Class description:
Implement the RunNumber class.
Method signatures and docstrings:
- def get_last(cls, filename=None): Return the last run and subrun numbers as a tuple
- def set_last(cls, number, subrun=0, filename=None): Set the last run and subrun numbers
<... | 718189be62907a6a8031980fe0c41fa7e06b898d | <|skeleton|>
class RunNumber:
def get_last(cls, filename=None):
"""Return the last run and subrun numbers as a tuple"""
<|body_0|>
def set_last(cls, number, subrun=0, filename=None):
"""Set the last run and subrun numbers"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RunNumber:
def get_last(cls, filename=None):
"""Return the last run and subrun numbers as a tuple"""
num = 1
subnum = 0
if filename is None:
filename = cls.DEFAULT_FILE
if os.path.exists(filename):
with open(filename, 'r') as fin:
... | the_stack_v2_python_sparse | RunNumber.py | dglo/dash | train | 0 | |
b19d04a16672a6e82ef0ac5031a632a46feb1e78 | [
"super(ModelGRUCell5, self).__init__()\nself.trg_embeder = Embedding(100, 32)\nself.output_layer = Linear(32, 32)\nself.decoder_cell = GRUCell(input_size=32, hidden_size=32)\nself.decoder = BeamSearchDecoder(self.decoder_cell, start_token=0, end_token=1, beam_size=4, embedding_fn=self.trg_embeder, output_fn=self.ou... | <|body_start_0|>
super(ModelGRUCell5, self).__init__()
self.trg_embeder = Embedding(100, 32)
self.output_layer = Linear(32, 32)
self.decoder_cell = GRUCell(input_size=32, hidden_size=32)
self.decoder = BeamSearchDecoder(self.decoder_cell, start_token=0, end_token=1, beam_size=4, ... | GRUCell model1 | ModelGRUCell5 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelGRUCell5:
"""GRUCell model1"""
def __init__(self):
"""initialize"""
<|body_0|>
def forward(self):
"""forward"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(ModelGRUCell5, self).__init__()
self.trg_embeder = Embedding(100, 32)... | stack_v2_sparse_classes_75kplus_train_006090 | 20,209 | no_license | [
{
"docstring": "initialize",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "forward",
"name": "forward",
"signature": "def forward(self)"
}
] | 2 | null | Implement the Python class `ModelGRUCell5` described below.
Class description:
GRUCell model1
Method signatures and docstrings:
- def __init__(self): initialize
- def forward(self): forward | Implement the Python class `ModelGRUCell5` described below.
Class description:
GRUCell model1
Method signatures and docstrings:
- def __init__(self): initialize
- def forward(self): forward
<|skeleton|>
class ModelGRUCell5:
"""GRUCell model1"""
def __init__(self):
"""initialize"""
<|body_0|>... | bd3790ce72a2a26611b5eda3901651b5a809348f | <|skeleton|>
class ModelGRUCell5:
"""GRUCell model1"""
def __init__(self):
"""initialize"""
<|body_0|>
def forward(self):
"""forward"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ModelGRUCell5:
"""GRUCell model1"""
def __init__(self):
"""initialize"""
super(ModelGRUCell5, self).__init__()
self.trg_embeder = Embedding(100, 32)
self.output_layer = Linear(32, 32)
self.decoder_cell = GRUCell(input_size=32, hidden_size=32)
self.decoder =... | the_stack_v2_python_sparse | framework/api/nn/test_dynamicdecode.py | PaddlePaddle/PaddleTest | train | 42 |
080b7c84d692b28fc532f66d7e56980e0e935d09 | [
"if s == '':\n return False\nif len(s) == 1:\n return True\np1 = 0\np2 = len(s) - 1\ns = s.lower()\nwhile p1 < p2:\n if s[p1] not in self.alphanum:\n p1 += 1\n elif s[p2] not in self.alphanum:\n p2 -= 1\n elif s[p1] != s[p2]:\n return False\n else:\n p1 += 1\n p2... | <|body_start_0|>
if s == '':
return False
if len(s) == 1:
return True
p1 = 0
p2 = len(s) - 1
s = s.lower()
while p1 < p2:
if s[p1] not in self.alphanum:
p1 += 1
elif s[p2] not in self.alphanum:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindrome(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def countSubstrings(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if s == '':
return False
if len(s) == 1:
... | stack_v2_sparse_classes_75kplus_train_006091 | 965 | no_license | [
{
"docstring": ":type s: str :rtype: bool",
"name": "isPalindrome",
"signature": "def isPalindrome(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "countSubstrings",
"signature": "def countSubstrings(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_044797 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, s): :type s: str :rtype: bool
- def countSubstrings(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, s): :type s: str :rtype: bool
- def countSubstrings(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def isPalindrome(self, s):
... | 528f545e9a262da09d51b908687dc1d416d907a3 | <|skeleton|>
class Solution:
def isPalindrome(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def countSubstrings(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isPalindrome(self, s):
""":type s: str :rtype: bool"""
if s == '':
return False
if len(s) == 1:
return True
p1 = 0
p2 = len(s) - 1
s = s.lower()
while p1 < p2:
if s[p1] not in self.alphanum:
... | the_stack_v2_python_sparse | python/leetcode/palindromic-substrings.py | quetzaluz/codesnippets | train | 1 | |
445e07a1b7c8c47e3a908bb2319e93a5b8427796 | [
"self.domain = domain\nif not adminuser:\n adminuser = creds.google[domain]['adminuser']\nif not oauth_secret:\n oauth_secret = creds.google[domain]['oauth_secret']\nif g_client:\n self.g_client = g_client\nelse:\n self.g_client = gdata.contacts.client.ContactsClient(source='pdx-edu-user-profile-client'... | <|body_start_0|>
self.domain = domain
if not adminuser:
adminuser = creds.google[domain]['adminuser']
if not oauth_secret:
oauth_secret = creds.google[domain]['oauth_secret']
if g_client:
self.g_client = g_client
else:
self.g_client... | Google user profile management. | Profile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Profile:
"""Google user profile management."""
def __init__(self, domain=None, adminuser=None, oauth_secret=None, g_client=None):
"""New profile object. Google <domain> required. <adminuser> and <oauth_secret> will override module defaults. A <g_client> of type gdata.contacts.client.... | stack_v2_sparse_classes_75kplus_train_006092 | 3,037 | no_license | [
{
"docstring": "New profile object. Google <domain> required. <adminuser> and <oauth_secret> will override module defaults. A <g_client> of type gdata.contacts.client.ContactsClient can be specified to re-use an existing client.",
"name": "__init__",
"signature": "def __init__(self, domain=None, adminus... | 3 | stack_v2_sparse_classes_30k_train_034319 | Implement the Python class `Profile` described below.
Class description:
Google user profile management.
Method signatures and docstrings:
- def __init__(self, domain=None, adminuser=None, oauth_secret=None, g_client=None): New profile object. Google <domain> required. <adminuser> and <oauth_secret> will override mod... | Implement the Python class `Profile` described below.
Class description:
Google user profile management.
Method signatures and docstrings:
- def __init__(self, domain=None, adminuser=None, oauth_secret=None, g_client=None): New profile object. Google <domain> required. <adminuser> and <oauth_secret> will override mod... | a82b88a4be6c17fe298549d0e753f14555ee60a3 | <|skeleton|>
class Profile:
"""Google user profile management."""
def __init__(self, domain=None, adminuser=None, oauth_secret=None, g_client=None):
"""New profile object. Google <domain> required. <adminuser> and <oauth_secret> will override module defaults. A <g_client> of type gdata.contacts.client.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Profile:
"""Google user profile management."""
def __init__(self, domain=None, adminuser=None, oauth_secret=None, g_client=None):
"""New profile object. Google <domain> required. <adminuser> and <oauth_secret> will override module defaults. A <g_client> of type gdata.contacts.client.ContactsClien... | the_stack_v2_python_sparse | mysite/psugle/profile.py | maxgarvey/psu_gcal | train | 0 |
ec465d95c25186c6d9cf643963034abde09e51cf | [
"self.mMapComponent2Object = {}\nself.mMapObject2Component = {}\nfor line in infile:\n if line[0] == '#':\n continue\n data = line[:-1].split('\\t')\n obj_id, obj_start, obj_end, ncoms, com_type, com_id = data[:6]\n if com_type == 'N':\n continue\n com_start, com_end, orientation = data... | <|body_start_0|>
self.mMapComponent2Object = {}
self.mMapObject2Component = {}
for line in infile:
if line[0] == '#':
continue
data = line[:-1].split('\t')
obj_id, obj_start, obj_end, ncoms, com_type, com_id = data[:6]
if com_type =... | Parser for AGP formatted files. | AGP | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AGP:
"""Parser for AGP formatted files."""
def readFromFile(self, infile):
"""read an agp file. Example line:: scaffold_1 1 1199 1 W contig_13 1 1199 + This method converts coordinates to zero-based coordinates using open/closed notation. In AGP nomenclature (http://www.ncbi.nlm.nih.... | stack_v2_sparse_classes_75kplus_train_006093 | 3,370 | permissive | [
{
"docstring": "read an agp file. Example line:: scaffold_1 1 1199 1 W contig_13 1 1199 + This method converts coordinates to zero-based coordinates using open/closed notation. In AGP nomenclature (http://www.ncbi.nlm.nih.gov/genome/guide/Assembly/AGP_Specification.html) objects (obj) like scaffolds are assembl... | 2 | stack_v2_sparse_classes_30k_train_002571 | Implement the Python class `AGP` described below.
Class description:
Parser for AGP formatted files.
Method signatures and docstrings:
- def readFromFile(self, infile): read an agp file. Example line:: scaffold_1 1 1199 1 W contig_13 1 1199 + This method converts coordinates to zero-based coordinates using open/close... | Implement the Python class `AGP` described below.
Class description:
Parser for AGP formatted files.
Method signatures and docstrings:
- def readFromFile(self, infile): read an agp file. Example line:: scaffold_1 1 1199 1 W contig_13 1 1199 + This method converts coordinates to zero-based coordinates using open/close... | d26fab0dff2192d4accc128d2895e668254d7b65 | <|skeleton|>
class AGP:
"""Parser for AGP formatted files."""
def readFromFile(self, infile):
"""read an agp file. Example line:: scaffold_1 1 1199 1 W contig_13 1 1199 + This method converts coordinates to zero-based coordinates using open/closed notation. In AGP nomenclature (http://www.ncbi.nlm.nih.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AGP:
"""Parser for AGP formatted files."""
def readFromFile(self, infile):
"""read an agp file. Example line:: scaffold_1 1 1199 1 W contig_13 1 1199 + This method converts coordinates to zero-based coordinates using open/closed notation. In AGP nomenclature (http://www.ncbi.nlm.nih.gov/genome/gu... | the_stack_v2_python_sparse | CGAT/AGP.py | jaquol/cgat | train | 1 |
5984271ee7cd364ff3b41be0b4c8a6b8522d13b8 | [
"post_body = json.dumps({'security_group_default_rule': kwargs})\nurl = 'os-security-group-default-rules'\nresp, body = self.post(url, post_body)\nbody = json.loads(body)\nself.validate_response(schema.create_get_security_group_default_rule, resp, body)\nreturn rest_client.ResponseBody(resp, body)",
"resp, body =... | <|body_start_0|>
post_body = json.dumps({'security_group_default_rule': kwargs})
url = 'os-security-group-default-rules'
resp, body = self.post(url, post_body)
body = json.loads(body)
self.validate_response(schema.create_get_security_group_default_rule, resp, body)
return... | SecurityGroupDefaultRulesClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SecurityGroupDefaultRulesClient:
def create_security_default_group_rule(self, **kwargs):
"""Create security group default rule. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/compute/#create-default-security-group-r... | stack_v2_sparse_classes_75kplus_train_006094 | 2,984 | permissive | [
{
"docstring": "Create security group default rule. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/compute/#create-default-security-group-rule",
"name": "create_security_default_group_rule",
"signature": "def create_security_defaul... | 4 | stack_v2_sparse_classes_30k_train_029385 | Implement the Python class `SecurityGroupDefaultRulesClient` described below.
Class description:
Implement the SecurityGroupDefaultRulesClient class.
Method signatures and docstrings:
- def create_security_default_group_rule(self, **kwargs): Create security group default rule. For a full list of available parameters,... | Implement the Python class `SecurityGroupDefaultRulesClient` described below.
Class description:
Implement the SecurityGroupDefaultRulesClient class.
Method signatures and docstrings:
- def create_security_default_group_rule(self, **kwargs): Create security group default rule. For a full list of available parameters,... | 3932a799e620a20d7abf7b89e21b520683a1809b | <|skeleton|>
class SecurityGroupDefaultRulesClient:
def create_security_default_group_rule(self, **kwargs):
"""Create security group default rule. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/compute/#create-default-security-group-r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SecurityGroupDefaultRulesClient:
def create_security_default_group_rule(self, **kwargs):
"""Create security group default rule. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/compute/#create-default-security-group-rule"""
... | the_stack_v2_python_sparse | tempest/lib/services/compute/security_group_default_rules_client.py | openstack/tempest | train | 270 | |
373c6d761db34bb1d0b838187730674054d4f94b | [
"super(MACNetwork, self).__init__()\nself.dim = 512\nself.embed_hidden = params.emb_dim\nself.max_step = 12\nself.self_attention = False\nself.memory_gate = False\nself.max_step = 12\nself.dropout = 0.15\ntry:\n self.nb_classes = params.num_classes\nexcept KeyError:\n self.logger.warning(\"Couldn't retrieve o... | <|body_start_0|>
super(MACNetwork, self).__init__()
self.dim = 512
self.embed_hidden = params.emb_dim
self.max_step = 12
self.self_attention = False
self.memory_gate = False
self.max_step = 12
self.dropout = 0.15
try:
self.nb_classes = ... | Implementation of the entire ``MAC`` network. | MACNetwork | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MACNetwork:
"""Implementation of the entire ``MAC`` network."""
def __init__(self, params):
"""Constructor for the ``MAC`` network. :param params: dict of parameters (read from configuration ``.yaml`` file). :type params: utils.ParamInterface :param problem_default_values_: default v... | stack_v2_sparse_classes_75kplus_train_006095 | 5,495 | permissive | [
{
"docstring": "Constructor for the ``MAC`` network. :param params: dict of parameters (read from configuration ``.yaml`` file). :type params: utils.ParamInterface :param problem_default_values_: default values coming from the ``Problem`` class. :type problem_default_values_: dict",
"name": "__init__",
... | 2 | stack_v2_sparse_classes_30k_train_045106 | Implement the Python class `MACNetwork` described below.
Class description:
Implementation of the entire ``MAC`` network.
Method signatures and docstrings:
- def __init__(self, params): Constructor for the ``MAC`` network. :param params: dict of parameters (read from configuration ``.yaml`` file). :type params: utils... | Implement the Python class `MACNetwork` described below.
Class description:
Implementation of the entire ``MAC`` network.
Method signatures and docstrings:
- def __init__(self, params): Constructor for the ``MAC`` network. :param params: dict of parameters (read from configuration ``.yaml`` file). :type params: utils... | 2e82ca75a3e4d4ccba00c5a763097cc0f650a0a4 | <|skeleton|>
class MACNetwork:
"""Implementation of the entire ``MAC`` network."""
def __init__(self, params):
"""Constructor for the ``MAC`` network. :param params: dict of parameters (read from configuration ``.yaml`` file). :type params: utils.ParamInterface :param problem_default_values_: default v... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MACNetwork:
"""Implementation of the entire ``MAC`` network."""
def __init__(self, params):
"""Constructor for the ``MAC`` network. :param params: dict of parameters (read from configuration ``.yaml`` file). :type params: utils.ParamInterface :param problem_default_values_: default values coming ... | the_stack_v2_python_sparse | vqa_experiments/s_mac/model.py | msrocean/REMIND | train | 1 |
23787fc865f134b31e77ffccdee6a860b99ba01e | [
"if not root:\n return ''\nleft = self.serialize(root.left)\nright = self.serialize(root.right)\nserialized = str(root.val) + 'R' + '[' + left + ']' + right\nreturn serialized",
"if not data:\n return None\nleft_index = data.index('R')\nroot = TreeNode(int(data[:left_index]))\nlr = data[left_index + 1:]\nl,... | <|body_start_0|>
if not root:
return ''
left = self.serialize(root.left)
right = self.serialize(root.right)
serialized = str(root.val) + 'R' + '[' + left + ']' + right
return serialized
<|end_body_0|>
<|body_start_1|>
if not data:
return None
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
... | stack_v2_sparse_classes_75kplus_train_006096 | 1,453 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_010278 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class Co... | 00bf9a8164008aa17507b1c87ce72a3374bcb7b9 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
if not root:
return ''
left = self.serialize(root.left)
right = self.serialize(root.right)
serialized = str(root.val) + 'R' + '[' + left + ']' + right
return ... | the_stack_v2_python_sparse | solutions/449.serialize-and-deserialize-bst.py | quixoteji/Leetcode | train | 1 | |
fd899f950f1e50bf1718487203b063fd03573ea8 | [
"self.power_off_vm_before_recovery = power_off_vm_before_recovery\nself.power_on_vm_after_recovery = power_on_vm_after_recovery\nself.target_source = target_source\nself.virtual_disk_mappings = virtual_disk_mappings",
"if dictionary is None:\n return None\npower_off_vm_before_recovery = dictionary.get('powerOf... | <|body_start_0|>
self.power_off_vm_before_recovery = power_off_vm_before_recovery
self.power_on_vm_after_recovery = power_on_vm_after_recovery
self.target_source = target_source
self.virtual_disk_mappings = virtual_disk_mappings
<|end_body_0|>
<|body_start_1|>
if dictionary is N... | Implementation of the 'VirtualDiskRestoreResponse' model. Specifies the parameters to recover virtual disks of a vm with full Protection Source. Attributes: power_off_vm_before_recovery (bool): Specifies whether to power off the VM before recovering virtual disks. power_on_vm_after_recovery (bool): Specifies whether to... | VirtualDiskRestoreResponse | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VirtualDiskRestoreResponse:
"""Implementation of the 'VirtualDiskRestoreResponse' model. Specifies the parameters to recover virtual disks of a vm with full Protection Source. Attributes: power_off_vm_before_recovery (bool): Specifies whether to power off the VM before recovering virtual disks. p... | stack_v2_sparse_classes_75kplus_train_006097 | 3,302 | permissive | [
{
"docstring": "Constructor for the VirtualDiskRestoreResponse class",
"name": "__init__",
"signature": "def __init__(self, power_off_vm_before_recovery=None, power_on_vm_after_recovery=None, target_source=None, virtual_disk_mappings=None)"
},
{
"docstring": "Creates an instance of this model fr... | 2 | stack_v2_sparse_classes_30k_train_051507 | Implement the Python class `VirtualDiskRestoreResponse` described below.
Class description:
Implementation of the 'VirtualDiskRestoreResponse' model. Specifies the parameters to recover virtual disks of a vm with full Protection Source. Attributes: power_off_vm_before_recovery (bool): Specifies whether to power off th... | Implement the Python class `VirtualDiskRestoreResponse` described below.
Class description:
Implementation of the 'VirtualDiskRestoreResponse' model. Specifies the parameters to recover virtual disks of a vm with full Protection Source. Attributes: power_off_vm_before_recovery (bool): Specifies whether to power off th... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class VirtualDiskRestoreResponse:
"""Implementation of the 'VirtualDiskRestoreResponse' model. Specifies the parameters to recover virtual disks of a vm with full Protection Source. Attributes: power_off_vm_before_recovery (bool): Specifies whether to power off the VM before recovering virtual disks. p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VirtualDiskRestoreResponse:
"""Implementation of the 'VirtualDiskRestoreResponse' model. Specifies the parameters to recover virtual disks of a vm with full Protection Source. Attributes: power_off_vm_before_recovery (bool): Specifies whether to power off the VM before recovering virtual disks. power_on_vm_af... | the_stack_v2_python_sparse | cohesity_management_sdk/models/virtual_disk_restore_response.py | cohesity/management-sdk-python | train | 24 |
f24ac3e0fdb91b8a4ff34b3af8197c8e2ce210da | [
"total, n = (0, len(nums))\nfor currBit in range(31):\n currOnes = 0\n for num in nums:\n currOnes += num >> currBit & 1\n total += currOnes * (n - currOnes)\nreturn total",
"total = 0\nfor b in zip(*map('{:030b}'.format, nums)):\n zeros = b.count('0')\n total += zeros * (len(b) - zeros)\nre... | <|body_start_0|>
total, n = (0, len(nums))
for currBit in range(31):
currOnes = 0
for num in nums:
currOnes += num >> currBit & 1
total += currOnes * (n - currOnes)
return total
<|end_body_0|>
<|body_start_1|>
total = 0
for b i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def totalHammingDistance(self, nums: List[int]) -> int:
"""According to the question's statement, the numbers in the input list is less than 10^9, which is less than 2^30. So for each bit of the input number, if there are k numbers with that bit as 1 while n - k numbers with th... | stack_v2_sparse_classes_75kplus_train_006098 | 1,729 | no_license | [
{
"docstring": "According to the question's statement, the numbers in the input list is less than 10^9, which is less than 2^30. So for each bit of the input number, if there are k numbers with that bit as 1 while n - k numbers with that bit as 0, then they could form k * (n - k) pairs of difference for that bi... | 2 | stack_v2_sparse_classes_30k_train_047116 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def totalHammingDistance(self, nums: List[int]) -> int: According to the question's statement, the numbers in the input list is less than 10^9, which is less than 2^30. So for ea... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def totalHammingDistance(self, nums: List[int]) -> int: According to the question's statement, the numbers in the input list is less than 10^9, which is less than 2^30. So for ea... | edb870f83f0c4568cce0cacec04ee70cf6b545bf | <|skeleton|>
class Solution:
def totalHammingDistance(self, nums: List[int]) -> int:
"""According to the question's statement, the numbers in the input list is less than 10^9, which is less than 2^30. So for each bit of the input number, if there are k numbers with that bit as 1 while n - k numbers with th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def totalHammingDistance(self, nums: List[int]) -> int:
"""According to the question's statement, the numbers in the input list is less than 10^9, which is less than 2^30. So for each bit of the input number, if there are k numbers with that bit as 1 while n - k numbers with that bit as 0, t... | the_stack_v2_python_sparse | 2020/total_hamming_distance.py | eronekogin/leetcode | train | 0 | |
db764bd8f2b1f941f276c0f489b22c6ea1ff800e | [
"try:\n val = field.data.strip()\n if val:\n float(val)\n return True\nexcept ValueError:\n raise ValidationError('Invalid number provided(only numbers and 1 period allowed)')",
"if not validator_names:\n return field\nfor i in xrange(0, len(validator_names)):\n if validator_names[i] == '... | <|body_start_0|>
try:
val = field.data.strip()
if val:
float(val)
return True
except ValueError:
raise ValidationError('Invalid number provided(only numbers and 1 period allowed)')
<|end_body_0|>
<|body_start_1|>
if not validator_n... | Form to add a new media item | AddMediaForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddMediaForm:
"""Form to add a new media item"""
def isNum(form, field):
"""Check if the field"s value is a number(integer or floating value)"""
<|body_0|>
def removeValidators(self, field, validator_names=None):
"""Remove validator from the field's validator lis... | stack_v2_sparse_classes_75kplus_train_006099 | 4,448 | no_license | [
{
"docstring": "Check if the field\"s value is a number(integer or floating value)",
"name": "isNum",
"signature": "def isNum(form, field)"
},
{
"docstring": "Remove validator from the field's validator list",
"name": "removeValidators",
"signature": "def removeValidators(self, field, va... | 2 | stack_v2_sparse_classes_30k_train_007489 | Implement the Python class `AddMediaForm` described below.
Class description:
Form to add a new media item
Method signatures and docstrings:
- def isNum(form, field): Check if the field"s value is a number(integer or floating value)
- def removeValidators(self, field, validator_names=None): Remove validator from the ... | Implement the Python class `AddMediaForm` described below.
Class description:
Form to add a new media item
Method signatures and docstrings:
- def isNum(form, field): Check if the field"s value is a number(integer or floating value)
- def removeValidators(self, field, validator_names=None): Remove validator from the ... | 320ae68ce21b24dfa5902e8e5b6f4bb0cf1d504e | <|skeleton|>
class AddMediaForm:
"""Form to add a new media item"""
def isNum(form, field):
"""Check if the field"s value is a number(integer or floating value)"""
<|body_0|>
def removeValidators(self, field, validator_names=None):
"""Remove validator from the field's validator lis... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AddMediaForm:
"""Form to add a new media item"""
def isNum(form, field):
"""Check if the field"s value is a number(integer or floating value)"""
try:
val = field.data.strip()
if val:
float(val)
return True
except ValueError:
... | the_stack_v2_python_sparse | mad/modules/media/forms.py | jorluft/fla | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.