blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d11d42c9a3e1496fe1eca2b528d6e6abe0a7889c | [
"print('1.引用,未开辟新的空间,赋值后b受影响')\na = [1, 2, 3]\nb = a\nprint('b: ', b)\na[0] = 4\nprint('b: ', b)",
"print('\\n2.浅复制只为列表的第一层开辟空间,若列表中还有列表则不会开辟空间,有两种浅复制方式')\nprint('浅复制使用a[:]')\na1 = [1, [1]]\nprint('a1: ', a1)\nb1 = a1[:]\na1[0] = 2\na1[1].append(2)\nprint('a1: ', a1)\nprint('b1: ', b1)\nprint('\\n浅复制调用copy')\nimp... | <|body_start_0|>
print('1.引用,未开辟新的空间,赋值后b受影响')
a = [1, 2, 3]
b = a
print('b: ', b)
a[0] = 4
print('b: ', b)
<|end_body_0|>
<|body_start_1|>
print('\n2.浅复制只为列表的第一层开辟空间,若列表中还有列表则不会开辟空间,有两种浅复制方式')
print('浅复制使用a[:]')
a1 = [1, [1]]
print('a1: '... | 要复制数组和列表,则直接使用copy.deepcopy()达到深复制的效果, copy.copy()只对数组有深复制的效果,列表是浅复制。 | copyTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class copyTest:
"""要复制数组和列表,则直接使用copy.deepcopy()达到深复制的效果, copy.copy()只对数组有深复制的效果,列表是浅复制。"""
def test_1(self):
"""对于列表直接赋值相当于引用"""
<|body_0|>
def test_2(self):
"""列表有浅复制和深赋值方式,浅复制有两种方式,深复制使用deepcopy"""
<|body_1|>
def test_3(self):
"""数组和列表一样,有浅复制和深赋... | stack_v2_sparse_classes_36k_train_028100 | 49,813 | no_license | [
{
"docstring": "对于列表直接赋值相当于引用",
"name": "test_1",
"signature": "def test_1(self)"
},
{
"docstring": "列表有浅复制和深赋值方式,浅复制有两种方式,深复制使用deepcopy",
"name": "test_2",
"signature": "def test_2(self)"
},
{
"docstring": "数组和列表一样,有浅复制和深赋值方式,浅复制一种,深复制使用copy,deepcopy",
"name": "test_3",
... | 3 | stack_v2_sparse_classes_30k_train_016127 | Implement the Python class `copyTest` described below.
Class description:
要复制数组和列表,则直接使用copy.deepcopy()达到深复制的效果, copy.copy()只对数组有深复制的效果,列表是浅复制。
Method signatures and docstrings:
- def test_1(self): 对于列表直接赋值相当于引用
- def test_2(self): 列表有浅复制和深赋值方式,浅复制有两种方式,深复制使用deepcopy
- def test_3(self): 数组和列表一样,有浅复制和深赋值方式,浅复制一种,深复制使用... | Implement the Python class `copyTest` described below.
Class description:
要复制数组和列表,则直接使用copy.deepcopy()达到深复制的效果, copy.copy()只对数组有深复制的效果,列表是浅复制。
Method signatures and docstrings:
- def test_1(self): 对于列表直接赋值相当于引用
- def test_2(self): 列表有浅复制和深赋值方式,浅复制有两种方式,深复制使用deepcopy
- def test_3(self): 数组和列表一样,有浅复制和深赋值方式,浅复制一种,深复制使用... | 5c3f7963a494f1a46e9e6a90b4bcd8aea4c9bb55 | <|skeleton|>
class copyTest:
"""要复制数组和列表,则直接使用copy.deepcopy()达到深复制的效果, copy.copy()只对数组有深复制的效果,列表是浅复制。"""
def test_1(self):
"""对于列表直接赋值相当于引用"""
<|body_0|>
def test_2(self):
"""列表有浅复制和深赋值方式,浅复制有两种方式,深复制使用deepcopy"""
<|body_1|>
def test_3(self):
"""数组和列表一样,有浅复制和深赋... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class copyTest:
"""要复制数组和列表,则直接使用copy.deepcopy()达到深复制的效果, copy.copy()只对数组有深复制的效果,列表是浅复制。"""
def test_1(self):
"""对于列表直接赋值相当于引用"""
print('1.引用,未开辟新的空间,赋值后b受影响')
a = [1, 2, 3]
b = a
print('b: ', b)
a[0] = 4
print('b: ', b)
def test_2(self):
"""... | the_stack_v2_python_sparse | common/study_note.py | Aaron20127/Course-Learning | train | 4 |
7f3ea4aeceac9362b57fa35cad570abe55c4032e | [
"assert isinstance(msg, str), 'Invalid message %s' % msg\nself.data = data\nself.messageByType = {}\nself.messages = []\nself.update(msg, *items)\nsuper().__init__()",
"for item in items:\n if isinstance(item, str):\n self.messages.append(item)\n else:\n typ = typeFor(item)\n assert isi... | <|body_start_0|>
assert isinstance(msg, str), 'Invalid message %s' % msg
self.data = data
self.messageByType = {}
self.messages = []
self.update(msg, *items)
super().__init__()
<|end_body_0|>
<|body_start_1|>
for item in items:
if isinstance(item, str... | Exception to be raised when the input is invalid. | InputError | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InputError:
"""Exception to be raised when the input is invalid."""
def __init__(self, msg, *items, **data):
"""Initializes the exception based on the items(s). ex: raise InputError('No idea what is wrong %(reason)s', reason='blame Gabriel') # The message is not associated with any t... | stack_v2_sparse_classes_36k_train_028101 | 5,632 | no_license | [
{
"docstring": "Initializes the exception based on the items(s). ex: raise InputError('No idea what is wrong %(reason)s', reason='blame Gabriel') # The message is not associated with any type. raise InputError('Something wrong with the id', Entity.Id) # The message is associated with the entity id. raise InputE... | 3 | stack_v2_sparse_classes_30k_train_019849 | Implement the Python class `InputError` described below.
Class description:
Exception to be raised when the input is invalid.
Method signatures and docstrings:
- def __init__(self, msg, *items, **data): Initializes the exception based on the items(s). ex: raise InputError('No idea what is wrong %(reason)s', reason='b... | Implement the Python class `InputError` described below.
Class description:
Exception to be raised when the input is invalid.
Method signatures and docstrings:
- def __init__(self, msg, *items, **data): Initializes the exception based on the items(s). ex: raise InputError('No idea what is wrong %(reason)s', reason='b... | e0b3466b34d31548996d57be4a9dac134d904380 | <|skeleton|>
class InputError:
"""Exception to be raised when the input is invalid."""
def __init__(self, msg, *items, **data):
"""Initializes the exception based on the items(s). ex: raise InputError('No idea what is wrong %(reason)s', reason='blame Gabriel') # The message is not associated with any t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InputError:
"""Exception to be raised when the input is invalid."""
def __init__(self, msg, *items, **data):
"""Initializes the exception based on the items(s). ex: raise InputError('No idea what is wrong %(reason)s', reason='blame Gabriel') # The message is not associated with any type. raise In... | the_stack_v2_python_sparse | components/ally-api/ally/api/error.py | cristidomsa/Ally-Py | train | 0 |
5b559883102438a230447a3b8a2ba732529dba47 | [
"try:\n if not isinstance(data['caseProject_id'], int):\n return JsonResponse(code='999996', msg='参数有误!')\n if not data['reportFrom'] or not data['mailUser'] or (not data['mailPass']):\n return JsonResponse(code='999996', msg='参数有误!')\nexcept KeyError:\n return JsonResponse(code='999996', msg... | <|body_start_0|>
try:
if not isinstance(data['caseProject_id'], int):
return JsonResponse(code='999996', msg='参数有误!')
if not data['reportFrom'] or not data['mailUser'] or (not data['mailPass']):
return JsonResponse(code='999996', msg='参数有误!')
excep... | EmailConfig | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailConfig:
def parameter_check(self, data):
"""校验参数 :param data: :return:"""
<|body_0|>
def post(self, request):
"""添加或修改邮件发送配置 :param request: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
if not isinstance(data['caseP... | stack_v2_sparse_classes_36k_train_028102 | 7,584 | no_license | [
{
"docstring": "校验参数 :param data: :return:",
"name": "parameter_check",
"signature": "def parameter_check(self, data)"
},
{
"docstring": "添加或修改邮件发送配置 :param request: :return:",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005122 | Implement the Python class `EmailConfig` described below.
Class description:
Implement the EmailConfig class.
Method signatures and docstrings:
- def parameter_check(self, data): 校验参数 :param data: :return:
- def post(self, request): 添加或修改邮件发送配置 :param request: :return: | Implement the Python class `EmailConfig` described below.
Class description:
Implement the EmailConfig class.
Method signatures and docstrings:
- def parameter_check(self, data): 校验参数 :param data: :return:
- def post(self, request): 添加或修改邮件发送配置 :param request: :return:
<|skeleton|>
class EmailConfig:
def parame... | d65297b71ac9f759d508985ee15564162c285e11 | <|skeleton|>
class EmailConfig:
def parameter_check(self, data):
"""校验参数 :param data: :return:"""
<|body_0|>
def post(self, request):
"""添加或修改邮件发送配置 :param request: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmailConfig:
def parameter_check(self, data):
"""校验参数 :param data: :return:"""
try:
if not isinstance(data['caseProject_id'], int):
return JsonResponse(code='999996', msg='参数有误!')
if not data['reportFrom'] or not data['mailUser'] or (not data['mailPass']... | the_stack_v2_python_sparse | automation-test_new/api_test/case/caseProjectMember.py | beitou/django_api_test | train | 0 | |
a946ca7f99f07949057882b643b859876757b72e | [
"self.logger = logging.getLogger(__name__)\nif name != 'flight' and name != 'pairing':\n raise CrewmlValueError('Valid values are flight or pairing')\nself.name = name\nself.overwrite = overwrite\nself.config = config.ConfigHolder(RESOURCE_DIR + 'pairing_config.ini')\nif year is not None:\n self.year = year\n... | <|body_start_0|>
self.logger = logging.getLogger(__name__)
if name != 'flight' and name != 'pairing':
raise CrewmlValueError('Valid values are flight or pairing')
self.name = name
self.overwrite = overwrite
self.config = config.ConfigHolder(RESOURCE_DIR + 'pairing_con... | Downloader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Downloader:
def __init__(self, name, year=None, month=None, overwrite=False):
"""Create Downloader to download data from S3 E.g. http://crewml.s3.amazonaws.com/flight/v1/2020/2020_dec.zip Parameters ---------- name : str Name of the data to download. It can be either flight or pairing ye... | stack_v2_sparse_classes_36k_train_028103 | 5,663 | permissive | [
{
"docstring": "Create Downloader to download data from S3 E.g. http://crewml.s3.amazonaws.com/flight/v1/2020/2020_dec.zip Parameters ---------- name : str Name of the data to download. It can be either flight or pairing year : number, optional Year of the data to download it can 2018,2019, 2020. If the default... | 2 | stack_v2_sparse_classes_30k_train_006536 | Implement the Python class `Downloader` described below.
Class description:
Implement the Downloader class.
Method signatures and docstrings:
- def __init__(self, name, year=None, month=None, overwrite=False): Create Downloader to download data from S3 E.g. http://crewml.s3.amazonaws.com/flight/v1/2020/2020_dec.zip P... | Implement the Python class `Downloader` described below.
Class description:
Implement the Downloader class.
Method signatures and docstrings:
- def __init__(self, name, year=None, month=None, overwrite=False): Create Downloader to download data from S3 E.g. http://crewml.s3.amazonaws.com/flight/v1/2020/2020_dec.zip P... | 4c4ab636309a88f59789b46079b7af109521b6a6 | <|skeleton|>
class Downloader:
def __init__(self, name, year=None, month=None, overwrite=False):
"""Create Downloader to download data from S3 E.g. http://crewml.s3.amazonaws.com/flight/v1/2020/2020_dec.zip Parameters ---------- name : str Name of the data to download. It can be either flight or pairing ye... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Downloader:
def __init__(self, name, year=None, month=None, overwrite=False):
"""Create Downloader to download data from S3 E.g. http://crewml.s3.amazonaws.com/flight/v1/2020/2020_dec.zip Parameters ---------- name : str Name of the data to download. It can be either flight or pairing year : number, o... | the_stack_v2_python_sparse | data/download.py | crewml/crewml | train | 12 | |
0d411c68430f9511fd84dada4894e10d7d5da108 | [
"super(LMC, self).__init__()\nself.encoder = LMCEncoder(token_vocab_size, metadata_vocab_size)\nself.decoder = LMCDecoder(token_vocab_size, metadata_vocab_size)",
"ids_tiled = ids.unsqueeze(-1).repeat(1, 1, metadata_ids.size()[-1])\nmu_marginal, sigma_marginal = self.decoder(ids_tiled, metadata_ids)\nreturn (mu_m... | <|body_start_0|>
super(LMC, self).__init__()
self.encoder = LMCEncoder(token_vocab_size, metadata_vocab_size)
self.decoder = LMCDecoder(token_vocab_size, metadata_vocab_size)
<|end_body_0|>
<|body_start_1|>
ids_tiled = ids.unsqueeze(-1).repeat(1, 1, metadata_ids.size()[-1])
mu_m... | LMC | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LMC:
def __init__(self, args, token_vocab_size, metadata_vocab_size):
"""Standard model as detailed in LMC paper"""
<|body_0|>
def _compute_marginal(self, ids, metadata_ids):
""":param ids: batch_size x 2 * context_window :param metadata_ids: batch_size x 2 * context... | stack_v2_sparse_classes_36k_train_028104 | 8,870 | no_license | [
{
"docstring": "Standard model as detailed in LMC paper",
"name": "__init__",
"signature": "def __init__(self, args, token_vocab_size, metadata_vocab_size)"
},
{
"docstring": ":param ids: batch_size x 2 * context_window :param metadata_ids: batch_size x 2 * context_window x metadata_samples :ret... | 3 | stack_v2_sparse_classes_30k_train_005678 | Implement the Python class `LMC` described below.
Class description:
Implement the LMC class.
Method signatures and docstrings:
- def __init__(self, args, token_vocab_size, metadata_vocab_size): Standard model as detailed in LMC paper
- def _compute_marginal(self, ids, metadata_ids): :param ids: batch_size x 2 * cont... | Implement the Python class `LMC` described below.
Class description:
Implement the LMC class.
Method signatures and docstrings:
- def __init__(self, args, token_vocab_size, metadata_vocab_size): Standard model as detailed in LMC paper
- def _compute_marginal(self, ids, metadata_ids): :param ids: batch_size x 2 * cont... | f07dfa472d3f6bfd7ce7f7ac7168687beb8efdaf | <|skeleton|>
class LMC:
def __init__(self, args, token_vocab_size, metadata_vocab_size):
"""Standard model as detailed in LMC paper"""
<|body_0|>
def _compute_marginal(self, ids, metadata_ids):
""":param ids: batch_size x 2 * context_window :param metadata_ids: batch_size x 2 * context... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LMC:
def __init__(self, args, token_vocab_size, metadata_vocab_size):
"""Standard model as detailed in LMC paper"""
super(LMC, self).__init__()
self.encoder = LMCEncoder(token_vocab_size, metadata_vocab_size)
self.decoder = LMCDecoder(token_vocab_size, metadata_vocab_size)
... | the_stack_v2_python_sparse | modules/lmc/lmc_model.py | griff4692/LMC | train | 13 | |
fd370e017757197189a3d98a241114b6c8ffc0c0 | [
"super(Actor, self).__init__()\nself.state_size = state_size\nself.action_size = action_size\nself.linear1 = nn.Linear(self.state_size, 128)\nself.linear2 = nn.Linear(128, 256)\nself.linear3 = nn.Linear(256, self.action_size)\nself.relu = nn.ReLU()\nself.tanh = nn.Tanh()\nself.weight_init()",
"output = self.relu(... | <|body_start_0|>
super(Actor, self).__init__()
self.state_size = state_size
self.action_size = action_size
self.linear1 = nn.Linear(self.state_size, 128)
self.linear2 = nn.Linear(128, 256)
self.linear3 = nn.Linear(256, self.action_size)
self.relu = nn.ReLU()
... | Actor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Actor:
def __init__(self, state_size, action_size):
"""init function Args: - state_size: int - action_size: int"""
<|body_0|>
def forward(self, state):
"""forward function Args: - state: torch.FloatTensor, shape==[batch_size, state_size]"""
<|body_1|>
de... | stack_v2_sparse_classes_36k_train_028105 | 2,778 | no_license | [
{
"docstring": "init function Args: - state_size: int - action_size: int",
"name": "__init__",
"signature": "def __init__(self, state_size, action_size)"
},
{
"docstring": "forward function Args: - state: torch.FloatTensor, shape==[batch_size, state_size]",
"name": "forward",
"signature"... | 3 | stack_v2_sparse_classes_30k_train_004230 | Implement the Python class `Actor` described below.
Class description:
Implement the Actor class.
Method signatures and docstrings:
- def __init__(self, state_size, action_size): init function Args: - state_size: int - action_size: int
- def forward(self, state): forward function Args: - state: torch.FloatTensor, sha... | Implement the Python class `Actor` described below.
Class description:
Implement the Actor class.
Method signatures and docstrings:
- def __init__(self, state_size, action_size): init function Args: - state_size: int - action_size: int
- def forward(self, state): forward function Args: - state: torch.FloatTensor, sha... | 2c622764bc1197e0ec5b1b3c30a9d12611b25738 | <|skeleton|>
class Actor:
def __init__(self, state_size, action_size):
"""init function Args: - state_size: int - action_size: int"""
<|body_0|>
def forward(self, state):
"""forward function Args: - state: torch.FloatTensor, shape==[batch_size, state_size]"""
<|body_1|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Actor:
def __init__(self, state_size, action_size):
"""init function Args: - state_size: int - action_size: int"""
super(Actor, self).__init__()
self.state_size = state_size
self.action_size = action_size
self.linear1 = nn.Linear(self.state_size, 128)
self.linea... | the_stack_v2_python_sparse | DDPG/model.py | keiiti975/RL_sample | train | 0 | |
25b4d4fbd168b1c0a1638d3ac1e58a4dc86d4917 | [
"from github.objects import CommitComment\ndata = self.http.fetch_commentable_comments(self.id)\nif data[0]['__typename'] == 'CommitComment':\n return CommitComment.from_data(data, self.http)\nelif data[0]['__typename'] == 'GistComment':\n return GistComment.from_data(data, self.http)\nelif data[0]['__typenam... | <|body_start_0|>
from github.objects import CommitComment
data = self.http.fetch_commentable_comments(self.id)
if data[0]['__typename'] == 'CommitComment':
return CommitComment.from_data(data, self.http)
elif data[0]['__typename'] == 'GistComment':
return GistComm... | Represents an object which can be commented on. Implemented by: * :class:`github.Issue` * :class:`github.PullRequest` | Commentable | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Commentable:
"""Represents an object which can be commented on. Implemented by: * :class:`github.Issue` * :class:`github.PullRequest`"""
def fetch_comments(self):
"""|coro| Fetches a list of comments on the commentable. Raises ------ ~github.errors.GitHubError An arbitrary GitHub-rel... | stack_v2_sparse_classes_36k_train_028106 | 4,370 | no_license | [
{
"docstring": "|coro| Fetches a list of comments on the commentable. Raises ------ ~github.errors.GitHubError An arbitrary GitHub-related error occurred. ~github.errors.HTTPException An arbitrary HTTP-related error occurred. ~github.errors.Internal A ``\"INTERNAL\"`` status-message was returned. ~github.errors... | 2 | stack_v2_sparse_classes_30k_train_015823 | Implement the Python class `Commentable` described below.
Class description:
Represents an object which can be commented on. Implemented by: * :class:`github.Issue` * :class:`github.PullRequest`
Method signatures and docstrings:
- def fetch_comments(self): |coro| Fetches a list of comments on the commentable. Raises ... | Implement the Python class `Commentable` described below.
Class description:
Represents an object which can be commented on. Implemented by: * :class:`github.Issue` * :class:`github.PullRequest`
Method signatures and docstrings:
- def fetch_comments(self): |coro| Fetches a list of comments on the commentable. Raises ... | 881c2772038ddf99f6b422987659501f10f23544 | <|skeleton|>
class Commentable:
"""Represents an object which can be commented on. Implemented by: * :class:`github.Issue` * :class:`github.PullRequest`"""
def fetch_comments(self):
"""|coro| Fetches a list of comments on the commentable. Raises ------ ~github.errors.GitHubError An arbitrary GitHub-rel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Commentable:
"""Represents an object which can be commented on. Implemented by: * :class:`github.Issue` * :class:`github.PullRequest`"""
def fetch_comments(self):
"""|coro| Fetches a list of comments on the commentable. Raises ------ ~github.errors.GitHubError An arbitrary GitHub-related error oc... | the_stack_v2_python_sparse | github/abc/commentable.py | mehdigolzadeh/Apiv4Downloader | train | 0 |
5c237e96143fec9cb11546b8f659c29bff903abc | [
"super().__init__(seed, max_outputs=max_outputs)\nself.glove = torchtext.vocab.GloVe(name='6B', dim='100')\nself.nlp = spacy_nlp if spacy_nlp else spacy.load('en_core_web_sm')\nself.max_outputs = max_outputs\nself.n_similar = n_similar",
"outputs = []\ncandidate_alignments = self.get_alignments(meaning_representa... | <|body_start_0|>
super().__init__(seed, max_outputs=max_outputs)
self.glove = torchtext.vocab.GloVe(name='6B', dim='100')
self.nlp = spacy_nlp if spacy_nlp else spacy.load('en_core_web_sm')
self.max_outputs = max_outputs
self.n_similar = n_similar
<|end_body_0|>
<|body_start_1|>... | MRValueReplacement | [
"MIT",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MRValueReplacement:
def __init__(self, seed=0, n_similar=10, max_outputs=1):
"""Method for initializing tools and setting variables."""
<|body_0|>
def generate(self, meaning_representation: dict, reference: str):
"""Method for generating variatios of the MR/utterance... | stack_v2_sparse_classes_36k_train_028107 | 3,530 | permissive | [
{
"docstring": "Method for initializing tools and setting variables.",
"name": "__init__",
"signature": "def __init__(self, seed=0, n_similar=10, max_outputs=1)"
},
{
"docstring": "Method for generating variatios of the MR/utterances.",
"name": "generate",
"signature": "def generate(self... | 5 | stack_v2_sparse_classes_30k_val_000169 | Implement the Python class `MRValueReplacement` described below.
Class description:
Implement the MRValueReplacement class.
Method signatures and docstrings:
- def __init__(self, seed=0, n_similar=10, max_outputs=1): Method for initializing tools and setting variables.
- def generate(self, meaning_representation: dic... | Implement the Python class `MRValueReplacement` described below.
Class description:
Implement the MRValueReplacement class.
Method signatures and docstrings:
- def __init__(self, seed=0, n_similar=10, max_outputs=1): Method for initializing tools and setting variables.
- def generate(self, meaning_representation: dic... | 619bc081fa506778526a1963d19a697367f1d553 | <|skeleton|>
class MRValueReplacement:
def __init__(self, seed=0, n_similar=10, max_outputs=1):
"""Method for initializing tools and setting variables."""
<|body_0|>
def generate(self, meaning_representation: dict, reference: str):
"""Method for generating variatios of the MR/utterance... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MRValueReplacement:
def __init__(self, seed=0, n_similar=10, max_outputs=1):
"""Method for initializing tools and setting variables."""
super().__init__(seed, max_outputs=max_outputs)
self.glove = torchtext.vocab.GloVe(name='6B', dim='100')
self.nlp = spacy_nlp if spacy_nlp els... | the_stack_v2_python_sparse | transformations/mr_value_replacement/transformation.py | dyrson11/NL-Augmenter | train | 1 | |
cfe009a515ead2d3b387dc33c7b89af56154d903 | [
"default = dict(_type='file')\nattr = Upload._attributes(field, default, **attributes)\ninp = DIV(DIV(INPUT(**attr), _id='uploadinput'), BR(), DIV(_id='photopicture'))\nif download_url and value:\n if callable(download_url):\n url = download_url(value)\n else:\n url = download_url + '/' + value\... | <|body_start_0|>
default = dict(_type='file')
attr = Upload._attributes(field, default, **attributes)
inp = DIV(DIV(INPUT(**attr), _id='uploadinput'), BR(), DIV(_id='photopicture'))
if download_url and value:
if callable(download_url):
url = download_url(value... | Upload | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Upload:
def widget(field, value, download_url=None, show=False, **attributes):
"""generates a INPUT file tag. Optionally provides an A link to the file, including a checkbox so the file can be deleted. All is wrapped in a DIV. see also: :meth:`FormWidget.widget` :param download_url: Opti... | stack_v2_sparse_classes_36k_train_028108 | 7,084 | no_license | [
{
"docstring": "generates a INPUT file tag. Optionally provides an A link to the file, including a checkbox so the file can be deleted. All is wrapped in a DIV. see also: :meth:`FormWidget.widget` :param download_url: Optional URL to link to the file (default = None)",
"name": "widget",
"signature": "de... | 3 | stack_v2_sparse_classes_30k_train_002824 | Implement the Python class `Upload` described below.
Class description:
Implement the Upload class.
Method signatures and docstrings:
- def widget(field, value, download_url=None, show=False, **attributes): generates a INPUT file tag. Optionally provides an A link to the file, including a checkbox so the file can be ... | Implement the Python class `Upload` described below.
Class description:
Implement the Upload class.
Method signatures and docstrings:
- def widget(field, value, download_url=None, show=False, **attributes): generates a INPUT file tag. Optionally provides an A link to the file, including a checkbox so the file can be ... | 033be58e5e6d37052b321acc01ad4a42bfcfff04 | <|skeleton|>
class Upload:
def widget(field, value, download_url=None, show=False, **attributes):
"""generates a INPUT file tag. Optionally provides an A link to the file, including a checkbox so the file can be deleted. All is wrapped in a DIV. see also: :meth:`FormWidget.widget` :param download_url: Opti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Upload:
def widget(field, value, download_url=None, show=False, **attributes):
"""generates a INPUT file tag. Optionally provides an A link to the file, including a checkbox so the file can be deleted. All is wrapped in a DIV. see also: :meth:`FormWidget.widget` :param download_url: Optional URL to li... | the_stack_v2_python_sparse | modules/helpers/widgets.py | goldenboy/Movuca | train | 0 | |
ee2a500d2de82fe9593a8b3981d4df780c8f9f01 | [
"self.backup_source_inode_id = backup_source_inode_id\nself.mtime_usecs = mtime_usecs\nself.size = size\nself.mtype = mtype",
"if dictionary is None:\n return None\nbackup_source_inode_id = dictionary.get('backupSourceInodeId')\nmtime_usecs = dictionary.get('mtimeUsecs')\nsize = dictionary.get('size')\nmtype =... | <|body_start_0|>
self.backup_source_inode_id = backup_source_inode_id
self.mtime_usecs = mtime_usecs
self.size = size
self.mtype = mtype
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
backup_source_inode_id = dictionary.get('backupSourceIn... | Implementation of the 'FileStatInfo' model. TODO: type description here. Attributes: backup_source_inode_id (long|int): Source inode id metadata for certain adapters e.g. Netapp. mtime_usecs (long|int): If this is a file, the mtime as returned by stat. size (long|int): If this is a file, the size of the file as returne... | FileStatInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileStatInfo:
"""Implementation of the 'FileStatInfo' model. TODO: type description here. Attributes: backup_source_inode_id (long|int): Source inode id metadata for certain adapters e.g. Netapp. mtime_usecs (long|int): If this is a file, the mtime as returned by stat. size (long|int): If this is... | stack_v2_sparse_classes_36k_train_028109 | 2,281 | permissive | [
{
"docstring": "Constructor for the FileStatInfo class",
"name": "__init__",
"signature": "def __init__(self, backup_source_inode_id=None, mtime_usecs=None, size=None, mtype=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary ... | 2 | null | Implement the Python class `FileStatInfo` described below.
Class description:
Implementation of the 'FileStatInfo' model. TODO: type description here. Attributes: backup_source_inode_id (long|int): Source inode id metadata for certain adapters e.g. Netapp. mtime_usecs (long|int): If this is a file, the mtime as return... | Implement the Python class `FileStatInfo` described below.
Class description:
Implementation of the 'FileStatInfo' model. TODO: type description here. Attributes: backup_source_inode_id (long|int): Source inode id metadata for certain adapters e.g. Netapp. mtime_usecs (long|int): If this is a file, the mtime as return... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class FileStatInfo:
"""Implementation of the 'FileStatInfo' model. TODO: type description here. Attributes: backup_source_inode_id (long|int): Source inode id metadata for certain adapters e.g. Netapp. mtime_usecs (long|int): If this is a file, the mtime as returned by stat. size (long|int): If this is... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileStatInfo:
"""Implementation of the 'FileStatInfo' model. TODO: type description here. Attributes: backup_source_inode_id (long|int): Source inode id metadata for certain adapters e.g. Netapp. mtime_usecs (long|int): If this is a file, the mtime as returned by stat. size (long|int): If this is a file, the ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/file_stat_info.py | cohesity/management-sdk-python | train | 24 |
f9ea0658341aabb480b555096d54cb553b5b0fcf | [
"self.start_all_services()\nclient = self.get_client('deproxy')\nmax_streams = 128\nfor _ in range(max_streams):\n client.make_request(request=self.post_request, end_stream=False)\n client.stream_id += 2\nclient.make_request(request=self.post_request, end_stream=True)\nclient.wait_for_response(1)\nself.assert... | <|body_start_0|>
self.start_all_services()
client = self.get_client('deproxy')
max_streams = 128
for _ in range(max_streams):
client.make_request(request=self.post_request, end_stream=False)
client.stream_id += 2
client.make_request(request=self.post_reque... | TestH2Stream | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestH2Stream:
def test_max_concurrent_stream(self):
"""An endpoint that receives a HEADERS frame that causes its advertised concurrent stream limit to be exceeded MUST treat this as a stream error of type PROTOCOL_ERROR or REFUSED_STREAM. RFC 9113 5.1.2"""
<|body_0|>
def tes... | stack_v2_sparse_classes_36k_train_028110 | 9,019 | no_license | [
{
"docstring": "An endpoint that receives a HEADERS frame that causes its advertised concurrent stream limit to be exceeded MUST treat this as a stream error of type PROTOCOL_ERROR or REFUSED_STREAM. RFC 9113 5.1.2",
"name": "test_max_concurrent_stream",
"signature": "def test_max_concurrent_stream(self... | 5 | null | Implement the Python class `TestH2Stream` described below.
Class description:
Implement the TestH2Stream class.
Method signatures and docstrings:
- def test_max_concurrent_stream(self): An endpoint that receives a HEADERS frame that causes its advertised concurrent stream limit to be exceeded MUST treat this as a str... | Implement the Python class `TestH2Stream` described below.
Class description:
Implement the TestH2Stream class.
Method signatures and docstrings:
- def test_max_concurrent_stream(self): An endpoint that receives a HEADERS frame that causes its advertised concurrent stream limit to be exceeded MUST treat this as a str... | d56358ea653dbb367624937197ce5e489abf0b00 | <|skeleton|>
class TestH2Stream:
def test_max_concurrent_stream(self):
"""An endpoint that receives a HEADERS frame that causes its advertised concurrent stream limit to be exceeded MUST treat this as a stream error of type PROTOCOL_ERROR or REFUSED_STREAM. RFC 9113 5.1.2"""
<|body_0|>
def tes... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestH2Stream:
def test_max_concurrent_stream(self):
"""An endpoint that receives a HEADERS frame that causes its advertised concurrent stream limit to be exceeded MUST treat this as a stream error of type PROTOCOL_ERROR or REFUSED_STREAM. RFC 9113 5.1.2"""
self.start_all_services()
cli... | the_stack_v2_python_sparse | http2_general/test_h2_streams.py | tempesta-tech/tempesta-test | train | 13 | |
e96660cb3378dd4cc6e0dae6ceffa1dcdc064953 | [
"object.__init__(self)\nself.name = name\nself.decls = decls",
"for d in self.decls:\n callable_ = getattr(d, self.name)\n callable_(*arguments, **keywords)"
] | <|body_start_0|>
object.__init__(self)
self.name = name
self.decls = decls
<|end_body_0|>
<|body_start_1|>
for d in self.decls:
callable_ = getattr(d, self.name)
callable_(*arguments, **keywords)
<|end_body_1|>
| Internal class used to call some function of objects | call_redirector_t | [
"IJG",
"Zlib",
"LicenseRef-scancode-proprietary-license",
"SMLNJ",
"BSD-3-Clause",
"BSD-4.3TAHOE",
"LicenseRef-scancode-free-unknown",
"Spencer-86",
"LicenseRef-scancode-llnl",
"FSFUL",
"Libpng",
"libtiff",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-permissive",
... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class call_redirector_t:
"""Internal class used to call some function of objects"""
def __init__(self, name, decls):
"""creates call_redirector_t instance. :param name: name of method, to be called on every object in the `decls` list :param decls: list of objects"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_028111 | 3,174 | permissive | [
{
"docstring": "creates call_redirector_t instance. :param name: name of method, to be called on every object in the `decls` list :param decls: list of objects",
"name": "__init__",
"signature": "def __init__(self, name, decls)"
},
{
"docstring": "calls method :attr:`call_redirector_t.name` on e... | 2 | stack_v2_sparse_classes_30k_train_009255 | Implement the Python class `call_redirector_t` described below.
Class description:
Internal class used to call some function of objects
Method signatures and docstrings:
- def __init__(self, name, decls): creates call_redirector_t instance. :param name: name of method, to be called on every object in the `decls` list... | Implement the Python class `call_redirector_t` described below.
Class description:
Internal class used to call some function of objects
Method signatures and docstrings:
- def __init__(self, name, decls): creates call_redirector_t instance. :param name: name of method, to be called on every object in the `decls` list... | 3eb8fd7cdfbc5ac2d0c2e5e776848a4cbab3d7e1 | <|skeleton|>
class call_redirector_t:
"""Internal class used to call some function of objects"""
def __init__(self, name, decls):
"""creates call_redirector_t instance. :param name: name of method, to be called on every object in the `decls` list :param decls: list of objects"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class call_redirector_t:
"""Internal class used to call some function of objects"""
def __init__(self, name, decls):
"""creates call_redirector_t instance. :param name: name of method, to be called on every object in the `decls` list :param decls: list of objects"""
object.__init__(self)
... | the_stack_v2_python_sparse | Modules/ThirdParty/pygccxml/src/pygccxml/declarations/mdecl_wrapper.py | InsightSoftwareConsortium/ITK | train | 1,229 |
bdd99fd7e3a4a0d0b08fa34e9bc9b7959c6b08b1 | [
"Thread.__init__(self)\nself.name = name\nself.count = count",
"try:\n lock.acquire()\n logging.debug('lock...')\n countdown(self.count)\nfinally:\n lock.release()\n logging.debug('open again')"
] | <|body_start_0|>
Thread.__init__(self)
self.name = name
self.count = count
<|end_body_0|>
<|body_start_1|>
try:
lock.acquire()
logging.debug('lock...')
countdown(self.count)
finally:
lock.release()
logging.debug('open a... | MyThread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyThread:
def __init__(self, name, count):
"""初始化,继承Thread"""
<|body_0|>
def run(self):
"""启动线程"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Thread.__init__(self)
self.name = name
self.count = count
<|end_body_0|>
<|body_start_1|... | stack_v2_sparse_classes_36k_train_028112 | 2,064 | no_license | [
{
"docstring": "初始化,继承Thread",
"name": "__init__",
"signature": "def __init__(self, name, count)"
},
{
"docstring": "启动线程",
"name": "run",
"signature": "def run(self)"
}
] | 2 | null | Implement the Python class `MyThread` described below.
Class description:
Implement the MyThread class.
Method signatures and docstrings:
- def __init__(self, name, count): 初始化,继承Thread
- def run(self): 启动线程 | Implement the Python class `MyThread` described below.
Class description:
Implement the MyThread class.
Method signatures and docstrings:
- def __init__(self, name, count): 初始化,继承Thread
- def run(self): 启动线程
<|skeleton|>
class MyThread:
def __init__(self, name, count):
"""初始化,继承Thread"""
<|body_... | 173f3a5fa24176df4c53bd36771cc733a1221dfd | <|skeleton|>
class MyThread:
def __init__(self, name, count):
"""初始化,继承Thread"""
<|body_0|>
def run(self):
"""启动线程"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyThread:
def __init__(self, name, count):
"""初始化,继承Thread"""
Thread.__init__(self)
self.name = name
self.count = count
def run(self):
"""启动线程"""
try:
lock.acquire()
logging.debug('lock...')
countdown(self.count)
... | the_stack_v2_python_sparse | async_demo/pratice/thread_lock.py | Joker2018goon/myGitRepo | train | 1 | |
b94392c9c6547415326d80ff0923cb8ba9251783 | [
"encoded_str = ''\nfor s in strs:\n encoded_str += '%0*x' % (8, len(s)) + s\nreturn encoded_str",
"i = 0\nstrs = []\nwhile i < len(s):\n l = int(s[i:i + 8], 16)\n strs.append(s[i + 8:i + 8 + l])\n i += 8 + l\nreturn strs"
] | <|body_start_0|>
encoded_str = ''
for s in strs:
encoded_str += '%0*x' % (8, len(s)) + s
return encoded_str
<|end_body_0|>
<|body_start_1|>
i = 0
strs = []
while i < len(s):
l = int(s[i:i + 8], 16)
strs.append(s[i + 8:i + 8 + l])
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_028113 | 2,992 | no_license | [
{
"docstring": "Encodes a list of strings to a single string. :type strs: List[str] :rtype: str",
"name": "encode",
"signature": "def encode(self, strs)"
},
{
"docstring": "Decodes a single string to a list of strings. :type s: str :rtype: List[str]",
"name": "decode",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_020376 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | 05e8f5a4e39d448eb333c813093fc7c1df4fc05e | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
encoded_str = ''
for s in strs:
encoded_str += '%0*x' % (8, len(s)) + s
return encoded_str
def decode(self, s):
"""Decodes a single stri... | the_stack_v2_python_sparse | leetcode_python/String/encode-and-decode-strings.py | DataEngDev/CS_basics | train | 0 | |
986b05d437abe965c336a7ca1882dd1778678695 | [
"board = boards_api.get(board_id)\nif boards_api.visible(board, request.current_user_id):\n return boards_api.get_permissions(board, request.current_user_id)\nelse:\n raise exc.NotFound(_('Board %s not found') % board_id)",
"if boards_api.editable(boards_api.get(board_id), request.current_user_id):\n ret... | <|body_start_0|>
board = boards_api.get(board_id)
if boards_api.visible(board, request.current_user_id):
return boards_api.get_permissions(board, request.current_user_id)
else:
raise exc.NotFound(_('Board %s not found') % board_id)
<|end_body_0|>
<|body_start_1|>
... | Manages operations on board permissions. | PermissionsController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PermissionsController:
"""Manages operations on board permissions."""
def get(self, board_id):
"""Get board permissions for the current user. :param board_id: The ID of the board."""
<|body_0|>
def post(self, board_id, permission):
"""Add a new permission to the ... | stack_v2_sparse_classes_36k_train_028114 | 11,356 | permissive | [
{
"docstring": "Get board permissions for the current user. :param board_id: The ID of the board.",
"name": "get",
"signature": "def get(self, board_id)"
},
{
"docstring": "Add a new permission to the board. :param board_id: The ID of the board. :param permission: The dict to use to create the p... | 3 | stack_v2_sparse_classes_30k_train_005309 | Implement the Python class `PermissionsController` described below.
Class description:
Manages operations on board permissions.
Method signatures and docstrings:
- def get(self, board_id): Get board permissions for the current user. :param board_id: The ID of the board.
- def post(self, board_id, permission): Add a n... | Implement the Python class `PermissionsController` described below.
Class description:
Manages operations on board permissions.
Method signatures and docstrings:
- def get(self, board_id): Get board permissions for the current user. :param board_id: The ID of the board.
- def post(self, board_id, permission): Add a n... | 2445e3dc904c7c83305a4a6274e6ae35dacb0cfa | <|skeleton|>
class PermissionsController:
"""Manages operations on board permissions."""
def get(self, board_id):
"""Get board permissions for the current user. :param board_id: The ID of the board."""
<|body_0|>
def post(self, board_id, permission):
"""Add a new permission to the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PermissionsController:
"""Manages operations on board permissions."""
def get(self, board_id):
"""Get board permissions for the current user. :param board_id: The ID of the board."""
board = boards_api.get(board_id)
if boards_api.visible(board, request.current_user_id):
... | the_stack_v2_python_sparse | storyboard/api/v1/boards.py | yeweiasia/storyboard | train | 0 |
9ed4321daf6a158fa763ba3eacb0ec39dad82448 | [
"from wejudge.core import WeJudgeResponse\nself._request = request\nself._response = response\nif isinstance(response, WeJudgeResponse):\n self.session = response.session\nelse:\n self.session = None",
"from wejudge.core.error import WeJudgeError\n\ndef wrapper(*args, **kwargs):\n self = args[0]\n sel... | <|body_start_0|>
from wejudge.core import WeJudgeResponse
self._request = request
self._response = response
if isinstance(response, WeJudgeResponse):
self.session = response.session
else:
self.session = None
<|end_body_0|>
<|body_start_1|>
from we... | WeJudgeControllerBase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WeJudgeControllerBase:
def __init__(self, request, response):
"""初始化 :param request: django request 对象 :param response: WeJudge response 对象"""
<|body_0|>
def login_validator(func):
"""登录检查器(装饰器) :return:"""
<|body_1|>
def login_check(self, throw=True):
... | stack_v2_sparse_classes_36k_train_028115 | 1,401 | no_license | [
{
"docstring": "初始化 :param request: django request 对象 :param response: WeJudge response 对象",
"name": "__init__",
"signature": "def __init__(self, request, response)"
},
{
"docstring": "登录检查器(装饰器) :return:",
"name": "login_validator",
"signature": "def login_validator(func)"
},
{
... | 3 | null | Implement the Python class `WeJudgeControllerBase` described below.
Class description:
Implement the WeJudgeControllerBase class.
Method signatures and docstrings:
- def __init__(self, request, response): 初始化 :param request: django request 对象 :param response: WeJudge response 对象
- def login_validator(func): 登录检查器(装饰器... | Implement the Python class `WeJudgeControllerBase` described below.
Class description:
Implement the WeJudgeControllerBase class.
Method signatures and docstrings:
- def __init__(self, request, response): 初始化 :param request: django request 对象 :param response: WeJudge response 对象
- def login_validator(func): 登录检查器(装饰器... | ded211428adc9506e7a7b9bbaa5d38c4b5c798d8 | <|skeleton|>
class WeJudgeControllerBase:
def __init__(self, request, response):
"""初始化 :param request: django request 对象 :param response: WeJudge response 对象"""
<|body_0|>
def login_validator(func):
"""登录检查器(装饰器) :return:"""
<|body_1|>
def login_check(self, throw=True):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WeJudgeControllerBase:
def __init__(self, request, response):
"""初始化 :param request: django request 对象 :param response: WeJudge response 对象"""
from wejudge.core import WeJudgeResponse
self._request = request
self._response = response
if isinstance(response, WeJudgeRespo... | the_stack_v2_python_sparse | server/wejudge/utils/controller_base.py | DICKQI/WeJudge-2-Dev | train | 0 | |
3e6b8fa9e3ab4b16ac0a8f3adf109cbe3fd351e1 | [
"binary = int(a)\nresult = 0\nbase = 1\nwhile binary:\n result += base * (binary % 10)\n base *= 2\n binary /= 10\nreturn result",
"result = self.binary_to_int(a) + self.binary_to_int(b)\nresult = bin(result)[2:]\nreturn result"
] | <|body_start_0|>
binary = int(a)
result = 0
base = 1
while binary:
result += base * (binary % 10)
base *= 2
binary /= 10
return result
<|end_body_0|>
<|body_start_1|>
result = self.binary_to_int(a) + self.binary_to_int(b)
resul... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def binary_to_int(self, a):
""">>> s = Solution() >>> s.binary_to_int("1") 1 >>> s.binary_to_int("111") 7 >>> s.binary_to_int("0") 0 >>> s.binary_to_int("100") 4 >>> s.binary_to_int("110010") 50 >>> s.binary_to_int("110") 6"""
<|body_0|>
def addBinary(self, a, b):
... | stack_v2_sparse_classes_36k_train_028116 | 1,250 | no_license | [
{
"docstring": ">>> s = Solution() >>> s.binary_to_int(\"1\") 1 >>> s.binary_to_int(\"111\") 7 >>> s.binary_to_int(\"0\") 0 >>> s.binary_to_int(\"100\") 4 >>> s.binary_to_int(\"110010\") 50 >>> s.binary_to_int(\"110\") 6",
"name": "binary_to_int",
"signature": "def binary_to_int(self, a)"
},
{
"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def binary_to_int(self, a): >>> s = Solution() >>> s.binary_to_int("1") 1 >>> s.binary_to_int("111") 7 >>> s.binary_to_int("0") 0 >>> s.binary_to_int("100") 4 >>> s.binary_to_int... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def binary_to_int(self, a): >>> s = Solution() >>> s.binary_to_int("1") 1 >>> s.binary_to_int("111") 7 >>> s.binary_to_int("0") 0 >>> s.binary_to_int("100") 4 >>> s.binary_to_int... | 3b13a02f9c8273f9794a57b948d2655792707f37 | <|skeleton|>
class Solution:
def binary_to_int(self, a):
""">>> s = Solution() >>> s.binary_to_int("1") 1 >>> s.binary_to_int("111") 7 >>> s.binary_to_int("0") 0 >>> s.binary_to_int("100") 4 >>> s.binary_to_int("110010") 50 >>> s.binary_to_int("110") 6"""
<|body_0|>
def addBinary(self, a, b):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def binary_to_int(self, a):
""">>> s = Solution() >>> s.binary_to_int("1") 1 >>> s.binary_to_int("111") 7 >>> s.binary_to_int("0") 0 >>> s.binary_to_int("100") 4 >>> s.binary_to_int("110010") 50 >>> s.binary_to_int("110") 6"""
binary = int(a)
result = 0
base = 1
... | the_stack_v2_python_sparse | add_string.py | gsy/leetcode | train | 1 | |
6a017a38ccaf36d39fc34f09adf897d7efa3215c | [
"solutions = []\nnums.sort()\nlength = len(nums)\nlist1 = [-x for x in nums]\nfor sum_id in range(length):\n dict = {}\n temp_num = nums[:]\n temp_num.pop(-(length - sum_id))\n for i in temp_num:\n if list1[sum_id] - i not in dict:\n dict[i] = i\n else:\n temp_sol = s... | <|body_start_0|>
solutions = []
nums.sort()
length = len(nums)
list1 = [-x for x in nums]
for sum_id in range(length):
dict = {}
temp_num = nums[:]
temp_num.pop(-(length - sum_id))
for i in temp_num:
if list1[sum_id]... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def threeSum2(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
solutions = []
num... | stack_v2_sparse_classes_36k_train_028117 | 1,992 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum",
"signature": "def threeSum(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum2",
"signature": "def threeSum2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015477 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def threeSum2(self, nums): :type nums: List[int] :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def threeSum2(self, nums): :type nums: List[int] :rtype: List[List[int]]
<|skeleton|>
class Solution:
... | 391328c7c601b5c77ff250ad173600d4d1dd7f57 | <|skeleton|>
class Solution:
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def threeSum2(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
solutions = []
nums.sort()
length = len(nums)
list1 = [-x for x in nums]
for sum_id in range(length):
dict = {}
temp_num = nums[:]
temp_nu... | the_stack_v2_python_sparse | leetcode/algo/p15_3Sum.py | wduncan21/Challenges | train | 0 | |
62365f19643efe42a56f89284e85bebf96032cdf | [
"ds = super(FeatureColumns, self).build_dataset(*args, **kwargs)\nds.__class__ = Dataset\nreturn ds",
"ds = super(FeatureColumns, self).build_dataset_from_stdin(*args, **kwargs)\nds.__class__ = Dataset\nreturn ds"
] | <|body_start_0|>
ds = super(FeatureColumns, self).build_dataset(*args, **kwargs)
ds.__class__ = Dataset
return ds
<|end_body_0|>
<|body_start_1|>
ds = super(FeatureColumns, self).build_dataset_from_stdin(*args, **kwargs)
ds.__class__ = Dataset
return ds
<|end_body_1|>
| A Dataset Factory object | FeatureColumns | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureColumns:
"""A Dataset Factory object"""
def build_dataset(self, *args, **kwargs):
"""build `Dataset` from `data_dir` or `data_file` if `use_gz`, will try to convert data_files to gz format and save to `gz_dir`, if `gz_dir` not given, will create one."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_028118 | 1,885 | permissive | [
{
"docstring": "build `Dataset` from `data_dir` or `data_file` if `use_gz`, will try to convert data_files to gz format and save to `gz_dir`, if `gz_dir` not given, will create one.",
"name": "build_dataset",
"signature": "def build_dataset(self, *args, **kwargs)"
},
{
"docstring": "doc",
"n... | 2 | null | Implement the Python class `FeatureColumns` described below.
Class description:
A Dataset Factory object
Method signatures and docstrings:
- def build_dataset(self, *args, **kwargs): build `Dataset` from `data_dir` or `data_file` if `use_gz`, will try to convert data_files to gz format and save to `gz_dir`, if `gz_di... | Implement the Python class `FeatureColumns` described below.
Class description:
A Dataset Factory object
Method signatures and docstrings:
- def build_dataset(self, *args, **kwargs): build `Dataset` from `data_dir` or `data_file` if `use_gz`, will try to convert data_files to gz format and save to `gz_dir`, if `gz_di... | e6ab0261eb719c21806bbadfd94001ecfe27de45 | <|skeleton|>
class FeatureColumns:
"""A Dataset Factory object"""
def build_dataset(self, *args, **kwargs):
"""build `Dataset` from `data_dir` or `data_file` if `use_gz`, will try to convert data_files to gz format and save to `gz_dir`, if `gz_dir` not given, will create one."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeatureColumns:
"""A Dataset Factory object"""
def build_dataset(self, *args, **kwargs):
"""build `Dataset` from `data_dir` or `data_file` if `use_gz`, will try to convert data_files to gz format and save to `gz_dir`, if `gz_dir` not given, will create one."""
ds = super(FeatureColumns, s... | the_stack_v2_python_sparse | competition/ogbg_molhiv/propeller/paddle/data/feature_column.py | PaddlePaddle/PaddleHelix | train | 771 |
235236d08a39a1fd56a9b73aeafc37e81bd6287b | [
"self.metric_name = metric['name'] or f\"{data_model['metrics'][metric['type']]['name']}\"\nself.metric_unit = metric['unit'] or f\"{data_model['metrics'][metric['type']]['unit']}\"\nrecent_measurements = metric['recent_measurements']\nscale = metric['scale']\nself.new_metric_value = None\nself.old_metric_value = N... | <|body_start_0|>
self.metric_name = metric['name'] or f"{data_model['metrics'][metric['type']]['name']}"
self.metric_unit = metric['unit'] or f"{data_model['metrics'][metric['type']]['unit']}"
recent_measurements = metric['recent_measurements']
scale = metric['scale']
self.new_me... | Handle metric data needed for notifications. | MetricNotificationData | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetricNotificationData:
"""Handle metric data needed for notifications."""
def __init__(self, metric, data_model, reason: str) -> None:
"""Initialise the Notification with metric data."""
<|body_0|>
def __user_friendly_status(data_model, metric_status) -> str:
""... | stack_v2_sparse_classes_36k_train_028119 | 1,839 | permissive | [
{
"docstring": "Initialise the Notification with metric data.",
"name": "__init__",
"signature": "def __init__(self, metric, data_model, reason: str) -> None"
},
{
"docstring": "Get the user friendly status name from the data model.",
"name": "__user_friendly_status",
"signature": "def _... | 2 | stack_v2_sparse_classes_30k_train_011804 | Implement the Python class `MetricNotificationData` described below.
Class description:
Handle metric data needed for notifications.
Method signatures and docstrings:
- def __init__(self, metric, data_model, reason: str) -> None: Initialise the Notification with metric data.
- def __user_friendly_status(data_model, m... | Implement the Python class `MetricNotificationData` described below.
Class description:
Handle metric data needed for notifications.
Method signatures and docstrings:
- def __init__(self, metric, data_model, reason: str) -> None: Initialise the Notification with metric data.
- def __user_friendly_status(data_model, m... | 602b6970e5d9088cb89cc6d488337349e54e1c9a | <|skeleton|>
class MetricNotificationData:
"""Handle metric data needed for notifications."""
def __init__(self, metric, data_model, reason: str) -> None:
"""Initialise the Notification with metric data."""
<|body_0|>
def __user_friendly_status(data_model, metric_status) -> str:
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MetricNotificationData:
"""Handle metric data needed for notifications."""
def __init__(self, metric, data_model, reason: str) -> None:
"""Initialise the Notification with metric data."""
self.metric_name = metric['name'] or f"{data_model['metrics'][metric['type']]['name']}"
self.... | the_stack_v2_python_sparse | components/notifier/src/models/metric_notification_data.py | Erik-Stel/quality-time | train | 0 |
6f1f6f9c2481a22512d07360ff62d3ee4ff15cd5 | [
"total = sum(nums)\nif total % 2 == 1:\n return False\ntarget = int(total / 2)\ndp = [0] * (total + 1)\nfor num in nums:\n i = target\n while i >= num:\n dp[i] = max(dp[i], dp[i - num] + num)\n i -= 1\n if dp[i] == target:\n return True\nreturn False",
"total = sum(nums)\n... | <|body_start_0|>
total = sum(nums)
if total % 2 == 1:
return False
target = int(total / 2)
dp = [0] * (total + 1)
for num in nums:
i = target
while i >= num:
dp[i] = max(dp[i], dp[i - num] + num)
i -= 1
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def can_partition(self, nums: List[int]) -> bool:
"""数组是否可以分为两半 Args: nums: 数组 Returns: 布尔值"""
<|body_0|>
def can_partition2(self, nums: List[int]) -> bool:
"""数组是否可以分为两半 Args: nums: 数组 Returns: 布尔值"""
<|body_1|>
def partition_helper(self, nums... | stack_v2_sparse_classes_36k_train_028120 | 2,791 | permissive | [
{
"docstring": "数组是否可以分为两半 Args: nums: 数组 Returns: 布尔值",
"name": "can_partition",
"signature": "def can_partition(self, nums: List[int]) -> bool"
},
{
"docstring": "数组是否可以分为两半 Args: nums: 数组 Returns: 布尔值",
"name": "can_partition2",
"signature": "def can_partition2(self, nums: List[int]) ... | 3 | stack_v2_sparse_classes_30k_test_001176 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def can_partition(self, nums: List[int]) -> bool: 数组是否可以分为两半 Args: nums: 数组 Returns: 布尔值
- def can_partition2(self, nums: List[int]) -> bool: 数组是否可以分为两半 Args: nums: 数组 Returns: 布... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def can_partition(self, nums: List[int]) -> bool: 数组是否可以分为两半 Args: nums: 数组 Returns: 布尔值
- def can_partition2(self, nums: List[int]) -> bool: 数组是否可以分为两半 Args: nums: 数组 Returns: 布... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def can_partition(self, nums: List[int]) -> bool:
"""数组是否可以分为两半 Args: nums: 数组 Returns: 布尔值"""
<|body_0|>
def can_partition2(self, nums: List[int]) -> bool:
"""数组是否可以分为两半 Args: nums: 数组 Returns: 布尔值"""
<|body_1|>
def partition_helper(self, nums... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def can_partition(self, nums: List[int]) -> bool:
"""数组是否可以分为两半 Args: nums: 数组 Returns: 布尔值"""
total = sum(nums)
if total % 2 == 1:
return False
target = int(total / 2)
dp = [0] * (total + 1)
for num in nums:
i = target
... | the_stack_v2_python_sparse | src/leetcodepython/array/partition_equal_subset_sum_416.py | zhangyu345293721/leetcode | train | 101 | |
de5cc6767c3f9066a3bc76aa323be54addad780c | [
"try:\n firewallController = FirewallController()\n json_data = json.dumps(firewallController.get_interface_ipv4Configuration_default_gw(id))\n resp = Response(json_data, status=200, mimetype='application/json')\n return resp\nexcept ValueError as ve:\n return Response(json.dumps(str(ve)), status=404... | <|body_start_0|>
try:
firewallController = FirewallController()
json_data = json.dumps(firewallController.get_interface_ipv4Configuration_default_gw(id))
resp = Response(json_data, status=200, mimetype='application/json')
return resp
except ValueError as v... | Interface_ifEntry_Ipv4Configuration_MacAddress | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Interface_ifEntry_Ipv4Configuration_MacAddress:
def get(self, id):
"""Get the default gw address of an interface"""
<|body_0|>
def put(self, id):
"""Update the default gw of an interface"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
... | stack_v2_sparse_classes_36k_train_028121 | 12,460 | no_license | [
{
"docstring": "Get the default gw address of an interface",
"name": "get",
"signature": "def get(self, id)"
},
{
"docstring": "Update the default gw of an interface",
"name": "put",
"signature": "def put(self, id)"
}
] | 2 | null | Implement the Python class `Interface_ifEntry_Ipv4Configuration_MacAddress` described below.
Class description:
Implement the Interface_ifEntry_Ipv4Configuration_MacAddress class.
Method signatures and docstrings:
- def get(self, id): Get the default gw address of an interface
- def put(self, id): Update the default ... | Implement the Python class `Interface_ifEntry_Ipv4Configuration_MacAddress` described below.
Class description:
Implement the Interface_ifEntry_Ipv4Configuration_MacAddress class.
Method signatures and docstrings:
- def get(self, id): Get the default gw address of an interface
- def put(self, id): Update the default ... | 6070e3cb6bf957e04f5d8267db11f3296410e18e | <|skeleton|>
class Interface_ifEntry_Ipv4Configuration_MacAddress:
def get(self, id):
"""Get the default gw address of an interface"""
<|body_0|>
def put(self, id):
"""Update the default gw of an interface"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Interface_ifEntry_Ipv4Configuration_MacAddress:
def get(self, id):
"""Get the default gw address of an interface"""
try:
firewallController = FirewallController()
json_data = json.dumps(firewallController.get_interface_ipv4Configuration_default_gw(id))
resp ... | the_stack_v2_python_sparse | configuration-agent/firewall/rest_api/resources/interface.py | ReliableLion/frog4-configurable-vnf | train | 0 | |
07d53a3569a5a132a3484bddf516f823e43a2d25 | [
"d = {}\nfor i in nums:\n d[i] = d.get(i, 0) + 1\nd = sorted(d.items(), key=lambda x: x[0])\nres = 0\nfor i in range(len(d) - 1):\n if d[i + 1][0] - d[i][0] == 1:\n res = max(res, d[i + 1][1] + d[i][1])\nreturn res",
"s = sorted(set(nums))\nres = 0\nfor i in range(len(s) - 1):\n if s[i] + 1 == s[i... | <|body_start_0|>
d = {}
for i in nums:
d[i] = d.get(i, 0) + 1
d = sorted(d.items(), key=lambda x: x[0])
res = 0
for i in range(len(d) - 1):
if d[i + 1][0] - d[i][0] == 1:
res = max(res, d[i + 1][1] + d[i][1])
return res
<|end_body_0... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findLHS(self, nums):
""":type nums: List[int] :rtype: int 140ms, beats: 42.25%"""
<|body_0|>
def findLHS2(self, nums):
""":type nums: List[int] :rtype: int 反向优化牛逼4500ms"""
<|body_1|>
def findLHS3(self, nums):
""":type nums: List[int... | stack_v2_sparse_classes_36k_train_028122 | 1,162 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int 140ms, beats: 42.25%",
"name": "findLHS",
"signature": "def findLHS(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int 反向优化牛逼4500ms",
"name": "findLHS2",
"signature": "def findLHS2(self, nums)"
},
{
"docstring": ":t... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLHS(self, nums): :type nums: List[int] :rtype: int 140ms, beats: 42.25%
- def findLHS2(self, nums): :type nums: List[int] :rtype: int 反向优化牛逼4500ms
- def findLHS3(self, nu... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLHS(self, nums): :type nums: List[int] :rtype: int 140ms, beats: 42.25%
- def findLHS2(self, nums): :type nums: List[int] :rtype: int 反向优化牛逼4500ms
- def findLHS3(self, nu... | 624975f767f6efa1d7361cc077eaebc344d57210 | <|skeleton|>
class Solution:
def findLHS(self, nums):
""":type nums: List[int] :rtype: int 140ms, beats: 42.25%"""
<|body_0|>
def findLHS2(self, nums):
""":type nums: List[int] :rtype: int 反向优化牛逼4500ms"""
<|body_1|>
def findLHS3(self, nums):
""":type nums: List[int... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findLHS(self, nums):
""":type nums: List[int] :rtype: int 140ms, beats: 42.25%"""
d = {}
for i in nums:
d[i] = d.get(i, 0) + 1
d = sorted(d.items(), key=lambda x: x[0])
res = 0
for i in range(len(d) - 1):
if d[i + 1][0] - d[... | the_stack_v2_python_sparse | 594. 最长和谐子序列.py | dx19910707/LeetCode | train | 0 | |
e9b450b2546051cffe51214d7ad9f26ca84c0263 | [
"self.name = name\nself.price = price\nself.outline = outline\nself.__db_file = course_db",
"if os.path.isfile(self.__db_file):\n with open(self.__db_file, 'rb') as fs:\n db = pickle.load(fs)\n if db:\n maxnums = max(db)\n return maxnums\nreturn 0",
"if os.path.isfile(self.__db_file):... | <|body_start_0|>
self.name = name
self.price = price
self.outline = outline
self.__db_file = course_db
<|end_body_0|>
<|body_start_1|>
if os.path.isfile(self.__db_file):
with open(self.__db_file, 'rb') as fs:
db = pickle.load(fs)
if db:
... | 课程的创建 | Course | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Course:
"""课程的创建"""
def __init__(self, course_db, name, price, outline):
""":param name: 课程名 :param price: 课程价格 :param outline: 课程周期 :param __db_file: 课程的数据表 相当于数据库表"""
<|body_0|>
def __max_course_id(self):
"""获取最大的id :return:"""
<|body_1|>
def __che... | stack_v2_sparse_classes_36k_train_028123 | 2,013 | no_license | [
{
"docstring": ":param name: 课程名 :param price: 课程价格 :param outline: 课程周期 :param __db_file: 课程的数据表 相当于数据库表",
"name": "__init__",
"signature": "def __init__(self, course_db, name, price, outline)"
},
{
"docstring": "获取最大的id :return:",
"name": "__max_course_id",
"signature": "def __max_cour... | 4 | null | Implement the Python class `Course` described below.
Class description:
课程的创建
Method signatures and docstrings:
- def __init__(self, course_db, name, price, outline): :param name: 课程名 :param price: 课程价格 :param outline: 课程周期 :param __db_file: 课程的数据表 相当于数据库表
- def __max_course_id(self): 获取最大的id :return:
- def __check_n... | Implement the Python class `Course` described below.
Class description:
课程的创建
Method signatures and docstrings:
- def __init__(self, course_db, name, price, outline): :param name: 课程名 :param price: 课程价格 :param outline: 课程周期 :param __db_file: 课程的数据表 相当于数据库表
- def __max_course_id(self): 获取最大的id :return:
- def __check_n... | 363e9176684fac2779f4da059f26e9406d754a7f | <|skeleton|>
class Course:
"""课程的创建"""
def __init__(self, course_db, name, price, outline):
""":param name: 课程名 :param price: 课程价格 :param outline: 课程周期 :param __db_file: 课程的数据表 相当于数据库表"""
<|body_0|>
def __max_course_id(self):
"""获取最大的id :return:"""
<|body_1|>
def __che... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Course:
"""课程的创建"""
def __init__(self, course_db, name, price, outline):
""":param name: 课程名 :param price: 课程价格 :param outline: 课程周期 :param __db_file: 课程的数据表 相当于数据库表"""
self.name = name
self.price = price
self.outline = outline
self.__db_file = course_db
def _... | the_stack_v2_python_sparse | Third_Module/Task/Start_shcoole/src/course.py | autoself/python_start | train | 0 |
d8ad01e011ec4db76801c30e0266e54cd22c7f05 | [
"if type == 'temp':\n self.mldFile = 'mld_DT02_c1m_reg2.0.nc'\nelif type == 'var':\n self.mldFile = 'mld_DReqDTm02_c1m_reg2.0.nc'\nelse:\n self.mldFile = 'mld_DR003_c1m_reg2.0.nc'\nsuper(Brest, self).__init__(**kwargs)\nself.add_mp()",
"gc = netcdf_file(self.gridfile)\nself.lat = gc.variables['lat'][:].c... | <|body_start_0|>
if type == 'temp':
self.mldFile = 'mld_DT02_c1m_reg2.0.nc'
elif type == 'var':
self.mldFile = 'mld_DReqDTm02_c1m_reg2.0.nc'
else:
self.mldFile = 'mld_DR003_c1m_reg2.0.nc'
super(Brest, self).__init__(**kwargs)
self.add_mp()
<|en... | Mixed layer climatology from Montegut et al. See more information at http://www.locean-ipsl.upmc.fr/~clement/mld.html MLD can be defined in three different ways: Temperature (temp) - Depth where temp is 10m temp +- 0.2 deg C Density (dens) - Depth where dens is 10m dens + 0.03 kg m-3 Variable criterion (var) | Brest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Brest:
"""Mixed layer climatology from Montegut et al. See more information at http://www.locean-ipsl.upmc.fr/~clement/mld.html MLD can be defined in three different ways: Temperature (temp) - Depth where temp is 10m temp +- 0.2 deg C Density (dens) - Depth where dens is 10m dens + 0.03 kg m-3 Va... | stack_v2_sparse_classes_36k_train_028124 | 2,271 | no_license | [
{
"docstring": "Initialize with chosen type of MLD",
"name": "__init__",
"signature": "def __init__(self, type='dens', **kwargs)"
},
{
"docstring": "Define lat and lon matrices for njord",
"name": "setup_grid",
"signature": "def setup_grid(self)"
},
{
"docstring": "Load mixed lay... | 4 | stack_v2_sparse_classes_30k_train_013659 | Implement the Python class `Brest` described below.
Class description:
Mixed layer climatology from Montegut et al. See more information at http://www.locean-ipsl.upmc.fr/~clement/mld.html MLD can be defined in three different ways: Temperature (temp) - Depth where temp is 10m temp +- 0.2 deg C Density (dens) - Depth ... | Implement the Python class `Brest` described below.
Class description:
Mixed layer climatology from Montegut et al. See more information at http://www.locean-ipsl.upmc.fr/~clement/mld.html MLD can be defined in three different ways: Temperature (temp) - Depth where temp is 10m temp +- 0.2 deg C Density (dens) - Depth ... | c756187f44186d7664055b23d83d0a8d5410ce9f | <|skeleton|>
class Brest:
"""Mixed layer climatology from Montegut et al. See more information at http://www.locean-ipsl.upmc.fr/~clement/mld.html MLD can be defined in three different ways: Temperature (temp) - Depth where temp is 10m temp +- 0.2 deg C Density (dens) - Depth where dens is 10m dens + 0.03 kg m-3 Va... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Brest:
"""Mixed layer climatology from Montegut et al. See more information at http://www.locean-ipsl.upmc.fr/~clement/mld.html MLD can be defined in three different ways: Temperature (temp) - Depth where temp is 10m temp +- 0.2 deg C Density (dens) - Depth where dens is 10m dens + 0.03 kg m-3 Variable criter... | the_stack_v2_python_sparse | njord/mimoc.py | brorfred/njord | train | 1 |
f1bc9e874854f5453cd4abb36f23f2852c9c966a | [
"dp = [0] * (n - 1)\ndp[0] = 1\nfor i in range(3, n + 1):\n for j in range(1, i):\n if i - j < 2:\n if j * (i - j) > dp[i - 2]:\n dp[i - 2] = j * (i - j)\n elif j * dp[i - j - 2] > dp[i - 2] or j * (i - j) > dp[i - 2]:\n dp[i - 2] = j * max(dp[i - j - 2], i - j)... | <|body_start_0|>
dp = [0] * (n - 1)
dp[0] = 1
for i in range(3, n + 1):
for j in range(1, i):
if i - j < 2:
if j * (i - j) > dp[i - 2]:
dp[i - 2] = j * (i - j)
elif j * dp[i - j - 2] > dp[i - 2] or j * (i - j... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def integerBreak(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def integerBreak2(self, n: int) -> int:
"""dp[i] is the maximum product for number i"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dp = [0] * (n - 1)
dp[0] = 1
... | stack_v2_sparse_classes_36k_train_028125 | 1,299 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "integerBreak",
"signature": "def integerBreak(self, n)"
},
{
"docstring": "dp[i] is the maximum product for number i",
"name": "integerBreak2",
"signature": "def integerBreak2(self, n: int) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_012791 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def integerBreak(self, n): :type n: int :rtype: int
- def integerBreak2(self, n: int) -> int: dp[i] is the maximum product for number i | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def integerBreak(self, n): :type n: int :rtype: int
- def integerBreak2(self, n: int) -> int: dp[i] is the maximum product for number i
<|skeleton|>
class Solution:
def int... | a5b02044ef39154b6a8d32eb57682f447e1632ba | <|skeleton|>
class Solution:
def integerBreak(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def integerBreak2(self, n: int) -> int:
"""dp[i] is the maximum product for number i"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def integerBreak(self, n):
""":type n: int :rtype: int"""
dp = [0] * (n - 1)
dp[0] = 1
for i in range(3, n + 1):
for j in range(1, i):
if i - j < 2:
if j * (i - j) > dp[i - 2]:
dp[i - 2] = j * (i ... | the_stack_v2_python_sparse | algo/dp/integer_break.py | xys234/coding-problems | train | 0 | |
34b63a9c42b6ee7a2a6b7e940a4253d96f179d0e | [
"self.file_name = file_name\nself.base_name = os.path.basename(urllib.request.urlparse(file_name).path)\nself.path = path",
"try:\n if len(self.path) > 0:\n full_file_path = self.path + '/' + self.base_name\n else:\n full_file_path = self.base_name\n urllib.request.urlretrieve(self.file_nam... | <|body_start_0|>
self.file_name = file_name
self.base_name = os.path.basename(urllib.request.urlparse(file_name).path)
self.path = path
<|end_body_0|>
<|body_start_1|>
try:
if len(self.path) > 0:
full_file_path = self.path + '/' + self.base_name
e... | Save | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Save:
def __init__(self, file_name, path=''):
"""SaveFile Constructor :param file_name: :param path :rtype: object"""
<|body_0|>
def save(self) -> object:
"""Download from web and save it to local folder :rtype: object"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_028126 | 801 | no_license | [
{
"docstring": "SaveFile Constructor :param file_name: :param path :rtype: object",
"name": "__init__",
"signature": "def __init__(self, file_name, path='')"
},
{
"docstring": "Download from web and save it to local folder :rtype: object",
"name": "save",
"signature": "def save(self) -> ... | 2 | stack_v2_sparse_classes_30k_test_000416 | Implement the Python class `Save` described below.
Class description:
Implement the Save class.
Method signatures and docstrings:
- def __init__(self, file_name, path=''): SaveFile Constructor :param file_name: :param path :rtype: object
- def save(self) -> object: Download from web and save it to local folder :rtype... | Implement the Python class `Save` described below.
Class description:
Implement the Save class.
Method signatures and docstrings:
- def __init__(self, file_name, path=''): SaveFile Constructor :param file_name: :param path :rtype: object
- def save(self) -> object: Download from web and save it to local folder :rtype... | 2c12e9870dc4c852a7da4ed6bc7ff063007d3bd7 | <|skeleton|>
class Save:
def __init__(self, file_name, path=''):
"""SaveFile Constructor :param file_name: :param path :rtype: object"""
<|body_0|>
def save(self) -> object:
"""Download from web and save it to local folder :rtype: object"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Save:
def __init__(self, file_name, path=''):
"""SaveFile Constructor :param file_name: :param path :rtype: object"""
self.file_name = file_name
self.base_name = os.path.basename(urllib.request.urlparse(file_name).path)
self.path = path
def save(self) -> object:
""... | the_stack_v2_python_sparse | Image/Save.py | digitaldreams/image-crawler-python | train | 37 | |
396071bcdee9ab2b031b084f18bd2aea6abd682d | [
"self.fs_type = fs_type\nself.image = image\nself.keyring = keyring\nself.monitors = monitors\nself.pool = pool\nself.read_only = read_only\nself.secret_ref = secret_ref\nself.user = user",
"if dictionary is None:\n return None\nfs_type = dictionary.get('fsType')\nimage = dictionary.get('image')\nkeyring = dic... | <|body_start_0|>
self.fs_type = fs_type
self.image = image
self.keyring = keyring
self.monitors = monitors
self.pool = pool
self.read_only = read_only
self.secret_ref = secret_ref
self.user = user
<|end_body_0|>
<|body_start_1|>
if dictionary is N... | Implementation of the 'PodInfo_PodSpec_VolumeInfo_RBD' model. Represents a Rados Block Device mount that lasts the lifetime of a pod. Attributes: fs_type (string): TODO: Type description here. image (string): TODO: Type description here. keyring (string): TODO: Type description here. monitors (list of string): TODO: Ty... | PodInfo_PodSpec_VolumeInfo_RBD | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PodInfo_PodSpec_VolumeInfo_RBD:
"""Implementation of the 'PodInfo_PodSpec_VolumeInfo_RBD' model. Represents a Rados Block Device mount that lasts the lifetime of a pod. Attributes: fs_type (string): TODO: Type description here. image (string): TODO: Type description here. keyring (string): TODO: ... | stack_v2_sparse_classes_36k_train_028127 | 3,022 | permissive | [
{
"docstring": "Constructor for the PodInfo_PodSpec_VolumeInfo_RBD class",
"name": "__init__",
"signature": "def __init__(self, fs_type=None, image=None, keyring=None, monitors=None, pool=None, read_only=None, secret_ref=None, user=None)"
},
{
"docstring": "Creates an instance of this model from... | 2 | stack_v2_sparse_classes_30k_test_000797 | Implement the Python class `PodInfo_PodSpec_VolumeInfo_RBD` described below.
Class description:
Implementation of the 'PodInfo_PodSpec_VolumeInfo_RBD' model. Represents a Rados Block Device mount that lasts the lifetime of a pod. Attributes: fs_type (string): TODO: Type description here. image (string): TODO: Type des... | Implement the Python class `PodInfo_PodSpec_VolumeInfo_RBD` described below.
Class description:
Implementation of the 'PodInfo_PodSpec_VolumeInfo_RBD' model. Represents a Rados Block Device mount that lasts the lifetime of a pod. Attributes: fs_type (string): TODO: Type description here. image (string): TODO: Type des... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class PodInfo_PodSpec_VolumeInfo_RBD:
"""Implementation of the 'PodInfo_PodSpec_VolumeInfo_RBD' model. Represents a Rados Block Device mount that lasts the lifetime of a pod. Attributes: fs_type (string): TODO: Type description here. image (string): TODO: Type description here. keyring (string): TODO: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PodInfo_PodSpec_VolumeInfo_RBD:
"""Implementation of the 'PodInfo_PodSpec_VolumeInfo_RBD' model. Represents a Rados Block Device mount that lasts the lifetime of a pod. Attributes: fs_type (string): TODO: Type description here. image (string): TODO: Type description here. keyring (string): TODO: Type descript... | the_stack_v2_python_sparse | cohesity_management_sdk/models/pod_info_pod_spec_volume_info_rbd.py | cohesity/management-sdk-python | train | 24 |
a7bd2a80bcf6a27c11ef916604536f12ff6d21f2 | [
"lines = []\nfor line in parent._lines:\n if len(line) > 120:\n DocWarning(path, f'Code line length over 120 chars: {line!r}')\n line = line[:120]\n lines.append(line)\nself = object.__new__(cls)\nself.language = parent._language\nself.lines = lines\nreturn self",
"result = ['<', self.__class_... | <|body_start_0|>
lines = []
for line in parent._lines:
if len(line) > 120:
DocWarning(path, f'Code line length over 120 chars: {line!r}')
line = line[:120]
lines.append(line)
self = object.__new__(cls)
self.language = parent._langua... | Represents a graved code block part of a docstring. Attributes ---------- language : `None`, `str` The language of the code if applicable. lines : `list` of `str` The lines of the code-block | GravedCodeBlock | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GravedCodeBlock:
"""Represents a graved code block part of a docstring. Attributes ---------- language : `None`, `str` The language of the code if applicable. lines : `list` of `str` The lines of the code-block"""
def __new__(cls, parent, path):
"""Creates a new graved code block.. P... | stack_v2_sparse_classes_36k_train_028128 | 25,556 | permissive | [
{
"docstring": "Creates a new graved code block.. Parameters ---------- parent : ``TextCodeBlock`` The source code block. path : ``QualPath`` The path of the respective docstring. Returns ------- self : ``GravedCodeBlock``",
"name": "__new__",
"signature": "def __new__(cls, parent, path)"
},
{
"... | 2 | stack_v2_sparse_classes_30k_train_009613 | Implement the Python class `GravedCodeBlock` described below.
Class description:
Represents a graved code block part of a docstring. Attributes ---------- language : `None`, `str` The language of the code if applicable. lines : `list` of `str` The lines of the code-block
Method signatures and docstrings:
- def __new_... | Implement the Python class `GravedCodeBlock` described below.
Class description:
Represents a graved code block part of a docstring. Attributes ---------- language : `None`, `str` The language of the code if applicable. lines : `list` of `str` The lines of the code-block
Method signatures and docstrings:
- def __new_... | 53f24fdb38459dc5a4fd04f11bdbfee8295b76a4 | <|skeleton|>
class GravedCodeBlock:
"""Represents a graved code block part of a docstring. Attributes ---------- language : `None`, `str` The language of the code if applicable. lines : `list` of `str` The lines of the code-block"""
def __new__(cls, parent, path):
"""Creates a new graved code block.. P... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GravedCodeBlock:
"""Represents a graved code block part of a docstring. Attributes ---------- language : `None`, `str` The language of the code if applicable. lines : `list` of `str` The lines of the code-block"""
def __new__(cls, parent, path):
"""Creates a new graved code block.. Parameters ---... | the_stack_v2_python_sparse | hata/ext/patchouli/graver.py | HuyaneMatsu/hata | train | 3 |
ca0956cc76016c6774af349bf4816c1a06b735a6 | [
"Inventory.__init__(self, inventory_info)\nself.brand = brand\nself.voltage = voltage",
"output_dict = Inventory.return_as_dictionary(self)\noutput_dict['brand'] = self.brand\noutput_dict['voltage'] = self.voltage\nreturn output_dict"
] | <|body_start_0|>
Inventory.__init__(self, inventory_info)
self.brand = brand
self.voltage = voltage
<|end_body_0|>
<|body_start_1|>
output_dict = Inventory.return_as_dictionary(self)
output_dict['brand'] = self.brand
output_dict['voltage'] = self.voltage
return o... | Creates a class that handles data on electric appliances | ElectricAppliances | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElectricAppliances:
"""Creates a class that handles data on electric appliances"""
def __init__(self, inventory_info, brand, voltage):
"""Initializes the class info"""
<|body_0|>
def return_as_dictionary(self):
"""Returns a dictionary of the appliance information... | stack_v2_sparse_classes_36k_train_028129 | 724 | no_license | [
{
"docstring": "Initializes the class info",
"name": "__init__",
"signature": "def __init__(self, inventory_info, brand, voltage)"
},
{
"docstring": "Returns a dictionary of the appliance information",
"name": "return_as_dictionary",
"signature": "def return_as_dictionary(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004297 | Implement the Python class `ElectricAppliances` described below.
Class description:
Creates a class that handles data on electric appliances
Method signatures and docstrings:
- def __init__(self, inventory_info, brand, voltage): Initializes the class info
- def return_as_dictionary(self): Returns a dictionary of the ... | Implement the Python class `ElectricAppliances` described below.
Class description:
Creates a class that handles data on electric appliances
Method signatures and docstrings:
- def __init__(self, inventory_info, brand, voltage): Initializes the class info
- def return_as_dictionary(self): Returns a dictionary of the ... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class ElectricAppliances:
"""Creates a class that handles data on electric appliances"""
def __init__(self, inventory_info, brand, voltage):
"""Initializes the class info"""
<|body_0|>
def return_as_dictionary(self):
"""Returns a dictionary of the appliance information... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ElectricAppliances:
"""Creates a class that handles data on electric appliances"""
def __init__(self, inventory_info, brand, voltage):
"""Initializes the class info"""
Inventory.__init__(self, inventory_info)
self.brand = brand
self.voltage = voltage
def return_as_dic... | the_stack_v2_python_sparse | students/dfspray/Lesson01/inventory_management/electric_appliances_class.py | JavaRod/SP_Python220B_2019 | train | 1 |
44a22f85050c3da60fd744e9ad5a8ba813d7c373 | [
"if not root:\n return\nq = [[root], []]\ni = 0\nj = (i + 1) % 2\nwhile q[0] or q[1]:\n while q[i]:\n node = q[i].pop(0)\n node.next = q[i][0] if q[i] else None\n if node.left:\n q[j].append(node.left)\n if node.right:\n q[j].append(node.right)\n i = j\n ... | <|body_start_0|>
if not root:
return
q = [[root], []]
i = 0
j = (i + 1) % 2
while q[0] or q[1]:
while q[i]:
node = q[i].pop(0)
node.next = q[i][0] if q[i] else None
if node.left:
q[j].appe... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def connect(self, root):
"""05/06/2018 23:03"""
<|body_0|>
def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
"""Time complexity: O(n) Space complexity: O(n/2) # the number of leaf nodes"""
<|body_1|>
def connect(self, root: 'Option... | stack_v2_sparse_classes_36k_train_028130 | 3,713 | no_license | [
{
"docstring": "05/06/2018 23:03",
"name": "connect",
"signature": "def connect(self, root)"
},
{
"docstring": "Time complexity: O(n) Space complexity: O(n/2) # the number of leaf nodes",
"name": "connect",
"signature": "def connect(self, root: 'Optional[Node]') -> 'Optional[Node]'"
},... | 3 | stack_v2_sparse_classes_30k_train_015350 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def connect(self, root): 05/06/2018 23:03
- def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': Time complexity: O(n) Space complexity: O(n/2) # the number of leaf nod... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def connect(self, root): 05/06/2018 23:03
- def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': Time complexity: O(n) Space complexity: O(n/2) # the number of leaf nod... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def connect(self, root):
"""05/06/2018 23:03"""
<|body_0|>
def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
"""Time complexity: O(n) Space complexity: O(n/2) # the number of leaf nodes"""
<|body_1|>
def connect(self, root: 'Option... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def connect(self, root):
"""05/06/2018 23:03"""
if not root:
return
q = [[root], []]
i = 0
j = (i + 1) % 2
while q[0] or q[1]:
while q[i]:
node = q[i].pop(0)
node.next = q[i][0] if q[i] else None
... | the_stack_v2_python_sparse | leetcode/solved/116_Populating_Next_Right_Pointers_in_Each_Node/solution.py | sungminoh/algorithms | train | 0 | |
64f3719d093c2fbda2bc243bb9fd3f1649c9afdb | [
"super().__init__(ff_settings=ff_settings, box_relax=True, **kwargs)\nbulk_structure_relaxed, bulk_energy, _, _ = super().calculate([bulk_structure])[0]\nself.bulk_energy_per_atom = bulk_energy / bulk_structure_relaxed.num_sites\nfrom pymatgen.core.surface import SlabGenerator\nslab_generators = [SlabGenerator(init... | <|body_start_0|>
super().__init__(ff_settings=ff_settings, box_relax=True, **kwargs)
bulk_structure_relaxed, bulk_energy, _, _ = super().calculate([bulk_structure])[0]
self.bulk_energy_per_atom = bulk_energy / bulk_structure_relaxed.num_sites
from pymatgen.core.surface import SlabGenerat... | Surface energy Calculator. This calculator generate and calculate surface energies of slab structures based on inputs of bulk_structure and miller_indexes with the SlabGenerator in pymatgen: https://pymatgen.org/pymatgen.core.surface.html | SurfaceEnergy | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SurfaceEnergy:
"""Surface energy Calculator. This calculator generate and calculate surface energies of slab structures based on inputs of bulk_structure and miller_indexes with the SlabGenerator in pymatgen: https://pymatgen.org/pymatgen.core.surface.html"""
def __init__(self, ff_settings, ... | stack_v2_sparse_classes_36k_train_028131 | 39,049 | permissive | [
{
"docstring": "Init. Args: ff_settings (list/Potential): Configure the force field settings for LAMMPS calculation, if given a Potential object, should apply Potential.write_param method to get the force field setting. bulk_structure (Structure): The bulk structure of target system. Slab structures will be gen... | 2 | null | Implement the Python class `SurfaceEnergy` described below.
Class description:
Surface energy Calculator. This calculator generate and calculate surface energies of slab structures based on inputs of bulk_structure and miller_indexes with the SlabGenerator in pymatgen: https://pymatgen.org/pymatgen.core.surface.html
... | Implement the Python class `SurfaceEnergy` described below.
Class description:
Surface energy Calculator. This calculator generate and calculate surface energies of slab structures based on inputs of bulk_structure and miller_indexes with the SlabGenerator in pymatgen: https://pymatgen.org/pymatgen.core.surface.html
... | 6ae3c7029b939e1183684358a3ae2fef41053be5 | <|skeleton|>
class SurfaceEnergy:
"""Surface energy Calculator. This calculator generate and calculate surface energies of slab structures based on inputs of bulk_structure and miller_indexes with the SlabGenerator in pymatgen: https://pymatgen.org/pymatgen.core.surface.html"""
def __init__(self, ff_settings, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SurfaceEnergy:
"""Surface energy Calculator. This calculator generate and calculate surface energies of slab structures based on inputs of bulk_structure and miller_indexes with the SlabGenerator in pymatgen: https://pymatgen.org/pymatgen.core.surface.html"""
def __init__(self, ff_settings, bulk_structur... | the_stack_v2_python_sparse | maml/apps/pes/_lammps.py | materialsvirtuallab/maml | train | 266 |
0a052a277ae607acd9a81affe76050c38f0727c9 | [
"bin_path = '/usr/local/bin/'\nself.prefix = bin_path + 'aws s3api'\nif options is None:\n options = []\nself.operation = operation\nself.options = ' '.join(options)",
"if params is None:\n params = []\ncommand_list = [self.prefix, self.options, self.operation] + params\ncmd = list(filter(lambda cmd: len(cm... | <|body_start_0|>
bin_path = '/usr/local/bin/'
self.prefix = bin_path + 'aws s3api'
if options is None:
options = []
self.operation = operation
self.options = ' '.join(options)
<|end_body_0|>
<|body_start_1|>
if params is None:
params = []
... | AWS | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AWS:
def __init__(self, operation, options=None):
"""Constructor for aws class operation(str): aws operations options(list): Optional options for the command"""
<|body_0|>
def command(self, params=None):
"""Args: params(list): list of params to be passed in the comma... | stack_v2_sparse_classes_36k_train_028132 | 973 | permissive | [
{
"docstring": "Constructor for aws class operation(str): aws operations options(list): Optional options for the command",
"name": "__init__",
"signature": "def __init__(self, operation, options=None)"
},
{
"docstring": "Args: params(list): list of params to be passed in the command Returns: com... | 2 | null | Implement the Python class `AWS` described below.
Class description:
Implement the AWS class.
Method signatures and docstrings:
- def __init__(self, operation, options=None): Constructor for aws class operation(str): aws operations options(list): Optional options for the command
- def command(self, params=None): Args... | Implement the Python class `AWS` described below.
Class description:
Implement the AWS class.
Method signatures and docstrings:
- def __init__(self, operation, options=None): Constructor for aws class operation(str): aws operations options(list): Optional options for the command
- def command(self, params=None): Args... | 4c3b9b3e8e7f42d43270a9b79299a8b404a76046 | <|skeleton|>
class AWS:
def __init__(self, operation, options=None):
"""Constructor for aws class operation(str): aws operations options(list): Optional options for the command"""
<|body_0|>
def command(self, params=None):
"""Args: params(list): list of params to be passed in the comma... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AWS:
def __init__(self, operation, options=None):
"""Constructor for aws class operation(str): aws operations options(list): Optional options for the command"""
bin_path = '/usr/local/bin/'
self.prefix = bin_path + 'aws s3api'
if options is None:
options = []
... | the_stack_v2_python_sparse | rgw/v2/lib/aws/resource_op.py | red-hat-storage/ceph-qe-scripts | train | 9 | |
f133cefe912376995390d8cc0ebc59d8bb37f084 | [
"if derivatives is not None:\n self.derivatives: BaseParameterDerivatives = derivatives\n for param_str in params:\n if not hasattr(self, param_str):\n setattr(self, param_str, self._make_param_function(param_str))\nsuper().__init__(params=params)",
"def param_function(ext: BatchL2Grad, mo... | <|body_start_0|>
if derivatives is not None:
self.derivatives: BaseParameterDerivatives = derivatives
for param_str in params:
if not hasattr(self, param_str):
setattr(self, param_str, self._make_param_function(param_str))
super().__init__(para... | BaseExtension for batch_l2. | BatchL2Base | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchL2Base:
"""BaseExtension for batch_l2."""
def __init__(self, params: List[str], derivatives: BaseParameterDerivatives=None):
"""Initialization. If derivatives object is provided initializes methods that compute batch_l2. If there is an existent method in a child class it is not ... | stack_v2_sparse_classes_36k_train_028133 | 2,514 | permissive | [
{
"docstring": "Initialization. If derivatives object is provided initializes methods that compute batch_l2. If there is an existent method in a child class it is not overwritten. Args: params: parameter names derivatives: derivatives object. Defaults to None.",
"name": "__init__",
"signature": "def __i... | 2 | null | Implement the Python class `BatchL2Base` described below.
Class description:
BaseExtension for batch_l2.
Method signatures and docstrings:
- def __init__(self, params: List[str], derivatives: BaseParameterDerivatives=None): Initialization. If derivatives object is provided initializes methods that compute batch_l2. I... | Implement the Python class `BatchL2Base` described below.
Class description:
BaseExtension for batch_l2.
Method signatures and docstrings:
- def __init__(self, params: List[str], derivatives: BaseParameterDerivatives=None): Initialization. If derivatives object is provided initializes methods that compute batch_l2. I... | 1ebfb4055be72ed9e0f9d101d78806bd4119645e | <|skeleton|>
class BatchL2Base:
"""BaseExtension for batch_l2."""
def __init__(self, params: List[str], derivatives: BaseParameterDerivatives=None):
"""Initialization. If derivatives object is provided initializes methods that compute batch_l2. If there is an existent method in a child class it is not ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BatchL2Base:
"""BaseExtension for batch_l2."""
def __init__(self, params: List[str], derivatives: BaseParameterDerivatives=None):
"""Initialization. If derivatives object is provided initializes methods that compute batch_l2. If there is an existent method in a child class it is not overwritten. ... | the_stack_v2_python_sparse | backpack/extensions/firstorder/batch_l2_grad/batch_l2_base.py | f-dangel/backpack | train | 505 |
2e33ad55923c100e8349a64dc1dce4b45caf17a5 | [
"self.loss_type = loss_type\nself.input_dim = input_dim\nself.device = torch.device('cuda:%d' % GPU if torch.cuda.is_available() and GPU >= 0 else 'cpu')",
"if self.loss_type in ('mmd_lin', 'mmd'):\n mmdloss = MMD_loss(kernel_type='linear')\n loss = mmdloss(X, Y)\nelif self.loss_type == 'coral':\n loss =... | <|body_start_0|>
self.loss_type = loss_type
self.input_dim = input_dim
self.device = torch.device('cuda:%d' % GPU if torch.cuda.is_available() and GPU >= 0 else 'cpu')
<|end_body_0|>
<|body_start_1|>
if self.loss_type in ('mmd_lin', 'mmd'):
mmdloss = MMD_loss(kernel_type='li... | TransferLoss | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransferLoss:
def __init__(self, loss_type='cosine', input_dim=512, GPU=0):
"""Supported loss_type: mmd(mmd_lin), mmd_rbf, coral, cosine, kl, js, mine, adv"""
<|body_0|>
def compute(self, X, Y):
"""Compute adaptation loss Arguments: X {tensor} -- source matrix Y {ten... | stack_v2_sparse_classes_36k_train_028134 | 27,939 | permissive | [
{
"docstring": "Supported loss_type: mmd(mmd_lin), mmd_rbf, coral, cosine, kl, js, mine, adv",
"name": "__init__",
"signature": "def __init__(self, loss_type='cosine', input_dim=512, GPU=0)"
},
{
"docstring": "Compute adaptation loss Arguments: X {tensor} -- source matrix Y {tensor} -- target ma... | 2 | null | Implement the Python class `TransferLoss` described below.
Class description:
Implement the TransferLoss class.
Method signatures and docstrings:
- def __init__(self, loss_type='cosine', input_dim=512, GPU=0): Supported loss_type: mmd(mmd_lin), mmd_rbf, coral, cosine, kl, js, mine, adv
- def compute(self, X, Y): Comp... | Implement the Python class `TransferLoss` described below.
Class description:
Implement the TransferLoss class.
Method signatures and docstrings:
- def __init__(self, loss_type='cosine', input_dim=512, GPU=0): Supported loss_type: mmd(mmd_lin), mmd_rbf, coral, cosine, kl, js, mine, adv
- def compute(self, X, Y): Comp... | 4c30e5827b74bcc45f14cf3ae0c1715459ed09ae | <|skeleton|>
class TransferLoss:
def __init__(self, loss_type='cosine', input_dim=512, GPU=0):
"""Supported loss_type: mmd(mmd_lin), mmd_rbf, coral, cosine, kl, js, mine, adv"""
<|body_0|>
def compute(self, X, Y):
"""Compute adaptation loss Arguments: X {tensor} -- source matrix Y {ten... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransferLoss:
def __init__(self, loss_type='cosine', input_dim=512, GPU=0):
"""Supported loss_type: mmd(mmd_lin), mmd_rbf, coral, cosine, kl, js, mine, adv"""
self.loss_type = loss_type
self.input_dim = input_dim
self.device = torch.device('cuda:%d' % GPU if torch.cuda.is_avail... | the_stack_v2_python_sparse | qlib/contrib/model/pytorch_adarnn.py | microsoft/qlib | train | 12,822 | |
7d949e7d1134bf651771606bf91fbb00001c7b16 | [
"self.ids.lblText.text = 'Check des servos'\ntime.sleep(0.5)\nself.tabServo = axControl.checkAllServo(14)",
"self.ids.lblText.text = 'En mouvement'\ntime.sleep(0.5)\naxControl.doFullMouvement(filename, 0.015)\nself.ids.lblText.text = 'En attente'\ntime.sleep(0.5)",
"self.Check()\nself.ids.lblText.text = 'Progra... | <|body_start_0|>
self.ids.lblText.text = 'Check des servos'
time.sleep(0.5)
self.tabServo = axControl.checkAllServo(14)
<|end_body_0|>
<|body_start_1|>
self.ids.lblText.text = 'En mouvement'
time.sleep(0.5)
axControl.doFullMouvement(filename, 0.015)
self.ids.lblT... | Menu principal de l'interface utilisateur | Menu | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Menu:
"""Menu principal de l'interface utilisateur"""
def Check(self):
"""Check tous les servos connectes et stock la valeur dans tabServo"""
<|body_0|>
def StartMouvement(self, filename):
"""Demarre un mouvement enregistrer"""
<|body_1|>
def ProgMou... | stack_v2_sparse_classes_36k_train_028135 | 4,508 | no_license | [
{
"docstring": "Check tous les servos connectes et stock la valeur dans tabServo",
"name": "Check",
"signature": "def Check(self)"
},
{
"docstring": "Demarre un mouvement enregistrer",
"name": "StartMouvement",
"signature": "def StartMouvement(self, filename)"
},
{
"docstring": "... | 3 | stack_v2_sparse_classes_30k_train_019729 | Implement the Python class `Menu` described below.
Class description:
Menu principal de l'interface utilisateur
Method signatures and docstrings:
- def Check(self): Check tous les servos connectes et stock la valeur dans tabServo
- def StartMouvement(self, filename): Demarre un mouvement enregistrer
- def ProgMouveme... | Implement the Python class `Menu` described below.
Class description:
Menu principal de l'interface utilisateur
Method signatures and docstrings:
- def Check(self): Check tous les servos connectes et stock la valeur dans tabServo
- def StartMouvement(self, filename): Demarre un mouvement enregistrer
- def ProgMouveme... | 4ce70329a6ee107754acf3f01c3794989bf6394b | <|skeleton|>
class Menu:
"""Menu principal de l'interface utilisateur"""
def Check(self):
"""Check tous les servos connectes et stock la valeur dans tabServo"""
<|body_0|>
def StartMouvement(self, filename):
"""Demarre un mouvement enregistrer"""
<|body_1|>
def ProgMou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Menu:
"""Menu principal de l'interface utilisateur"""
def Check(self):
"""Check tous les servos connectes et stock la valeur dans tabServo"""
self.ids.lblText.text = 'Check des servos'
time.sleep(0.5)
self.tabServo = axControl.checkAllServo(14)
def StartMouvement(self... | the_stack_v2_python_sparse | 2019 - Atom Factory/Développement/Bras_robotis/SAMFRA_RASPBERRYHUMANOIDE_2016-17/Software/R0B1/robui.py | EMBAvalais/EMBA_Eurobot | train | 0 |
34ec68688143315b7b0922ddf27fd74908760a67 | [
"CREATION_METHOD_NAMES = ('copy', 'difference', 'intersection', 'symmetric_difference', 'union', '__and__', '__or__', '__rand__', '__ror__', '__rsub__', '__rxor__', '__sub__', '__xor__')\nfrozenset_subclass = super().__new__(metacls, class_name, class_base_classes, class_attrs)\nfor creation_method_name in CREATION... | <|body_start_0|>
CREATION_METHOD_NAMES = ('copy', 'difference', 'intersection', 'symmetric_difference', 'union', '__and__', '__or__', '__rand__', '__ror__', '__rsub__', '__rxor__', '__sub__', '__xor__')
frozenset_subclass = super().__new__(metacls, class_name, class_base_classes, class_attrs)
fo... | Metaclass of the abstract :class:`FrozenSetSubclassable` base class and all concrete subclasses thereof. This metaclass dynamically redefines *all* container-creating methods of the :class:`frozenset` superclass of the :class:`FrozenSetSubclassable` class (e.g., :meth:`frozenset.__or__`) within the currently declared c... | FrozenSetSubclassableMeta | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FrozenSetSubclassableMeta:
"""Metaclass of the abstract :class:`FrozenSetSubclassable` base class and all concrete subclasses thereof. This metaclass dynamically redefines *all* container-creating methods of the :class:`frozenset` superclass of the :class:`FrozenSetSubclassable` class (e.g., :met... | stack_v2_sparse_classes_36k_train_028136 | 14,366 | no_license | [
{
"docstring": "Redefine all container-creating methods of the :class:`frozenset` superclass of the :class:`FrozenSetSubclassable` class (e.g., :meth:`frozenset.__or__`) within the currently declared concrete subclass of that class identified by the passed parameters.",
"name": "__new__",
"signature": "... | 2 | null | Implement the Python class `FrozenSetSubclassableMeta` described below.
Class description:
Metaclass of the abstract :class:`FrozenSetSubclassable` base class and all concrete subclasses thereof. This metaclass dynamically redefines *all* container-creating methods of the :class:`frozenset` superclass of the :class:`F... | Implement the Python class `FrozenSetSubclassableMeta` described below.
Class description:
Metaclass of the abstract :class:`FrozenSetSubclassable` base class and all concrete subclasses thereof. This metaclass dynamically redefines *all* container-creating methods of the :class:`frozenset` superclass of the :class:`F... | dd03ff5e3df3ef48d887a6566a6286fcd168880b | <|skeleton|>
class FrozenSetSubclassableMeta:
"""Metaclass of the abstract :class:`FrozenSetSubclassable` base class and all concrete subclasses thereof. This metaclass dynamically redefines *all* container-creating methods of the :class:`frozenset` superclass of the :class:`FrozenSetSubclassable` class (e.g., :met... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FrozenSetSubclassableMeta:
"""Metaclass of the abstract :class:`FrozenSetSubclassable` base class and all concrete subclasses thereof. This metaclass dynamically redefines *all* container-creating methods of the :class:`frozenset` superclass of the :class:`FrozenSetSubclassable` class (e.g., :meth:`frozenset.... | the_stack_v2_python_sparse | betse/util/type/iterable/set/setcls.py | R-Stefano/betse-ml | train | 0 |
ae38f318e5540817e9be8505ddce210a9ea84fbb | [
"self.controller_bus_number = controller_bus_number\nself.controller_type = controller_type\nself.unit_number = unit_number",
"if dictionary is None:\n return None\ncontroller_bus_number = dictionary.get('controllerBusNumber')\ncontroller_type = dictionary.get('controllerType')\nunit_number = dictionary.get('u... | <|body_start_0|>
self.controller_bus_number = controller_bus_number
self.controller_type = controller_type
self.unit_number = unit_number
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
controller_bus_number = dictionary.get('controllerBusNumber')
... | Implementation of the 'VmwareDiskExclusionProto' model. This message contains basic info of the disk to be excluded from backup. The info contained here: 1. should be enough to identify the disk during the backup job. 2. is a subset of the message fetched to be displayed to the end user. Example: entities/vmware.proto.... | VmwareDiskExclusionProto | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VmwareDiskExclusionProto:
"""Implementation of the 'VmwareDiskExclusionProto' model. This message contains basic info of the disk to be excluded from backup. The info contained here: 1. should be enough to identify the disk during the backup job. 2. is a subset of the message fetched to be displa... | stack_v2_sparse_classes_36k_train_028137 | 2,384 | permissive | [
{
"docstring": "Constructor for the VmwareDiskExclusionProto class",
"name": "__init__",
"signature": "def __init__(self, controller_bus_number=None, controller_type=None, unit_number=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A d... | 2 | null | Implement the Python class `VmwareDiskExclusionProto` described below.
Class description:
Implementation of the 'VmwareDiskExclusionProto' model. This message contains basic info of the disk to be excluded from backup. The info contained here: 1. should be enough to identify the disk during the backup job. 2. is a sub... | Implement the Python class `VmwareDiskExclusionProto` described below.
Class description:
Implementation of the 'VmwareDiskExclusionProto' model. This message contains basic info of the disk to be excluded from backup. The info contained here: 1. should be enough to identify the disk during the backup job. 2. is a sub... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class VmwareDiskExclusionProto:
"""Implementation of the 'VmwareDiskExclusionProto' model. This message contains basic info of the disk to be excluded from backup. The info contained here: 1. should be enough to identify the disk during the backup job. 2. is a subset of the message fetched to be displa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VmwareDiskExclusionProto:
"""Implementation of the 'VmwareDiskExclusionProto' model. This message contains basic info of the disk to be excluded from backup. The info contained here: 1. should be enough to identify the disk during the backup job. 2. is a subset of the message fetched to be displayed to the en... | the_stack_v2_python_sparse | cohesity_management_sdk/models/vmware_disk_exclusion_proto.py | cohesity/management-sdk-python | train | 24 |
d05f400552ebf568250df561dea2196126921694 | [
"super().__init__()\nif weights.dim() != 1:\n raise ValueError('weights must be a one-dimensional tensor.')\nself.register_buffer('weights', weights)",
"if samples.shape[-1] != self.weights.shape[-1]:\n raise RuntimeError('Output shape of samples not equal to that of weights')\nreturn torch.einsum('...m, m'... | <|body_start_0|>
super().__init__()
if weights.dim() != 1:
raise ValueError('weights must be a one-dimensional tensor.')
self.register_buffer('weights', weights)
<|end_body_0|>
<|body_start_1|>
if samples.shape[-1] != self.weights.shape[-1]:
raise RuntimeError('O... | Linear objective constructed from a weight tensor. For input `samples` and `mc_obj = LinearMCObjective(weights)`, this produces `mc_obj(samples) = sum_{i} weights[i] * samples[..., i]` Example: Example for a model with two outcomes: >>> weights = torch.tensor([0.75, 0.25]) >>> linear_objective = LinearMCObjective(weigh... | LinearMCObjective | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearMCObjective:
"""Linear objective constructed from a weight tensor. For input `samples` and `mc_obj = LinearMCObjective(weights)`, this produces `mc_obj(samples) = sum_{i} weights[i] * samples[..., i]` Example: Example for a model with two outcomes: >>> weights = torch.tensor([0.75, 0.25]) >... | stack_v2_sparse_classes_36k_train_028138 | 22,827 | permissive | [
{
"docstring": "Args: weights: A one-dimensional tensor with `m` elements representing the linear weights on the outputs.",
"name": "__init__",
"signature": "def __init__(self, weights: Tensor) -> None"
},
{
"docstring": "Evaluate the linear objective on the samples. Args: samples: A `sample_sha... | 2 | stack_v2_sparse_classes_30k_train_019256 | Implement the Python class `LinearMCObjective` described below.
Class description:
Linear objective constructed from a weight tensor. For input `samples` and `mc_obj = LinearMCObjective(weights)`, this produces `mc_obj(samples) = sum_{i} weights[i] * samples[..., i]` Example: Example for a model with two outcomes: >>>... | Implement the Python class `LinearMCObjective` described below.
Class description:
Linear objective constructed from a weight tensor. For input `samples` and `mc_obj = LinearMCObjective(weights)`, this produces `mc_obj(samples) = sum_{i} weights[i] * samples[..., i]` Example: Example for a model with two outcomes: >>>... | 4cc5ed59b2e8a9c780f786830c548e05cc74d53c | <|skeleton|>
class LinearMCObjective:
"""Linear objective constructed from a weight tensor. For input `samples` and `mc_obj = LinearMCObjective(weights)`, this produces `mc_obj(samples) = sum_{i} weights[i] * samples[..., i]` Example: Example for a model with two outcomes: >>> weights = torch.tensor([0.75, 0.25]) >... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinearMCObjective:
"""Linear objective constructed from a weight tensor. For input `samples` and `mc_obj = LinearMCObjective(weights)`, this produces `mc_obj(samples) = sum_{i} weights[i] * samples[..., i]` Example: Example for a model with two outcomes: >>> weights = torch.tensor([0.75, 0.25]) >>> linear_obj... | the_stack_v2_python_sparse | botorch/acquisition/objective.py | pytorch/botorch | train | 2,891 |
726ca9d290e827e770b872e0d7ebd50aefe8cc21 | [
"population_size = 4\nnumber_universe = 1\nfactory = Factory_SimGAN_ECG\nmpi = False\ngenome_seeds = [['misc/IndivSeed_SimGAN_Seed0/RefinerBlock_lisp.txt', 'misc/IndivSeed_SimGAN_Seed0/DiscriminatorBlock_lisp.txt', 'misc/IndivSeed_SimGAN_ECG_Seed0/ConfigBlock_lisp.txt']] * population_size\nhall_of_fame_flag = True\... | <|body_start_0|>
population_size = 4
number_universe = 1
factory = Factory_SimGAN_ECG
mpi = False
genome_seeds = [['misc/IndivSeed_SimGAN_Seed0/RefinerBlock_lisp.txt', 'misc/IndivSeed_SimGAN_Seed0/DiscriminatorBlock_lisp.txt', 'misc/IndivSeed_SimGAN_ECG_Seed0/ConfigBlock_lisp.txt... | Problem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Problem:
def __init__(self):
"""not gonna init problem_simgan.Problem since we want our genome and block defs to be a little different"""
<|body_0|>
def construct_dataset(self):
"""Constructs a train and validation 1D signal datasets"""
<|body_1|>
def ch... | stack_v2_sparse_classes_36k_train_028139 | 6,254 | permissive | [
{
"docstring": "not gonna init problem_simgan.Problem since we want our genome and block defs to be a little different",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Constructs a train and validation 1D signal datasets",
"name": "construct_dataset",
"signature... | 3 | stack_v2_sparse_classes_30k_train_007199 | Implement the Python class `Problem` described below.
Class description:
Implement the Problem class.
Method signatures and docstrings:
- def __init__(self): not gonna init problem_simgan.Problem since we want our genome and block defs to be a little different
- def construct_dataset(self): Constructs a train and val... | Implement the Python class `Problem` described below.
Class description:
Implement the Problem class.
Method signatures and docstrings:
- def __init__(self): not gonna init problem_simgan.Problem since we want our genome and block defs to be a little different
- def construct_dataset(self): Constructs a train and val... | a93df7ae91fd5905df368661b86ae653c3d08869 | <|skeleton|>
class Problem:
def __init__(self):
"""not gonna init problem_simgan.Problem since we want our genome and block defs to be a little different"""
<|body_0|>
def construct_dataset(self):
"""Constructs a train and validation 1D signal datasets"""
<|body_1|>
def ch... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Problem:
def __init__(self):
"""not gonna init problem_simgan.Problem since we want our genome and block defs to be a little different"""
population_size = 4
number_universe = 1
factory = Factory_SimGAN_ECG
mpi = False
genome_seeds = [['misc/IndivSeed_SimGAN_See... | the_stack_v2_python_sparse | problems/problem_simgan_ecg.py | ezCGP/ezCGP | train | 6 | |
dc9333cd7cff9e14d7759362999cfb8236c30d4e | [
"value = self.request.query_params.get(key, None)\nif value is None:\n value = self.request.data.get(key, None)\nif value is None:\n value = default\nreturn value",
"ordering = self.get_query_param('ordering', self.ordering)\nif not ordering:\n return search\nordering_field = ordering.lstrip('-')\nif ord... | <|body_start_0|>
value = self.request.query_params.get(key, None)
if value is None:
value = self.request.data.get(key, None)
if value is None:
value = default
return value
<|end_body_0|>
<|body_start_1|>
ordering = self.get_query_param('ordering', self.or... | Mixin to use Django REST Framework with ElasticSearch based querysets. This mixin adds following methods: * :func:`~ElasticSearchMixin.order_search` * :func:`~ElasticSearchMixin.filter_search` * :func:`~ElasticSearchMixin.filter_permissions` | ElasticSearchMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElasticSearchMixin:
"""Mixin to use Django REST Framework with ElasticSearch based querysets. This mixin adds following methods: * :func:`~ElasticSearchMixin.order_search` * :func:`~ElasticSearchMixin.filter_search` * :func:`~ElasticSearchMixin.filter_permissions`"""
def get_query_param(self... | stack_v2_sparse_classes_36k_train_028140 | 9,274 | permissive | [
{
"docstring": "Get query parameter uniformly for GET and POST requests.",
"name": "get_query_param",
"signature": "def get_query_param(self, key, default=None)"
},
{
"docstring": "Order given search by the ordering parameter given in request. :param search: ElasticSearch query object",
"nam... | 4 | stack_v2_sparse_classes_30k_train_016634 | Implement the Python class `ElasticSearchMixin` described below.
Class description:
Mixin to use Django REST Framework with ElasticSearch based querysets. This mixin adds following methods: * :func:`~ElasticSearchMixin.order_search` * :func:`~ElasticSearchMixin.filter_search` * :func:`~ElasticSearchMixin.filter_permis... | Implement the Python class `ElasticSearchMixin` described below.
Class description:
Mixin to use Django REST Framework with ElasticSearch based querysets. This mixin adds following methods: * :func:`~ElasticSearchMixin.order_search` * :func:`~ElasticSearchMixin.filter_search` * :func:`~ElasticSearchMixin.filter_permis... | 155f0bf51c30dbe8c3626bdd6c7a3dd44d7b27e3 | <|skeleton|>
class ElasticSearchMixin:
"""Mixin to use Django REST Framework with ElasticSearch based querysets. This mixin adds following methods: * :func:`~ElasticSearchMixin.order_search` * :func:`~ElasticSearchMixin.filter_search` * :func:`~ElasticSearchMixin.filter_permissions`"""
def get_query_param(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ElasticSearchMixin:
"""Mixin to use Django REST Framework with ElasticSearch based querysets. This mixin adds following methods: * :func:`~ElasticSearchMixin.order_search` * :func:`~ElasticSearchMixin.filter_search` * :func:`~ElasticSearchMixin.filter_permissions`"""
def get_query_param(self, key, defaul... | the_stack_v2_python_sparse | resolwe/elastic/viewsets.py | tristanbrown/resolwe | train | 0 |
e57a6304bc327d42064483e9b6290eeccd1752ba | [
"if context is None:\n context = {}\nres = super(exchange_partial_picking, self).default_get(cr, uid, fields, context=context)\nexchange_ids = context.get('active_ids', [])\nif not exchange_ids or not context.get('active_model') == 'exchange.order' or len(exchange_ids) != 1:\n return res\nexchange_id, = excha... | <|body_start_0|>
if context is None:
context = {}
res = super(exchange_partial_picking, self).default_get(cr, uid, fields, context=context)
exchange_ids = context.get('active_ids', [])
if not exchange_ids or not context.get('active_model') == 'exchange.order' or len(exchange_... | exchange_partial_picking | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class exchange_partial_picking:
def default_get(self, cr, uid, fields, context=None):
"""This function gets default values from the object @param fields: List of fields for which we want default values @return: A dictionary which of fields with values."""
<|body_0|>
def _partial_m... | stack_v2_sparse_classes_36k_train_028141 | 6,351 | no_license | [
{
"docstring": "This function gets default values from the object @param fields: List of fields for which we want default values @return: A dictionary which of fields with values.",
"name": "default_get",
"signature": "def default_get(self, cr, uid, fields, context=None)"
},
{
"docstring": "Used... | 3 | stack_v2_sparse_classes_30k_train_007605 | Implement the Python class `exchange_partial_picking` described below.
Class description:
Implement the exchange_partial_picking class.
Method signatures and docstrings:
- def default_get(self, cr, uid, fields, context=None): This function gets default values from the object @param fields: List of fields for which we... | Implement the Python class `exchange_partial_picking` described below.
Class description:
Implement the exchange_partial_picking class.
Method signatures and docstrings:
- def default_get(self, cr, uid, fields, context=None): This function gets default values from the object @param fields: List of fields for which we... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class exchange_partial_picking:
def default_get(self, cr, uid, fields, context=None):
"""This function gets default values from the object @param fields: List of fields for which we want default values @return: A dictionary which of fields with values."""
<|body_0|>
def _partial_m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class exchange_partial_picking:
def default_get(self, cr, uid, fields, context=None):
"""This function gets default values from the object @param fields: List of fields for which we want default values @return: A dictionary which of fields with values."""
if context is None:
context = {}... | the_stack_v2_python_sparse | v_7/Dongola/common/stock_exchange/wizard/exchange_partial_picking.py | musabahmed/baba | train | 0 | |
9ea6a21cb69bea2dde6d2504583fb38c175a5d65 | [
"for filename in self.changes.get_files():\n log.debug('Looking whether %s was actually uploaded' % filename)\n if os.path.isfile(os.path.join(config['debexpo.upload.incoming'], filename)):\n log.debug('%s is present' % filename)\n self.passed('file-is-present', filename, constants.PLUGIN_SEVERI... | <|body_start_0|>
for filename in self.changes.get_files():
log.debug('Looking whether %s was actually uploaded' % filename)
if os.path.isfile(os.path.join(config['debexpo.upload.incoming'], filename)):
log.debug('%s is present' % filename)
self.passed('fil... | CheckFilesPlugin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckFilesPlugin:
def test_files_present(self):
"""Check whether each file listed in the changes file is present."""
<|body_0|>
def test_md5sum(self):
"""Check each file's md5sum and make sure the md5sum in the changes file is the same as the actual file's md5sum."""... | stack_v2_sparse_classes_36k_train_028142 | 3,751 | no_license | [
{
"docstring": "Check whether each file listed in the changes file is present.",
"name": "test_files_present",
"signature": "def test_files_present(self)"
},
{
"docstring": "Check each file's md5sum and make sure the md5sum in the changes file is the same as the actual file's md5sum.",
"name... | 2 | stack_v2_sparse_classes_30k_train_014356 | Implement the Python class `CheckFilesPlugin` described below.
Class description:
Implement the CheckFilesPlugin class.
Method signatures and docstrings:
- def test_files_present(self): Check whether each file listed in the changes file is present.
- def test_md5sum(self): Check each file's md5sum and make sure the m... | Implement the Python class `CheckFilesPlugin` described below.
Class description:
Implement the CheckFilesPlugin class.
Method signatures and docstrings:
- def test_files_present(self): Check whether each file listed in the changes file is present.
- def test_md5sum(self): Check each file's md5sum and make sure the m... | 04c09606daca2fceccffaed0b9df777efad375bb | <|skeleton|>
class CheckFilesPlugin:
def test_files_present(self):
"""Check whether each file listed in the changes file is present."""
<|body_0|>
def test_md5sum(self):
"""Check each file's md5sum and make sure the md5sum in the changes file is the same as the actual file's md5sum."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CheckFilesPlugin:
def test_files_present(self):
"""Check whether each file listed in the changes file is present."""
for filename in self.changes.get_files():
log.debug('Looking whether %s was actually uploaded' % filename)
if os.path.isfile(os.path.join(config['debexpo... | the_stack_v2_python_sparse | debexpo/plugins/checkfiles.py | certik/debexpo | train | 1 | |
aaf7c34461cc0698fb7ba5dc26f5cac0d682ff3b | [
"assert system and system.getInstances() and gwAddress\nself.system = system\nself.gwAddress = gwAddress\nself.instancesCound = entity.WeakNumeric(int)\nself.instancesCound.set(instancesCount)\nself.serviceName = serviceName\nself.comment = comment",
"instanceNumber = self.system.getInstances()[0].getNumber()\nad... | <|body_start_0|>
assert system and system.getInstances() and gwAddress
self.system = system
self.gwAddress = gwAddress
self.instancesCound = entity.WeakNumeric(int)
self.instancesCound.set(instancesCount)
self.serviceName = serviceName
self.comment = comment
<|end... | @types: DOM for the ini file | RfcConfiguration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RfcConfiguration:
"""@types: DOM for the ini file"""
def __init__(self, system, gwAddress, instancesCount=None, serviceName=None, comment=None):
"""DOM for the one section in the TREXRfcServer.ini file and represents RFC connection from RFC Instance @param system: has at least one in... | stack_v2_sparse_classes_36k_train_028143 | 22,285 | no_license | [
{
"docstring": "DOM for the one section in the TREXRfcServer.ini file and represents RFC connection from RFC Instance @param system: has at least one instance @types: sap.System, str, int, str, str",
"name": "__init__",
"signature": "def __init__(self, system, gwAddress, instancesCount=None, serviceName... | 2 | null | Implement the Python class `RfcConfiguration` described below.
Class description:
@types: DOM for the ini file
Method signatures and docstrings:
- def __init__(self, system, gwAddress, instancesCount=None, serviceName=None, comment=None): DOM for the one section in the TREXRfcServer.ini file and represents RFC connec... | Implement the Python class `RfcConfiguration` described below.
Class description:
@types: DOM for the ini file
Method signatures and docstrings:
- def __init__(self, system, gwAddress, instancesCount=None, serviceName=None, comment=None): DOM for the one section in the TREXRfcServer.ini file and represents RFC connec... | c431e809e8d0f82e1bca7e3429dd0245560b5680 | <|skeleton|>
class RfcConfiguration:
"""@types: DOM for the ini file"""
def __init__(self, system, gwAddress, instancesCount=None, serviceName=None, comment=None):
"""DOM for the one section in the TREXRfcServer.ini file and represents RFC connection from RFC Instance @param system: has at least one in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RfcConfiguration:
"""@types: DOM for the ini file"""
def __init__(self, system, gwAddress, instancesCount=None, serviceName=None, comment=None):
"""DOM for the one section in the TREXRfcServer.ini file and represents RFC connection from RFC Instance @param system: has at least one instance @types... | the_stack_v2_python_sparse | reference/ucmdb/discovery/sap_trex_discoverer.py | madmonkyang/cda-record | train | 0 |
3def64a5ae20590dcdf83dad734b3f533e6f7016 | [
"self.f = f\nself.gp = GP(X_init, Y_init, l, sigma_f)\nac = ac_samples\nself.X_s = np.linspace(bounds[0], bounds[1], ac).reshape((ac, 1))\nself.xsi = xsi\nself.minimize = minimize",
"\"\"\"\n mu, sigma = self.gp.predict(self.X_s)\n if not self.minimize:\n X_next = np.amax(self.gp.Y)\n ... | <|body_start_0|>
self.f = f
self.gp = GP(X_init, Y_init, l, sigma_f)
ac = ac_samples
self.X_s = np.linspace(bounds[0], bounds[1], ac).reshape((ac, 1))
self.xsi = xsi
self.minimize = minimize
<|end_body_0|>
<|body_start_1|>
"""
mu, sigma = self.gp.... | 1d bayesaian gaussian process | BayesianOptimization | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BayesianOptimization:
"""1d bayesaian gaussian process"""
def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):
"""initializer f: black box function to be optimizd X_init: np arr (t, 1) of inputs already sample with blackblox f'n Y_init: ... | stack_v2_sparse_classes_36k_train_028144 | 4,345 | no_license | [
{
"docstring": "initializer f: black box function to be optimizd X_init: np arr (t, 1) of inputs already sample with blackblox f'n Y_init: np arr (t, 1) of outputs of BB f'n t: number of initial samples bounds: tuple of (min, max) of bounds of the space to look for optimal point ac_samples: number of samples to... | 3 | null | Implement the Python class `BayesianOptimization` described below.
Class description:
1d bayesaian gaussian process
Method signatures and docstrings:
- def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True): initializer f: black box function to be optimizd X_init: np arr (t... | Implement the Python class `BayesianOptimization` described below.
Class description:
1d bayesaian gaussian process
Method signatures and docstrings:
- def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True): initializer f: black box function to be optimizd X_init: np arr (t... | d86b0e0cae2dd07c761f84a493abc895007873ee | <|skeleton|>
class BayesianOptimization:
"""1d bayesaian gaussian process"""
def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):
"""initializer f: black box function to be optimizd X_init: np arr (t, 1) of inputs already sample with blackblox f'n Y_init: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BayesianOptimization:
"""1d bayesaian gaussian process"""
def __init__(self, f, X_init, Y_init, bounds, ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):
"""initializer f: black box function to be optimizd X_init: np arr (t, 1) of inputs already sample with blackblox f'n Y_init: np arr (t, 1)... | the_stack_v2_python_sparse | unsupervised_learning/0x03-hyperparameter_tuning/5-bayes_opt.py | mag389/holbertonschool-machine_learning | train | 2 |
b85b2cef95f3f2ca5f41259d76d1d881e0b404bf | [
"if orders_since is None:\n orders_since = timezone.now() - dt.timedelta(days=30)\nreturn Order.objects.filter(dispatched_at__gte=orders_since)",
"orders = self.get_recent_orders(orders_since).filter(linnworks_order__isnull=True)\nwait_time = 60\nfor i, order in enumerate(orders):\n try:\n guid = get... | <|body_start_0|>
if orders_since is None:
orders_since = timezone.now() - dt.timedelta(days=30)
return Order.objects.filter(dispatched_at__gte=orders_since)
<|end_body_0|>
<|body_start_1|>
orders = self.get_recent_orders(orders_since).filter(linnworks_order__isnull=True)
wai... | Model manager for the LinnworksOrder model. | LinnworksOrderManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinnworksOrderManager:
"""Model manager for the LinnworksOrder model."""
def get_recent_orders(self, orders_since=None):
"""Return orders dispatched after a datetime."""
<|body_0|>
def update_order_guids(self, orders_since=None):
"""Add Linnworks order GUIDs to r... | stack_v2_sparse_classes_36k_train_028145 | 12,307 | no_license | [
{
"docstring": "Return orders dispatched after a datetime.",
"name": "get_recent_orders",
"signature": "def get_recent_orders(self, orders_since=None)"
},
{
"docstring": "Add Linnworks order GUIDs to recent orders.",
"name": "update_order_guids",
"signature": "def update_order_guids(self... | 3 | stack_v2_sparse_classes_30k_train_006298 | Implement the Python class `LinnworksOrderManager` described below.
Class description:
Model manager for the LinnworksOrder model.
Method signatures and docstrings:
- def get_recent_orders(self, orders_since=None): Return orders dispatched after a datetime.
- def update_order_guids(self, orders_since=None): Add Linnw... | Implement the Python class `LinnworksOrderManager` described below.
Class description:
Model manager for the LinnworksOrder model.
Method signatures and docstrings:
- def get_recent_orders(self, orders_since=None): Return orders dispatched after a datetime.
- def update_order_guids(self, orders_since=None): Add Linnw... | ba51d4e304b1aeb296fa2fe16611c892fcdbd471 | <|skeleton|>
class LinnworksOrderManager:
"""Model manager for the LinnworksOrder model."""
def get_recent_orders(self, orders_since=None):
"""Return orders dispatched after a datetime."""
<|body_0|>
def update_order_guids(self, orders_since=None):
"""Add Linnworks order GUIDs to r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinnworksOrderManager:
"""Model manager for the LinnworksOrder model."""
def get_recent_orders(self, orders_since=None):
"""Return orders dispatched after a datetime."""
if orders_since is None:
orders_since = timezone.now() - dt.timedelta(days=30)
return Order.objects... | the_stack_v2_python_sparse | linnworks/models/orders.py | stcstores/stcadmin | train | 0 |
b9037bcc476f188d3c3aa0f4711c1f43f8baead4 | [
"super().__init__()\nself.in_chans = in_chans\nself.out_chans = out_chans\nself.chans = chans\nself.num_pool_layers = num_pool_layers\nself.drop_prob = drop_prob\nself.down_sample_layers = nn.ModuleList([Conv3dBlock(in_chans, chans, drop_prob)])\nch = chans\nfor _ in range(num_pool_layers - 1):\n self.down_sampl... | <|body_start_0|>
super().__init__()
self.in_chans = in_chans
self.out_chans = out_chans
self.chans = chans
self.num_pool_layers = num_pool_layers
self.drop_prob = drop_prob
self.down_sample_layers = nn.ModuleList([Conv3dBlock(in_chans, chans, drop_prob)])
... | Implementation of the 3D UNet, as presented in O. Ronneberger, P. Fischer, and Thomas Brox. References ---------- .. O. Ronneberger, P. Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assisted intervention, pa... | UNet3D | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UNet3D:
"""Implementation of the 3D UNet, as presented in O. Ronneberger, P. Fischer, and Thomas Brox. References ---------- .. O. Ronneberger, P. Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and ... | stack_v2_sparse_classes_36k_train_028146 | 5,686 | permissive | [
{
"docstring": "Parameters ---------- in_chans : int Number of input channels. out_chans : int Number of output channels. chans : int Number of output channels of the first convolutional layer. num_pool_layers : int Number of down-sampling and up-sampling layers. drop_prob : float Dropout probability. block : n... | 2 | stack_v2_sparse_classes_30k_test_000902 | Implement the Python class `UNet3D` described below.
Class description:
Implementation of the 3D UNet, as presented in O. Ronneberger, P. Fischer, and Thomas Brox. References ---------- .. O. Ronneberger, P. Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Con... | Implement the Python class `UNet3D` described below.
Class description:
Implementation of the 3D UNet, as presented in O. Ronneberger, P. Fischer, and Thomas Brox. References ---------- .. O. Ronneberger, P. Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Con... | 6d15dd55ca5ed6fc9fbfd31d8488ee7bab453066 | <|skeleton|>
class UNet3D:
"""Implementation of the 3D UNet, as presented in O. Ronneberger, P. Fischer, and Thomas Brox. References ---------- .. O. Ronneberger, P. Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UNet3D:
"""Implementation of the 3D UNet, as presented in O. Ronneberger, P. Fischer, and Thomas Brox. References ---------- .. O. Ronneberger, P. Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assi... | the_stack_v2_python_sparse | mridc/collections/segmentation/models/unet3d_base/unet3d_block.py | wdika/mridc | train | 40 |
897a5b25f1ee712c2048b3ec66837a56cdfc0bf5 | [
"pip_manager = PipManager.get_singleton()\npip_manager.install_pip(lazy=True, op=op)\nadd_command_line_sys_path()\ndependency_install_command = [_get_python_exe_path(), '-m', 'pip', 'install', '--no-cache-dir', self.package_name]\nlog_report('INFO', f'Installing dependency with {dependency_install_command}', op)\ns... | <|body_start_0|>
pip_manager = PipManager.get_singleton()
pip_manager.install_pip(lazy=True, op=op)
add_command_line_sys_path()
dependency_install_command = [_get_python_exe_path(), '-m', 'pip', 'install', '--no-cache-dir', self.package_name]
log_report('INFO', f'Installing depen... | Class that describes an optional Python dependency of the addon. | OptionalDependency | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptionalDependency:
"""Class that describes an optional Python dependency of the addon."""
def install(self, op=None):
"""Install this dependency."""
<|body_0|>
def uninstall(self, remove_sys_path=True, op=None):
"""Uninstall this dependency."""
<|body_1|... | stack_v2_sparse_classes_36k_train_028147 | 14,831 | permissive | [
{
"docstring": "Install this dependency.",
"name": "install",
"signature": "def install(self, op=None)"
},
{
"docstring": "Uninstall this dependency.",
"name": "uninstall",
"signature": "def uninstall(self, remove_sys_path=True, op=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009437 | Implement the Python class `OptionalDependency` described below.
Class description:
Class that describes an optional Python dependency of the addon.
Method signatures and docstrings:
- def install(self, op=None): Install this dependency.
- def uninstall(self, remove_sys_path=True, op=None): Uninstall this dependency. | Implement the Python class `OptionalDependency` described below.
Class description:
Class that describes an optional Python dependency of the addon.
Method signatures and docstrings:
- def install(self, op=None): Install this dependency.
- def uninstall(self, remove_sys_path=True, op=None): Uninstall this dependency.... | da404ebf8d4412196c2740f0b569cbf9e542952d | <|skeleton|>
class OptionalDependency:
"""Class that describes an optional Python dependency of the addon."""
def install(self, op=None):
"""Install this dependency."""
<|body_0|>
def uninstall(self, remove_sys_path=True, op=None):
"""Uninstall this dependency."""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OptionalDependency:
"""Class that describes an optional Python dependency of the addon."""
def install(self, op=None):
"""Install this dependency."""
pip_manager = PipManager.get_singleton()
pip_manager.install_pip(lazy=True, op=op)
add_command_line_sys_path()
depe... | the_stack_v2_python_sparse | photogrammetry_importer/preferences/dependency.py | SBCV/Blender-Addon-Photogrammetry-Importer | train | 718 |
b4911d470ac28e11dd1963eaa87a8863864fd6d8 | [
"if not isinstance(data, dict):\n raise ValueError('Data needs to be a dictionary.')\nreturn json.dumps(data)",
"dict_value = json.loads(data)\nif not isinstance(dict_value, dict):\n raise ValueError(\"Unable to read in the data, it's not stored as a dictionary\")\nreturn dict_value"
] | <|body_start_0|>
if not isinstance(data, dict):
raise ValueError('Data needs to be a dictionary.')
return json.dumps(data)
<|end_body_0|>
<|body_start_1|>
dict_value = json.loads(data)
if not isinstance(dict_value, dict):
raise ValueError("Unable to read in the d... | Implements the ontology for dict structures. | DictOntology | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DictOntology:
"""Implements the ontology for dict structures."""
def encode(data):
"""Returns an encoded string that can be stored in the database. Raises: ValueError: If the value is not a dict."""
<|body_0|>
def decode(data):
"""Returns a dict object from the s... | stack_v2_sparse_classes_36k_train_028148 | 5,323 | permissive | [
{
"docstring": "Returns an encoded string that can be stored in the database. Raises: ValueError: If the value is not a dict.",
"name": "encode",
"signature": "def encode(data)"
},
{
"docstring": "Returns a dict object from the stored string in the database.",
"name": "decode",
"signatur... | 2 | null | Implement the Python class `DictOntology` described below.
Class description:
Implements the ontology for dict structures.
Method signatures and docstrings:
- def encode(data): Returns an encoded string that can be stored in the database. Raises: ValueError: If the value is not a dict.
- def decode(data): Returns a d... | Implement the Python class `DictOntology` described below.
Class description:
Implements the ontology for dict structures.
Method signatures and docstrings:
- def encode(data): Returns an encoded string that can be stored in the database. Raises: ValueError: If the value is not a dict.
- def decode(data): Returns a d... | 24f471b58ca4a87cb053961b5f05c07a544ca7b8 | <|skeleton|>
class DictOntology:
"""Implements the ontology for dict structures."""
def encode(data):
"""Returns an encoded string that can be stored in the database. Raises: ValueError: If the value is not a dict."""
<|body_0|>
def decode(data):
"""Returns a dict object from the s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DictOntology:
"""Implements the ontology for dict structures."""
def encode(data):
"""Returns an encoded string that can be stored in the database. Raises: ValueError: If the value is not a dict."""
if not isinstance(data, dict):
raise ValueError('Data needs to be a dictionary... | the_stack_v2_python_sparse | timesketch/lib/ontology.py | google/timesketch | train | 2,263 |
fdc440a4b8096fecd15c0a7680fd1f4ae08bd924 | [
"if not root:\n return root\nif p == root or q == root:\n return root\nleft = self.lowestCommonAncestor(root.left, p, q)\nright = self.lowestCommonAncestor(root.right, p, q)\nif left and right:\n return root\nif not left and (not right):\n return None\nif not left:\n return right\nreturn left",
"if... | <|body_start_0|>
if not root:
return root
if p == root or q == root:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left and right:
return root
if not left and (not r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode :没有利用二叉搜索树的性质"""
<|body_0|>
def lowestCommonAncestor2(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rt... | stack_v2_sparse_classes_36k_train_028149 | 2,274 | no_license | [
{
"docstring": ":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode :没有利用二叉搜索树的性质",
"name": "lowestCommonAncestor",
"signature": "def lowestCommonAncestor(self, root, p, q)"
},
{
"docstring": ":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode :二叉搜索树的... | 3 | stack_v2_sparse_classes_30k_train_000681 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root, p, q): :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode :没有利用二叉搜索树的性质
- def lowestCommonAncestor2(self, root, p, q):... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root, p, q): :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode :没有利用二叉搜索树的性质
- def lowestCommonAncestor2(self, root, p, q):... | 6e18c5d257840489cc3fb1079ae3804c743982a4 | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode :没有利用二叉搜索树的性质"""
<|body_0|>
def lowestCommonAncestor2(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode :没有利用二叉搜索树的性质"""
if not root:
return root
if p == root or q == root:
return root
left = self.lowestCommonAncestor(root.left... | the_stack_v2_python_sparse | out/production/leetcode/235.二叉搜索树的最近公共祖先.py | yangyuxiang1996/leetcode | train | 0 | |
ef695b9614f0863793acb548a2cfa85e79a6c865 | [
"Algorithm.__init__(self)\nself.name = 'Edge attribute filter'\nself.parent = 'Graph filtering'\nself.attribute = DropDown('Attribute', {'width', 'length'})\nself.drop_downs.append(self.attribute)\nself.attribute_threshold_value = FloatSlider('Attribute treshold', 0.0, 20.0, 0.1, 10.0)\nself.float_sliders.append(se... | <|body_start_0|>
Algorithm.__init__(self)
self.name = 'Edge attribute filter'
self.parent = 'Graph filtering'
self.attribute = DropDown('Attribute', {'width', 'length'})
self.drop_downs.append(self.attribute)
self.attribute_threshold_value = FloatSlider('Attribute treshol... | Edge attribute filter algorithm implementation | AlgBody | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlgBody:
"""Edge attribute filter algorithm implementation"""
def __init__(self):
"""Edge attribute object constructor Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriated category | *attribute* : A valid edge attribute present in the graph. | *attrib... | stack_v2_sparse_classes_36k_train_028150 | 3,328 | permissive | [
{
"docstring": "Edge attribute object constructor Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriated category | *attribute* : A valid edge attribute present in the graph. | *attribute_threshold_value* : A threshold value for the given attribute | *operator* : A logical python ... | 2 | stack_v2_sparse_classes_30k_train_014294 | Implement the Python class `AlgBody` described below.
Class description:
Edge attribute filter algorithm implementation
Method signatures and docstrings:
- def __init__(self): Edge attribute object constructor Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriated category | *attribute*... | Implement the Python class `AlgBody` described below.
Class description:
Edge attribute filter algorithm implementation
Method signatures and docstrings:
- def __init__(self): Edge attribute object constructor Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriated category | *attribute*... | 0dc9becc09da22af3edac90b81b1dd9b1f44fd5b | <|skeleton|>
class AlgBody:
"""Edge attribute filter algorithm implementation"""
def __init__(self):
"""Edge attribute object constructor Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriated category | *attribute* : A valid edge attribute present in the graph. | *attrib... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlgBody:
"""Edge attribute filter algorithm implementation"""
def __init__(self):
"""Edge attribute object constructor Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriated category | *attribute* : A valid edge attribute present in the graph. | *attribute_threshold... | the_stack_v2_python_sparse | nefi2/model/algorithms/edge_attribute_filter.py | andreasfirczynski/NetworkExtractionFromImages | train | 0 |
8540fa794627a633dea438101ce73b94384f7635 | [
"if not root:\n return '[]'\nres, queue = ([], [])\nqueue.append(root)\nwhile queue:\n node: TreeNode = queue.pop(0)\n if node:\n queue.append(node.left)\n queue.append(node.right)\n res.append(str(node.val))\n else:\n res.append('None')\nreturn ','.join(res)",
"if data == ... | <|body_start_0|>
if not root:
return '[]'
res, queue = ([], [])
queue.append(root)
while queue:
node: TreeNode = queue.pop(0)
if node:
queue.append(node.left)
queue.append(node.right)
res.append(str(node.... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_028151 | 1,673 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_val_001167 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 97bd0712ca820034bfe3ab6b61c8070b67c3cac9 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return '[]'
res, queue = ([], [])
queue.append(root)
while queue:
node: TreeNode = queue.pop(0)
if node:
... | the_stack_v2_python_sparse | algorithm_questions/LeetCode/剑指Offer/37序列化二叉树.py | SaItFish/PySundries | train | 0 | |
6d50eec95ab9d007acff606ca3fb77acac5ec6bf | [
"if self._errors:\n return\nuser = authenticate(username=self.cleaned_data['username'].lower(), password=self.cleaned_data['password'])\nif user:\n if user.is_active:\n self.user = user\n else:\n raise forms.ValidationError('This account is currently inactive.')\nelse:\n raise forms.Valida... | <|body_start_0|>
if self._errors:
return
user = authenticate(username=self.cleaned_data['username'].lower(), password=self.cleaned_data['password'])
if user:
if user.is_active:
self.user = user
else:
raise forms.ValidationError(... | Django-backed login form for normal authentication. | LoginForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoginForm:
"""Django-backed login form for normal authentication."""
def clean(self):
"""Validates the login form."""
<|body_0|>
def login(self, request):
"""Logs the user in."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if self._errors:
... | stack_v2_sparse_classes_36k_train_028152 | 1,209 | permissive | [
{
"docstring": "Validates the login form.",
"name": "clean",
"signature": "def clean(self)"
},
{
"docstring": "Logs the user in.",
"name": "login",
"signature": "def login(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014690 | Implement the Python class `LoginForm` described below.
Class description:
Django-backed login form for normal authentication.
Method signatures and docstrings:
- def clean(self): Validates the login form.
- def login(self, request): Logs the user in. | Implement the Python class `LoginForm` described below.
Class description:
Django-backed login form for normal authentication.
Method signatures and docstrings:
- def clean(self): Validates the login form.
- def login(self, request): Logs the user in.
<|skeleton|>
class LoginForm:
"""Django-backed login form for... | 4b7dd685012ec64758affe0ecee3103596d16aa7 | <|skeleton|>
class LoginForm:
"""Django-backed login form for normal authentication."""
def clean(self):
"""Validates the login form."""
<|body_0|>
def login(self, request):
"""Logs the user in."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoginForm:
"""Django-backed login form for normal authentication."""
def clean(self):
"""Validates the login form."""
if self._errors:
return
user = authenticate(username=self.cleaned_data['username'].lower(), password=self.cleaned_data['password'])
if user:
... | the_stack_v2_python_sparse | makahiki/apps/managers/auth_mgr/forms.py | justinslee/Wai-Not-Makahiki | train | 1 |
4d0009d949d754816d61d31782da11b8b1344c53 | [
"@lru_cache(None)\ndef dfs(cur: int) -> int:\n res = 0\n for next in adjList[cur]:\n res = max(res, dfs(next))\n return res + 1\nreturn max((dfs(i) for i in range(len(adjList)))) - 1",
"n = len(adjList)\ndeg = [0] * n\nfor i in range(n):\n for j in adjList[i]:\n deg[j] += 1\nqueue = dequ... | <|body_start_0|>
@lru_cache(None)
def dfs(cur: int) -> int:
res = 0
for next in adjList[cur]:
res = max(res, dfs(next))
return res + 1
return max((dfs(i) for i in range(len(adjList)))) - 1
<|end_body_0|>
<|body_start_1|>
n = len(adjLis... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def solve(self, adjList: List[List[int]]) -> int:
"""DAG中最长路径只和当前位置有关"""
<|body_0|>
def solve2(self, adjList: List[List[int]]) -> int:
"""DAG中最长路径只和当前位置有关"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
@lru_cache(None)
def dfs(cur... | stack_v2_sparse_classes_36k_train_028153 | 1,503 | no_license | [
{
"docstring": "DAG中最长路径只和当前位置有关",
"name": "solve",
"signature": "def solve(self, adjList: List[List[int]]) -> int"
},
{
"docstring": "DAG中最长路径只和当前位置有关",
"name": "solve2",
"signature": "def solve2(self, adjList: List[List[int]]) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_011362 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def solve(self, adjList: List[List[int]]) -> int: DAG中最长路径只和当前位置有关
- def solve2(self, adjList: List[List[int]]) -> int: DAG中最长路径只和当前位置有关 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def solve(self, adjList: List[List[int]]) -> int: DAG中最长路径只和当前位置有关
- def solve2(self, adjList: List[List[int]]) -> int: DAG中最长路径只和当前位置有关
<|skeleton|>
class Solution:
def so... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def solve(self, adjList: List[List[int]]) -> int:
"""DAG中最长路径只和当前位置有关"""
<|body_0|>
def solve2(self, adjList: List[List[int]]) -> int:
"""DAG中最长路径只和当前位置有关"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def solve(self, adjList: List[List[int]]) -> int:
"""DAG中最长路径只和当前位置有关"""
@lru_cache(None)
def dfs(cur: int) -> int:
res = 0
for next in adjList[cur]:
res = max(res, dfs(next))
return res + 1
return max((dfs(i) for i ... | the_stack_v2_python_sparse | 7_graph/拓扑排序/DAG最长路/DAG中的最长路径.py | 981377660LMT/algorithm-study | train | 225 | |
afa42a0f4ca01d58d50440f995bc1c52c7b0d3c0 | [
"self.open(base_url + '/logout')\nself.open(base_url + '/register')\nself.type('#email', test_user.email)\nself.type('#name', 'te')\nself.type('#password', test_user.password)\nself.type('#password2', test_user.password)\nself.click('input[type=\"submit\"]')\nself.assert_element('h1')\nself.assert_text('Log In', 'h... | <|body_start_0|>
self.open(base_url + '/logout')
self.open(base_url + '/register')
self.type('#email', test_user.email)
self.type('#name', 'te')
self.type('#password', test_user.password)
self.type('#password2', test_user.password)
self.click('input[type="submit"]... | FrontEndRegistrationR8 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FrontEndRegistrationR8:
def test_userNameTooShort(self, *_):
"""This function tests that the user registration fails and an error message is returned if the name entered is 2 characters or shorter"""
<|body_0|>
def test_userNameTooLong(self, *_):
"""This function tes... | stack_v2_sparse_classes_36k_train_028154 | 3,988 | permissive | [
{
"docstring": "This function tests that the user registration fails and an error message is returned if the name entered is 2 characters or shorter",
"name": "test_userNameTooShort",
"signature": "def test_userNameTooShort(self, *_)"
},
{
"docstring": "This function tests that the user registra... | 2 | stack_v2_sparse_classes_30k_train_021174 | Implement the Python class `FrontEndRegistrationR8` described below.
Class description:
Implement the FrontEndRegistrationR8 class.
Method signatures and docstrings:
- def test_userNameTooShort(self, *_): This function tests that the user registration fails and an error message is returned if the name entered is 2 ch... | Implement the Python class `FrontEndRegistrationR8` described below.
Class description:
Implement the FrontEndRegistrationR8 class.
Method signatures and docstrings:
- def test_userNameTooShort(self, *_): This function tests that the user registration fails and an error message is returned if the name entered is 2 ch... | 582e00a4c16016e545fedcbb14a745d125db94e0 | <|skeleton|>
class FrontEndRegistrationR8:
def test_userNameTooShort(self, *_):
"""This function tests that the user registration fails and an error message is returned if the name entered is 2 characters or shorter"""
<|body_0|>
def test_userNameTooLong(self, *_):
"""This function tes... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FrontEndRegistrationR8:
def test_userNameTooShort(self, *_):
"""This function tests that the user registration fails and an error message is returned if the name entered is 2 characters or shorter"""
self.open(base_url + '/logout')
self.open(base_url + '/register')
self.type('#... | the_stack_v2_python_sparse | qa327_test/frontend/registration/test_28.py | GraemeBadley/QA-Project | train | 0 | |
62f2c8ed228d5e031079097b1590f017fc53f44e | [
"self.logger = ServerLogger(__name__, debug=debug)\nif ip_list:\n self.ip = ip_list\nelse:\n self.ip = []\nif status_code:\n self.status_code = [int(status) for status in status_code]\nelse:\n self.status_code = []\nself.logged_IP = list()",
"for ip in data.keys():\n if ip in self.ip:\n if i... | <|body_start_0|>
self.logger = ServerLogger(__name__, debug=debug)
if ip_list:
self.ip = ip_list
else:
self.ip = []
if status_code:
self.status_code = [int(status) for status in status_code]
else:
self.status_code = []
self.... | UserFilter class. | UserFilter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserFilter:
"""UserFilter class."""
def __init__(self, debug=False, ip_list=None, status_code=None):
"""Initialize UserFilter. Args: debug (bool): Log on terminal or not ip_list (list): List of IPs to filter / grab of the log file status_code (list): List of status code to filter / g... | stack_v2_sparse_classes_36k_train_028155 | 3,678 | permissive | [
{
"docstring": "Initialize UserFilter. Args: debug (bool): Log on terminal or not ip_list (list): List of IPs to filter / grab of the log file status_code (list): List of status code to filter / grab of the log file Raises: None Returns: None",
"name": "__init__",
"signature": "def __init__(self, debug=... | 3 | stack_v2_sparse_classes_30k_train_020404 | Implement the Python class `UserFilter` described below.
Class description:
UserFilter class.
Method signatures and docstrings:
- def __init__(self, debug=False, ip_list=None, status_code=None): Initialize UserFilter. Args: debug (bool): Log on terminal or not ip_list (list): List of IPs to filter / grab of the log f... | Implement the Python class `UserFilter` described below.
Class description:
UserFilter class.
Method signatures and docstrings:
- def __init__(self, debug=False, ip_list=None, status_code=None): Initialize UserFilter. Args: debug (bool): Log on terminal or not ip_list (list): List of IPs to filter / grab of the log f... | 43dec187e5848b9ced8a6b4957b6e9028d4d43cd | <|skeleton|>
class UserFilter:
"""UserFilter class."""
def __init__(self, debug=False, ip_list=None, status_code=None):
"""Initialize UserFilter. Args: debug (bool): Log on terminal or not ip_list (list): List of IPs to filter / grab of the log file status_code (list): List of status code to filter / g... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserFilter:
"""UserFilter class."""
def __init__(self, debug=False, ip_list=None, status_code=None):
"""Initialize UserFilter. Args: debug (bool): Log on terminal or not ip_list (list): List of IPs to filter / grab of the log file status_code (list): List of status code to filter / grab of the lo... | the_stack_v2_python_sparse | securetea/lib/log_monitor/server_log/user_filter.py | rejahrehim/SecureTea-Project | train | 1 |
770b6bbf4b2911f02e3b2f36f056590d4e68f35a | [
"if not prices:\n return 0\nprofit = 0\nfor i in range(len(prices[:-1])):\n if prices[i] < prices[i + 1]:\n profit += prices[i + 1] - prices[i]\nreturn profit",
"if not prices:\n return 0\nhave_bought = False\nbuy_in_price = prices[0]\nprofit = 0\nfor price in prices[1:]:\n tmp = price - buy_in... | <|body_start_0|>
if not prices:
return 0
profit = 0
for i in range(len(prices[:-1])):
if prices[i] < prices[i + 1]:
profit += prices[i + 1] - prices[i]
return profit
<|end_body_0|>
<|body_start_1|>
if not prices:
return 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfitOld(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not prices:
return 0
... | stack_v2_sparse_classes_36k_train_028156 | 954 | no_license | [
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, prices)"
},
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfitOld",
"signature": "def maxProfitOld(self, prices)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfitOld(self, prices): :type prices: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfitOld(self, prices): :type prices: List[int] :rtype: int
<|skeleton|>
class Solution:
def maxP... | ac53dd9bf2c4c9d17c9dc5f7fdda32e386658fdd | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfitOld(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
if not prices:
return 0
profit = 0
for i in range(len(prices[:-1])):
if prices[i] < prices[i + 1]:
profit += prices[i + 1] - prices[i]
return profit
... | the_stack_v2_python_sparse | cs_notes/greedy/best_time_to_buy_and_sell_stock_ii.py | hwc1824/LeetCodeSolution | train | 0 | |
eeeab85448750279fd10a2b8407768446a4e0473 | [
"self.reponame = os.environ['reponame']\nself.model = os.environ['model']\nself.qa_model_name = os.environ['qa_yaml_name']\nself.rd_model_name = os.environ['rd_yaml_path']\nself.log_dir = 'logs'\nself.log_name = 'train_prim_single.log'\nself.log_path = os.path.join(os.getcwd(), self.log_dir, self.reponame, self.qa_... | <|body_start_0|>
self.reponame = os.environ['reponame']
self.model = os.environ['model']
self.qa_model_name = os.environ['qa_yaml_name']
self.rd_model_name = os.environ['rd_yaml_path']
self.log_dir = 'logs'
self.log_name = 'train_prim_single.log'
self.log_path = o... | case执行结束后 | PaddleDetection_End | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PaddleDetection_End:
"""case执行结束后"""
def __init__(self):
"""初始化"""
<|body_0|>
def build_end(self):
"""执行准备过程"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.reponame = os.environ['reponame']
self.model = os.environ['model']
... | stack_v2_sparse_classes_36k_train_028157 | 1,679 | no_license | [
{
"docstring": "初始化",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "执行准备过程",
"name": "build_end",
"signature": "def build_end(self)"
}
] | 2 | null | Implement the Python class `PaddleDetection_End` described below.
Class description:
case执行结束后
Method signatures and docstrings:
- def __init__(self): 初始化
- def build_end(self): 执行准备过程 | Implement the Python class `PaddleDetection_End` described below.
Class description:
case执行结束后
Method signatures and docstrings:
- def __init__(self): 初始化
- def build_end(self): 执行准备过程
<|skeleton|>
class PaddleDetection_End:
"""case执行结束后"""
def __init__(self):
"""初始化"""
<|body_0|>
def b... | bd3790ce72a2a26611b5eda3901651b5a809348f | <|skeleton|>
class PaddleDetection_End:
"""case执行结束后"""
def __init__(self):
"""初始化"""
<|body_0|>
def build_end(self):
"""执行准备过程"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PaddleDetection_End:
"""case执行结束后"""
def __init__(self):
"""初始化"""
self.reponame = os.environ['reponame']
self.model = os.environ['model']
self.qa_model_name = os.environ['qa_yaml_name']
self.rd_model_name = os.environ['rd_yaml_path']
self.log_dir = 'logs'
... | the_stack_v2_python_sparse | models_restruct/PaddleDetection/tools/end.py | PaddlePaddle/PaddleTest | train | 42 |
0c7a1a5b96126d09e5945b798b8f16a5c95957cd | [
"super().__init__(*args, **kwargs)\nself.command_q = command_q\nself.signal_q = signal_q\nself.sphere_args = sphere_args\nself.fname = fname\nself.file_lock = file_lock",
"try:\n self._main()\nexcept:\n print('-' * 60)\n traceback.print_exc()\n print('-' * 60)",
"sphere = EwaldSphere(data_file=self.... | <|body_start_0|>
super().__init__(*args, **kwargs)
self.command_q = command_q
self.signal_q = signal_q
self.sphere_args = sphere_args
self.fname = fname
self.file_lock = file_lock
<|end_body_0|>
<|body_start_1|>
try:
self._main()
except:
... | Base class for wrangler processes. Subclasses should extend _main, NOT run. _main is run in a try except clause which ensures errors are printed. attributes: command_q: mp.Queue, queue for commands from parent thread. file_lock: mp.Condition, process safe lock for file access fname: str, path to data file signal_q: que... | wranglerProcess | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class wranglerProcess:
"""Base class for wrangler processes. Subclasses should extend _main, NOT run. _main is run in a try except clause which ensures errors are printed. attributes: command_q: mp.Queue, queue for commands from parent thread. file_lock: mp.Condition, process safe lock for file access ... | stack_v2_sparse_classes_36k_train_028158 | 8,377 | no_license | [
{
"docstring": "command_q: mp.Queue, queue for commands from parent thread. signal_q: queue to place signals back to parent thread. sphere_args: dict, used as **kwargs in sphere initialization. see EwaldSphere. fname: str, path to data file file_lock: mp.Condition, process safe lock for file access",
"name"... | 3 | stack_v2_sparse_classes_30k_train_015510 | Implement the Python class `wranglerProcess` described below.
Class description:
Base class for wrangler processes. Subclasses should extend _main, NOT run. _main is run in a try except clause which ensures errors are printed. attributes: command_q: mp.Queue, queue for commands from parent thread. file_lock: mp.Condit... | Implement the Python class `wranglerProcess` described below.
Class description:
Base class for wrangler processes. Subclasses should extend _main, NOT run. _main is run in a try except clause which ensures errors are printed. attributes: command_q: mp.Queue, queue for commands from parent thread. file_lock: mp.Condit... | f145e757d092d85b5a21dc4c36d99f82d55f7037 | <|skeleton|>
class wranglerProcess:
"""Base class for wrangler processes. Subclasses should extend _main, NOT run. _main is run in a try except clause which ensures errors are printed. attributes: command_q: mp.Queue, queue for commands from parent thread. file_lock: mp.Condition, process safe lock for file access ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class wranglerProcess:
"""Base class for wrangler processes. Subclasses should extend _main, NOT run. _main is run in a try except clause which ensures errors are printed. attributes: command_q: mp.Queue, queue for commands from parent thread. file_lock: mp.Condition, process safe lock for file access fname: str, p... | the_stack_v2_python_sparse | xdart/gui/tabs/static_scan/wranglers/wrangler_widget.py | rwalroth/xdart | train | 2 |
17cac41953736f6bb8cf9a20d06f6cf80a705990 | [
"if 'model' in blend_coord and model_id_attr is None:\n raise ValueError('model_id_attr required to blend over {}'.format(blend_coord))\nif 'model' not in blend_coord and model_id_attr is not None:\n warnings.warn('model_id_attr not required for blending over {} - will be ignored'.format(blend_coord))\n mo... | <|body_start_0|>
if 'model' in blend_coord and model_id_attr is None:
raise ValueError('model_id_attr required to blend over {}'.format(blend_coord))
if 'model' not in blend_coord and model_id_attr is not None:
warnings.warn('model_id_attr not required for blending over {} - will... | Prepares cubes for cycle and grid blending | MergeCubesForWeightedBlending | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MergeCubesForWeightedBlending:
"""Prepares cubes for cycle and grid blending"""
def __init__(self, blend_coord, weighting_coord=None, model_id_attr=None):
"""Initialise the class Args: blend_coord (str): Name of coordinate over which blending will be performed. For multi-model blendi... | stack_v2_sparse_classes_36k_train_028159 | 40,273 | permissive | [
{
"docstring": "Initialise the class Args: blend_coord (str): Name of coordinate over which blending will be performed. For multi-model blending this is flexible to any string containing \"model\". For all other coordinates this is prescriptive: cube.coord(blend_coord) must return an iris.coords.Coord instance ... | 4 | stack_v2_sparse_classes_30k_train_013668 | Implement the Python class `MergeCubesForWeightedBlending` described below.
Class description:
Prepares cubes for cycle and grid blending
Method signatures and docstrings:
- def __init__(self, blend_coord, weighting_coord=None, model_id_attr=None): Initialise the class Args: blend_coord (str): Name of coordinate over... | Implement the Python class `MergeCubesForWeightedBlending` described below.
Class description:
Prepares cubes for cycle and grid blending
Method signatures and docstrings:
- def __init__(self, blend_coord, weighting_coord=None, model_id_attr=None): Initialise the class Args: blend_coord (str): Name of coordinate over... | 74b7bc0d194c30ea7af426d153e5047ccb67f60c | <|skeleton|>
class MergeCubesForWeightedBlending:
"""Prepares cubes for cycle and grid blending"""
def __init__(self, blend_coord, weighting_coord=None, model_id_attr=None):
"""Initialise the class Args: blend_coord (str): Name of coordinate over which blending will be performed. For multi-model blendi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MergeCubesForWeightedBlending:
"""Prepares cubes for cycle and grid blending"""
def __init__(self, blend_coord, weighting_coord=None, model_id_attr=None):
"""Initialise the class Args: blend_coord (str): Name of coordinate over which blending will be performed. For multi-model blending this is fl... | the_stack_v2_python_sparse | lib/improver/blending/weighted_blend.py | TomekTrzeciak/improver | train | 0 |
58f30b73c59ecb722a870efa5bf0ed312fabd444 | [
"rs1 = self.create(self.leader, 't', self.tid, self.pid, 144000, 2, 'true', card='string:index', merchant='string:index', amt='double')\nself.assertIn('Create table ok', rs1)\nschema, column_key = self.showschema(self.leader, self.tid, self.pid)\nself.assertEqual(len(schema), 3)\nself.assertEqual(schema[0], ['0', '... | <|body_start_0|>
rs1 = self.create(self.leader, 't', self.tid, self.pid, 144000, 2, 'true', card='string:index', merchant='string:index', amt='double')
self.assertIn('Create table ok', rs1)
schema, column_key = self.showschema(self.leader, self.tid, self.pid)
self.assertEqual(len(schema)... | TestShowSchema | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestShowSchema:
def test_showschema_tid_not_exist(self):
"""tid不存在,查看schema :return:"""
<|body_0|>
def test_showschema_type(self):
"""测试showschema是否支持所有字段类型 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
rs1 = self.create(self.leader, 't',... | stack_v2_sparse_classes_36k_train_028160 | 3,832 | permissive | [
{
"docstring": "tid不存在,查看schema :return:",
"name": "test_showschema_tid_not_exist",
"signature": "def test_showschema_tid_not_exist(self)"
},
{
"docstring": "测试showschema是否支持所有字段类型 :return:",
"name": "test_showschema_type",
"signature": "def test_showschema_type(self)"
}
] | 2 | null | Implement the Python class `TestShowSchema` described below.
Class description:
Implement the TestShowSchema class.
Method signatures and docstrings:
- def test_showschema_tid_not_exist(self): tid不存在,查看schema :return:
- def test_showschema_type(self): 测试showschema是否支持所有字段类型 :return: | Implement the Python class `TestShowSchema` described below.
Class description:
Implement the TestShowSchema class.
Method signatures and docstrings:
- def test_showschema_tid_not_exist(self): tid不存在,查看schema :return:
- def test_showschema_type(self): 测试showschema是否支持所有字段类型 :return:
<|skeleton|>
class TestShowSchema... | 14f662558880f0784699eb8339677e5afa6df6cf | <|skeleton|>
class TestShowSchema:
def test_showschema_tid_not_exist(self):
"""tid不存在,查看schema :return:"""
<|body_0|>
def test_showschema_type(self):
"""测试showschema是否支持所有字段类型 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestShowSchema:
def test_showschema_tid_not_exist(self):
"""tid不存在,查看schema :return:"""
rs1 = self.create(self.leader, 't', self.tid, self.pid, 144000, 2, 'true', card='string:index', merchant='string:index', amt='double')
self.assertIn('Create table ok', rs1)
schema, column_ke... | the_stack_v2_python_sparse | test-common/integrationtest/testcase/test_showschema.py | RhnSharma/OpenMLDB | train | 1 | |
0d88ef04ffd5c68290e2af0f5ae28d531353c4ad | [
"self.input_directory = input_directory\nself.save_directory = save_directory\nself.file_paths = []\nself.number_of_files = 0\nself.__folder_controller()\nself.__delete_non_merge_files()",
"for root, directory, files in os.walk(self.input_directory):\n for direc in directory:\n directory_path = os.path.... | <|body_start_0|>
self.input_directory = input_directory
self.save_directory = save_directory
self.file_paths = []
self.number_of_files = 0
self.__folder_controller()
self.__delete_non_merge_files()
<|end_body_0|>
<|body_start_1|>
for root, directory, files in os.... | Merge | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Merge:
def __init__(self, input_directory: str, save_directory: str):
"""This class is responsible for methods that will combine multiple text files in one folder to create one file self.__create_merged_file will coordinate the creating of a new file to place contents in self.__concatena... | stack_v2_sparse_classes_36k_train_028161 | 7,079 | no_license | [
{
"docstring": "This class is responsible for methods that will combine multiple text files in one folder to create one file self.__create_merged_file will coordinate the creating of a new file to place contents in self.__concatenate_files will perform the actual concatenation of files self.__folder_controller ... | 6 | stack_v2_sparse_classes_30k_train_008776 | Implement the Python class `Merge` described below.
Class description:
Implement the Merge class.
Method signatures and docstrings:
- def __init__(self, input_directory: str, save_directory: str): This class is responsible for methods that will combine multiple text files in one folder to create one file self.__creat... | Implement the Python class `Merge` described below.
Class description:
Implement the Merge class.
Method signatures and docstrings:
- def __init__(self, input_directory: str, save_directory: str): This class is responsible for methods that will combine multiple text files in one folder to create one file self.__creat... | 9ab650a460785adab085af523dec8ee8fa2105ba | <|skeleton|>
class Merge:
def __init__(self, input_directory: str, save_directory: str):
"""This class is responsible for methods that will combine multiple text files in one folder to create one file self.__create_merged_file will coordinate the creating of a new file to place contents in self.__concatena... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Merge:
def __init__(self, input_directory: str, save_directory: str):
"""This class is responsible for methods that will combine multiple text files in one folder to create one file self.__create_merged_file will coordinate the creating of a new file to place contents in self.__concatenate_files will ... | the_stack_v2_python_sparse | Scripts/MergeFiles.py | JoshLoecker/ARS | train | 0 | |
5d117a377f379ffef5a3894a86fab6d8fe8e4eb6 | [
"self.mols = mols\nif which('parmchk'):\n self.parmchk_version = 'parmchk'\nelse:\n self.parmchk_version = 'parmchk2'",
"command = parmchk_version + ' -i {} -f {} -o {} -w {}'.format(filename, format, outfile_name, print_improper_dihedrals)\nexit_code = subprocess.call(shlex.split(command))\nreturn exit_cod... | <|body_start_0|>
self.mols = mols
if which('parmchk'):
self.parmchk_version = 'parmchk'
else:
self.parmchk_version = 'parmchk2'
<|end_body_0|>
<|body_start_1|>
command = parmchk_version + ' -i {} -f {} -o {} -w {}'.format(filename, format, outfile_name, print_imp... | A wrapper for AntechamberRunner software | AntechamberRunner | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AntechamberRunner:
"""A wrapper for AntechamberRunner software"""
def __init__(self, mols):
"""Args: mols: List of molecules"""
<|body_0|>
def _run_parmchk(self, filename='mol.mol2', format='mol2', outfile_name='mol.frcmod', print_improper_dihedrals='Y'):
"""run ... | stack_v2_sparse_classes_36k_train_028162 | 6,484 | no_license | [
{
"docstring": "Args: mols: List of molecules",
"name": "__init__",
"signature": "def __init__(self, mols)"
},
{
"docstring": "run parmchk",
"name": "_run_parmchk",
"signature": "def _run_parmchk(self, filename='mol.mol2', format='mol2', outfile_name='mol.frcmod', print_improper_dihedral... | 6 | stack_v2_sparse_classes_30k_train_002081 | Implement the Python class `AntechamberRunner` described below.
Class description:
A wrapper for AntechamberRunner software
Method signatures and docstrings:
- def __init__(self, mols): Args: mols: List of molecules
- def _run_parmchk(self, filename='mol.mol2', format='mol2', outfile_name='mol.frcmod', print_improper... | Implement the Python class `AntechamberRunner` described below.
Class description:
A wrapper for AntechamberRunner software
Method signatures and docstrings:
- def __init__(self, mols): Args: mols: List of molecules
- def _run_parmchk(self, filename='mol.mol2', format='mol2', outfile_name='mol.frcmod', print_improper... | b07ebd0d32a3968fd6c120579f87590ec8bdd3ae | <|skeleton|>
class AntechamberRunner:
"""A wrapper for AntechamberRunner software"""
def __init__(self, mols):
"""Args: mols: List of molecules"""
<|body_0|>
def _run_parmchk(self, filename='mol.mol2', format='mol2', outfile_name='mol.frcmod', print_improper_dihedrals='Y'):
"""run ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AntechamberRunner:
"""A wrapper for AntechamberRunner software"""
def __init__(self, mols):
"""Args: mols: List of molecules"""
self.mols = mols
if which('parmchk'):
self.parmchk_version = 'parmchk'
else:
self.parmchk_version = 'parmchk2'
def _... | the_stack_v2_python_sparse | rubicon/io/amber/antechamber.py | molmd/rubicon | train | 0 |
5e872ff9af67cddf26439df37d4f98d0bcbd670e | [
"x, y, n = (train_data.X, train_data.y, train_data.n)\nt, n_test = (test_inputs, test_inputs.shape[0])\nobs_noise = self.likelihood.obs_noise\nmx = self.prior.mean_function(x)\nKxx = self.prior.kernel.gram(x) + identity(n) * self.prior.jitter\nSigma = Kxx + identity(n) * obs_noise\nmean_t = self.prior.mean_function... | <|body_start_0|>
x, y, n = (train_data.X, train_data.y, train_data.n)
t, n_test = (test_inputs, test_inputs.shape[0])
obs_noise = self.likelihood.obs_noise
mx = self.prior.mean_function(x)
Kxx = self.prior.kernel.gram(x) + identity(n) * self.prior.jitter
Sigma = Kxx + ide... | A Conjuate Gaussian process posterior object. A Gaussian process posterior distribution when the constituent likelihood function is a Gaussian distribution. In such cases, the latent function values $`f`$ can be analytically integrated out of the posterior distribution. As such, many computational operations can be sim... | ConjugatePosterior | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConjugatePosterior:
"""A Conjuate Gaussian process posterior object. A Gaussian process posterior distribution when the constituent likelihood function is a Gaussian distribution. In such cases, the latent function values $`f`$ can be analytically integrated out of the posterior distribution. As ... | stack_v2_sparse_classes_36k_train_028163 | 28,950 | permissive | [
{
"docstring": "Query the predictive posterior distribution. Conditional on a training data set, compute the GP's posterior predictive distribution for a given set of parameters. The returned function can be evaluated at a set of test inputs to compute the corresponding predictive density. The predictive distri... | 2 | stack_v2_sparse_classes_30k_train_018129 | Implement the Python class `ConjugatePosterior` described below.
Class description:
A Conjuate Gaussian process posterior object. A Gaussian process posterior distribution when the constituent likelihood function is a Gaussian distribution. In such cases, the latent function values $`f`$ can be analytically integrated... | Implement the Python class `ConjugatePosterior` described below.
Class description:
A Conjuate Gaussian process posterior object. A Gaussian process posterior distribution when the constituent likelihood function is a Gaussian distribution. In such cases, the latent function values $`f`$ can be analytically integrated... | b5009ec975bf25474055cf252297ff9ac462d9f5 | <|skeleton|>
class ConjugatePosterior:
"""A Conjuate Gaussian process posterior object. A Gaussian process posterior distribution when the constituent likelihood function is a Gaussian distribution. In such cases, the latent function values $`f`$ can be analytically integrated out of the posterior distribution. As ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConjugatePosterior:
"""A Conjuate Gaussian process posterior object. A Gaussian process posterior distribution when the constituent likelihood function is a Gaussian distribution. In such cases, the latent function values $`f`$ can be analytically integrated out of the posterior distribution. As such, many co... | the_stack_v2_python_sparse | gpjax/gps.py | JaxGaussianProcesses/GPJax | train | 129 |
c0bf57c5b5c9a2c08bdeb89b17eadcc1911cf968 | [
"self.f_beta_sq = f_beta_sq\nself.regularization = regularization\nself.learning_rate = learning_rate\nself.num_epochs = num_epochs",
"regularization = self.regularization\nnum_epochs = self.num_epochs\nalpha = None if self.f_beta_sq is None else np.reciprocal(self.f_beta_sq + 1.0)\nlr_init = self.learning_rate\n... | <|body_start_0|>
self.f_beta_sq = f_beta_sq
self.regularization = regularization
self.learning_rate = learning_rate
self.num_epochs = num_epochs
<|end_body_0|>
<|body_start_1|>
regularization = self.regularization
num_epochs = self.num_epochs
alpha = None if self... | Weighted edge model - classifies a path according to a score based on the weight of its edge types, and classifies a term-pair as positive if at least one of its paths is indicative. | SoftPathValidator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SoftPathValidator:
"""Weighted edge model - classifies a path according to a score based on the weight of its edge types, and classifies a term-pair as positive if at least one of its paths is indicative."""
def __init__(self, f_beta_sq=None, regularization=1.0, learning_rate=1.0, num_epochs... | stack_v2_sparse_classes_36k_train_028164 | 5,237 | permissive | [
{
"docstring": "Initialize the weighted edge model. :param f_beta_sq: the beta parameter for F_beta measure :param regularization: the regularization factor (lambda) :param learning_rate: learning rate (for w's update) :param num_epochs: the number of epochs",
"name": "__init__",
"signature": "def __ini... | 3 | stack_v2_sparse_classes_30k_train_010349 | Implement the Python class `SoftPathValidator` described below.
Class description:
Weighted edge model - classifies a path according to a score based on the weight of its edge types, and classifies a term-pair as positive if at least one of its paths is indicative.
Method signatures and docstrings:
- def __init__(sel... | Implement the Python class `SoftPathValidator` described below.
Class description:
Weighted edge model - classifies a path according to a score based on the weight of its edge types, and classifies a term-pair as positive if at least one of its paths is indicative.
Method signatures and docstrings:
- def __init__(sel... | 23596baa6453ea17c130a1b6e1b5da3004265740 | <|skeleton|>
class SoftPathValidator:
"""Weighted edge model - classifies a path according to a score based on the weight of its edge types, and classifies a term-pair as positive if at least one of its paths is indicative."""
def __init__(self, f_beta_sq=None, regularization=1.0, learning_rate=1.0, num_epochs... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SoftPathValidator:
"""Weighted edge model - classifies a path according to a score based on the weight of its edge types, and classifies a term-pair as positive if at least one of its paths is indicative."""
def __init__(self, f_beta_sq=None, regularization=1.0, learning_rate=1.0, num_epochs=100):
... | the_stack_v2_python_sparse | source/soft_path_validator.py | vered1986/linker | train | 7 |
0edb166f40e2d7faf6f5f2f4f68c5a29bf88362e | [
"self.model_name = model\nself.engine = engine\nself.schema = schema\nself.start_date = start\nself.end_date = end\nself.init_customers = init_customers\nself.monthly_growth_rate = 0.1\nself.util_mod = UtilityModel(self.model_name)\npath = conf_folder + '/'\nbehavior_versions = glob.glob(path + self.model_name + '_... | <|body_start_0|>
self.model_name = model
self.engine = engine
self.schema = schema
self.start_date = start
self.end_date = end
self.init_customers = init_customers
self.monthly_growth_rate = 0.1
self.util_mod = UtilityModel(self.model_name)
path = ... | ChurnSimulation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChurnSimulation:
def __init__(self, model, start, end, init_customers, seed, engine, schema=None):
"""Creates the behavior/utility model objects, sets internal variables to prepare for simulation, and creates the database connection :param model: name of the behavior/utility model parame... | stack_v2_sparse_classes_36k_train_028165 | 15,277 | permissive | [
{
"docstring": "Creates the behavior/utility model objects, sets internal variables to prepare for simulation, and creates the database connection :param model: name of the behavior/utility model parameters :param start: start date for simulation :param end: end date for simulation :param init_customers: how ma... | 3 | stack_v2_sparse_classes_30k_train_018887 | Implement the Python class `ChurnSimulation` described below.
Class description:
Implement the ChurnSimulation class.
Method signatures and docstrings:
- def __init__(self, model, start, end, init_customers, seed, engine, schema=None): Creates the behavior/utility model objects, sets internal variables to prepare for... | Implement the Python class `ChurnSimulation` described below.
Class description:
Implement the ChurnSimulation class.
Method signatures and docstrings:
- def __init__(self, model, start, end, init_customers, seed, engine, schema=None): Creates the behavior/utility model objects, sets internal variables to prepare for... | fcaaf17a30d69851be42a54c0e68ca4444fb97e1 | <|skeleton|>
class ChurnSimulation:
def __init__(self, model, start, end, init_customers, seed, engine, schema=None):
"""Creates the behavior/utility model objects, sets internal variables to prepare for simulation, and creates the database connection :param model: name of the behavior/utility model parame... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChurnSimulation:
def __init__(self, model, start, end, init_customers, seed, engine, schema=None):
"""Creates the behavior/utility model objects, sets internal variables to prepare for simulation, and creates the database connection :param model: name of the behavior/utility model parameters :param st... | the_stack_v2_python_sparse | churnmodels/simulation/churnsim2.py | ypix/fight-churn-nb | train | 0 | |
ddfd4460e5dbae4547f79161f6d5cd230d238e31 | [
"time = self.flowsheet().config.time.first()\nself.flow_in = pyunits.convert(self.flow_vol_in[time], to_units=pyunits.Mgallons / pyunits.day)\nself.toc_in = pyunits.convert(self.conc_mass_in[time, 'toc'], to_units=pyunits.mg / pyunits.liter)\nself.aop = unit_params['aop']\nself.contact_time = unit_params['contact_t... | <|body_start_0|>
time = self.flowsheet().config.time.first()
self.flow_in = pyunits.convert(self.flow_vol_in[time], to_units=pyunits.Mgallons / pyunits.day)
self.toc_in = pyunits.convert(self.conc_mass_in[time, 'toc'], to_units=pyunits.mg / pyunits.liter)
self.aop = unit_params['aop']
... | UnitProcess | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnitProcess:
def fixed_cap(self, unit_params):
"""Fixed capital for Ozone/Ozone AOP unit. :param unit_params: Input parameter dictionary from input sheet :type unit_params: dict :param toc_in: TOC concentration into unit [mg/L] :type toc_in: float :param aop: Boolean to indicate if unit ... | stack_v2_sparse_classes_36k_train_028166 | 5,609 | permissive | [
{
"docstring": "Fixed capital for Ozone/Ozone AOP unit. :param unit_params: Input parameter dictionary from input sheet :type unit_params: dict :param toc_in: TOC concentration into unit [mg/L] :type toc_in: float :param aop: Boolean to indicate if unit is AOP or not. :type aop: bool :param contact_time: Ozone ... | 5 | null | Implement the Python class `UnitProcess` described below.
Class description:
Implement the UnitProcess class.
Method signatures and docstrings:
- def fixed_cap(self, unit_params): Fixed capital for Ozone/Ozone AOP unit. :param unit_params: Input parameter dictionary from input sheet :type unit_params: dict :param toc... | Implement the Python class `UnitProcess` described below.
Class description:
Implement the UnitProcess class.
Method signatures and docstrings:
- def fixed_cap(self, unit_params): Fixed capital for Ozone/Ozone AOP unit. :param unit_params: Input parameter dictionary from input sheet :type unit_params: dict :param toc... | 0e9713a195b50824c4d38ff6ea5db244a6f1ad57 | <|skeleton|>
class UnitProcess:
def fixed_cap(self, unit_params):
"""Fixed capital for Ozone/Ozone AOP unit. :param unit_params: Input parameter dictionary from input sheet :type unit_params: dict :param toc_in: TOC concentration into unit [mg/L] :type toc_in: float :param aop: Boolean to indicate if unit ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnitProcess:
def fixed_cap(self, unit_params):
"""Fixed capital for Ozone/Ozone AOP unit. :param unit_params: Input parameter dictionary from input sheet :type unit_params: dict :param toc_in: TOC concentration into unit [mg/L] :type toc_in: float :param aop: Boolean to indicate if unit is AOP or not.... | the_stack_v2_python_sparse | watertap3/watertap3/wt_units/ozone_aop.py | JamariMurke/WaterTAP3 | train | 0 | |
2f863fc945478a43066cd04d25f1b69ed4ca4aa5 | [
"response = self.client.get(reverse('survey:index'))\nself.assertEqual(response.status_code, 200)\nself.assertContains(response, 'No new surveys are available')\nself.assertQuerysetEqual(response.context['latest_questions'], [])",
"q = create_question(text='Past question.', days=-30)\nresponse = self.client.get(r... | <|body_start_0|>
response = self.client.get(reverse('survey:index'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'No new surveys are available')
self.assertQuerysetEqual(response.context['latest_questions'], [])
<|end_body_0|>
<|body_start_1|>
q = c... | QuestionIndexViewTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionIndexViewTests:
def test_no_questions(self):
"""If no questions exist, an appropriate message is displayed."""
<|body_0|>
def test_past_question(self):
"""Questions with published date in the past are displayed on the index page."""
<|body_1|>
de... | stack_v2_sparse_classes_36k_train_028167 | 2,953 | no_license | [
{
"docstring": "If no questions exist, an appropriate message is displayed.",
"name": "test_no_questions",
"signature": "def test_no_questions(self)"
},
{
"docstring": "Questions with published date in the past are displayed on the index page.",
"name": "test_past_question",
"signature":... | 5 | stack_v2_sparse_classes_30k_train_000623 | Implement the Python class `QuestionIndexViewTests` described below.
Class description:
Implement the QuestionIndexViewTests class.
Method signatures and docstrings:
- def test_no_questions(self): If no questions exist, an appropriate message is displayed.
- def test_past_question(self): Questions with published date... | Implement the Python class `QuestionIndexViewTests` described below.
Class description:
Implement the QuestionIndexViewTests class.
Method signatures and docstrings:
- def test_no_questions(self): If no questions exist, an appropriate message is displayed.
- def test_past_question(self): Questions with published date... | 6233d5be19ebe240d4e444a803e5d9ad19e46747 | <|skeleton|>
class QuestionIndexViewTests:
def test_no_questions(self):
"""If no questions exist, an appropriate message is displayed."""
<|body_0|>
def test_past_question(self):
"""Questions with published date in the past are displayed on the index page."""
<|body_1|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuestionIndexViewTests:
def test_no_questions(self):
"""If no questions exist, an appropriate message is displayed."""
response = self.client.get(reverse('survey:index'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'No new surveys are available')
... | the_stack_v2_python_sparse | surveyproj/survey/tests.py | ulianadc/sumosurvey | train | 0 | |
225528d4c4f946222001e451721200006fb184db | [
"import sys\nfrom os.path import isfile\nif len(sys_args) == 2:\n filename = sys_args[1]\n if isfile(filename):\n msg = 'Loading configuration parameters from {}'\n print(msg.format(filename))\n else:\n print('Input argument is not a valid file')\n print('Using default configura... | <|body_start_0|>
import sys
from os.path import isfile
if len(sys_args) == 2:
filename = sys_args[1]
if isfile(filename):
msg = 'Loading configuration parameters from {}'
print(msg.format(filename))
else:
print('... | parser class manipulation of parser from ini files | parser | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class parser:
"""parser class manipulation of parser from ini files"""
def check_file(self, sys_args):
"""chek_file(args): Parse paramenters for the simulation from a .ini file Args: filename (str): the file name of the map to be read Raises: Returns: readmap: a healpix map, class ?"""
... | stack_v2_sparse_classes_36k_train_028168 | 38,527 | permissive | [
{
"docstring": "chek_file(args): Parse paramenters for the simulation from a .ini file Args: filename (str): the file name of the map to be read Raises: Returns: readmap: a healpix map, class ?",
"name": "check_file",
"signature": "def check_file(self, sys_args)"
},
{
"docstring": "chek_file(arg... | 4 | stack_v2_sparse_classes_30k_train_017311 | Implement the Python class `parser` described below.
Class description:
parser class manipulation of parser from ini files
Method signatures and docstrings:
- def check_file(self, sys_args): chek_file(args): Parse paramenters for the simulation from a .ini file Args: filename (str): the file name of the map to be rea... | Implement the Python class `parser` described below.
Class description:
parser class manipulation of parser from ini files
Method signatures and docstrings:
- def check_file(self, sys_args): chek_file(args): Parse paramenters for the simulation from a .ini file Args: filename (str): the file name of the map to be rea... | 97aba40ea37428273895f02c40bb6ea1db6f349b | <|skeleton|>
class parser:
"""parser class manipulation of parser from ini files"""
def check_file(self, sys_args):
"""chek_file(args): Parse paramenters for the simulation from a .ini file Args: filename (str): the file name of the map to be read Raises: Returns: readmap: a healpix map, class ?"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class parser:
"""parser class manipulation of parser from ini files"""
def check_file(self, sys_args):
"""chek_file(args): Parse paramenters for the simulation from a .ini file Args: filename (str): the file name of the map to be read Raises: Returns: readmap: a healpix map, class ?"""
import s... | the_stack_v2_python_sparse | src/cv19.py | ivco19/countries | train | 0 |
f1102a6f30f464ebe55acf85bc63b240f5e0a45a | [
"node = ListNode(-1)\nhead = node\nwhile l1 and l2:\n if l1.val <= l2.val:\n node.next = l1\n l1 = l1.next\n else:\n node.next = l2\n l2 = l2.next\n node = node.next\nif not l1:\n node.next = l2\nif not l2:\n node.next = l1\nreturn head.next",
"if not l1:\n return l2\... | <|body_start_0|>
node = ListNode(-1)
head = node
while l1 and l2:
if l1.val <= l2.val:
node.next = l1
l1 = l1.next
else:
node.next = l2
l2 = l2.next
node = node.next
if not l1:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode:
"""合并两个链表 Args: l1: l1链表 l2: l2链表 Returns: 合并后的链表"""
<|body_0|>
def merge_two_lists_2(self, l1: ListNode, l2: ListNode) -> ListNode:
"""合并两个链表 Args: l1: l1链表 l2: l2链表 Returns: 合并后的链表"""
... | stack_v2_sparse_classes_36k_train_028169 | 2,281 | permissive | [
{
"docstring": "合并两个链表 Args: l1: l1链表 l2: l2链表 Returns: 合并后的链表",
"name": "merge_two_lists",
"signature": "def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode"
},
{
"docstring": "合并两个链表 Args: l1: l1链表 l2: l2链表 Returns: 合并后的链表",
"name": "merge_two_lists_2",
"signature": "def ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode: 合并两个链表 Args: l1: l1链表 l2: l2链表 Returns: 合并后的链表
- def merge_two_lists_2(self, l1: ListNode, l2: ListNode) -> Lis... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode: 合并两个链表 Args: l1: l1链表 l2: l2链表 Returns: 合并后的链表
- def merge_two_lists_2(self, l1: ListNode, l2: ListNode) -> Lis... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode:
"""合并两个链表 Args: l1: l1链表 l2: l2链表 Returns: 合并后的链表"""
<|body_0|>
def merge_two_lists_2(self, l1: ListNode, l2: ListNode) -> ListNode:
"""合并两个链表 Args: l1: l1链表 l2: l2链表 Returns: 合并后的链表"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode:
"""合并两个链表 Args: l1: l1链表 l2: l2链表 Returns: 合并后的链表"""
node = ListNode(-1)
head = node
while l1 and l2:
if l1.val <= l2.val:
node.next = l1
l1 = l1.next
... | the_stack_v2_python_sparse | src/leetcodepython/list/merge_two_sorted_lists_21.py | zhangyu345293721/leetcode | train | 101 | |
22a8228030b06e5bb135f6b35d45d5c775c9bb62 | [
"self.get_response = get_response\nself.jwt_decode_handler = api_settings.JWT_DECODE_HANDLER\nself.jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER",
"try:\n payload = self.jwt_decode_handler(request.COOKIES.get(settings.OPEN_DISCUSSIONS_COOKIE_NAME, None))\nexcept jwt.InvalidTokenError:\n return None\n... | <|body_start_0|>
self.get_response = get_response
self.jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
self.jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
<|end_body_0|>
<|body_start_1|>
try:
payload = self.jwt_decode_handler(request.COOKIES.get(settings.OPEN_DISC... | Track user activity | UserActivityMiddleware | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserActivityMiddleware:
"""Track user activity"""
def __init__(self, get_response):
"""One-time configuration"""
<|body_0|>
def _track_activity(self, request):
"""Updates activity date on the user record Args: request (django.http.request.Request): the request to... | stack_v2_sparse_classes_36k_train_028170 | 1,970 | permissive | [
{
"docstring": "One-time configuration",
"name": "__init__",
"signature": "def __init__(self, get_response)"
},
{
"docstring": "Updates activity date on the user record Args: request (django.http.request.Request): the request to inspect Returns: bool: True if the activity was tracked",
"name... | 3 | null | Implement the Python class `UserActivityMiddleware` described below.
Class description:
Track user activity
Method signatures and docstrings:
- def __init__(self, get_response): One-time configuration
- def _track_activity(self, request): Updates activity date on the user record Args: request (django.http.request.Req... | Implement the Python class `UserActivityMiddleware` described below.
Class description:
Track user activity
Method signatures and docstrings:
- def __init__(self, get_response): One-time configuration
- def _track_activity(self, request): Updates activity date on the user record Args: request (django.http.request.Req... | 2c1266aedf0117f44dba661841f4fe8003a1664c | <|skeleton|>
class UserActivityMiddleware:
"""Track user activity"""
def __init__(self, get_response):
"""One-time configuration"""
<|body_0|>
def _track_activity(self, request):
"""Updates activity date on the user record Args: request (django.http.request.Request): the request to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserActivityMiddleware:
"""Track user activity"""
def __init__(self, get_response):
"""One-time configuration"""
self.get_response = get_response
self.jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
self.jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
def _t... | the_stack_v2_python_sparse | open_discussions/middleware/user_activity.py | MasterGowen/open-discussions | train | 0 |
e804863764cd51b6008c332a5771ab1b96329ca7 | [
"dataset = m.device\nif not dataset_exists(dataset, 'filesystem'):\n raise ex.syncNotSnapable\nsnapdev = dataset + '@osvc_sync'\nmount_point = m.mount_point\nsnap_mount_point = mount_point + '/.zfs/snapshot/osvc_sync/'\nif dataset_exists(snapdev, 'snapshot'):\n ret, buff, err = self.vcall([rcEnv.syspaths.zfs,... | <|body_start_0|>
dataset = m.device
if not dataset_exists(dataset, 'filesystem'):
raise ex.syncNotSnapable
snapdev = dataset + '@osvc_sync'
mount_point = m.mount_point
snap_mount_point = mount_point + '/.zfs/snapshot/osvc_sync/'
if dataset_exists(snapdev, 'sna... | Defines a snap object with ZFS | Snap | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Snap:
"""Defines a snap object with ZFS"""
def snapcreate(self, m):
"""create a snapshot for m add self.snaps[m] with dict(snapinfo key val)"""
<|body_0|>
def snapdestroykey(self, snap_key):
"""destroy a snapshot for a mount_point"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k_train_028171 | 1,445 | no_license | [
{
"docstring": "create a snapshot for m add self.snaps[m] with dict(snapinfo key val)",
"name": "snapcreate",
"signature": "def snapcreate(self, m)"
},
{
"docstring": "destroy a snapshot for a mount_point",
"name": "snapdestroykey",
"signature": "def snapdestroykey(self, snap_key)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007599 | Implement the Python class `Snap` described below.
Class description:
Defines a snap object with ZFS
Method signatures and docstrings:
- def snapcreate(self, m): create a snapshot for m add self.snaps[m] with dict(snapinfo key val)
- def snapdestroykey(self, snap_key): destroy a snapshot for a mount_point | Implement the Python class `Snap` described below.
Class description:
Defines a snap object with ZFS
Method signatures and docstrings:
- def snapcreate(self, m): create a snapshot for m add self.snaps[m] with dict(snapinfo key val)
- def snapdestroykey(self, snap_key): destroy a snapshot for a mount_point
<|skeleton... | 75baeb19e0d26d5e150e770aef4d615c2327f32e | <|skeleton|>
class Snap:
"""Defines a snap object with ZFS"""
def snapcreate(self, m):
"""create a snapshot for m add self.snaps[m] with dict(snapinfo key val)"""
<|body_0|>
def snapdestroykey(self, snap_key):
"""destroy a snapshot for a mount_point"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Snap:
"""Defines a snap object with ZFS"""
def snapcreate(self, m):
"""create a snapshot for m add self.snaps[m] with dict(snapinfo key val)"""
dataset = m.device
if not dataset_exists(dataset, 'filesystem'):
raise ex.syncNotSnapable
snapdev = dataset + '@osvc_... | the_stack_v2_python_sparse | lib/snapZfsSunOS.py | SLB-DeN/opensvc | train | 1 |
49fad8568ecbe66fe0cc2c1192f0413069d69829 | [
"SHOW_REG = re.compile('^/dumi/travel')\nPLAY_REG = re.compile('/m\\\\.gif')\nret = {}\nquery = []\npage = []\nret['query'] = query\nret['page'] = page\ntravel_Db = midpagedb.DateLogDb()\ntravel = travel_Db.get_collection()\ntravelDb = travel_Db.get_db()\nquery_info = travel.aggregate([{'$match': {'url': SHOW_REG}}... | <|body_start_0|>
SHOW_REG = re.compile('^/dumi/travel')
PLAY_REG = re.compile('/m\\.gif')
ret = {}
query = []
page = []
ret['query'] = query
ret['page'] = page
travel_Db = midpagedb.DateLogDb()
travel = travel_Db.get_collection()
travelDb =... | Product | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Product:
def statist(self):
"""self.log_collection可以拿到mongo中的日志集合,用于统计指标的函数"""
<|body_0|>
def save_result(self, result):
"""result为statist返回的结果,用于存储结果,可以存储到本地也可以存储如数据库"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
SHOW_REG = re.compile('^/dumi/tra... | stack_v2_sparse_classes_36k_train_028172 | 2,550 | no_license | [
{
"docstring": "self.log_collection可以拿到mongo中的日志集合,用于统计指标的函数",
"name": "statist",
"signature": "def statist(self)"
},
{
"docstring": "result为statist返回的结果,用于存储结果,可以存储到本地也可以存储如数据库",
"name": "save_result",
"signature": "def save_result(self, result)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015987 | Implement the Python class `Product` described below.
Class description:
Implement the Product class.
Method signatures and docstrings:
- def statist(self): self.log_collection可以拿到mongo中的日志集合,用于统计指标的函数
- def save_result(self, result): result为statist返回的结果,用于存储结果,可以存储到本地也可以存储如数据库 | Implement the Python class `Product` described below.
Class description:
Implement the Product class.
Method signatures and docstrings:
- def statist(self): self.log_collection可以拿到mongo中的日志集合,用于统计指标的函数
- def save_result(self, result): result为statist返回的结果,用于存储结果,可以存储到本地也可以存储如数据库
<|skeleton|>
class Product:
def s... | f2303a443122e87296fb5b72a8af02d642297bc4 | <|skeleton|>
class Product:
def statist(self):
"""self.log_collection可以拿到mongo中的日志集合,用于统计指标的函数"""
<|body_0|>
def save_result(self, result):
"""result为statist返回的结果,用于存储结果,可以存储到本地也可以存储如数据库"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Product:
def statist(self):
"""self.log_collection可以拿到mongo中的日志集合,用于统计指标的函数"""
SHOW_REG = re.compile('^/dumi/travel')
PLAY_REG = re.compile('/m\\.gif')
ret = {}
query = []
page = []
ret['query'] = query
ret['page'] = page
travel_Db = midp... | the_stack_v2_python_sparse | midpage/products/travel.py | cash2one/statistic | train | 0 | |
5a625280f2b7359100e6b7ab4cc1ebf2959f956e | [
"self._click_add_new_button2_()\nself._set_product_name_(productname)\nself._set_meta_tag_(keywords)\nself._click_data_tab_()\nself._set_model_name_(modelname)\nself._click_save_button_()",
"self._click_edit_button_()\nself._clear_product_name_()\nself._set_product_name_(productname)\nself._clear_meta_tag_()\nsel... | <|body_start_0|>
self._click_add_new_button2_()
self._set_product_name_(productname)
self._set_meta_tag_(keywords)
self._click_data_tab_()
self._set_model_name_(modelname)
self._click_save_button_()
<|end_body_0|>
<|body_start_1|>
self._click_edit_button_()
... | Managing product operations | ProductManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductManager:
"""Managing product operations"""
def add_new_product(self, productname, keywords, modelname):
"""Add new product to site"""
<|body_0|>
def edit_product(self, productname, keywords, modelname):
"""Edit created product"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_028173 | 6,654 | permissive | [
{
"docstring": "Add new product to site",
"name": "add_new_product",
"signature": "def add_new_product(self, productname, keywords, modelname)"
},
{
"docstring": "Edit created product",
"name": "edit_product",
"signature": "def edit_product(self, productname, keywords, modelname)"
}
] | 2 | null | Implement the Python class `ProductManager` described below.
Class description:
Managing product operations
Method signatures and docstrings:
- def add_new_product(self, productname, keywords, modelname): Add new product to site
- def edit_product(self, productname, keywords, modelname): Edit created product | Implement the Python class `ProductManager` described below.
Class description:
Managing product operations
Method signatures and docstrings:
- def add_new_product(self, productname, keywords, modelname): Add new product to site
- def edit_product(self, productname, keywords, modelname): Edit created product
<|skele... | 510a4f1971b35048d760fcc45098e511b81bea31 | <|skeleton|>
class ProductManager:
"""Managing product operations"""
def add_new_product(self, productname, keywords, modelname):
"""Add new product to site"""
<|body_0|>
def edit_product(self, productname, keywords, modelname):
"""Edit created product"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProductManager:
"""Managing product operations"""
def add_new_product(self, productname, keywords, modelname):
"""Add new product to site"""
self._click_add_new_button2_()
self._set_product_name_(productname)
self._set_meta_tag_(keywords)
self._click_data_tab_()
... | the_stack_v2_python_sparse | SeleniumCloud/models/page_objects/page_objects.py | BahrmaLe/otus_python_homework | train | 1 |
9d334671995beeb247af5ff2b5c3c983413d9e9d | [
"def help(root):\n if root:\n left = help(root.left)\n right = help(root.right)\n if left:\n root.right = left\n root.left = None\n while left.right:\n left = left.right\n left.right = right\n return root\n else:\n r... | <|body_start_0|>
def help(root):
if root:
left = help(root.left)
right = help(root.right)
if left:
root.right = left
root.left = None
while left.right:
left = left.righ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def flatten1(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
<|body_0|>
def flatten(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
... | stack_v2_sparse_classes_36k_train_028174 | 1,541 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.",
"name": "flatten1",
"signature": "def flatten1(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.",
"name": "flatten"... | 2 | stack_v2_sparse_classes_30k_val_000549 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten1(self, root): :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.
- def flatten(self, root): :type root: TreeNode :rtype: void Do ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten1(self, root): :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.
- def flatten(self, root): :type root: TreeNode :rtype: void Do ... | e5b018493bbd12edcdcd0434f35d9c358106d391 | <|skeleton|>
class Solution:
def flatten1(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
<|body_0|>
def flatten(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def flatten1(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
def help(root):
if root:
left = help(root.left)
right = help(root.right)
if left:
ro... | the_stack_v2_python_sparse | py/leetcode/114.py | wfeng1991/learnpy | train | 0 | |
a3af7de48b4c9f423874b5608c35eff88d3ce9da | [
"with open(file_path, 'rb') as f:\n md5obj = hashlib.md5()\n for line in f:\n md5obj.update(line)\n return md5obj.hexdigest()",
"with open(settings.help_file, encoding='utf-8') as f:\n for i in f:\n i = i.rstrip()\n print(i)",
"logger = logging.getLogger()\nfh = logging.FileHand... | <|body_start_0|>
with open(file_path, 'rb') as f:
md5obj = hashlib.md5()
for line in f:
md5obj.update(line)
return md5obj.hexdigest()
<|end_body_0|>
<|body_start_1|>
with open(settings.help_file, encoding='utf-8') as f:
for i in f:
... | Public | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Public:
def get_md5(file_path):
"""获取文件的md5值 :param file_path: 文件路径 :return:"""
<|body_0|>
def helper():
"""帮助文档"""
<|body_1|>
def log():
"""定义日志输出合格 :return: 返回一个可以直接使用的logger对象"""
<|body_2|>
def progress_bar(num, total):
""... | stack_v2_sparse_classes_36k_train_028175 | 1,525 | no_license | [
{
"docstring": "获取文件的md5值 :param file_path: 文件路径 :return:",
"name": "get_md5",
"signature": "def get_md5(file_path)"
},
{
"docstring": "帮助文档",
"name": "helper",
"signature": "def helper()"
},
{
"docstring": "定义日志输出合格 :return: 返回一个可以直接使用的logger对象",
"name": "log",
"signatur... | 4 | null | Implement the Python class `Public` described below.
Class description:
Implement the Public class.
Method signatures and docstrings:
- def get_md5(file_path): 获取文件的md5值 :param file_path: 文件路径 :return:
- def helper(): 帮助文档
- def log(): 定义日志输出合格 :return: 返回一个可以直接使用的logger对象
- def progress_bar(num, total): 进度条 | Implement the Python class `Public` described below.
Class description:
Implement the Public class.
Method signatures and docstrings:
- def get_md5(file_path): 获取文件的md5值 :param file_path: 文件路径 :return:
- def helper(): 帮助文档
- def log(): 定义日志输出合格 :return: 返回一个可以直接使用的logger对象
- def progress_bar(num, total): 进度条
<|skele... | d7fc68d3d23345df5bfb09d4a84686c8b49a5ad7 | <|skeleton|>
class Public:
def get_md5(file_path):
"""获取文件的md5值 :param file_path: 文件路径 :return:"""
<|body_0|>
def helper():
"""帮助文档"""
<|body_1|>
def log():
"""定义日志输出合格 :return: 返回一个可以直接使用的logger对象"""
<|body_2|>
def progress_bar(num, total):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Public:
def get_md5(file_path):
"""获取文件的md5值 :param file_path: 文件路径 :return:"""
with open(file_path, 'rb') as f:
md5obj = hashlib.md5()
for line in f:
md5obj.update(line)
return md5obj.hexdigest()
def helper():
"""帮助文档"""
... | the_stack_v2_python_sparse | Homework/day08/ftp_client/core/Pubulic.py | 214031230/Python21 | train | 0 | |
57efe61e025fff8b6a5e5d4cba5b634ad9c5dc1b | [
"action_key = request.POST.get('action')\n_, method = self.actions[action_key]\ngetattr(self, method)()\nreturn HttpResponseRedirect(reverse('event_admin', kwargs={'pk': pk}))",
"username = self.request.POST.get('text')\nif self.request.POST.get('Regelboks') == 'True':\n regelbryting = True\nelse:\n regelbr... | <|body_start_0|>
action_key = request.POST.get('action')
_, method = self.actions[action_key]
getattr(self, method)()
return HttpResponseRedirect(reverse('event_admin', kwargs={'pk': pk}))
<|end_body_0|>
<|body_start_1|>
username = self.request.POST.get('text')
if self.r... | Viser påmeldingslisten til et Event med mulighet for å melde folk på og av. | AdministerRegistrationsView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdministerRegistrationsView:
"""Viser påmeldingslisten til et Event med mulighet for å melde folk på og av."""
def post(self, request, pk):
"""Handle http post request"""
<|body_0|>
def register_user(self):
"""Melder på brukeren nevnt i POST['text'] på arrangemen... | stack_v2_sparse_classes_36k_train_028176 | 24,750 | permissive | [
{
"docstring": "Handle http post request",
"name": "post",
"signature": "def post(self, request, pk)"
},
{
"docstring": "Melder på brukeren nevnt i POST['text'] på arrangementet.",
"name": "register_user",
"signature": "def register_user(self)"
},
{
"docstring": "Melder av bruker... | 3 | stack_v2_sparse_classes_30k_test_000850 | Implement the Python class `AdministerRegistrationsView` described below.
Class description:
Viser påmeldingslisten til et Event med mulighet for å melde folk på og av.
Method signatures and docstrings:
- def post(self, request, pk): Handle http post request
- def register_user(self): Melder på brukeren nevnt i POST[... | Implement the Python class `AdministerRegistrationsView` described below.
Class description:
Viser påmeldingslisten til et Event med mulighet for å melde folk på og av.
Method signatures and docstrings:
- def post(self, request, pk): Handle http post request
- def register_user(self): Melder på brukeren nevnt i POST[... | 5661cbea1011f8851a244ae3d72351fce647123f | <|skeleton|>
class AdministerRegistrationsView:
"""Viser påmeldingslisten til et Event med mulighet for å melde folk på og av."""
def post(self, request, pk):
"""Handle http post request"""
<|body_0|>
def register_user(self):
"""Melder på brukeren nevnt i POST['text'] på arrangemen... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdministerRegistrationsView:
"""Viser påmeldingslisten til et Event med mulighet for å melde folk på og av."""
def post(self, request, pk):
"""Handle http post request"""
action_key = request.POST.get('action')
_, method = self.actions[action_key]
getattr(self, method)()
... | the_stack_v2_python_sparse | nablapps/events/views.py | Nabla-NTNU/nablaweb | train | 21 |
c0c6aea8e298c52e99e367bcb4a56fb04d49abbc | [
"loss_fn = functools.partial(metrics.weighted_loss, all_metrics.ALL_LOSSES['categorical_cross_entropy'])\nenv_dann_losses = []\nfor i in range(len(env_logits)):\n batch = env_batches[i]\n loss_value, loss_normalizer = loss_fn(env_logits[i], env_labels[i], batch.get('weights'))\n loss = loss_value / loss_no... | <|body_start_0|>
loss_fn = functools.partial(metrics.weighted_loss, all_metrics.ALL_LOSSES['categorical_cross_entropy'])
env_dann_losses = []
for i in range(len(env_logits)):
batch = env_batches[i]
loss_value, loss_normalizer = loss_fn(env_logits[i], env_labels[i], batch.... | Task class for Domain Adverserial NNs. | MultiEnvDannClassification | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiEnvDannClassification:
"""Task class for Domain Adverserial NNs."""
def dann_loss(self, env_logits, env_labels, env_batches):
"""Compute DANN loss. Reference: https://jmlr.org/papers/volume17/15-239/15-239.pdf Args: env_logits: list; Domain logits for all labeled environments. T... | stack_v2_sparse_classes_36k_train_028177 | 44,080 | permissive | [
{
"docstring": "Compute DANN loss. Reference: https://jmlr.org/papers/volume17/15-239/15-239.pdf Args: env_logits: list; Domain logits for all labeled environments. This is the output of the domain discriminator module. env_labels: list; Domain Labels. env_batches: list(dict); List of batches of examples of all... | 2 | null | Implement the Python class `MultiEnvDannClassification` described below.
Class description:
Task class for Domain Adverserial NNs.
Method signatures and docstrings:
- def dann_loss(self, env_logits, env_labels, env_batches): Compute DANN loss. Reference: https://jmlr.org/papers/volume17/15-239/15-239.pdf Args: env_lo... | Implement the Python class `MultiEnvDannClassification` described below.
Class description:
Task class for Domain Adverserial NNs.
Method signatures and docstrings:
- def dann_loss(self, env_logits, env_labels, env_batches): Compute DANN loss. Reference: https://jmlr.org/papers/volume17/15-239/15-239.pdf Args: env_lo... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class MultiEnvDannClassification:
"""Task class for Domain Adverserial NNs."""
def dann_loss(self, env_logits, env_labels, env_batches):
"""Compute DANN loss. Reference: https://jmlr.org/papers/volume17/15-239/15-239.pdf Args: env_logits: list; Domain logits for all labeled environments. T... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiEnvDannClassification:
"""Task class for Domain Adverserial NNs."""
def dann_loss(self, env_logits, env_labels, env_batches):
"""Compute DANN loss. Reference: https://jmlr.org/papers/volume17/15-239/15-239.pdf Args: env_logits: list; Domain logits for all labeled environments. This is the ou... | the_stack_v2_python_sparse | gift/tasks/task.py | Jimmy-INL/google-research | train | 1 |
29762484be0810c5d403a994de05b65016cf9a29 | [
"self.dependents: dict[str, set[str]] = {}\nself.started: set[str] = set()\nself.node_services: dict[str, 'ConfigService'] = {}\nfor service in services.values():\n self.node_services[service.name] = service\n for dependency in service.dependencies:\n dependents = self.dependents.setdefault(dependency,... | <|body_start_0|>
self.dependents: dict[str, set[str]] = {}
self.started: set[str] = set()
self.node_services: dict[str, 'ConfigService'] = {}
for service in services.values():
self.node_services[service.name] = service
for dependency in service.dependencies:
... | Generates sets of services to start in order of their dependencies. | ConfigServiceDependencies | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigServiceDependencies:
"""Generates sets of services to start in order of their dependencies."""
def __init__(self, services: dict[str, 'ConfigService']) -> None:
"""Create a ConfigServiceDependencies instance. :param services: services for determining dependency sets"""
... | stack_v2_sparse_classes_36k_train_028178 | 4,298 | permissive | [
{
"docstring": "Create a ConfigServiceDependencies instance. :param services: services for determining dependency sets",
"name": "__init__",
"signature": "def __init__(self, services: dict[str, 'ConfigService']) -> None"
},
{
"docstring": "Find startup path sets based on service dependencies. :r... | 5 | null | Implement the Python class `ConfigServiceDependencies` described below.
Class description:
Generates sets of services to start in order of their dependencies.
Method signatures and docstrings:
- def __init__(self, services: dict[str, 'ConfigService']) -> None: Create a ConfigServiceDependencies instance. :param servi... | Implement the Python class `ConfigServiceDependencies` described below.
Class description:
Generates sets of services to start in order of their dependencies.
Method signatures and docstrings:
- def __init__(self, services: dict[str, 'ConfigService']) -> None: Create a ConfigServiceDependencies instance. :param servi... | 20071eed2e73a2287aa385698dd604f4933ae7ff | <|skeleton|>
class ConfigServiceDependencies:
"""Generates sets of services to start in order of their dependencies."""
def __init__(self, services: dict[str, 'ConfigService']) -> None:
"""Create a ConfigServiceDependencies instance. :param services: services for determining dependency sets"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigServiceDependencies:
"""Generates sets of services to start in order of their dependencies."""
def __init__(self, services: dict[str, 'ConfigService']) -> None:
"""Create a ConfigServiceDependencies instance. :param services: services for determining dependency sets"""
self.dependen... | the_stack_v2_python_sparse | daemon/core/configservice/dependencies.py | coreemu/core | train | 606 |
f1f4e75164a08543bb0ea6d1598de3b2706fa6a4 | [
"result = []\nfraction = ()\nm = 0\nd = 1\nself.a0 = number ** 0.5\nif self.a0.is_integer():\n return [self.a0, None]\nself.a0 = floor(self.a0)\na = self.a0\nwhile True:\n m = d * a - m\n d = (number - m ** 2) / d\n a = floor((self.a0 + m) / d)\n fraction += (a,)\n if a == 2 * self.a0:\n br... | <|body_start_0|>
result = []
fraction = ()
m = 0
d = 1
self.a0 = number ** 0.5
if self.a0.is_integer():
return [self.a0, None]
self.a0 = floor(self.a0)
a = self.a0
while True:
m = d * a - m
d = (number - m ** 2) ... | Made by Bogdan Trif @ 2016-11-18. It needs the factions.Fraction, itertools.cycle and math.floor | CONTINUED_FRACTIONS | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CONTINUED_FRACTIONS:
"""Made by Bogdan Trif @ 2016-11-18. It needs the factions.Fraction, itertools.cycle and math.floor"""
def continued_fractions(self, number):
""":Description: THE FASTEST ALGORITHM After if find the proper period of the continued fractions it returns the result. ... | stack_v2_sparse_classes_36k_train_028179 | 2,664 | no_license | [
{
"docstring": ":Description: THE FASTEST ALGORITHM After if find the proper period of the continued fractions it returns the result. :param number: is the number for which the square root continued fraction coefficients will be computed :return: list containing the periodic continued fractions terms",
"nam... | 2 | stack_v2_sparse_classes_30k_train_015928 | Implement the Python class `CONTINUED_FRACTIONS` described below.
Class description:
Made by Bogdan Trif @ 2016-11-18. It needs the factions.Fraction, itertools.cycle and math.floor
Method signatures and docstrings:
- def continued_fractions(self, number): :Description: THE FASTEST ALGORITHM After if find the proper ... | Implement the Python class `CONTINUED_FRACTIONS` described below.
Class description:
Made by Bogdan Trif @ 2016-11-18. It needs the factions.Fraction, itertools.cycle and math.floor
Method signatures and docstrings:
- def continued_fractions(self, number): :Description: THE FASTEST ALGORITHM After if find the proper ... | b4c81010a1476721cabc2621b17d92fead9314b4 | <|skeleton|>
class CONTINUED_FRACTIONS:
"""Made by Bogdan Trif @ 2016-11-18. It needs the factions.Fraction, itertools.cycle and math.floor"""
def continued_fractions(self, number):
""":Description: THE FASTEST ALGORITHM After if find the proper period of the continued fractions it returns the result. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CONTINUED_FRACTIONS:
"""Made by Bogdan Trif @ 2016-11-18. It needs the factions.Fraction, itertools.cycle and math.floor"""
def continued_fractions(self, number):
""":Description: THE FASTEST ALGORITHM After if find the proper period of the continued fractions it returns the result. :param number... | the_stack_v2_python_sparse | Algorithms/Continued_Fractions_tools.py | btrif/Python_dev_repo | train | 0 |
d2928c15b2c3fe50a6daec8a2883581c7172d86f | [
"data = [{'name': 'Normal string', 'item_num': 1}, {'name': 'String, with, commas', 'item_num': 2}, {'name': 'String with \" quote', 'item_num': 3}]\ntable = TableReportForTesting(data)\nresponse = table.as_csv(HttpRequest())\nself.assertEqual(response.status_code, 200)\ncontent = response.content\nif PY3:\n con... | <|body_start_0|>
data = [{'name': 'Normal string', 'item_num': 1}, {'name': 'String, with, commas', 'item_num': 2}, {'name': 'String with " quote', 'item_num': 3}]
table = TableReportForTesting(data)
response = table.as_csv(HttpRequest())
self.assertEqual(response.status_code, 200)
... | Test csv generation on sample table data. | TestCsvGeneration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCsvGeneration:
"""Test csv generation on sample table data."""
def test_csv_simple_input(self):
"""Test ability to generate csv with simple input data."""
<|body_0|>
def test_csv_with_unicode(self):
"""Test that unicode cell values are converted correctly to ... | stack_v2_sparse_classes_36k_train_028180 | 7,242 | no_license | [
{
"docstring": "Test ability to generate csv with simple input data.",
"name": "test_csv_simple_input",
"signature": "def test_csv_simple_input(self)"
},
{
"docstring": "Test that unicode cell values are converted correctly to csv.",
"name": "test_csv_with_unicode",
"signature": "def tes... | 4 | stack_v2_sparse_classes_30k_train_013096 | Implement the Python class `TestCsvGeneration` described below.
Class description:
Test csv generation on sample table data.
Method signatures and docstrings:
- def test_csv_simple_input(self): Test ability to generate csv with simple input data.
- def test_csv_with_unicode(self): Test that unicode cell values are co... | Implement the Python class `TestCsvGeneration` described below.
Class description:
Test csv generation on sample table data.
Method signatures and docstrings:
- def test_csv_simple_input(self): Test ability to generate csv with simple input data.
- def test_csv_with_unicode(self): Test that unicode cell values are co... | 0fcdb4becd8e25559819e877e77078c0cf17b6cd | <|skeleton|>
class TestCsvGeneration:
"""Test csv generation on sample table data."""
def test_csv_simple_input(self):
"""Test ability to generate csv with simple input data."""
<|body_0|>
def test_csv_with_unicode(self):
"""Test that unicode cell values are converted correctly to ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestCsvGeneration:
"""Test csv generation on sample table data."""
def test_csv_simple_input(self):
"""Test ability to generate csv with simple input data."""
data = [{'name': 'Normal string', 'item_num': 1}, {'name': 'String, with, commas', 'item_num': 2}, {'name': 'String with " quote',... | the_stack_v2_python_sparse | django_tables2_reports/tests.py | goinnn/django-tables2-reports | train | 48 |
6bce6a91f1f9bc9332ea0e37557a1043a7f4fcf5 | [
"num_rows = len(matrix) if matrix else -1\nnum_cols = len(matrix[0]) if num_rows >= 1 else -1\nif num_rows < 1 or num_cols < 1:\n return False\nleft, right = (0, num_rows * num_cols - 1)\nwhile left <= right:\n mid = left + (right - left) // 2\n val = matrix[mid // num_cols][mid % num_cols]\n if val == ... | <|body_start_0|>
num_rows = len(matrix) if matrix else -1
num_cols = len(matrix[0]) if num_rows >= 1 else -1
if num_rows < 1 or num_cols < 1:
return False
left, right = (0, num_rows * num_cols - 1)
while left <= right:
mid = left + (right - left) // 2
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrix_v2(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k_train_028181 | 2,487 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix",
"signature": "def searchMatrix(self, matrix, target)"
},
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix_v2",
"signature": "def sear... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def searchMatrix_v2(self, matrix, target): :type matrix: List[List[int]] :t... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def searchMatrix_v2(self, matrix, target): :type matrix: List[List[int]] :t... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrix_v2(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
num_rows = len(matrix) if matrix else -1
num_cols = len(matrix[0]) if num_rows >= 1 else -1
if num_rows < 1 or num_cols < 1:
return False
lef... | the_stack_v2_python_sparse | src/lt_74.py | oxhead/CodingYourWay | train | 0 | |
b3f6becc065d01a911d7856738f1809550ddc6a2 | [
"time = self.flowsheet().config.time.first()\nself.flow_in = pyunits.convert(self.flow_vol_in[time], to_units=pyunits.m ** 3 / pyunits.hr)\nself.number_of_units = 2\nself.base_fixed_cap_cost = 900.97\nself.cap_scaling_exp = 0.6179\nchem_name = unit_params['chemical_name']\nself.dose = pyunits.convert(unit_params['d... | <|body_start_0|>
time = self.flowsheet().config.time.first()
self.flow_in = pyunits.convert(self.flow_vol_in[time], to_units=pyunits.m ** 3 / pyunits.hr)
self.number_of_units = 2
self.base_fixed_cap_cost = 900.97
self.cap_scaling_exp = 0.6179
chem_name = unit_params['chem... | UnitProcess | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnitProcess:
def fixed_cap(self, unit_params):
"""**"unit_params" are the unit parameters passed to the model from the input sheet as a Python dictionary.** **EXAMPLE: {'dose': 10}** Fixed capital for chemical addition is a function of chemical dose, chemical solution flow, and the numbe... | stack_v2_sparse_classes_36k_train_028182 | 3,680 | permissive | [
{
"docstring": "**\"unit_params\" are the unit parameters passed to the model from the input sheet as a Python dictionary.** **EXAMPLE: {'dose': 10}** Fixed capital for chemical addition is a function of chemical dose, chemical solution flow, and the number of units. :param chemical_name: Chemical name to be us... | 4 | null | Implement the Python class `UnitProcess` described below.
Class description:
Implement the UnitProcess class.
Method signatures and docstrings:
- def fixed_cap(self, unit_params): **"unit_params" are the unit parameters passed to the model from the input sheet as a Python dictionary.** **EXAMPLE: {'dose': 10}** Fixed... | Implement the Python class `UnitProcess` described below.
Class description:
Implement the UnitProcess class.
Method signatures and docstrings:
- def fixed_cap(self, unit_params): **"unit_params" are the unit parameters passed to the model from the input sheet as a Python dictionary.** **EXAMPLE: {'dose': 10}** Fixed... | 0e9713a195b50824c4d38ff6ea5db244a6f1ad57 | <|skeleton|>
class UnitProcess:
def fixed_cap(self, unit_params):
"""**"unit_params" are the unit parameters passed to the model from the input sheet as a Python dictionary.** **EXAMPLE: {'dose': 10}** Fixed capital for chemical addition is a function of chemical dose, chemical solution flow, and the numbe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnitProcess:
def fixed_cap(self, unit_params):
"""**"unit_params" are the unit parameters passed to the model from the input sheet as a Python dictionary.** **EXAMPLE: {'dose': 10}** Fixed capital for chemical addition is a function of chemical dose, chemical solution flow, and the number of units. :p... | the_stack_v2_python_sparse | watertap3/watertap3/wt_units/chemical_addition.py | JamariMurke/WaterTAP3 | train | 0 | |
f865edb1017dc8d64ed4897e9b152af0d2cafa5e | [
"if self.num_shared_convs > 0:\n for conv in self.shared_convs:\n x = conv(x)\nif self.num_shared_fcs > 0:\n if self.with_avg_pool:\n x = self.avg_pool(x)\n x = x.flatten(1)\n for fc in self.shared_fcs:\n x = self.relu(fc(x))\nreturn x",
"x_cls = x\nx_reg = x\nfor conv in self.cls... | <|body_start_0|>
if self.num_shared_convs > 0:
for conv in self.shared_convs:
x = conv(x)
if self.num_shared_fcs > 0:
if self.with_avg_pool:
x = self.avg_pool(x)
x = x.flatten(1)
for fc in self.shared_fcs:
x ... | BBox head for `SCNet <https://arxiv.org/abs/2012.10150>`_. This inherits ``ConvFCBBoxHead`` with modified forward() function, allow us to get intermediate shared feature. | SCNetBBoxHead | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SCNetBBoxHead:
"""BBox head for `SCNet <https://arxiv.org/abs/2012.10150>`_. This inherits ``ConvFCBBoxHead`` with modified forward() function, allow us to get intermediate shared feature."""
def _forward_shared(self, x: Tensor) -> Tensor:
"""Forward function for shared part. Args: x... | stack_v2_sparse_classes_36k_train_028183 | 2,836 | permissive | [
{
"docstring": "Forward function for shared part. Args: x (Tensor): Input feature. Returns: Tensor: Shared feature.",
"name": "_forward_shared",
"signature": "def _forward_shared(self, x: Tensor) -> Tensor"
},
{
"docstring": "Forward function for classification and regression parts. Args: x (Ten... | 3 | stack_v2_sparse_classes_30k_train_009528 | Implement the Python class `SCNetBBoxHead` described below.
Class description:
BBox head for `SCNet <https://arxiv.org/abs/2012.10150>`_. This inherits ``ConvFCBBoxHead`` with modified forward() function, allow us to get intermediate shared feature.
Method signatures and docstrings:
- def _forward_shared(self, x: Ten... | Implement the Python class `SCNetBBoxHead` described below.
Class description:
BBox head for `SCNet <https://arxiv.org/abs/2012.10150>`_. This inherits ``ConvFCBBoxHead`` with modified forward() function, allow us to get intermediate shared feature.
Method signatures and docstrings:
- def _forward_shared(self, x: Ten... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class SCNetBBoxHead:
"""BBox head for `SCNet <https://arxiv.org/abs/2012.10150>`_. This inherits ``ConvFCBBoxHead`` with modified forward() function, allow us to get intermediate shared feature."""
def _forward_shared(self, x: Tensor) -> Tensor:
"""Forward function for shared part. Args: x... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SCNetBBoxHead:
"""BBox head for `SCNet <https://arxiv.org/abs/2012.10150>`_. This inherits ``ConvFCBBoxHead`` with modified forward() function, allow us to get intermediate shared feature."""
def _forward_shared(self, x: Tensor) -> Tensor:
"""Forward function for shared part. Args: x (Tensor): In... | the_stack_v2_python_sparse | ai/mmdetection/mmdet/models/roi_heads/bbox_heads/scnet_bbox_head.py | alldatacenter/alldata | train | 774 |
f4f403160933a8e0848b70a18b81278caf73804c | [
"if value is None:\n value = ''\nreturn value",
"if isinstance(value, cls.TYPE):\n return value\nelif is_null(value):\n return None\nelse:\n return value"
] | <|body_start_0|>
if value is None:
value = ''
return value
<|end_body_0|>
<|body_start_1|>
if isinstance(value, cls.TYPE):
return value
elif is_null(value):
return None
else:
return value
<|end_body_1|>
| Base Field class - all fields should inherit from this As the fallback for all other field types are the BinaryField, this Field actually implements what is expected in the BinaryField | Field | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Field:
"""Base Field class - all fields should inherit from this As the fallback for all other field types are the BinaryField, this Field actually implements what is expected in the BinaryField"""
def serialize(cls, value, *args, **kwargs):
"""Serialize a value to be exported `cls.s... | stack_v2_sparse_classes_36k_train_028184 | 20,159 | no_license | [
{
"docstring": "Serialize a value to be exported `cls.serialize` should always return an unicode value, except for BinaryField",
"name": "serialize",
"signature": "def serialize(cls, value, *args, **kwargs)"
},
{
"docstring": "Deserialize a value just after importing it `cls.deserialize` should ... | 2 | stack_v2_sparse_classes_30k_train_018163 | Implement the Python class `Field` described below.
Class description:
Base Field class - all fields should inherit from this As the fallback for all other field types are the BinaryField, this Field actually implements what is expected in the BinaryField
Method signatures and docstrings:
- def serialize(cls, value, ... | Implement the Python class `Field` described below.
Class description:
Base Field class - all fields should inherit from this As the fallback for all other field types are the BinaryField, this Field actually implements what is expected in the BinaryField
Method signatures and docstrings:
- def serialize(cls, value, ... | a082f068f89e05a6ef9c983d3ece4791b3101a5b | <|skeleton|>
class Field:
"""Base Field class - all fields should inherit from this As the fallback for all other field types are the BinaryField, this Field actually implements what is expected in the BinaryField"""
def serialize(cls, value, *args, **kwargs):
"""Serialize a value to be exported `cls.s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Field:
"""Base Field class - all fields should inherit from this As the fallback for all other field types are the BinaryField, this Field actually implements what is expected in the BinaryField"""
def serialize(cls, value, *args, **kwargs):
"""Serialize a value to be exported `cls.serialize` sho... | the_stack_v2_python_sparse | venv/Lib/site-packages/rows/fields.py | Pastutia/paint | train | 0 |
1606a214d93e235b65bcceeff28a467f668ec6f2 | [
"result.save()\nsample = Sample(name='SMPL_01', **{tool_result_name: result}).save()\nself.assertTrue(getattr(sample, tool_result_name))",
"sample_group = add_sample_group(name='SMPL_01')\nresult.sample_group_uuid = sample_group.id\nresult.save()\nfetch_result = model_cls.objects.get(sample_group_uuid=sample_grou... | <|body_start_0|>
result.save()
sample = Sample(name='SMPL_01', **{tool_result_name: result}).save()
self.assertTrue(getattr(sample, tool_result_name))
<|end_body_0|>
<|body_start_1|>
sample_group = add_sample_group(name='SMPL_01')
result.sample_group_uuid = sample_group.id
... | Test suite for VFDB tool result model. | BaseToolResultTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseToolResultTest:
"""Test suite for VFDB tool result model."""
def generic_add_sample_tool_test(self, result, tool_result_name):
"""Ensure tool result model is created correctly."""
<|body_0|>
def generic_add_group_tool_test(self, result, model_cls):
"""Ensure ... | stack_v2_sparse_classes_36k_train_028185 | 2,821 | permissive | [
{
"docstring": "Ensure tool result model is created correctly.",
"name": "generic_add_sample_tool_test",
"signature": "def generic_add_sample_tool_test(self, result, tool_result_name)"
},
{
"docstring": "Ensure tool result model is created correctly.",
"name": "generic_add_group_tool_test",
... | 5 | stack_v2_sparse_classes_30k_test_001061 | Implement the Python class `BaseToolResultTest` described below.
Class description:
Test suite for VFDB tool result model.
Method signatures and docstrings:
- def generic_add_sample_tool_test(self, result, tool_result_name): Ensure tool result model is created correctly.
- def generic_add_group_tool_test(self, result... | Implement the Python class `BaseToolResultTest` described below.
Class description:
Test suite for VFDB tool result model.
Method signatures and docstrings:
- def generic_add_sample_tool_test(self, result, tool_result_name): Ensure tool result model is created correctly.
- def generic_add_group_tool_test(self, result... | 609cd57c626c857c8efde8237a1f22f4d1e6065d | <|skeleton|>
class BaseToolResultTest:
"""Test suite for VFDB tool result model."""
def generic_add_sample_tool_test(self, result, tool_result_name):
"""Ensure tool result model is created correctly."""
<|body_0|>
def generic_add_group_tool_test(self, result, model_cls):
"""Ensure ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseToolResultTest:
"""Test suite for VFDB tool result model."""
def generic_add_sample_tool_test(self, result, tool_result_name):
"""Ensure tool result model is created correctly."""
result.save()
sample = Sample(name='SMPL_01', **{tool_result_name: result}).save()
self.a... | the_stack_v2_python_sparse | app/tool_results/tool_result_test_utils/tool_result_base_test.py | MetaGenScope/metagenscope-server | train | 0 |
90eed52965b93f79e6f03ac37e49c796c666b539 | [
"self.path = path\nwith open(self.path, 'w') as file:\n file.write('Logger initiated: {} \\n \\n'.format(date.today()))",
"with open(self.path, 'a+') as file:\n file.write(text + '\\n')\nprint(text)",
"text = ''\nfor key, value in dict.items():\n text = text + '{}: {} \\n'.format(key, value)\nwith open... | <|body_start_0|>
self.path = path
with open(self.path, 'w') as file:
file.write('Logger initiated: {} \n \n'.format(date.today()))
<|end_body_0|>
<|body_start_1|>
with open(self.path, 'a+') as file:
file.write(text + '\n')
print(text)
<|end_body_1|>
<|body_start... | Logger | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Logger:
def __init__(self, path):
"""Instantiates the logger as a .txt file at the specified path :param path: (str) path to model outputs"""
<|body_0|>
def write(self, text):
"""Writes text to logger and prints text. :param text: (str) :return: void"""
<|bod... | stack_v2_sparse_classes_36k_train_028186 | 3,982 | permissive | [
{
"docstring": "Instantiates the logger as a .txt file at the specified path :param path: (str) path to model outputs",
"name": "__init__",
"signature": "def __init__(self, path)"
},
{
"docstring": "Writes text to logger and prints text. :param text: (str) :return: void",
"name": "write",
... | 3 | stack_v2_sparse_classes_30k_train_019524 | Implement the Python class `Logger` described below.
Class description:
Implement the Logger class.
Method signatures and docstrings:
- def __init__(self, path): Instantiates the logger as a .txt file at the specified path :param path: (str) path to model outputs
- def write(self, text): Writes text to logger and pri... | Implement the Python class `Logger` described below.
Class description:
Implement the Logger class.
Method signatures and docstrings:
- def __init__(self, path): Instantiates the logger as a .txt file at the specified path :param path: (str) path to model outputs
- def write(self, text): Writes text to logger and pri... | 94c0c01e01a9d221f2611b1f5c585434f3b0cb22 | <|skeleton|>
class Logger:
def __init__(self, path):
"""Instantiates the logger as a .txt file at the specified path :param path: (str) path to model outputs"""
<|body_0|>
def write(self, text):
"""Writes text to logger and prints text. :param text: (str) :return: void"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Logger:
def __init__(self, path):
"""Instantiates the logger as a .txt file at the specified path :param path: (str) path to model outputs"""
self.path = path
with open(self.path, 'w') as file:
file.write('Logger initiated: {} \n \n'.format(date.today()))
def write(sel... | the_stack_v2_python_sparse | utils.py | avaimar/urban_emissions | train | 1 | |
2e2fc5dfd186d056307981f3de6a54429a20b1d8 | [
"self.__logger = State().getLogger('Preprocessing_Component_Logger')\nself.__logger.info('Starting __init__()', 'Preprocessor:__init__()')\nself.__orderedPrePorcessingUnits = orderedPreprocessingUnits\nself.__logger.info('Finished __init__()', 'Preprocessor:__init__()')",
"self.__logger.info('Starting preProcess(... | <|body_start_0|>
self.__logger = State().getLogger('Preprocessing_Component_Logger')
self.__logger.info('Starting __init__()', 'Preprocessor:__init__()')
self.__orderedPrePorcessingUnits = orderedPreprocessingUnits
self.__logger.info('Finished __init__()', 'Preprocessor:__init__()')
<|en... | Preprocessor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Preprocessor:
def __init__(self, orderedPreprocessingUnits):
"""Constructor, initialisiert Membervariablen Parameters ---------- orderedPreprocessingUnits: list Eine geordnete Liste von PreprrcessingUnits in Ausführungsreihenfolge."""
<|body_0|>
def preProcess(self, mat):
... | stack_v2_sparse_classes_36k_train_028187 | 1,968 | no_license | [
{
"docstring": "Constructor, initialisiert Membervariablen Parameters ---------- orderedPreprocessingUnits: list Eine geordnete Liste von PreprrcessingUnits in Ausführungsreihenfolge.",
"name": "__init__",
"signature": "def __init__(self, orderedPreprocessingUnits)"
},
{
"docstring": "Führt die ... | 2 | null | Implement the Python class `Preprocessor` described below.
Class description:
Implement the Preprocessor class.
Method signatures and docstrings:
- def __init__(self, orderedPreprocessingUnits): Constructor, initialisiert Membervariablen Parameters ---------- orderedPreprocessingUnits: list Eine geordnete Liste von P... | Implement the Python class `Preprocessor` described below.
Class description:
Implement the Preprocessor class.
Method signatures and docstrings:
- def __init__(self, orderedPreprocessingUnits): Constructor, initialisiert Membervariablen Parameters ---------- orderedPreprocessingUnits: list Eine geordnete Liste von P... | 3daaa72b193ebfb55894b47b6a752cdc2192bb6b | <|skeleton|>
class Preprocessor:
def __init__(self, orderedPreprocessingUnits):
"""Constructor, initialisiert Membervariablen Parameters ---------- orderedPreprocessingUnits: list Eine geordnete Liste von PreprrcessingUnits in Ausführungsreihenfolge."""
<|body_0|>
def preProcess(self, mat):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Preprocessor:
def __init__(self, orderedPreprocessingUnits):
"""Constructor, initialisiert Membervariablen Parameters ---------- orderedPreprocessingUnits: list Eine geordnete Liste von PreprrcessingUnits in Ausführungsreihenfolge."""
self.__logger = State().getLogger('Preprocessing_Component_... | the_stack_v2_python_sparse | SheetMusicScanner/Preprocessing_Component/PreprocessingUnit/Preprocessor.py | jadeskon/score-scan | train | 0 | |
b31db16e3ab46aa28fc7692cc69c6557bc1abcf1 | [
"alg = MagicMock()\nalg.asString = MagicMock(return_value='DummyAlgo(\"RoiCreator\")')\ninst = Instantiator()\nself.assertTrue(len(inst.cache) == 0)\nself.assertTrue(inst(alg).__class__.__name__ == 'PESA__DummyUnseededAllTEAlgo')\nself.assertTrue(len(inst.cache) == 1)\ninst(alg)\nself.assertTrue(inst(alg).__class__... | <|body_start_0|>
alg = MagicMock()
alg.asString = MagicMock(return_value='DummyAlgo("RoiCreator")')
inst = Instantiator()
self.assertTrue(len(inst.cache) == 0)
self.assertTrue(inst(alg).__class__.__name__ == 'PESA__DummyUnseededAllTEAlgo')
self.assertTrue(len(inst.cache) ... | Test_jetDefInstantiator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_jetDefInstantiator:
def test_0(self):
"""test instantiation and caching if instatiation is ok"""
<|body_0|>
def test_1(self):
"""test instantiation if instatiation is fails"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
alg = MagicMock()
... | stack_v2_sparse_classes_36k_train_028188 | 1,050 | permissive | [
{
"docstring": "test instantiation and caching if instatiation is ok",
"name": "test_0",
"signature": "def test_0(self)"
},
{
"docstring": "test instantiation if instatiation is fails",
"name": "test_1",
"signature": "def test_1(self)"
}
] | 2 | null | Implement the Python class `Test_jetDefInstantiator` described below.
Class description:
Implement the Test_jetDefInstantiator class.
Method signatures and docstrings:
- def test_0(self): test instantiation and caching if instatiation is ok
- def test_1(self): test instantiation if instatiation is fails | Implement the Python class `Test_jetDefInstantiator` described below.
Class description:
Implement the Test_jetDefInstantiator class.
Method signatures and docstrings:
- def test_0(self): test instantiation and caching if instatiation is ok
- def test_1(self): test instantiation if instatiation is fails
<|skeleton|>... | 354f92551294f7be678aebcd7b9d67d2c4448176 | <|skeleton|>
class Test_jetDefInstantiator:
def test_0(self):
"""test instantiation and caching if instatiation is ok"""
<|body_0|>
def test_1(self):
"""test instantiation if instatiation is fails"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_jetDefInstantiator:
def test_0(self):
"""test instantiation and caching if instatiation is ok"""
alg = MagicMock()
alg.asString = MagicMock(return_value='DummyAlgo("RoiCreator")')
inst = Instantiator()
self.assertTrue(len(inst.cache) == 0)
self.assertTrue(i... | the_stack_v2_python_sparse | Trigger/TriggerCommon/TriggerMenu/python/jet/jetDefInstantiator_test.py | strigazi/athena | train | 0 | |
453adbd03da3aa234f58b40fccbf6288d4a24cbe | [
"game = self.game(gameId)\nplayer = self.login(game, playerName, password)\nLog.debug('Undeploying from origin star %s' % self.starName(starId))\ninstances = store.get().fetchObjectsOfClass(TriggerInstance, clauses='WHERE playerId = %s and triggerDefId = %s' % (player.sqlObjRef(), autoDeployTrigger(store.get()).sql... | <|body_start_0|>
game = self.game(gameId)
player = self.login(game, playerName, password)
Log.debug('Undeploying from origin star %s' % self.starName(starId))
instances = store.get().fetchObjectsOfClass(TriggerInstance, clauses='WHERE playerId = %s and triggerDefId = %s' % (player.sqlObj... | Specify deployment orders for a star | DeploymentOrders | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeploymentOrders:
"""Specify deployment orders for a star"""
def undeploy(self, gameId, playerName, password, starId):
"""Remove the deployment orders for a player's star, identified by its ID"""
<|body_0|>
def deploy(self, gameId, playerName, password, originId, destina... | stack_v2_sparse_classes_36k_train_028189 | 2,264 | no_license | [
{
"docstring": "Remove the deployment orders for a player's star, identified by its ID",
"name": "undeploy",
"signature": "def undeploy(self, gameId, playerName, password, starId)"
},
{
"docstring": "Create deployment orders from originId to destinationId",
"name": "deploy",
"signature":... | 2 | null | Implement the Python class `DeploymentOrders` described below.
Class description:
Specify deployment orders for a star
Method signatures and docstrings:
- def undeploy(self, gameId, playerName, password, starId): Remove the deployment orders for a player's star, identified by its ID
- def deploy(self, gameId, playerN... | Implement the Python class `DeploymentOrders` described below.
Class description:
Specify deployment orders for a star
Method signatures and docstrings:
- def undeploy(self, gameId, playerName, password, starId): Remove the deployment orders for a player's star, identified by its ID
- def deploy(self, gameId, playerN... | bcff0fefc87ad5a4c72e9e01ee7747006ce0c14a | <|skeleton|>
class DeploymentOrders:
"""Specify deployment orders for a star"""
def undeploy(self, gameId, playerName, password, starId):
"""Remove the deployment orders for a player's star, identified by its ID"""
<|body_0|>
def deploy(self, gameId, playerName, password, originId, destina... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeploymentOrders:
"""Specify deployment orders for a star"""
def undeploy(self, gameId, playerName, password, starId):
"""Remove the deployment orders for a player's star, identified by its ID"""
game = self.game(gameId)
player = self.login(game, playerName, password)
Log.... | the_stack_v2_python_sparse | python/nova/api/deploy.py | kgilpin/nova | train | 1 |
9da8d6189b861ab6d0939a6a31be168c0a3f0304 | [
"path = cloud.make_file_paths_local('gs://bucket-name/bucket/dir/some_file.gin', 'gin/search/path')\ndownload_from_gstorage_function.assert_called_once()\nself.assertEqual(path, 'some_file.gin')",
"path = cloud.make_file_paths_local('local_file.gin', 'gin/search/path')\ndownload_from_gstorage_function.assert_not_... | <|body_start_0|>
path = cloud.make_file_paths_local('gs://bucket-name/bucket/dir/some_file.gin', 'gin/search/path')
download_from_gstorage_function.assert_called_once()
self.assertEqual(path, 'some_file.gin')
<|end_body_0|>
<|body_start_1|>
path = cloud.make_file_paths_local('local_file... | MakeFilePathsLocalTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MakeFilePathsLocalTest:
def test_single_path_handling(self, download_from_gstorage_function):
"""Tests that function returns a single value if given single value."""
<|body_0|>
def test_single_local_path_handling(self, download_from_gstorage_function):
"""Tests that ... | stack_v2_sparse_classes_36k_train_028190 | 2,970 | permissive | [
{
"docstring": "Tests that function returns a single value if given single value.",
"name": "test_single_path_handling",
"signature": "def test_single_path_handling(self, download_from_gstorage_function)"
},
{
"docstring": "Tests that function does nothing if given local file path.",
"name":... | 4 | null | Implement the Python class `MakeFilePathsLocalTest` described below.
Class description:
Implement the MakeFilePathsLocalTest class.
Method signatures and docstrings:
- def test_single_path_handling(self, download_from_gstorage_function): Tests that function returns a single value if given single value.
- def test_sin... | Implement the Python class `MakeFilePathsLocalTest` described below.
Class description:
Implement the MakeFilePathsLocalTest class.
Method signatures and docstrings:
- def test_single_path_handling(self, download_from_gstorage_function): Tests that function returns a single value if given single value.
- def test_sin... | 7e0a39420f3bd87d9efd54cf0d36f4e258311340 | <|skeleton|>
class MakeFilePathsLocalTest:
def test_single_path_handling(self, download_from_gstorage_function):
"""Tests that function returns a single value if given single value."""
<|body_0|>
def test_single_local_path_handling(self, download_from_gstorage_function):
"""Tests that ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MakeFilePathsLocalTest:
def test_single_path_handling(self, download_from_gstorage_function):
"""Tests that function returns a single value if given single value."""
path = cloud.make_file_paths_local('gs://bucket-name/bucket/dir/some_file.gin', 'gin/search/path')
download_from_gstorag... | the_stack_v2_python_sparse | ddsp/training/cloud_test.py | magenta/ddsp | train | 2,666 | |
1993e58a5ae2f06df71f553ac33ec15daeddc5f9 | [
"rng, inputs, shared_args = test_utils.get_common_model_test_inputs()\nmodel = longformer.LongformerEncoder(**shared_args, sliding_window_size=3)\nparams = model.init(rng, inputs)\ny = model.apply(params, inputs)\nself.assertEqual(y.shape, inputs.shape + (shared_args['emb_dim'],))",
"rng = random.PRNGKey(0)\nx = ... | <|body_start_0|>
rng, inputs, shared_args = test_utils.get_common_model_test_inputs()
model = longformer.LongformerEncoder(**shared_args, sliding_window_size=3)
params = model.init(rng, inputs)
y = model.apply(params, inputs)
self.assertEqual(y.shape, inputs.shape + (shared_args[... | Tests for the Longformer model. | LongformerTransformerTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LongformerTransformerTest:
"""Tests for the Longformer model."""
def test_longformer(self):
"""Tests Longformer self attention."""
<|body_0|>
def test_longformer_self_attention(self):
"""Tests Longformer self attention."""
<|body_1|>
def test_longfor... | stack_v2_sparse_classes_36k_train_028191 | 4,921 | permissive | [
{
"docstring": "Tests Longformer self attention.",
"name": "test_longformer",
"signature": "def test_longformer(self)"
},
{
"docstring": "Tests Longformer self attention.",
"name": "test_longformer_self_attention",
"signature": "def test_longformer_self_attention(self)"
},
{
"doc... | 5 | stack_v2_sparse_classes_30k_train_013621 | Implement the Python class `LongformerTransformerTest` described below.
Class description:
Tests for the Longformer model.
Method signatures and docstrings:
- def test_longformer(self): Tests Longformer self attention.
- def test_longformer_self_attention(self): Tests Longformer self attention.
- def test_longformer_... | Implement the Python class `LongformerTransformerTest` described below.
Class description:
Tests for the Longformer model.
Method signatures and docstrings:
- def test_longformer(self): Tests Longformer self attention.
- def test_longformer_self_attention(self): Tests Longformer self attention.
- def test_longformer_... | 1b4929016aba883d2f06fa1a51e343ccdbd631ed | <|skeleton|>
class LongformerTransformerTest:
"""Tests for the Longformer model."""
def test_longformer(self):
"""Tests Longformer self attention."""
<|body_0|>
def test_longformer_self_attention(self):
"""Tests Longformer self attention."""
<|body_1|>
def test_longfor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LongformerTransformerTest:
"""Tests for the Longformer model."""
def test_longformer(self):
"""Tests Longformer self attention."""
rng, inputs, shared_args = test_utils.get_common_model_test_inputs()
model = longformer.LongformerEncoder(**shared_args, sliding_window_size=3)
... | the_stack_v2_python_sparse | pegasus/flax/models/encoders/longformer/test_longformer.py | google-research/pegasus | train | 1,543 |
bedb3a468de70144573245effe3655bfa5a896b2 | [
"super(EncDecModel, self).__init__()\nself._config = config\nself._model_version = model_version\nassert model_version in ('v2',), 'model_version only support v2'\nself.encoder = encoder_v2.Text2SQLEncoderV2(config)\nself.decoder = decoder_v2.Text2SQLDecoder(label_encoder, dropout=0.2, desc_attn='mha', use_align_ma... | <|body_start_0|>
super(EncDecModel, self).__init__()
self._config = config
self._model_version = model_version
assert model_version in ('v2',), 'model_version only support v2'
self.encoder = encoder_v2.Text2SQLEncoderV2(config)
self.decoder = decoder_v2.Text2SQLDecoder(la... | Dygraph version of BoomUp Model | EncDecModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncDecModel:
"""Dygraph version of BoomUp Model"""
def __init__(self, config, label_encoder, model_version='v2'):
"""init of class Args: model_configs (TYPE): NULL"""
<|body_0|>
def forward(self, inputs, labels=None, db=None, is_train=True):
"""Args: inputs (TYPE... | stack_v2_sparse_classes_36k_train_028192 | 3,369 | permissive | [
{
"docstring": "init of class Args: model_configs (TYPE): NULL",
"name": "__init__",
"signature": "def __init__(self, config, label_encoder, model_version='v2')"
},
{
"docstring": "Args: inputs (TYPE): NULL labels (TYPE) Returns: TODO",
"name": "forward",
"signature": "def forward(self, ... | 4 | null | Implement the Python class `EncDecModel` described below.
Class description:
Dygraph version of BoomUp Model
Method signatures and docstrings:
- def __init__(self, config, label_encoder, model_version='v2'): init of class Args: model_configs (TYPE): NULL
- def forward(self, inputs, labels=None, db=None, is_train=True... | Implement the Python class `EncDecModel` described below.
Class description:
Dygraph version of BoomUp Model
Method signatures and docstrings:
- def __init__(self, config, label_encoder, model_version='v2'): init of class Args: model_configs (TYPE): NULL
- def forward(self, inputs, labels=None, db=None, is_train=True... | b8ec015fa9e16c0a879c619ee1f2aab8a393c7bd | <|skeleton|>
class EncDecModel:
"""Dygraph version of BoomUp Model"""
def __init__(self, config, label_encoder, model_version='v2'):
"""init of class Args: model_configs (TYPE): NULL"""
<|body_0|>
def forward(self, inputs, labels=None, db=None, is_train=True):
"""Args: inputs (TYPE... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EncDecModel:
"""Dygraph version of BoomUp Model"""
def __init__(self, config, label_encoder, model_version='v2'):
"""init of class Args: model_configs (TYPE): NULL"""
super(EncDecModel, self).__init__()
self._config = config
self._model_version = model_version
asse... | the_stack_v2_python_sparse | NLP/Text2SQL-BASELINE/text2sql/models/enc_dec.py | sserdoubleh/Research | train | 10 |
81a42ad652f9b795c357d85a8884f19422a64fea | [
"self.request = request\nself.reminder = reminder\nself.signature_receipt = signature_receipt\nself.final_receipt = final_receipt\nself.canceled = canceled\nself.expired = expired\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\nrequest = dictionary.get('request')\nr... | <|body_start_0|>
self.request = request
self.reminder = reminder
self.signature_receipt = signature_receipt
self.final_receipt = final_receipt
self.canceled = canceled
self.expired = expired
self.additional_properties = additional_properties
<|end_body_0|>
<|body... | Implementation of the 'Setup' model. TODO: type model description here. Attributes: request (Request): TODO: type description here. reminder (Reminder): TODO: type description here. signature_receipt (SignatureReceipt): TODO: type description here. final_receipt (FinalReceipt): TODO: type description here. canceled (Ca... | Setup | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Setup:
"""Implementation of the 'Setup' model. TODO: type model description here. Attributes: request (Request): TODO: type description here. reminder (Reminder): TODO: type description here. signature_receipt (SignatureReceipt): TODO: type description here. final_receipt (FinalReceipt): TODO: ty... | stack_v2_sparse_classes_36k_train_028193 | 3,070 | permissive | [
{
"docstring": "Constructor for the Setup class",
"name": "__init__",
"signature": "def __init__(self, request=None, reminder=None, signature_receipt=None, final_receipt=None, canceled=None, expired=None, additional_properties={})"
},
{
"docstring": "Creates an instance of this model from a dict... | 2 | stack_v2_sparse_classes_30k_test_000472 | Implement the Python class `Setup` described below.
Class description:
Implementation of the 'Setup' model. TODO: type model description here. Attributes: request (Request): TODO: type description here. reminder (Reminder): TODO: type description here. signature_receipt (SignatureReceipt): TODO: type description here.... | Implement the Python class `Setup` described below.
Class description:
Implementation of the 'Setup' model. TODO: type model description here. Attributes: request (Request): TODO: type description here. reminder (Reminder): TODO: type description here. signature_receipt (SignatureReceipt): TODO: type description here.... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class Setup:
"""Implementation of the 'Setup' model. TODO: type model description here. Attributes: request (Request): TODO: type description here. reminder (Reminder): TODO: type description here. signature_receipt (SignatureReceipt): TODO: type description here. final_receipt (FinalReceipt): TODO: ty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Setup:
"""Implementation of the 'Setup' model. TODO: type model description here. Attributes: request (Request): TODO: type description here. reminder (Reminder): TODO: type description here. signature_receipt (SignatureReceipt): TODO: type description here. final_receipt (FinalReceipt): TODO: type descriptio... | the_stack_v2_python_sparse | idfy_rest_client/models/setup.py | dealflowteam/Idfy | train | 0 |
edb8e5be5423bf9b6dbb2eca318689671900fde9 | [
"self._calc = WazeRouteCalculator\nself.origin = origin\nself.destination = destination\nself.region = region\nself.include = include\nself.exclude = exclude\nself.realtime = realtime\nself.units = units\nself.duration = None\nself.distance = None\nself.route = None\nself.avoid_toll_roads = avoid_toll_roads\nself.a... | <|body_start_0|>
self._calc = WazeRouteCalculator
self.origin = origin
self.destination = destination
self.region = region
self.include = include
self.exclude = exclude
self.realtime = realtime
self.units = units
self.duration = None
self.d... | WazeTravelTime Data object. | WazeTravelTimeData | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WazeTravelTimeData:
"""WazeTravelTime Data object."""
def __init__(self, origin, destination, region, include, exclude, realtime, units, vehicle_type, avoid_toll_roads, avoid_subscription_roads, avoid_ferries):
"""Set up WazeRouteCalculator."""
<|body_0|>
def update(self... | stack_v2_sparse_classes_36k_train_028194 | 11,036 | permissive | [
{
"docstring": "Set up WazeRouteCalculator.",
"name": "__init__",
"signature": "def __init__(self, origin, destination, region, include, exclude, realtime, units, vehicle_type, avoid_toll_roads, avoid_subscription_roads, avoid_ferries)"
},
{
"docstring": "Update WazeRouteCalculator Sensor.",
... | 2 | null | Implement the Python class `WazeTravelTimeData` described below.
Class description:
WazeTravelTime Data object.
Method signatures and docstrings:
- def __init__(self, origin, destination, region, include, exclude, realtime, units, vehicle_type, avoid_toll_roads, avoid_subscription_roads, avoid_ferries): Set up WazeRo... | Implement the Python class `WazeTravelTimeData` described below.
Class description:
WazeTravelTime Data object.
Method signatures and docstrings:
- def __init__(self, origin, destination, region, include, exclude, realtime, units, vehicle_type, avoid_toll_roads, avoid_subscription_roads, avoid_ferries): Set up WazeRo... | ed4ab403deaed9e8c95e0db728477fcb012bf4fa | <|skeleton|>
class WazeTravelTimeData:
"""WazeTravelTime Data object."""
def __init__(self, origin, destination, region, include, exclude, realtime, units, vehicle_type, avoid_toll_roads, avoid_subscription_roads, avoid_ferries):
"""Set up WazeRouteCalculator."""
<|body_0|>
def update(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WazeTravelTimeData:
"""WazeTravelTime Data object."""
def __init__(self, origin, destination, region, include, exclude, realtime, units, vehicle_type, avoid_toll_roads, avoid_subscription_roads, avoid_ferries):
"""Set up WazeRouteCalculator."""
self._calc = WazeRouteCalculator
sel... | the_stack_v2_python_sparse | homeassistant/components/waze_travel_time/sensor.py | tchellomello/home-assistant | train | 8 |
03844b3080cdaff41534beaf3f68ec40f7475a22 | [
"super().__init__(name, mode, session, options)\nif options is None:\n options = _DEFAULT_FLOWDRONET_OPTS\nself.ds = dataset\nself.dronet_graph = None\nself.dronet_x_tnsr = None\nself.dronet_y_tnsr = None\nself.dronet_sess = None\nself.set_dronet_graph(options['dronet_model_path'])",
"try:\n with tf.gfile.G... | <|body_start_0|>
super().__init__(name, mode, session, options)
if options is None:
options = _DEFAULT_FLOWDRONET_OPTS
self.ds = dataset
self.dronet_graph = None
self.dronet_x_tnsr = None
self.dronet_y_tnsr = None
self.dronet_sess = None
self.s... | ModelFlowDroNet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelFlowDroNet:
def __init__(self, name='flowdronet', mode='train', session=None, options=None, dataset=None):
"""Initialize the ModelFloDroNet object Args: name: Model name mode: Possible values: 'train', 'val', 'test' session: optional TF session options: see _DEFAULT_PWCNET_TRAIN_OPT... | stack_v2_sparse_classes_36k_train_028195 | 9,033 | permissive | [
{
"docstring": "Initialize the ModelFloDroNet object Args: name: Model name mode: Possible values: 'train', 'val', 'test' session: optional TF session options: see _DEFAULT_PWCNET_TRAIN_OPTIONS comments dataset: Dataset loader Training Ref: See original PWC-Net Model",
"name": "__init__",
"signature": "... | 3 | stack_v2_sparse_classes_30k_train_020657 | Implement the Python class `ModelFlowDroNet` described below.
Class description:
Implement the ModelFlowDroNet class.
Method signatures and docstrings:
- def __init__(self, name='flowdronet', mode='train', session=None, options=None, dataset=None): Initialize the ModelFloDroNet object Args: name: Model name mode: Pos... | Implement the Python class `ModelFlowDroNet` described below.
Class description:
Implement the ModelFlowDroNet class.
Method signatures and docstrings:
- def __init__(self, name='flowdronet', mode='train', session=None, options=None, dataset=None): Initialize the ModelFloDroNet object Args: name: Model name mode: Pos... | a2281a37b4cc6482eb87546fa414fdaa38ec04e5 | <|skeleton|>
class ModelFlowDroNet:
def __init__(self, name='flowdronet', mode='train', session=None, options=None, dataset=None):
"""Initialize the ModelFloDroNet object Args: name: Model name mode: Possible values: 'train', 'val', 'test' session: optional TF session options: see _DEFAULT_PWCNET_TRAIN_OPT... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModelFlowDroNet:
def __init__(self, name='flowdronet', mode='train', session=None, options=None, dataset=None):
"""Initialize the ModelFloDroNet object Args: name: Model name mode: Possible values: 'train', 'val', 'test' session: optional TF session options: see _DEFAULT_PWCNET_TRAIN_OPTIONS comments ... | the_stack_v2_python_sparse | DroNeTello/tfoptflow/tfoptflow/model_flowdronet.py | MISTLab/of-obstacledetection | train | 13 | |
b601b0fd8c0a11b9cf0413e7f0c39a1a0f62453a | [
"print('\\nrunning test method:{}'.format(inspect.stack()[0][3]))\nreal_result = MathOperation(10, 2).multiply()\nexcept_result = 20\nmsg = '两个正数相乘失败'\ntry:\n self.assertEqual(except_result, real_result, msg=msg)\nexcept AssertionError as e:\n print('具体异常为:{}'.format(e))\n file.write('{},执行结果为:{}\\n具体异常为:{... | <|body_start_0|>
print('\nrunning test method:{}'.format(inspect.stack()[0][3]))
real_result = MathOperation(10, 2).multiply()
except_result = 20
msg = '两个正数相乘失败'
try:
self.assertEqual(except_result, real_result, msg=msg)
except AssertionError as e:
... | 测试两数相乘 | TestMulti | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMulti:
"""测试两数相乘"""
def test_two_pos_multi(self):
"""1.两个正数相除 :return:"""
<|body_0|>
def test_two_neg_multi(self):
"""2.两个负数相除 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
print('\nrunning test method:{}'.format(inspect.stack()[0... | stack_v2_sparse_classes_36k_train_028196 | 7,546 | no_license | [
{
"docstring": "1.两个正数相除 :return:",
"name": "test_two_pos_multi",
"signature": "def test_two_pos_multi(self)"
},
{
"docstring": "2.两个负数相除 :return:",
"name": "test_two_neg_multi",
"signature": "def test_two_neg_multi(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003364 | Implement the Python class `TestMulti` described below.
Class description:
测试两数相乘
Method signatures and docstrings:
- def test_two_pos_multi(self): 1.两个正数相除 :return:
- def test_two_neg_multi(self): 2.两个负数相除 :return: | Implement the Python class `TestMulti` described below.
Class description:
测试两数相乘
Method signatures and docstrings:
- def test_two_pos_multi(self): 1.两个正数相除 :return:
- def test_two_neg_multi(self): 2.两个负数相除 :return:
<|skeleton|>
class TestMulti:
"""测试两数相乘"""
def test_two_pos_multi(self):
"""1.两个正数相除... | 09d6bf79f46002b590289fdb94cbf1febe891184 | <|skeleton|>
class TestMulti:
"""测试两数相乘"""
def test_two_pos_multi(self):
"""1.两个正数相除 :return:"""
<|body_0|>
def test_two_neg_multi(self):
"""2.两个负数相除 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestMulti:
"""测试两数相乘"""
def test_two_pos_multi(self):
"""1.两个正数相除 :return:"""
print('\nrunning test method:{}'.format(inspect.stack()[0][3]))
real_result = MathOperation(10, 2).multiply()
except_result = 20
msg = '两个正数相乘失败'
try:
self.assertEqual... | the_stack_v2_python_sparse | pythonbase_class_1/Class_11_Unittest_start_end_handle.py | 2353501820/erp | train | 0 |
534e083de66c632373bf09343a96a0b66115a417 | [
"if user_id is None:\n return None\nif type(user_id) is not str:\n return None\nself.id = str(uuid.uuid4())\nself.__class__.user_id_by_session_id[self.id] = user_id\nreturn self.id",
"if session_id is None or type(session_id) is not str:\n return None\nsessions = self.__class__.user_id_by_session_id\nuse... | <|body_start_0|>
if user_id is None:
return None
if type(user_id) is not str:
return None
self.id = str(uuid.uuid4())
self.__class__.user_id_by_session_id[self.id] = user_id
return self.id
<|end_body_0|>
<|body_start_1|>
if session_id is None or t... | [Session authentication class] Args: Auth ([Class]): [auth Class] | SessionAuth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionAuth:
"""[Session authentication class] Args: Auth ([Class]): [auth Class]"""
def create_session(self, user_id: str=None) -> str:
"""[Create a new Session, by generating a Session ID and using t] Args: user_id (str, optional): [description]. Defaults to None. Returns: str: [de... | stack_v2_sparse_classes_36k_train_028197 | 2,343 | no_license | [
{
"docstring": "[Create a new Session, by generating a Session ID and using t] Args: user_id (str, optional): [description]. Defaults to None. Returns: str: [description]",
"name": "create_session",
"signature": "def create_session(self, user_id: str=None) -> str"
},
{
"docstring": "[Retrdieve u... | 4 | stack_v2_sparse_classes_30k_train_000258 | Implement the Python class `SessionAuth` described below.
Class description:
[Session authentication class] Args: Auth ([Class]): [auth Class]
Method signatures and docstrings:
- def create_session(self, user_id: str=None) -> str: [Create a new Session, by generating a Session ID and using t] Args: user_id (str, opti... | Implement the Python class `SessionAuth` described below.
Class description:
[Session authentication class] Args: Auth ([Class]): [auth Class]
Method signatures and docstrings:
- def create_session(self, user_id: str=None) -> str: [Create a new Session, by generating a Session ID and using t] Args: user_id (str, opti... | 94cae2ce3aa4cd72fc5907bd0148694054a9e60f | <|skeleton|>
class SessionAuth:
"""[Session authentication class] Args: Auth ([Class]): [auth Class]"""
def create_session(self, user_id: str=None) -> str:
"""[Create a new Session, by generating a Session ID and using t] Args: user_id (str, optional): [description]. Defaults to None. Returns: str: [de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SessionAuth:
"""[Session authentication class] Args: Auth ([Class]): [auth Class]"""
def create_session(self, user_id: str=None) -> str:
"""[Create a new Session, by generating a Session ID and using t] Args: user_id (str, optional): [description]. Defaults to None. Returns: str: [description]"""... | the_stack_v2_python_sparse | 0x07-Session_authentication/api/v1/auth/session_auth.py | nakadorx/holbertonschool-web_back_end | train | 0 |
3453e0b5155e3c6725b97b009a3f55ce3966be47 | [
"count = 0\nn = n & 4294967295\nwhile n:\n count += 1\n n = n & n - 1\nreturn count",
"count, flag = (0, 1)\nn = n & 4294967295\nwhile flag and flag < 4294967295:\n print(flag)\n if flag & n:\n count += 1\n flag = flag << 1\nreturn count"
] | <|body_start_0|>
count = 0
n = n & 4294967295
while n:
count += 1
n = n & n - 1
return count
<|end_body_0|>
<|body_start_1|>
count, flag = (0, 1)
n = n & 4294967295
while flag and flag < 4294967295:
print(flag)
if f... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def NumberOf1(self, n):
""":param n: :return: 如果一个整数不为0,那么这个整数至少有一位是1。如果我们把这个整数减1,那么原来处在整数最右边的1就会变为0, 原来在1后面的所有的0都会变成1(如果最右边的1后面还有0的话)。其余所有位将不会受到影响。 举个例子:一个二进制数1100,从右边数起第三位是处于最右边的一个1。减去1后,第三位变成0,它后面的两位0变 成了1,而前面的1保持不变,因此得到的结果是1011.我们发现减1的结果是把最右边的一个1开始的所有位都取反了。 这个时候如果我们再把原来的整数和... | stack_v2_sparse_classes_36k_train_028198 | 1,756 | no_license | [
{
"docstring": ":param n: :return: 如果一个整数不为0,那么这个整数至少有一位是1。如果我们把这个整数减1,那么原来处在整数最右边的1就会变为0, 原来在1后面的所有的0都会变成1(如果最右边的1后面还有0的话)。其余所有位将不会受到影响。 举个例子:一个二进制数1100,从右边数起第三位是处于最右边的一个1。减去1后,第三位变成0,它后面的两位0变 成了1,而前面的1保持不变,因此得到的结果是1011.我们发现减1的结果是把最右边的一个1开始的所有位都取反了。 这个时候如果我们再把原来的整数和减去1之后的结果做与运算,从原来整数最右边一个1那一位开始所有位都会变成0。 如1100&... | 2 | stack_v2_sparse_classes_30k_train_010939 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def NumberOf1(self, n): :param n: :return: 如果一个整数不为0,那么这个整数至少有一位是1。如果我们把这个整数减1,那么原来处在整数最右边的1就会变为0, 原来在1后面的所有的0都会变成1(如果最右边的1后面还有0的话)。其余所有位将不会受到影响。 举个例子:一个二进制数1100,从右边数起第三位是处于最右边的一... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def NumberOf1(self, n): :param n: :return: 如果一个整数不为0,那么这个整数至少有一位是1。如果我们把这个整数减1,那么原来处在整数最右边的1就会变为0, 原来在1后面的所有的0都会变成1(如果最右边的1后面还有0的话)。其余所有位将不会受到影响。 举个例子:一个二进制数1100,从右边数起第三位是处于最右边的一... | 2154a7d6e0a058b7094669264d5c836a44f4ab3a | <|skeleton|>
class Solution:
def NumberOf1(self, n):
""":param n: :return: 如果一个整数不为0,那么这个整数至少有一位是1。如果我们把这个整数减1,那么原来处在整数最右边的1就会变为0, 原来在1后面的所有的0都会变成1(如果最右边的1后面还有0的话)。其余所有位将不会受到影响。 举个例子:一个二进制数1100,从右边数起第三位是处于最右边的一个1。减去1后,第三位变成0,它后面的两位0变 成了1,而前面的1保持不变,因此得到的结果是1011.我们发现减1的结果是把最右边的一个1开始的所有位都取反了。 这个时候如果我们再把原来的整数和... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def NumberOf1(self, n):
""":param n: :return: 如果一个整数不为0,那么这个整数至少有一位是1。如果我们把这个整数减1,那么原来处在整数最右边的1就会变为0, 原来在1后面的所有的0都会变成1(如果最右边的1后面还有0的话)。其余所有位将不会受到影响。 举个例子:一个二进制数1100,从右边数起第三位是处于最右边的一个1。减去1后,第三位变成0,它后面的两位0变 成了1,而前面的1保持不变,因此得到的结果是1011.我们发现减1的结果是把最右边的一个1开始的所有位都取反了。 这个时候如果我们再把原来的整数和减去1之后的结果做与运算,从... | the_stack_v2_python_sparse | 010-二进制中1的个数/010.py | zazaliu/Target-Offer-Python | train | 0 | |
de48ea093cbca475fc04911d694b91cd53c1d68b | [
"begin = 0\nend = len(height) - 1\nmaxArea = -1\nwhile begin < end:\n if height[begin] <= height[end]:\n maxArea = max(maxArea, height[begin] * (end - begin))\n begin += 1\n else:\n maxArea = max(maxArea, height[end] * (end - begin))\n end -= 1\nreturn maxArea",
"maxArea = -1\nma... | <|body_start_0|>
begin = 0
end = len(height) - 1
maxArea = -1
while begin < end:
if height[begin] <= height[end]:
maxArea = max(maxArea, height[begin] * (end - begin))
begin += 1
else:
maxArea = max(maxArea, height[e... | AC time complexity O(n) reference to Solution 2 | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""AC time complexity O(n) reference to Solution 2"""
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def maxArea_WA(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_36k_train_028199 | 2,574 | no_license | [
{
"docstring": ":type height: List[int] :rtype: int",
"name": "maxArea",
"signature": "def maxArea(self, height)"
},
{
"docstring": ":type height: List[int] :rtype: int",
"name": "maxArea_WA",
"signature": "def maxArea_WA(self, height)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
AC time complexity O(n) reference to Solution 2
Method signatures and docstrings:
- def maxArea(self, height): :type height: List[int] :rtype: int
- def maxArea_WA(self, height): :type height: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
AC time complexity O(n) reference to Solution 2
Method signatures and docstrings:
- def maxArea(self, height): :type height: List[int] :rtype: int
- def maxArea_WA(self, height): :type height: List[int] :rtype: int
<|skeleton|>
class Solution:... | 2e146808b2d3259965d9aa671f2956b130d43a7e | <|skeleton|>
class Solution:
"""AC time complexity O(n) reference to Solution 2"""
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def maxArea_WA(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""AC time complexity O(n) reference to Solution 2"""
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
begin = 0
end = len(height) - 1
maxArea = -1
while begin < end:
if height[begin] <= height[end]:
maxArea... | the_stack_v2_python_sparse | medium/11_containerWithMostWater.py | grapefruit623/leetcode | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.